feat(primitives): clean up primitives proof.rs file (#5167)

This commit is contained in:
Thomas Coratger
2023-10-25 15:30:56 +02:00
committed by GitHub
parent fb5f0bac06
commit 98e03ee4e2
11 changed files with 45 additions and 57 deletions

View File

@ -1160,7 +1160,7 @@ mod tests {
use reth_db::{tables, test_utils::create_test_rw_db, transaction::DbTxMut, DatabaseEnv};
use reth_interfaces::test_utils::TestConsensus;
use reth_primitives::{
proofs::EMPTY_ROOT, stage::StageCheckpoint, ChainSpecBuilder, B256, MAINNET,
constants::EMPTY_ROOT_HASH, stage::StageCheckpoint, ChainSpecBuilder, B256, MAINNET,
};
use reth_provider::{
test_utils::{blocks::BlockChainTestData, TestExecutorFactory},
@ -1190,7 +1190,7 @@ mod tests {
// insert genesis to db.
genesis.header.header.number = 10;
genesis.header.header.state_root = EMPTY_ROOT;
genesis.header.header.state_root = EMPTY_ROOT_HASH;
let factory = ProviderFactory::new(&db, MAINNET.clone());
let provider = factory.provider_rw().unwrap();

View File

@ -198,7 +198,6 @@ pub fn validate_block_standalone(
chain_spec: &ChainSpec,
) -> Result<(), ConsensusError> {
// Check ommers hash
// TODO(onbjerg): This should probably be accessible directly on [Block]
let ommers_hash = reth_primitives::proofs::calculate_ommers_root(&block.ommers);
if block.header.ommers_hash != ommers_hash {
return Err(ConsensusError::BodyOmmersHashDiff {

View File

@ -100,18 +100,18 @@ pub const KECCAK_EMPTY: B256 =
pub const EMPTY_OMMER_ROOT: B256 =
b256!("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347");
/// hash of an empty set `keccak256(rlp([]))`
const EMPTY_SET_HASH: B256 =
/// Root hash of an empty trie.
pub const EMPTY_ROOT_HASH: B256 =
b256!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421");
/// Transactions root of empty receipts set.
pub const EMPTY_RECEIPTS: B256 = EMPTY_SET_HASH;
pub const EMPTY_RECEIPTS: B256 = EMPTY_ROOT_HASH;
/// Transactions root of empty transactions set.
pub const EMPTY_TRANSACTIONS: B256 = EMPTY_SET_HASH;
pub const EMPTY_TRANSACTIONS: B256 = EMPTY_ROOT_HASH;
/// Withdrawals root of empty withdrawals set.
pub const EMPTY_WITHDRAWALS: B256 = EMPTY_SET_HASH;
pub const EMPTY_WITHDRAWALS: B256 = EMPTY_ROOT_HASH;
/// The number of blocks to unwind during a reorg that already became a part of canonical chain.
///

View File

@ -1,6 +1,6 @@
use crate::{
constants::EMPTY_ROOT_HASH,
keccak256,
proofs::EMPTY_ROOT,
serde_helper::{
deserialize_json_u256, deserialize_json_u256_opt, deserialize_storage_map,
num::{u64_hex_or_decimal, u64_hex_or_decimal_opt},
@ -159,7 +159,7 @@ impl GenesisAccount {
len += self.balance.length();
// rather than rlp-encoding the storage, we just return the length of a single hash
// hashes are a fixed size, so it is safe to use the empty root for this
len += EMPTY_ROOT.length();
len += EMPTY_ROOT_HASH.length();
// we are encoding a hash, so let's just use the length of the empty hash for the code hash
len += KECCAK_EMPTY.length();
len
@ -199,9 +199,9 @@ impl Encodable for GenesisAccount {
self.balance.encode(out);
self.storage
.as_ref()
.map_or(EMPTY_ROOT, |storage| {
.map_or(EMPTY_ROOT_HASH, |storage| {
if storage.is_empty() {
return EMPTY_ROOT
return EMPTY_ROOT_HASH
}
let storage_with_sorted_hashed_keys = storage

View File

@ -1,10 +1,9 @@
use crate::{
basefee::calculate_next_block_base_fee,
constants::{EMPTY_OMMER_ROOT, EMPTY_ROOT_HASH},
eip4844::{calc_blob_gasprice, calculate_excess_blob_gas},
keccak256,
proofs::{EMPTY_LIST_HASH, EMPTY_ROOT},
Address, BaseFeeParams, BlockBodyRoots, BlockHash, BlockNumHash, BlockNumber, Bloom, Bytes,
B256, B64, U256,
keccak256, Address, BaseFeeParams, BlockBodyRoots, BlockHash, BlockNumHash, BlockNumber, Bloom,
Bytes, B256, B64, U256,
};
use alloy_rlp::{length_of_length, Decodable, Encodable, EMPTY_LIST_CODE, EMPTY_STRING_CODE};
use bytes::{Buf, BufMut, BytesMut};
@ -116,11 +115,11 @@ impl Default for Header {
fn default() -> Self {
Header {
parent_hash: Default::default(),
ommers_hash: EMPTY_LIST_HASH,
ommers_hash: EMPTY_OMMER_ROOT,
beneficiary: Default::default(),
state_root: EMPTY_ROOT,
transactions_root: EMPTY_ROOT,
receipts_root: EMPTY_ROOT,
state_root: EMPTY_ROOT_HASH,
transactions_root: EMPTY_ROOT_HASH,
receipts_root: EMPTY_ROOT_HASH,
logs_bloom: Default::default(),
difficulty: Default::default(),
number: 0,
@ -157,7 +156,7 @@ impl Header {
pub fn is_empty(&self) -> bool {
let txs_and_ommers_empty = self.transaction_root_is_empty() && self.ommers_hash_is_empty();
if let Some(withdrawals_root) = self.withdrawals_root {
txs_and_ommers_empty && withdrawals_root == EMPTY_ROOT
txs_and_ommers_empty && withdrawals_root == EMPTY_ROOT_HASH
} else {
txs_and_ommers_empty
}
@ -165,12 +164,12 @@ impl Header {
/// Check if the ommers hash equals to empty hash list.
pub fn ommers_hash_is_empty(&self) -> bool {
self.ommers_hash == EMPTY_LIST_HASH
self.ommers_hash == EMPTY_OMMER_ROOT
}
/// Check if the transaction root equals to empty root.
pub fn transaction_root_is_empty(&self) -> bool {
self.transactions_root == EMPTY_ROOT
self.transactions_root == EMPTY_ROOT_HASH
}
/// Converts all roots in the header to a [BlockBodyRoots] struct.

View File

@ -1,9 +1,10 @@
//! Helper function for calculating Merkle proofs and hashes.
use crate::{
b256, keccak256,
constants::EMPTY_OMMER_ROOT,
keccak256,
trie::{HashBuilder, Nibbles},
Address, GenesisAccount, Header, Log, ReceiptWithBloom, ReceiptWithBloomRef, TransactionSigned,
Address, GenesisAccount, Header, ReceiptWithBloom, ReceiptWithBloomRef, TransactionSigned,
Withdrawal, B256,
};
use alloy_rlp::Encodable;
@ -11,14 +12,6 @@ use bytes::{BufMut, BytesMut};
use itertools::Itertools;
use std::collections::HashMap;
/// Keccak-256 hash of the RLP of an empty list, KEC("\xc0").
pub const EMPTY_LIST_HASH: B256 =
b256!("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347");
/// Root hash of an empty trie.
pub const EMPTY_ROOT: B256 =
b256!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421");
/// Adjust the index of an item for rlp encoding.
pub const fn adjust_index_for_rlp(i: usize, len: usize) -> usize {
if i > 0x7f {
@ -92,16 +85,12 @@ where
})
}
/// Calculates the log root for headers.
pub fn calculate_log_root(logs: &[Log]) -> B256 {
//https://github.com/ethereum/go-ethereum/blob/356bbe343a30789e77bb38f25983c8f2f2bfbb47/cmd/evm/internal/t8ntool/execution.go#L255
let mut logs_rlp = Vec::new();
alloy_rlp::encode_list(logs, &mut logs_rlp);
keccak256(logs_rlp)
}
/// Calculates the root hash for ommer/uncle headers.
pub fn calculate_ommers_root(ommers: &[Header]) -> B256 {
// Check if `ommers` list is empty
if ommers.is_empty() {
return EMPTY_OMMER_ROOT
}
// RLP Encode
let mut ommers_rlp = Vec::new();
alloy_rlp::encode_list(ommers, &mut ommers_rlp);
@ -157,7 +146,8 @@ pub mod triehash {
mod tests {
use super::*;
use crate::{
bloom, hex, Block, Receipt, TxType, B256, GOERLI, HOLESKY, MAINNET, SEPOLIA, U256,
b256, bloom, constants::EMPTY_ROOT_HASH, hex, Block, Log, Receipt, TxType, B256, GOERLI,
HOLESKY, MAINNET, SEPOLIA, U256,
};
use alloy_rlp::Decodable;
@ -216,7 +206,7 @@ mod tests {
fn check_empty_state_root() {
let genesis_alloc = HashMap::new();
let root = genesis_state_root(&genesis_alloc);
assert_eq!(root, EMPTY_ROOT);
assert_eq!(root, EMPTY_ROOT_HASH);
}
#[test]

View File

@ -2,7 +2,7 @@ use super::{
nodes::{rlp_hash, BranchNode, ExtensionNode, LeafNode},
BranchNodeCompact, Nibbles, TrieMask,
};
use crate::{keccak256, proofs::EMPTY_ROOT, Bytes, B256};
use crate::{constants::EMPTY_ROOT_HASH, keccak256, Bytes, B256};
use std::{
collections::{BTreeMap, HashMap},
fmt::Debug,
@ -186,7 +186,7 @@ impl HashBuilder {
keccak256(node_ref)
}
} else {
EMPTY_ROOT
EMPTY_ROOT_HASH
}
}
@ -500,7 +500,7 @@ mod tests {
#[test]
fn empty() {
assert_eq!(HashBuilder::default().root(), EMPTY_ROOT);
assert_eq!(HashBuilder::default().root(), EMPTY_ROOT_HASH);
}
#[test]

View File

@ -1,8 +1,8 @@
//! Standalone Conversion Functions for Handling Different Versions of Execution Payloads in
//! Ethereum's Engine
use reth_primitives::{
constants::{MAXIMUM_EXTRA_DATA_SIZE, MIN_PROTOCOL_BASE_FEE_U256},
proofs::{self, EMPTY_LIST_HASH},
constants::{EMPTY_OMMER_ROOT, MAXIMUM_EXTRA_DATA_SIZE, MIN_PROTOCOL_BASE_FEE_U256},
proofs::{self},
Block, Header, SealedBlock, TransactionSigned, UintTryTo, Withdrawal, B256, U256, U64,
};
use reth_rpc_types::engine::{
@ -51,7 +51,7 @@ pub fn try_payload_v1_to_block(payload: ExecutionPayloadV1) -> Result<Block, Pay
parent_beacon_block_root: None,
extra_data: payload.extra_data,
// Defaults
ommers_hash: EMPTY_LIST_HASH,
ommers_hash: EMPTY_OMMER_ROOT,
difficulty: Default::default(),
nonce: Default::default(),
};

View File

@ -1,5 +1,5 @@
use alloy_rlp::{RlpDecodable, RlpEncodable};
use reth_primitives::{proofs::EMPTY_ROOT, Account, B256, KECCAK_EMPTY, U256};
use reth_primitives::{constants::EMPTY_ROOT_HASH, Account, B256, KECCAK_EMPTY, U256};
/// An Ethereum account as represented in the trie.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, RlpEncodable, RlpDecodable)]
@ -19,7 +19,7 @@ impl From<Account> for EthAccount {
EthAccount {
nonce: acc.nonce,
balance: acc.balance,
storage_root: EMPTY_ROOT,
storage_root: EMPTY_ROOT_HASH,
code_hash: acc.bytecode_hash.unwrap_or(KECCAK_EMPTY),
}
}

View File

@ -10,8 +10,8 @@ use crate::{
use alloy_rlp::{BufMut, Encodable};
use reth_db::{tables, transaction::DbTx};
use reth_primitives::{
constants::EMPTY_ROOT_HASH,
keccak256,
proofs::EMPTY_ROOT,
trie::{AccountProof, HashBuilder, Nibbles, StorageProof},
Address, B256,
};
@ -115,7 +115,7 @@ where
// short circuit on empty storage
if hashed_storage_cursor.is_storage_empty(hashed_address)? {
return Ok((EMPTY_ROOT, proofs))
return Ok((EMPTY_ROOT_HASH, proofs))
}
let target_nibbles = proofs.iter().map(|p| p.nibbles.clone()).collect::<Vec<_>>();
@ -299,7 +299,7 @@ mod tests {
let target = Address::from_str("0x1ed9b1dd266b607ee278726d324b855a093394a6").unwrap();
let slots = Vec::from([B256::with_last_byte(1), B256::with_last_byte(3)]);
let account_proof = Proof::new(&tx).account_proof(target, &slots).unwrap();
assert_eq!(account_proof.storage_root, EMPTY_ROOT, "expected empty storage root");
assert_eq!(account_proof.storage_root, EMPTY_ROOT_HASH, "expected empty storage root");
assert_eq!(slots.len(), account_proof.storage_proofs.len());
for (idx, slot) in slots.into_iter().enumerate() {

View File

@ -12,8 +12,8 @@ use crate::{
use alloy_rlp::{BufMut, Encodable};
use reth_db::{tables, transaction::DbTx};
use reth_primitives::{
constants::EMPTY_ROOT_HASH,
keccak256,
proofs::EMPTY_ROOT,
trie::{HashBuilder, Nibbles},
Address, BlockNumber, B256,
};
@ -438,7 +438,7 @@ where
// short circuit on empty storage
if hashed_storage_cursor.is_storage_empty(self.hashed_address)? {
return Ok((
EMPTY_ROOT,
EMPTY_ROOT_HASH,
0,
TrieUpdates::from([(TrieKey::StorageTrie(self.hashed_address), TrieOp::Delete)]),
))
@ -671,7 +671,7 @@ mod tests {
let tx = factory.provider_rw().unwrap();
let got = StorageRoot::new(tx.tx_ref(), address).root().unwrap();
assert_eq!(got, EMPTY_ROOT);
assert_eq!(got, EMPTY_ROOT_HASH);
}
#[test]