zaino-state 0.2.0

A mempool and chain-fetching service built on top of zebra's ReadStateService and TrustedChainSync.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
#![allow(deprecated)]
//! Holds error types for Zaino-state.

// Needs to be module level due to the thiserror::Error macro

use crate::BlockHash;

use std::{any::type_name, fmt::Display};

use zaino_fetch::jsonrpsee::connector::RpcRequestError;
use zaino_proto::proto::utils::GetBlockRangeError;

/// Errors related to the `StateService`.
// #[deprecated]
#[derive(Debug, thiserror::Error)]
#[allow(clippy::result_large_err)]
pub enum StateServiceError {
    /// Critical Errors, Restart Zaino.
    #[error("Critical error: {0}")]
    Critical(String),

    /// An rpc-specific error we haven't accounted for
    #[error("unhandled fallible RPC call {0}")]
    UnhandledRpcError(String),
    /// Custom Errors. *Remove before production.
    #[error("Custom error: {0}")]
    Custom(String),

    /// Error from a Tokio JoinHandle.
    #[error("Join error: {0}")]
    JoinError(#[from] tokio::task::JoinError),

    /// Error from JsonRpcConnector.
    #[error("JsonRpcConnector error: {0}")]
    JsonRpcConnectorError(#[from] zaino_fetch::jsonrpsee::error::TransportError),

    /// RPC error in compatibility with zcashd.
    #[error("RPC error: {0:?}")]
    RpcError(#[from] zaino_fetch::jsonrpsee::connector::RpcError),

    /// Chain index error.
    #[error("Chain index error: {0}")]
    ChainIndexError(#[from] ChainIndexError),

    /// Error from the block cache.
    #[error("Mempool error: {0}")]
    BlockCacheError(#[from] BlockCacheError),

    /// Error from the mempool.
    #[error("Mempool error: {0}")]
    MempoolError(#[from] MempoolError),

    /// Tonic gRPC error.
    #[error("Tonic status error: {0}")]
    TonicStatusError(#[from] tonic::Status),

    /// Serialization error.
    #[error("Serialization error: {0}")]
    SerializationError(#[from] zebra_chain::serialization::SerializationError),

    /// Integer conversion error.
    #[error("Integer conversion error: {0}")]
    TryFromIntError(#[from] std::num::TryFromIntError),

    /// std::io::Error
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    /// A generic boxed error.
    #[error("Generic error: {0}")]
    Generic(#[from] Box<dyn std::error::Error + Send + Sync>),

    /// The zebrad version and zebra library version do not align
    #[error(
        "zebrad version mismatch. this build of zaino requires a \
        version of {expected_zebrad_version}, but the connected zebrad \
        is version {connected_zebrad_version}"
    )]
    ZebradVersionMismatch {
        /// The version string or commit hash we specify in Cargo.lock
        expected_zebrad_version: String,
        /// The version string of the zebrad, plus its git describe
        /// information if applicable
        connected_zebrad_version: String,
    },
    #[error("zaino not yet synced")]
    /// Zaino has not yet synced.
    UnavailableNotSyncedEnough,
}

impl From<GetBlockRangeError> for StateServiceError {
    fn from(value: GetBlockRangeError) -> Self {
        match value {
            GetBlockRangeError::StartHeightOutOfRange => {
                Self::TonicStatusError(tonic::Status::out_of_range(
                    "Error: Start height out of range. Failed to convert to u32.",
                ))
            }
            GetBlockRangeError::NoStartHeightProvided => {
                Self::TonicStatusError(tonic::Status::out_of_range("Error: No start height given"))
            }
            GetBlockRangeError::EndHeightOutOfRange => {
                Self::TonicStatusError(tonic::Status::out_of_range(
                    "Error: End height out of range. Failed to convert to u32.",
                ))
            }
            GetBlockRangeError::NoEndHeightProvided => {
                Self::TonicStatusError(tonic::Status::out_of_range("Error: No end height given."))
            }
            GetBlockRangeError::PoolTypeArgumentError(_) => {
                Self::TonicStatusError(tonic::Status::invalid_argument("Error: invalid pool type"))
            }
        }
    }
}

#[allow(deprecated)]
impl From<StateServiceError> for tonic::Status {
    fn from(error: StateServiceError) -> Self {
        match error {
            StateServiceError::Critical(message) => tonic::Status::internal(message),
            StateServiceError::Custom(message) => tonic::Status::internal(message),
            StateServiceError::JoinError(err) => {
                tonic::Status::internal(format!("Join error: {err}"))
            }
            StateServiceError::JsonRpcConnectorError(err) => {
                tonic::Status::internal(format!("JsonRpcConnector error: {err}"))
            }
            StateServiceError::RpcError(err) => {
                tonic::Status::internal(format!("RPC error: {err:?}"))
            }
            StateServiceError::ChainIndexError(err) => match err.kind {
                ChainIndexErrorKind::InternalServerError => tonic::Status::internal(err.message),
                ChainIndexErrorKind::InvalidSnapshot => {
                    tonic::Status::failed_precondition(err.message)
                }
            },
            StateServiceError::BlockCacheError(err) => {
                tonic::Status::internal(format!("BlockCache error: {err:?}"))
            }
            StateServiceError::MempoolError(err) => {
                tonic::Status::internal(format!("Mempool error: {err:?}"))
            }
            StateServiceError::TonicStatusError(err) => err,
            StateServiceError::SerializationError(err) => {
                tonic::Status::internal(format!("Serialization error: {err}"))
            }
            StateServiceError::TryFromIntError(err) => {
                tonic::Status::internal(format!("Integer conversion error: {err}"))
            }
            StateServiceError::IoError(err) => tonic::Status::internal(format!("IO error: {err}")),
            StateServiceError::Generic(err) => {
                tonic::Status::internal(format!("Generic error: {err}"))
            }
            ref err @ StateServiceError::ZebradVersionMismatch { .. } => {
                tonic::Status::internal(err.to_string())
            }
            StateServiceError::UnhandledRpcError(e) => tonic::Status::internal(e.to_string()),
            StateServiceError::UnavailableNotSyncedEnough => {
                tonic::Status::failed_precondition("zaino not yet synced".to_string())
            }
        }
    }
}

impl<T: ToString> From<RpcRequestError<T>> for StateServiceError {
    fn from(value: RpcRequestError<T>) -> Self {
        match value {
            RpcRequestError::Transport(transport_error) => {
                Self::JsonRpcConnectorError(transport_error)
            }
            RpcRequestError::Method(e) => Self::UnhandledRpcError(format!(
                "{}: {}",
                std::any::type_name::<T>(),
                e.to_string()
            )),
            RpcRequestError::JsonRpc(error) => Self::Custom(format!("bad argument: {error}")),
            RpcRequestError::InternalUnrecoverable(e) => Self::Custom(e.to_string()),
            RpcRequestError::ServerWorkQueueFull => {
                Self::Custom("Server queue full. Handling for this not yet implemented".to_string())
            }
            RpcRequestError::UnexpectedErrorResponse(error) => Self::Custom(format!("{error}")),
        }
    }
}

/// Errors related to the `FetchService`.
#[deprecated]
#[derive(Debug, thiserror::Error)]
pub enum FetchServiceError {
    /// Critical Errors, Restart Zaino.
    #[error("Critical error: {0}")]
    Critical(String),

    /// Error from JsonRpcConnector.
    #[error("JsonRpcConnector error: {0}")]
    JsonRpcConnectorError(#[from] zaino_fetch::jsonrpsee::error::TransportError),

    /// Chain index error.
    #[error("Chain index error: {0}")]
    ChainIndexError(#[from] ChainIndexError),

    /// RPC error in compatibility with zcashd.
    #[error("RPC error: {0:?}")]
    RpcError(#[from] zaino_fetch::jsonrpsee::connector::RpcError),

    /// Tonic gRPC error.
    #[error("Tonic status error: {0}")]
    TonicStatusError(#[from] tonic::Status),

    /// Serialization error.
    #[error("Serialization error: {0}")]
    SerializationError(#[from] zebra_chain::serialization::SerializationError),
    #[error("Zaino has not synced high enough to serve this data")]
    /// Zaino has not yet synced.
    UnavailableNotSyncedEnough,
}

impl From<FetchServiceError> for tonic::Status {
    fn from(error: FetchServiceError) -> Self {
        match error {
            FetchServiceError::Critical(message) => tonic::Status::internal(message),
            FetchServiceError::JsonRpcConnectorError(err) => {
                tonic::Status::internal(format!("JsonRpcConnector error: {err}"))
            }
            FetchServiceError::ChainIndexError(err) => match err.kind {
                ChainIndexErrorKind::InternalServerError => tonic::Status::internal(err.message),
                ChainIndexErrorKind::InvalidSnapshot => {
                    tonic::Status::failed_precondition(err.message)
                }
            },
            FetchServiceError::RpcError(err) => {
                tonic::Status::internal(format!("RPC error: {err:?}"))
            }
            FetchServiceError::TonicStatusError(err) => err,
            FetchServiceError::SerializationError(err) => {
                tonic::Status::internal(format!("Serialization error: {err}"))
            }
            FetchServiceError::UnavailableNotSyncedEnough => {
                tonic::Status::failed_precondition("zaino not yet synced".to_string())
            }
        }
    }
}

impl<T: ToString> From<RpcRequestError<T>> for FetchServiceError {
    fn from(value: RpcRequestError<T>) -> Self {
        match value {
            RpcRequestError::Transport(transport_error) => {
                FetchServiceError::JsonRpcConnectorError(transport_error)
            }
            RpcRequestError::JsonRpc(error) => {
                FetchServiceError::Critical(format!("argument failed to serialze: {error}"))
            }
            RpcRequestError::InternalUnrecoverable(e) => {
                FetchServiceError::Critical(format!("Internal unrecoverable error: {e}"))
            }
            RpcRequestError::ServerWorkQueueFull => FetchServiceError::Critical(
                "Server queue full. Handling for this not yet implemented".to_string(),
            ),
            RpcRequestError::Method(e) => FetchServiceError::Critical(format!(
                "unhandled rpc-specific {} error: {}",
                type_name::<T>(),
                e.to_string()
            )),
            RpcRequestError::UnexpectedErrorResponse(error) => {
                FetchServiceError::Critical(format!(
                    "unhandled rpc-specific {} error: {}",
                    type_name::<T>(),
                    error
                ))
            }
        }
    }
}

impl From<GetBlockRangeError> for FetchServiceError {
    fn from(value: GetBlockRangeError) -> Self {
        match value {
            GetBlockRangeError::StartHeightOutOfRange => {
                FetchServiceError::TonicStatusError(tonic::Status::out_of_range(
                    "Error: Start height out of range. Failed to convert to u32.",
                ))
            }
            GetBlockRangeError::NoStartHeightProvided => FetchServiceError::TonicStatusError(
                tonic::Status::out_of_range("Error: No start height given"),
            ),
            GetBlockRangeError::EndHeightOutOfRange => {
                FetchServiceError::TonicStatusError(tonic::Status::out_of_range(
                    "Error: End height out of range. Failed to convert to u32.",
                ))
            }
            GetBlockRangeError::NoEndHeightProvided => FetchServiceError::TonicStatusError(
                tonic::Status::out_of_range("Error: No end height given."),
            ),
            GetBlockRangeError::PoolTypeArgumentError(_) => FetchServiceError::TonicStatusError(
                tonic::Status::invalid_argument("Error: invalid pool type"),
            ),
        }
    }
}

/// These aren't the best conversions, but the MempoolError should go away
/// in favor of a new type with the new chain cache is complete
impl<T: ToString> From<RpcRequestError<T>> for MempoolError {
    fn from(value: RpcRequestError<T>) -> Self {
        match value {
            RpcRequestError::Transport(transport_error) => {
                MempoolError::JsonRpcConnectorError(transport_error)
            }
            RpcRequestError::JsonRpc(error) => {
                MempoolError::Critical(format!("argument failed to serialze: {error}"))
            }
            RpcRequestError::InternalUnrecoverable(e) => {
                MempoolError::Critical(format!("Internal unrecoverable error: {e}"))
            }
            RpcRequestError::ServerWorkQueueFull => MempoolError::Critical(
                "Server queue full. Handling for this not yet implemented".to_string(),
            ),
            RpcRequestError::Method(e) => MempoolError::Critical(format!(
                "unhandled rpc-specific {} error: {}",
                type_name::<T>(),
                e.to_string()
            )),
            RpcRequestError::UnexpectedErrorResponse(error) => MempoolError::Critical(format!(
                "unhandled rpc-specific {} error: {}",
                type_name::<T>(),
                error
            )),
        }
    }
}

/// Errors related to the `Mempool`.
#[derive(Debug, thiserror::Error)]
pub enum MempoolError {
    /// Critical Errors, Restart Zaino.
    #[error("Critical error: {0}")]
    Critical(String),

    /// Incorrect expected chain tip given from client.
    #[error(
        "Incorrect chain tip (expected {expected_chain_tip:?}, current {current_chain_tip:?})"
    )]
    IncorrectChainTip {
        expected_chain_tip: BlockHash,
        current_chain_tip: BlockHash,
    },

    /// Error from JsonRpcConnector.
    #[error("JsonRpcConnector error: {0}")]
    JsonRpcConnectorError(#[from] zaino_fetch::jsonrpsee::error::TransportError),

    /// Errors originating from the BlockchainSource in use.
    #[error("blockchain source error: {0}")]
    BlockchainSourceError(#[from] crate::chain_index::source::BlockchainSourceError),

    /// Error from a Tokio Watch Receiver.
    #[error("Join error: {0}")]
    WatchRecvError(#[from] tokio::sync::watch::error::RecvError),

    /// Unexpected status-related error.
    #[error("Status error: {0:?}")]
    StatusError(StatusError),
}

/// Errors related to the `BlockCache`.
#[derive(Debug, thiserror::Error)]
pub enum BlockCacheError {
    /// Custom Errors. *Remove before production.
    #[error("Custom error: {0}")]
    Custom(String),

    /// Critical Errors, Restart Zaino.
    #[error("Critical error: {0}")]
    Critical(String),

    /// Errors from the NonFinalisedState.
    #[error("NonFinalisedState Error: {0}")]
    NonFinalisedStateError(#[from] NonFinalisedStateError),

    /// Errors from the FinalisedState.
    #[error("FinalisedState Error: {0}")]
    FinalisedStateError(#[from] FinalisedStateError),

    /// Error from JsonRpcConnector.
    #[error("JsonRpcConnector error: {0}")]
    JsonRpcConnectorError(#[from] zaino_fetch::jsonrpsee::error::TransportError),

    /// Chain parse error.
    #[error("Chain parse error: {0}")]
    ChainParseError(#[from] zaino_fetch::chain::error::ParseError),

    /// Serialization error.
    #[error("Serialization error: {0}")]
    SerializationError(#[from] zebra_chain::serialization::SerializationError),

    /// UTF-8 conversion error.
    #[error("UTF-8 conversion error: {0}")]
    Utf8Error(#[from] std::str::Utf8Error),

    /// Integer parsing error.
    #[error("Integer parsing error: {0}")]
    ParseIntError(#[from] std::num::ParseIntError),

    /// Integer conversion error.
    #[error("Integer conversion error: {0}")]
    TryFromIntError(#[from] std::num::TryFromIntError),
}

/// Errors related to the `NonFinalisedState`.
#[derive(Debug, thiserror::Error)]
pub enum NonFinalisedStateError {
    /// Custom Errors. *Remove before production.
    #[error("Custom error: {0}")]
    Custom(String),

    /// Required data is missing from the non-finalised state.
    #[error("Missing data: {0}")]
    MissingData(String),

    /// Critical Errors, Restart Zaino.
    #[error("Critical error: {0}")]
    Critical(String),

    /// Error from JsonRpcConnector.
    #[error("JsonRpcConnector error: {0}")]
    JsonRpcConnectorError(#[from] zaino_fetch::jsonrpsee::error::TransportError),

    /// Unexpected status-related error.
    #[error("Status error: {0:?}")]
    StatusError(StatusError),
}

/// These aren't the best conversions, but the NonFinalizedStateError should go away
/// in favor of a new type with the new chain cache is complete
impl<T: ToString> From<RpcRequestError<T>> for NonFinalisedStateError {
    fn from(value: RpcRequestError<T>) -> Self {
        match value {
            RpcRequestError::Transport(transport_error) => {
                NonFinalisedStateError::JsonRpcConnectorError(transport_error)
            }
            RpcRequestError::JsonRpc(error) => {
                NonFinalisedStateError::Custom(format!("argument failed to serialze: {error}"))
            }
            RpcRequestError::InternalUnrecoverable(e) => {
                NonFinalisedStateError::Custom(format!("Internal unrecoverable error: {e}"))
            }
            RpcRequestError::ServerWorkQueueFull => NonFinalisedStateError::Custom(
                "Server queue full. Handling for this not yet implemented".to_string(),
            ),
            RpcRequestError::Method(e) => NonFinalisedStateError::Custom(format!(
                "unhandled rpc-specific {} error: {}",
                type_name::<T>(),
                e.to_string()
            )),
            RpcRequestError::UnexpectedErrorResponse(error) => {
                NonFinalisedStateError::Custom(format!(
                    "unhandled rpc-specific {} error: {}",
                    type_name::<T>(),
                    error
                ))
            }
        }
    }
}

/// Errors related to the `FinalisedState`.
// TODO: Update name to DbError when ZainoDB replaces legacy finalised state.
#[derive(Debug, thiserror::Error)]
pub enum FinalisedStateError {
    /// Custom Errors.
    // TODO: Remove before production
    #[error("Custom error: {0}")]
    Custom(String),

    /// Requested data is missing from the finalised state.
    ///
    /// This could be due to the databae not yet being synced or due to a bad request input.
    ///
    /// We could split this into 2 distinct types if needed.
    #[error("Missing data: {0}")]
    DataUnavailable(String),

    /// A block is present on disk but failed internal validation.
    ///
    /// *Typically means: checksum mismatch, corrupt CBOR, Merkle check
    /// failed, etc.*  The caller should fetch the correct data and
    /// overwrite the faulty block.
    #[error("invalid block @ height {height} (hash {hash}): {reason}")]
    InvalidBlock {
        height: u32,
        hash: BlockHash,
        reason: String,
    },

    /// Returned when a caller asks for a feature that the
    /// currently-opened database version does not advertise.
    #[error("feature unavailable: {0}")]
    FeatureUnavailable(&'static str),

    /// Errors originating from the BlockchainSource in use.
    #[error("blockchain source error: {0}")]
    BlockchainSourceError(#[from] crate::chain_index::source::BlockchainSourceError),

    /// Critical Errors, Restart Zaino.
    #[error("Critical error: {0}")]
    Critical(String),

    /// Error from the LMDB database.
    // NOTE: Should this error type be here or should we handle all LMDB errors internally?
    #[error("LMDB database error: {0}")]
    LmdbError(#[from] lmdb::Error),

    /// Serde Json serialisation / deserialisation errors.
    // TODO: Remove when ZainoDB replaces legacy finalised state.
    #[error("LMDB database error: {0}")]
    SerdeJsonError(#[from] serde_json::Error),

    /// Unexpected status-related error.
    #[error("Status error: {0:?}")]
    StatusError(StatusError),

    /// Error from JsonRpcConnector.
    // TODO: Remove when ZainoDB replaces legacy finalised state.
    #[error("JsonRpcConnector error: {0}")]
    JsonRpcConnectorError(#[from] zaino_fetch::jsonrpsee::error::TransportError),

    /// std::io::Error
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

/// These aren't the best conversions, but the FinalizedStateError should go away
/// in favor of a new type with the new chain cache is complete
impl<T: ToString> From<RpcRequestError<T>> for FinalisedStateError {
    fn from(value: RpcRequestError<T>) -> Self {
        match value {
            RpcRequestError::Transport(transport_error) => {
                FinalisedStateError::JsonRpcConnectorError(transport_error)
            }
            RpcRequestError::JsonRpc(error) => {
                FinalisedStateError::Custom(format!("argument failed to serialze: {error}"))
            }
            RpcRequestError::InternalUnrecoverable(e) => {
                FinalisedStateError::Custom(format!("Internal unrecoverable error: {e}"))
            }
            RpcRequestError::ServerWorkQueueFull => FinalisedStateError::Custom(
                "Server queue full. Handling for this not yet implemented".to_string(),
            ),
            RpcRequestError::Method(e) => FinalisedStateError::Custom(format!(
                "unhandled rpc-specific {} error: {}",
                type_name::<T>(),
                e.to_string()
            )),
            RpcRequestError::UnexpectedErrorResponse(error) => {
                FinalisedStateError::Custom(format!(
                    "unhandled rpc-specific {} error: {}",
                    type_name::<T>(),
                    error
                ))
            }
        }
    }
}

/// A general error type to represent error StatusTypes.
#[derive(Debug, Clone, thiserror::Error)]
#[error("Unexpected status error: {server_status:?}")]
pub struct StatusError {
    pub server_status: crate::status::StatusType,
}

#[derive(Debug, thiserror::Error)]
#[error("{kind}: {message}")]
/// The set of errors that can occur during the public API calls
/// of a NodeBackedChainIndex
pub struct ChainIndexError {
    pub(crate) kind: ChainIndexErrorKind,
    pub(crate) message: String,
    pub(crate) source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
}

#[derive(Debug, Copy, Clone)]
#[non_exhaustive]
/// The high-level kinds of thing that can fail
pub enum ChainIndexErrorKind {
    /// Zaino is in some way nonfunctional
    InternalServerError,
    /// The given snapshot contains invalid data.
    // This variant isn't used yet...it should indicate
    // that the provided snapshot contains information unknown to Zebra
    // Unlike an internal server error, generating a new snapshot may solve
    // whatever went wrong
    #[allow(dead_code)]
    InvalidSnapshot,
}

impl Display for ChainIndexErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ChainIndexErrorKind::InternalServerError => "internal server error",
            ChainIndexErrorKind::InvalidSnapshot => "invalid snapshot",
        })
    }
}

impl ChainIndexError {
    /// The error kind
    pub fn kind(&self) -> ChainIndexErrorKind {
        self.kind
    }
    pub(crate) fn backing_validator(value: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            kind: ChainIndexErrorKind::InternalServerError,
            message: "InternalServerError: error receiving data from backing node".to_string(),
            source: Some(Box::new(value)),
        }
    }

    pub(crate) fn database_hole(
        missing_block: impl Display,
        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
    ) -> Self {
        Self {
            kind: ChainIndexErrorKind::InternalServerError,
            message: format!(
                "InternalServerError: hole in validator database, missing block {missing_block}"
            ),
            source,
        }
    }

    pub(crate) fn validator_data_error_block_coinbase_height_missing() -> Self {
        Self {
            kind: ChainIndexErrorKind::InternalServerError,
            message: "validator error: data error: block.coinbase_height() returned None"
                .to_string(),
            source: None,
        }
    }

    pub(crate) fn child_process_status_error(process: &str, status_err: StatusError) -> Self {
        use crate::status::StatusType;

        let message = match status_err.server_status {
            StatusType::Spawning => format!("{process} status: Spawning (not ready yet)"),
            StatusType::Syncing => format!("{process} status: Syncing (not ready yet)"),
            StatusType::Ready => format!("{process} status: Ready (unexpected error path)"),
            StatusType::Busy => format!("{process} status: Busy (temporarily unavailable)"),
            StatusType::Closing => format!("{process} status: Closing (shutting down)"),
            StatusType::Offline => format!("{process} status: Offline (not available)"),
            StatusType::RecoverableError => {
                format!("{process} status: RecoverableError (retry may succeed)")
            }
            StatusType::CriticalError => {
                format!("{process} status: CriticalError (requires operator action)")
            }
        };

        ChainIndexError {
            kind: ChainIndexErrorKind::InternalServerError,
            message,
            source: Some(Box::new(status_err)),
        }
    }
}

impl From<FinalisedStateError> for ChainIndexError {
    fn from(value: FinalisedStateError) -> Self {
        let message = match &value {
            FinalisedStateError::DataUnavailable(err) => format!("unhandled missing data: {err}"),
            FinalisedStateError::FeatureUnavailable(err) => {
                format!("unhandled missing feature: {err}")
            }
            FinalisedStateError::InvalidBlock {
                height,
                hash: _,
                reason,
            } => format!("invalid block at height {height}: {reason}"),
            FinalisedStateError::Custom(err) | FinalisedStateError::Critical(err) => err.clone(),
            FinalisedStateError::LmdbError(error) => error.to_string(),
            FinalisedStateError::SerdeJsonError(error) => error.to_string(),
            FinalisedStateError::StatusError(status_error) => status_error.to_string(),
            FinalisedStateError::JsonRpcConnectorError(transport_error) => {
                transport_error.to_string()
            }
            FinalisedStateError::IoError(error) => error.to_string(),
            FinalisedStateError::BlockchainSourceError(blockchain_source_error) => {
                blockchain_source_error.to_string()
            }
        };
        ChainIndexError {
            kind: ChainIndexErrorKind::InternalServerError,
            message,
            source: Some(Box::new(value)),
        }
    }
}

impl From<MempoolError> for ChainIndexError {
    fn from(value: MempoolError) -> Self {
        // Construct a user-facing message depending on the variant
        let message = match &value {
            MempoolError::Critical(msg) => format!("critical mempool error: {msg}"),
            MempoolError::IncorrectChainTip {
                expected_chain_tip,
                current_chain_tip,
            } => {
                format!(
                    "incorrect chain tip (expected {expected_chain_tip:?}, current {current_chain_tip:?})"
                )
            }
            MempoolError::JsonRpcConnectorError(err) => {
                format!("mempool json-rpc connector error: {err}")
            }
            MempoolError::BlockchainSourceError(err) => {
                format!("mempool blockchain source error: {err}")
            }
            MempoolError::WatchRecvError(err) => format!("mempool watch receiver error: {err}"),
            MempoolError::StatusError(status_err) => {
                format!("mempool status error: {status_err:?}")
            }
        };

        ChainIndexError {
            kind: ChainIndexErrorKind::InternalServerError,
            message,
            source: Some(Box::new(value)),
        }
    }
}