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
//! Errors when encoding or decoding
//!
//! These erros contain more specific information about e.g. where a hash mismatch occured
use crate::{ChunkNum, TreeNode};
use std::{fmt, io};

/// Error when starting to decode from a reader
#[derive(Debug)]
pub enum StartDecodeError {
    /// We got an EOF when reading the size, indicating that the remote end does not have the blob
    NotFound,
    /// A generic io error
    Io(io::Error),
}

impl fmt::Display for StartDecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl std::error::Error for StartDecodeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<StartDecodeError> for io::Error {
    fn from(e: StartDecodeError) -> Self {
        use StartDecodeError::*;
        match e {
            Io(e) => e,
            NotFound => io::Error::new(io::ErrorKind::UnexpectedEof, e),
        }
    }
}

impl StartDecodeError {
    pub(crate) fn maybe_not_found(e: io::Error) -> Self {
        if e.kind() == io::ErrorKind::UnexpectedEof {
            Self::NotFound
        } else {
            Self::Io(e)
        }
    }
}

/// Error when decoding from a reader, both when reading the size and after
///
/// This is an union of [`StartDecodeError`] and [`DecodeError`] for convenience.
#[derive(Debug)]
pub enum AnyDecodeError {
    /// We got an EOF when reading the size, indicating that the remote end does not have the blob
    NotFound,
    /// We got an EOF while reading a parent hash pair, indicating that the remote end does not have the outboard
    ParentNotFound(TreeNode),
    /// We got an EOF while reading a chunk, indicating that the remote end does not have the data
    LeafNotFound(ChunkNum),
    /// The hash of a parent did not match the expected hash
    ParentHashMismatch(TreeNode),
    /// The hash of a leaf did not match the expected hash
    LeafHashMismatch(ChunkNum),
    /// There was an error reading from the underlying io
    Io(io::Error),
}

impl From<DecodeError> for AnyDecodeError {
    fn from(e: DecodeError) -> Self {
        match e {
            DecodeError::Io(e) => Self::Io(e),
            DecodeError::ParentHashMismatch(node) => Self::ParentHashMismatch(node),
            DecodeError::LeafHashMismatch(chunk) => Self::LeafHashMismatch(chunk),
            DecodeError::LeafNotFound(chunk) => Self::LeafNotFound(chunk),
            DecodeError::ParentNotFound(node) => Self::ParentNotFound(node),
        }
    }
}

impl From<StartDecodeError> for AnyDecodeError {
    fn from(e: StartDecodeError) -> Self {
        match e {
            StartDecodeError::Io(e) => Self::Io(e),
            StartDecodeError::NotFound => Self::NotFound,
        }
    }
}

impl fmt::Display for AnyDecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl std::error::Error for AnyDecodeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<AnyDecodeError> for io::Error {
    fn from(e: AnyDecodeError) -> Self {
        match e {
            AnyDecodeError::Io(e) => e,
            AnyDecodeError::ParentHashMismatch(node) => io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "parent hash mismatch (level {}, block {})",
                    node.level(),
                    node.mid().0
                ),
            ),
            AnyDecodeError::LeafHashMismatch(chunk) => io::Error::new(
                io::ErrorKind::InvalidData,
                format!("leaf hash mismatch (offset {})", chunk.to_bytes().0),
            ),
            AnyDecodeError::LeafNotFound(_) => io::Error::new(io::ErrorKind::UnexpectedEof, e),
            AnyDecodeError::ParentNotFound(_) => io::Error::new(io::ErrorKind::UnexpectedEof, e),
            AnyDecodeError::NotFound => io::Error::new(io::ErrorKind::UnexpectedEof, e),
        }
    }
}

/// Error when decoding from a reader, after the size has been read
#[derive(Debug)]
pub enum DecodeError {
    /// We got an EOF while reading a parent hash pair, indicating that the remote end does not have the outboard
    ParentNotFound(TreeNode),
    /// We got an EOF while reading a chunk, indicating that the remote end does not have the data
    LeafNotFound(ChunkNum),
    /// The hash of a parent did not match the expected hash
    ParentHashMismatch(TreeNode),
    /// The hash of a leaf did not match the expected hash
    LeafHashMismatch(ChunkNum),
    /// There was an error reading from the underlying io
    Io(io::Error),
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl std::error::Error for DecodeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<DecodeError> for io::Error {
    fn from(e: DecodeError) -> Self {
        match e {
            DecodeError::Io(e) => e,
            DecodeError::ParentHashMismatch(node) => io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "parent hash mismatch (level {}, block {})",
                    node.level(),
                    node.mid().0
                ),
            ),
            DecodeError::LeafHashMismatch(chunk) => io::Error::new(
                io::ErrorKind::InvalidData,
                format!("leaf hash mismatch (offset {})", chunk.to_bytes().0),
            ),
            DecodeError::LeafNotFound(_) => io::Error::new(io::ErrorKind::UnexpectedEof, e),
            DecodeError::ParentNotFound(_) => io::Error::new(io::ErrorKind::UnexpectedEof, e),
        }
    }
}

impl DecodeError {
    pub(crate) fn maybe_parent_not_found(e: io::Error, node: TreeNode) -> Self {
        if e.kind() == io::ErrorKind::UnexpectedEof {
            Self::ParentNotFound(node)
        } else {
            Self::Io(e)
        }
    }

    pub(crate) fn maybe_leaf_not_found(e: io::Error, chunk: ChunkNum) -> Self {
        if e.kind() == io::ErrorKind::UnexpectedEof {
            Self::LeafNotFound(chunk)
        } else {
            Self::Io(e)
        }
    }
}

/// Error when encoding from outboard and data
///
/// This can either be a io error or a more specific error like a hash mismatch
/// or a size mismatch. If the remote end stops listening while we are writing,
/// the error will indicate which parent or chunk we were writing at the time.
#[derive(Debug)]
pub enum EncodeError {
    /// The hash of a parent did not match the expected hash
    ParentHashMismatch(TreeNode),
    /// The hash of a leaf did not match the expected hash
    LeafHashMismatch(ChunkNum),
    /// We got a ConnectionReset while writing a parent hash pair, indicating that the remote end stopped listening
    ParentWrite(TreeNode),
    /// We got a ConnectionReset while writing a chunk, indicating that the remote end stopped listening
    LeafWrite(ChunkNum),
    /// File size does not match size in outboard
    SizeMismatch,
    /// There was an error reading from the underlying io
    Io(io::Error),
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl std::error::Error for EncodeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            EncodeError::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<EncodeError> for io::Error {
    fn from(e: EncodeError) -> Self {
        match e {
            EncodeError::Io(e) => e,
            EncodeError::ParentHashMismatch(node) => io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "parent hash mismatch (level {}, block {})",
                    node.level(),
                    node.mid().0
                ),
            ),
            EncodeError::LeafHashMismatch(chunk) => io::Error::new(
                io::ErrorKind::InvalidData,
                format!("leaf hash mismatch at {}", chunk.to_bytes().0),
            ),
            EncodeError::ParentWrite(node) => io::Error::new(
                io::ErrorKind::ConnectionReset,
                format!(
                    "parent write failed (level {}, block {})",
                    node.level(),
                    node.mid().0
                ),
            ),
            EncodeError::LeafWrite(chunk) => io::Error::new(
                io::ErrorKind::ConnectionReset,
                format!("leaf write failed at {}", chunk.to_bytes().0),
            ),
            EncodeError::SizeMismatch => {
                io::Error::new(io::ErrorKind::InvalidData, "size mismatch")
            }
        }
    }
}

impl From<io::Error> for EncodeError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

impl EncodeError {
    pub(crate) fn maybe_parent_write(e: io::Error, node: TreeNode) -> Self {
        if e.kind() == io::ErrorKind::ConnectionReset {
            Self::ParentWrite(node)
        } else {
            Self::Io(e)
        }
    }

    pub(crate) fn maybe_leaf_write(e: io::Error, chunk: ChunkNum) -> Self {
        if e.kind() == io::ErrorKind::ConnectionReset {
            Self::LeafWrite(chunk)
        } else {
            Self::Io(e)
        }
    }
}