reth_consensus/
lib.rs

1//! Consensus protocol functions
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
10#![cfg_attr(not(feature = "std"), no_std)]
11
12extern crate alloc;
13
14use alloc::{fmt::Debug, string::String, vec::Vec};
15use alloy_consensus::Header;
16use alloy_primitives::{BlockHash, BlockNumber, Bloom, B256};
17use reth_execution_types::BlockExecutionResult;
18use reth_primitives_traits::{
19    constants::{MAXIMUM_GAS_LIMIT_BLOCK, MINIMUM_GAS_LIMIT},
20    transaction::error::InvalidTransactionError,
21    Block, GotExpected, GotExpectedBoxed, NodePrimitives, RecoveredBlock, SealedBlock,
22    SealedHeader,
23};
24
25/// A consensus implementation that does nothing.
26pub mod noop;
27
28#[cfg(any(test, feature = "test-utils"))]
29/// test helpers for mocking consensus
30pub mod test_utils;
31
32/// [`Consensus`] implementation which knows full node primitives and is able to validation block's
33/// execution outcome.
34#[auto_impl::auto_impl(&, Arc)]
35pub trait FullConsensus<N: NodePrimitives>: Consensus<N::Block> {
36    /// Validate a block considering world state, i.e. things that can not be checked before
37    /// execution.
38    ///
39    /// See the Yellow Paper sections 4.3.2 "Holistic Validity".
40    ///
41    /// Note: validating blocks does not include other validations of the Consensus
42    fn validate_block_post_execution(
43        &self,
44        block: &RecoveredBlock<N::Block>,
45        result: &BlockExecutionResult<N::Receipt>,
46    ) -> Result<(), ConsensusError>;
47}
48
49/// Consensus is a protocol that chooses canonical chain.
50#[auto_impl::auto_impl(&, Arc)]
51pub trait Consensus<B: Block>: HeaderValidator<B::Header> {
52    /// The error type related to consensus.
53    type Error;
54
55    /// Ensures that body field values match the header.
56    fn validate_body_against_header(
57        &self,
58        body: &B::Body,
59        header: &SealedHeader<B::Header>,
60    ) -> Result<(), Self::Error>;
61
62    /// Validate a block disregarding world state, i.e. things that can be checked before sender
63    /// recovery and execution.
64    ///
65    /// See the Yellow Paper sections 4.3.2 "Holistic Validity", 4.3.4 "Block Header Validity", and
66    /// 11.1 "Ommer Validation".
67    ///
68    /// **This should not be called for the genesis block**.
69    ///
70    /// Note: validating blocks does not include other validations of the Consensus
71    fn validate_block_pre_execution(&self, block: &SealedBlock<B>) -> Result<(), Self::Error>;
72}
73
74/// HeaderValidator is a protocol that validates headers and their relationships.
75#[auto_impl::auto_impl(&, Arc)]
76pub trait HeaderValidator<H = Header>: Debug + Send + Sync {
77    /// Validate if header is correct and follows consensus specification.
78    ///
79    /// This is called on standalone header to check if all hashes are correct.
80    fn validate_header(&self, header: &SealedHeader<H>) -> Result<(), ConsensusError>;
81
82    /// Validate that the header information regarding parent are correct.
83    /// This checks the block number, timestamp, basefee and gas limit increment.
84    ///
85    /// This is called before properties that are not in the header itself (like total difficulty)
86    /// have been computed.
87    ///
88    /// **This should not be called for the genesis block**.
89    ///
90    /// Note: Validating header against its parent does not include other HeaderValidator
91    /// validations.
92    fn validate_header_against_parent(
93        &self,
94        header: &SealedHeader<H>,
95        parent: &SealedHeader<H>,
96    ) -> Result<(), ConsensusError>;
97
98    /// Validates the given headers
99    ///
100    /// This ensures that the first header is valid on its own and all subsequent headers are valid
101    /// on its own and valid against its parent.
102    ///
103    /// Note: this expects that the headers are in natural order (ascending block number)
104    fn validate_header_range(
105        &self,
106        headers: &[SealedHeader<H>],
107    ) -> Result<(), HeaderConsensusError<H>>
108    where
109        H: Clone,
110    {
111        if let Some((initial_header, remaining_headers)) = headers.split_first() {
112            self.validate_header(initial_header)
113                .map_err(|e| HeaderConsensusError(e, initial_header.clone()))?;
114            let mut parent = initial_header;
115            for child in remaining_headers {
116                self.validate_header(child).map_err(|e| HeaderConsensusError(e, child.clone()))?;
117                self.validate_header_against_parent(child, parent)
118                    .map_err(|e| HeaderConsensusError(e, child.clone()))?;
119                parent = child;
120            }
121        }
122        Ok(())
123    }
124}
125
126/// Consensus Errors
127#[derive(Debug, PartialEq, Eq, Clone, thiserror::Error)]
128pub enum ConsensusError {
129    /// Error when the gas used in the header exceeds the gas limit.
130    #[error("block used gas ({gas_used}) is greater than gas limit ({gas_limit})")]
131    HeaderGasUsedExceedsGasLimit {
132        /// The gas used in the block header.
133        gas_used: u64,
134        /// The gas limit in the block header.
135        gas_limit: u64,
136    },
137    /// Error when the gas the gas limit is more than the maximum allowed.
138    #[error(
139        "header gas limit ({gas_limit}) exceed the maximum allowed gas limit ({MAXIMUM_GAS_LIMIT_BLOCK})"
140    )]
141    HeaderGasLimitExceedsMax {
142        /// The gas limit in the block header.
143        gas_limit: u64,
144    },
145
146    /// Error when block gas used doesn't match expected value
147    #[error("block gas used mismatch: {gas}; gas spent by each transaction: {gas_spent_by_tx:?}")]
148    BlockGasUsed {
149        /// The gas diff.
150        gas: GotExpected<u64>,
151        /// Gas spent by each transaction
152        gas_spent_by_tx: Vec<(u64, u64)>,
153    },
154
155    /// Error when the hash of block ommer is different from the expected hash.
156    #[error("mismatched block ommer hash: {0}")]
157    BodyOmmersHashDiff(GotExpectedBoxed<B256>),
158
159    /// Error when the state root in the block is different from the expected state root.
160    #[error("mismatched block state root: {0}")]
161    BodyStateRootDiff(GotExpectedBoxed<B256>),
162
163    /// Error when the transaction root in the block is different from the expected transaction
164    /// root.
165    #[error("mismatched block transaction root: {0}")]
166    BodyTransactionRootDiff(GotExpectedBoxed<B256>),
167
168    /// Error when the receipt root in the block is different from the expected receipt root.
169    #[error("receipt root mismatch: {0}")]
170    BodyReceiptRootDiff(GotExpectedBoxed<B256>),
171
172    /// Error when header bloom filter is different from the expected bloom filter.
173    #[error("header bloom filter mismatch: {0}")]
174    BodyBloomLogDiff(GotExpectedBoxed<Bloom>),
175
176    /// Error when the withdrawals root in the block is different from the expected withdrawals
177    /// root.
178    #[error("mismatched block withdrawals root: {0}")]
179    BodyWithdrawalsRootDiff(GotExpectedBoxed<B256>),
180
181    /// Error when the requests hash in the block is different from the expected requests
182    /// hash.
183    #[error("mismatched block requests hash: {0}")]
184    BodyRequestsHashDiff(GotExpectedBoxed<B256>),
185
186    /// Error when a block with a specific hash and number is already known.
187    #[error("block with [hash={hash}, number={number}] is already known")]
188    BlockKnown {
189        /// The hash of the known block.
190        hash: BlockHash,
191        /// The block number of the known block.
192        number: BlockNumber,
193    },
194
195    /// Error when the parent hash of a block is not known.
196    #[error("block parent [hash={hash}] is not known")]
197    ParentUnknown {
198        /// The hash of the unknown parent block.
199        hash: BlockHash,
200    },
201
202    /// Error when the block number does not match the parent block number.
203    #[error(
204        "block number {block_number} does not match parent block number {parent_block_number}"
205    )]
206    ParentBlockNumberMismatch {
207        /// The parent block number.
208        parent_block_number: BlockNumber,
209        /// The block number.
210        block_number: BlockNumber,
211    },
212
213    /// Error when the parent hash does not match the expected parent hash.
214    #[error("mismatched parent hash: {0}")]
215    ParentHashMismatch(GotExpectedBoxed<B256>),
216
217    /// Error when the block timestamp is in the future compared to our clock time.
218    #[error(
219        "block timestamp {timestamp} is in the future compared to our clock time {present_timestamp}"
220    )]
221    TimestampIsInFuture {
222        /// The block's timestamp.
223        timestamp: u64,
224        /// The current timestamp.
225        present_timestamp: u64,
226    },
227
228    /// Error when the base fee is missing.
229    #[error("base fee missing")]
230    BaseFeeMissing,
231
232    /// Error when there is a transaction signer recovery error.
233    #[error("transaction signer recovery error")]
234    TransactionSignerRecoveryError,
235
236    /// Error when the extra data length exceeds the maximum allowed.
237    #[error("extra data {len} exceeds max length")]
238    ExtraDataExceedsMax {
239        /// The length of the extra data.
240        len: usize,
241    },
242
243    /// Error when the difficulty after a merge is not zero.
244    #[error("difficulty after merge is not zero")]
245    TheMergeDifficultyIsNotZero,
246
247    /// Error when the nonce after a merge is not zero.
248    #[error("nonce after merge is not zero")]
249    TheMergeNonceIsNotZero,
250
251    /// Error when the ommer root after a merge is not empty.
252    #[error("ommer root after merge is not empty")]
253    TheMergeOmmerRootIsNotEmpty,
254
255    /// Error when the withdrawals root is missing.
256    #[error("missing withdrawals root")]
257    WithdrawalsRootMissing,
258
259    /// Error when the requests hash is missing.
260    #[error("missing requests hash")]
261    RequestsHashMissing,
262
263    /// Error when an unexpected withdrawals root is encountered.
264    #[error("unexpected withdrawals root")]
265    WithdrawalsRootUnexpected,
266
267    /// Error when an unexpected requests hash is encountered.
268    #[error("unexpected requests hash")]
269    RequestsHashUnexpected,
270
271    /// Error when withdrawals are missing.
272    #[error("missing withdrawals")]
273    BodyWithdrawalsMissing,
274
275    /// Error when requests are missing.
276    #[error("missing requests")]
277    BodyRequestsMissing,
278
279    /// Error when blob gas used is missing.
280    #[error("missing blob gas used")]
281    BlobGasUsedMissing,
282
283    /// Error when unexpected blob gas used is encountered.
284    #[error("unexpected blob gas used")]
285    BlobGasUsedUnexpected,
286
287    /// Error when excess blob gas is missing.
288    #[error("missing excess blob gas")]
289    ExcessBlobGasMissing,
290
291    /// Error when unexpected excess blob gas is encountered.
292    #[error("unexpected excess blob gas")]
293    ExcessBlobGasUnexpected,
294
295    /// Error when the parent beacon block root is missing.
296    #[error("missing parent beacon block root")]
297    ParentBeaconBlockRootMissing,
298
299    /// Error when an unexpected parent beacon block root is encountered.
300    #[error("unexpected parent beacon block root")]
301    ParentBeaconBlockRootUnexpected,
302
303    /// Error when blob gas used exceeds the maximum allowed.
304    #[error("blob gas used {blob_gas_used} exceeds maximum allowance {max_blob_gas_per_block}")]
305    BlobGasUsedExceedsMaxBlobGasPerBlock {
306        /// The actual blob gas used.
307        blob_gas_used: u64,
308        /// The maximum allowed blob gas per block.
309        max_blob_gas_per_block: u64,
310    },
311
312    /// Error when blob gas used is not a multiple of blob gas per blob.
313    #[error(
314        "blob gas used {blob_gas_used} is not a multiple of blob gas per blob {blob_gas_per_blob}"
315    )]
316    BlobGasUsedNotMultipleOfBlobGasPerBlob {
317        /// The actual blob gas used.
318        blob_gas_used: u64,
319        /// The blob gas per blob.
320        blob_gas_per_blob: u64,
321    },
322
323    /// Error when excess blob gas is not a multiple of blob gas per blob.
324    #[error(
325        "excess blob gas {excess_blob_gas} is not a multiple of blob gas per blob {blob_gas_per_blob}"
326    )]
327    ExcessBlobGasNotMultipleOfBlobGasPerBlob {
328        /// The actual excess blob gas.
329        excess_blob_gas: u64,
330        /// The blob gas per blob.
331        blob_gas_per_blob: u64,
332    },
333
334    /// Error when the blob gas used in the header does not match the expected blob gas used.
335    #[error("blob gas used mismatch: {0}")]
336    BlobGasUsedDiff(GotExpected<u64>),
337
338    /// Error for a transaction that violates consensus.
339    #[error(transparent)]
340    InvalidTransaction(InvalidTransactionError),
341
342    /// Error when the block's base fee is different from the expected base fee.
343    #[error("block base fee mismatch: {0}")]
344    BaseFeeDiff(GotExpected<u64>),
345
346    /// Error when there is an invalid excess blob gas.
347    #[error(
348        "invalid excess blob gas: {diff}; \
349            parent excess blob gas: {parent_excess_blob_gas}, \
350            parent blob gas used: {parent_blob_gas_used}"
351    )]
352    ExcessBlobGasDiff {
353        /// The excess blob gas diff.
354        diff: GotExpected<u64>,
355        /// The parent excess blob gas.
356        parent_excess_blob_gas: u64,
357        /// The parent blob gas used.
358        parent_blob_gas_used: u64,
359    },
360
361    /// Error when the child gas limit exceeds the maximum allowed increase.
362    #[error("child gas_limit {child_gas_limit} max increase is {parent_gas_limit}/1024")]
363    GasLimitInvalidIncrease {
364        /// The parent gas limit.
365        parent_gas_limit: u64,
366        /// The child gas limit.
367        child_gas_limit: u64,
368    },
369
370    /// Error indicating that the child gas limit is below the minimum allowed limit.
371    ///
372    /// This error occurs when the child gas limit is less than the specified minimum gas limit.
373    #[error(
374        "child gas limit {child_gas_limit} is below the minimum allowed limit ({MINIMUM_GAS_LIMIT})"
375    )]
376    GasLimitInvalidMinimum {
377        /// The child gas limit.
378        child_gas_limit: u64,
379    },
380
381    /// Error indicating that the block gas limit is above the allowed maximum.
382    ///
383    /// This error occurs when the gas limit is more than the specified maximum gas limit.
384    #[error("child gas limit {block_gas_limit} is above the maximum allowed limit ({MAXIMUM_GAS_LIMIT_BLOCK})")]
385    GasLimitInvalidBlockMaximum {
386        /// block gas limit.
387        block_gas_limit: u64,
388    },
389
390    /// Error when the child gas limit exceeds the maximum allowed decrease.
391    #[error("child gas_limit {child_gas_limit} max decrease is {parent_gas_limit}/1024")]
392    GasLimitInvalidDecrease {
393        /// The parent gas limit.
394        parent_gas_limit: u64,
395        /// The child gas limit.
396        child_gas_limit: u64,
397    },
398
399    /// Error when the block timestamp is in the past compared to the parent timestamp.
400    #[error(
401        "block timestamp {timestamp} is in the past compared to the parent timestamp {parent_timestamp}"
402    )]
403    TimestampIsInPast {
404        /// The parent block's timestamp.
405        parent_timestamp: u64,
406        /// The block's timestamp.
407        timestamp: u64,
408    },
409    /// Other, likely an injected L2 error.
410    #[error("{0}")]
411    Other(String),
412}
413
414impl ConsensusError {
415    /// Returns `true` if the error is a state root error.
416    pub const fn is_state_root_error(&self) -> bool {
417        matches!(self, Self::BodyStateRootDiff(_))
418    }
419}
420
421impl From<InvalidTransactionError> for ConsensusError {
422    fn from(value: InvalidTransactionError) -> Self {
423        Self::InvalidTransaction(value)
424    }
425}
426
427/// `HeaderConsensusError` combines a `ConsensusError` with the `SealedHeader` it relates to.
428#[derive(thiserror::Error, Debug)]
429#[error("Consensus error: {0}, Invalid header: {1:?}")]
430pub struct HeaderConsensusError<H>(ConsensusError, SealedHeader<H>);