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(snapshots): write Headers to snapshots during HeaderStage #6273

Merged
merged 51 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
24b9a1e
write headers to static files during HeaderStage
joshieDo Jan 29, 2024
a7132ea
get sync gap from the snapshot provider
joshieDo Jan 29, 2024
fd32124
insert_genesis_header writes to static files
joshieDo Jan 29, 2024
5f0d4c6
init_genesis takes a ProviderFactory with snapshots instead
joshieDo Jan 29, 2024
3ed71ee
append_header uses CompactU256 for td
joshieDo Jan 29, 2024
290f5da
make sure to commit static file writer on write_headers
joshieDo Jan 29, 2024
eee811f
add some docs related to append_X and increment block
joshieDo Jan 29, 2024
6c50aff
unwind HeaderStage
joshieDo Jan 29, 2024
ad6bb26
clippy
joshieDo Jan 29, 2024
debaca4
calculate_gas_used_from_headers uses static files
joshieDo Jan 30, 2024
489b582
change stages test_db to seed to Header static file instead
joshieDo Jan 30, 2024
c1f5704
Merge remote-tracking branch 'origin/feat/static-files' into feat/hea…
joshieDo Jan 30, 2024
f8cdc93
add warning if mdbx::begin_rw_txn gets stuck waiting rw unlock
joshieDo Jan 31, 2024
3d2514e
fix deadlock
joshieDo Jan 31, 2024
8673d82
fix header test seed_execution and validation
joshieDo Jan 31, 2024
155ce6e
add static file provider to StateProviders
joshieDo Jan 31, 2024
b442fee
get block_hash instead of the whole header
joshieDo Jan 31, 2024
c04e3dc
Merge remote-tracking branch 'origin/feat/static-files' into feat/hea…
joshieDo Jan 31, 2024
c988685
rm totaldifficulty stage file
joshieDo Jan 31, 2024
8873287
clippy
joshieDo Jan 31, 2024
5b20c26
change header_sync_gap_lookup test
joshieDo Jan 31, 2024
cc2adfa
fix auto mine by adding static headers to fetch_latest_canonical_hashes
joshieDo Jan 31, 2024
c186a5e
remove dbg statement
joshieDo Jan 31, 2024
7ddad97
fix range end
joshieDo Jan 31, 2024
78e0ab2
clippy
joshieDo Jan 31, 2024
8890dc9
fix remaining calc
joshieDo Jan 31, 2024
4778948
only check header hashes if static files has any
joshieDo Jan 31, 2024
3fda062
add temporary snapshots path to beacon engine tests
joshieDo Jan 31, 2024
9dcf073
use tempdir from tempfile
joshieDo Feb 1, 2024
e1647ac
enable test-utils for reth-providers on ef-tests
joshieDo Feb 1, 2024
b74b726
fix fail_init_inconsistent_db test
joshieDo Feb 1, 2024
d0a14f1
fix prune test
joshieDo Feb 1, 2024
4b6eb0a
fix prune tests
joshieDo Feb 1, 2024
a201af2
fmt
joshieDo Feb 1, 2024
874ae1c
fix bodies stage tests
joshieDo Feb 1, 2024
4a36762
fix merkle stage tests
joshieDo Feb 1, 2024
ced4432
fix update_index when called on the block start of a range without txs
joshieDo Feb 1, 2024
9b0ff57
fix number of headers to unwind
joshieDo Feb 1, 2024
0088ff1
remove dbg statement
joshieDo Feb 1, 2024
e0668ef
Update crates/stages/src/stages/headers.rs
joshieDo Feb 2, 2024
13382ce
Merge remote-tracking branch 'origin/feat/static-files' into feat/hea…
shekhirin Feb 2, 2024
94c6d16
fix snapshotter test
shekhirin Feb 2, 2024
132bd00
make sure we delete the data when pruning all blocks from the first b…
joshieDo Feb 5, 2024
483ae7f
no need for &mut self on rows
joshieDo Feb 5, 2024
c29c100
prune len from user header not num_rows
joshieDo Feb 5, 2024
ed4d768
Headers segment should not call increment_block before or after appen…
joshieDo Feb 5, 2024
0210eb9
fix debug_assert on increment block
joshieDo Feb 5, 2024
f6a8b5e
temporary/ci: comment fsync
joshieDo Feb 5, 2024
05ad35e
Revert "temporary/ci: comment fsync"
joshieDo Feb 5, 2024
b2dfb31
add insert_historical_block
joshieDo Feb 5, 2024
6c515f5
clippy
joshieDo Feb 5, 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
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion bin/reth/src/commands/debug_cmd/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ impl Command {
ProviderFactory::new(db.clone(), self.chain.clone(), data_dir.snapshots_path())?;

debug!(target: "reth::cli", chain=%self.chain.chain, genesis=?self.chain.genesis_hash(), "Initializing genesis");
init_genesis(provider_factory.clone(), self.chain.clone())?;
init_genesis(provider_factory.clone())?;

let consensus: Arc<dyn Consensus> = Arc::new(BeaconConsensus::new(Arc::clone(&self.chain)));

Expand Down
13 changes: 7 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 @@ -19,9 +19,8 @@ use reth_network::NetworkHandle;
use reth_network_api::NetworkInfo;
use reth_primitives::{fs, stage::StageId, BlockHashOrNumber, ChainSpec};
use reth_provider::{
AccountExtReader, BlockWriter, ExecutorFactory, HashingWriter, HeaderProvider,
LatestStateProviderRef, OriginalValuesKnown, ProviderFactory, StageCheckpointReader,
StorageReader,
AccountExtReader, ExecutorFactory, HashingWriter, HeaderProvider, LatestStateProviderRef,
OriginalValuesKnown, ProviderFactory, StageCheckpointReader, StorageReader,
};
use reth_tasks::TaskExecutor;
use reth_trie::{hashed_cursor::HashedPostStateCursorFactory, updates::TrieKey, StateRoot};
Expand Down Expand Up @@ -167,8 +166,10 @@ impl Command {
.await?;

let executor_factory = reth_revm::EvmProcessorFactory::new(self.chain.clone());
let mut executor =
executor_factory.with_state(LatestStateProviderRef::new(provider.tx_ref()));
let mut executor = executor_factory.with_state(LatestStateProviderRef::new(
provider.tx_ref(),
factory.snapshot_provider(),
));

let merkle_block_td =
provider.header_td_by_number(merkle_block_number)?.unwrap_or_default();
Expand Down Expand Up @@ -201,7 +202,7 @@ impl Command {
let provider_rw = factory.provider_rw()?;

// Insert block, state and hashes
provider_rw.insert_block(
provider_rw.insert_historical_block(
block
.clone()
.try_seal_with_senders()
Expand Down
2 changes: 1 addition & 1 deletion bin/reth/src/commands/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl ImportCommand {

debug!(target: "reth::cli", chain=%self.chain.chain, genesis=?self.chain.genesis_hash(), "Initializing genesis");

init_genesis(provider_factory.clone(), self.chain.clone())?;
init_genesis(provider_factory.clone())?;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is better!!


let consensus = Arc::new(BeaconConsensus::new(self.chain.clone()));
info!(target: "reth::cli", "Consensus engine initialized");
Expand Down
3 changes: 2 additions & 1 deletion bin/reth/src/commands/init_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ impl InitCommand {
ProviderFactory::new(db.clone(), self.chain.clone(), data_dir.snapshots_path())?;

info!(target: "reth::cli", "Writing genesis block");
let hash = init_genesis(provider_factory, self.chain)?;

let hash = init_genesis(provider_factory)?;

info!(target: "reth::cli", hash = ?hash, "Genesis block written");
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion bin/reth/src/commands/recover/storage_tries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl Command {
let factory = ProviderFactory::new(&db, self.chain.clone(), data_dir.snapshots_path())?;

debug!(target: "reth::cli", chain=%self.chain.chain, genesis=?self.chain.genesis_hash(), "Initializing genesis");
init_genesis(factory.clone(), self.chain.clone())?;
init_genesis(factory.clone())?;

let mut provider = factory.provider_rw()?;
let best_block = provider.best_block_number()?;
Expand Down
7 changes: 4 additions & 3 deletions bin/reth/src/commands/stage/drop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ impl Command {
open_db(db_path.as_ref(), DatabaseArguments::default().log_level(self.db.log_level))?;
let provider_factory =
ProviderFactory::new(db, self.chain.clone(), data_dir.snapshots_path())?;
let snapshot_provider = provider_factory.snapshot_provider();

let tool = DbTool::new(provider_factory, self.chain.clone())?;

Expand All @@ -74,7 +75,7 @@ impl Command {
tx.clear::<tables::BlockOmmers>()?;
tx.clear::<tables::BlockWithdrawals>()?;
tx.put::<tables::SyncStage>(StageId::Bodies.to_string(), Default::default())?;
insert_genesis_header::<DatabaseEnv>(tx, self.chain)?;
insert_genesis_header::<DatabaseEnv>(tx, snapshot_provider, self.chain)?;
}
StageEnum::Senders => {
tx.clear::<tables::TxSenders>()?;
Expand Down Expand Up @@ -159,15 +160,15 @@ impl Command {
StageId::TotalDifficulty.to_string(),
Default::default(),
)?;
insert_genesis_header::<DatabaseEnv>(tx, self.chain)?;
insert_genesis_header::<DatabaseEnv>(tx, snapshot_provider, self.chain)?;
}
StageEnum::TxLookup => {
tx.clear::<tables::TxHashNumber>()?;
tx.put::<tables::SyncStage>(
StageId::TransactionLookup.to_string(),
Default::default(),
)?;
insert_genesis_header::<DatabaseEnv>(tx, self.chain)?;
insert_genesis_header::<DatabaseEnv>(tx, snapshot_provider, self.chain)?;
}
_ => {
info!("Nothing to do for stage {:?}", self.stage);
Expand Down
2 changes: 1 addition & 1 deletion crates/blockchain-tree/src/blockchain_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1288,7 +1288,7 @@ mod tests {
let provider = factory.provider_rw().unwrap();

provider
.insert_block(
.insert_historical_block(
genesis.try_seal_with_senders().expect("invalid tx signature in genesis"),
None,
)
Expand Down
32 changes: 27 additions & 5 deletions crates/blockchain-tree/src/externals.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! Blockchain tree externals.

use reth_db::{cursor::DbCursorRO, database::Database, tables, transaction::DbTx};
use reth_db::{
cursor::DbCursorRO, database::Database, snapshot::HeaderMask, tables, transaction::DbTx,
};
use reth_interfaces::{consensus::Consensus, RethResult};
use reth_primitives::{BlockHash, BlockNumber};
use reth_provider::ProviderFactory;
use reth_primitives::{BlockHash, BlockNumber, SnapshotSegment};
use reth_provider::{ProviderFactory, StatsReader};
use std::{collections::BTreeMap, sync::Arc};

/// A container for external components.
Expand Down Expand Up @@ -44,13 +46,33 @@ impl<DB: Database, EF> TreeExternals<DB, EF> {
&self,
num_hashes: usize,
) -> RethResult<BTreeMap<BlockNumber, BlockHash>> {
Ok(self
let mut hashes = self
.provider_factory
.provider()?
.tx_ref()
.cursor_read::<tables::CanonicalHeaders>()?
.walk_back(None)?
.take(num_hashes)
.collect::<Result<BTreeMap<BlockNumber, BlockHash>, _>>()?)
.collect::<Result<BTreeMap<BlockNumber, BlockHash>, _>>()?;

if hashes.len() < num_hashes {
let snapshot_provider = self.provider_factory.snapshot_provider();
let total_headers = snapshot_provider.count_entries::<tables::Headers>()? as u64;
if total_headers > 0 {
Copy link
Member

@onbjerg onbjerg Feb 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm this is ok for now, i'd add a comment on what this is doing, but ideally the switch between fetching from db vs snapshots would be a bit more transparent 😬

let range = total_headers
.saturating_sub(1)
.saturating_sub((num_hashes - hashes.len()) as u64)..
total_headers;

hashes.extend(range.clone().zip(snapshot_provider.fetch_range_with_predicate(
SnapshotSegment::Headers,
range,
|cursor, number| cursor.get_one::<HeaderMask<BlockHash>>(number.into()),
|_| true,
)?));
}
}

Ok(hashes)
}
}
1 change: 1 addition & 0 deletions crates/consensus/beacon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ reth-downloaders.workspace = true
reth-node-builder.workspace = true

assert_matches.workspace = true
tempfile.workspace = true

[features]
optimism = [
Expand Down
8 changes: 4 additions & 4 deletions crates/consensus/common/src/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ pub fn validate_block_standalone(

// Check transaction root
if let Err(error) = block.ensure_transaction_root_valid() {
return Err(ConsensusError::BodyTransactionRootDiff(error.into()));
return Err(ConsensusError::BodyTransactionRootDiff(error.into()))
}

// EIP-4895: Beacon chain push withdrawals as operations
Expand Down Expand Up @@ -280,19 +280,19 @@ fn check_gas_limit(
return Err(ConsensusError::GasLimitInvalidIncrease {
parent_gas_limit,
child_gas_limit: child.gas_limit,
});
})
}
}
// Check for a decrease in gas limit beyond the allowed threshold.
else if parent_gas_limit - child.gas_limit >= parent_gas_limit / 1024 {
return Err(ConsensusError::GasLimitInvalidDecrease {
parent_gas_limit,
child_gas_limit: child.gas_limit,
});
})
}
// Check if the child gas limit is below the minimum required limit.
else if child.gas_limit < MINIMUM_GAS_LIMIT {
return Err(ConsensusError::GasLimitInvalidMinimum { child_gas_limit: child.gas_limit });
return Err(ConsensusError::GasLimitInvalidMinimum { child_gas_limit: child.gas_limit })
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion crates/ethereum-forks/src/hardfork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl Hardfork {
/// Retrieves the activation block for the specified hardfork on the Ethereum mainnet.
pub fn mainnet_activation_block(&self, chain: Chain) -> Option<u64> {
if chain != Chain::mainnet() {
return None;
return None
}
match self {
Hardfork::Frontier => Some(0),
Expand Down
2 changes: 1 addition & 1 deletion crates/etl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ impl EtlFile {
/// Can return error if it reaches EOF before filling the internal buffers.
pub(crate) fn read_next(&mut self) -> std::io::Result<Option<(Vec<u8>, Vec<u8>)>> {
if self.len == 0 {
return Ok(None);
return Ok(None)
}

let mut buffer_key_length = [0; 8];
Expand Down
2 changes: 1 addition & 1 deletion crates/net/network/src/transactions/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ impl TransactionFetcher {
);

max_retried_hashes.push(hash);
continue;
continue
}
*retries += 1;
}
Expand Down
Loading
Loading