reth_storage_errors/
provider.rs

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