Add support for account index.

This commit is contained in:
Spencer Ofwiti 2021-01-15 07:30:19 +03:00
parent f7f4fe77f6
commit 4d920cdbe9
31 changed files with 1117 additions and 17 deletions

View File

@ -0,0 +1,47 @@
import { AccountRegistry } from '../../assets/js/eth_account_index';
import * as accountIndex from '../../assets/json/accountIndex.abi.json';
import {environment} from '../../environments/environment';
const Web3 = require('web3');
const web3 = new Web3(environment.web3Provider);
// @ts-ignore
const abi = accountIndex.default;
export class AccountIndex {
contractAddress: string;
signerAddress: string;
contract: any;
constructor(contractAddress: string, signerAddress?: string) {
this.contractAddress = contractAddress;
if (signerAddress) {
this.signerAddress = signerAddress;
}
this.contract = new AccountRegistry(web3, abi, this.contractAddress, this.signerAddress);
}
async totalAccounts(): Promise<number> {
return await this.contract.count();
}
async haveAccount(address: string): Promise<boolean> {
return await this.contract.have(address);
}
async addAccount(address: string): Promise<boolean> {
return await this.contract.add(address);
}
async last(numberOfAccounts: number): Promise<Array<string>> {
return await this.contract.last(numberOfAccounts);
}
async addToAccountRegistry(address: string): Promise<boolean> {
if (!await this.contract.have(address)) {
await this.contract.add(address);
return await this.contract.have(address);
} else {
return await this.contract.have(address);
}
}
}

View File

@ -0,0 +1,34 @@
// function httpGetter(): any {
// }
//
// httpGetter().prototype.get = (filename: string) => new Promise((whohoo, doh) => {
// const xhr = new XMLHttpRequest();
// xhr.addEventListener('load', (e) => {
// if (xhr.status === 200) {
// whohoo(xhr.responseText);
// return;
// }
// doh('failed with status ' + xhr.status + ': ' + xhr.statusText);
// });
// xhr.open('GET', filename);
// xhr.send();
// });
//
// class HttpGetter {
// async get(filename: string): Promise<any> {
// const xhr = new XMLHttpRequest();
// xhr.addEventListener('load', (e) => {
// if (xhr.status === 200) {
// // whohoo(xhr.responseText);
// return;
// }
// // doh('failed with status ' + xhr.status + ': ' + xhr.statusText);
// });
// xhr.open('GET', filename);
// xhr.send();
// }
// }
// export {
// httpGetter,
// HttpGetter
// };

View File

@ -1,2 +1,6 @@
export * from './mock-backend';
export * from './array-sum';
export * from './accountIndex';
export {AccountIndex} from './accountIndex';
export * from './http-getter';

2
src/app/_models/staff.ts Normal file
View File

@ -0,0 +1,2 @@
export interface Staff {
}

15
src/app/_models/token.ts Normal file
View File

@ -0,0 +1,15 @@
export interface Token {
name: string;
symbol: string;
address: string;
supply: string;
decimals: string;
reserves: {
'0xa686005CE37Dce7738436256982C3903f2E4ea8E'?: {
weight: string;
balance: string;
}
};
reserveRatio?: string;
owner?: string;
}

View File

@ -4,27 +4,37 @@ import Web3 from 'web3';
import {abi, Registry, TransactionHelper} from 'cic-client';
import {first} from 'rxjs/operators';
import {TransactionService} from './transaction.service';
import {environment} from '../../environments/environment';
import {httpGetter} from '../_helpers';
const cic = require('../../assets/js/block-sync/cic-client.web');
@Injectable({
providedIn: 'root'
})
export class BlockSyncService {
registryAddress: string = '0xb708175e3f6Cd850643aAF7B32212AFad50e2549';
readyStateTarget: number = 3;
// registryAddress: string = '0xb708175e3f6Cd850643aAF7B32212AFad50e2549';
// registryAddress: string = '0x4f8af296202Bff3B8589DA4Af87A8cfe74ad4d3A';
trustedDeclaratorAddress: string = '0x5567139c7a1C2977A391f51D8cA45B1D6700f5F6';
readyStateTarget: number = 2;
readyState: number = 0;
constructor(private transactionService: TransactionService) { }
blockSync(): any {
const settings = new Settings(this.scan);
const provider = 'ws://localhost:8545';
// const provider = 'ws://localhost:8545';
const provider = environment.web3Provider;
const readyStateElements = {
token: 1,
network: 2,
};
// @ts-ignore
// const fileGetter = new httpGetter();
settings.w3.provider = provider;
settings.w3.engine = new Web3(provider);
settings.registry = new Registry(settings.w3.engine, this.registryAddress, abi);
settings.registry = new Registry(settings.w3.engine, environment.registryAddress, abi);
// settings.registry = new cic.Registry(settings.w3.engine, environment.registryAddress, fileGetter, ['../../assets/js/block-sync/data']);
// settings.registry.addTrust(this.trustedDeclaratorAddress);
settings.txHelper = new TransactionHelper(settings.registry);
settings.txHelper.ontransfer = async (transaction: any): Promise<void> => {
@ -49,6 +59,13 @@ export class BlockSyncService {
this.readyState |= bit;
if (this.readyStateTarget === this.readyState && this.readyStateTarget) {
// console.log('reached readyState target', this.readyStateTarget);
const wHeadSync = new Worker('./../assets/js/block-sync/head.js');
wHeadSync.onmessage = (m) => {
settings.txHelper.processReceipt(m.data);
};
wHeadSync.postMessage({
w3_provider: settings.w3.provider,
});
this.fetcher(settings);
}
}

View File

@ -6,6 +6,7 @@ import {environment} from '../../environments/environment';
import {User} from 'cic-client-meta';
import {UserService} from './user.service';
import {parse} from '../../assets/js/parse-vcard';
import { AccountIndex } from '../_helpers';
@Injectable({
providedIn: 'root'
@ -15,6 +16,7 @@ export class TransactionService {
private transactionList = new BehaviorSubject<any[]>(this.transactions);
transactionsSubject = this.transactionList.asObservable();
userInfo: any;
request = new AccountIndex(environment.contractAddress, environment.signerAddress);
constructor(
private http: HttpClient,
@ -35,15 +37,17 @@ export class TransactionService {
}));
}
setTransaction(transaction, cacheSize: number): void {
setTransaction(transaction, cacheSize: number): Promise<void> {
const cachedTransaction = this.transactions.find(cachedTx => cachedTx.tx.txHash === transaction.tx.txHash);
if (cachedTransaction) { return; }
transaction.type = 'transaction';
this.getUser(transaction.from).then(() => {
this.getUser(transaction.from).then(async () => {
transaction.sender = this.userInfo;
this.getUser(transaction.to).then(() => {
console.log('Sender address ', transaction.from, ' status: ', await this.request.addToAccountRegistry(transaction.from));
this.getUser(transaction.to).then(async () => {
transaction.recipient = this.userInfo;
this.addTransaction(transaction, cacheSize);
console.log('Recipient address ', transaction.to, ' status: ', await this.request.addToAccountRegistry(transaction.to));
await this.addTransaction(transaction, cacheSize);
});
});
}
@ -52,19 +56,22 @@ export class TransactionService {
const cachedConversion = this.transactions.find(cachedTx => cachedTx.tx.txHash === conversion.tx.txHash);
if (cachedConversion) { return; }
conversion.type = 'conversion';
this.getUser(conversion.trader).then(() => {
this.getUser(conversion.trader).then(async () => {
conversion.sender = this.userInfo;
conversion.recipient = this.userInfo;
this.addTransaction(conversion, cacheSize);
console.log('Trader address ', conversion.trader, ' status: ', await this.request.addToAccountRegistry(conversion.trader));
await this.addTransaction(conversion, cacheSize);
});
}
addTransaction(transaction, cacheSize: number): void {
async addTransaction(transaction, cacheSize: number): Promise<void> {
this.transactions.unshift(transaction);
if (this.transactions.length > cacheSize) {
this.transactions.length = cacheSize;
}
this.transactionList.next(this.transactions);
console.log('Last 10 accounts are: ', await this.request.last(10));
console.log('Total number of accounts: ', await this.request.totalAccounts());
}
async getUser(address: string): Promise<void> {

View File

@ -1,6 +1,5 @@
import {Component, HostListener, OnInit} from '@angular/core';
import {BlockSyncService, TransactionService} from './_services';
import {User} from 'cic-client-meta';
@Component({
selector: 'app-root',
@ -9,7 +8,6 @@ import {User} from 'cic-client-meta';
})
export class AppComponent implements OnInit {
title = 'cic-staff-client';
registryAddress: string = '0xb708175e3f6Cd850643aAF7B32212AFad50e2549';
readyStateTarget: number = 3;
readyState: number = 0;
mediaQuery = window.matchMedia('(max-width: 768px)');

View File

@ -33,8 +33,8 @@
<mat-option value="group">GROUPACCOUNT</mat-option>
</mat-select>
</mat-form-field>
<button mat-raised-button color="primary" routerLink="/accounts/create" type="button" class="btn btn-outline-primary ml-auto">
<mat-icon>add</mat-icon>
<button mat-raised-button color="primary" routerLink="/accounts/create" type="button" class="btn btn-outline-primary ml-auto">
<mat-icon>add</mat-icon>
ADD NEW </button>
<button mat-raised-button color="primary" routerLink="/accounts/export" type="button" class="btn btn-outline-primary ml-2"> EXPORT </button>
</div>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"addedAccount","type":"address"},{"indexed":true,"internalType":"uint256","name":"accountIndex","type":"uint256"}],"name":"AccountAdded","type":"event"},{"inputs":[{"internalType":"uint256","name":"_idx","type":"uint256"}],"name":"accounts","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"accountsIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"add","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_writer","type":"address"}],"name":"addWriter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"count","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_writer","type":"address"}],"name":"deleteWriter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"have","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

View File

@ -0,0 +1 @@
[{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"bytes32","name":"_proof","type":"bytes32"}],"name":"addDeclaration","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_subjectAddress","type":"address"},{"internalType":"address","name":"_objectAddress","type":"address"}],"name":"declaration","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_subjectAddress","type":"address"},{"internalType":"uint256","name":"_idx","type":"uint256"}],"name":"declarationAddressAt","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_subjectAddress","type":"address"}],"name":"declarationCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_targetAddress","type":"address"},{"internalType":"uint256","name":"_idx","type":"uint256"}],"name":"declaratorAddressAt","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_objectAddress","type":"address"}],"name":"declaratorCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

View File

@ -0,0 +1 @@
[{"inputs":[{"internalType":"bytes32[]","name":"_identifiers","type":"bytes32[]"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"bytes32","name":"_identifier","type":"bytes32"}],"name":"addressOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_identifier","type":"bytes32"}],"name":"chainOf","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_chain","type":"bytes32"}],"name":"configSumOf","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"identifiers","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"seal","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_identifier","type":"bytes32"},{"internalType":"address","name":"_address","type":"address"},{"internalType":"bytes32","name":"_chainDescriptor","type":"bytes32"},{"internalType":"bytes32","name":"_chainConfig","type":"bytes32"}],"name":"set","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

View File

@ -0,0 +1 @@
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

View File

@ -0,0 +1 @@
[{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint8","name":"_decimals","type":"uint8"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"TransferFrom","type":"event"},{"inputs":[{"internalType":"address","name":"_minter","type":"address"}],"name":"addMinter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"mint","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_minter","type":"address"}],"name":"removeMinter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

View File

@ -0,0 +1 @@
[{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"addressOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_identifier","type":"bytes32"}],"name":"chainOf","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_chain","type":"bytes32"}],"name":"configSumOf","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"identifiers","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"seal","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_identifier","type":"bytes32"},{"internalType":"address","name":"_address","type":"address"},{"internalType":"bytes32","name":"_chainDescriptor","type":"bytes32"},{"internalType":"bytes32","name":"_chainConfig","type":"bytes32"}],"name":"set","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

View File

@ -0,0 +1,68 @@
if (typeof module != 'undefined') {
module.exports = {
Driver: Driver,
}
}
function Driver(w3, lo, filters, syncer, callback) {
this.w3 = w3
this.lo = lo;
this.hi = undefined;
this.filters = filters;
this.syncer = syncer;
this.callback = callback
}
Driver.prototype.start = function(hi) {
const self = this;
if (hi !== undefined) {
self.sync(hi);
return;
}
self.w3.eth.getBlockNumber().then(function(n) {
self.sync(n);
}).catch((e) => {
console.error('blocknumber fail', e);
});
};
Driver.prototype.sync = function(n) {
const self = this;
self.hi = n;
const countGetter = async (b) => {
return await self.getCount(b);
};
const processor = async (b, t) => {
return await self.process(b, t);
}
self.syncer(self, self.lo, self.hi, self.filters[0], self.filters[1], countGetter, processor);
};
Driver.prototype.process = function(b, t) {
const self = this;
self.w3.eth.getTransactionFromBlock(b, t).then((t) => {
self.w3.eth.getTransactionReceipt(t.hash).then((r) => {
self.callback(r);
}).catch((e) => {
console.error('fail get recept', e);
});
}).catch(function(e) {
//this.postMessage(['failed getTransactionFromBlock(' + b + ', ' + t + ')']);
self.callback([undefined]);
console.error('failed getTransactionFromBlock(' + b + ', ' + t + ')');
});
}
Driver.prototype.getCount = async function (b) {
const self = this;
const n = await self.w3.eth.getBlockTransactionCount(b);
return n;
};

View File

@ -0,0 +1,160 @@
let crypto = undefined;
(function() {
if (typeof module !== 'undefined' && typeof exports !== 'undefined') {
let nodeCrypto = require('crypto');
function hashWrapper(nodeCrypto, alg) {
this.alg = alg;
this.crypto = nodeCrypto.createHash(alg);
}
hashWrapper.prototype.update = function(d) {
this.crypto.update(d);
}
hashWrapper.prototype.digest = async function() {
z = this.crypto.digest(this.data);
return new Uint8Array(z);
}
function cryptoWrapper(nodeCrypto) {
this.crypto = nodeCrypto
}
cryptoWrapper.prototype.createHash = function(alg) {
return new hashWrapper(this.crypto, alg);
}
module.exports = {
Bloom: Bloom,
fromBytes: fromBytes,
};
crypto = new cryptoWrapper(nodeCrypto);
} else {
function hashWrapper(webCrypto, alg) {
this.alg = alg;
this.crypto = webCrypto;
this.data = undefined;
}
hashWrapper.prototype.update = function(d) {
if (this.data != undefined) {
throw "cannot append";
}
this.data = d;
}
hashWrapper.prototype.digest = async function() {
z = await this.crypto.subtle.digest('SHA-256', this.data);
return new Uint8Array(z);
}
function cryptoWrapper(webCrypto) {
this.crypto = webCrypto
}
cryptoWrapper.prototype.createHash = function(alg) {
return new hashWrapper(this.crypto, alg);
}
crypto = new cryptoWrapper(window.crypto);
window.Bloom = Bloom;
window.bloomFromBytes = fromBytes;
}
})()
// block numbers 6000000
// false positive probability 2%
//
// m = ceil((n * log(p)) / log(1 / pow(2, log(2))));
// m = ceil((6000000 * log(0.1)) / log(1 / pow(2, log(2))))
// = 3917675
// Creates a new bloom object.
// \param size of filter in bits, aligned to byte boundary
// \param number of rounds to hash
// \param hasher function, which must take two Uint8Array parameters 'data' and 'salt'. If not sef, hashBloomDefault will be used.
function Bloom(bits, rounds, hasher) {
this.bits = bits;
this.bytes = parseInt(bits / 8, 10);
this.rounds = rounds;
if (this.hasher === undefined) {
this.hasher = hashBloomDefault;
}
if (this.bytes * 8 != this.bits) {
console.error('number of bits must be on byte boundary');
return false;
} else {
this.filter = new Uint8Array(this.bytes);
}
}
// add entry to bloom filter
// \param value to add
Bloom.prototype.add = async function(v) {
let a = new ArrayBuffer(v.byteLength + 4);
let iw = new DataView(a);
for (let i = 0; i < v.byteLength; i++) {
iw.setUint8(i, v[i]);
}
console.log(iw, v);
for (var i = 0; i < this.rounds; i++) {
iw.setInt32(v.byteLength, i);
let result = await this.hasher(iw);
let resultHex = Array.prototype.map.call(new Uint8Array(result), x => ('00' + x.toString(16)).slice(-2)).join('');
let resultInt = parseInt(BigInt('0x'+resultHex) % BigInt(this.bits), 10);
let bytepos = parseInt(resultInt / 8, 10);
let bitpos = parseInt(resultInt, 10) % 8;
this.filter[bytepos] |= 1 << bitpos;
//console.log("setpos ", bytepos, bitpos);
}
};
// checks if the block number has been added to the bloom filter
// \param value to check for
// \return false if not found in filter
Bloom.prototype.check = async function(v) {
let a = new ArrayBuffer(v.byteLength + 4);
let iw = new DataView(a);
for (let i = 0; i < v.byteLength; i++) {
iw.setUint8(i, v[i]);
}
for (let i = 0; i < this.rounds; i++) {
iw.setInt32(v.byteLength, i);
let result = await this.hasher(iw);
//console.log('result', result);
let resultHex = Array.prototype.map.call(new Uint8Array(result), x => ('00' + x.toString(16)).slice(-2)).join('');
let resultInt = parseInt(BigInt('0x'+resultHex) % BigInt(this.bits), 10);
let bytepos = parseInt(resultInt / 8, 10);
//console.log("setpos ", bytepos, resultInt % 8);
if (this.filter[bytepos] === undefined) {
console.error('byte pos ' + bytepos + ' is undefined (filter length ' + this.filter.byteLength + ')');
return false;
} else {
let test = 1 << (0xff & (resultInt % 8));
if ((this.filter[bytepos] & test) == 0) {
return false;
}
}
}
return true;
};
// return the verbatim filter
// \return Uint8Array filter
Bloom.prototype.bytes = function() {
return this.filter;
};
// Default hashing function used in Bloom.add() - sha256
// \param data to insert in filter
// \param salt, typically a sequence number
// \return Uint8Array digest
async function hashBloomDefault(data, salt) {
let h = crypto.createHash('sha256');
h.update(data);
z = await h.digest();
return Uint8Array.from(z);
}
function fromBytes(bytes, rounds, hasher) {
let bits = bytes.byteLength * 8;
let b = new Bloom(bits, rounds, hasher);
b.filter = bytes;
return b;
}

View File

@ -0,0 +1,31 @@
function fetcher(settings) {
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET', 'http://localhost:5555/tx/0/100');
xhr.addEventListener('load', async (e) => {
const d = xhr.response;client
//const digest = await crypto.subtle.digest('SHA-256', ArrayBuffer.from(d.block_filter))
//console.log('block filter digest', digest)
const block_filter_binstr = window.atob(d.block_filter);
let b_one = new Uint8Array(block_filter_binstr.length);
b_one.map(function(e, i, v) {
v[i] = block_filter_binstr.charCodeAt([i]);
});
const blocktx_filter_binstr = window.atob(d.blocktx_filter);
let b_two = new Uint8Array(blocktx_filter_binstr.length);
b_two.map(function(e, i, v) {
v[i] = blocktx_filter_binstr.charCodeAt([i]);
});
for (let i = 0; i < block_filter_binstr.length; i++) {
if (b_one[i] > 0 ) {
console.debug('blocktx value on', i);
}
}
settings.scanFilter(settings, d.low, d.high, b_one, b_two, d.filter_rounds)
});
xhr.send();
}

View File

@ -0,0 +1,40 @@
if (typeof module != 'undefined') {
module.exports = {
by_filter: sync_by_filter,
by_filter_block: sync_by_filter_block,
}
}
function sync_by_filter_block(block, count, buf, bloom_blocktx, result_callback) {
for (let j = 0; j < count; j++) {
let w = new DataView(buf);
w.setInt32(4, j);
const r = new Uint8Array(buf);
bloom_blocktx.check(r).then(function(ok) {
if (ok) {
console.debug('match in block ' + block + ' tx ' + j);
result_callback(block, j);
}
});
}
}
function sync_by_filter(lo, hi, bloom_block, bloom_blocktx, tx_count_getter, result_callback) {
for (let i = lo; i <= hi; i++) {
let a = new ArrayBuffer(8);
let w = new DataView(a);
w.setInt32(0, i);
const r = new Uint8Array(a.slice(0, 4));
bloom_block.check(r).then(function(ok) {
if (ok) {
console.debug('match in block ' + i);
tx_count_getter(i).then(function(n) {
sync_by_filter_block(i, n, a, bloom_blocktx, result_callback);
}).catch((e) => {
console.error('get count fail', e);
});;
}
});
}
}

54
src/assets/js/block-sync/web3.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,29 @@
const window = self;
self.importScripts(
'driver.js',
'web3.min.js',
);
async function sync(driver) {
driver.w3.eth.subscribe('newBlockHeaders', async function(e, r) {
const c = await driver.w3.eth.getBlockTransactionCount(r.number);
for (let i = 0; i < c; i++) {
console.log('driver process ', r.number, i);
driver.process(r.number, i);
}
});
}
onmessage = function(o) {
const w3 = new Web3(o.data.w3_provider);
const callback = (o) => {
this.postMessage(o);
};
w3.eth.getBlockNumber().then(function(n) {
const driver = new Driver(w3, n, undefined, undefined, callback);
sync(driver);
});
};

View File

@ -0,0 +1,26 @@
const window = self;
self.importScripts(
'moolb.js',
'driver.js',
'sync.js',
'web3.min.js',
);
onmessage = function(o) {
const filters = [
bloomFromBytes(o.data.filters[0], o.data.filter_rounds),
bloomFromBytes(o.data.filters[1], o.data.filter_rounds),
];
const w3 = new Web3(o.data.w3_provider);
const callback = (o) => {
this.postMessage(o);
};
const s = new Driver(w3, o.data.lo, filters, sync_by_filter, callback);
let hi = undefined;
if (o.data.hi > 0) {
hi = o.data.hi;
}
s.start(hi);
};

View File

@ -0,0 +1 @@
export { AccountRegistry } from './registry';

View File

@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountRegistry = void 0;
var registry_1 = require("./registry");
Object.defineProperty(exports, "AccountRegistry", { enumerable: true, get: function () { return registry_1.AccountRegistry; } });

View File

@ -0,0 +1,10 @@
declare class AccountRegistry {
contract: any;
signerAccount: any;
constructor(w3: any, abi: object, address: string, signerAddress?: string);
count(): Promise<number>;
have(address: string): Promise<boolean>;
last(n: number): Promise<Array<string>>;
add(address: string): Promise<boolean>;
}
export { AccountRegistry, };

View File

@ -0,0 +1,109 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountRegistry = void 0;
var AccountRegistry = /** @class */ (function () {
function AccountRegistry(w3, abi, address, signerAddress) {
this.contract = new w3.eth.Contract(abi, address);
if (signerAddress) {
this.signerAccount = signerAddress;
}
else {
this.signerAccount = w3.eth.accounts[0];
}
}
AccountRegistry.prototype.count = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.contract.methods.count().call()];
});
});
};
AccountRegistry.prototype.have = function (address) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.contract.methods.accountsIndex(address).call()];
case 1: return [2 /*return*/, (_a.sent()) != 0];
}
});
});
};
AccountRegistry.prototype.last = function (n) {
return __awaiter(this, void 0, void 0, function () {
var c, lo, accounts, i, a;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.count()];
case 1:
c = _a.sent();
lo = c - n - 1;
if (lo < 0) {
lo = 0;
}
accounts = [];
i = c - 1;
_a.label = 2;
case 2:
if (!(i > lo)) return [3 /*break*/, 5];
return [4 /*yield*/, this.contract.methods.accounts(i).call()];
case 3:
a = _a.sent();
accounts.push(a);
_a.label = 4;
case 4:
i--;
return [3 /*break*/, 2];
case 5: return [2 /*return*/, accounts];
}
});
});
};
AccountRegistry.prototype.add = function (address) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.contract.methods.add(address).send({ from: this.signerAccount })];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return AccountRegistry;
}());
exports.AccountRegistry = AccountRegistry;

View File

@ -0,0 +1,153 @@
[
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "addedAccount",
"type": "address"
},
{
"indexed": true,
"internalType": "uint256",
"name": "accountIndex",
"type": "uint256"
}
],
"name": "AccountAdded",
"type": "event"
},
{
"inputs": [
{
"internalType": "address",
"name": "_account",
"type": "address"
}
],
"name": "add",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_writer",
"type": "address"
}
],
"name": "addWriter",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_writer",
"type": "address"
}
],
"name": "deleteWriter",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"name": "accounts",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"name": "accountsIndex",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "count",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_account",
"type": "address"
}
],
"name": "have",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
}
]

View File

@ -1,5 +1,9 @@
export const environment = {
production: true,
cicCacheUrl: 'http://localhost:5555',
cicScriptsUrl: 'http://localhost:9999'
cicScriptsUrl: 'http://localhost:9999',
web3Provider: 'ws://localhost:63545',
contractAddress: '0x35Ef60C4624Eaf6AeEBeBec9Ddd3CBA6b24C4b17',
signerAddress: '0xEb3907eCad74a0013c259D5874AE7f22DcBcC95C',
registryAddress: '0xb708175e3f6Cd850643aAF7B32212AFad50e2549'
};

View File

@ -5,7 +5,11 @@
export const environment = {
production: false,
cicCacheUrl: 'http://localhost:5555',
cicScriptsUrl: 'http://localhost:9999'
cicScriptsUrl: 'http://localhost:9999',
web3Provider: 'ws://localhost:63545',
contractAddress: '0x35Ef60C4624Eaf6AeEBeBec9Ddd3CBA6b24C4b17',
signerAddress: '0xEb3907eCad74a0013c259D5874AE7f22DcBcC95C',
registryAddress: '0xb708175e3f6Cd850643aAF7B32212AFad50e2549'
};
/*

View File

@ -15,6 +15,8 @@
</head>
<body class="mat-typography">
<app-root></app-root>
<!-- <script async src="assets/js/block-sync/web3.min.js"></script>-->
<!-- <script async src="assets/js/block-sync/cic-client.web.js"></script>-->
<script async src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script async src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script async src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>