reth_storage_errors/
provider.rs

1use crate::{any::AnyError, db::DatabaseError, writer::UnifiedStorageWriterError};
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    /// The total difficulty for a block is missing.
62    #[error("total difficulty not found for block #{_0}")]
63    TotalDifficultyNotFound(BlockNumber),
64    /// When required header related data was not found but was required.
65    #[error("no header found for {_0:?}")]
66    HeaderNotFound(BlockHashOrNumber),
67    /// The specific transaction identified by hash or id is missing.
68    #[error("no transaction found for {_0:?}")]
69    TransactionNotFound(HashOrNumber),
70    /// The specific receipt for a transaction identified by hash or id is missing
71    #[error("no receipt found for {_0:?}")]
72    ReceiptNotFound(HashOrNumber),
73    /// Unable to find the best block.
74    #[error("best block does not exist")]
75    BestBlockNotFound,
76    /// Unable to find the finalized block.
77    #[error("finalized block does not exist")]
78    FinalizedBlockNotFound,
79    /// Unable to find the safe block.
80    #[error("safe block does not exist")]
81    SafeBlockNotFound,
82    /// Thrown when we failed to lookup a block for the pending state.
83    #[error("unknown block {_0}")]
84    UnknownBlockHash(B256),
85    /// Thrown when we were unable to find a state for a block hash.
86    #[error("no state found for block {_0}")]
87    StateForHashNotFound(B256),
88    /// Thrown when we were unable to find a state for a block number.
89    #[error("no state found for block number {_0}")]
90    StateForNumberNotFound(u64),
91    /// Unable to find the block number for a given transaction index.
92    #[error("unable to find the block number for a given transaction index")]
93    BlockNumberForTransactionIndexNotFound,
94    /// Root mismatch.
95    #[error("merkle trie {_0}")]
96    StateRootMismatch(Box<RootMismatch>),
97    /// Root mismatch during unwind
98    #[error("unwind merkle trie {_0}")]
99    UnwindStateRootMismatch(Box<RootMismatch>),
100    /// State is not available for the given block number because it is pruned.
101    #[error("state at block #{_0} is pruned")]
102    StateAtBlockPruned(BlockNumber),
103    /// Provider does not support this particular request.
104    #[error("this provider does not support this request")]
105    UnsupportedProvider,
106    /// Static File is not found at specified path.
107    #[cfg(feature = "std")]
108    #[error("not able to find {_0} static file at {_1:?}")]
109    MissingStaticFilePath(StaticFileSegment, std::path::PathBuf),
110    /// Static File is not found for requested block.
111    #[error("not able to find {_0} static file for block number {_1}")]
112    MissingStaticFileBlock(StaticFileSegment, BlockNumber),
113    /// Static File is not found for requested transaction.
114    #[error("unable to find {_0} static file for transaction id {_1}")]
115    MissingStaticFileTx(StaticFileSegment, TxNumber),
116    /// Static File is finalized and cannot be written to.
117    #[error("unable to write block #{_1} to finalized static file {_0}")]
118    FinalizedStaticFile(StaticFileSegment, BlockNumber),
119    /// Trying to insert data from an unexpected block number.
120    #[error("trying to append data to {_0} as block #{_1} but expected block #{_2}")]
121    UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber),
122    /// Trying to insert data from an unexpected block number.
123    #[error("trying to append row to {_0} at index #{_1} but expected index #{_2}")]
124    UnexpectedStaticFileTxNumber(StaticFileSegment, TxNumber, TxNumber),
125    /// Static File Provider was initialized as read-only.
126    #[error("cannot get a writer on a read-only environment.")]
127    ReadOnlyStaticFileAccess,
128    /// Consistent view error.
129    #[error("failed to initialize consistent view: {_0}")]
130    ConsistentView(Box<ConsistentViewError>),
131    /// Storage writer error.
132    #[error(transparent)]
133    UnifiedStorageWriterError(#[from] UnifiedStorageWriterError),
134    /// Received invalid output from configured storage implementation.
135    #[error("received invalid output from storage")]
136    InvalidStorageOutput,
137    /// Missing trie updates.
138    #[error("missing trie updates for block {0}")]
139    MissingTrieUpdates(B256),
140    /// Any other error type wrapped into a cloneable [`AnyError`].
141    #[error(transparent)]
142    Other(#[from] AnyError),
143}
144
145impl ProviderError {
146    /// Creates a new [`ProviderError::Other`] variant by wrapping the given error into an
147    /// [`AnyError`]
148    pub fn other<E>(error: E) -> Self
149    where
150        E: core::error::Error + Send + Sync + 'static,
151    {
152        Self::Other(AnyError::new(error))
153    }
154
155    /// Returns the arbitrary error if it is [`ProviderError::Other`]
156    pub fn as_other(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
157        match self {
158            Self::Other(err) => Some(err.as_error()),
159            _ => None,
160        }
161    }
162
163    /// Returns a reference to the [`ProviderError::Other`] value if this type is a
164    /// [`ProviderError::Other`] and the [`AnyError`] wraps an error of that type. Returns None
165    /// otherwise.
166    pub fn downcast_other_ref<T: core::error::Error + 'static>(&self) -> Option<&T> {
167        let other = self.as_other()?;
168        other.downcast_ref()
169    }
170
171    /// Returns true if the this type is a [`ProviderError::Other`] of that error
172    /// type. Returns false otherwise.
173    pub fn is_other<T: core::error::Error + 'static>(&self) -> bool {
174        self.as_other().map(|err| err.is::<T>()).unwrap_or(false)
175    }
176}
177
178impl DBErrorMarker for ProviderError {}
179
180impl From<alloy_rlp::Error> for ProviderError {
181    fn from(error: alloy_rlp::Error) -> Self {
182        Self::Rlp(error)
183    }
184}
185
186impl From<RecoveryError> for ProviderError {
187    fn from(_: RecoveryError) -> Self {
188        Self::SenderRecoveryError
189    }
190}
191
192/// A root mismatch error at a given block height.
193#[derive(Clone, Debug, PartialEq, Eq, Display)]
194#[display("root mismatch at #{block_number} ({block_hash}): {root}")]
195pub struct RootMismatch {
196    /// The target block root diff.
197    pub root: GotExpected<B256>,
198    /// The target block number.
199    pub block_number: BlockNumber,
200    /// The target block hash.
201    pub block_hash: BlockHash,
202}
203
204/// A Static File Write Error.
205#[derive(Debug, thiserror::Error)]
206#[error("{message}")]
207pub struct StaticFileWriterError {
208    /// The error message.
209    pub message: String,
210}
211
212impl StaticFileWriterError {
213    /// Creates a new [`StaticFileWriterError`] with the given message.
214    pub fn new(message: impl Into<String>) -> Self {
215        Self { message: message.into() }
216    }
217}
218/// Consistent database view error.
219#[derive(Clone, Debug, PartialEq, Eq, Display)]
220pub enum ConsistentViewError {
221    /// Error thrown on attempt to initialize provider while node is still syncing.
222    #[display("node is syncing. best block: {best_block:?}")]
223    Syncing {
224        /// Best block diff.
225        best_block: GotExpected<BlockNumber>,
226    },
227    /// Error thrown on inconsistent database view.
228    #[display("inconsistent database state: {tip:?}")]
229    Inconsistent {
230        /// The tip diff.
231        tip: GotExpected<Option<B256>>,
232    },
233    /// Error thrown when the database does not contain a block from the previous database view.
234    #[display("database view no longer contains block: {block:?}")]
235    Reorged {
236        /// The previous block
237        block: B256,
238    },
239}
240
241impl From<ConsistentViewError> for ProviderError {
242    fn from(error: ConsistentViewError) -> Self {
243        Self::ConsistentView(Box::new(error))
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[derive(thiserror::Error, Debug)]
252    #[error("E")]
253    struct E;
254
255    #[test]
256    fn other_err() {
257        let err = ProviderError::other(E);
258        assert!(err.is_other::<E>());
259        assert!(err.downcast_other_ref::<E>().is_some());
260    }
261}