reth_storage_errors/
provider.rs

1use crate::{any::AnyError, db::DatabaseError};
2use alloc::{boxed::Box, string::String};
3use alloy_eips::{BlockHashOrNumber, HashOrNumber};
4use alloy_primitives::{Address, BlockHash, BlockNumber, TxNumber, B256};
5use derive_more::Display;
6use reth_primitives_traits::{transaction::signed::RecoveryError, GotExpected};
7use reth_prune_types::PruneSegmentError;
8use reth_static_file_types::StaticFileSegment;
9use revm_database_interface::DBErrorMarker;
10
11/// Provider result type.
12pub type ProviderResult<Ok> = Result<Ok, ProviderError>;
13
14/// Bundled errors variants thrown by various providers.
15#[derive(Clone, Debug, thiserror::Error)]
16pub enum ProviderError {
17    /// Database error.
18    #[error(transparent)]
19    Database(#[from] DatabaseError),
20    /// Pruning error.
21    #[error(transparent)]
22    Pruning(#[from] PruneSegmentError),
23    /// RLP error.
24    #[error("{_0}")]
25    Rlp(alloy_rlp::Error),
26    /// Trie witness error.
27    #[error("trie witness error: {_0}")]
28    TrieWitnessError(String),
29    /// Error when recovering the sender for a transaction
30    #[error("failed to recover sender for transaction")]
31    SenderRecoveryError,
32    /// The header number was not found for the given block hash.
33    #[error("block hash {_0} does not exist in Headers table")]
34    BlockHashNotFound(BlockHash),
35    /// A block body is missing.
36    #[error("block meta not found for block #{_0}")]
37    BlockBodyIndicesNotFound(BlockNumber),
38    /// The transition ID was found for the given address and storage key, but the changeset was
39    /// not found.
40    #[error(
41        "storage change set for address {address} and key {storage_key} at block #{block_number} does not exist"
42    )]
43    StorageChangesetNotFound {
44        /// The block number found for the address and storage key.
45        block_number: BlockNumber,
46        /// The account address.
47        address: Address,
48        /// The storage key.
49        // NOTE: This is a Box only because otherwise this variant is 16 bytes larger than the
50        // second largest (which uses `BlockHashOrNumber`).
51        storage_key: Box<B256>,
52    },
53    /// The block number was found for the given address, but the changeset was not found.
54    #[error("account change set for address {address} at block #{block_number} does not exist")]
55    AccountChangesetNotFound {
56        /// Block number found for the address.
57        block_number: BlockNumber,
58        /// The account address.
59        address: Address,
60    },
61    /// When required header related data was not found but was required.
62    #[error("no header found for {_0:?}")]
63    HeaderNotFound(BlockHashOrNumber),
64    /// The specific transaction identified by hash or id is missing.
65    #[error("no transaction found for {_0:?}")]
66    TransactionNotFound(HashOrNumber),
67    /// The specific receipt for a transaction identified by hash or id is missing
68    #[error("no receipt found for {_0:?}")]
69    ReceiptNotFound(HashOrNumber),
70    /// Unable to find the best block.
71    #[error("best block does not exist")]
72    BestBlockNotFound,
73    /// Unable to find the finalized block.
74    #[error("finalized block does not exist")]
75    FinalizedBlockNotFound,
76    /// Unable to find the safe block.
77    #[error("safe block does not exist")]
78    SafeBlockNotFound,
79    /// Thrown when we failed to lookup a block for the pending state.
80    #[error("unknown block {_0}")]
81    UnknownBlockHash(B256),
82    /// Thrown when we were unable to find a state for a block hash.
83    #[error("no state found for block {_0}")]
84    StateForHashNotFound(B256),
85    /// Thrown when we were unable to find a state for a block number.
86    #[error("no state found for block number {_0}")]
87    StateForNumberNotFound(u64),
88    /// Unable to find the block number for a given transaction index.
89    #[error("unable to find the block number for a given transaction index")]
90    BlockNumberForTransactionIndexNotFound,
91    /// Root mismatch.
92    #[error("merkle trie {_0}")]
93    StateRootMismatch(Box<RootMismatch>),
94    /// Root mismatch during unwind
95    #[error("unwind merkle trie {_0}")]
96    UnwindStateRootMismatch(Box<RootMismatch>),
97    /// State is not available for the given block number because it is pruned.
98    #[error("state at block #{_0} is pruned")]
99    StateAtBlockPruned(BlockNumber),
100    /// Provider does not support this particular request.
101    #[error("this provider does not support this request")]
102    UnsupportedProvider,
103    /// Static File is not found at specified path.
104    #[cfg(feature = "std")]
105    #[error("not able to find {_0} static file at {_1:?}")]
106    MissingStaticFilePath(StaticFileSegment, std::path::PathBuf),
107    /// Static File is not found for requested block.
108    #[error("not able to find {_0} static file for block number {_1}")]
109    MissingStaticFileBlock(StaticFileSegment, BlockNumber),
110    /// Static File is not found for requested transaction.
111    #[error("unable to find {_0} static file for transaction id {_1}")]
112    MissingStaticFileTx(StaticFileSegment, TxNumber),
113    /// Static File is finalized and cannot be written to.
114    #[error("unable to write block #{_1} to finalized static file {_0}")]
115    FinalizedStaticFile(StaticFileSegment, BlockNumber),
116    /// Trying to insert data from an unexpected block number.
117    #[error("trying to append data to {_0} as block #{_1} but expected block #{_2}")]
118    UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber),
119    /// Trying to insert data from an unexpected block number.
120    #[error("trying to append row to {_0} at index #{_1} but expected index #{_2}")]
121    UnexpectedStaticFileTxNumber(StaticFileSegment, TxNumber, TxNumber),
122    /// Static File Provider was initialized as read-only.
123    #[error("cannot get a writer on a read-only environment.")]
124    ReadOnlyStaticFileAccess,
125    /// Consistent view error.
126    #[error("failed to initialize consistent view: {_0}")]
127    ConsistentView(Box<ConsistentViewError>),
128    /// Received invalid output from configured storage implementation.
129    #[error("received invalid output from storage")]
130    InvalidStorageOutput,
131    /// Missing trie updates.
132    #[error("missing trie updates for block {0}")]
133    MissingTrieUpdates(B256),
134    /// Insufficient changesets to revert to the requested block.
135    #[error("insufficient changesets to revert to block #{requested}. Available changeset range: {available:?}")]
136    InsufficientChangesets {
137        /// The block number requested for reversion
138        requested: BlockNumber,
139        /// The available range of blocks with changesets
140        available: core::ops::RangeInclusive<BlockNumber>,
141    },
142    /// Any other error type wrapped into a cloneable [`AnyError`].
143    #[error(transparent)]
144    Other(#[from] AnyError),
145}
146
147impl ProviderError {
148    /// Creates a new [`ProviderError::Other`] variant by wrapping the given error into an
149    /// [`AnyError`]
150    pub fn other<E>(error: E) -> Self
151    where
152        E: core::error::Error + Send + Sync + 'static,
153    {
154        Self::Other(AnyError::new(error))
155    }
156
157    /// Returns the arbitrary error if it is [`ProviderError::Other`]
158    pub fn as_other(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
159        match self {
160            Self::Other(err) => Some(err.as_error()),
161            _ => None,
162        }
163    }
164
165    /// Returns a reference to the [`ProviderError::Other`] value if this type is a
166    /// [`ProviderError::Other`] and the [`AnyError`] wraps an error of that type. Returns None
167    /// otherwise.
168    pub fn downcast_other_ref<T: core::error::Error + 'static>(&self) -> Option<&T> {
169        let other = self.as_other()?;
170        other.downcast_ref()
171    }
172
173    /// Returns true if the this type is a [`ProviderError::Other`] of that error
174    /// type. Returns false otherwise.
175    pub fn is_other<T: core::error::Error + 'static>(&self) -> bool {
176        self.as_other().map(|err| err.is::<T>()).unwrap_or(false)
177    }
178}
179
180impl DBErrorMarker for ProviderError {}
181
182impl From<alloy_rlp::Error> for ProviderError {
183    fn from(error: alloy_rlp::Error) -> Self {
184        Self::Rlp(error)
185    }
186}
187
188impl From<RecoveryError> for ProviderError {
189    fn from(_: RecoveryError) -> Self {
190        Self::SenderRecoveryError
191    }
192}
193
194/// A root mismatch error at a given block height.
195#[derive(Clone, Debug, PartialEq, Eq, Display)]
196#[display("root mismatch at #{block_number} ({block_hash}): {root}")]
197pub struct RootMismatch {
198    /// The target block root diff.
199    pub root: GotExpected<B256>,
200    /// The target block number.
201    pub block_number: BlockNumber,
202    /// The target block hash.
203    pub block_hash: BlockHash,
204}
205
206/// A Static File Write Error.
207#[derive(Debug, thiserror::Error)]
208#[error("{message}")]
209pub struct StaticFileWriterError {
210    /// The error message.
211    pub message: String,
212}
213
214impl StaticFileWriterError {
215    /// Creates a new [`StaticFileWriterError`] with the given message.
216    pub fn new(message: impl Into<String>) -> Self {
217        Self { message: message.into() }
218    }
219}
220/// Consistent database view error.
221#[derive(Clone, Debug, PartialEq, Eq, Display)]
222pub enum ConsistentViewError {
223    /// Error thrown on attempt to initialize provider while node is still syncing.
224    #[display("node is syncing. best block: {best_block:?}")]
225    Syncing {
226        /// Best block diff.
227        best_block: GotExpected<BlockNumber>,
228    },
229    /// Error thrown on inconsistent database view.
230    #[display("inconsistent database state: {tip:?}")]
231    Inconsistent {
232        /// The tip diff.
233        tip: GotExpected<Option<B256>>,
234    },
235    /// Error thrown when the database does not contain a block from the previous database view.
236    #[display("database view no longer contains block: {block:?}")]
237    Reorged {
238        /// The previous block
239        block: B256,
240    },
241}
242
243impl From<ConsistentViewError> for ProviderError {
244    fn from(error: ConsistentViewError) -> Self {
245        Self::ConsistentView(Box::new(error))
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[derive(thiserror::Error, Debug)]
254    #[error("E")]
255    struct E;
256
257    #[test]
258    fn other_err() {
259        let err = ProviderError::other(E);
260        assert!(err.is_other::<E>());
261        assert!(err.downcast_other_ref::<E>().is_some());
262    }
263}