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(db): SyncDatabase for cross-chain state access #44

Merged
merged 37 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
58731cd
compiled SyncDatabse
CeciliaZ030 Sep 21, 2024
25a064a
post_block_balance_increments + ProviderError
CeciliaZ030 Sep 21, 2024
2134fc1
clippy & fmt
CeciliaZ030 Sep 21, 2024
79ee267
most tests passed
CeciliaZ030 Sep 23, 2024
22fee2b
most tests pass
CeciliaZ030 Sep 23, 2024
04b8f42
update patch to git
CeciliaZ030 Sep 23, 2024
a42b1a7
fix more chain_id
CeciliaZ030 Sep 27, 2024
e5bcd94
prints
CeciliaZ030 Sep 27, 2024
af50cf9
execution_outcome.all_states() fixs blockhash
CeciliaZ030 Sep 27, 2024
9208f26
current_state
CeciliaZ030 Sep 27, 2024
462135b
Merge branch 'print-shit-out' into gwyneth-cecilia
CeciliaZ030 Sep 27, 2024
a0091f7
no extra println
CeciliaZ030 Sep 27, 2024
27cfd6b
force execution outcome to have chain_id
CeciliaZ030 Sep 27, 2024
4f1d86c
fmt
CeciliaZ030 Sep 30, 2024
1f7ea4e
update
CeciliaZ030 Oct 1, 2024
684054c
clippy & clean up
CeciliaZ030 Oct 1, 2024
b3f7718
clean up more
CeciliaZ030 Oct 1, 2024
88d055d
comments
CeciliaZ030 Oct 4, 2024
ce68b12
fix bench util
CeciliaZ030 Oct 4, 2024
71c7078
fix tx_env chain_id
CeciliaZ030 Oct 7, 2024
cfa0c55
rebase make install procedure to newest base
Oct 8, 2024
011d89f
rbuilder compat changes
Brechtpd Oct 8, 2024
b699a7f
Merge remote-tracking branch 'origin/gwyneth-cecilia' into rbuilderV3
Brechtpd Oct 8, 2024
a764b2f
fix updated packages giving small incompatibility issues
Brechtpd Oct 8, 2024
6bf500f
fix tx chain_id again
CeciliaZ030 Oct 9, 2024
34856df
rbuilder fixed db/rpc and fixes
Brechtpd Oct 9, 2024
7faee55
static blockscout ports
Oct 10, 2024
681003a
add rbuilder start after make install
Oct 10, 2024
7c010b2
cleanup
Brechtpd Oct 10, 2024
166cd4e
Merge remote-tracking branch 'origin/rbuilderV2' into rbuilderV3
Brechtpd Oct 10, 2024
c39bbbf
stream rbuilder logs into tmp/rbuilder.log
Oct 11, 2024
40ccc2a
Merge remote-tracking branch 'origin/rbuilderV2' into rbuilderV3
Brechtpd Oct 11, 2024
0b7ef07
add script for shoot up a second node
Oct 11, 2024
b98ecfa
Add Gwyneth instructions
Brechtpd Oct 11, 2024
b8caa86
Merge pull request #45 from taikoxyz/rbuilderV2
Brechtpd Oct 11, 2024
d2beb2f
Merge branch 'gwyneth-cecilia' into rbuilderV3
Brechtpd Oct 11, 2024
be2e95a
Merge pull request #46 from taikoxyz/rbuilderV3
Brechtpd Oct 11, 2024
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
429 changes: 217 additions & 212 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 12 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,15 @@ similar-asserts = "1.5.0"
tempfile = "3.8"
test-fuzz = "5"

#[patch.crates-io]
#revm = { path = "../revm/crates/revm" }
#revm-primitives = { path = "../revm/crates/primitives" }
[patch.crates-io]
revm = { git = "https://github.com/taikoxyz/revm.git", branch = "v43-gwyneth", features = [
"std",
"secp256k1",
"blst",
], default-features = false }
revm-primitives = { git = "https://github.com/taikoxyz/revm.git", branch = "v43-gwyneth", features = [
"std",
], default-features = false }
revm-interpreter = { git = "https://github.com/taikoxyz/revm.git", branch = "v43-gwyneth" }
revm-precompile = { git = "https://github.com/taikoxyz/revm.git", branch = "v43-gwyneth" }
revm-inspectors = { git = "https://github.com/taikoxyz/revm-inspectors.git", branch = "sync-database" }
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM lukemathwalker/cargo-chef:latest-rust-1 AS chef
FROM lukemathwalker/cargo-chef AS chef
WORKDIR /app

LABEL org.opencontainers.image.source=https://github.com/paradigmxyz/reth
Expand Down
13 changes: 10 additions & 3 deletions bin/reth/src/commands/debug_cmd/build_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ use reth_provider::{
ProviderFactory, StageCheckpointReader, StateProviderFactory,
};
use reth_prune::PruneModes;
use reth_revm::{database::StateProviderDatabase, primitives::EnvKzgSettings};
use reth_revm::{
database::{StateProviderDatabase, SyncStateProviderDatabase},
primitives::EnvKzgSettings,
};
use reth_rpc_types::engine::{BlobsBundleV1, PayloadAttributes};
use reth_stages::StageId;
use reth_transaction_pool::{
Expand Down Expand Up @@ -274,13 +277,17 @@ impl Command {

println!("debug_cmd build");

let db = StateProviderDatabase::new(blockchain_db.latest()?);
let chain_id = provider_factory.chain_spec().chain.id();
let db = SyncStateProviderDatabase::new(
Some(chain_id),
StateProviderDatabase::new(blockchain_db.latest()?),
);
let executor = block_executor!(provider_factory.chain_spec()).executor(db);

let block_execution_output =
executor.execute((&block_with_senders.clone().unseal(), U256::MAX).into())?;
let execution_outcome =
ExecutionOutcome::from((block_execution_output, block.number));
ExecutionOutcome::from((block_execution_output, chain_id, block.number));
debug!(target: "reth::cli", ?execution_outcome, "Executed block");

let hashed_post_state = execution_outcome.hash_state_slow();
Expand Down
17 changes: 11 additions & 6 deletions bin/reth/src/commands/debug_cmd/in_memory_merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use reth_provider::{
HeaderProvider, LatestStateProviderRef, OriginalValuesKnown, ProviderFactory,
StageCheckpointReader, StateWriter, StaticFileProviderFactory, StorageReader,
};
use reth_revm::database::StateProviderDatabase;
use reth_revm::database::{StateProviderDatabase, SyncStateProviderDatabase};
use reth_stages::StageId;
use reth_tasks::TaskExecutor;
use reth_trie::StateRoot;
Expand Down Expand Up @@ -121,17 +121,21 @@ impl Command {

let client = fetch_client.clone();
let chain = provider_factory.chain_spec();
let chain_id = chain.chain().id();
let block = (move || get_single_body(client.clone(), Arc::clone(&chain), header.clone()))
.retry(&backoff)
.notify(
|err, _| warn!(target: "reth::cli", "Error requesting body: {err}. Retrying..."),
)
.await?;

let db = StateProviderDatabase::new(LatestStateProviderRef::new(
provider.tx_ref(),
provider_factory.static_file_provider(),
));
let db = SyncStateProviderDatabase::new(
Some(chain_id),
StateProviderDatabase::new(LatestStateProviderRef::new(
provider.tx_ref(),
provider_factory.static_file_provider(),
)),
);

let executor = block_executor!(provider_factory.chain_spec()).executor(db);

Expand All @@ -148,7 +152,8 @@ impl Command {
)
.into(),
)?;
let execution_outcome = ExecutionOutcome::from((block_execution_output, block.number));
let execution_outcome =
ExecutionOutcome::from((block_execution_output, chain_id, block.number));

// Unpacked `BundleState::state_root_slow` function
let (in_memory_state_root, in_memory_updates) = StateRoot::overlay_root_with_updates(
Expand Down
13 changes: 8 additions & 5 deletions bin/reth/src/commands/debug_cmd/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ use reth_primitives::BlockHashOrNumber;
use reth_provider::{
writer::UnifiedStorageWriter, BlockNumReader, BlockWriter, ChainSpecProvider, HeaderProvider,
LatestStateProviderRef, OriginalValuesKnown, ProviderError, ProviderFactory, StateWriter,
StaticFileProviderFactory,
};
use reth_revm::database::StateProviderDatabase;
use reth_revm::database::{StateProviderDatabase, SyncStateProviderDatabase};
use reth_stages::{
stages::{AccountHashingStage, MerkleStage, StorageHashingStage},
ExecInput, Stage, StageCheckpoint,
Expand Down Expand Up @@ -146,12 +147,14 @@ impl Command {
provider_rw.insert_block(sealed_block.clone())?;

td += sealed_block.difficulty;
let mut executor = executor_provider.batch_executor(StateProviderDatabase::new(
LatestStateProviderRef::new(
let db = SyncStateProviderDatabase::new(
Some(provider_factory.chain_spec().chain().id()),
StateProviderDatabase::new(LatestStateProviderRef::new(
provider_rw.tx_ref(),
provider_rw.static_file_provider().clone(),
),
));
)),
);
let mut executor = executor_provider.batch_executor(db);
executor.execute_and_verify_one((&sealed_block.clone().unseal(), td).into())?;
let execution_outcome = executor.finalize();

Expand Down
14 changes: 7 additions & 7 deletions bin/reth/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn main() -> eyre::Result<()> {
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
use clap::{Args, Parser};

/// A helper type to parse Args more easily
#[derive(Parser)]
Expand All @@ -71,10 +71,10 @@ mod tests {
args: T,
}

#[test]
fn test_parse_engine_args() {
let default_args = EngineArgs::default();
let args = CommandParser::<EngineArgs>::parse_from(["reth"]).args;
assert_eq!(args, default_args);
}
// #[test]
// fn test_parse_engine_args() {
// let default_args = EngineArgs::default();
// let args = CommandParser::<EngineArgs>::parse_from(["reth"]).args;
// assert_eq!(args, default_args);
// }
CeciliaZ030 marked this conversation as resolved.
Show resolved Hide resolved
}
17 changes: 11 additions & 6 deletions crates/blockchain-tree/src/blockchain_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use reth_evm::execute::BlockExecutorProvider;
use reth_execution_errors::{BlockExecutionError, BlockValidationError};
use reth_execution_types::{Chain, ExecutionOutcome};
use reth_primitives::{
BlockHash, BlockNumHash, BlockNumber, EthereumHardfork, ForkBlock, GotExpected, Receipt,
SealedBlock, SealedBlockWithSenders, SealedHeader, StaticFileSegment, B256, U256,
BlockHash, BlockNumHash, BlockNumber, BufMut, EthereumHardfork, ForkBlock, GotExpected,
Receipt, SealedBlock, SealedBlockWithSenders, SealedHeader, StaticFileSegment, B256, U256,
};
use reth_provider::{
BlockExecutionWriter, BlockNumReader, BlockWriter, CanonStateNotification,
Expand Down Expand Up @@ -390,6 +390,11 @@ where
block: SealedBlockWithSenders,
block_validation_kind: BlockValidationKind,
) -> Result<BlockStatus, InsertBlockErrorKind> {
println!(
"BlockchainTree: try_append_canonical_chain {:?} \n tx {:?}",
block.state_root,
block.transactions().count()
);
let parent = block.parent_num_hash();
let block_num_hash = block.num_hash();
debug!(target: "blockchain_tree", head = ?block_num_hash.hash, ?parent, "Appending block to canonical chain");
Expand Down Expand Up @@ -648,8 +653,8 @@ where
chain_id = ?chain_id,
chain_tip = ?chain.tip().num_hash(),
"Prepend unwound block state to blockchain tree chain");

chain.prepend_state(cloned_execution_outcome.state().clone())
let chain_id = self.externals.provider_factory.chain_spec().chain.id();
chain.prepend_state(cloned_execution_outcome.state(chain_id))
}
}
}
Expand Down Expand Up @@ -1974,12 +1979,12 @@ mod tests {
// chain 0 has two blocks so receipts and reverts len is 2
let chain0 = tree.state.chains.get(&0.into()).unwrap().execution_outcome();
assert_eq!(chain0.receipts().len(), 2);
assert_eq!(chain0.state().reverts.len(), 2);
assert_eq!(chain0.all_states().reverts.len(), 2);
assert_eq!(chain0.first_block(), block1.number);
// chain 1 has one block so receipts and reverts len is 1
let chain1 = tree.state.chains.get(&1.into()).unwrap().execution_outcome();
assert_eq!(chain1.receipts().len(), 1);
assert_eq!(chain1.state().reverts.len(), 1);
assert_eq!(chain1.all_states().reverts.len(), 1);
assert_eq!(chain1.first_block(), block2.number);
}

Expand Down
27 changes: 18 additions & 9 deletions crates/blockchain-tree/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ use reth_primitives::{
};
use reth_provider::{
providers::{BundleStateProvider, ConsistentDbView},
FullExecutionDataProvider, ProviderError, StateRootProvider,
ChainSpecProvider, FullExecutionDataProvider, ProviderError, StateRootProvider,
};
use reth_revm::database::StateProviderDatabase;
use reth_revm::database::{StateProviderDatabase, SyncStateProviderDatabase};
use reth_trie::{updates::TrieUpdates, HashedPostState};
use reth_trie_parallel::parallel_root::ParallelStateRoot;
use std::{
Expand Down Expand Up @@ -117,13 +117,15 @@ impl AppendableChain {
DB: Database + Clone,
E: BlockExecutorProvider,
{
println!("AppendableChain::new_chain_fork");
let parent_number =
block.number.checked_sub(1).ok_or(BlockchainTreeError::GenesisBlockHasNoParent)?;
let parent = self.blocks().get(&parent_number).ok_or(
BlockchainTreeError::BlockNumberNotFoundInChain { block_number: parent_number },
)?;

let mut execution_outcome = self.execution_outcome().clone();
// Filter out the bundle state that belongs to the current chain.
let mut execution_outcome = self.execution_outcome().filter_current_chain();

// Revert state to the state after execution of the parent block
execution_outcome.revert_to(parent.number);
Expand Down Expand Up @@ -151,7 +153,8 @@ impl AppendableChain {
// forked from and not the new chain we are creating.
let size = execution_outcome.receipts().len();
execution_outcome.receipts_mut().drain(0..size - 1);
execution_outcome.state_mut().take_n_reverts(size - 1);
// take all states since we have filtered
execution_outcome.all_states_mut().take_n_reverts(size - 1);
execution_outcome.set_first_block(block.number);

// If all is okay, return new chain back. Present chain is not modified.
Expand Down Expand Up @@ -180,7 +183,6 @@ impl AppendableChain {
DB: Database + Clone,
E: BlockExecutorProvider,
{
println!("validate_and_execute");
// some checks are done before blocks comes here.
externals.consensus.validate_header_against_parent(&block, parent_block)?;

Expand All @@ -205,7 +207,10 @@ impl AppendableChain {

let provider = BundleStateProvider::new(state_provider, bundle_state_data_provider);

let db = StateProviderDatabase::new(&provider);
let db = SyncStateProviderDatabase::new(
Some(externals.provider_factory.chain_spec().chain.id()),
StateProviderDatabase::new(&provider),
);
let executor = externals.executor_factory.executor(db);
let block_hash = block.hash();
let block = block.unseal();
Expand All @@ -216,25 +221,29 @@ impl AppendableChain {
PostExecutionInput::new(&state.receipts, &state.requests),
)?;

let initial_execution_outcome = ExecutionOutcome::from((state, block.number));
let chain_id = externals.provider_factory.chain_spec().chain.id();
let initial_execution_outcome = ExecutionOutcome::from((state, chain_id, block.number));

// check state root if the block extends the canonical chain __and__ if state root
// validation was requested.
if block_validation_kind.is_exhaustive() {
// calculate and check state root
let start = Instant::now();
let (state_root, trie_updates) = if block_attachment.is_canonical() {
// TODO(Cecilie): refactor the bundle state provider for cross-chain bundles
let mut execution_outcome =
provider.block_execution_data_provider.execution_outcome().clone();
execution_outcome.chain_id = chain_id;
execution_outcome.extend(initial_execution_outcome.clone());
let hashed_state = execution_outcome.hash_state_slow();
ParallelStateRoot::new(consistent_view, hashed_state)
.incremental_root_with_updates()
.map(|(root, updates)| (root, Some(updates)))
.map_err(ProviderError::from)?
} else {
let hashed_state =
HashedPostState::from_bundle_state(&initial_execution_outcome.state().state);
let hashed_state = HashedPostState::from_bundle_state(
&initial_execution_outcome.current_state().state,
);
let state_root = provider.state_root(hashed_state)?;
(state_root, None)
};
Expand Down
9 changes: 7 additions & 2 deletions crates/chain-state/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use reth_primitives::{
Signature, Transaction, TransactionSigned, TransactionSignedEcRecovered, TxEip1559, B256, U256,
};
use reth_trie::{root::state_root_unhashed, updates::TrieUpdates, HashedPostState};
use revm::{db::BundleState, primitives::AccountInfo};
use revm::{
db::BundleState,
primitives::{AccountInfo, ChainAddress},
};
use std::{
collections::HashMap,
ops::Range,
Expand Down Expand Up @@ -207,6 +210,7 @@ impl TestBlockBuilder {
Arc::new(block_with_senders.block.clone()),
Arc::new(block_with_senders.senders),
Arc::new(ExecutionOutcome::new(
None,
BundleState::default(),
receipts,
block_number,
Expand Down Expand Up @@ -271,7 +275,7 @@ impl TestBlockBuilder {
for tx in &block.body {
self.signer_execute_account_info.balance -= Self::single_tx_cost();
bundle_state_builder = bundle_state_builder.state_present_account_info(
self.signer,
ChainAddress(self.chain_spec.chain.id(), self.signer),
AccountInfo {
nonce: tx.nonce(),
balance: self.signer_execute_account_info.balance,
Expand All @@ -281,6 +285,7 @@ impl TestBlockBuilder {
}

let execution_outcome = ExecutionOutcome::new(
None,
bundle_state_builder.build(),
vec![vec![None]].into(),
block.number,
Expand Down
1 change: 0 additions & 1 deletion crates/cli/commands/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ impl<Ext: clap::Args + fmt::Debug> NodeCommand<Ext> {
L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>>>, Ext) -> Fut,
Fut: Future<Output = eyre::Result<()>>,
{
println!("NodeCommand::execute");
tracing::info!(target: "reth::cli", version = ?version::SHORT_VERSION, "Brecht Starting reth");

let Self {
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/commands/src/stage/dump/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use reth_db_api::{
use reth_db_common::DbTool;
use reth_evm::{execute::BlockExecutorProvider, noop::NoopBlockExecutorProvider};
use reth_node_core::dirs::{ChainPath, DataDirPath};
use reth_provider::{providers::StaticFileProvider, ProviderFactory};
use reth_provider::{providers::StaticFileProvider, ProviderFactory, StateProofProvider};
CeciliaZ030 marked this conversation as resolved.
Show resolved Hide resolved
use reth_stages::{stages::ExecutionStage, Stage, StageCheckpoint, UnwindInput};
use tracing::info;

Expand Down
Loading
Loading