-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
node.ts
981 lines (791 loc) · 27.2 KB
/
node.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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
import VM from "@nomiclabs/ethereumjs-vm";
import { EVMResult, ExecResult } from "@nomiclabs/ethereumjs-vm/dist/evm/evm";
import { ERROR } from "@nomiclabs/ethereumjs-vm/dist/exceptions";
import {
RunBlockResult,
TxReceipt
} from "@nomiclabs/ethereumjs-vm/dist/runBlock";
import { StateManager } from "@nomiclabs/ethereumjs-vm/dist/state";
import PStateManager from "@nomiclabs/ethereumjs-vm/dist/state/promisified";
import chalk from "chalk";
import debug from "debug";
import Account from "ethereumjs-account";
import Block from "ethereumjs-block";
import Common from "ethereumjs-common";
import { FakeTransaction, Transaction } from "ethereumjs-tx";
import {
BN,
bufferToHex,
ECDSASignature,
ecsign,
hashPersonalMessage,
privateToAddress,
toBuffer
} from "ethereumjs-util";
import Trie from "merkle-patricia-tree/secure";
import { promisify } from "util";
import { BUIDLEREVM_DEFAULT_GAS_PRICE } from "../../core/config/default-config";
import { getUserConfigPath } from "../../core/project-structure";
import { createModelsAndDecodeBytecodes } from "../stack-traces/compiler-to-model";
import { CompilerInput, CompilerOutput } from "../stack-traces/compiler-types";
import { ContractsIdentifier } from "../stack-traces/contracts-identifier";
import { decodeRevertReason } from "../stack-traces/revert-reasons";
import { encodeSolidityStackTrace } from "../stack-traces/solidity-errors";
import { SolidityStackTrace } from "../stack-traces/solidity-stack-trace";
import { SolidityTracer } from "../stack-traces/solidityTracer";
import { VMTracer } from "../stack-traces/vm-tracer";
import { Blockchain } from "./blockchain";
import { InternalError, InvalidInputError } from "./errors";
import { getCurrentTimestamp } from "./utils";
const log = debug("buidler:core:buidler-evm:node");
// This library's types are wrong, they don't type check
// tslint:disable-next-line no-var-requires
const ethSigUtil = require("eth-sig-util");
export type Block = any;
export interface GenesisAccount {
privateKey: string;
balance: string | number | BN;
}
export const COINBASE_ADDRESS = toBuffer(
"0xc014ba5ec014ba5ec014ba5ec014ba5ec014ba5e"
);
export interface CallParams {
to: Buffer;
from: Buffer;
gasLimit: BN;
gasPrice: BN;
value: BN;
data: Buffer;
}
export interface TransactionParams {
to: Buffer;
from: Buffer;
gasLimit: BN;
gasPrice: BN;
value: BN;
data: Buffer;
nonce: BN;
}
export class TransactionExecutionError extends Error {}
export interface TxBlockResult {
receipt: TxReceipt;
createAddresses: Buffer | undefined;
bloomBitvector: Buffer;
}
// tslint:disable only-buidler-error
export interface SolidityTracerOptions {
solidityVersion: string;
compilerInput: CompilerInput;
compilerOutput: CompilerOutput;
}
export const SUPPORTED_HARDFORKS = [
"byzantium",
"constantinople",
"petersburg",
"istanbul"
];
export class BuidlerNode {
public static async create(
hardfork: string,
networkName: string,
chainId: number,
networkId: number,
blockGasLimit: number,
throwOnTransactionFailures: boolean,
throwOnCallFailures: boolean,
genesisAccounts: GenesisAccount[] = [],
stackTracesOptions?: SolidityTracerOptions
): Promise<[Common, BuidlerNode]> {
const stateTrie = new Trie();
const putIntoStateTrie = promisify(stateTrie.put.bind(stateTrie));
for (const acc of genesisAccounts) {
let balance: BN;
if (
typeof acc.balance === "string" &&
acc.balance.toLowerCase().startsWith("0x")
) {
balance = new BN(toBuffer(acc.balance));
} else {
balance = new BN(acc.balance);
}
const account = new Account({ balance });
const pk = toBuffer(acc.privateKey);
const address = privateToAddress(pk);
await putIntoStateTrie(address, account.serialize());
}
// Mimic precompiles activation
for (let i = 1; i <= 8; i++) {
await putIntoStateTrie(
new BN(i).toArrayLike(Buffer, "be", 20),
new Account().serialize()
);
}
const common = Common.forCustomChain(
"mainnet",
{
chainId,
networkId,
name: networkName,
genesis: {
timestamp: `0x${getCurrentTimestamp().toString(16)}`,
hash: "0x",
gasLimit: blockGasLimit,
difficulty: 1,
nonce: "0x42",
extraData: "0x1234",
stateRoot: bufferToHex(stateTrie.root)
}
},
hardfork
);
const stateManager = new StateManager({
common: common as any, // TS error because of a version mismatch
trie: stateTrie
});
const blockchain = new Blockchain();
const vm = new VM({
common: common as any, // TS error because of a version mismatch
activatePrecompiles: true,
stateManager,
blockchain: blockchain as any
});
const genesisBlock = new Block(null, { common });
genesisBlock.setGenesisParams();
await new Promise(resolve => {
blockchain.putBlock(genesisBlock, () => resolve());
});
const node = new BuidlerNode(
vm,
genesisAccounts.map(acc => toBuffer(acc.privateKey)),
new BN(blockGasLimit),
genesisBlock,
throwOnTransactionFailures,
throwOnCallFailures,
stackTracesOptions
);
return [common, node];
}
private readonly _common: Common;
private readonly _stateManager: PStateManager;
private _blockTimeOffsetSeconds: BN = new BN(0);
private readonly _accountPrivateKeys: Map<string, Buffer> = new Map();
private readonly _transactionByHash: Map<string, Transaction> = new Map();
private readonly _transactionHashToBlockHash: Map<string, string> = new Map();
private readonly _blockHashToTxBlockResults: Map<
string,
TxBlockResult[]
> = new Map();
private readonly _blockHashToTotalDifficulty: Map<string, BN> = new Map();
private readonly _stackTracesEnabled: boolean = false;
private readonly _vmTracer?: VMTracer;
private readonly _solidityTracer?: SolidityTracer;
private readonly _getLatestBlock: () => Promise<Block>;
private readonly _getBlock: (hashOrNumber: Buffer | BN) => Promise<Block>;
private _failedStackTraces = 0;
private constructor(
private readonly _vm: VM,
localAccounts: Buffer[],
private readonly _blockGasLimit: BN,
genesisBlock: Block,
private readonly _throwOnTransactionFailures: boolean,
private readonly _throwOnCallFailures: boolean,
stackTracesOptions?: SolidityTracerOptions
) {
const config = getUserConfigPath();
this._stateManager = new PStateManager(this._vm.stateManager);
this._common = this._vm._common as any; // TODO: There's a version mismatch, that's why we cast
this._initLocalAccounts(localAccounts);
this._blockHashToTotalDifficulty.set(
bufferToHex(genesisBlock.hash()),
this._computeTotalDifficulty(genesisBlock)
);
this._getLatestBlock = promisify(
this._vm.blockchain.getLatestBlock.bind(this._vm.blockchain)
);
this._getBlock = promisify(
this._vm.blockchain.getBlock.bind(this._vm.blockchain)
);
if (stackTracesOptions !== undefined) {
this._stackTracesEnabled = true;
this._vmTracer = new VMTracer(this._vm, true);
try {
this._vmTracer.enableTracing();
const bytecodes = createModelsAndDecodeBytecodes(
stackTracesOptions.solidityVersion,
stackTracesOptions.compilerInput,
stackTracesOptions.compilerOutput
);
const contractsIdentifier = new ContractsIdentifier();
for (const bytecode of bytecodes) {
contractsIdentifier.addBytecode(bytecode);
}
this._solidityTracer = new SolidityTracer(contractsIdentifier);
} catch (error) {
console.warn(
chalk.yellow(
"Stack traces engine could not be initialized. Run Buidler with --verbose to learn more."
)
);
this._stackTracesEnabled = false;
this._vmTracer.disableTracing();
log(
"Solidity stack traces disabled: SolidityTracer failed to be initialized. Please report this to help us improve Buidler.\n",
error
);
}
}
}
public async getSignedTransaction(
txParams: TransactionParams
): Promise<Transaction> {
const tx = new Transaction(txParams, { common: this._common });
const pk = await this._getLocalAccountPrivateKey(txParams.from);
tx.sign(pk);
return tx;
}
public async _getFakeTransaction(
txParams: TransactionParams
): Promise<Transaction> {
return new FakeTransaction(txParams, { common: this._common });
}
public async runTransactionInNewBlock(
tx: Transaction
): Promise<RunBlockResult> {
await this._validateTransaction(tx);
await this._saveTransactionAsReceived(tx);
const block = await this._getNextBlockTemplate();
const needsTimestampIncrease = await this._timestampClashesWithPreviousBlockOne(
block
);
if (needsTimestampIncrease) {
await this._increaseBlockTimestamp(block);
}
await this._addTransactionToBlock(block, tx);
const result = await this._vm.runBlock({
block,
generate: true,
skipBlockValidation: true
});
const error = !this._throwOnTransactionFailures
? undefined
: await this._manageErrors(result.results[0].execResult);
if (needsTimestampIncrease) {
await this.increaseTime(new BN(1));
}
await this._saveBlockAsSuccessfullyRun(block, result);
await this._saveTransactionAsSuccessfullyRun(tx, block);
if (error !== undefined) {
throw error;
}
return result;
}
public async mineEmptyBlock() {
const block = await this._getNextBlockTemplate();
const needsTimestampIncrease = await this._timestampClashesWithPreviousBlockOne(
block
);
if (needsTimestampIncrease) {
await this._increaseBlockTimestamp(block);
}
await promisify(block.genTxTrie.bind(block))();
block.header.transactionsTrie = block.txTrie.root;
const previousRoot = await this._stateManager.getStateRoot();
let result: RunBlockResult;
try {
result = await this._vm.runBlock({
block,
generate: true,
skipBlockValidation: true
});
if (needsTimestampIncrease) {
await this.increaseTime(new BN(1));
}
await this._saveBlockAsSuccessfullyRun(block, result);
return result;
} catch (error) {
// We set the state root to the previous one. This is equivalent to a
// rollback of this block.
await this._stateManager.setStateRoot(previousRoot);
throw error;
}
}
public async runCall(call: CallParams): Promise<Buffer> {
const tx = await this._getFakeTransaction({
...call,
nonce: await this.getAccountNonce(call.from)
});
const result = await this._runTxAndRevertMutations(tx, false);
const error = !this._throwOnCallFailures
? undefined
: await this._manageErrors(result.execResult);
if (error !== undefined) {
throw error;
}
if (
result.execResult.exceptionError === undefined ||
result.execResult.exceptionError.error === ERROR.REVERT
) {
return result.execResult.returnValue;
}
// If we got here we found another kind of error and we throw anyway
throw this._manageErrors(result.execResult)!;
}
public async getAccountBalance(address: Buffer): Promise<BN> {
const account = await this._stateManager.getAccount(address);
return new BN(account.balance);
}
public async getAccountNonce(address: Buffer): Promise<BN> {
const account = await this._stateManager.getAccount(address);
return new BN(account.nonce);
}
public async getLatestBlock(): Promise<Block> {
return this._getLatestBlock();
}
public async getLocalAccountAddresses(): Promise<string[]> {
return [...this._accountPrivateKeys.keys()];
}
public async getBlockGasLimit(): Promise<BN> {
return this._blockGasLimit;
}
public async estimateGas(txParams: TransactionParams): Promise<BN> {
const tx = await this._getFakeTransaction({
...txParams,
gasLimit: await this.getBlockGasLimit()
});
const result = await this._runTxAndRevertMutations(tx, true);
// This is only considered if the call to _runTxAndRevertMutations doesn't
// manage errors
if (result.execResult.exceptionError !== undefined) {
return this.getBlockGasLimit();
}
const initialEstimation = result.gasUsed;
return this._correctInitialEstimation(txParams, initialEstimation);
}
public async getGasPrice(): Promise<BN> {
return new BN(BUIDLEREVM_DEFAULT_GAS_PRICE);
}
public async getCoinbaseAddress(): Promise<Buffer> {
return COINBASE_ADDRESS;
}
public async getStorageAt(address: Buffer, slot: BN): Promise<Buffer> {
const key = slot.toArrayLike(Buffer, "be", 32);
const data = await this._stateManager.getContractStorage(address, key);
// TODO: The state manager returns the data as it was saved, it doesn't
// pad it. Technically, the storage consists of 32-byte slots, so we should
// always return 32 bytes. The problem is that Ganache doesn't handle them
// this way. We compromise a little here to ease the migration into
// BuidlerEVM :(
// const EXPECTED_DATA_SIZE = 32;
// if (data.length < EXPECTED_DATA_SIZE) {
// return Buffer.concat(
// [Buffer.alloc(EXPECTED_DATA_SIZE - data.length, 0), data],
// EXPECTED_DATA_SIZE
// );
// }
return data;
}
public async getBlockByNumber(blockNumber: BN): Promise<Block | undefined> {
if (blockNumber.gten(this._blockHashToTotalDifficulty.size)) {
return undefined;
}
return this._getBlock(blockNumber);
}
public async getBlockByHash(hash: Buffer): Promise<Block | undefined> {
if (!(await this._hasBlockWithHash(hash))) {
return undefined;
}
return this._getBlock(hash);
}
public async getBlockByTransactionHash(
hash: Buffer
): Promise<Block | undefined> {
const blockHash = this._transactionHashToBlockHash.get(bufferToHex(hash));
if (blockHash === undefined) {
return undefined;
}
return this.getBlockByHash(toBuffer(blockHash));
}
public async getBlockTotalDifficulty(block: Block): Promise<BN> {
const blockHash = bufferToHex(block.hash());
const td = this._blockHashToTotalDifficulty.get(blockHash);
if (td !== undefined) {
return td;
}
return this._computeTotalDifficulty(block);
}
public async getCode(address: Buffer): Promise<Buffer> {
return this._stateManager.getContractCode(address);
}
public async increaseTime(increment: BN) {
this._blockTimeOffsetSeconds = this._blockTimeOffsetSeconds.add(increment);
}
public async getTimeIncrement(): Promise<BN> {
return this._blockTimeOffsetSeconds;
}
public async getSuccessfulTransactionByHash(
hash: Buffer
): Promise<Transaction | undefined> {
const tx = this._transactionByHash.get(bufferToHex(hash));
if (tx !== undefined && (await this._transactionWasSuccessful(tx))) {
return tx;
}
return undefined;
}
public async getTxBlockResults(
block: Block
): Promise<TxBlockResult[] | undefined> {
return this._blockHashToTxBlockResults.get(bufferToHex(block.hash()));
}
public async getPendingTransactions(): Promise<Transaction[]> {
return [];
}
public async signPersonalMessage(
address: Buffer,
data: Buffer
): Promise<ECDSASignature> {
const messageHash = hashPersonalMessage(data);
const privateKey = await this._getLocalAccountPrivateKey(address);
return ecsign(messageHash, privateKey);
}
public async signTypedData(address: Buffer, typedData: any): Promise<string> {
const privateKey = await this._getLocalAccountPrivateKey(address);
return ethSigUtil.signTypedData_v4(privateKey, {
data: typedData
});
}
public async getStackTraceFailuresCount(): Promise<number> {
return this._failedStackTraces;
}
private _initLocalAccounts(localAccounts: Buffer[]) {
for (const pk of localAccounts) {
this._accountPrivateKeys.set(bufferToHex(privateToAddress(pk)), pk);
}
}
private async _manageErrors(
vmResult: ExecResult
): Promise<TransactionExecutionError | undefined> {
if (vmResult.exceptionError === undefined) {
return undefined;
}
let stackTrace: SolidityStackTrace | undefined;
if (this._stackTracesEnabled) {
try {
const vmTracerError = this._vmTracer!.getLastError();
if (vmTracerError !== undefined) {
this._vmTracer!.clearLastError();
throw vmTracerError;
}
const messageTrace = this._vmTracer!.getLastTopLevelMessageTrace();
const decodedTrace = this._solidityTracer!.tryToDecodeMessageTrace(
messageTrace
);
stackTrace = this._solidityTracer!.getStackTrace(decodedTrace);
} catch (error) {
this._failedStackTraces += 1;
log(
"Could not generate stack trace. Please report this to help us improve Buidler.\n",
error
);
}
}
const error = vmResult.exceptionError;
if (error.error === ERROR.OUT_OF_GAS) {
return new TransactionExecutionError("Transaction run out of gas");
}
if (error.error === ERROR.REVERT) {
if (vmResult.returnValue.length === 0) {
if (stackTrace !== undefined) {
return encodeSolidityStackTrace(
"Transaction reverted without a reason",
stackTrace
);
}
return new TransactionExecutionError(
"Transaction reverted without a reason"
);
}
if (stackTrace !== undefined) {
return encodeSolidityStackTrace(
`VM Exception while processing transaction: revert ${decodeRevertReason(
vmResult.returnValue
)}`,
stackTrace
);
}
return new TransactionExecutionError(
`VM Exception while processing transaction: revert ${decodeRevertReason(
vmResult.returnValue
)}`
);
}
if (stackTrace !== undefined) {
return encodeSolidityStackTrace("Transaction failed: revert", stackTrace);
}
return new TransactionExecutionError("Transaction failed: revert");
}
private async _getNextBlockTemplate(): Promise<Block> {
const block = new Block(
{
header: {
gasLimit: this._blockGasLimit,
nonce: "0x42",
timestamp: await this._getNextBlockTimestamp()
}
},
{ common: this._common }
);
block.validate = (blockchain: any, cb: any) => cb(null);
const latestBlock = await this.getLatestBlock();
block.header.number = toBuffer(new BN(latestBlock.header.number).addn(1));
block.header.parentHash = latestBlock.hash();
block.header.difficulty = block.header.canonicalDifficulty(latestBlock);
block.header.coinbase = await this.getCoinbaseAddress();
return block;
}
private async _getNextBlockTimestamp(): Promise<BN> {
const realTimestamp = new BN(getCurrentTimestamp());
return realTimestamp.add(this._blockTimeOffsetSeconds);
}
private async _saveTransactionAsReceived(tx: Transaction) {
this._transactionByHash.set(bufferToHex(tx.hash(true)), tx);
}
private async _getLocalAccountPrivateKey(sender: Buffer): Promise<Buffer> {
const senderAddress = bufferToHex(sender);
if (!this._accountPrivateKeys.has(senderAddress)) {
throw new InvalidInputError(`unknown account ${senderAddress}`);
}
return this._accountPrivateKeys.get(senderAddress)!;
}
private async _addTransactionToBlock(block: Block, tx: Transaction) {
block.transactions.push(tx);
await promisify(block.genTxTrie.bind(block))();
block.header.transactionsTrie = block.txTrie.root;
}
private async _saveBlockAsSuccessfullyRun(
block: Block,
runBlockResult: RunBlockResult
) {
await this._putBlock(block);
const txBlockResults: TxBlockResult[] = [];
for (let i = 0; i < runBlockResult.results.length; i += 1) {
const result = runBlockResult.results[i];
txBlockResults.push({
bloomBitvector: result.bloom.bitvector,
createAddresses: result.createdAddress,
receipt: runBlockResult.receipts[i]
});
}
const blockHash = bufferToHex(block.hash());
this._blockHashToTxBlockResults.set(blockHash, txBlockResults);
const td = this._computeTotalDifficulty(block);
this._blockHashToTotalDifficulty.set(blockHash, td);
}
private async _putBlock(block: Block): Promise<void> {
return new Promise((resolve, reject) => {
this._vm.blockchain.putBlock(block, (err?: any) => {
if (err !== undefined && err !== null) {
reject(err);
return;
}
resolve();
});
});
}
private async _hasBlockWithHash(blockHash: Buffer): Promise<boolean> {
if (this._blockHashToTotalDifficulty.has(bufferToHex(blockHash))) {
return true;
}
const block = await this.getBlockByNumber(new BN(0));
return block.hash().equals(blockHash);
}
private async _saveTransactionAsSuccessfullyRun(
tx: Transaction,
block: Block
) {
this._transactionHashToBlockHash.set(
bufferToHex(tx.hash(true)),
bufferToHex(block.hash())
);
}
private async _transactionWasSuccessful(tx: Transaction): Promise<boolean> {
return this._transactionHashToBlockHash.has(bufferToHex(tx.hash(true)));
}
private async _timestampClashesWithPreviousBlockOne(
block: Block
): Promise<boolean> {
const blockTimestamp = new BN(block.header.timestamp);
const latestBlock = await this.getLatestBlock();
const latestBlockTimestamp = new BN(latestBlock.header.timestamp);
return latestBlockTimestamp.eq(blockTimestamp);
}
private async _increaseBlockTimestamp(block: Block) {
block.header.timestamp = new BN(block.header.timestamp).addn(1);
}
private async _validateTransaction(tx: Transaction) {
// Geth throws this error if a tx is sent twice
if (await this._transactionWasSuccessful(tx)) {
throw new InvalidInputError(
`known transaction: ${bufferToHex(tx.hash(true)).toString()}`
);
}
if (!tx.verifySignature()) {
throw new InvalidInputError("Invalid transaction signature");
}
// Geth returns this error if trying to create a contract and no data is provided
if (tx.to.length === 0 && tx.data.length === 0) {
throw new InvalidInputError(
"contract creation without any data provided"
);
}
const expectedNonce = await this.getAccountNonce(tx.getSenderAddress());
const actualNonce = new BN(tx.nonce);
if (!expectedNonce.eq(actualNonce)) {
throw new InvalidInputError(
`Invalid nonce. Expected ${expectedNonce} but got ${actualNonce}`
);
}
const baseFee = tx.getBaseFee();
const gasLimit = new BN(tx.gasLimit);
if (baseFee.gt(gasLimit)) {
throw new InvalidInputError(
`Transaction requires at least ${baseFee} gas but got ${gasLimit}`
);
}
if (gasLimit.gt(this._blockGasLimit)) {
throw new InvalidInputError(
`Transaction gas limit is ${gasLimit} and exceeds block gas limit of ${this._blockGasLimit}`
);
}
}
private _computeTotalDifficulty(block: Block): BN {
const difficulty = new BN(block.header.difficulty);
const parentHash = bufferToHex(block.header.parentHash);
if (
parentHash ===
"0x0000000000000000000000000000000000000000000000000000000000000000"
) {
return difficulty;
}
const parentTd = this._blockHashToTotalDifficulty.get(parentHash);
if (parentTd === undefined) {
throw new InternalError(`Unrecognized parent block ${parentHash}`);
}
return parentTd.add(difficulty);
}
private async _correctInitialEstimation(
txParams: TransactionParams,
initialEstimation: BN
): Promise<BN> {
let tx = await this._getFakeTransaction({
...txParams,
gasLimit: initialEstimation
});
if (tx.getBaseFee().gte(initialEstimation)) {
initialEstimation = tx.getBaseFee().addn(1);
tx = await this._getFakeTransaction({
...txParams,
gasLimit: initialEstimation
});
}
const result = await this._runTxAndRevertMutations(tx, false);
if (result.execResult.exceptionError === undefined) {
return initialEstimation;
}
return this._binarySearchEstimation(
txParams,
initialEstimation,
await this.getBlockGasLimit()
);
}
private async _binarySearchEstimation(
txParams: TransactionParams,
highestFailingEstimation: BN,
lowestSuccessfulEstimation: BN,
roundNumber = 0
): Promise<BN> {
if (lowestSuccessfulEstimation.lte(highestFailingEstimation)) {
// This shouldn't happen, but we don't wan't to go into an infinite loop
// if it ever happens
return lowestSuccessfulEstimation;
}
const MAX_GAS_ESTIMATION_IMPROVEMENT_ROUNDS = 20;
const diff = lowestSuccessfulEstimation.sub(highestFailingEstimation);
const minDiff = highestFailingEstimation.gten(4_000_000)
? 50_000
: highestFailingEstimation.gten(1_000_000)
? 10_000
: highestFailingEstimation.gten(100_000)
? 1_000
: highestFailingEstimation.gten(50_000)
? 500
: highestFailingEstimation.gten(30_000)
? 300
: 200;
if (diff.lten(minDiff)) {
return lowestSuccessfulEstimation;
}
if (roundNumber > MAX_GAS_ESTIMATION_IMPROVEMENT_ROUNDS) {
return lowestSuccessfulEstimation;
}
const binSearchNewEstimation = highestFailingEstimation.add(diff.divn(2));
const optimizedEstimation =
roundNumber === 0
? highestFailingEstimation.muln(3)
: binSearchNewEstimation;
const newEstimation = optimizedEstimation.gt(binSearchNewEstimation)
? binSearchNewEstimation
: optimizedEstimation;
// Let other things execute
await new Promise(resolve => setImmediate(resolve));
const tx = await this._getFakeTransaction({
...txParams,
gasLimit: newEstimation
});
const result = await this._runTxAndRevertMutations(tx, false);
if (result.execResult.exceptionError === undefined) {
return this._binarySearchEstimation(
txParams,
highestFailingEstimation,
newEstimation,
roundNumber + 1
);
}
return this._binarySearchEstimation(
txParams,
newEstimation,
lowestSuccessfulEstimation,
roundNumber + 1
);
}
private async _runTxAndRevertMutations(
tx: Transaction,
manageErrors = true
): Promise<EVMResult> {
const initialStateRoot = await this._stateManager.getStateRoot();
try {
const block = await this._getNextBlockTemplate();
const needsTimestampIncrease = await this._timestampClashesWithPreviousBlockOne(
block
);
if (needsTimestampIncrease) {
await this._increaseBlockTimestamp(block);
}
await this._addTransactionToBlock(block, tx);
const result = await this._vm.runTx({
block,
tx,
skipNonce: true,
skipBalance: true
});
if (manageErrors) {
const error = await this._manageErrors(result.execResult);
if (error !== undefined) {
throw error;
}
}
return result;
} finally {
await this._stateManager.setStateRoot(initialStateRoot);
}
}
}