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

feat(sync): MerkleStage #994

Merged
merged 66 commits into from
Feb 4, 2023
Merged
Show file tree
Hide file tree
Changes from 42 commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
7e0410e
Add DBTrieLoader skeleton
MegaRedHand Jan 16, 2023
2a7fc36
Add storage root calculation
MegaRedHand Jan 17, 2023
8a88280
Add test verifying mainnet genesis block
MegaRedHand Jan 17, 2023
fbdb3ac
Add custom NodeCodec skeleton
MegaRedHand Jan 18, 2023
c57be05
Implement custom NodeCodec
MegaRedHand Jan 18, 2023
e5c9190
Add tests using cita_trie
MegaRedHand Jan 20, 2023
423538c
Remove allows and fix
MegaRedHand Jan 23, 2023
8a1e509
Add root calculation to MerkleStage
MegaRedHand Jan 23, 2023
cce16f4
Remove unwraps in trie
MegaRedHand Jan 23, 2023
4f2eaa7
Add traces to stage
MegaRedHand Jan 23, 2023
31ca213
Add comments
MegaRedHand Jan 24, 2023
88becea
Replace unwrap with unreachable
MegaRedHand Jan 24, 2023
d11d4c5
Add intermediate hashes persistence
MegaRedHand Jan 24, 2023
a6cdacb
Add incremental trie building
MegaRedHand Jan 24, 2023
571d58e
Add node decoding
MegaRedHand Jan 26, 2023
6011c4a
Add stage tests
MegaRedHand Jan 25, 2023
2ccd366
Add get_header_by_num to stages' Transaction
MegaRedHand Jan 26, 2023
68c89a9
Fix compile error
MegaRedHand Jan 26, 2023
5809342
Fix: was not adding accounts to HashedAccounts
MegaRedHand Jan 26, 2023
b68de75
Add check for genesis block
MegaRedHand Jan 26, 2023
c6fe95f
Generate old trie on seed_execution
MegaRedHand Jan 26, 2023
40b62ff
Change parity's TrieDBMut for cita_trie
MegaRedHand Jan 27, 2023
b78a1a3
Gather changes before updating
MegaRedHand Jan 27, 2023
1a4c159
Remove all trie-db stuff
MegaRedHand Jan 27, 2023
09fbb0e
Add unwind, update stage type struct, add tests
fkrause98 Jan 27, 2023
2c7fe54
Modify test seeding
MegaRedHand Jan 27, 2023
3a2a9fb
Merge branch 'merkle-stage' into merkle-stage-unwind
fkrause98 Jan 27, 2023
c5dbafa
Fix off by 1 error in test seed
MegaRedHand Jan 27, 2023
8e700c7
Merge branch 'merkle-stage' into merkle-stage-unwind
fkrause98 Jan 27, 2023
d4f2340
Fix transition id in seed_execution
MegaRedHand Jan 30, 2023
e700c54
Fix failing tests
MegaRedHand Jan 30, 2023
6d1ae39
Merge branch 'merkle-stage' into merkle-stage-unwind
fkrause98 Jan 30, 2023
2968893
Failing test
fkrause98 Jan 30, 2023
4e14b8e
Use proper tx
fkrause98 Jan 30, 2023
4ee2437
Passing test
fkrause98 Jan 30, 2023
6e771bb
Passing test
fkrause98 Jan 30, 2023
9a74916
Merge branch 'merkle-stage-unwind' of github.com:lambdaclass/reth int…
fkrause98 Jan 30, 2023
371a11f
Remove commented code
MegaRedHand Jan 30, 2023
74a54d3
Fix assert fail
MegaRedHand Jan 30, 2023
a7a456f
Fix fmt and warnings
MegaRedHand Jan 30, 2023
1dd0858
Merge branch 'main' into merkle-stage
MegaRedHand Jan 30, 2023
4573314
Change unwind tactic to incremental unwind
MegaRedHand Jan 30, 2023
3e234c0
Add derive_arbitrary for StorageTrieEntry
MegaRedHand Jan 31, 2023
292f3eb
Merge branch 'main' into merkle-stage
MegaRedHand Jan 31, 2023
cd02905
Remove unused deps
MegaRedHand Jan 31, 2023
56e8ae3
Fix clippy warnings
MegaRedHand Jan 31, 2023
f24d99c
Change error params order
MegaRedHand Jan 31, 2023
b5adaa3
Implement From cita-trie's error for TrieError
MegaRedHand Jan 31, 2023
78e1d74
Cleanup some comments
MegaRedHand Jan 31, 2023
805d35a
nit: use cursor to avoid double searching
MegaRedHand Jan 31, 2023
39cbe91
Change walk for walk_range
MegaRedHand Jan 31, 2023
a41f050
gather_changes hashes content at the end
MegaRedHand Jan 31, 2023
8e3ba6e
Remove transition id incrementing
MegaRedHand Jan 31, 2023
ce419d1
Use cita-trie's TrieError in our TrieError
MegaRedHand Feb 1, 2023
e8efafb
Add comments and remove unwraps
MegaRedHand Feb 1, 2023
4ae6f9e
Remove dbg!
MegaRedHand Feb 1, 2023
4d75437
Fix: was encoding values wrong
MegaRedHand Feb 1, 2023
f1e2964
Fix: hashing stages weren't hashing genesis accs
MegaRedHand Feb 1, 2023
8de7eab
Appease clippy
MegaRedHand Feb 1, 2023
401b8dd
Add fuzzing test for trie
MegaRedHand Feb 1, 2023
9fe2b4f
Fix and update docs and comments
MegaRedHand Feb 2, 2023
acf7e48
Add defaults for MerkleStage
MegaRedHand Feb 2, 2023
77618d7
Change `new_with_root` to `from_root`
MegaRedHand Feb 2, 2023
82dc1f3
Fix storage value encoding
MegaRedHand Feb 2, 2023
ef2edfe
Fix: merkle execute fails caused unwind fails
MegaRedHand Feb 3, 2023
a240b6a
Merge branch 'main' into merkle-stage
MegaRedHand Feb 3, 2023
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
604 changes: 319 additions & 285 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions crates/common/rlp/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,9 @@ where
}
}

pub fn encode_iter<'a, K>(i: impl Iterator<Item = &'a K> + Clone, out: &mut dyn BufMut)
pub fn encode_iter<K>(i: impl Iterator<Item = K> + Clone, out: &mut dyn BufMut)
where
K: Encodable + 'a,
K: Encodable,
{
let mut h = Header { list: true, payload_length: 0 };
for x in i.clone() {
Expand Down
2 changes: 2 additions & 0 deletions crates/interfaces/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub enum Error {
HeaderGasUsedExceedsGasLimit { gas_used: u64, gas_limit: u64 },
#[error("Block ommer hash ({got:?}) is different then expected: ({expected:?})")]
BodyOmmersHashDiff { got: H256, expected: H256 },
#[error("Block state root ({got:?}) is different then expected: ({expected:?})")]
BodyStateRootDiff { got: H256, expected: H256 },
#[error("Block transaction root ({got:?}) is different then expected: ({expected:?})")]
BodyTransactionRootDiff { got: H256, expected: H256 },
#[error("Block receipts root ({got:?}) is different then expected: ({expected:?}).")]
Expand Down
15 changes: 14 additions & 1 deletion crates/interfaces/src/test_utils/generators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ pub fn random_eoa_account() -> (Address, Account) {
(addr, Account { nonce, balance, bytecode_hash: None })
}

/// Docs
/// Generate random Externaly Owned Accounts
pub fn random_eoa_account_range(acc_range: &mut std::ops::Range<u64>) -> Vec<(Address, Account)> {
let mut accounts = Vec::with_capacity(acc_range.end.saturating_sub(acc_range.start) as usize);
for _ in acc_range {
Expand All @@ -182,6 +182,19 @@ pub fn random_eoa_account_range(acc_range: &mut std::ops::Range<u64>) -> Vec<(Ad
accounts
}

/// Generate random Contract Accounts
pub fn random_contract_account_range(
acc_range: &mut std::ops::Range<u64>,
) -> Vec<(Address, Account)> {
let mut accounts = Vec::with_capacity(acc_range.end.saturating_sub(acc_range.start) as usize);
for _ in acc_range {
let (address, eoa_account) = random_eoa_account();
let account = Account { bytecode_hash: Some(H256::random()), ..eoa_account };
accounts.push((address, account))
}
accounts
}

#[cfg(test)]
mod test {
use std::str::FromStr;
Expand Down
2 changes: 1 addition & 1 deletion crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub use log::Log;
pub use net::NodeRecord;
pub use peer::{PeerId, WithPeerId};
pub use receipt::Receipt;
pub use storage::StorageEntry;
pub use storage::{StorageEntry, StorageTrieEntry};
pub use transaction::{
AccessList, AccessListItem, FromRecoveredTransaction, IntoRecoveredTransaction, Signature,
Transaction, TransactionKind, TransactionSigned, TransactionSignedEcRecovered, TxEip1559,
Expand Down
2 changes: 1 addition & 1 deletion crates/primitives/src/proofs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub const EMPTY_ROOT: H256 =

/// A [Hasher] that calculates a keccak256 hash of the given data.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub(crate) struct KeccakHasher;
pub struct KeccakHasher;

impl Hasher for KeccakHasher {
type Out = H256;
Expand Down
30 changes: 30 additions & 0 deletions crates/primitives/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,33 @@ impl Compact for StorageEntry {
(Self { key, value }, out)
}
}

/// Account storage trie node.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
pub struct StorageTrieEntry {
/// Hashed storage key.
pub hash: H256,
/// Encoded node.
pub node: Vec<u8>,
}

// NOTE: Removing main_codec and manually encode subkey
gakonst marked this conversation as resolved.
Show resolved Hide resolved
// and compress second part of the value. If we have compression
// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey
impl Compact for StorageTrieEntry {
fn to_compact(self, buf: &mut impl bytes::BufMut) -> usize {
// for now put full bytes and later compress it.
buf.put_slice(&self.hash.to_fixed_bytes()[..]);
buf.put_slice(&self.node[..]);
self.node.len() + 32
}

fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8])
where
Self: Sized,
{
let key = H256::from_slice(&buf[..32]);
let node = Vec::from(&buf[32..len]);
(Self { hash: key, node }, &buf[len..])
}
}
14 changes: 13 additions & 1 deletion crates/stages/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ thiserror = "1.0.37"
aquamarine = "0.1.12"
itertools = "0.10.5"
rayon = "1.6.0"

# trie
trie-db = "0.24.0"
hash-db = "0.15.2"
parity-scale-codec = { version = "3.2.1", features = ["bytes"] }
cita_trie = "4.0.0"
hasher = "0.1.4"

[dev-dependencies]
# reth
reth-db = { path = "../storage/db", features = ["test-utils", "mdbx"] }
Expand All @@ -50,6 +58,10 @@ assert_matches = "1.5.0"
rand = "0.8.5"
paste = "1.0"

# trie
reth-staged-sync = { path = "../staged-sync" }
triehash = "0.8"

[features]
default = ["serde"]
serde = ["dep:serde"]
serde = ["dep:serde"]
11 changes: 10 additions & 1 deletion crates/stages/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use reth_db::{
transaction::{DbTx, DbTxMut},
Error,
};
use reth_primitives::{BlockHash, BlockNumber, TransitionId, TxNumber};
use reth_primitives::{BlockHash, BlockNumber, Header, TransitionId, TxNumber};

use crate::{DatabaseIntegrityError, StageError};

Expand Down Expand Up @@ -164,6 +164,15 @@ where
Ok((prev_body.start_tx_id + prev_body.tx_count, last_transition))
}

/// Query the block header by number
pub(crate) fn get_header_by_num(&self, block: BlockNumber) -> Result<Header, StageError> {
let key = self.get_block_numhash(block)?;
let header = self
.get::<tables::Headers>(key)?
.ok_or(DatabaseIntegrityError::Header { number: block, hash: key.hash() })?;
Ok(header)
}

/// Unwind table by some number key
#[inline]
pub(crate) fn unwind_table_by_num<T>(&self, num: u64) -> Result<(), Error>
Expand Down
1 change: 1 addition & 0 deletions crates/stages/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ mod error;
mod id;
mod pipeline;
mod stage;
mod trie;
mod util;

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion crates/stages/src/sets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ impl<DB: Database> StageSet<DB> for HashingStages {
.add_stage(MerkleStage::Unwind)
.add_stage(AccountHashingStage::default())
.add_stage(StorageHashingStage::default())
.add_stage(MerkleStage::Execution)
.add_stage(MerkleStage::Execution { clean_threshold: 1_000 })
}
}

Expand Down
Loading