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
11pub type ProviderResult<Ok> = Result<Ok, ProviderError>;
13
14#[derive(Clone, Debug, thiserror::Error)]
16pub enum ProviderError {
17 #[error(transparent)]
19 Database(#[from] DatabaseError),
20 #[error(transparent)]
22 Pruning(#[from] PruneSegmentError),
23 #[error(transparent)]
25 StaticFileWriter(#[from] StaticFileWriterError),
26 #[error("{_0}")]
28 Rlp(alloy_rlp::Error),
29 #[error("trie witness error: {_0}")]
31 TrieWitnessError(String),
32 #[error("failed to recover sender for transaction")]
34 SenderRecoveryError,
35 #[error("block hash {_0} does not exist in Headers table")]
37 BlockHashNotFound(BlockHash),
38 #[error("block meta not found for block #{_0}")]
40 BlockBodyIndicesNotFound(BlockNumber),
41 #[error(
44 "storage change set for address {address} and key {storage_key} at block #{block_number} does not exist"
45 )]
46 StorageChangesetNotFound {
47 block_number: BlockNumber,
49 address: Address,
51 storage_key: Box<B256>,
55 },
56 #[error("account change set for address {address} at block #{block_number} does not exist")]
58 AccountChangesetNotFound {
59 block_number: BlockNumber,
61 address: Address,
63 },
64 #[error("no header found for {_0:?}")]
66 HeaderNotFound(BlockHashOrNumber),
67 #[error("no transaction found for {_0:?}")]
69 TransactionNotFound(HashOrNumber),
70 #[error("no receipt found for {_0:?}")]
72 ReceiptNotFound(HashOrNumber),
73 #[error("best block does not exist")]
75 BestBlockNotFound,
76 #[error("finalized block does not exist")]
78 FinalizedBlockNotFound,
79 #[error("safe block does not exist")]
81 SafeBlockNotFound,
82 #[error("unknown block {_0}")]
84 UnknownBlockHash(B256),
85 #[error("no state found for block {_0}")]
87 StateForHashNotFound(B256),
88 #[error("no state found for block number {_0}")]
90 StateForNumberNotFound(u64),
91 #[error("unable to find the block number for a given transaction index")]
93 BlockNumberForTransactionIndexNotFound,
94 #[error("merkle trie {_0}")]
96 StateRootMismatch(Box<RootMismatch>),
97 #[error("unwind merkle trie {_0}")]
99 UnwindStateRootMismatch(Box<RootMismatch>),
100 #[error("state at block #{_0} is pruned")]
102 StateAtBlockPruned(BlockNumber),
103 #[error("historical state is temporarily unavailable during pipeline sync; try again later")]
105 StateUnavailableDuringSync,
106 #[error("state at block #{requested} is not available, block has not been executed yet (latest executed: #{executed})")]
108 BlockNotExecuted {
109 requested: BlockNumber,
111 executed: BlockNumber,
113 },
114 #[error("block #{requested} is not available, history has expired (earliest available: #{earliest_available})")]
118 BlockExpired {
119 requested: BlockNumber,
121 earliest_available: BlockNumber,
123 },
124 #[error("this provider does not support this request")]
126 UnsupportedProvider,
127 #[cfg(feature = "std")]
129 #[error("not able to find {_0} static file at {_1:?}")]
130 MissingStaticFileSegmentPath(StaticFileSegment, std::path::PathBuf),
131 #[cfg(feature = "std")]
133 #[error("not able to find static file at {_0:?}")]
134 MissingStaticFilePath(std::path::PathBuf),
135 #[error("highest block is not found for {_0} static file")]
137 MissingHighestStaticFileBlock(StaticFileSegment),
138 #[error("not able to find {_0} static file for block number {_1}")]
140 MissingStaticFileBlock(StaticFileSegment, BlockNumber),
141 #[error("unable to find {_0} static file for transaction id {_1}")]
143 MissingStaticFileTx(StaticFileSegment, TxNumber),
144 #[error("unable to write block #{_1} to finalized static file {_0}")]
146 FinalizedStaticFile(StaticFileSegment, BlockNumber),
147 #[error("trying to append data to {_0} as block #{_1} but expected block #{_2}")]
149 UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber),
150 #[error("trying to append row to {_0} at index #{_1} but expected index #{_2}")]
152 UnexpectedStaticFileTxNumber(StaticFileSegment, TxNumber, TxNumber),
153 #[error("changeset static file is corrupted, missing offsets for changesets in each block")]
155 CorruptedChangeSetStaticFile,
156 #[error("Unbounded start is unsupported in from_reverts")]
158 UnboundedStartUnsupported,
159 #[error("cannot get a writer on a read-only environment.")]
161 ReadOnlyStaticFileAccess,
162 #[error("failed to initialize consistent view: {_0}")]
164 ConsistentView(Box<ConsistentViewError>),
165 #[error("received invalid output from storage")]
167 InvalidStorageOutput,
168 #[error("missing trie updates for block {0}")]
170 MissingTrieUpdates(B256),
171 #[error("insufficient changesets to revert to block #{requested}. Available changeset range: {available:?}")]
173 InsufficientChangesets {
174 requested: BlockNumber,
176 available: core::ops::RangeInclusive<BlockNumber>,
178 },
179 #[error("consistency check failed for {data_source}. Db must be unwound to {unwind_to}")]
183 MustUnwind {
184 data_source: &'static str,
186 unwind_to: BlockNumber,
188 },
189 #[error(
191 "snap attempt record version {found:?} is not supported, this build writes {supported}"
192 )]
193 UnsupportedSnapAttemptVersion {
194 found: Option<u64>,
196 supported: u32,
198 },
199 #[error("snap sync requires the hashed state layout, which this database predates")]
202 SnapStorageLayoutUnsupported,
203 #[error("snap attempt {attempt} has not verified the downloaded state")]
205 UnverifiedSnapState {
206 attempt: u64,
208 },
209 #[error(
212 "snap attempt {attempt} left unverified state, restart with snap sync or wipe the database"
213 )]
214 SnapStateRequiresSnapSync {
215 attempt: u64,
217 },
218 #[error(transparent)]
220 Other(#[from] AnyError),
221}
222
223impl ProviderError {
224 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 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 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 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#[derive(Clone, Debug, PartialEq, Eq, Display)]
276#[display("root mismatch at #{block_number} ({block_hash}): {root}")]
277pub struct RootMismatch {
278 pub root: GotExpected<B256>,
280 pub block_number: BlockNumber,
282 pub block_hash: BlockHash,
284}
285
286#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
288pub enum StaticFileWriterError {
289 #[error("cannot call sync_all or finalize when prune is queued, use commit() instead")]
291 FinalizeWithPruneQueued,
292 #[error("thread panicked: {_0}")]
294 ThreadPanic(&'static str),
295 #[error("{0}")]
297 Other(String),
298 #[error("cannot unwind {segment} to block {target} below the pruned anchor at block {anchor}")]
301 UnwindBelowPrunedAnchor {
302 segment: StaticFileSegment,
304 target: BlockNumber,
306 anchor: BlockNumber,
308 },
309}
310
311impl StaticFileWriterError {
312 pub fn new(message: impl Into<String>) -> Self {
314 Self::Other(message.into())
315 }
316}
317#[derive(Clone, Debug, PartialEq, Eq, Display)]
319pub enum ConsistentViewError {
320 #[display("node is syncing. best block: {best_block:?}")]
322 Syncing {
323 best_block: GotExpected<BlockNumber>,
325 },
326 #[display("inconsistent database state: {tip:?}")]
328 Inconsistent {
329 tip: GotExpected<Option<B256>>,
331 },
332 #[display("database view no longer contains block: {block:?}")]
334 Reorged {
335 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}