Skip to content

Commit b13d9e3

Browse files
committed
opt(state root) compact trie node serialization and remove comptiable trie updates
1 parent 79c6bfb commit b13d9e3

18 files changed

Lines changed: 221 additions & 361 deletions

File tree

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/engine/tree/src/persistence.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use reth_primitives_traits::NodePrimitives;
88
use reth_provider::{
99
providers::ProviderNodeTypes, writer::UnifiedStorageWriter, BlockHashReader,
1010
ChainStateBlockWriter, DatabaseProviderFactory, ProviderFactory, StaticFileProviderFactory,
11+
PERSIST_BLOCK_CACHE,
1112
};
1213
use reth_prune::{PrunerError, PrunerOutput, PrunerWithFactory};
1314
use reth_stages_api::{MetricEvent, MetricEventsSender};
@@ -151,12 +152,13 @@ where
151152
});
152153

153154
let num_blocks = blocks.len();
154-
if last_block_hash_num.is_some() {
155+
if let Some(last_block_hn) = &last_block_hash_num {
155156
let provider_rw = self.provider.database_provider_rw()?;
156157
let static_file_provider = self.provider.static_file_provider();
157158

158159
UnifiedStorageWriter::from(&provider_rw, &static_file_provider).save_blocks(blocks)?;
159160
UnifiedStorageWriter::commit(provider_rw)?;
161+
PERSIST_BLOCK_CACHE.persist_tip(last_block_hn.number);
160162
}
161163
let elapsed = start_time.elapsed();
162164
self.metrics.save_blocks_duration_seconds.record(elapsed);

crates/gravity-primitives/src/config.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,13 @@ pub struct Config {
99
pub disable_pipe_execution: bool,
1010
/// Whether to disable the Grevm executor. default true.
1111
pub disable_grevm: bool,
12-
/// Whether compatible with trie output. default false.
13-
pub compatible_trie_output: bool,
1412
}
1513

1614
/// Global configuration instance, initialized lazily.
1715
pub static CONFIG: LazyLock<Config> = LazyLock::new(|| {
1816
let config = Config {
1917
disable_pipe_execution: std::env::var("GRETH_DISABLE_PIPE_EXECUTION").is_ok(),
2018
disable_grevm: std::env::var("GRETH_DISABLE_GREVM").is_ok(),
21-
compatible_trie_output: std::env::var("COMPATIBLE_TRIE_OUTPUT")
22-
.ok()
23-
.and_then(|v| v.parse().ok())
24-
.unwrap_or(false),
2519
};
2620
println!("Gravity Reth config: {config:#?}");
2721
config

crates/gravity-storage/src/block_view_storage/mod.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,7 @@ use reth_revm::{
1010
state::AccountInfo, DatabaseRef,
1111
};
1212
use reth_storage_api::StateProviderFactory;
13-
use reth_trie::{
14-
updates::{TrieUpdates, TrieUpdatesV2},
15-
HashedPostState,
16-
};
13+
use reth_trie::{updates::TrieUpdatesV2, HashedPostState};
1714
use reth_trie_parallel::nested_hash::NestedStateRoot;
1815
use std::{collections::BTreeMap, sync::Mutex};
1916

@@ -58,14 +55,10 @@ where
5855
Ok(BlockViewProvider::new(StateProviderDatabase::new(state), Some(self.cache.clone())))
5956
}
6057

61-
fn state_root(
62-
&self,
63-
hashed_state: &HashedPostState,
64-
compatible: bool,
65-
) -> ProviderResult<(B256, TrieUpdatesV2, Option<TrieUpdates>)> {
58+
fn state_root(&self, hashed_state: &HashedPostState) -> ProviderResult<(B256, TrieUpdatesV2)> {
6659
let provider = || self.client.database_provider_ro().map(|db| db.into_tx());
6760
let nested_hash = NestedStateRoot::new(provider, Some(self.cache.clone()));
68-
nested_hash.calculate(hashed_state, compatible)
61+
nested_hash.calculate(hashed_state)
6962
}
7063

7164
fn insert_block_id(&self, block_number: u64, block_id: B256) {

crates/gravity-storage/src/lib.rs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ pub mod block_view_storage;
66
use alloy_primitives::B256;
77
use reth_evm::ParallelDatabase;
88
use reth_provider::ProviderResult;
9-
use reth_trie::{
10-
updates::{TrieUpdates, TrieUpdatesV2},
11-
HashedPostState,
12-
};
9+
use reth_trie::{updates::TrieUpdatesV2, HashedPostState};
1310

1411
/// Gravity storage for pipeline execution
1512
pub trait GravityStorage: Send + Sync + 'static {
@@ -20,11 +17,7 @@ pub trait GravityStorage: Send + Sync + 'static {
2017
fn get_state_view(&self) -> ProviderResult<Self::StateView>;
2118

2219
/// calculate state root
23-
fn state_root(
24-
&self,
25-
hashed_state: &HashedPostState,
26-
compatible: bool,
27-
) -> ProviderResult<(B256, TrieUpdatesV2, Option<TrieUpdates>)>;
20+
fn state_root(&self, hashed_state: &HashedPostState) -> ProviderResult<(B256, TrieUpdatesV2)>;
2821

2922
/// Insert the mapping from `block_number` to `block_id`
3023
fn insert_block_id(&self, block_number: u64, block_id: B256);

crates/pipe-exec-layer-ext-v2/execute/src/lib.rs

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ use tokio::sync::{
5353
oneshot, Mutex,
5454
};
5555

56-
use gravity_primitives::CONFIG;
5756
use reth_trie::{HashedPostState, KeccakKeyHasher};
5857
use tracing::*;
5958

@@ -333,8 +332,7 @@ impl<Storage: GravityStorage> Core<Storage> {
333332
// Merkling the state trie
334333
self.merklize_barrier.wait(block_number - 1).await.unwrap();
335334
let start_time = Instant::now();
336-
let (state_root, trie_updates, compatible_trie_pudates) =
337-
self.storage.state_root(&hashed_state, CONFIG.compatible_trie_output).unwrap();
335+
let (state_root, trie_updates) = self.storage.state_root(&hashed_state).unwrap();
338336
let write_start = Instant::now();
339337
self.cache.write_trie_updates(&trie_updates, block_number);
340338
self.metrics.cache_trie_state.record(write_start.elapsed());
@@ -367,23 +365,13 @@ impl<Storage: GravityStorage> Core<Storage> {
367365
);
368366

369367
let gas_used = sealed_block.gas_used;
370-
let executed_block = if let Some(compatible_trie_updates) = compatible_trie_pudates {
371-
ExecutedBlockWithTrieUpdates::new(
372-
Arc::new(RecoveredBlock::new_sealed(sealed_block, senders)),
373-
Arc::new(execution_outcome),
374-
Arc::new(hashed_state),
375-
ExecutedTrieUpdates::Present(Arc::new(compatible_trie_updates)),
376-
Arc::new(trie_updates),
377-
)
378-
} else {
379-
ExecutedBlockWithTrieUpdates::new(
380-
Arc::new(RecoveredBlock::new_sealed(sealed_block, senders)),
381-
Arc::new(execution_outcome),
382-
Arc::new(hashed_state),
383-
ExecutedTrieUpdates::empty(),
384-
Arc::new(trie_updates),
385-
)
386-
};
368+
let executed_block = ExecutedBlockWithTrieUpdates::new(
369+
Arc::new(RecoveredBlock::new_sealed(sealed_block, senders)),
370+
Arc::new(execution_outcome),
371+
Arc::new(hashed_state),
372+
ExecutedTrieUpdates::empty(),
373+
Arc::new(trie_updates),
374+
);
387375
let execution_result =
388376
ExecutionResult { block_id, block_number, block_hash, txs_info, gravity_events };
389377

crates/pipe-exec-layer-ext-v2/execute/tests/pipe_test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ async fn run_pipe(
145145
let nested_provider = || provider.database_provider_ro().map(|db| db.into_tx());
146146
let nested_hash = NestedStateRoot::new(nested_provider, None);
147147
let hashed_state = nested_hash.read_hashed_state(None).unwrap();
148-
let (root_hash, trie_updates, _) = nested_hash.calculate(&hashed_state, false).unwrap();
148+
let (root_hash, trie_updates) = nested_hash.calculate(&hashed_state).unwrap();
149149
let trie_write = provider.database_provider_rw().unwrap();
150150
trie_write.write_trie_updatesv2(&trie_updates).unwrap();
151151
UnifiedStorageWriter::commit_unwind(trie_write)?;

crates/stages/stages/src/stages/merkle.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@ use reth_db_api::{
88
};
99
use reth_primitives_traits::{GotExpected, SealedHeader};
1010
use reth_provider::{
11-
DBProvider, HeaderProvider, ProviderError, StageCheckpointReader, StageCheckpointWriter,
12-
StatsReader, TrieWriter, TrieWriterV2, EXECUTION_MERKLE_CHANNEL,
11+
DBProvider, HeaderProvider, PersistBlockCache, ProviderError, StageCheckpointReader,
12+
StageCheckpointWriter, StatsReader, TrieWriter, TrieWriterV2, EXECUTION_MERKLE_CHANNEL,
13+
PERSIST_BLOCK_CACHE,
1314
};
1415
use reth_stages_api::{
1516
BlockErrorKind, BoxedConcurrentProvider, EntitiesCheckpoint, ExecInput, ExecOutput,
@@ -197,16 +198,21 @@ where
197198
(target_block_root, input.checkpoint().entities_stage_checkpoint().unwrap_or_default())
198199
} else {
199200
debug!(target: "sync::stages::merkle::exec", current = ?current_block_number, target = ?to_block, "Updating trie in chunks");
201+
let cache: PersistBlockCache = PERSIST_BLOCK_CACHE.clone();
200202
// Use optimized nested hash algorithm for state root calculation
201-
let nested_state_root = NestedStateRoot::new(
202-
|| provider_ro().map(|db| db.into_tx()),
203-
None, // No cache for history sync
204-
);
203+
let nested_state_root =
204+
NestedStateRoot::new(|| provider_ro().map(|db| db.into_tx()), Some(cache.clone()));
205205
// Read the hashed state from database for the specified range
206-
let hashed_state = EXECUTION_MERKLE_CHANNEL.consume(from_block);
207-
let (final_root, trie_updates_v2, _compatible_updates) =
208-
nested_state_root.calculate(&hashed_state, false)?;
206+
let hashed_state =
207+
if let Some(hashed_state) = EXECUTION_MERKLE_CHANNEL.consume(from_block) {
208+
hashed_state
209+
} else {
210+
nested_state_root.read_hashed_state(Some(range))?
211+
};
212+
let (final_root, trie_updates_v2) = nested_state_root.calculate(&hashed_state)?;
213+
cache.write_trie_updates(&trie_updates_v2, to_block);
209214
provider.write_trie_updatesv2(&trie_updates_v2)?;
215+
cache.persist_tip(to_block);
210216

211217
let total_hashed_entries = (provider.count_entries::<tables::HashedAccounts>()? +
212218
provider.count_entries::<tables::HashedStorages>()?)
@@ -278,8 +284,7 @@ where
278284
let nested_state_root =
279285
NestedStateRoot::new(|| provider_ro().map(|db| db.into_tx()), None);
280286
let hashed_state = nested_state_root.read_hashed_state(Some(range))?;
281-
let (block_root, trie_updates_v2, _compatible_updates) =
282-
nested_state_root.calculate(&hashed_state, false)?;
287+
let (block_root, trie_updates_v2) = nested_state_root.calculate(&hashed_state)?;
283288

284289
// Validate the calculated state root
285290
let target = provider

crates/storage/db-common/src/init.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ where
329329
}
330330
let hashed_state = HashedPostState { accounts, storages };
331331
let nested_hash = NestedStateRoot::new(provider, None);
332-
let (root_hash, trie_updates, _) = nested_hash.calculate(&hashed_state, false)?;
332+
let (root_hash, trie_updates) = nested_hash.calculate(&hashed_state)?;
333333

334334
writer.write_trie_updatesv2(&trie_updates)?;
335335
info!(target: "reth::cli",

crates/storage/provider/src/writer/mod.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
providers::{StaticFileProvider, StaticFileWriter as SfWriter},
33
BlockExecutionWriter, BlockWriter, HistoryWriter, StateWriter, StaticFileProviderFactory,
4-
StorageLocation, TrieWriter, TrieWriterV2, PERSIST_BLOCK_CACHE,
4+
StorageLocation, TrieWriter, TrieWriterV2,
55
};
66
use alloy_consensus::BlockHeader;
77
use reth_chain_state::{ExecutedBlock, ExecutedBlockWithTrieUpdates};
@@ -167,7 +167,6 @@ where
167167
triev2,
168168
} in blocks
169169
{
170-
let block_number = recovered_block.number();
171170
let block_hash = recovered_block.hash();
172171

173172
#[cfg(not(feature = "pipe_test"))]
@@ -188,7 +187,6 @@ where
188187
trie.as_ref().ok_or(ProviderError::MissingTrieUpdates(block_hash))?,
189188
)?;
190189
let _ = self.database().write_trie_updatesv2(triev2.as_ref())?;
191-
PERSIST_BLOCK_CACHE.persist_tip(block_number);
192190
}
193191

194192
// update history indices

0 commit comments

Comments
 (0)