reth_chain_state/in_memory/executed_block.rs
1use alloy_consensus::BlockHeader;
2use alloy_primitives::BlockNumber;
3use reth_ethereum_primitives::EthPrimitives;
4use reth_execution_types::{BlockExecutionOutput, BlockExecutionResult, DecodedEvmBal};
5use reth_primitives_traits::{NodePrimitives, RecoveredBlock, SealedBlock};
6use reth_trie::{updates::TrieUpdatesSorted, HashedPostStateSorted, LazyTrieData, SortedTrieData};
7use std::sync::Arc;
8
9/// Represents an executed block stored in-memory.
10#[derive(Clone, Debug)]
11pub struct ExecutedBlock<N: NodePrimitives = EthPrimitives> {
12 /// Recovered Block
13 pub recovered_block: Arc<RecoveredBlock<N::Block>>,
14 /// Block's execution outcome.
15 pub execution_output: Arc<BlockExecutionOutput<N::Receipt>>,
16 /// Deferred trie data produced by execution.
17 ///
18 /// This allows deferring the computation of the trie data which can be expensive.
19 /// The data can be populated asynchronously after the block was validated.
20 pub trie_data: LazyTrieData,
21 /// The prepared block access list of the block, if one is available.
22 ///
23 /// `None` means no BAL was available when the block was constructed, not that the block
24 /// has none: only blocks the engine validated from a payload that carried a BAL have it
25 /// attached. Blocks from before the BAL fork, blocks built or loaded outside engine
26 /// validation (payload builder, persistence, tests) and downloaded blocks without a BAL
27 /// sidecar leave it unset; the BAL store is the source of truth in that case.
28 ///
29 /// When present, this carries the raw RLP (for the BAL store) together with the evm2
30 /// representation (for consumers like the RPC state cache), so that neither has to be
31 /// re-derived after validation.
32 pub bal: Option<Arc<DecodedEvmBal>>,
33}
34
35impl<N: NodePrimitives> Default for ExecutedBlock<N> {
36 fn default() -> Self {
37 Self {
38 recovered_block: Default::default(),
39 execution_output: Arc::new(BlockExecutionOutput {
40 result: BlockExecutionResult {
41 receipts: Default::default(),
42 requests: Default::default(),
43 gas_used: 0,
44 blob_gas_used: 0,
45 },
46 state: Default::default(),
47 }),
48 trie_data: LazyTrieData::ready(SortedTrieData::default()),
49 bal: None,
50 }
51 }
52}
53
54impl<N: NodePrimitives> PartialEq for ExecutedBlock<N> {
55 fn eq(&self, other: &Self) -> bool {
56 // Trie data is computed asynchronously and the block access list is derived data; neither
57 // defines block identity.
58 self.recovered_block == other.recovered_block &&
59 self.execution_output == other.execution_output
60 }
61}
62
63impl<N: NodePrimitives> ExecutedBlock<N> {
64 /// Create a new [`ExecutedBlock`] with already-computed trie data.
65 ///
66 /// Use this constructor when trie data is available immediately (e.g., sequencers,
67 /// payload builders). This is the safe default path.
68 pub fn new(
69 recovered_block: Arc<RecoveredBlock<N::Block>>,
70 execution_output: Arc<BlockExecutionOutput<N::Receipt>>,
71 trie_data: SortedTrieData,
72 ) -> Self {
73 Self {
74 recovered_block,
75 execution_output,
76 trie_data: LazyTrieData::ready(trie_data),
77 bal: None,
78 }
79 }
80
81 /// Create a new [`ExecutedBlock`] with deferred trie data.
82 ///
83 /// This is useful if the trie data is populated somewhere else, e.g. asynchronously
84 /// after the block was validated.
85 ///
86 /// The [`LazyTrieData`] handle allows expensive trie operations (sorting hashed state and
87 /// trie updates) to be performed outside the critical validation path by a background task.
88 /// This can improve latency for time-sensitive operations like block validation.
89 ///
90 /// If the data hasn't been populated when [`Self::trie_data()`] is called, the caller waits
91 /// for the background task to publish it.
92 ///
93 /// Use [`Self::new()`] instead when trie data is already computed and available immediately.
94 pub const fn with_deferred_trie_data(
95 recovered_block: Arc<RecoveredBlock<N::Block>>,
96 execution_output: Arc<BlockExecutionOutput<N::Receipt>>,
97 trie_data: LazyTrieData,
98 ) -> Self {
99 Self { recovered_block, execution_output, trie_data, bal: None }
100 }
101
102 /// Attaches the prepared block access list of the block, or clears it with `None`.
103 pub fn with_bal(mut self, bal: Option<Arc<DecodedEvmBal>>) -> Self {
104 self.bal = bal;
105 self
106 }
107
108 /// Returns the prepared block access list of the block, if one is available.
109 ///
110 /// `None` only means no BAL was attached to this block; see the `bal` field for details.
111 #[inline]
112 pub const fn bal(&self) -> Option<&Arc<DecodedEvmBal>> {
113 self.bal.as_ref()
114 }
115
116 /// Returns a reference to an inner [`SealedBlock`]
117 #[inline]
118 pub fn sealed_block(&self) -> &SealedBlock<N::Block> {
119 self.recovered_block.sealed_block()
120 }
121
122 /// Returns a reference to [`RecoveredBlock`]
123 #[inline]
124 pub fn recovered_block(&self) -> &RecoveredBlock<N::Block> {
125 &self.recovered_block
126 }
127
128 /// Returns a reference to the block's execution outcome
129 #[inline]
130 pub fn execution_outcome(&self) -> &BlockExecutionOutput<N::Receipt> {
131 &self.execution_output
132 }
133
134 /// Returns the trie data, waiting for the background task if not already cached.
135 ///
136 /// Uses `OnceLock::get_or_init` internally:
137 /// - If already computed: returns cached result immediately
138 /// - If not computed: first caller waits for the publishing task, others wait for that result
139 #[inline]
140 #[tracing::instrument(level = "debug", target = "engine::tree", name = "trie_data", skip_all)]
141 pub fn trie_data(&self) -> SortedTrieData {
142 self.trie_data.get().clone()
143 }
144
145 /// Returns a clone of the deferred trie data handle.
146 ///
147 /// A handle is a lightweight reference that can be passed to descendants without
148 /// forcing trie data to be observed immediately. The actual work runs in the background task.
149 #[inline]
150 pub fn trie_data_handle(&self) -> LazyTrieData {
151 self.trie_data.clone()
152 }
153
154 /// Returns the hashed state result of the execution outcome.
155 ///
156 /// May wait for trie data if the deferred task hasn't completed.
157 #[inline]
158 pub fn hashed_state(&self) -> Arc<HashedPostStateSorted> {
159 self.trie_data().hashed_state
160 }
161
162 /// Returns a reference to the hashed state result of the execution outcome.
163 ///
164 /// May wait for trie data if the deferred task hasn't completed.
165 #[inline]
166 pub fn hashed_state_ref(&self) -> &HashedPostStateSorted {
167 &self.trie_data.get().hashed_state
168 }
169
170 /// Returns references to the hashed state results of the executed blocks.
171 ///
172 /// May wait for trie data if any deferred task hasn't completed.
173 pub fn hashed_state_refs(blocks: &[Self]) -> Vec<&HashedPostStateSorted> {
174 blocks.iter().map(Self::hashed_state_ref).collect()
175 }
176
177 /// Returns the trie updates resulting from the execution outcome.
178 ///
179 /// May wait for trie data if the deferred task hasn't completed.
180 #[inline]
181 pub fn trie_updates(&self) -> Arc<TrieUpdatesSorted> {
182 self.trie_data().trie_updates
183 }
184
185 /// Returns a reference to the trie updates resulting from the execution outcome.
186 ///
187 /// May wait for trie data if the deferred task hasn't completed.
188 #[inline]
189 pub fn trie_updates_ref(&self) -> &TrieUpdatesSorted {
190 &self.trie_data.get().trie_updates
191 }
192
193 /// Returns references to the trie updates of the executed blocks.
194 ///
195 /// May wait for trie data if any deferred task hasn't completed.
196 pub fn trie_updates_refs(blocks: &[Self]) -> Vec<&TrieUpdatesSorted> {
197 blocks.iter().map(Self::trie_updates_ref).collect()
198 }
199
200 /// Returns a [`BlockNumber`] of the block.
201 #[inline]
202 pub fn block_number(&self) -> BlockNumber {
203 self.recovered_block.header().number()
204 }
205}