chore(sdk): Add blanket impls for refs to prim traits (#12613)

This commit is contained in:
Emilia Hane
2024-11-17 17:48:27 +01:00
committed by GitHub
parent 2f3fde8fb5
commit 7ae8ce1d00
13 changed files with 57 additions and 60 deletions

1
Cargo.lock generated
View File

@ -8582,6 +8582,7 @@ dependencies = [
"alloy-primitives", "alloy-primitives",
"alloy-rlp", "alloy-rlp",
"arbitrary", "arbitrary",
"auto_impl",
"bincode", "bincode",
"byteorder", "byteorder",
"bytes", "bytes",

View File

@ -3,7 +3,7 @@ use std::collections::HashMap;
use alloy_eips::eip7685::Requests; use alloy_eips::eip7685::Requests;
use alloy_primitives::{Address, BlockNumber, Bloom, Log, B256, U256}; use alloy_primitives::{Address, BlockNumber, Bloom, Log, B256, U256};
use reth_primitives::{logs_bloom, Account, Bytecode, Receipts, StorageEntry}; use reth_primitives::{logs_bloom, Account, Bytecode, Receipts, StorageEntry};
use reth_primitives_traits::Receipt; use reth_primitives_traits::{receipt::ReceiptExt, Receipt};
use reth_trie::HashedPostState; use reth_trie::HashedPostState;
use revm::{ use revm::{
db::{states::BundleState, BundleAccount}, db::{states::BundleState, BundleAccount},
@ -182,36 +182,6 @@ impl<T> ExecutionOutcome<T> {
Some(index as usize) Some(index as usize)
} }
/// Returns an iterator over all block logs.
pub fn logs(&self, block_number: BlockNumber) -> Option<impl Iterator<Item = &Log>>
where
T: Receipt,
{
let index = self.block_number_to_index(block_number)?;
Some(self.receipts[index].iter().filter_map(|r| Some(r.as_ref()?.logs().iter())).flatten())
}
/// Return blocks logs bloom
pub fn block_logs_bloom(&self, block_number: BlockNumber) -> Option<Bloom>
where
T: Receipt,
{
Some(logs_bloom(self.logs(block_number)?))
}
/// Returns the receipt root for all recorded receipts.
/// Note: this function calculated Bloom filters for every receipt and created merkle trees
/// of receipt. This is a expensive operation.
pub fn receipts_root_slow(&self, _block_number: BlockNumber) -> Option<B256>
where
T: Receipt,
{
#[cfg(feature = "optimism")]
panic!("This should not be called in optimism mode. Use `optimism_receipts_root_slow` instead.");
#[cfg(not(feature = "optimism"))]
self.receipts.root_slow(self.block_number_to_index(_block_number)?, T::receipts_root)
}
/// Returns the receipt root for all recorded receipts. /// Returns the receipt root for all recorded receipts.
/// Note: this function calculated Bloom filters for every receipt and created merkle trees /// Note: this function calculated Bloom filters for every receipt and created merkle trees
/// of receipt. This is a expensive operation. /// of receipt. This is a expensive operation.
@ -364,6 +334,32 @@ impl<T> ExecutionOutcome<T> {
} }
} }
impl<T: Receipt> ExecutionOutcome<T> {
/// Returns an iterator over all block logs.
pub fn logs(&self, block_number: BlockNumber) -> Option<impl Iterator<Item = &Log>> {
let index = self.block_number_to_index(block_number)?;
Some(self.receipts[index].iter().filter_map(|r| Some(r.as_ref()?.logs().iter())).flatten())
}
/// Return blocks logs bloom
pub fn block_logs_bloom(&self, block_number: BlockNumber) -> Option<Bloom> {
Some(logs_bloom(self.logs(block_number)?))
}
/// Returns the receipt root for all recorded receipts.
/// Note: this function calculated Bloom filters for every receipt and created merkle trees
/// of receipt. This is a expensive operation.
pub fn receipts_root_slow(&self, _block_number: BlockNumber) -> Option<B256>
where
T: ReceiptExt,
{
#[cfg(feature = "optimism")]
panic!("This should not be called in optimism mode. Use `optimism_receipts_root_slow` instead.");
#[cfg(not(feature = "optimism"))]
self.receipts.root_slow(self.block_number_to_index(_block_number)?, T::receipts_root)
}
}
impl<T> From<(BlockExecutionOutput<T>, BlockNumber)> for ExecutionOutcome<T> { impl<T> From<(BlockExecutionOutput<T>, BlockNumber)> for ExecutionOutcome<T> {
fn from(value: (BlockExecutionOutput<T>, BlockNumber)) -> Self { fn from(value: (BlockExecutionOutput<T>, BlockNumber)) -> Self {
Self { Self {

View File

@ -27,6 +27,7 @@ byteorder = "1"
derive_more.workspace = true derive_more.workspace = true
roaring = "0.10.2" roaring = "0.10.2"
serde_with = { workspace = true, optional = true } serde_with = { workspace = true, optional = true }
auto_impl.workspace = true
# required by reth-codecs # required by reth-codecs
bytes.workspace = true bytes.workspace = true

View File

@ -5,6 +5,7 @@ use alloc::fmt;
use alloy_consensus::Transaction; use alloy_consensus::Transaction;
/// Abstraction for block's body. /// Abstraction for block's body.
#[auto_impl::auto_impl(&, Arc)]
pub trait BlockBody: pub trait BlockBody:
Send Send
+ Sync + Sync
@ -19,7 +20,6 @@ pub trait BlockBody:
+ alloy_rlp::Encodable + alloy_rlp::Encodable
+ alloy_rlp::Decodable + alloy_rlp::Decodable
+ InMemorySize + InMemorySize
+ 'static
{ {
/// Ordered list of signed transactions as committed in block. /// Ordered list of signed transactions as committed in block.
// todo: requires trait for signed transaction // todo: requires trait for signed transaction

View File

@ -26,7 +26,6 @@ pub trait BlockHeader:
+ alloy_consensus::BlockHeader + alloy_consensus::BlockHeader
+ Sealable + Sealable
+ InMemorySize + InMemorySize
+ 'static
{ {
} }
@ -46,6 +45,5 @@ impl<T> BlockHeader for T where
+ alloy_consensus::BlockHeader + alloy_consensus::BlockHeader
+ Sealable + Sealable
+ InMemorySize + InMemorySize
+ 'static
{ {
} }

View File

@ -18,6 +18,7 @@ impl<T> FullBlock for T where T: Block<Header: FullBlockHeader> + Compact {}
// todo: make sealable super-trait, depends on <https://github.com/paradigmxyz/reth/issues/11449> // todo: make sealable super-trait, depends on <https://github.com/paradigmxyz/reth/issues/11449>
// todo: make with senders extension trait, so block can be impl by block type already containing // todo: make with senders extension trait, so block can be impl by block type already containing
// senders // senders
#[auto_impl::auto_impl(&, Arc)]
pub trait Block: pub trait Block:
Send Send
+ Sync + Sync
@ -32,7 +33,7 @@ pub trait Block:
+ InMemorySize + InMemorySize
{ {
/// Header part of the block. /// Header part of the block.
type Header: BlockHeader; type Header: BlockHeader + 'static;
/// The block's body contains the transactions in the block. /// The block's body contains the transactions in the block.
type Body: Send + Sync + Unpin + 'static; type Body: Send + Sync + Unpin + 'static;

View File

@ -10,9 +10,10 @@ use serde::{Deserialize, Serialize};
/// Helper trait that unifies all behaviour required by receipt to support full node operations. /// Helper trait that unifies all behaviour required by receipt to support full node operations.
pub trait FullReceipt: Receipt + Compact {} pub trait FullReceipt: Receipt + Compact {}
impl<T> FullReceipt for T where T: Receipt + Compact {} impl<T> FullReceipt for T where T: ReceiptExt + Compact {}
/// Abstraction of a receipt. /// Abstraction of a receipt.
#[auto_impl::auto_impl(&, Arc)]
pub trait Receipt: pub trait Receipt:
Send Send
+ Sync + Sync
@ -28,7 +29,10 @@ pub trait Receipt:
{ {
/// Returns transaction type. /// Returns transaction type.
fn tx_type(&self) -> u8; fn tx_type(&self) -> u8;
}
/// Extension if [`Receipt`] used in block execution.
pub trait ReceiptExt: Receipt {
/// Calculates the receipts root of the given receipts. /// Calculates the receipts root of the given receipts.
fn receipts_root(receipts: &[&Self]) -> B256; fn receipts_root(receipts: &[&Self]) -> B256;
} }

View File

@ -1,4 +1,5 @@
/// Trait for calculating a heuristic for the in-memory size of a struct. /// Trait for calculating a heuristic for the in-memory size of a struct.
#[auto_impl::auto_impl(&, Arc, Box)]
pub trait InMemorySize { pub trait InMemorySize {
/// Returns a heuristic for the in-memory size of a struct. /// Returns a heuristic for the in-memory size of a struct.
fn size(&self) -> usize; fn size(&self) -> usize;

View File

@ -53,6 +53,7 @@ impl<T> Transaction for T where
} }
/// Extension trait of [`alloy_consensus::Transaction`]. /// Extension trait of [`alloy_consensus::Transaction`].
#[auto_impl::auto_impl(&, Arc)]
pub trait TransactionExt: alloy_consensus::Transaction { pub trait TransactionExt: alloy_consensus::Transaction {
/// Transaction envelope type ID. /// Transaction envelope type ID.
type Type: TxType; type Type: TxType;

View File

@ -8,7 +8,7 @@ use alloy_primitives::{keccak256, Address, PrimitiveSignature, TxHash, B256};
use reth_codecs::Compact; use reth_codecs::Compact;
use revm_primitives::TxEnv; use revm_primitives::TxEnv;
use crate::{transaction::TransactionExt, FullTransaction, MaybeArbitrary, Transaction}; use crate::{FullTransaction, MaybeArbitrary, Transaction};
/// Helper trait that unifies all behaviour required by block to support full node operations. /// Helper trait that unifies all behaviour required by block to support full node operations.
pub trait FullSignedTx: SignedTransaction<Transaction: FullTransaction> + Compact {} pub trait FullSignedTx: SignedTransaction<Transaction: FullTransaction> + Compact {}
@ -16,6 +16,7 @@ pub trait FullSignedTx: SignedTransaction<Transaction: FullTransaction> + Compac
impl<T> FullSignedTx for T where T: SignedTransaction<Transaction: FullTransaction> + Compact {} impl<T> FullSignedTx for T where T: SignedTransaction<Transaction: FullTransaction> + Compact {}
/// A signed transaction. /// A signed transaction.
#[auto_impl::auto_impl(&, Arc)]
pub trait SignedTransaction: pub trait SignedTransaction:
Send Send
+ Sync + Sync
@ -32,7 +33,7 @@ pub trait SignedTransaction:
+ alloy_rlp::Decodable + alloy_rlp::Decodable
+ Encodable2718 + Encodable2718
+ Decodable2718 + Decodable2718
+ TransactionExt + alloy_consensus::Transaction
+ MaybeArbitrary + MaybeArbitrary
{ {
/// Transaction type that is signed. /// Transaction type that is signed.
@ -65,14 +66,6 @@ pub trait SignedTransaction:
/// `reth_primitives::transaction::recover_signer_unchecked`. /// `reth_primitives::transaction::recover_signer_unchecked`.
fn recover_signer_unchecked(&self) -> Option<Address>; fn recover_signer_unchecked(&self) -> Option<Address>;
/// Create a new signed transaction from a transaction and its signature.
///
/// This will also calculate the transaction hash using its encoding.
fn from_transaction_and_signature(
transaction: Self::Transaction,
signature: PrimitiveSignature,
) -> Self;
/// Calculate transaction hash, eip2728 transaction does not contain rlp header and start with /// Calculate transaction hash, eip2728 transaction does not contain rlp header and start with
/// tx type. /// tx type.
fn recalculate_hash(&self) -> B256 { fn recalculate_hash(&self) -> B256 {
@ -83,10 +76,14 @@ pub trait SignedTransaction:
fn fill_tx_env(&self, tx_env: &mut TxEnv, sender: Address); fn fill_tx_env(&self, tx_env: &mut TxEnv, sender: Address);
} }
impl<T: SignedTransaction> TransactionExt for T { /// Helper trait used in testing.
type Type = <T::Transaction as TransactionExt>::Type; #[cfg(feature = "test-utils")]
pub trait SignedTransactionTesting: SignedTransaction {
fn signature_hash(&self) -> B256 { /// Create a new signed transaction from a transaction and its signature.
self.transaction().signature_hash() ///
} /// This will also calculate the transaction hash using its encoding.
fn from_transaction_and_signature(
transaction: Self::Transaction,
signature: PrimitiveSignature,
) -> Self;
} }

View File

@ -465,8 +465,8 @@ where
impl<H, B> reth_primitives_traits::Block for SealedBlock<H, B> impl<H, B> reth_primitives_traits::Block for SealedBlock<H, B>
where where
H: reth_primitives_traits::BlockHeader, H: reth_primitives_traits::BlockHeader + 'static,
B: reth_primitives_traits::BlockBody, B: reth_primitives_traits::BlockBody + 'static,
Self: Serialize + for<'a> Deserialize<'a>, Self: Serialize + for<'a> Deserialize<'a>,
{ {
type Header = H; type Header = H;

View File

@ -10,6 +10,7 @@ use alloy_primitives::{Bloom, Log, B256};
use alloy_rlp::{length_of_length, Decodable, Encodable, RlpDecodable, RlpEncodable}; use alloy_rlp::{length_of_length, Decodable, Encodable, RlpDecodable, RlpEncodable};
use bytes::{Buf, BufMut}; use bytes::{Buf, BufMut};
use derive_more::{DerefMut, From, IntoIterator}; use derive_more::{DerefMut, From, IntoIterator};
use reth_primitives_traits::receipt::ReceiptExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[cfg(feature = "reth-codec")] #[cfg(feature = "reth-codec")]
@ -97,7 +98,9 @@ impl reth_primitives_traits::Receipt for Receipt {
fn tx_type(&self) -> u8 { fn tx_type(&self) -> u8 {
self.tx_type as u8 self.tx_type as u8
} }
}
impl ReceiptExt for Receipt {
fn receipts_root(_receipts: &[&Self]) -> B256 { fn receipts_root(_receipts: &[&Self]) -> B256 {
#[cfg(feature = "optimism")] #[cfg(feature = "optimism")]
panic!("This should not be called in optimism mode. Use `optimism_receipts_root_slow` instead."); panic!("This should not be called in optimism mode. Use `optimism_receipts_root_slow` instead.");

View File

@ -1367,12 +1367,6 @@ impl SignedTransaction for TransactionSigned {
recover_signer_unchecked(&self.signature, signature_hash) recover_signer_unchecked(&self.signature, signature_hash)
} }
fn from_transaction_and_signature(transaction: Transaction, signature: Signature) -> Self {
let mut initial_tx = Self { transaction, hash: Default::default(), signature };
initial_tx.hash = initial_tx.recalculate_hash();
initial_tx
}
fn fill_tx_env(&self, tx_env: &mut TxEnv, sender: Address) { fn fill_tx_env(&self, tx_env: &mut TxEnv, sender: Address) {
tx_env.caller = sender; tx_env.caller = sender;
match self.as_ref() { match self.as_ref() {