-
Notifications
You must be signed in to change notification settings - Fork 286
/
wallet-manager.ts
474 lines (389 loc) · 18 KB
/
wallet-manager.ts
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
import { app } from "@arkecosystem/core-container";
import { Logger, Shared, State } from "@arkecosystem/core-interfaces";
import { Handlers } from "@arkecosystem/core-transactions";
import { Enums, Identities, Interfaces, Utils } from "@arkecosystem/crypto";
import pluralize from "pluralize";
import { WalletIndexAlreadyRegisteredError, WalletIndexNotFoundError } from "./errors";
import { TempWalletManager } from "./temp-wallet-manager";
import { Wallet } from "./wallet";
import { WalletIndex } from "./wallet-index";
export class WalletManager implements State.IWalletManager {
// @TODO: make this private and read-only
public logger: Logger.ILogger = app.resolvePlugin<Logger.ILogger>("logger");
private readonly indexes: Record<string, State.IWalletIndex> = {};
private currentBlock: Interfaces.IBlock;
constructor() {
this.reset();
this.registerIndex(State.WalletIndexes.Addresses, (index: State.IWalletIndex, wallet: State.IWallet) => {
if (wallet.address) {
index.set(wallet.address, wallet);
}
});
this.registerIndex(State.WalletIndexes.PublicKeys, (index: State.IWalletIndex, wallet: State.IWallet) => {
if (wallet.publicKey) {
index.set(wallet.publicKey, wallet);
}
});
this.registerIndex(State.WalletIndexes.Usernames, (index: State.IWalletIndex, wallet: State.IWallet) => {
if (wallet.isDelegate()) {
index.set(wallet.getAttribute("delegate.username"), wallet);
}
});
}
public registerIndex(name: string, indexer: State.WalletIndexer): void {
if (this.indexes[name]) {
throw new WalletIndexAlreadyRegisteredError(name);
}
this.indexes[name] = new WalletIndex(indexer);
}
public unregisterIndex(name: string): void {
if (!this.indexes[name]) {
throw new WalletIndexNotFoundError(name);
}
delete this.indexes[name];
}
public getIndex(name: string): State.IWalletIndex {
if (!this.indexes[name]) {
throw new WalletIndexNotFoundError(name);
}
return this.indexes[name];
}
public allByAddress(): ReadonlyArray<State.IWallet> {
return this.getIndex(State.WalletIndexes.Addresses).all();
}
public allByPublicKey(): ReadonlyArray<State.IWallet> {
return this.getIndex(State.WalletIndexes.PublicKeys).all();
}
public allByUsername(): ReadonlyArray<State.IWallet> {
return this.getIndex(State.WalletIndexes.Usernames).all();
}
public findById(id: string): State.IWallet {
for (const index of Object.values(this.indexes)) {
const wallet: State.IWallet = index.get(id);
if (wallet) {
return wallet;
}
}
return undefined;
}
public findByAddress(address: string): State.IWallet {
const index: State.IWalletIndex = this.getIndex(State.WalletIndexes.Addresses);
if (address && !index.has(address)) {
index.set(address, new Wallet(address));
}
return index.get(address);
}
public findByPublicKey(publicKey: string): State.IWallet {
const index: State.IWalletIndex = this.getIndex(State.WalletIndexes.PublicKeys);
if (publicKey && !index.has(publicKey)) {
const address: string = Identities.Address.fromPublicKey(publicKey);
const wallet: State.IWallet = this.findByAddress(address);
wallet.publicKey = publicKey;
index.set(publicKey, wallet);
}
return index.get(publicKey);
}
public findByUsername(username: string): State.IWallet {
return this.findByIndex(State.WalletIndexes.Usernames, username);
}
public findByIndex(indexName: string, key: string): State.IWallet | undefined {
return this.getIndex(indexName).get(key);
}
public has(key: string): boolean {
for (const walletIndex of Object.values(this.indexes)) {
if (walletIndex.has(key)) {
return true;
}
}
return false;
}
public hasByAddress(address: string): boolean {
return this.hasByIndex(State.WalletIndexes.Addresses, address);
}
public hasByPublicKey(publicKey: string): boolean {
return this.hasByIndex(State.WalletIndexes.PublicKeys, publicKey);
}
public hasByUsername(username: string): boolean {
return this.hasByIndex(State.WalletIndexes.Usernames, username);
}
public hasByIndex(indexName: string, key: string): boolean {
return this.getIndex(indexName).has(key);
}
public getNonce(publicKey: string): Utils.BigNumber {
if (this.hasByPublicKey(publicKey)) {
return this.findByPublicKey(publicKey).nonce;
}
return Utils.BigNumber.ZERO;
}
public forgetByAddress(address: string): void {
this.forgetByIndex(State.WalletIndexes.Addresses, address);
}
public forgetByPublicKey(publicKey: string): void {
this.forgetByIndex(State.WalletIndexes.PublicKeys, publicKey);
}
public forgetByUsername(username: string): void {
this.forgetByIndex(State.WalletIndexes.Usernames, username);
}
public forgetByIndex(indexName: string, key: string): void {
this.getIndex(indexName).forget(key);
}
public index(wallets: ReadonlyArray<State.IWallet>): void {
for (const wallet of wallets) {
this.reindex(wallet);
}
}
public reindex(wallet: State.IWallet): void {
for (const walletIndex of Object.values(this.indexes)) {
walletIndex.index(wallet);
}
}
public getCurrentBlock(): Readonly<Interfaces.IBlock> {
return this.currentBlock;
}
public clone(): WalletManager {
return new TempWalletManager(this);
}
public loadActiveDelegateList(roundInfo: Shared.IRoundInfo): State.IWallet[] {
const delegates: State.IWallet[] = this.buildDelegateRanking(roundInfo);
const { maxDelegates } = roundInfo;
if (delegates.length < maxDelegates) {
throw new Error(
`Expected to find ${maxDelegates} delegates but only found ${delegates.length}. ` +
`This indicates an issue with the genesis block & delegates.`,
);
}
this.logger.debug(`Loaded ${delegates.length} active ${pluralize("delegate", delegates.length)}`);
return delegates;
}
// Only called during integrity verification on boot.
public buildVoteBalances(): void {
for (const voter of this.allByPublicKey()) {
if (voter.hasVoted()) {
const delegate: State.IWallet = this.findByPublicKey(voter.getAttribute<string>("vote"));
const voteBalance: Utils.BigNumber = delegate.getAttribute("delegate.voteBalance");
delegate.setAttribute("delegate.voteBalance", voteBalance.plus(voter.balance));
}
}
}
public async applyBlock(block: Interfaces.IBlock): Promise<void> {
this.currentBlock = block;
const generatorPublicKey: string = block.data.generatorPublicKey;
let delegate: State.IWallet;
if (!this.has(generatorPublicKey)) {
const generator: string = Identities.Address.fromPublicKey(generatorPublicKey);
if (block.data.height === 1) {
delegate = new Wallet(generator);
delegate.publicKey = generatorPublicKey;
this.reindex(delegate);
} else {
app.forceExit(`Failed to lookup generator '${generatorPublicKey}' of block '${block.data.id}'.`);
}
} else {
delegate = this.findByPublicKey(block.data.generatorPublicKey);
}
const appliedTransactions: Interfaces.ITransaction[] = [];
try {
for (const transaction of block.transactions) {
this.applyTransaction(transaction);
appliedTransactions.push(transaction);
}
const applied: boolean = delegate.applyBlock(block.data);
// If the block has been applied to the delegate, the balance is increased
// by reward + totalFee. In which case the vote balance of the
// delegate's delegate has to be updated.
if (applied && delegate.hasVoted()) {
const increase: Utils.BigNumber = block.data.reward.plus(block.data.totalFee);
const votedDelegate: State.IWallet = this.findByPublicKey(delegate.getAttribute<string>("vote"));
const voteBalance: Utils.BigNumber = votedDelegate.getAttribute("delegate.voteBalance");
votedDelegate.setAttribute("delegate.voteBalance", voteBalance.plus(increase));
}
} catch (error) {
this.logger.error("Failed to apply all transactions in block - reverting previous transactions");
// Revert the applied transactions from last to first
for (const transaction of appliedTransactions.reverse()) {
await this.revertTransaction(transaction);
}
throw error;
} finally {
this.currentBlock = undefined;
}
}
public async revertBlock(block: Interfaces.IBlock): Promise<void> {
if (!this.has(block.data.generatorPublicKey)) {
app.forceExit(`Failed to lookup generator '${block.data.generatorPublicKey}' of block '${block.data.id}'.`);
}
this.currentBlock = block;
const delegate: State.IWallet = this.findByPublicKey(block.data.generatorPublicKey);
const revertedTransactions: Interfaces.ITransaction[] = [];
try {
// Revert the transactions from last to first
for (let i = block.transactions.length - 1; i >= 0; i--) {
const transaction: Interfaces.ITransaction = block.transactions[i];
this.revertTransaction(transaction);
revertedTransactions.push(transaction);
}
const reverted: boolean = delegate.revertBlock(block.data);
// If the block has been reverted, the balance is decreased
// by reward + totalFee. In which case the vote balance of the
// delegate's delegate has to be updated.
if (reverted && delegate.hasVoted()) {
const decrease: Utils.BigNumber = block.data.reward.plus(block.data.totalFee);
const votedDelegate: State.IWallet = this.findByPublicKey(delegate.getAttribute<string>("vote"));
const voteBalance: Utils.BigNumber = votedDelegate.getAttribute("delegate.voteBalance");
votedDelegate.setAttribute("delegate.voteBalance", voteBalance.minus(decrease));
}
} catch (error) {
this.logger.error(error.stack);
for (const transaction of revertedTransactions.reverse()) {
this.applyTransaction(transaction);
}
throw error;
} finally {
this.currentBlock = undefined;
}
}
public applyTransaction(transaction: Interfaces.ITransaction): void {
const transactionHandler: Handlers.TransactionHandler = Handlers.Registry.get(transaction.type);
transactionHandler.apply(transaction, this);
const sender: State.IWallet = this.findByPublicKey(transaction.data.senderPublicKey);
const recipient: State.IWallet = this.findByAddress(transaction.data.recipientId);
this.updateVoteBalances(sender, recipient, transaction.data);
}
public async revertTransaction(transaction: Interfaces.ITransaction): Promise<void> {
const { data } = transaction;
const transactionHandler: Handlers.TransactionHandler = Handlers.Registry.get(transaction.type);
const sender: State.IWallet = this.findByPublicKey(data.senderPublicKey);
const recipient: State.IWallet = this.findByAddress(data.recipientId);
transactionHandler.revert(transaction, this);
// Revert vote balance updates
this.updateVoteBalances(sender, recipient, data, true);
}
public canBePurged(wallet: State.IWallet): boolean {
return wallet.canBePurged();
}
public reset(): void {
for (const walletIndex of Object.values(this.indexes)) {
walletIndex.clear();
}
}
public buildDelegateRanking(roundInfo?: Shared.IRoundInfo): State.IWallet[] {
const delegates: State.IWallet[] = this.allByUsername().filter(
(wallet: State.IWallet) => !wallet.hasAttribute("delegate.resigned"),
);
let delegateWallets = delegates
.sort((a, b) => {
const voteBalanceA: Utils.BigNumber = a.getAttribute("delegate.voteBalance");
const voteBalanceB: Utils.BigNumber = b.getAttribute("delegate.voteBalance");
const diff = voteBalanceB.comparedTo(voteBalanceA);
if (diff === 0) {
if (a.publicKey === b.publicKey) {
throw new Error(
`The balance and public key of both delegates are identical! Delegate "${a.getAttribute(
"delegate.username",
)}" appears twice in the list.`,
);
}
return a.publicKey.localeCompare(b.publicKey, "en");
}
return diff;
})
.map(
(delegate, i): State.IWallet => {
const rank = i + 1;
delegate.setAttribute("delegate.rank", rank);
return delegate;
},
);
if (roundInfo) {
delegateWallets = delegateWallets.slice(0, roundInfo.maxDelegates);
for (const delegate of delegateWallets) {
delegate.setAttribute("delegate.round", roundInfo.round);
}
}
return delegateWallets;
}
/**
* Updates the vote balances of the respective delegates of sender and recipient.
* If the transaction is not a vote...
* 1. fee + amount is removed from the sender's delegate vote balance
* 2. amount is added to the recipient's delegate vote balance
*
* in case of a vote...
* 1. the full sender balance is added to the sender's delegate vote balance
*
* If revert is set to true, the operations are reversed (plus -> minus, minus -> plus).
*/
private updateVoteBalances(
sender: State.IWallet,
recipient: State.IWallet,
transaction: Interfaces.ITransactionData,
revert: boolean = false,
): void {
if (transaction.type !== Enums.TransactionTypes.Vote) {
// Update vote balance of the sender's delegate
if (sender.hasVoted()) {
const delegate: State.IWallet = this.findByPublicKey(sender.getAttribute("vote"));
const amount =
transaction.type === Enums.TransactionTypes.MultiPayment
? transaction.asset.payments.reduce(
(prev, curr) => prev.plus(curr.amount),
Utils.BigNumber.ZERO,
)
: transaction.amount;
const total: Utils.BigNumber = amount.plus(transaction.fee);
const voteBalance: Utils.BigNumber = delegate.getAttribute(
"delegate.voteBalance",
Utils.BigNumber.ZERO,
);
delegate.setAttribute(
"delegate.voteBalance",
revert ? voteBalance.plus(total) : voteBalance.minus(total),
);
}
if (transaction.type === Enums.TransactionTypes.MultiPayment) {
// go through all payments and update recipients delegates vote balance
for (const { recipientId, amount } of transaction.asset.payments) {
const recipientWallet: State.IWallet = this.findByAddress(recipientId);
const vote = recipientWallet.getAttribute("vote");
if (vote) {
const delegate: State.IWallet = this.findByPublicKey(vote);
const voteBalance: Utils.BigNumber = delegate.getAttribute(
"delegate.voteBalance",
Utils.BigNumber.ZERO,
);
delegate.setAttribute(
"delegate.voteBalance",
revert ? voteBalance.minus(amount) : voteBalance.plus(amount),
);
}
}
}
// Update vote balance of recipient's delegate
if (recipient && recipient.hasVoted()) {
const delegate: State.IWallet = this.findByPublicKey(recipient.getAttribute("vote"));
const voteBalance: Utils.BigNumber = delegate.getAttribute(
"delegate.voteBalance",
Utils.BigNumber.ZERO,
);
delegate.setAttribute(
"delegate.voteBalance",
revert ? voteBalance.minus(transaction.amount) : voteBalance.plus(transaction.amount),
);
}
} else {
const vote: string = transaction.asset.votes[0];
const delegate: State.IWallet = this.findByPublicKey(vote.substr(1));
let voteBalance: Utils.BigNumber = delegate.getAttribute("delegate.voteBalance", Utils.BigNumber.ZERO);
if (vote.startsWith("+")) {
voteBalance = revert
? voteBalance.minus(sender.balance.minus(transaction.fee))
: voteBalance.plus(sender.balance);
} else {
voteBalance = revert
? voteBalance.plus(sender.balance)
: voteBalance.minus(sender.balance.plus(transaction.fee));
}
delegate.setAttribute("delegate.voteBalance", voteBalance);
}
}
}