Skip to content

Commit

Permalink
feat: add block_body_indices for BlockchainProvider2 (#10106)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rjected authored Aug 7, 2024
1 parent e199173 commit a706206
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
2 changes: 1 addition & 1 deletion crates/chain-state/src/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ impl CanonicalInMemoryState {
Self { inner: Arc::new(inner) }
}

/// Returns the block hash corresponding to the given number
/// Returns the block hash corresponding to the given number.
pub fn hash_by_number(&self, number: u64) -> Option<B256> {
self.inner.in_memory_state.hash_by_number(number)
}
Expand Down
5 changes: 4 additions & 1 deletion crates/storage/errors/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,11 @@ pub enum ProviderError {
#[error("unknown block {0}")]
UnknownBlockHash(B256),
/// Thrown when we were unable to find a state for a block hash.
#[error("no state found for block {0}")]
#[error("no state found for block hash {0}")]
StateForHashNotFound(B256),
/// Thrown when we were unable to find a state for a block number.
#[error("no state found for block number {0}")]
StateForNumberNotFound(u64),
/// Unable to find the block number for a given transaction index.
#[error("unable to find the block number for a given transaction index")]
BlockNumberForTransactionIndexNotFound,
Expand Down
29 changes: 28 additions & 1 deletion crates/storage/provider/src/providers/blockchain_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,34 @@ where
&self,
number: BlockNumber,
) -> ProviderResult<Option<StoredBlockBodyIndices>> {
self.database.block_body_indices(number)
if let Some(indices) = self.database.block_body_indices(number)? {
Ok(Some(indices))
} else if let Some(state) = self.canonical_in_memory_state.state_by_number(number) {
// we have to construct the stored indices for the in memory blocks
//
// To calculate this we will fetch the anchor block and walk forward from all parents
let mut parent_chain = state.parent_state_chain();
parent_chain.reverse();
let anchor_num = state.anchor().number;
let mut stored_indices = self
.database
.block_body_indices(anchor_num)?
.ok_or_else(|| ProviderError::BlockBodyIndicesNotFound(anchor_num))?;
stored_indices.first_tx_num = stored_indices.next_tx_num();

for state in parent_chain {
let txs = state.block().block.body.len() as u64;
if state.block().block().number == number {
stored_indices.tx_count = txs;
} else {
stored_indices.first_tx_num += txs;
}
}

Ok(Some(stored_indices))
} else {
Ok(None)
}
}

/// Returns the block with senders with matching number or hash from database.
Expand Down

0 comments on commit a706206

Please sign in to comment.