Skip to main content

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_codecs::DecompressError;
7use reth_primitives_traits::{transaction::signed::RecoveryError, GotExpected};
8use reth_prune_types::PruneSegmentError;
9use reth_static_file_types::StaticFileSegment;
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    /// Static file writer error.
24    #[error(transparent)]
25    StaticFileWriter(#[from] StaticFileWriterError),
26    /// RLP error.
27    #[error("{_0}")]
28    Rlp(alloy_rlp::Error),
29    /// Trie witness error.
30    #[error("trie witness error: {_0}")]
31    TrieWitnessError(String),
32    /// Error when recovering the sender for a transaction
33    #[error("failed to recover sender for transaction")]
34    SenderRecoveryError,
35    /// The header number was not found for the given block hash.
36    #[error("block hash {_0} does not exist in Headers table")]
37    BlockHashNotFound(BlockHash),
38    /// A block body is missing.
39    #[error("block meta not found for block #{_0}")]
40    BlockBodyIndicesNotFound(BlockNumber),
41    /// The transition ID was found for the given address and storage key, but the changeset was
42    /// not found.
43    #[error(
44        "storage change set for address {address} and key {storage_key} at block #{block_number} does not exist"
45    )]
46    StorageChangesetNotFound {
47        /// The block number found for the address and storage key.
48        block_number: BlockNumber,
49        /// The account address.
50        address: Address,
51        /// The storage key.
52        // NOTE: This is a Box only because otherwise this variant is 16 bytes larger than the
53        // second largest (which uses `BlockHashOrNumber`).
54        storage_key: Box<B256>,
55    },
56    /// The block number was found for the given address, but the changeset was not found.
57    #[error("account change set for address {address} at block #{block_number} does not exist")]
58    AccountChangesetNotFound {
59        /// Block number found for the address.
60        block_number: BlockNumber,
61        /// The account address.
62        address: Address,
63    },
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    /// The pipeline has committed state past the last finished block.
104    #[error("historical state is temporarily unavailable during pipeline sync; try again later")]
105    StateUnavailableDuringSync,
106    /// State is not available because the block has not been executed yet.
107    #[error("state at block #{requested} is not available, block has not been executed yet (latest executed: #{executed})")]
108    BlockNotExecuted {
109        /// The block number that was requested.
110        requested: BlockNumber,
111        /// The latest executed block number.
112        executed: BlockNumber,
113    },
114    /// Block data is not available because history has expired.
115    ///
116    /// The requested block number is below the earliest available block.
117    #[error("block #{requested} is not available, history has expired (earliest available: #{earliest_available})")]
118    BlockExpired {
119        /// The block number that was requested.
120        requested: BlockNumber,
121        /// The earliest available block number.
122        earliest_available: BlockNumber,
123    },
124    /// Provider does not support this particular request.
125    #[error("this provider does not support this request")]
126    UnsupportedProvider,
127    /// Static File is not found at specified path.
128    #[cfg(feature = "std")]
129    #[error("not able to find {_0} static file at {_1:?}")]
130    MissingStaticFileSegmentPath(StaticFileSegment, std::path::PathBuf),
131    /// Static File is not found at specified path.
132    #[cfg(feature = "std")]
133    #[error("not able to find static file at {_0:?}")]
134    MissingStaticFilePath(std::path::PathBuf),
135    /// Highest block is not found for static file block.
136    #[error("highest block is not found for {_0} static file")]
137    MissingHighestStaticFileBlock(StaticFileSegment),
138    /// Static File is not found for requested block.
139    #[error("not able to find {_0} static file for block number {_1}")]
140    MissingStaticFileBlock(StaticFileSegment, BlockNumber),
141    /// Static File is not found for requested transaction.
142    #[error("unable to find {_0} static file for transaction id {_1}")]
143    MissingStaticFileTx(StaticFileSegment, TxNumber),
144    /// Static File is finalized and cannot be written to.
145    #[error("unable to write block #{_1} to finalized static file {_0}")]
146    FinalizedStaticFile(StaticFileSegment, BlockNumber),
147    /// Trying to insert data from an unexpected block number.
148    #[error("trying to append data to {_0} as block #{_1} but expected block #{_2}")]
149    UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber),
150    /// Trying to insert data from an unexpected block number.
151    #[error("trying to append row to {_0} at index #{_1} but expected index #{_2}")]
152    UnexpectedStaticFileTxNumber(StaticFileSegment, TxNumber, TxNumber),
153    /// Changeset static file is corrupted, and does not have offsets for changesets in each block
154    #[error("changeset static file is corrupted, missing offsets for changesets in each block")]
155    CorruptedChangeSetStaticFile,
156    /// Error when constructing hashed post state reverts
157    #[error("Unbounded start is unsupported in from_reverts")]
158    UnboundedStartUnsupported,
159    /// Static File Provider was initialized as read-only.
160    #[error("cannot get a writer on a read-only environment.")]
161    ReadOnlyStaticFileAccess,
162    /// Consistent view error.
163    #[error("failed to initialize consistent view: {_0}")]
164    ConsistentView(Box<ConsistentViewError>),
165    /// Received invalid output from configured storage implementation.
166    #[error("received invalid output from storage")]
167    InvalidStorageOutput,
168    /// Missing trie updates.
169    #[error("missing trie updates for block {0}")]
170    MissingTrieUpdates(B256),
171    /// Insufficient changesets to revert to the requested block.
172    #[error("insufficient changesets to revert to block #{requested}. Available changeset range: {available:?}")]
173    InsufficientChangesets {
174        /// The block number requested for reversion
175        requested: BlockNumber,
176        /// The available range of blocks with changesets
177        available: core::ops::RangeInclusive<BlockNumber>,
178    },
179    /// Inconsistency detected between static files/rocksdb and the DB during
180    /// `ProviderFactory::check_consistency`. The database must be unwound to
181    /// the specified block number to restore consistency.
182    #[error("consistency check failed for {data_source}. Db must be unwound to {unwind_to}")]
183    MustUnwind {
184        /// The inconsistent data source(s).
185        data_source: &'static str,
186        /// The block number to which the database must be unwound.
187        unwind_to: BlockNumber,
188    },
189    /// A persisted snap attempt record this build cannot read.
190    #[error(
191        "snap attempt record version {found:?} is not supported, this build writes {supported}"
192    )]
193    UnsupportedSnapAttemptVersion {
194        /// Version found on disk, absent when the record carries no numeric version.
195        found: Option<u64>,
196        /// Version this build writes.
197        supported: u32,
198    },
199    /// Snap sync was selected on a database that predates the hashed state layout it downloads
200    /// into.
201    #[error("snap sync requires the hashed state layout, which this database predates")]
202    SnapStorageLayoutUnsupported,
203    /// State a snap attempt is still downloading was about to be marked complete.
204    #[error("snap attempt {attempt} has not verified the downloaded state")]
205    UnverifiedSnapState {
206        /// Attempt that owns the unverified state.
207        attempt: u64,
208    },
209    /// The staged pipeline was selected on a database holding state a snap attempt left
210    /// unverified, which only snap can finish or replace.
211    #[error(
212        "snap attempt {attempt} left unverified state, restart with snap sync or wipe the database"
213    )]
214    SnapStateRequiresSnapSync {
215        /// Attempt that owns the unverified state.
216        attempt: u64,
217    },
218    /// Any other error type wrapped into a cloneable [`AnyError`].
219    #[error(transparent)]
220    Other(#[from] AnyError),
221}
222
223impl ProviderError {
224    /// Creates a new [`ProviderError::Other`] variant by wrapping the given error into an
225    /// [`AnyError`]
226    pub fn other<E>(error: E) -> Self
227    where
228        E: core::error::Error + Send + Sync + 'static,
229    {
230        Self::Other(AnyError::new(error))
231    }
232
233    /// Returns the arbitrary error if it is [`ProviderError::Other`]
234    pub fn as_other(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
235        match self {
236            Self::Other(err) => Some(err.as_error()),
237            _ => None,
238        }
239    }
240
241    /// Returns a reference to the [`ProviderError::Other`] value if this type is a
242    /// [`ProviderError::Other`] and the [`AnyError`] wraps an error of that type. Returns None
243    /// otherwise.
244    pub fn downcast_other_ref<T: core::error::Error + 'static>(&self) -> Option<&T> {
245        let other = self.as_other()?;
246        other.downcast_ref()
247    }
248
249    /// Returns true if this type is a [`ProviderError::Other`] of that error
250    /// type. Returns false otherwise.
251    pub fn is_other<T: core::error::Error + 'static>(&self) -> bool {
252        self.as_other().is_some_and(|err| err.is::<T>())
253    }
254}
255
256impl From<alloy_rlp::Error> for ProviderError {
257    fn from(error: alloy_rlp::Error) -> Self {
258        Self::Rlp(error)
259    }
260}
261
262impl From<RecoveryError> for ProviderError {
263    fn from(_: RecoveryError) -> Self {
264        Self::SenderRecoveryError
265    }
266}
267
268impl From<DecompressError> for ProviderError {
269    fn from(error: DecompressError) -> Self {
270        Self::Database(error.into())
271    }
272}
273
274/// A root mismatch error at a given block height.
275#[derive(Clone, Debug, PartialEq, Eq, Display)]
276#[display("root mismatch at #{block_number} ({block_hash}): {root}")]
277pub struct RootMismatch {
278    /// The target block root diff.
279    pub root: GotExpected<B256>,
280    /// The target block number.
281    pub block_number: BlockNumber,
282    /// The target block hash.
283    pub block_hash: BlockHash,
284}
285
286/// A Static File Writer Error.
287#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
288pub enum StaticFileWriterError {
289    /// Cannot call `sync_all` or `finalize` when prune is queued.
290    #[error("cannot call sync_all or finalize when prune is queued, use commit() instead")]
291    FinalizeWithPruneQueued,
292    /// Thread panicked during execution.
293    #[error("thread panicked: {_0}")]
294    ThreadPanic(&'static str),
295    /// Other error with message.
296    #[error("{0}")]
297    Other(String),
298    /// An unwind would keep blocks below the block a pruned segment is anchored at, which the
299    /// segment no longer stores.
300    #[error("cannot unwind {segment} to block {target} below the pruned anchor at block {anchor}")]
301    UnwindBelowPrunedAnchor {
302        /// Segment being unwound.
303        segment: StaticFileSegment,
304        /// Highest block the unwind would keep.
305        target: BlockNumber,
306        /// Lowest block the segment stores.
307        anchor: BlockNumber,
308    },
309}
310
311impl StaticFileWriterError {
312    /// Creates a new [`StaticFileWriterError::Other`] with the given message.
313    pub fn new(message: impl Into<String>) -> Self {
314        Self::Other(message.into())
315    }
316}
317/// Consistent database view error.
318#[derive(Clone, Debug, PartialEq, Eq, Display)]
319pub enum ConsistentViewError {
320    /// Error thrown on attempt to initialize provider while node is still syncing.
321    #[display("node is syncing. best block: {best_block:?}")]
322    Syncing {
323        /// Best block diff.
324        best_block: GotExpected<BlockNumber>,
325    },
326    /// Error thrown on inconsistent database view.
327    #[display("inconsistent database state: {tip:?}")]
328    Inconsistent {
329        /// The tip diff.
330        tip: GotExpected<Option<B256>>,
331    },
332    /// Error thrown when the database does not contain a block from the previous database view.
333    #[display("database view no longer contains block: {block:?}")]
334    Reorged {
335        /// The previous block
336        block: B256,
337    },
338}
339
340impl From<ConsistentViewError> for ProviderError {
341    fn from(error: ConsistentViewError) -> Self {
342        Self::ConsistentView(Box::new(error))
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[derive(thiserror::Error, Debug)]
351    #[error("E")]
352    struct E;
353
354    #[test]
355    fn other_err() {
356        let err = ProviderError::other(E);
357        assert!(err.is_other::<E>());
358        assert!(err.downcast_other_ref::<E>().is_some());
359    }
360}