This repository has been archived by the owner on Jun 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 457
/
chain_state_builder.js
504 lines (452 loc) · 13.7 KB
/
chain_state_builder.js
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
* Copyright © 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
const {
createSignatureObject,
TransferTransaction,
DelegateTransaction,
VoteTransaction,
castVotes,
MultisignatureTransaction,
registerMultisignature: registerMultisignatureLisk,
} = require('@liskhq/lisk-transactions');
const {
getAddressFromPrivateKey,
getPrivateAndPublicKeyFromPassphrase,
} = require('@liskhq/lisk-cryptography');
const { Mnemonic } = require('@liskhq/lisk-passphrase');
const { cloneDeep } = require('lodash');
const BigNum = require('@liskhq/bignum');
const { createBlock } = require('./blocks');
const defaultConfig = require('../config/devnet');
class ChainStateBuilder {
constructor(
genesisBlock,
initialAccountsStates,
accounts,
includeGenesisBlockInState = false,
) {
this.genesisBlock = genesisBlock;
this.previousBlock = genesisBlock;
this.state = {
chain: includeGenesisBlockInState ? [this.genesisBlock] : [],
accounts: cloneDeep(accounts),
accountStore: [cloneDeep(initialAccountsStates)],
initialAccountStore: cloneDeep(initialAccountsStates),
pendingTransactions: [],
appliedTransactions: [],
inputBlock: [],
};
this.round = 0;
this.slot = 0;
this.fixedPoint = 10 ** 8;
this.fees = {
transfer: this.fixedPoint * 0.1,
signature: this.fixedPoint * 5,
delegate: this.fixedPoint * 25,
vote: this.fixedPoint * 1,
multisignature: this.fixedPoint * 5,
};
this.lastTransactionId = null;
this.timestamp = 102702700;
}
transfer(amount) {
return {
from: addressFrom => ({
to: addressTo => {
const amountBeddows = `${amount * this.fixedPoint}`;
const transferTx = new TransferTransaction({
amount: amountBeddows,
recipientId: Object.values(this.state.accounts).find(
anAccount => anAccount.address === addressTo,
).address,
timestamp: this.timestamp,
});
transferTx.sign(
Object.values(this.state.accounts).find(
anAccount => anAccount.address === addressFrom,
).passphrase,
);
// Push it to pending transaction
this.state.pendingTransactions.push(transferTx);
this.lastTransactionId = transferTx._id;
return this;
},
}),
};
}
registerDelegate(delegateName) {
return {
for: delegateAddress => {
const sender = Object.values(this.state.accounts).find(
anAccount => anAccount.address === delegateAddress,
);
const registerDelegateTx = new DelegateTransaction({
timestamp: this.timestamp,
asset: {
delegate: {
username: delegateName,
},
},
});
registerDelegateTx.sign(sender.passphrase);
// Push it to pending transaction
this.state.pendingTransactions.push(registerDelegateTx);
this.lastTransactionId = registerDelegateTx._id;
return this;
},
};
}
// eslint-disable-next-line class-methods-use-this
registerMultisignature(address) {
const members = [];
const finish = () => {
// Extract main account info
const targetAccount = this.findAccountByAddress(
address,
Object.values(this.state.accounts),
);
// Extract members info
const membersAccounts = [];
// eslint-disable-next-line no-restricted-syntax
for (const aMemberAddress of members) {
const thisMember = this.findAccountByAddress(
aMemberAddress,
Object.values(this.state.accounts),
);
if (!thisMember) {
throw new Error(
'One of the members for a Multisignature Transaction was not found. Check your initial account setup. Make sure all members exist',
);
}
membersAccounts.push(thisMember);
}
// Create basic multisignature object
const multisignatureObject = registerMultisignatureLisk({
lifetime: 1,
minimum: membersAccounts.length,
keysgroup: membersAccounts.map(aMember => aMember.publicKey),
});
multisignatureObject.timestamp = this.timestamp;
// Create a multisignature instance
const multisignatureTXInstance = new MultisignatureTransaction(
multisignatureObject,
);
multisignatureTXInstance.sign(targetAccount.passphrase);
// Add the signatures for each member
// eslint-disable-next-line no-restricted-syntax
for (const aMemberAccount of membersAccounts) {
const aSigObject = createSignatureObject(
multisignatureTXInstance.toJSON(),
aMemberAccount.passphrase,
);
multisignatureTXInstance.addMultisignature(null, aSigObject);
}
// Push it to the pending
this.state.pendingTransactions.push(multisignatureTXInstance);
this.lastTransactionId = multisignatureTXInstance._id;
return this;
};
const addMemberAndSign = aMember => {
members.push(aMember);
return { finish, addMemberAndSign };
};
return {
addMemberAndSign,
};
}
// This method adds signatures ONLY too the last transaction sent
signTransaction(transactionId) {
const transactionToBeSigned = this.state.pendingTransactions.find(
aTransaction => aTransaction.id === transactionId,
);
if (!transactionToBeSigned) {
throw new Error(
'The provided transaction id was not found make sure you are callign `signTransaction` correctly.',
);
}
return {
withAccount: signerAccountAddress => {
const accountStore = Object.values(this.state.accounts);
const signerAccount = accountStore.find(
anAccount => anAccount.address === signerAccountAddress,
);
if (!signerAccount) {
throw new Error(
'Signer account not found make sure the account exists on your intial account state.',
);
}
const transactionSignature = createSignatureObject(
transactionToBeSigned.toJSON(),
signerAccount.passphrase,
);
transactionToBeSigned.signatures.push(transactionSignature.signature);
return this;
},
};
}
castVotesFrom(votingAccountAddress) {
return {
voteDelegates: votedDelegates => ({
unvoteDelegates: unvotedDelegates => {
if (votedDelegates.length + unvotedDelegates.length > 33) {
// eslint-disable-next-line no-console
console.log(
`WARNING: you included '${votedDelegates.length +
unvotedDelegates.length}' votes in a vote transaction. This is only valid for simulating invalid scenarios!`,
);
}
// Get the account that's voting
const votingAccount = this.findAccountByAddress(
votingAccountAddress,
Object.values(this.state.accounts),
);
// Create the JSON for the vote transaction
const castVotesObject = castVotes({
votes: votedDelegates,
unvotes: unvotedDelegates,
});
castVotesObject.timestamp = this.timestamp;
// Create vote transaction instance
const voteInstance = new VoteTransaction(castVotesObject);
voteInstance.sign(votingAccount.passphrase);
this.state.pendingTransactions.push(voteInstance);
return this;
},
}),
};
}
forge() {
const latestsAccountState = this.state.accountStore.slice(-1)[0];
this.processBlockTransactions(this.state.pendingTransactions);
const newBlock = createBlock(
defaultConfig,
latestsAccountState,
this.previousBlock,
this.round,
this.slot,
{
version: 1,
transactions: [...this.state.pendingTransactions],
},
);
this.state.chain.push(newBlock);
this.previousBlock = newBlock;
this.state.appliedTransactions.push([...this.state.pendingTransactions]);
this.state.pendingTransactions = [];
return this;
}
forgeInvalidInputBlock() {
const latestsAccountState = this.state.accountStore.slice(-1)[0];
const newBlock = createBlock(
defaultConfig,
latestsAccountState,
this.previousBlock,
this.round,
this.slot,
{
version: 1,
transactions: [...this.state.pendingTransactions],
},
);
this.state.inputBlock.push(newBlock);
this.state.appliedTransactions.push(...this.state.pendingTransactions);
this.state.pendingTransactions = [];
return this;
}
processBlockTransactions() {
// eslint-disable-next-line no-restricted-syntax
for (const aTransaction of this.state.pendingTransactions) {
switch (aTransaction.type) {
case 0:
this.updateAccountBalancesAfterTransfer(
aTransaction.senderId,
aTransaction.recipientId,
aTransaction.amount.toString(),
);
break;
case 2:
this.updateAccountStateAfterDelegateRegistration(
aTransaction.senderId,
this.fees.delegate,
aTransaction.asset.delegate.username,
);
break;
case 3:
this.updateAccountStateAfterCastingvotes(aTransaction);
break;
case 4:
this.updateAccountStateAfterMultisignatureRegistration(aTransaction);
break;
default:
break;
}
}
return this;
}
getScenario() {
return {
initialAccountsState: this.state.initialAccountStore,
finalAccountsState: this.state.accountStore,
chain: this.state.chain,
inputBlock: this.state.inputBlock,
};
}
updateAccountBalancesAfterTransfer(from, to, amount) {
const newAccountStoreState = cloneDeep(
this.state.accountStore.slice(-1)[0],
);
const sender = this.findAccountByAddress(from, newAccountStoreState);
const recipient = this.findAccountByAddress(to, newAccountStoreState);
if (!sender) {
throw new Error(
'Sender does not exists so it would not be possible to transfer from this account. Check the values passed to the constructor',
);
}
if (!sender && !recipient) {
throw new Error(
'Both sender and recipient were not found in the account store state. This means that something is wrong with the values passed to the constructor.',
);
}
// Update sender balance
sender.balance = new BigNum(sender.balance.toString())
.sub(amount)
.sub(this.fees.transfer)
.toString();
// If recipient does not exists create the account
if (!recipient) {
const newAccount = this.newAccountFromTemplate(
Object.values(this.state.accounts).find(
anAccount => anAccount.address === to,
),
);
newAccount.balance = new BigNum(newAccount.balance.toString())
.add(amount)
.toString();
newAccountStoreState.push(newAccount);
} else {
recipient.balance = new BigNum(recipient.balance.toString())
.add(amount)
.toString();
}
this.state.accountStore.push(newAccountStoreState);
}
updateAccountStateAfterDelegateRegistration(from, amount, delegateName) {
const newAccountStoreState = cloneDeep(
this.state.accountStore.slice(-1)[0],
);
const sender = this.findAccountByAddress(from, newAccountStoreState);
if (!sender) {
throw new Error(
'Sender does not exists so it would not be possible to transfer from this account. Check the values passed to the constructor',
);
}
// Update sender balance
sender.balance = new BigNum(sender.balance.toString())
.sub(amount)
.toString();
sender.username = delegateName;
sender.isDelegate = true;
this.state.accountStore.push(newAccountStoreState);
}
updateAccountStateAfterMultisignatureRegistration(multisignatureTransaction) {
const newAccountStoreState = cloneDeep(
this.state.accountStore.slice(-1)[0],
);
// Update sender balance
const sender = this.findAccountByAddress(
multisignatureTransaction._senderId,
newAccountStoreState,
);
sender.balance = new BigNum(sender.balance.toString())
.sub(multisignatureTransaction.fee)
.toString();
sender.multiMin = multisignatureTransaction.asset.multisignature.min;
sender.multiLifetime =
multisignatureTransaction.asset.multisignature.lifetime;
this.state.accountStore.push(newAccountStoreState);
}
updateAccountStateAfterCastingvotes(castVotesTransaction) {
const newAccountStoreState = cloneDeep(
this.state.accountStore.slice(-1)[0],
);
// Update sender balance
const sender = this.findAccountByAddress(
castVotesTransaction._senderId,
newAccountStoreState,
);
sender.balance = new BigNum(sender.balance.toString())
.sub(castVotesTransaction.fee)
.toString();
// Extract voted publicKeys from vote transaction
// eslint-disable-next-line no-restricted-syntax
for (const aVotedPublicKey of castVotesTransaction.asset.votes) {
const action = aVotedPublicKey.slice(0, 1);
const publickKey = aVotedPublicKey.slice(1);
const affectedAccount = newAccountStoreState.find(
anAccount => anAccount.publicKey === publickKey,
);
if (action === '+') {
affectedAccount.vote = new BigNum(affectedAccount.vote)
.plus(sender.balance)
.toString();
} else {
affectedAccount.vote = new BigNum(affectedAccount.vote)
.sub(sender.balance)
.toString();
}
}
// Finally push all updates to the account store
this.state.accountStore.push(newAccountStoreState);
}
// eslint-disable-next-line
findAccountByAddress(address, collection) {
return collection.find(anAccount => anAccount.address === address);
}
// eslint-disable-next-line
newAccountFromTemplate(account) {
return {
address: account.address,
publicKey: account.publicKey,
secondPublicKey: null,
username: '',
isDelegate: false,
secondSignature: false,
balance: 0,
multiMin: 0,
multiLifetime: 0,
nameExist: false,
missedBlocks: 0,
producedBlocks: 0,
rank: 0,
fees: 0,
rewards: 0,
vote: 0,
productivity: 0,
};
}
static createAccount() {
const passphrase = Mnemonic.generateMnemonic();
const keys = getPrivateAndPublicKeyFromPassphrase(passphrase);
const address = getAddressFromPrivateKey(keys.privateKey);
return {
passphrase,
privateKey: keys.privateKey,
publicKey: keys.publicKey,
address,
balance: '0',
};
}
}
module.exports = ChainStateBuilder;