Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix how the state of the fork block is handled #1016

Merged
merged 2 commits into from
Nov 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import { Map as ImmutableMap, Record as ImmutableRecord } from "immutable";
import { callbackify } from "util";

import { JsonRpcClient } from "../../jsonrpc/client";
import { GenesisAccount } from "../node-types";
import { PStateManager } from "../types/PStateManager";
import { StateManager } from "../types/StateManager";
import { makeAccount } from "../utils/makeAccount";

import { AccountState, makeAccountState } from "./Account";
import { randomHash } from "./random";
Expand All @@ -36,7 +38,8 @@ const notSupportedError = (method: string) =>

export class ForkStateManager implements PStateManager {
private _state: State = ImmutableMap();
private _stateRoot: string = randomHash();
private _initialStateRoot: string = randomHash();
private _stateRoot: string = this._initialStateRoot;
private _stateRootToState: Map<string, State> = new Map();
private _originalStorageCache: Map<string, Buffer> = new Map();
private _stateCheckpoints: string[] = [];
Expand All @@ -45,9 +48,17 @@ export class ForkStateManager implements PStateManager {

constructor(
private readonly _jsonRpcClient: JsonRpcClient,
private readonly _forkBlockNumber: BN
private readonly _forkBlockNumber: BN,
genesisAccounts: GenesisAccount[] = []
) {
this._state = ImmutableMap();

for (const ga of genesisAccounts) {
const { address, account } = makeAccount(ga);
this._putAccount(address, account);
}

this._stateRootToState.set(this._initialStateRoot, this._state);
}

public copy(): ForkStateManager {
Expand Down Expand Up @@ -104,20 +115,7 @@ export class ForkStateManager implements PStateManager {
}

public async putAccount(address: Buffer, account: Account): Promise<void> {
// Because the vm only ever modifies the nonce, balance and codeHash using this
// method we ignore the stateRoot property
const hexAddress = bufferToHex(address);
let localAccount = this._state.get(hexAddress) ?? makeAccountState();
localAccount = localAccount
.set("nonce", bufferToHex(account.nonce))
.set("balance", bufferToHex(account.balance));

// Code is set to empty string here to prevent unnecessary
// JsonRpcClient.getCode calls in getAccount method
if (account.codeHash.equals(KECCAK256_NULL)) {
localAccount = localAccount.set("code", "0x");
}
this._state = this._state.set(hexAddress, localAccount);
this._putAccount(address, account);
}

public touchAccount(address: Buffer): void {
Expand Down Expand Up @@ -319,6 +317,10 @@ export class ForkStateManager implements PStateManager {
if (this._stateCheckpoints.length !== 0) {
throw checkpointedError("setBlockContext");
}
if (blockNumber.eq(this._forkBlockNumber)) {
this._setStateRoot(toBuffer(this._initialStateRoot));
return;
}
Comment on lines +320 to +323

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +320 to +323

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of adding this if statement, we could make the this._initialStateRoot equal to the actual stateRoot of the fork block. However this would require fetching the block before FSM construction and would slow down the HardhatNode creation. Having considered this I would leave this the way it is.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did exactly the same reasoning, I'm glad that you agree 😅

if (blockNumber.gt(this._forkBlockNumber)) {
this._setStateRoot(stateRoot);
return;
Expand All @@ -343,6 +345,23 @@ export class ForkStateManager implements PStateManager {
}
}

private _putAccount(address: Buffer, account: Account): void {
// Because the vm only ever modifies the nonce, balance and codeHash using this
// method we ignore the stateRoot property
const hexAddress = bufferToHex(address);
let localAccount = this._state.get(hexAddress) ?? makeAccountState();
localAccount = localAccount
.set("nonce", bufferToHex(account.nonce))
.set("balance", bufferToHex(account.balance));

// Code is set to empty string here to prevent unnecessary
// JsonRpcClient.getCode calls in getAccount method
if (account.codeHash.equals(KECCAK256_NULL)) {
localAccount = localAccount.set("code", "0x");
}
this._state = this._state.set(hexAddress, localAccount);
}

private _setStateRoot(stateRoot: Buffer) {
const newRoot = bufferToHex(stateRoot);
const state = this._stateRootToState.get(newRoot);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
ecsign,
hashPersonalMessage,
privateToAddress,
stripZeros,
toBuffer,
} from "ethereumjs-util";
import EventEmitter from "events";
Expand Down Expand Up @@ -71,7 +70,6 @@ import { makeCommon } from "./utils/makeCommon";
import { makeForkClient } from "./utils/makeForkClient";
import { makeForkCommon } from "./utils/makeForkCommon";
import { makeStateTrie } from "./utils/makeStateTrie";
import { putGenesisAccounts } from "./utils/putGenesisAccounts";
import { putGenesisBlock } from "./utils/putGenesisBlock";

const log = debug("hardhat:core:hardhat-network:node");
Expand Down Expand Up @@ -109,8 +107,11 @@ export class HardhatNode extends EventEmitter {
);
common = await makeForkCommon(forkClient, forkBlockNumber);

stateManager = new ForkStateManager(forkClient, forkBlockNumber);
await putGenesisAccounts(stateManager, genesisAccounts);
stateManager = new ForkStateManager(
forkClient,
forkBlockNumber,
genesisAccounts
);

blockchain = new ForkBlockchain(forkClient, forkBlockNumber, common);
} else {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ export async function deployContract(
}

export async function sendTxToZeroAddress(
provider: EthereumProvider
provider: EthereumProvider,
from?: string
): Promise<string> {
const accounts = await provider.send("eth_accounts");

const burnTxParams = {
from: accounts[0],
from: from ?? accounts[0],
to: zeroAddress(),
value: numberToRpcQuantity(1),
gas: numberToRpcQuantity(21000),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,25 @@ describe("Eth module", function () {
`Received invalid block number ${futureBlock}. Latest block number is ${firstBlock}`
);
});

it("Should return the initial balance for the genesis accounts in the previous block after a transaction", async function () {
const blockNumber = await this.provider.send("eth_blockNumber");
const account = DEFAULT_ACCOUNTS_ADDRESSES[0];

const initialBalanceBeforeTx = await this.provider.send(
"eth_getBalance",
[account, blockNumber]
);
assert.equal(initialBalanceBeforeTx, "0xde0b6b3a7640000");

await sendTxToZeroAddress(this.provider, account);

const initialBalanceAfterTx = await this.provider.send(
"eth_getBalance",
[account, blockNumber]
);
assert.equal(initialBalanceAfterTx, "0xde0b6b3a7640000");
});
});

describe("eth_getBlockByHash", async function () {
Expand Down