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
use bitcoin::consensus;
use core::fmt;

pub type Result<T> = core::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    InvalidMutlipartLengthError(usize),
    InvalidSequenceLengthError(usize),
    InvalidSequenceMessageLengthError(usize),
    InvalidSequenceMessageLabelError(u8),
    Invalid256BitHashLengthError(usize),
    InvalidTopicError(Vec<u8>),
    BitcoinDeserializationError(consensus::encode::Error),
    ZmqError(zmq::Error),
}

impl From<zmq::Error> for Error {
    fn from(value: zmq::Error) -> Self {
        Self::ZmqError(value)
    }
}

impl From<consensus::encode::Error> for Error {
    fn from(value: consensus::encode::Error) -> Self {
        Self::BitcoinDeserializationError(value)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InvalidMutlipartLengthError(len) => {
                write!(f, "invalid multipart message length: {len} (expected 3)")
            }
            Error::InvalidSequenceLengthError(len) => {
                write!(f, "invalid sequence length: {len} (expected 4)")
            }
            Error::InvalidSequenceMessageLengthError(len) => {
                write!(f, "invalid message length {len} of message type 'sequence'")
            }
            Error::InvalidSequenceMessageLabelError(label) => {
                write!(
                    f,
                    "invalid label '{}' (0x{:02x}) of message type 'sequence'",
                    *label as char, label
                )
            }
            Error::Invalid256BitHashLengthError(len) => {
                write!(f, "invalid hash length: {len} (expected 32)")
            }
            Error::InvalidTopicError(topic) => {
                write!(
                    f,
                    "invalid message topic '{}'",
                    String::from_utf8_lossy(topic)
                )
            }
            Error::BitcoinDeserializationError(e) => {
                write!(f, "bitcoin consensus deserialization error: {e}")
            }
            Error::ZmqError(e) => write!(f, "ZMQ Error: {e}"),
        }
    }
}

impl std::error::Error for Error {
    fn cause(&self) -> Option<&dyn std::error::Error> {
        Some(match self {
            Self::BitcoinDeserializationError(e) => e,
            Self::ZmqError(e) => e,
            Self::InvalidMutlipartLengthError(_)
            | Self::InvalidSequenceLengthError(_)
            | Self::InvalidSequenceMessageLengthError(_)
            | Self::InvalidSequenceMessageLabelError(_)
            | Self::Invalid256BitHashLengthError(_)
            | Self::InvalidTopicError(_) => return None,
        })
    }
}