Repository navigation
Expand file tree
/
Copy pathpseudoToken.js
More file actions
128 lines (101 loc) · 3.05 KB
/
Copy pathpseudoToken.js
File metadata and controls
128 lines (101 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/**
* Token transactions controller
*/
const verifyAsync = require('./verifyWorker');
const VERIFY_WORKERS = 6;
class PseudoToken {
constructor(initialEmissions = [], walletObject) {
this.wallets = {};
this._totalSupply = 0;
/**
* @var {Wallet}
*/
this._walletObject = walletObject;
//Initial token minting
for (let emission of initialEmissions) {
this.mint(emission.to, emission.amount);
}
}
_checkTxSign(tx) {
return true;
//return this._walletObject.verifyData(tx.data, tx.sign, tx.pubkey);
//return false;
}
_createWalletIfNotExists(address) {
if(typeof this.wallets[address] === 'undefined') {
this.wallets[address] = 0;
}
}
balanceOf(address) {
this._createWalletIfNotExists(address);
return this.wallets[address];
}
totalSupply() {
return this._totalSupply;
}
mint(to, amount) {
this._createWalletIfNotExists(to);
this.wallets[to] += amount;
this._totalSupply += amount;
return true;
}
burn(from, amount) {
this._createWalletIfNotExists(from);
if(this.wallets[from] - amount < 0) {
console.log('Insufficient funds', from);
return false;
}
this.wallets[from] -= amount;
this._totalSupply -= amount;
return true;
}
transfer(from, to, amount) {
this._createWalletIfNotExists(to);
if(this.burn(from, amount)) {
this.mint(to, amount);
return true;
}
return false;
}
updateStateByTX(tx) {
//Если подпись транзакции корректна то обрабатываем её
if(this._checkTxSign(tx)) {
this.transfer(tx.pubkey, tx.to, tx.amount);
} else {
console.log('Invalid TX sign', tx.pubkey, tx.sign);
}
}
async _verifySigns(txs) {
console.time('Verify');
let delta = txs.length / VERIFY_WORKERS;
let workers = [];
let needWorkers = Math.ceil(txs.length / delta);
for (let i = 0; i < needWorkers; i++) {
let workerTxs = txs.slice(0, Math.round(delta));
txs = txs.slice(Math.round(delta));
workers.push(verifyAsync(workerTxs));
}
console.log('Start workers', workers.length);
try {
await Promise.all(workers);
} catch (e) {
console.timeEnd('Verify');
return false;
}
console.timeEnd('Verify');
return true;
}
async processBlock(block) {
console.log('Start block processing');
if(await this._verifySigns(block.txs)) {
console.time('Processing block');
for (let tx of block.txs) {
this.updateStateByTX(tx);
}
console.timeEnd('Processing block');
} else {
console.log('Invalid signs');
}
}
}
module.exports = PseudoToken;