primitives: use SealedHeader::seal (#12507)

This commit is contained in:
Thomas Coratger
2024-11-13 13:41:56 +01:00
committed by GitHub
parent 527767cc34
commit 9313737dbb
32 changed files with 108 additions and 277 deletions

View File

@ -1377,7 +1377,7 @@ mod tests {
use alloy_consensus::{TxEip1559, EMPTY_ROOT_HASH}; use alloy_consensus::{TxEip1559, EMPTY_ROOT_HASH};
use alloy_eips::{eip1559::INITIAL_BASE_FEE, eip4895::Withdrawals}; use alloy_eips::{eip1559::INITIAL_BASE_FEE, eip4895::Withdrawals};
use alloy_genesis::{Genesis, GenesisAccount}; use alloy_genesis::{Genesis, GenesisAccount};
use alloy_primitives::{keccak256, Address, PrimitiveSignature as Signature, Sealable, B256}; use alloy_primitives::{keccak256, Address, PrimitiveSignature as Signature, B256};
use assert_matches::assert_matches; use assert_matches::assert_matches;
use linked_hash_set::LinkedHashSet; use linked_hash_set::LinkedHashSet;
use reth_chainspec::{ChainSpecBuilder, MAINNET, MIN_TRANSACTION_GAS}; use reth_chainspec::{ChainSpecBuilder, MAINNET, MIN_TRANSACTION_GAS};
@ -1598,7 +1598,7 @@ mod tests {
// receipts root computation is different for OP // receipts root computation is different for OP
let receipts_root = calculate_receipt_root(&receipts); let receipts_root = calculate_receipt_root(&receipts);
let sealed = Header { let header = Header {
number, number,
parent_hash: parent.unwrap_or_default(), parent_hash: parent.unwrap_or_default(),
gas_used: body.len() as u64 * MIN_TRANSACTION_GAS, gas_used: body.len() as u64 * MIN_TRANSACTION_GAS,
@ -1620,13 +1620,11 @@ mod tests {
), ),
)])), )])),
..Default::default() ..Default::default()
} };
.seal_slow();
let (header, seal) = sealed.into_parts();
SealedBlockWithSenders::new( SealedBlockWithSenders::new(
SealedBlock { SealedBlock {
header: SealedHeader::new(header, seal), header: SealedHeader::seal(header),
body: BlockBody { body: BlockBody {
transactions: body.clone().into_iter().map(|tx| tx.into_signed()).collect(), transactions: body.clone().into_iter().map(|tx| tx.into_signed()).collect(),
ommers: Vec::new(), ommers: Vec::new(),

View File

@ -4,7 +4,7 @@ use crate::{
}; };
use alloy_consensus::{Transaction as _, TxEip1559, EMPTY_ROOT_HASH}; use alloy_consensus::{Transaction as _, TxEip1559, EMPTY_ROOT_HASH};
use alloy_eips::{eip1559::INITIAL_BASE_FEE, eip7685::Requests}; use alloy_eips::{eip1559::INITIAL_BASE_FEE, eip7685::Requests};
use alloy_primitives::{Address, BlockNumber, Sealable, B256, U256}; use alloy_primitives::{Address, BlockNumber, B256, U256};
use alloy_signer::SignerSync; use alloy_signer::SignerSync;
use alloy_signer_local::PrivateKeySigner; use alloy_signer_local::PrivateKeySigner;
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
@ -160,11 +160,8 @@ impl TestBlockBuilder {
..Default::default() ..Default::default()
}; };
let sealed = header.seal_slow();
let (header, seal) = sealed.into_parts();
let block = SealedBlock { let block = SealedBlock {
header: SealedHeader::new(header, seal), header: SealedHeader::seal(header),
body: BlockBody { body: BlockBody {
transactions: transactions.into_iter().map(|tx| tx.into_signed()).collect(), transactions: transactions.into_iter().map(|tx| tx.into_signed()).collect(),
ommers: Vec::new(), ommers: Vec::new(),

View File

@ -106,14 +106,12 @@ struct InvalidHeaderCacheMetrics {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use alloy_primitives::Sealable;
#[test] #[test]
fn test_hit_eviction() { fn test_hit_eviction() {
let mut cache = InvalidHeaderCache::new(10); let mut cache = InvalidHeaderCache::new(10);
let sealed = Header::default().seal_slow(); let header = Header::default();
let (header, seal) = sealed.into_parts(); let header = SealedHeader::seal(header);
let header = SealedHeader::new(header, seal);
cache.insert(header.clone()); cache.insert(header.clone());
assert_eq!(cache.headers.get(&header.hash()).unwrap().hit_count, 0); assert_eq!(cache.headers.get(&header.hash()).unwrap().hit_count, 0);

View File

@ -410,7 +410,6 @@ impl<N: ProviderNodeTypes> PipelineState<N> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use alloy_primitives::Sealable;
use assert_matches::assert_matches; use assert_matches::assert_matches;
use futures::poll; use futures::poll;
use reth_chainspec::{ChainSpec, ChainSpecBuilder, MAINNET}; use reth_chainspec::{ChainSpec, ChainSpecBuilder, MAINNET};
@ -599,9 +598,7 @@ mod tests {
header.parent_hash = hash; header.parent_hash = hash;
header.number += 1; header.number += 1;
header.timestamp += 1; header.timestamp += 1;
let sealed = header.seal_slow(); sealed_header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
sealed_header = SealedHeader::new(header, seal);
client.insert(sealed_header.clone(), body.clone()); client.insert(sealed_header.clone(), body.clone());
} }
} }
@ -617,14 +614,12 @@ mod tests {
); );
let client = TestFullBlockClient::default(); let client = TestFullBlockClient::default();
let sealed = Header { let header = Header {
base_fee_per_gas: Some(7), base_fee_per_gas: Some(7),
gas_limit: chain_spec.max_gas_limit, gas_limit: chain_spec.max_gas_limit,
..Default::default() ..Default::default()
} };
.seal_slow(); let header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
let header = SealedHeader::new(header, seal);
insert_headers_into_client(&client, header, 0..10); insert_headers_into_client(&client, header, 0..10);
// set up a pipeline // set up a pipeline

View File

@ -4,7 +4,7 @@ use crate::{
BeaconConsensusEngineError, BeaconConsensusEngineHandle, BeaconForkChoiceUpdateError, BeaconConsensusEngineError, BeaconConsensusEngineHandle, BeaconForkChoiceUpdateError,
BeaconOnNewPayloadError, EthBeaconConsensus, MIN_BLOCKS_FOR_PIPELINE_RUN, BeaconOnNewPayloadError, EthBeaconConsensus, MIN_BLOCKS_FOR_PIPELINE_RUN,
}; };
use alloy_primitives::{BlockNumber, Sealable, B256}; use alloy_primitives::{BlockNumber, B256};
use alloy_rpc_types_engine::{ use alloy_rpc_types_engine::{
ExecutionPayload, ExecutionPayloadSidecar, ForkchoiceState, ForkchoiceUpdated, PayloadStatus, ExecutionPayload, ExecutionPayloadSidecar, ForkchoiceState, ForkchoiceUpdated, PayloadStatus,
}; };
@ -402,9 +402,8 @@ where
BlockchainTree::new(externals, BlockchainTreeConfig::new(1, 2, 3, 2)) BlockchainTree::new(externals, BlockchainTreeConfig::new(1, 2, 3, 2))
.expect("failed to create tree"), .expect("failed to create tree"),
)); ));
let sealed = self.base_config.chain_spec.genesis_header().clone().seal_slow(); let header = self.base_config.chain_spec.genesis_header().clone();
let (header, seal) = sealed.into_parts(); let genesis_block = SealedHeader::seal(header);
let genesis_block = SealedHeader::new(header, seal);
let blockchain_provider = BlockchainProvider::with_blocks( let blockchain_provider = BlockchainProvider::with_blocks(
provider_factory.clone(), provider_factory.clone(),

View File

@ -326,7 +326,7 @@ mod tests {
}; };
use alloy_primitives::{ use alloy_primitives::{
hex_literal::hex, Address, BlockHash, BlockNumber, Bytes, PrimitiveSignature as Signature, hex_literal::hex, Address, BlockHash, BlockNumber, Bytes, PrimitiveSignature as Signature,
Sealable, U256, U256,
}; };
use mockall::mock; use mockall::mock;
use rand::Rng; use rand::Rng;
@ -495,12 +495,9 @@ mod tests {
let ommers = Vec::new(); let ommers = Vec::new();
let transactions = Vec::new(); let transactions = Vec::new();
let sealed = header.seal_slow();
let (header, seal) = sealed.into_parts();
( (
SealedBlock { SealedBlock {
header: SealedHeader::new(header, seal), header: SealedHeader::seal(header),
body: BlockBody { transactions, ommers, withdrawals: None }, body: BlockBody { transactions, ommers, withdrawals: None },
}, },
parent, parent,
@ -519,15 +516,13 @@ mod tests {
.collect(), .collect(),
); );
let sealed = Header { let header = Header {
withdrawals_root: Some(proofs::calculate_withdrawals_root(&withdrawals)), withdrawals_root: Some(proofs::calculate_withdrawals_root(&withdrawals)),
..Default::default() ..Default::default()
} };
.seal_slow();
let (header, seal) = sealed.into_parts();
SealedBlock { SealedBlock {
header: SealedHeader::new(header, seal), header: SealedHeader::seal(header),
body: BlockBody { withdrawals: Some(withdrawals), ..Default::default() }, body: BlockBody { withdrawals: Some(withdrawals), ..Default::default() },
} }
}; };
@ -558,16 +553,14 @@ mod tests {
// create a tx with 10 blobs // create a tx with 10 blobs
let transaction = mock_blob_tx(1, 10); let transaction = mock_blob_tx(1, 10);
let sealed = Header { let header = Header {
base_fee_per_gas: Some(1337), base_fee_per_gas: Some(1337),
withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])), withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
blob_gas_used: Some(1), blob_gas_used: Some(1),
transactions_root: proofs::calculate_transaction_root(&[transaction.clone()]), transactions_root: proofs::calculate_transaction_root(&[transaction.clone()]),
..Default::default() ..Default::default()
} };
.seal_slow(); let header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
let header = SealedHeader::new(header, seal);
let body = BlockBody { let body = BlockBody {
transactions: vec![transaction], transactions: vec![transaction],

View File

@ -230,7 +230,7 @@ impl<N: ProviderNodeTypes> PipelineState<N> {
mod tests { mod tests {
use super::*; use super::*;
use crate::test_utils::{insert_headers_into_client, TestPipelineBuilder}; use crate::test_utils::{insert_headers_into_client, TestPipelineBuilder};
use alloy_primitives::{BlockNumber, Sealable, B256}; use alloy_primitives::{BlockNumber, B256};
use assert_matches::assert_matches; use assert_matches::assert_matches;
use futures::poll; use futures::poll;
use reth_chainspec::{ChainSpecBuilder, MAINNET}; use reth_chainspec::{ChainSpecBuilder, MAINNET};
@ -267,14 +267,12 @@ mod tests {
let pipeline_sync = PipelineSync::new(pipeline, Box::<TokioTaskExecutor>::default()); let pipeline_sync = PipelineSync::new(pipeline, Box::<TokioTaskExecutor>::default());
let client = TestFullBlockClient::default(); let client = TestFullBlockClient::default();
let sealed = Header { let header = Header {
base_fee_per_gas: Some(7), base_fee_per_gas: Some(7),
gas_limit: chain_spec.max_gas_limit, gas_limit: chain_spec.max_gas_limit,
..Default::default() ..Default::default()
} };
.seal_slow(); let header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
let header = SealedHeader::new(header, seal);
insert_headers_into_client(&client, header, 0..total_blocks); insert_headers_into_client(&client, header, 0..total_blocks);
let tip = client.highest_block().expect("there should be blocks here").hash(); let tip = client.highest_block().expect("there should be blocks here").hash();

View File

@ -309,7 +309,6 @@ impl BlockDownloader for NoopBlockDownloader {
mod tests { mod tests {
use super::*; use super::*;
use crate::test_utils::insert_headers_into_client; use crate::test_utils::insert_headers_into_client;
use alloy_primitives::Sealable;
use assert_matches::assert_matches; use assert_matches::assert_matches;
use reth_beacon_consensus::EthBeaconConsensus; use reth_beacon_consensus::EthBeaconConsensus;
use reth_chainspec::{ChainSpecBuilder, MAINNET}; use reth_chainspec::{ChainSpecBuilder, MAINNET};
@ -333,14 +332,12 @@ mod tests {
); );
let client = TestFullBlockClient::default(); let client = TestFullBlockClient::default();
let sealed = Header { let header = Header {
base_fee_per_gas: Some(7), base_fee_per_gas: Some(7),
gas_limit: chain_spec.max_gas_limit, gas_limit: chain_spec.max_gas_limit,
..Default::default() ..Default::default()
} };
.seal_slow(); let header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
let header = SealedHeader::new(header, seal);
insert_headers_into_client(&client, header, 0..total_blocks); insert_headers_into_client(&client, header, 0..total_blocks);
let consensus = Arc::new(EthBeaconConsensus::new(chain_spec)); let consensus = Arc::new(EthBeaconConsensus::new(chain_spec));

View File

@ -1,4 +1,4 @@
use alloy_primitives::{Sealable, B256}; use alloy_primitives::B256;
use reth_chainspec::ChainSpec; use reth_chainspec::ChainSpec;
use reth_network_p2p::test_utils::TestFullBlockClient; use reth_network_p2p::test_utils::TestFullBlockClient;
use reth_primitives::{BlockBody, SealedHeader}; use reth_primitives::{BlockBody, SealedHeader};
@ -76,9 +76,7 @@ pub fn insert_headers_into_client(
header.parent_hash = hash; header.parent_hash = hash;
header.number += 1; header.number += 1;
header.timestamp += 1; header.timestamp += 1;
let sealed = header.seal_slow(); sealed_header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
sealed_header = SealedHeader::new(header, seal);
client.insert(sealed_header.clone(), body.clone()); client.insert(sealed_header.clone(), body.clone());
} }
} }

View File

@ -2597,7 +2597,7 @@ pub enum AdvancePersistenceError {
mod tests { mod tests {
use super::*; use super::*;
use crate::persistence::PersistenceAction; use crate::persistence::PersistenceAction;
use alloy_primitives::{Bytes, Sealable}; use alloy_primitives::Bytes;
use alloy_rlp::Decodable; use alloy_rlp::Decodable;
use alloy_rpc_types_engine::{CancunPayloadFields, ExecutionPayloadSidecar}; use alloy_rpc_types_engine::{CancunPayloadFields, ExecutionPayloadSidecar};
use assert_matches::assert_matches; use assert_matches::assert_matches;
@ -2709,9 +2709,8 @@ mod tests {
let (from_tree_tx, from_tree_rx) = unbounded_channel(); let (from_tree_tx, from_tree_rx) = unbounded_channel();
let sealed = chain_spec.genesis_header().clone().seal_slow(); let header = chain_spec.genesis_header().clone();
let (header, seal) = sealed.into_parts(); let header = SealedHeader::seal(header);
let header = SealedHeader::new(header, seal);
let engine_api_tree_state = EngineApiTreeState::new(10, 10, header.num_hash()); let engine_api_tree_state = EngineApiTreeState::new(10, 10, header.num_hash());
let canonical_in_memory_state = CanonicalInMemoryState::with_head(header, None, None); let canonical_in_memory_state = CanonicalInMemoryState::with_head(header, None, None);

View File

@ -236,7 +236,7 @@ impl<ChainSpec: Send + Sync + EthChainSpec + EthereumHardforks + Debug> Consensu
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use alloy_primitives::{Sealable, B256}; use alloy_primitives::B256;
use reth_chainspec::{ChainSpec, ChainSpecBuilder}; use reth_chainspec::{ChainSpec, ChainSpecBuilder};
use reth_primitives::proofs; use reth_primitives::proofs;
@ -321,16 +321,14 @@ mod tests {
// that the header is valid // that the header is valid
let chain_spec = Arc::new(ChainSpecBuilder::mainnet().shanghai_activated().build()); let chain_spec = Arc::new(ChainSpecBuilder::mainnet().shanghai_activated().build());
let sealed = Header { let header = Header {
base_fee_per_gas: Some(1337), base_fee_per_gas: Some(1337),
withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])), withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
..Default::default() ..Default::default()
} };
.seal_slow();
let (header, seal) = sealed.into_parts();
assert_eq!( assert_eq!(
EthBeaconConsensus::new(chain_spec).validate_header(&SealedHeader::new(header, seal)), EthBeaconConsensus::new(chain_spec).validate_header(&SealedHeader::seal(header,)),
Ok(()) Ok(())
); );
} }

View File

@ -1,7 +1,7 @@
use std::{collections::HashMap, io, path::Path}; use std::{collections::HashMap, io, path::Path};
use alloy_eips::BlockHashOrNumber; use alloy_eips::BlockHashOrNumber;
use alloy_primitives::{BlockHash, BlockNumber, Sealable, B256}; use alloy_primitives::{BlockHash, BlockNumber, B256};
use futures::Future; use futures::Future;
use itertools::Either; use itertools::Either;
use reth_network_p2p::{ use reth_network_p2p::{
@ -114,11 +114,7 @@ impl FileClient {
/// Clones and returns the highest header of this client has or `None` if empty. Seals header /// Clones and returns the highest header of this client has or `None` if empty. Seals header
/// before returning. /// before returning.
pub fn tip_header(&self) -> Option<SealedHeader> { pub fn tip_header(&self) -> Option<SealedHeader> {
self.headers.get(&self.max_block()?).map(|h| { self.headers.get(&self.max_block()?).map(|h| SealedHeader::seal(h.clone()))
let sealed = h.clone().seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
})
} }
/// Returns true if all blocks are canonical (no gaps) /// Returns true if all blocks are canonical (no gaps)

View File

@ -4,7 +4,7 @@ use super::task::TaskDownloader;
use crate::metrics::HeaderDownloaderMetrics; use crate::metrics::HeaderDownloaderMetrics;
use alloy_consensus::BlockHeader; use alloy_consensus::BlockHeader;
use alloy_eips::BlockHashOrNumber; use alloy_eips::BlockHashOrNumber;
use alloy_primitives::{BlockNumber, Sealable, B256}; use alloy_primitives::{BlockNumber, B256};
use futures::{stream::Stream, FutureExt}; use futures::{stream::Stream, FutureExt};
use futures_util::{stream::FuturesUnordered, StreamExt}; use futures_util::{stream::FuturesUnordered, StreamExt};
use rayon::prelude::*; use rayon::prelude::*;
@ -250,15 +250,7 @@ where
) -> Result<(), ReverseHeadersDownloaderError<H::Header>> { ) -> Result<(), ReverseHeadersDownloaderError<H::Header>> {
let mut validated = Vec::with_capacity(headers.len()); let mut validated = Vec::with_capacity(headers.len());
let sealed_headers = headers let sealed_headers = headers.into_par_iter().map(SealedHeader::seal).collect::<Vec<_>>();
.into_par_iter()
.map(|h| {
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
})
.collect::<Vec<_>>();
for parent in sealed_headers { for parent in sealed_headers {
// Validate that the header is the parent header of the last validated header. // Validate that the header is the parent header of the last validated header.
if let Some(validated_header) = if let Some(validated_header) =
@ -384,9 +376,8 @@ where
.into()) .into())
} }
let sealed_target = headers.swap_remove(0).seal_slow(); let header = headers.swap_remove(0);
let (header, seal) = sealed_target.into_parts(); let target = SealedHeader::seal(header);
let target = SealedHeader::new(header, seal);
match sync_target { match sync_target {
SyncTargetBlock::Hash(hash) | SyncTargetBlock::HashAndNumber { hash, .. } => { SyncTargetBlock::Hash(hash) | SyncTargetBlock::HashAndNumber { hash, .. } => {

View File

@ -2,7 +2,6 @@
#![allow(dead_code)] #![allow(dead_code)]
use alloy_primitives::Sealable;
use reth_primitives::SealedHeader; use reth_primitives::SealedHeader;
/// Returns a new [`SealedHeader`] that's the child header of the given `parent`. /// Returns a new [`SealedHeader`] that's the child header of the given `parent`.
@ -10,7 +9,5 @@ pub(crate) fn child_header(parent: &SealedHeader) -> SealedHeader {
let mut child = parent.as_ref().clone(); let mut child = parent.as_ref().clone();
child.number += 1; child.number += 1;
child.parent_hash = parent.hash_slow(); child.parent_hash = parent.hash_slow();
let sealed = child.seal_slow(); SealedHeader::seal(child)
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
} }

View File

@ -199,15 +199,8 @@ where
ResponseResult::Header(res) => { ResponseResult::Header(res) => {
match res { match res {
Ok(maybe_header) => { Ok(maybe_header) => {
let (peer, maybe_header) = maybe_header let (peer, maybe_header) =
.map(|h| { maybe_header.map(|h| h.map(SealedHeader::seal)).split();
h.map(|h| {
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
})
})
.split();
if let Some(header) = maybe_header { if let Some(header) = maybe_header {
if header.hash() == this.hash { if header.hash() == this.hash {
this.header = Some(header); this.header = Some(header);
@ -457,17 +450,8 @@ where
} }
fn on_headers_response(&mut self, headers: WithPeerId<Vec<Client::Header>>) { fn on_headers_response(&mut self, headers: WithPeerId<Vec<Client::Header>>) {
let (peer, mut headers_falling) = headers let (peer, mut headers_falling) =
.map(|h| { headers.map(|h| h.into_iter().map(SealedHeader::seal).collect::<Vec<_>>()).split();
h.into_iter()
.map(|h| {
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
})
.collect::<Vec<_>>()
})
.split();
// fill in the response if it's the correct length // fill in the response if it's the correct length
if headers_falling.len() == self.count as usize { if headers_falling.len() == self.count as usize {
@ -707,9 +691,7 @@ mod tests {
header.parent_hash = hash; header.parent_hash = hash;
header.number += 1; header.number += 1;
let sealed = header.seal_slow(); sealed_header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
sealed_header = SealedHeader::new(header, seal);
client.insert(sealed_header.clone(), body.clone()); client.insert(sealed_header.clone(), body.clone());
} }

View File

@ -10,7 +10,6 @@ use crate::{
}, },
priority::Priority, priority::Priority,
}; };
use alloy_primitives::Sealable;
use futures::{Future, FutureExt, Stream, StreamExt}; use futures::{Future, FutureExt, Stream, StreamExt};
use reth_consensus::{test_utils::TestConsensus, Consensus}; use reth_consensus::{test_utils::TestConsensus, Consensus};
use reth_eth_wire_types::HeadersDirection; use reth_eth_wire_types::HeadersDirection;
@ -160,16 +159,8 @@ impl Stream for TestDownload {
match ready!(this.get_or_init_fut().poll_unpin(cx)) { match ready!(this.get_or_init_fut().poll_unpin(cx)) {
Ok(resp) => { Ok(resp) => {
// Skip head and seal headers // Skip head and seal headers
let mut headers = resp let mut headers =
.1 resp.1.into_iter().skip(1).map(SealedHeader::seal).collect::<Vec<_>>();
.into_iter()
.skip(1)
.map(|header| {
let sealed = header.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
})
.collect::<Vec<_>>();
headers.sort_unstable_by_key(|h| h.number); headers.sort_unstable_by_key(|h| h.number);
headers.into_iter().for_each(|h| this.buffer.push(h)); headers.into_iter().for_each(|h| this.buffer.push(h));
this.done = true; this.done = true;

View File

@ -3,7 +3,6 @@
use alloy_consensus::BlockHeader; use alloy_consensus::BlockHeader;
use alloy_eips::BlockHashOrNumber; use alloy_eips::BlockHashOrNumber;
use alloy_primitives::Sealable;
use alloy_rpc_types_engine::{JwtError, JwtSecret}; use alloy_rpc_types_engine::{JwtError, JwtSecret};
use eyre::Result; use eyre::Result;
use reth_consensus::Consensus; use reth_consensus::Consensus;
@ -44,13 +43,12 @@ where
{ {
let (peer_id, response) = client.get_header_with_priority(id, Priority::High).await?.split(); let (peer_id, response) = client.get_header_with_priority(id, Priority::High).await?.split();
let Some(sealed_header) = response.map(|block| block.seal_slow()) else { let Some(header) = response else {
client.report_bad_message(peer_id); client.report_bad_message(peer_id);
eyre::bail!("Invalid number of headers received. Expected: 1. Received: 0") eyre::bail!("Invalid number of headers received. Expected: 1. Received: 0")
}; };
let (header, seal) = sealed_header.into_parts(); let header = SealedHeader::seal(header);
let header = SealedHeader::new(header, seal);
let valid = match id { let valid = match id {
BlockHashOrNumber::Hash(hash) => header.hash() == hash, BlockHashOrNumber::Hash(hash) => header.hash() == hash,

View File

@ -156,9 +156,7 @@ impl<'a> arbitrary::Arbitrary<'a> for SealedHeader {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let header = Header::arbitrary(u)?; let header = Header::arbitrary(u)?;
let sealed = header.seal_slow(); Ok(Self::seal(header))
let (header, seal) = sealed.into_parts();
Ok(Self::new(header, seal))
} }
} }

View File

@ -1,7 +1,7 @@
use crate::{GotExpected, Header, SealedHeader, TransactionSigned, TransactionSignedEcRecovered}; use crate::{GotExpected, Header, SealedHeader, TransactionSigned, TransactionSignedEcRecovered};
use alloc::vec::Vec; use alloc::vec::Vec;
use alloy_eips::{eip2718::Encodable2718, eip4895::Withdrawals}; use alloy_eips::{eip2718::Encodable2718, eip4895::Withdrawals};
use alloy_primitives::{Address, Bytes, Sealable, B256}; use alloy_primitives::{Address, Bytes, B256};
use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable}; use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable};
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
#[cfg(any(test, feature = "arbitrary"))] #[cfg(any(test, feature = "arbitrary"))]
@ -25,9 +25,7 @@ pub struct Block {
impl Block { impl Block {
/// Calculate the header hash and seal the block so that it can't be changed. /// Calculate the header hash and seal the block so that it can't be changed.
pub fn seal_slow(self) -> SealedBlock { pub fn seal_slow(self) -> SealedBlock {
let sealed = self.header.seal_slow(); SealedBlock { header: SealedHeader::seal(self.header), body: self.body }
let (header, seal) = sealed.into_parts();
SealedBlock { header: SealedHeader::new(header, seal), body: self.body }
} }
/// Seal the block with a known hash. /// Seal the block with a known hash.

View File

@ -1,7 +1,7 @@
//! Some payload tests //! Some payload tests
use alloy_eips::eip4895::Withdrawals; use alloy_eips::eip4895::Withdrawals;
use alloy_primitives::{Bytes, Sealable, U256}; use alloy_primitives::{Bytes, U256};
use alloy_rlp::{Decodable, Error as RlpError}; use alloy_rlp::{Decodable, Error as RlpError};
use alloy_rpc_types_engine::{ use alloy_rpc_types_engine::{
ExecutionPayload, ExecutionPayloadBodyV1, ExecutionPayloadSidecar, ExecutionPayloadV1, ExecutionPayload, ExecutionPayloadBodyV1, ExecutionPayloadSidecar, ExecutionPayloadV1,
@ -24,10 +24,8 @@ fn transform_block<F: FnOnce(Block) -> Block>(src: SealedBlock, f: F) -> Executi
transformed.header.transactions_root = transformed.header.transactions_root =
proofs::calculate_transaction_root(&transformed.body.transactions); proofs::calculate_transaction_root(&transformed.body.transactions);
transformed.header.ommers_hash = proofs::calculate_ommers_root(&transformed.body.ommers); transformed.header.ommers_hash = proofs::calculate_ommers_root(&transformed.body.ommers);
let sealed = transformed.header.seal_slow();
let (header, seal) = sealed.into_parts();
block_to_payload(SealedBlock { block_to_payload(SealedBlock {
header: SealedHeader::new(header, seal), header: SealedHeader::seal(transformed.header),
body: transformed.body, body: transformed.body,
}) })
} }

View File

@ -1,5 +1,5 @@
#![allow(unreachable_pub)] #![allow(unreachable_pub)]
use alloy_primitives::{Address, Sealable, B256, U256}; use alloy_primitives::{Address, B256, U256};
use itertools::concat; use itertools::concat;
use reth_db::{tables, test_utils::TempDatabase, Database, DatabaseEnv}; use reth_db::{tables, test_utils::TempDatabase, Database, DatabaseEnv};
use reth_db_api::{ use reth_db_api::{
@ -147,9 +147,7 @@ pub(crate) fn txs_testdata(num_blocks: u64) -> TestStageDB {
let cloned_second = second_block.clone(); let cloned_second = second_block.clone();
let mut updated_header = cloned_second.header.unseal(); let mut updated_header = cloned_second.header.unseal();
updated_header.state_root = root; updated_header.state_root = root;
let sealed = updated_header.seal_slow(); *second_block = SealedBlock { header: SealedHeader::seal(updated_header), ..cloned_second };
let (header, seal) = sealed.into_parts();
*second_block = SealedBlock { header: SealedHeader::new(header, seal), ..cloned_second };
let offset = transitions.len() as u64; let offset = transitions.len() as u64;
@ -182,9 +180,7 @@ pub(crate) fn txs_testdata(num_blocks: u64) -> TestStageDB {
let cloned_last = last_block.clone(); let cloned_last = last_block.clone();
let mut updated_header = cloned_last.header.unseal(); let mut updated_header = cloned_last.header.unseal();
updated_header.state_root = root; updated_header.state_root = root;
let sealed = updated_header.seal_slow(); *last_block = SealedBlock { header: SealedHeader::seal(updated_header), ..cloned_last };
let (header, seal) = sealed.into_parts();
*last_block = SealedBlock { header: SealedHeader::new(header, seal), ..cloned_last };
db.insert_blocks(blocks.iter(), StorageKind::Static).unwrap(); db.insert_blocks(blocks.iter(), StorageKind::Static).unwrap();

View File

@ -1,5 +1,5 @@
use crate::stages::MERKLE_STAGE_DEFAULT_CLEAN_THRESHOLD; use crate::stages::MERKLE_STAGE_DEFAULT_CLEAN_THRESHOLD;
use alloy_primitives::{BlockNumber, Sealable}; use alloy_primitives::BlockNumber;
use num_traits::Zero; use num_traits::Zero;
use reth_config::config::ExecutionConfig; use reth_config::config::ExecutionConfig;
use reth_db::{static_file::HeaderMask, tables}; use reth_db::{static_file::HeaderMask, tables};
@ -276,11 +276,8 @@ where
let execute_start = Instant::now(); let execute_start = Instant::now();
self.metrics.metered_one((&block, td).into(), |input| { self.metrics.metered_one((&block, td).into(), |input| {
let sealed = block.header.clone().seal_slow();
let (header, seal) = sealed.into_parts();
executor.execute_and_verify_one(input).map_err(|error| StageError::Block { executor.execute_and_verify_one(input).map_err(|error| StageError::Block {
block: Box::new(SealedHeader::new(header, seal)), block: Box::new(SealedHeader::seal(block.header.clone())),
error: BlockErrorKind::Execution(error), error: BlockErrorKind::Execution(error),
}) })
})?; })?;

View File

@ -392,7 +392,7 @@ mod tests {
use crate::test_utils::{ use crate::test_utils::{
stage_test_suite, ExecuteStageTestRunner, StageTestRunner, UnwindStageTestRunner, stage_test_suite, ExecuteStageTestRunner, StageTestRunner, UnwindStageTestRunner,
}; };
use alloy_primitives::{Sealable, B256}; use alloy_primitives::B256;
use assert_matches::assert_matches; use assert_matches::assert_matches;
use reth_execution_types::ExecutionOutcome; use reth_execution_types::ExecutionOutcome;
use reth_primitives::{BlockBody, SealedBlock, SealedBlockWithSenders}; use reth_primitives::{BlockBody, SealedBlock, SealedBlockWithSenders};
@ -509,9 +509,7 @@ mod tests {
// validate the header // validate the header
let header = provider.header_by_number(block_num)?; let header = provider.header_by_number(block_num)?;
assert!(header.is_some()); assert!(header.is_some());
let sealed = header.unwrap().seal_slow(); let header = SealedHeader::seal(header.unwrap());
let (header, seal) = sealed.into_parts();
let header = SealedHeader::new(header, seal);
assert_eq!(header.hash(), hash); assert_eq!(header.hash(), hash);
// validate the header total difficulty // validate the header total difficulty

View File

@ -1,4 +1,4 @@
use alloy_primitives::{BlockNumber, Sealable, B256}; use alloy_primitives::{BlockNumber, B256};
use reth_codecs::Compact; use reth_codecs::Compact;
use reth_consensus::ConsensusError; use reth_consensus::ConsensusError;
use reth_db::tables; use reth_db::tables;
@ -276,10 +276,7 @@ where
// Reset the checkpoint // Reset the checkpoint
self.save_execution_checkpoint(provider, None)?; self.save_execution_checkpoint(provider, None)?;
let sealed = target_block.seal_slow(); validate_state_root(trie_root, SealedHeader::seal(target_block), to_block)?;
let (header, seal) = sealed.into_parts();
validate_state_root(trie_root, SealedHeader::new(header, seal), to_block)?;
Ok(ExecOutput { Ok(ExecOutput {
checkpoint: StageCheckpoint::new(to_block) checkpoint: StageCheckpoint::new(to_block)
@ -332,10 +329,7 @@ where
.header_by_number(input.unwind_to)? .header_by_number(input.unwind_to)?
.ok_or_else(|| ProviderError::HeaderNotFound(input.unwind_to.into()))?; .ok_or_else(|| ProviderError::HeaderNotFound(input.unwind_to.into()))?;
let sealed = target.seal_slow(); validate_state_root(block_root, SealedHeader::seal(target), input.unwind_to)?;
let (header, seal) = sealed.into_parts();
validate_state_root(block_root, SealedHeader::new(header, seal), input.unwind_to)?;
// Validation passed, apply unwind changes to the database. // Validation passed, apply unwind changes to the database.
provider.write_trie_updates(&updates)?; provider.write_trie_updates(&updates)?;
@ -538,9 +532,7 @@ mod tests {
.into_iter() .into_iter()
.map(|(address, account)| (address, (account, std::iter::empty()))), .map(|(address, account)| (address, (account, std::iter::empty()))),
); );
let sealed = header.seal_slow(); let sealed_head = SealedBlock { header: SealedHeader::seal(header), body };
let (header, seal) = sealed.into_parts();
let sealed_head = SealedBlock { header: SealedHeader::new(header, seal), body };
let head_hash = sealed_head.hash(); let head_hash = sealed_head.hash();
let mut blocks = vec![sealed_head]; let mut blocks = vec![sealed_head];

View File

@ -10,7 +10,7 @@ use alloy_eips::{
eip4895::{Withdrawal, Withdrawals}, eip4895::{Withdrawal, Withdrawals},
BlockHashOrNumber, BlockId, BlockNumHash, BlockNumberOrTag, HashOrNumber, BlockHashOrNumber, BlockId, BlockNumHash, BlockNumberOrTag, HashOrNumber,
}; };
use alloy_primitives::{Address, BlockHash, BlockNumber, Sealable, TxHash, TxNumber, B256, U256}; use alloy_primitives::{Address, BlockHash, BlockNumber, TxHash, TxNumber, B256, U256};
use reth_chain_state::{BlockState, CanonicalInMemoryState, MemoryOverlayStateProviderRef}; use reth_chain_state::{BlockState, CanonicalInMemoryState, MemoryOverlayStateProviderRef};
use reth_chainspec::{ChainInfo, EthereumHardforks}; use reth_chainspec::{ChainInfo, EthereumHardforks};
use reth_db::models::BlockNumberAddress; use reth_db::models::BlockNumberAddress;
@ -1324,34 +1324,20 @@ impl<N: ProviderNodeTypes> BlockReaderIdExt for ConsistentProvider<N> {
Ok(self.canonical_in_memory_state.get_finalized_header()) Ok(self.canonical_in_memory_state.get_finalized_header())
} }
BlockNumberOrTag::Safe => Ok(self.canonical_in_memory_state.get_safe_header()), BlockNumberOrTag::Safe => Ok(self.canonical_in_memory_state.get_safe_header()),
BlockNumberOrTag::Earliest => self.header_by_number(0)?.map_or_else( BlockNumberOrTag::Earliest => self
|| Ok(None), .header_by_number(0)?
|h| { .map_or_else(|| Ok(None), |h| Ok(Some(SealedHeader::seal(h)))),
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
Ok(Some(SealedHeader::new(header, seal)))
},
),
BlockNumberOrTag::Pending => Ok(self.canonical_in_memory_state.pending_sealed_header()), BlockNumberOrTag::Pending => Ok(self.canonical_in_memory_state.pending_sealed_header()),
BlockNumberOrTag::Number(num) => self.header_by_number(num)?.map_or_else( BlockNumberOrTag::Number(num) => self
|| Ok(None), .header_by_number(num)?
|h| { .map_or_else(|| Ok(None), |h| Ok(Some(SealedHeader::seal(h)))),
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
Ok(Some(SealedHeader::new(header, seal)))
},
),
} }
} }
fn sealed_header_by_id(&self, id: BlockId) -> ProviderResult<Option<SealedHeader>> { fn sealed_header_by_id(&self, id: BlockId) -> ProviderResult<Option<SealedHeader>> {
Ok(match id { Ok(match id {
BlockId::Number(num) => self.sealed_header_by_number_or_tag(num)?, BlockId::Number(num) => self.sealed_header_by_number_or_tag(num)?,
BlockId::Hash(hash) => self.header(&hash.block_hash)?.map(|h| { BlockId::Hash(hash) => self.header(&hash.block_hash)?.map(SealedHeader::seal),
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
}),
}) })
} }

View File

@ -11,7 +11,7 @@ use alloy_eips::{
eip4895::{Withdrawal, Withdrawals}, eip4895::{Withdrawal, Withdrawals},
BlockHashOrNumber, BlockId, BlockNumHash, BlockNumberOrTag, BlockHashOrNumber, BlockId, BlockNumHash, BlockNumberOrTag,
}; };
use alloy_primitives::{Address, BlockHash, BlockNumber, Sealable, TxHash, TxNumber, B256, U256}; use alloy_primitives::{Address, BlockHash, BlockNumber, TxHash, TxNumber, B256, U256};
use reth_blockchain_tree_api::{ use reth_blockchain_tree_api::{
error::{CanonicalError, InsertBlockError}, error::{CanonicalError, InsertBlockError},
BlockValidationKind, BlockchainTreeEngine, BlockchainTreeViewer, CanonicalOutcome, BlockValidationKind, BlockchainTreeEngine, BlockchainTreeViewer, CanonicalOutcome,
@ -847,34 +847,20 @@ where
BlockNumberOrTag::Latest => Ok(Some(self.chain_info.get_canonical_head())), BlockNumberOrTag::Latest => Ok(Some(self.chain_info.get_canonical_head())),
BlockNumberOrTag::Finalized => Ok(self.chain_info.get_finalized_header()), BlockNumberOrTag::Finalized => Ok(self.chain_info.get_finalized_header()),
BlockNumberOrTag::Safe => Ok(self.chain_info.get_safe_header()), BlockNumberOrTag::Safe => Ok(self.chain_info.get_safe_header()),
BlockNumberOrTag::Earliest => self.header_by_number(0)?.map_or_else( BlockNumberOrTag::Earliest => self
|| Ok(None), .header_by_number(0)?
|h| { .map_or_else(|| Ok(None), |h| Ok(Some(SealedHeader::seal(h)))),
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
Ok(Some(SealedHeader::new(header, seal)))
},
),
BlockNumberOrTag::Pending => Ok(self.tree.pending_header()), BlockNumberOrTag::Pending => Ok(self.tree.pending_header()),
BlockNumberOrTag::Number(num) => self.header_by_number(num)?.map_or_else( BlockNumberOrTag::Number(num) => self
|| Ok(None), .header_by_number(num)?
|h| { .map_or_else(|| Ok(None), |h| Ok(Some(SealedHeader::seal(h)))),
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
Ok(Some(SealedHeader::new(header, seal)))
},
),
} }
} }
fn sealed_header_by_id(&self, id: BlockId) -> ProviderResult<Option<SealedHeader>> { fn sealed_header_by_id(&self, id: BlockId) -> ProviderResult<Option<SealedHeader>> {
Ok(match id { Ok(match id {
BlockId::Number(num) => self.sealed_header_by_number_or_tag(num)?, BlockId::Number(num) => self.sealed_header_by_number_or_tag(num)?,
BlockId::Hash(hash) => self.header(&hash.block_hash)?.map(|h| { BlockId::Hash(hash) => self.header(&hash.block_hash)?.map(SealedHeader::seal),
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
}),
}) })
} }

View File

@ -2,8 +2,7 @@
use crate::{DBProvider, DatabaseProviderRW, ExecutionOutcome}; use crate::{DBProvider, DatabaseProviderRW, ExecutionOutcome};
use alloy_consensus::{TxLegacy, EMPTY_OMMER_ROOT_HASH}; use alloy_consensus::{TxLegacy, EMPTY_OMMER_ROOT_HASH};
use alloy_primitives::{ use alloy_primitives::{
b256, hex_literal::hex, map::HashMap, Address, BlockNumber, Bytes, Log, Sealable, TxKind, B256, b256, hex_literal::hex, map::HashMap, Address, BlockNumber, Bytes, Log, TxKind, B256, U256,
U256,
}; };
use alloy_eips::eip4895::{Withdrawal, Withdrawals}; use alloy_eips::eip4895::{Withdrawal, Withdrawals};
@ -233,9 +232,7 @@ fn block1(number: BlockNumber) -> (SealedBlockWithSenders, ExecutionOutcome) {
header.number = number; header.number = number;
header.state_root = state_root; header.state_root = state_root;
header.parent_hash = B256::ZERO; header.parent_hash = B256::ZERO;
let sealed = header.seal_slow(); block.header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
block.header = SealedHeader::new(header, seal);
(SealedBlockWithSenders { block, senders: vec![Address::new([0x30; 20])] }, execution_outcome) (SealedBlockWithSenders { block, senders: vec![Address::new([0x30; 20])] }, execution_outcome)
} }
@ -299,9 +296,7 @@ fn block2(
header.state_root = state_root; header.state_root = state_root;
// parent_hash points to block1 hash // parent_hash points to block1 hash
header.parent_hash = parent_hash; header.parent_hash = parent_hash;
let sealed = header.seal_slow(); block.header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
block.header = SealedHeader::new(header, seal);
(SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome) (SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome)
} }
@ -365,9 +360,7 @@ fn block3(
header.state_root = state_root; header.state_root = state_root;
// parent_hash points to block1 hash // parent_hash points to block1 hash
header.parent_hash = parent_hash; header.parent_hash = parent_hash;
let sealed = header.seal_slow(); block.header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
block.header = SealedHeader::new(header, seal);
(SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome) (SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome)
} }
@ -456,9 +449,7 @@ fn block4(
header.state_root = state_root; header.state_root = state_root;
// parent_hash points to block1 hash // parent_hash points to block1 hash
header.parent_hash = parent_hash; header.parent_hash = parent_hash;
let sealed = header.seal_slow(); block.header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
block.header = SealedHeader::new(header, seal);
(SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome) (SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome)
} }
@ -544,9 +535,7 @@ fn block5(
header.state_root = state_root; header.state_root = state_root;
// parent_hash points to block1 hash // parent_hash points to block1 hash
header.parent_hash = parent_hash; header.parent_hash = parent_hash;
let sealed = header.seal_slow(); block.header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
block.header = SealedHeader::new(header, seal);
(SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome) (SealedBlockWithSenders { block, senders: vec![Address::new([0x31; 20])] }, execution_outcome)
} }

View File

@ -13,8 +13,7 @@ use alloy_eips::{
use alloy_primitives::{ use alloy_primitives::{
keccak256, keccak256,
map::{HashMap, HashSet}, map::{HashMap, HashSet},
Address, BlockHash, BlockNumber, Bytes, Sealable, StorageKey, StorageValue, TxHash, TxNumber, Address, BlockHash, BlockNumber, Bytes, StorageKey, StorageValue, TxHash, TxNumber, B256, U256,
B256, U256,
}; };
use parking_lot::Mutex; use parking_lot::Mutex;
use reth_chainspec::{ChainInfo, ChainSpec}; use reth_chainspec::{ChainInfo, ChainSpec};
@ -218,11 +217,7 @@ impl HeaderProvider for MockEthProvider {
} }
fn sealed_header(&self, number: BlockNumber) -> ProviderResult<Option<SealedHeader>> { fn sealed_header(&self, number: BlockNumber) -> ProviderResult<Option<SealedHeader>> {
Ok(self.header_by_number(number)?.map(|h| { Ok(self.header_by_number(number)?.map(SealedHeader::seal))
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
}))
} }
fn sealed_headers_while( fn sealed_headers_while(
@ -233,11 +228,7 @@ impl HeaderProvider for MockEthProvider {
Ok(self Ok(self
.headers_range(range)? .headers_range(range)?
.into_iter() .into_iter()
.map(|h| { .map(SealedHeader::seal)
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
})
.take_while(|h| predicate(h)) .take_while(|h| predicate(h))
.collect()) .collect())
} }
@ -566,14 +557,7 @@ impl BlockReaderIdExt for MockEthProvider {
} }
fn sealed_header_by_id(&self, id: BlockId) -> ProviderResult<Option<SealedHeader>> { fn sealed_header_by_id(&self, id: BlockId) -> ProviderResult<Option<SealedHeader>> {
self.header_by_id(id)?.map_or_else( self.header_by_id(id)?.map_or_else(|| Ok(None), |h| Ok(Some(SealedHeader::seal(h))))
|| Ok(None),
|h| {
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
Ok(Some(SealedHeader::new(header, seal)))
},
)
} }
fn header_by_id(&self, id: BlockId) -> ProviderResult<Option<Header>> { fn header_by_id(&self, id: BlockId) -> ProviderResult<Option<Header>> {

View File

@ -3,7 +3,7 @@ use crate::{
TransactionsProvider, WithdrawalsProvider, TransactionsProvider, WithdrawalsProvider,
}; };
use alloy_eips::{BlockHashOrNumber, BlockId, BlockNumberOrTag}; use alloy_eips::{BlockHashOrNumber, BlockId, BlockNumberOrTag};
use alloy_primitives::{BlockNumber, Sealable, B256}; use alloy_primitives::{BlockNumber, B256};
use reth_db_models::StoredBlockBodyIndices; use reth_db_models::StoredBlockBodyIndices;
use reth_primitives::{ use reth_primitives::{
Block, BlockWithSenders, Header, Receipt, SealedBlock, SealedBlockWithSenders, SealedHeader, Block, BlockWithSenders, Header, Receipt, SealedBlock, SealedBlockWithSenders, SealedHeader,
@ -243,14 +243,7 @@ pub trait BlockReaderIdExt: BlockReader + ReceiptProviderIdExt {
) -> ProviderResult<Option<SealedHeader>> { ) -> ProviderResult<Option<SealedHeader>> {
self.convert_block_number(id)? self.convert_block_number(id)?
.map_or_else(|| Ok(None), |num| self.header_by_hash_or_number(num.into()))? .map_or_else(|| Ok(None), |num| self.header_by_hash_or_number(num.into()))?
.map_or_else( .map_or_else(|| Ok(None), |h| Ok(Some(SealedHeader::seal(h))))
|| Ok(None),
|h| {
let sealed = h.seal_slow();
let (header, seal) = sealed.into_parts();
Ok(Some(SealedHeader::new(header, seal)))
},
)
} }
/// Returns the sealed header with the matching `BlockId` from the database. /// Returns the sealed header with the matching `BlockId` from the database.

View File

@ -8,7 +8,7 @@ use crate::{
BlockInfo, PoolTransaction, BlockInfo, PoolTransaction,
}; };
use alloy_eips::BlockNumberOrTag; use alloy_eips::BlockNumberOrTag;
use alloy_primitives::{Address, BlockHash, BlockNumber, Sealable}; use alloy_primitives::{Address, BlockHash, BlockNumber};
use futures_util::{ use futures_util::{
future::{BoxFuture, Fuse, FusedFuture}, future::{BoxFuture, Fuse, FusedFuture},
FutureExt, Stream, StreamExt, FutureExt, Stream, StreamExt,
@ -106,9 +106,7 @@ pub async fn maintain_transaction_pool<Client, P, St, Tasks>(
let MaintainPoolConfig { max_update_depth, max_reload_accounts, .. } = config; let MaintainPoolConfig { max_update_depth, max_reload_accounts, .. } = config;
// ensure the pool points to latest state // ensure the pool points to latest state
if let Ok(Some(latest)) = client.header_by_number_or_tag(BlockNumberOrTag::Latest) { if let Ok(Some(latest)) = client.header_by_number_or_tag(BlockNumberOrTag::Latest) {
let sealed = latest.seal_slow(); let latest = SealedHeader::seal(latest);
let (header, seal) = sealed.into_parts();
let latest = SealedHeader::new(header, seal);
let chain_spec = client.chain_spec(); let chain_spec = client.chain_spec();
let info = BlockInfo { let info = BlockInfo {
block_gas_limit: latest.gas_limit, block_gas_limit: latest.gas_limit,

View File

@ -1,4 +1,4 @@
use alloy_primitives::{Address, Sealable, B256}; use alloy_primitives::{Address, B256};
use alloy_rpc_types_eth::{Filter, FilteredParams}; use alloy_rpc_types_eth::{Filter, FilteredParams};
use reth_chainspec::ChainSpecBuilder; use reth_chainspec::ChainSpecBuilder;
use reth_db::{open_db_read_only, DatabaseEnv}; use reth_db::{open_db_read_only, DatabaseEnv};
@ -63,9 +63,7 @@ fn header_provider_example<T: HeaderProvider>(provider: T, number: u64) -> eyre:
// We can convert a header to a sealed header which contains the hash w/o needing to re-compute // We can convert a header to a sealed header which contains the hash w/o needing to re-compute
// it every time. // it every time.
let sealed = header.seal_slow(); let sealed_header = SealedHeader::seal(header);
let (header, seal) = sealed.into_parts();
let sealed_header = SealedHeader::new(header, seal);
// Can also query the header by hash! // Can also query the header by hash!
let header_by_hash = let header_by_hash =

View File

@ -2,7 +2,7 @@
use alloy_consensus::{Transaction as _, TxLegacy}; use alloy_consensus::{Transaction as _, TxLegacy};
use alloy_eips::eip4895::{Withdrawal, Withdrawals}; use alloy_eips::eip4895::{Withdrawal, Withdrawals};
use alloy_primitives::{Address, BlockNumber, Bytes, Sealable, TxKind, B256, U256}; use alloy_primitives::{Address, BlockNumber, Bytes, TxKind, B256, U256};
pub use rand::Rng; pub use rand::Rng;
use rand::{ use rand::{
distributions::uniform::SampleRange, rngs::StdRng, seq::SliceRandom, thread_rng, SeedableRng, distributions::uniform::SampleRange, rngs::StdRng, seq::SliceRandom, thread_rng, SeedableRng,
@ -106,9 +106,7 @@ pub fn random_header<R: Rng>(rng: &mut R, number: u64, parent: Option<B256>) ->
parent_hash: parent.unwrap_or_default(), parent_hash: parent.unwrap_or_default(),
..Default::default() ..Default::default()
}; };
let sealed = header.seal_slow(); SealedHeader::seal(header)
let (header, seal) = sealed.into_parts();
SealedHeader::new(header, seal)
} }
/// Generates a random legacy [Transaction]. /// Generates a random legacy [Transaction].
@ -203,7 +201,7 @@ pub fn random_block<R: Rng>(rng: &mut R, number: u64, block_params: BlockParams)
}); });
let withdrawals_root = withdrawals.as_ref().map(|w| proofs::calculate_withdrawals_root(w)); let withdrawals_root = withdrawals.as_ref().map(|w| proofs::calculate_withdrawals_root(w));
let sealed = Header { let header = Header {
parent_hash: block_params.parent.unwrap_or_default(), parent_hash: block_params.parent.unwrap_or_default(),
number, number,
gas_used: total_gas, gas_used: total_gas,
@ -215,13 +213,10 @@ pub fn random_block<R: Rng>(rng: &mut R, number: u64, block_params: BlockParams)
requests_hash: None, requests_hash: None,
withdrawals_root, withdrawals_root,
..Default::default() ..Default::default()
} };
.seal_slow();
let (header, seal) = sealed.into_parts();
SealedBlock { SealedBlock {
header: SealedHeader::new(header, seal), header: SealedHeader::seal(header),
body: BlockBody { transactions, ommers, withdrawals: withdrawals.map(Withdrawals::new) }, body: BlockBody { transactions, ommers, withdrawals: withdrawals.map(Withdrawals::new) },
} }
} }