Skip to content
Open
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
9 changes: 2 additions & 7 deletions packages/api-sync/source/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ type Ctx = {
entityManager: any;
repos: Record<string, any>;
systemRepo: any;
evm: any;
state: any;
validatorSet: any;
proposerCalculator: any;
Expand Down Expand Up @@ -160,7 +159,6 @@ describe<Ctx>("Sync", ({ it, beforeEach, assert, stub, spy, clock }) => {

context.migrations = { runMigrations: async () => {}, synchronizeEntities: async () => {} };
context.systemRepo = { inMaintenance: async () => false };
context.evm = { getAccountInfo: async () => ({ balance: 1000n, nonce: 3n }) };
context.state = { isBootstrap: () => false };
context.validatorSet = { getDirtyValidators: () => [], getRoundValidators: () => [] };
context.proposerCalculator = { getValidatorIndex: (index: number) => index };
Expand Down Expand Up @@ -225,7 +223,6 @@ describe<Ctx>("Sync", ({ it, beforeEach, assert, stub, spy, clock }) => {
context.app
.bind(ApiDatabaseIdentifiers.LegacyColdWalletRepositoryFactory)
.toConstantValue(() => context.repos.legacyColdWallet);
context.app.bind(Identifiers.Evm.Instance).toConstantValue(context.evm).whenTagged("instance", "evm");
context.app.bind(Identifiers.EvmConsensus.Contracts.MultiPayment).toConstantValue("0xmultipayment");
context.app.bind(Identifiers.State.State).toConstantValue(context.state);
context.app.bind(Identifiers.ValidatorSet.Service).toConstantValue(context.validatorSet);
Expand Down Expand Up @@ -451,15 +448,13 @@ describe<Ctx>("Sync", ({ it, beforeEach, assert, stub, spy, clock }) => {
assert.equal(transactionBatch[0].nonce, "1");
assert.undefined(transactionBatch[0].decodedError);

// The genesis proposer account is force-created on the first non-genesis block,
// and the block proposer (not part of any account update) is manually inserted.
// The block proposer (not part of any account update) is manually inserted.
assert.equal(repos.wallet.queries.length, 1);
const [sql, parameters] = repos.wallet.queries[0];
assert.true(sql.includes("INSERT INTO wallets"));
// genesis proposer row + no separate proposer row (same address)
assert.equal(parameters.length, 6);
assert.equal(parameters[0], PROPOSER);
assert.equal(parameters[2], "1000"); // balance from evm.getAccountInfo
assert.equal(parameters[2], "-1");

// Configuration version update without new milestones
assert.equal(repos.configuration.qb.calls.set[0][0].version, "0.0.1-test");
Expand Down
20 changes: 0 additions & 20 deletions packages/api-sync/source/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,6 @@ export class Sync implements Contracts.ApiSync.Service {
@inject(ApiDatabaseIdentifiers.LegacyColdWalletRepositoryFactory)
private readonly legacyColdWalletRepositoryFactory!: ApiDatabaseContracts.LegacyColdWalletRepositoryFactory;

@inject(Identifiers.Evm.Instance)
@tagged("instance", "evm")
private readonly evm!: Contracts.Evm.Instance;

@inject(Identifiers.EvmConsensus.Contracts.MultiPayment)
private readonly multiPaymentContractAddress!: string;

Expand Down Expand Up @@ -259,22 +255,6 @@ export class Sync implements Contracts.ApiSync.Service {
return accumulator;
}, {});

// Add accountUpdate for genesisAccount on the very first non-genesis block to ensure
// the wallet is created in postgres.
const genesisBlock = this.app.config<Contracts.Crypto.CommitJson>("crypto.genesisBlock");
assert.defined(genesisBlock);

if (unit.blockNumber - 1 === genesisBlock.block.number && !accountUpdates[genesisBlock.block.proposer]) {
const genesisAccount = await this.evm.getAccountInfo(genesisBlock.block.proposer);

accountUpdates[genesisBlock.block.proposer] = {
address: genesisBlock.block.proposer,
balance: genesisAccount.balance,
nonce: genesisAccount.nonce,
usernameResigned: false,
};
}

const validatorAttributes = (address: string) => {
const dirtyValidator = dirtyValidators[address];
const isBlockValidator = header.proposer === address;
Expand Down
88 changes: 88 additions & 0 deletions packages/evm-service/source/instances/evm-genesis.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,4 +233,92 @@ describe<{
await instance.dispose();
}
});

it("initializeGenesis after the genesis commit keeps state roots in sync", async () => {
const genesisInfo: Contracts.Evm.GenesisInfo = {
account: "0x1111111111111111111111111111111111111111",
deployerAccount: "0x0000000000000000000000000000000000000001",
initialBlockNumber: 0n,
initialSupply: 0n,
usernameContract: "0x0000000000000000000000000000000000000001",
validatorContract: "0x0000000000000000000000000000000000000001",
};

const hasGenesisAccount = async (instance: Contracts.Evm.Instance & Contracts.Evm.Storage) => {
const { accounts } = await instance.getAccounts(0n, 1000n);
return accounts.some(({ address }) => address.toLowerCase() === genesisInfo.account.toLowerCase());
};

const commitGenesisBlock = async (instance: Contracts.Evm.Instance & Contracts.Evm.Storage) => {
const commitKey = { blockNumber: 0n, round: 0n };

await instance.initializeGenesis(genesisInfo);
assert.true(await hasGenesisAccount(instance));

await instance.prepareNextCommit({
blockContext: { ...blockContext, commitKey, validatorAddress: genesisInfo.account },
});
await instance.updateRewardsAndVotes({
blockReward: 0n,
commitKey,
specId: Enums.Evm.SpecId.OSAKA,
timestamp: 12_345n,
validatorAddress: genesisInfo.account,
});
await instance.onCommit({
blockNumber: 0n,
getBlock: () => ({ number: 0n, round: 0n }),
round: 0n,
setAccountUpdates: () => {},
setContractEvents: () => {},
} as any);
};

const touchGenesisAccount = async (instance: Contracts.Evm.Instance) => {
const commitKey = { blockNumber: 1n, round: 0n };

await instance.prepareNextCommit({ blockContext: { ...blockContext, commitKey } });
const { receipt } = await instance.process({
commitKey,
data: Buffer.alloc(0),
from: genesisInfo.deployerAccount,
gasLimit: 21_000n,
gasPrice: 0n,
nonce: (await instance.getAccountInfo(genesisInfo.deployerAccount)).nonce,
specId: Enums.Evm.SpecId.OSAKA,
to: genesisInfo.account,
txHash: "11".repeat(32),
value: 0n,
});
assert.equal(receipt.status, 1);

return instance.stateRoot(commitKey, zeroHash.slice(2));
};

const instances: (Contracts.Evm.Instance & Contracts.Evm.Storage)[] = [];

try {
for (let index = 0; index < 2; index++) {
const context = {} as { app: Application };
await prepareSandbox(context);
instances.push(context.app.resolve<Contracts.Evm.Instance & Contracts.Evm.Storage>(EvmInstance));
}

const [running, restarted] = instances;

for (const instance of instances) {
await commitGenesisBlock(instance);
assert.false(await hasGenesisAccount(instance));
}

await restarted.initializeGenesis(genesisInfo);

assert.false(await hasGenesisAccount(restarted));
assert.equal(await touchGenesisAccount(restarted), await touchGenesisAccount(running));
} finally {
for (const instance of instances) {
await instance.dispose();
}
}
});
});
85 changes: 85 additions & 0 deletions packages/evm/core/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,10 @@ impl PersistentDB {
self.with_write_txn(|wtxn| {
let inner = &self.inner;

if self.is_block_committed(wtxn, genesis_info.initial_block_number)? {
return Ok(());
}

if inner
.accounts
.get(wtxn, &AddressWrapper(genesis_info.account))?
Expand Down Expand Up @@ -2442,6 +2446,87 @@ mod tests {

assert_eq!(db.genesis_info, Some(Default::default()));
}

#[test]
fn test_set_genesis_info_seeds_account_until_genesis_commit() {
let mut db = create_temp_database();

let genesis_info = crate::db::GenesisInfo {
account: address!("0000000000000000000000000000000000000001"),
initial_block_number: 1000,
..Default::default()
};

assert_eq!(db.basic(genesis_info.account).unwrap(), None);

db.set_genesis_info(genesis_info.clone()).expect("ok");

assert_eq!(
db.basic(genesis_info.account).unwrap(),
Some(AccountInfo::default())
);

// The genesis block deletes the empty genesis account.
let mut state_commit = StateCommit {
key: CommitKey(genesis_info.initial_block_number, 0, B256::ZERO),
change_set: StateChangeset {
accounts: vec![(genesis_info.account, None)],
..Default::default()
},
results: Default::default(),
};
db.commit(&mut state_commit, &None).unwrap();

assert_eq!(db.basic(genesis_info.account).unwrap(), None);

// A restart or proposal initializes the genesis info again.
db.set_genesis_info(genesis_info.clone()).expect("ok");

assert_eq!(db.basic(genesis_info.account).unwrap(), None);
assert_eq!(db.genesis_info, Some(genesis_info));
}

#[test]
fn test_set_genesis_info_on_new_instance_after_genesis_commit() {
let path = tempfile::Builder::new()
.prefix("evm.mdb")
.tempdir()
.unwrap();

let genesis_info = crate::db::GenesisInfo {
account: address!("0000000000000000000000000000000000000001"),
initial_block_number: 1000,
..Default::default()
};

let mut db =
PersistentDB::new(PersistentDBOptions::new(path.path().to_path_buf())).expect("db");
db.set_genesis_info(genesis_info.clone()).expect("ok");

let mut state_commit = StateCommit {
key: CommitKey(genesis_info.initial_block_number, 0, B256::ZERO),
change_set: StateChangeset {
accounts: vec![(genesis_info.account, None)],
..Default::default()
},
results: Default::default(),
};
db.commit(&mut state_commit, &None).unwrap();
drop(db);

// Each boot and each proposal opens a new instance without genesis info.
let mut db =
PersistentDB::new(PersistentDBOptions::new(path.path().to_path_buf())).expect("db");

assert_eq!(db.genesis_info, None);
assert_eq!(db.basic(genesis_info.account).unwrap(), None);

db.set_genesis_info(genesis_info.clone()).expect("ok");

assert_eq!(db.basic(genesis_info.account).unwrap(), None);
assert_eq!(db.genesis_info, Some(genesis_info));
}

#[test]
fn test_get_commits_by_block_range() {
let db = create_temp_database();
Expand Down
Loading