This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 676
/
blockchain.ts
1641 lines (1454 loc) · 50.5 KB
/
blockchain.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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EOL } from "os";
import Miner, { Capacity } from "./miner/miner";
import Database from "./database";
import Emittery from "emittery";
import {
BlockLogs,
Account,
ITraceData,
TraceDataFactory,
TraceStorageMap,
RuntimeError,
RETURN_TYPES,
StorageKeys,
StorageRangeResult,
StorageRecords,
RangedStorageKeys,
StructLog,
TransactionTraceOptions,
EthereumRawAccount,
TraceTransactionResult
} from "@ganache/ethereum-utils";
import type { Address as EthereumJsAddress } from "ethereumjs-util";
import type { InterpreterStep } from "@ethereumjs/vm/dist/evm/interpreter";
import { decode } from "@ganache/rlp";
import { BN, KECCAK256_RLP } from "ethereumjs-util";
import Common from "@ethereumjs/common";
import VM from "@ethereumjs/vm";
import { EVMResult } from "@ethereumjs/vm/dist/evm/evm";
import { VmError, ERROR } from "@ethereumjs/vm/dist/exceptions";
import { EthereumInternalOptions, Hardfork } from "@ganache/ethereum-options";
import {
Quantity,
Data,
BUFFER_EMPTY,
RPCQUANTITY_EMPTY,
BUFFER_32_ZERO,
BUFFER_256_ZERO,
RPCQUANTITY_ZERO,
findInsertPosition,
unref,
KNOWN_CHAINIDS
} from "@ganache/utils";
import AccountManager from "./data-managers/account-manager";
import BlockManager from "./data-managers/block-manager";
import BlockLogManager from "./data-managers/blocklog-manager";
import TransactionManager from "./data-managers/transaction-manager";
import { Fork } from "./forking/fork";
import { Address } from "@ganache/ethereum-address";
import {
calculateIntrinsicGas,
TransactionReceipt,
VmTransaction,
TypedTransaction
} from "@ganache/ethereum-transaction";
import { Block, RuntimeBlock, Snapshots } from "@ganache/ethereum-block";
import { SimulationTransaction } from "./helpers/run-call";
import { ForkStateManager } from "./forking/state-manager";
import {
DefaultStateManager,
StateManager
} from "@ethereumjs/vm/dist/state/index";
import { GanacheTrie } from "./helpers/trie";
import { ForkTrie } from "./forking/trie";
import { LevelUp } from "levelup";
import { activatePrecompiles, warmPrecompiles } from "./helpers/precompiles";
import TransactionReceiptManager from "./data-managers/transaction-receipt-manager";
import { BUFFER_ZERO } from "@ganache/utils";
import {
makeStepEvent,
VmAfterTransactionEvent,
VmBeforeTransactionEvent,
VmStepEvent
} from "./provider-events";
import mcl from "mcl-wasm";
const mclInitPromise = mcl.init(mcl.BLS12_381).then(() => {
mcl.setMapToMode(mcl.IRTF); // set the right map mode; otherwise mapToG2 will return wrong values.
mcl.verifyOrderG1(true); // subgroup checks for G1
mcl.verifyOrderG2(true); // subgroup checks for G2
});
export enum Status {
// Flags
started = 1, // 0000 0001
starting = 2, // 0000 0010
stopped = 4, // 0000 0100
stopping = 8, // 0000 1000
paused = 16 // 0001 0000
}
type BlockchainTypedEvents = {
block: Block;
blockLogs: BlockLogs;
pendingTransaction: TypedTransaction;
"ganache:vm:tx:step": VmStepEvent;
"ganache:vm:tx:before": VmBeforeTransactionEvent;
"ganache:vm:tx:after": VmAfterTransactionEvent;
};
type BlockchainEvents = "ready" | "stop";
interface Logger {
log(message?: any, ...optionalParams: any[]): void;
}
export type BlockchainOptions = {
db?: string | object;
db_path?: string;
initialAccounts?: Account[];
hardfork?: string;
allowUnlimitedContractSize?: boolean;
gasLimit?: Quantity;
time?: Date;
blockTime?: number;
coinbase: Account;
chainId: number;
common: Common;
legacyInstamine: boolean;
vmErrorsOnRPCResponse: boolean;
logger: Logger;
};
/**
* Sets the provided VM state manager's state root *without* first
* checking for checkpoints or flushing the existing cache.
*
* Useful if you know the state manager is not in a checkpoint and its internal
* cache is safe to discard.
*
* @param stateManager
* @param stateRoot
*/
function setStateRootSync(stateManager: StateManager, stateRoot: Buffer) {
(stateManager as any)._trie.root = stateRoot;
(stateManager as any)._cache.clear();
(stateManager as any)._storageTries = {};
}
function makeTrie(blockchain: Blockchain, db: LevelUp | null, root: Data) {
if (blockchain.fallback) {
return new ForkTrie(db, root ? root.toBuffer() : null, blockchain);
} else {
return new GanacheTrie(db, root ? root.toBuffer() : null, blockchain);
}
}
function createCommon(chainId: number, networkId: number, hardfork: Hardfork) {
const common = Common.forCustomChain(
// if we were given a chain id that matches a real chain, use it
// NOTE: I don't think Common serves a purpose other than instructing the
// VM what hardfork is in use. But just incase things change in the future
// its configured "more correctly" here.
KNOWN_CHAINIDS.has(chainId) ? chainId : 1,
{
name: "ganache",
networkId: networkId,
chainId: chainId,
comment: "Local test network"
},
hardfork
);
// the VM likes to listen to "hardforkChanged" events from common, but:
// a) we don't currently support changing hardforks
// b) it can cause `MaxListenersExceededWarning`.
// Since we don't need it we overwrite .on to make it be quiet.
(common as any).on = () => {};
return common;
}
export default class Blockchain extends Emittery.Typed<
BlockchainTypedEvents,
BlockchainEvents
> {
#state: Status = Status.starting;
#miner: Miner;
#blockBeingSavedPromise: Promise<{ block: Block; blockLogs: BlockLogs }>;
/**
* When not instamining (blockTime > 0) this value holds the timeout timer.
*/
#timer: NodeJS.Timer | null = null;
/**
* Because step events are expensive to create and emit, CPU-wise, we do it
* conditionally.
*/
#emitStepEvent: boolean = false;
public blocks: BlockManager;
public blockLogs: BlockLogManager;
public transactions: TransactionManager;
public transactionReceipts: TransactionReceiptManager;
public storageKeys: Database["storageKeys"];
public accounts: AccountManager;
public vm: VM;
public trie: GanacheTrie;
readonly #database: Database;
readonly #options: EthereumInternalOptions;
readonly #instamine: boolean;
public common: Common;
public fallback: Fork;
/**
* Initializes the underlying Database and handles synchronization between
* the API and the database.
*
* Emits a `ready` event once the database and all dependencies are fully
* initialized.
* @param options
*/
constructor(
options: EthereumInternalOptions,
coinbase: Address,
fallback?: Fork
) {
super();
this.#options = options;
this.fallback = fallback;
const instamine = (this.#instamine =
!options.miner.blockTime || options.miner.blockTime <= 0);
const legacyInstamine = options.miner.legacyInstamine;
{
// warnings and errors
if (legacyInstamine) {
console.info(
"Legacy instamining, where transactions are fully mined before the hash is returned, is deprecated and will be removed in the future."
);
}
if (!instamine) {
if (legacyInstamine) {
console.info(
"Setting `legacyInstamine` to `true` has no effect when blockTime is non-zero"
);
}
if (options.chain.vmErrorsOnRPCResponse) {
console.info(
"Setting `vmErrorsOnRPCResponse` to `true` has no effect on transactions when blockTime is non-zero"
);
}
}
}
this.coinbase = coinbase;
this.#database = new Database(options.database, this);
}
async initialize(initialAccounts: Account[]) {
const database = this.#database;
const options = this.#options;
const instamine = this.#instamine;
try {
let common: Common;
if (this.fallback) {
await this.fallback.initialize();
await database.initialize();
common = this.common = this.fallback.common;
options.fork.blockNumber = this.fallback.blockNumber.toNumber();
options.chain.networkId = common.networkId();
options.chain.chainId = common.chainId();
} else {
await database.initialize();
common = this.common = createCommon(
options.chain.chainId,
options.chain.networkId,
options.chain.hardfork
);
}
const blocks = (this.blocks = await BlockManager.initialize(
this,
common,
database.blockIndexes,
database.blocks
));
this.blockLogs = new BlockLogManager(database.blockLogs, this);
this.transactions = new TransactionManager(
options.miner,
common,
this,
database.transactions
);
this.transactionReceipts = new TransactionReceiptManager(
database.transactionReceipts,
this
);
this.accounts = new AccountManager(this);
this.storageKeys = database.storageKeys;
// if we have a latest block, use it to set up the trie.
const { latest } = blocks;
{
let stateRoot: Data | null;
if (latest) {
this.#blockBeingSavedPromise = Promise.resolve({
block: latest,
blockLogs: null
});
({ stateRoot } = latest.header);
} else {
stateRoot = null;
}
this.trie = makeTrie(this, database.trie, stateRoot);
}
// create VM and listen to step events
this.vm = await this.createVmFromStateTrie(
this.trie,
options.chain.allowUnlimitedContractSize,
true
);
{
// create first block
let firstBlockTime: number;
if (options.chain.time != null) {
// If we were given a timestamp, use it instead of the `_currentTime`
const t = options.chain.time.getTime();
firstBlockTime = Math.floor(t / 1000);
this.setTime(t);
} else {
firstBlockTime = this.#currentTime();
}
// if we don't already have a latest block, create a genesis block!
if (!latest) {
if (initialAccounts.length > 0) {
await this.#commitAccounts(initialAccounts);
}
this.#blockBeingSavedPromise = this.#initializeGenesisBlock(
firstBlockTime,
options.miner.blockGasLimit,
initialAccounts
);
blocks.earliest = blocks.latest = await this.#blockBeingSavedPromise.then(
({ block }) => block
);
}
}
{
// configure and start miner
const txPool = this.transactions.transactionPool;
const minerOpts = options.miner;
const miner = (this.#miner = new Miner(
minerOpts,
txPool.executables,
this.vm,
this.#readyNextBlock
));
//#region re-emit miner events:
miner.on("ganache:vm:tx:before", event => {
this.emit("ganache:vm:tx:before", event);
});
miner.on("ganache:vm:tx:step", event => {
if (!this.#emitStepEvent) return;
this.emit("ganache:vm:tx:step", event);
});
miner.on("ganache:vm:tx:after", event => {
this.emit("ganache:vm:tx:after", event);
});
//#endregion
//#region automatic mining
const nullResolved = Promise.resolve(null);
const mineAll = (maxTransactions: Capacity) =>
this.#isPaused() ? nullResolved : this.mine(maxTransactions);
if (instamine) {
// insta mining
// whenever the transaction pool is drained mine the txs into blocks
txPool.on("drain", mineAll.bind(null, Capacity.Single));
} else {
// interval mining
const wait = () =>
// unref, so we don't hold the chain open if nothing can interact with it
unref((this.#timer = setTimeout(next, minerOpts.blockTime * 1e3)));
const next = () => mineAll(Capacity.FillBlock).then(wait);
wait();
}
//#endregion
miner.on("block", this.#handleNewBlockData);
this.once("stop").then(() => miner.clearListeners());
}
} catch (e) {
// we failed to start up :-( bail!
this.#state = Status.stopping;
// ignore errors while stopping here, since we are already in an
// exceptional case
await this.stop().catch(_ => {});
throw e;
}
this.#state = Status.started;
this.emit("ready");
}
#saveNewBlock = ({
block,
serialized,
storageKeys,
transactions
}: {
block: Block;
serialized: Buffer;
storageKeys: StorageKeys;
transactions: TypedTransaction[];
}) => {
const { blocks } = this;
blocks.latest = block;
return this.#database.batch(() => {
const blockHash = block.hash();
const blockHeader = block.header;
const blockNumberQ = blockHeader.number;
const blockNumber = blockNumberQ.toBuffer();
const blockLogs = BlockLogs.create(blockHash);
const timestamp = blockHeader.timestamp;
const timestampStr = new Date(timestamp.toNumber() * 1000).toString();
const logOutput: string[] = [];
transactions.forEach((tx: TypedTransaction, i: number) => {
const hash = tx.hash.toBuffer();
const index = Quantity.from(i);
// save transaction to the database
const serialized = tx.serializeForDb(blockHash, blockNumberQ, index);
this.transactions.set(hash, serialized);
// save receipt to the database
const receipt = tx.getReceipt();
const encodedReceipt = receipt.serialize(true);
this.transactionReceipts.set(hash, encodedReceipt);
// collect block logs
tx.getLogs().forEach(blockLogs.append.bind(blockLogs, index, tx.hash));
// prepare log output
logOutput.push(
this.#getTransactionLogOutput(
hash,
receipt,
blockHeader.number,
timestampStr,
tx.execException
)
);
});
// save storage keys to the database
storageKeys.forEach(value => {
this.storageKeys.put(value.hashedKey, value.key);
});
blockLogs.blockNumber = blockHeader.number;
// save block logs to the database
this.blockLogs.set(blockNumber, blockLogs.serialize());
// save block to the database
blocks.putBlock(blockNumber, blockHash, serialized);
// output to the log, if we have data to output
if (logOutput.length > 0)
this.#options.logging.logger.log(logOutput.join(EOL));
return { block, blockLogs, transactions };
});
};
#emitNewBlock = async (blockInfo: {
block: Block;
blockLogs: BlockLogs;
transactions: TypedTransaction[];
}) => {
const options = this.#options;
const { block, blockLogs, transactions } = blockInfo;
// emit the block once everything has been fully saved to the database
transactions.forEach(transaction => {
transaction.finalize("confirmed", transaction.execException);
});
if (this.#instamine && options.miner.legacyInstamine) {
// in legacy instamine mode we must delay the broadcast of new blocks
await new Promise(resolve => {
process.nextTick(async () => {
// emit block logs first so filters can pick them up before
// block listeners are notified
await Promise.all([
this.emit("blockLogs", blockLogs),
this.emit("block", block)
]);
resolve(void 0);
});
});
} else {
// emit block logs first so filters can pick them up before
// block listeners are notified
await Promise.all([
this.emit("blockLogs", blockLogs),
this.emit("block", block)
]);
}
return blockInfo;
};
#getTransactionLogOutput = (
hash: Buffer,
receipt: TransactionReceipt,
blockNumber: Quantity,
timestamp: string,
error: RuntimeError | undefined
) => {
let str = `${EOL} Transaction: ${Data.from(hash)}${EOL}`;
const contractAddress = receipt.contractAddress;
if (contractAddress != null) {
str += ` Contract created: ${Address.from(contractAddress)}${EOL}`;
}
str += ` Gas usage: ${Quantity.from(receipt.raw[1]).toNumber()}
Block number: ${blockNumber.toNumber()}
Block time: ${timestamp}${EOL}`;
if (error) {
str += ` Runtime error: ${error.data.message}${EOL}`;
if (error.data.reason) {
str += ` Revert reason: ${error.data.reason}${EOL}`;
}
}
return str;
};
#handleNewBlockData = async (blockData: {
block: Block;
serialized: Buffer;
storageKeys: StorageKeys;
transactions: TypedTransaction[];
}) => {
this.#blockBeingSavedPromise = this.#blockBeingSavedPromise
.then(() => this.#saveNewBlock(blockData))
.then(this.#emitNewBlock);
return this.#blockBeingSavedPromise;
};
coinbase: Address;
#readyNextBlock = (previousBlock: Block, timestamp?: number) => {
const previousHeader = previousBlock.header;
const previousNumber = previousHeader.number.toBigInt() || 0n;
return new RuntimeBlock(
Quantity.from(previousNumber + 1n),
previousBlock.hash(),
this.coinbase,
this.#options.miner.blockGasLimit.toBuffer(),
BUFFER_ZERO,
Quantity.from(timestamp == null ? this.#currentTime() : timestamp),
this.#options.miner.difficulty,
previousHeader.totalDifficulty,
Block.calcNextBaseFee(previousBlock)
);
};
isStarted = () => {
return this.#state === Status.started;
};
mine = async (
maxTransactions: number | Capacity,
timestamp?: number,
onlyOneBlock: boolean = false
) => {
await this.#blockBeingSavedPromise;
const nextBlock = this.#readyNextBlock(this.blocks.latest, timestamp);
return {
transactions: await this.#miner.mine(
nextBlock,
maxTransactions,
onlyOneBlock
),
blockNumber: nextBlock.header.number.toBuffer()
};
};
#isPaused = () => {
return (this.#state & Status.paused) !== 0;
};
pause() {
this.#state |= Status.paused;
}
resume(_threads: number = 1) {
if (!this.#isPaused()) {
console.log("Warning: startMining called when miner was already started");
return;
}
// toggles the `paused` bit
this.#state ^= Status.paused;
// if we are instamining mine a block right away
if (this.#instamine) {
return this.mine(Capacity.FillBlock);
}
}
createVmFromStateTrie = async (
stateTrie: GanacheTrie | ForkTrie,
allowUnlimitedContractSize: boolean,
activatePrecompile: boolean,
common?: Common
) => {
const blocks = this.blocks;
// ethereumjs vm doesn't use the callback style anymore
const blockchain = {
getBlock: async (number: BN) => {
const block = await blocks.get(number.toBuffer()).catch(_ => null);
return block ? { hash: () => block.hash().toBuffer() } : null;
}
} as any;
// ethereumjs-vm wants to "copy" the blockchain when `vm.copy` is called.
blockchain.copy = () => {
return blockchain;
};
common = common || this.common;
const vm = new VM({
state: stateTrie,
activatePrecompiles: false,
common,
allowUnlimitedContractSize,
blockchain,
stateManager: this.fallback
? new ForkStateManager({ common, trie: stateTrie as ForkTrie })
: new DefaultStateManager({ common, trie: stateTrie })
});
if (activatePrecompile) {
await activatePrecompiles(vm.stateManager);
if (common.isActivatedEIP(2537)) {
// BLS12-381 curve, not yet included in any supported hardforks
// but probably will be in the Shanghai hardfork
// TODO: remove above comment once Shanghai is supported!
await mclInitPromise; // ensure that mcl is initialized!
}
}
// skip `vm.init`, since we don't use any of it
(vm as any)._isInitialized = true;
return vm;
};
#commitAccounts = (accounts: Account[]) => {
return Promise.all<void>(
accounts.map(account =>
this.trie.put(account.address.toBuffer(), account.serialize())
)
);
};
#initializeGenesisBlock = async (
timestamp: number,
blockGasLimit: Quantity,
initialAccounts: Account[]
) => {
if (this.fallback != null) {
const { block: fallbackBlock } = this.fallback;
const { miner: minerOptions } = this.#options;
// commit accounts, but for forking.
const stateManager = <DefaultStateManager>this.vm.stateManager;
await stateManager.checkpoint();
initialAccounts.forEach(acc => {
const a = { buf: acc.address.toBuffer() } as any;
(stateManager as any)._cache.put(a, acc);
stateManager.touchAccount(a);
});
await stateManager.commit();
// create the genesis block
let baseFeePerGas: bigint;
if (this.common.isActivatedEIP(1559)) {
if (fallbackBlock.header.baseFeePerGas === undefined) {
baseFeePerGas = Block.INITIAL_BASE_FEE_PER_GAS;
} else {
baseFeePerGas = fallbackBlock.header.baseFeePerGas.toBigInt();
}
}
const genesis = new RuntimeBlock(
Quantity.from(fallbackBlock.header.number.toBigInt() + 1n),
fallbackBlock.hash(),
this.coinbase,
blockGasLimit.toBuffer(),
BUFFER_ZERO,
Quantity.from(timestamp),
minerOptions.difficulty,
fallbackBlock.header.totalDifficulty,
baseFeePerGas
);
// store the genesis block in the database
const { block, serialized } = genesis.finalize(
KECCAK256_RLP,
KECCAK256_RLP,
BUFFER_256_ZERO,
this.trie.root,
0n,
minerOptions.extraData,
[],
new Map()
);
const hash = block.hash();
return this.blocks
.putBlock(block.header.number.toBuffer(), hash, serialized)
.then(_ => ({
block,
blockLogs: BlockLogs.create(hash)
}));
}
await this.#commitAccounts(initialAccounts);
// README: block `0` is weird in that a `0` _should_ be hashed as `[]`,
// instead of `[0]`, so we set it to `RPCQUANTITY_EMPTY` instead of
// `RPCQUANTITY_ZERO` here. A few lines down in this function we swap
// this `RPCQUANTITY_EMPTY` for `RPCQUANTITY_ZERO`. This is all so we don't
// have to have a "treat empty as 0` check in every function that uses the
// "latest" block (which this genesis block will be for brief moment).
const rawBlockNumber = RPCQUANTITY_EMPTY;
// create the genesis block
const baseFeePerGas = this.common.isActivatedEIP(1559)
? Block.INITIAL_BASE_FEE_PER_GAS
: undefined;
const genesis = new RuntimeBlock(
rawBlockNumber,
Data.from(BUFFER_32_ZERO),
this.coinbase,
blockGasLimit.toBuffer(),
BUFFER_ZERO,
Quantity.from(timestamp),
this.#options.miner.difficulty,
RPCQUANTITY_ZERO, // we start the totalDifficulty at 0
baseFeePerGas
);
// store the genesis block in the database
const { block, serialized } = genesis.finalize(
KECCAK256_RLP,
KECCAK256_RLP,
BUFFER_256_ZERO,
this.trie.root,
0n,
this.#options.miner.extraData,
[],
new Map()
);
// README: set the block number to an actual 0 now.
block.header.number = RPCQUANTITY_ZERO;
const hash = block.hash();
return this.blocks
.putBlock(block.header.number.toBuffer(), hash, serialized)
.then(_ => ({
block,
blockLogs: BlockLogs.create(hash)
}));
};
#timeAdjustment: number = 0;
/**
* Returns the timestamp, adjusted by the timeAdjustment offset, in seconds.
*/
#currentTime = () => {
return Math.floor((Date.now() + this.#timeAdjustment) / 1000);
};
/**
* @param seconds
* @returns the total time offset *in milliseconds*
*/
public increaseTime(seconds: number) {
if (seconds < 0) {
seconds = 0;
}
return (this.#timeAdjustment += seconds);
}
/**
* @param seconds
* @returns the total time offset *in milliseconds*
*/
public setTime(timestamp: number) {
return (this.#timeAdjustment = timestamp - Date.now());
}
#deleteBlockData = async (blocksToDelete: Block[]) => {
// if we are forking we need to make sure we clean up the forking related
// metadata that isn't stored in the trie
if ("revertMetaData" in this.trie) {
await (this.trie as ForkTrie).revertMetaData(
blocksToDelete[blocksToDelete.length - 1].header.number,
blocksToDelete[0].header.number
);
}
await this.#database.batch(() => {
const { blocks, transactions, transactionReceipts, blockLogs } = this;
blocksToDelete.forEach(block => {
block.getTransactions().forEach(tx => {
const txHash = tx.hash.toBuffer();
transactions.del(txHash);
transactionReceipts.del(txHash);
});
const blockNum = block.header.number.toBuffer();
blocks.del(blockNum);
blocks.del(block.hash().toBuffer());
blockLogs.del(blockNum);
});
});
};
// TODO(stability): this.#snapshots is a potential unbound memory suck. Caller
// could call `evm_snapshot` over and over to grow the snapshot stack
// indefinitely. `this.#snapshots.blocks` is even worse. To solve this we
// might need to store in the db. An unlikely real problem, but possible.
#snapshots: Snapshots = {
snaps: [],
blocks: null,
unsubscribeFromBlocks: null
};
public snapshot() {
const snapshots = this.#snapshots;
const snaps = snapshots.snaps;
// Subscription ids are based on the number of active snapshots. Weird? Yes.
// But it's the way it's been since the beginning so it just hasn't been
// changed. Feel free to change it so ids are unique if it bothers you
// enough.
const id = snaps.push({
block: this.blocks.latest,
timeAdjustment: this.#timeAdjustment
});
// start listening to new blocks if this is the first snapshot
if (id === 1) {
snapshots.unsubscribeFromBlocks = this.on("block", block => {
snapshots.blocks = {
current: block.hash().toBuffer(),
next: snapshots.blocks
};
});
}
this.#options.logging.logger.log("Saved snapshot #" + id);
return id;
}
public async revert(snapshotId: Quantity) {
const rawValue = snapshotId.valueOf();
if (rawValue === null || rawValue === undefined) {
throw new Error("invalid snapshotId");
}
this.#options.logging.logger.log("Reverting to snapshot #" + snapshotId);
// snapshot ids can't be < 1, so we do a quick sanity check here
if (rawValue < 1n) {
return false;
}
const snapshots = this.#snapshots;
const snaps = snapshots.snaps;
const snapshotIndex = Number(rawValue - 1n);
const snapshot = snaps[snapshotIndex];
if (!snapshot) {
return false;
}
// pause processing new transactions...
await this.transactions.pause();
// then pause the miner, too.
await this.#miner.pause();
// wait for anything in the process of being saved to finish up
await this.#blockBeingSavedPromise;
// Pending transactions are always removed when you revert, even if they
// were present before the snapshot was created. Ideally, we'd remove only
// the new transactions.. but we'll leave that for another day.
this.transactions.clear();
const blocks = this.blocks;
const currentHash = blocks.latest.hash().toBuffer();
const snapshotBlock = snapshot.block;
const snapshotHeader = snapshotBlock.header;
const snapshotHash = snapshotBlock.hash().toBuffer();
// remove this and all stored snapshots after this snapshot
snaps.splice(snapshotIndex);
// if there are no more listeners, stop listening to new blocks
if (snaps.length === 0) {
snapshots.unsubscribeFromBlocks();
}
// if the snapshot's hash is different than the latest block's hash we've
// got new blocks to clean up.
if (!currentHash.equals(snapshotHash)) {
// if we've added blocks since we snapshotted we need to delete them and put
// some things back the way they were.
const blockPromises: Promise<Block>[] = [];
let blockList = snapshots.blocks;
while (blockList !== null) {
if (blockList.current.equals(snapshotHash)) break;
blockPromises.push(blocks.getByHash(blockList.current));
blockList = blockList.next;
}
snapshots.blocks = blockList;
const blockData = await Promise.all(blockPromises);
await this.#deleteBlockData(blockData);
setStateRootSync(
this.vm.stateManager,
snapshotHeader.stateRoot.toBuffer()
);
blocks.latest = snapshotBlock;
}
// put our time adjustment back
this.#timeAdjustment = snapshot.timeAdjustment;
// resume mining
this.#miner.resume();
// resume processing transactions
this.transactions.resume();
return true;
}
public async queueTransaction(
transaction: TypedTransaction,
secretKey?: Data
) {
// NOTE: this.transactions.add *must* be awaited before returning the
// `transaction.hash()`, as the transactionPool may change the transaction
// (and thus its hash!)
// It may also throw Errors that must be returned to the caller.
const isExecutable =
(await this.transactions.add(transaction, secretKey)) === true;
if (isExecutable) {
process.nextTick(this.emit.bind(this), "pendingTransaction", transaction);
}
const hash = transaction.hash;
if (this.#isPaused() || !this.#instamine) {
return hash;
} else {
if (this.#instamine && this.#options.miner.legacyInstamine) {
// in legacyInstamine mode we must wait for the transaction to be saved
// before we can return the hash
const { status, error } = await transaction.once("finalized");
// in legacyInstamine mode we must throw on all rejected transaction
// errors. We must also throw on `confirmed` transactions when
// vmErrorsOnRPCResponse is enabled.
if (
error &&
(status === "rejected" || this.#options.chain.vmErrorsOnRPCResponse)
)
throw error;
}
return hash;
}
}
public async simulateTransaction(
transaction: SimulationTransaction,
parentBlock: Block
) {
let result: EVMResult;