/
ForkBlockchain.ts
370 lines (327 loc) · 11.5 KB
/
ForkBlockchain.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
import { Block } from "@nomicfoundation/ethereumjs-block";
import { Common } from "@nomicfoundation/ethereumjs-common";
import { TypedTransaction } from "@nomicfoundation/ethereumjs-tx";
import { Address } from "@nomicfoundation/ethereumjs-util";
import { FeeMarketEIP1559TxData } from "@nomicfoundation/ethereumjs-tx/dist/types";
import { RpcBlockWithTransactions } from "../../../core/jsonrpc/types/output/block";
import { RpcTransactionReceipt } from "../../../core/jsonrpc/types/output/receipt";
import { RpcTransaction } from "../../../core/jsonrpc/types/output/transaction";
import { InternalError } from "../../../core/providers/errors";
import { JsonRpcClient } from "../../jsonrpc/client";
import { BlockchainBase } from "../BlockchainBase";
import { FilterParams } from "../node-types";
import {
remoteReceiptToRpcReceiptOutput,
RpcLogOutput,
RpcReceiptOutput,
shouldShowEffectiveGasPriceForHardfork,
shouldShowTransactionTypeForHardfork,
toRpcLogOutput,
} from "../output";
import { ReadOnlyValidEIP2930Transaction } from "../transactions/ReadOnlyValidEIP2930Transaction";
import { ReadOnlyValidTransaction } from "../transactions/ReadOnlyValidTransaction";
import { HardhatBlockchainInterface } from "../types/HardhatBlockchainInterface";
import { ReadOnlyValidEIP1559Transaction } from "../transactions/ReadOnlyValidEIP1559Transaction";
import { ReadOnlyValidUnknownTypeTransaction } from "../transactions/ReadOnlyValidUnknownTypeTransaction";
import { rpcToBlockData } from "./rpcToBlockData";
import { rpcToTxData } from "./rpcToTxData";
/* eslint-disable @nomiclabs/hardhat-internal-rules/only-hardhat-error */
export class ForkBlockchain
extends BlockchainBase
implements HardhatBlockchainInterface
{
private _latestBlockNumber = this._forkBlockNumber;
constructor(
private _jsonRpcClient: JsonRpcClient,
private _forkBlockNumber: bigint,
common: Common
) {
super(common);
}
public getLatestBlockNumber(): bigint {
return this._latestBlockNumber;
}
public async getBlock(
blockHashOrNumber: Buffer | bigint
): Promise<Block | null> {
if (
typeof blockHashOrNumber === "bigint" &&
this._data.isReservedBlock(blockHashOrNumber)
) {
this._data.fulfillBlockReservation(blockHashOrNumber);
}
let block: Block | undefined | null;
if (Buffer.isBuffer(blockHashOrNumber)) {
block = await this._getBlockByHash(blockHashOrNumber);
return block ?? null;
}
block = await this._getBlockByNumber(BigInt(blockHashOrNumber));
return block ?? null;
}
public async addBlock(block: Block): Promise<Block> {
const blockNumber = BigInt(block.header.number);
if (blockNumber !== this._latestBlockNumber + 1n) {
throw new Error(
`Invalid block number ${blockNumber}. Expected ${
this._latestBlockNumber + 1n
}`
);
}
// When forking a network whose consensus is not the classic PoW,
// we can't calculate the hash correctly.
// Thus, we avoid this check for the first block after the fork.
if (blockNumber > this._forkBlockNumber + 1n) {
const parent = await this.getLatestBlock();
if (!block.header.parentHash.equals(parent.hash())) {
throw new Error("Invalid parent hash");
}
}
this._latestBlockNumber++;
const totalDifficulty = await this._computeTotalDifficulty(block);
this._data.addBlock(block, totalDifficulty);
return block;
}
public reserveBlocks(
count: bigint,
interval: bigint,
previousBlockStateRoot: Buffer,
previousBlockTotalDifficulty: bigint,
previousBlockBaseFeePerGas: bigint | undefined
) {
super.reserveBlocks(
count,
interval,
previousBlockStateRoot,
previousBlockTotalDifficulty,
previousBlockBaseFeePerGas
);
this._latestBlockNumber += count;
}
public deleteLaterBlocks(block: Block): void {
const blockNumber = block.header.number;
const savedBlock = this._data.getBlockByNumber(blockNumber);
if (savedBlock === undefined || !savedBlock.hash().equals(block.hash())) {
throw new Error("Invalid block");
}
const nextBlockNumber = blockNumber + 1n;
if (this._forkBlockNumber >= nextBlockNumber) {
throw new Error("Cannot delete remote block");
}
this._delBlock(nextBlockNumber);
}
public async getTotalDifficulty(blockHash: Buffer): Promise<bigint> {
let td = this._data.getTotalDifficulty(blockHash);
if (td !== undefined) {
return td;
}
const block = await this.getBlock(blockHash);
if (block === null) {
throw new Error("Block not found");
}
td = this._data.getTotalDifficulty(blockHash);
if (td === undefined) {
throw new Error("This should never happen");
}
return td;
}
public async getTransaction(
transactionHash: Buffer
): Promise<TypedTransaction | undefined> {
const tx = this.getLocalTransaction(transactionHash);
if (tx === undefined) {
const remote = await this._jsonRpcClient.getTransactionByHash(
transactionHash
);
return this._processRemoteTransaction(remote);
}
return tx;
}
public async getBlockByTransactionHash(
transactionHash: Buffer
): Promise<Block | null> {
let block = this._data.getBlockByTransactionHash(transactionHash);
if (block === undefined) {
const remote = await this._jsonRpcClient.getTransactionByHash(
transactionHash
);
this._processRemoteTransaction(remote);
if (remote !== null && remote.blockHash !== null) {
await this.getBlock(remote.blockHash);
block = this._data.getBlockByTransactionHash(transactionHash);
}
}
return block ?? null;
}
public async getTransactionReceipt(
transactionHash: Buffer
): Promise<RpcReceiptOutput | null> {
const local = this._data.getTransactionReceipt(transactionHash);
if (local !== undefined) {
return local;
}
const remote = await this._jsonRpcClient.getTransactionReceipt(
transactionHash
);
if (remote !== null) {
const receipt = await this._processRemoteReceipt(remote);
return receipt ?? null;
}
return null;
}
public getForkBlockNumber() {
return this._forkBlockNumber;
}
public async getLogs(filterParams: FilterParams): Promise<RpcLogOutput[]> {
if (filterParams.fromBlock <= this._forkBlockNumber) {
let toBlock = filterParams.toBlock;
let localLogs: RpcLogOutput[] = [];
if (toBlock > this._forkBlockNumber) {
toBlock = this._forkBlockNumber;
localLogs = this._data.getLogs({
...filterParams,
fromBlock: this._forkBlockNumber + 1n,
});
}
const remoteLogs = await this._jsonRpcClient.getLogs({
fromBlock: filterParams.fromBlock,
toBlock,
address:
filterParams.addresses.length === 1
? filterParams.addresses[0]
: filterParams.addresses,
topics: filterParams.normalizedTopics,
});
return remoteLogs.map(toRpcLogOutput).concat(localLogs);
}
return this._data.getLogs(filterParams);
}
private async _getBlockByHash(blockHash: Buffer) {
const block = this._data.getBlockByHash(blockHash);
if (block !== undefined) {
return block;
}
const rpcBlock = await this._jsonRpcClient.getBlockByHash(blockHash, true);
return this._processRemoteBlock(rpcBlock);
}
private async _getBlockByNumber(blockNumber: bigint) {
if (blockNumber > this._latestBlockNumber) {
return undefined;
}
const block = await super.getBlock(blockNumber);
if (block !== null) {
return block;
}
const rpcBlock = await this._jsonRpcClient.getBlockByNumber(
blockNumber,
true
);
return this._processRemoteBlock(rpcBlock);
}
private async _processRemoteBlock(rpcBlock: RpcBlockWithTransactions | null) {
if (
rpcBlock === null ||
rpcBlock.hash === null ||
rpcBlock.number === null ||
rpcBlock.number > this._forkBlockNumber
) {
return undefined;
}
const common = this._common.copy();
// We set the common's hardfork to Berlin if the remote block doesn't have
// EIP-1559 activated. The reason for this is that ethereumjs throws if we
// have a base fee for an older hardfork, and set a default one for London.
if (rpcBlock.baseFeePerGas !== undefined) {
common.setHardfork("london"); // TODO: consider changing this to "latest hardfork"
} else {
common.setHardfork("berlin");
}
// we don't include the transactions to add our own custom tx objects,
// otherwise they are recreated with upstream classes
const blockData = rpcToBlockData({
...rpcBlock,
transactions: [],
});
const block = Block.fromBlockData(blockData, {
common,
// We use freeze false here because we add the transactions manually
freeze: false,
// don't validate things like the size of `extraData` in the header
skipConsensusFormatValidation: true,
});
for (const transaction of rpcBlock.transactions) {
let tx;
if (transaction.type === undefined || transaction.type === 0n) {
tx = new ReadOnlyValidTransaction(
new Address(transaction.from),
rpcToTxData(transaction)
);
} else if (transaction.type === 1n) {
tx = new ReadOnlyValidEIP2930Transaction(
new Address(transaction.from),
rpcToTxData(transaction)
);
} else if (transaction.type === 2n) {
tx = new ReadOnlyValidEIP1559Transaction(
new Address(transaction.from),
rpcToTxData(transaction) as FeeMarketEIP1559TxData
);
} else {
// we try to interpret unknown txs as legacy transactions, to support
// networks like Arbitrum that have non-standards tx types
try {
tx = new ReadOnlyValidUnknownTypeTransaction(
new Address(transaction.from),
Number(transaction.type),
rpcToTxData(transaction)
);
} catch (e: any) {
throw new InternalError(
`Could not process transaction with type ${transaction.type.toString()}`,
e
);
}
}
block.transactions.push(tx);
}
this._data.addBlock(block, rpcBlock.totalDifficulty);
return block;
}
protected _delBlock(blockNumber: bigint): void {
if (blockNumber <= this._forkBlockNumber) {
throw new Error("Cannot delete remote block");
}
super._delBlock(blockNumber);
this._latestBlockNumber = blockNumber - 1n;
}
private _processRemoteTransaction(rpcTransaction: RpcTransaction | null) {
if (
rpcTransaction === null ||
rpcTransaction.blockNumber === null ||
rpcTransaction.blockNumber > this._forkBlockNumber
) {
return undefined;
}
const transaction = new ReadOnlyValidTransaction(
new Address(rpcTransaction.from),
rpcToTxData(rpcTransaction)
);
this._data.addTransaction(transaction);
return transaction;
}
private async _processRemoteReceipt(
txReceipt: RpcTransactionReceipt | null
): Promise<RpcReceiptOutput | undefined> {
if (txReceipt === null || txReceipt.blockNumber > this._forkBlockNumber) {
return undefined;
}
const tx = await this.getTransaction(txReceipt.transactionHash);
const receipt = remoteReceiptToRpcReceiptOutput(
txReceipt,
tx!,
shouldShowTransactionTypeForHardfork(this._common),
shouldShowEffectiveGasPriceForHardfork(this._common)
);
this._data.addTransactionReceipt(receipt);
return receipt;
}
}