Skip to content

Commit

Permalink
chore: replace TrieAccount with alloy's
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Dec 14, 2024
1 parent 16f6d7a commit 7650628
Show file tree
Hide file tree
Showing 17 changed files with 93 additions and 173 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 7 additions & 10 deletions crates/blockchain-tree/src/blockchain_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1399,7 +1399,6 @@ mod tests {
},
ProviderFactory, StorageLocation,
};
use reth_revm::primitives::AccountInfo;
use reth_stages_api::StageCheckpoint;
use reth_trie::{root::state_root_unhashed, StateRoot};
use std::collections::HashMap;
Expand Down Expand Up @@ -1624,15 +1623,13 @@ mod tests {
receipts_root,
state_root: state_root_unhashed(HashMap::from([(
signer,
(
AccountInfo {
balance: initial_signer_balance -
(single_tx_cost * U256::from(num_of_signer_txs)),
nonce: num_of_signer_txs,
..Default::default()
},
EMPTY_ROOT_HASH,
),
Account {
balance: initial_signer_balance -
(single_tx_cost * U256::from(num_of_signer_txs)),
nonce: num_of_signer_txs,
..Default::default()
}
.into_trie_account(EMPTY_ROOT_HASH),
)])),
..Default::default()
};
Expand Down
15 changes: 7 additions & 8 deletions crates/chain-state/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use reth_primitives::{
BlockBody, EthPrimitives, NodePrimitives, Receipt, Receipts, RecoveredTx, SealedBlock,
SealedBlockWithSenders, SealedHeader, Transaction, TransactionSigned,
};
use reth_primitives_traits::Account;
use reth_storage_api::NodePrimitivesProvider;
use reth_trie::{root::state_root_unhashed, updates::TrieUpdates, HashedPostState};
use revm::{db::BundleState, primitives::AccountInfo};
Expand Down Expand Up @@ -150,14 +151,12 @@ impl TestBlockBuilder {
beneficiary: Address::random(),
state_root: state_root_unhashed(HashMap::from([(
self.signer,
(
AccountInfo {
balance: initial_signer_balance - signer_balance_decrease,
nonce: num_txs,
..Default::default()
},
EMPTY_ROOT_HASH,
),
Account {
balance: initial_signer_balance - signer_balance_decrease,
nonce: num_txs,
..Default::default()
}
.into_trie_account(EMPTY_ROOT_HASH),
)])),
// use the number as the timestamp so it is monotonically increasing
timestamp: number +
Expand Down
10 changes: 7 additions & 3 deletions crates/primitives-traits/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ alloy-eips.workspace = true
alloy-genesis.workspace = true
alloy-primitives.workspace = true
alloy-rlp.workspace = true
alloy-trie.workspace = true
revm-primitives.workspace = true

# op
Expand Down Expand Up @@ -80,7 +81,8 @@ std = [
"bytes/std",
"derive_more/std",
"k256/std",
"secp256k1?/std"
"secp256k1?/std",
"alloy-trie/std"
]
secp256k1 = ["dep:secp256k1"]
test-utils = [
Expand All @@ -99,7 +101,8 @@ arbitrary = [
"reth-codecs?/arbitrary",
"secp256k1?/global-context",
"secp256k1?/rand",
"op-alloy-consensus?/arbitrary"
"op-alloy-consensus?/arbitrary",
"alloy-trie/arbitrary"
]
serde-bincode-compat = [
"serde",
Expand All @@ -120,7 +123,8 @@ serde = [
"revm-primitives/serde",
"op-alloy-consensus?/serde",
"k256/serde",
"secp256k1?/serde"
"secp256k1?/serde",
"alloy-trie/serde"
]
reth-codec = [
"dep:reth-codecs",
Expand Down
12 changes: 12 additions & 0 deletions crates/primitives-traits/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use alloy_consensus::constants::KECCAK_EMPTY;
use alloy_genesis::GenesisAccount;
use alloy_primitives::{keccak256, Bytes, B256, U256};
use alloy_trie::TrieAccount;
use derive_more::Deref;
use revm_primitives::{AccountInfo, Bytecode as RevmBytecode, BytecodeDecodeError};

Expand Down Expand Up @@ -57,6 +58,17 @@ impl Account {
pub fn get_bytecode_hash(&self) -> B256 {
self.bytecode_hash.unwrap_or(KECCAK_EMPTY)
}

/// Converts the account into a trie account with the given storage root.
pub fn into_trie_account(self, storage_root: B256) -> TrieAccount {
let Self { nonce, balance, bytecode_hash } = self;
TrieAccount {
nonce,
balance,
storage_root,
code_hash: bytecode_hash.unwrap_or(KECCAK_EMPTY),
}
}
}

/// Bytecode for an account.
Expand Down
17 changes: 7 additions & 10 deletions crates/storage/provider/src/test_utils/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,13 @@ fn bundle_state_root(execution_outcome: &ExecutionOutcome) -> B256 {
account.info.as_ref().map(|info| {
(
address,
(
Account::from(info),
storage_root_unhashed(
account
.storage
.iter()
.filter(|(_, value)| !value.present_value.is_zero())
.map(|(slot, value)| ((*slot).into(), value.present_value)),
),
),
Account::from(info).into_trie_account(storage_root_unhashed(
account
.storage
.iter()
.filter(|(_, value)| !value.present_value.is_zero())
.map(|(slot, value)| ((*slot).into(), value.present_value)),
)),
)
})
},
Expand Down
5 changes: 1 addition & 4 deletions crates/trie/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ alloy-trie.workspace = true
alloy-consensus.workspace = true
reth-primitives-traits.workspace = true
reth-codecs = { workspace = true, optional = true }
revm-primitives.workspace = true

alloy-genesis.workspace = true
alloy-rpc-types-eth = { workspace = true, optional = true }
alloy-serde = { workspace = true, optional = true }

Expand All @@ -43,6 +41,7 @@ arbitrary = { workspace = true, features = ["derive"], optional = true }
[dev-dependencies]
reth-primitives-traits = { workspace = true, features = ["serde"] }
reth-codecs.workspace = true
alloy-genesis.workspace = true

alloy-primitives = { workspace = true, features = ["getrandom"] }
alloy-trie = { workspace = true, features = ["arbitrary", "serde"] }
Expand Down Expand Up @@ -71,7 +70,6 @@ serde = [
"alloy-consensus/serde",
"alloy-trie/serde",
"alloy-rpc-types-eth?/serde",
"revm-primitives/serde",
"reth-primitives-traits/serde",
"reth-codecs?/serde"
]
Expand Down Expand Up @@ -101,7 +99,6 @@ arbitrary = [
"alloy-consensus/arbitrary",
"alloy-primitives/arbitrary",
"nybbles/arbitrary",
"revm-primitives/arbitrary",
"reth-codecs/arbitrary",
"alloy-rpc-types-eth?/arbitrary"
]
Expand Down
122 changes: 19 additions & 103 deletions crates/trie/common/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,83 +1,18 @@
use crate::root::storage_root_unhashed;
use alloy_consensus::constants::KECCAK_EMPTY;
use alloy_genesis::GenesisAccount;
use alloy_primitives::{keccak256, B256, U256};
use alloy_rlp::{RlpDecodable, RlpEncodable};
use alloy_trie::EMPTY_ROOT_HASH;
use reth_primitives_traits::Account;
use revm_primitives::AccountInfo;

/// An Ethereum account as represented in the trie.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, RlpEncodable, RlpDecodable)]
pub struct TrieAccount {
/// Account nonce.
pub nonce: u64,
/// Account balance.
pub balance: U256,
/// Account's storage root.
pub storage_root: B256,
/// Hash of the account's bytecode.
pub code_hash: B256,
}

impl TrieAccount {
/// Get account's storage root.
pub const fn storage_root(&self) -> B256 {
self.storage_root
}
}

impl From<GenesisAccount> for TrieAccount {
fn from(account: GenesisAccount) -> Self {
let storage_root = account
.storage
.map(|storage| {
storage_root_unhashed(
storage
.into_iter()
.filter(|(_, value)| !value.is_zero())
.map(|(slot, value)| (slot, U256::from_be_bytes(*value))),
)
})
.unwrap_or(EMPTY_ROOT_HASH);

Self {
nonce: account.nonce.unwrap_or_default(),
balance: account.balance,
storage_root,
code_hash: account.code.map_or(KECCAK_EMPTY, keccak256),
}
}
}

impl From<(Account, B256)> for TrieAccount {
fn from((account, storage_root): (Account, B256)) -> Self {
Self {
nonce: account.nonce,
balance: account.balance,
storage_root,
code_hash: account.bytecode_hash.unwrap_or(KECCAK_EMPTY),
}
}
}

impl From<(AccountInfo, B256)> for TrieAccount {
fn from((account, storage_root): (AccountInfo, B256)) -> Self {
Self {
nonce: account.nonce,
balance: account.balance,
storage_root,
code_hash: account.code_hash,
}
}
}
/// Re-export for convenience.
pub use alloy_trie::TrieAccount;

#[cfg(test)]
mod tests {
use super::*;
use alloy_primitives::Bytes;
use crate::root::storage_root_unhashed;
use alloy_consensus::constants::KECCAK_EMPTY;
use alloy_genesis::GenesisAccount;
use alloy_primitives::{keccak256, Bytes, B256, U256};
use std::collections::BTreeMap;

use alloy_trie::EMPTY_ROOT_HASH;
use reth_primitives_traits::Account;

#[test]
fn test_from_genesis_account_with_default_values() {
let genesis_account = GenesisAccount::default();
Expand All @@ -88,14 +23,11 @@ mod tests {
// Check the fields are properly set.
assert_eq!(trie_account.nonce, 0);
assert_eq!(trie_account.balance, U256::default());
assert_eq!(trie_account.storage_root(), EMPTY_ROOT_HASH);
assert_eq!(trie_account.storage_root, EMPTY_ROOT_HASH);
assert_eq!(trie_account.code_hash, KECCAK_EMPTY);

// Check that the default Account converts to the same TrieAccount
assert_eq!(TrieAccount::from((Account::default(), EMPTY_ROOT_HASH)), trie_account);

// Check that the default AccountInfo converts to the same TrieAccount
assert_eq!(TrieAccount::from((AccountInfo::default(), EMPTY_ROOT_HASH)), trie_account);
assert_eq!(Account::default().into_trie_account(EMPTY_ROOT_HASH), trie_account);
}

#[test]
Expand Down Expand Up @@ -123,33 +55,17 @@ mod tests {
// Check that the fields are properly set.
assert_eq!(trie_account.nonce, 10);
assert_eq!(trie_account.balance, U256::from(1000));
assert_eq!(trie_account.storage_root(), expected_storage_root);
assert_eq!(trie_account.storage_root, expected_storage_root);
assert_eq!(trie_account.code_hash, keccak256([0x60, 0x61]));

// Check that the Account converts to the same TrieAccount
assert_eq!(
TrieAccount::from((
Account {
nonce: 10,
balance: U256::from(1000),
bytecode_hash: Some(keccak256([0x60, 0x61]))
},
expected_storage_root
)),
trie_account
);

// Check that the AccountInfo converts to the same TrieAccount
assert_eq!(
TrieAccount::from((
AccountInfo {
nonce: 10,
balance: U256::from(1000),
code_hash: keccak256([0x60, 0x61]),
..Default::default()
},
expected_storage_root
)),
Account {
nonce: 10,
balance: U256::from(1000),
bytecode_hash: Some(keccak256([0x60, 0x61]))
}
.into_trie_account(expected_storage_root),
trie_account
);
}
Expand All @@ -174,7 +90,7 @@ mod tests {
assert_eq!(trie_account.nonce, 3);
assert_eq!(trie_account.balance, U256::from(300));
// Zero values in storage should result in EMPTY_ROOT_HASH
assert_eq!(trie_account.storage_root(), EMPTY_ROOT_HASH);
assert_eq!(trie_account.storage_root, EMPTY_ROOT_HASH);
// No code provided, so code hash should be KECCAK_EMPTY
assert_eq!(trie_account.code_hash, KECCAK_EMPTY);
}
Expand Down
7 changes: 3 additions & 4 deletions crates/trie/common/src/proofs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,10 +258,9 @@ impl AccountProof {
let expected = if self.info.is_none() && self.storage_root == EMPTY_ROOT_HASH {
None
} else {
Some(alloy_rlp::encode(TrieAccount::from((
self.info.unwrap_or_default(),
self.storage_root,
))))
Some(alloy_rlp::encode(
self.info.unwrap_or_default().into_trie_account(self.storage_root),
))
};
let nibbles = Nibbles::unpack(keccak256(self.address));
verify_proof(root, nibbles, expected, &self.proof)
Expand Down
4 changes: 2 additions & 2 deletions crates/trie/db/tests/trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use reth_trie::{
triehash::KeccakHasher,
updates::StorageTrieUpdates,
BranchNodeCompact, HashBuilder, IntermediateStateRootState, Nibbles, StateRoot,
StateRootProgress, StorageRoot, TrieAccount, TrieMask,
StateRootProgress, StorageRoot, TrieMask,
};
use reth_trie_db::{DatabaseStateRoot, DatabaseStorageRoot};
use std::{collections::BTreeMap, ops::Mul, str::FromStr, sync::Arc};
Expand Down Expand Up @@ -284,7 +284,7 @@ fn test_state_root_with_state(state: State) {
}

fn encode_account(account: Account, storage_root: Option<B256>) -> Vec<u8> {
let account = TrieAccount::from((account, storage_root.unwrap_or(EMPTY_ROOT_HASH)));
let account = account.into_trie_account(storage_root.unwrap_or(EMPTY_ROOT_HASH));
let mut account_rlp = Vec::with_capacity(account.length());
account.encode(&mut account_rlp);
account_rlp
Expand Down
Loading

0 comments on commit 7650628

Please sign in to comment.