ton_net/error.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2026 Nirapod Labs
3
4//! The facade error type and the mappings from the lower crates into it.
5
6/// The error type for every fallible operation in this crate.
7///
8/// A closed, `#[non_exhaustive]` enum: variants can be added before 1.0 without a
9/// breaking change. The lower crates' narrow errors are mapped into this set.
10#[derive(Debug, thiserror::Error)]
11#[non_exhaustive]
12pub enum Error {
13 /// A transport failure: a socket could not connect, read, or write.
14 #[error("transport: {0}")]
15 Transport(String),
16
17 /// The ADNL handshake with a liteserver failed.
18 #[error("handshake failed")]
19 Handshake,
20
21 /// A query did not complete within its deadline.
22 #[error("timed out")]
23 Timeout,
24
25 /// The liteserver returned an error response.
26 #[error("liteserver error {code}: {message}")]
27 LiteServer {
28 /// The liteserver error code.
29 code: i32,
30 /// The liteserver error message.
31 message: String,
32 },
33
34 /// A wire value could not be decoded, or a frame checksum did not match.
35 #[error("decode: {0}")]
36 Decode(String),
37
38 /// An address string was not a valid address.
39 #[error("address: {0}")]
40 Address(String),
41
42 /// A config could not be parsed.
43 #[error("config: {0}")]
44 Config(String),
45
46 /// A cell, a bag of cells, or a structure built from them could not be read.
47 #[error("cell: {0}")]
48 Cell(String),
49
50 /// A proof did not check out, or the account did not bind to the trusted block.
51 ///
52 /// A read that fails this way returns no value at all. There is no partial result and
53 /// no unproven fallback: a verified read either proves what it returns or fails.
54 #[error("proof: {0}")]
55 Proof(String),
56
57 /// A block proof chain did not establish a block to trust.
58 ///
59 /// Separate from [`Proof`](Self::Proof) because the two fail at different stages. A
60 /// proof failure means a server's answer did not match a block the client already
61 /// trusts; a sync failure means the client never established that block at all, and
62 /// retrying against another server is a reasonable response to one and not the other.
63 #[error("sync: {0}")]
64 Sync(String),
65
66 /// The newest block the server could prove is older than the freshness bound.
67 ///
68 /// The one failure here where the server may be honest and merely behind. A liteserver
69 /// can serve a real, fully proved block that is simply old, and nothing inside a proof
70 /// says when it was served.
71 #[error("the proven head is {age_seconds}s old, past the {limit_seconds}s bound")]
72 Stale {
73 /// How far behind the local clock the proven head is.
74 age_seconds: u64,
75 /// The bound that was exceeded, from [`crate::Config::max_head_age`].
76 limit_seconds: u64,
77 },
78
79 /// The local clock is far enough behind the chain that freshness cannot be judged.
80 ///
81 /// Validators do not sign blocks from the future, so a proven block well ahead of the
82 /// local clock places the fault on this side. It is reported rather than ignored
83 /// because the freshness check is what separates a current block from a genuine old
84 /// one replayed, and a clock this wrong silently switches it off. The remedy is a
85 /// correct clock, not another server.
86 #[error("the local clock is {by_seconds}s behind the chain, past the {tolerated_seconds}s tolerated")]
87 ClockBehind {
88 /// How far the proven block is ahead of the local clock.
89 by_seconds: u64,
90 /// The drift that is tolerated before this is reported.
91 tolerated_seconds: u64,
92 },
93
94 /// The session lost its place in the byte stream and cannot be used again.
95 ///
96 /// The ADNL ciphers are a counter the two ends advance in step, so a frame that only
97 /// half moved leaves this side unable to read anything further. Abandoning a call at
98 /// its deadline is one way to get here. A caller opens a new client; retrying on this
99 /// one fails the same way every time.
100 #[error("the connection lost its place and has to be reopened")]
101 ConnectionLost,
102}
103
104/// The stable name for a kind of failure, for a caller that has to branch on one.
105///
106/// [`Error`] is `#[non_exhaustive]`, so outside this crate it cannot be matched to the
107/// end, and a caller who tried would be writing a wildcard arm that silently swallows
108/// whatever is added next. This is the type to match on instead: the variant set is what
109/// callers are promised, and [`as_str`](ErrorCode::as_str) is the same name spelled for a
110/// language that has no enums.
111///
112/// # Why it lives here and not in each binding
113///
114/// Which failure occurred decides what a caller does next, and two of the answers are
115/// opposites. A transport failure means the socket dropped and the server may be fine, so
116/// trying again is right. A proof failure means the server did not prove its answer, so
117/// asking it again is the reverse of what this library is for.
118///
119/// That distinction has to reach every language this library is bound into, spelled the
120/// same way. Held in a binding it is one `match` per binding, drifting as each is
121/// written, and a caller who learns `PROOF` in JavaScript meets something else in Swift.
122/// Held here, a binding maps rather than invents.
123///
124/// The strings are a compatibility surface: they are what a caller compares against, so
125/// they are fixed once published, and renaming one breaks a caller no compiler warns.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127#[non_exhaustive]
128pub enum ErrorCode {
129 /// A socket could not connect, read, or write. The server may be fine.
130 Transport,
131 /// The ADNL handshake failed: the configured key is not the key that answered.
132 Handshake,
133 /// A call passed its deadline.
134 Timeout,
135 /// The connection lost its place in the cipher stream and cannot be reused.
136 ConnectionLost,
137 /// The liteserver answered with an error of its own.
138 LiteServer,
139 /// Bytes that did not read, from a call that verified nothing.
140 Decode,
141 /// An address that is not one.
142 Address,
143 /// A network configuration that could not be used.
144 Config,
145 /// A cell or bag of cells that is not well formed.
146 Cell,
147 /// A server did not prove its answer. Asking it again is not the repair.
148 Proof,
149 /// A walk toward the head could not be completed or checked.
150 Sync,
151 /// The proven head is older than the caller allowed.
152 Stale,
153 /// The local clock is far enough behind the chain that freshness cannot be judged.
154 ClockBehind,
155 /// An argument refused before any call was made.
156 ///
157 /// No [`Error`] carries this: the failure is the caller's rather than the network's,
158 /// and it happens above this crate. It is named here anyway, because a binding that
159 /// validates its own arguments needs a spelling for it, and the point of this type is
160 /// that the spelling is not invented once per language.
161 InvalidArgument,
162}
163
164impl ErrorCode {
165 /// The stable name, for a binding whose language has no enums.
166 ///
167 /// Upper case with underscores, the form the Node binding already publishes in its
168 /// message prefix.
169 #[must_use]
170 pub fn as_str(self) -> &'static str {
171 match self {
172 Self::Transport => "TRANSPORT",
173 Self::Handshake => "HANDSHAKE",
174 Self::Timeout => "TIMEOUT",
175 Self::ConnectionLost => "CONNECTION_LOST",
176 Self::LiteServer => "LITESERVER",
177 Self::Decode => "DECODE",
178 Self::Address => "ADDRESS",
179 Self::Config => "CONFIG",
180 Self::Cell => "CELL",
181 Self::Proof => "PROOF",
182 Self::Sync => "SYNC",
183 Self::Stale => "STALE",
184 Self::ClockBehind => "CLOCK_BEHIND",
185 Self::InvalidArgument => "INVALID_ARGUMENT",
186 }
187 }
188}
189
190impl std::fmt::Display for ErrorCode {
191 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192 f.write_str(self.as_str())
193 }
194}
195
196impl Error {
197 /// Which kind of failure this is, as a name a caller can branch on.
198 ///
199 /// The match below is exhaustive on purpose. `#[non_exhaustive]` binds callers
200 /// outside this crate and not this file, so a variant added without a code here fails
201 /// to compile rather than reaching a caller unnamed. That is the whole mechanism:
202 /// before this existed the mapping was a wildcard inside the Node binding, and a new
203 /// variant would have arrived in JavaScript as `UNKNOWN`.
204 #[must_use]
205 pub fn code(&self) -> ErrorCode {
206 match self {
207 Self::Transport(_) => ErrorCode::Transport,
208 Self::Handshake => ErrorCode::Handshake,
209 Self::Timeout => ErrorCode::Timeout,
210 Self::ConnectionLost => ErrorCode::ConnectionLost,
211 Self::LiteServer { .. } => ErrorCode::LiteServer,
212 Self::Decode(_) => ErrorCode::Decode,
213 Self::Address(_) => ErrorCode::Address,
214 Self::Config(_) => ErrorCode::Config,
215 Self::Cell(_) => ErrorCode::Cell,
216 Self::Proof(_) => ErrorCode::Proof,
217 Self::Sync(_) => ErrorCode::Sync,
218 Self::Stale { .. } => ErrorCode::Stale,
219 Self::ClockBehind { .. } => ErrorCode::ClockBehind,
220 }
221 }
222
223 /// Classifies a block-structure failure from a read that checked nothing.
224 ///
225 /// The same [`BlockError`](ton_net_block::BlockError) means two different things
226 /// depending on which call produced it, and the difference is what a caller acts on.
227 /// Out of the proof engine it is a server that did not prove its answer, and the
228 /// conversion below says so. Out of `Client::account_reported` there was no proof to
229 /// fail, so the same failure is only bytes that did not read, and calling it a proof
230 /// failure would report a check that never ran.
231 pub(crate) fn decoding(error: &ton_net_block::BlockError) -> Self {
232 Self::Cell(error.to_string())
233 }
234}
235
236impl From<ton_net_block::BlockError> for Error {
237 /// Every way the proof engine fails is a proof failure, bytes that are not cells
238 /// included.
239 ///
240 /// The tempting split is to call unparsable bytes a decode failure, on the reasoning
241 /// that they failed before any proof was in question. They did not: the bytes are the
242 /// server's proof, and the engine parses them with no precondition, so four bytes of
243 /// junk in a shard proof is a server failing to prove its answer in the cheapest way
244 /// available. A caller deciding whether to keep asking this server needs both to
245 /// arrive as the same kind of failure.
246 ///
247 /// A read that verified nothing must not use this. It has a classifier of its own, so
248 /// a failure out of one stays a failure to read bytes.
249 fn from(error: ton_net_block::BlockError) -> Self {
250 Self::Proof(error.to_string())
251 }
252}
253
254impl From<ton_net_adnl::TransportError> for Error {
255 fn from(error: ton_net_adnl::TransportError) -> Self {
256 // A connect timeout reads as unreachable at this layer: the deadline for a whole
257 // call is separate and surfaces as `Timeout`.
258 Self::Transport(error.to_string())
259 }
260}
261
262impl From<ton_net_adnl::AdnlError> for Error {
263 fn from(error: ton_net_adnl::AdnlError) -> Self {
264 use ton_net_adnl::AdnlError;
265 match error {
266 AdnlError::Transport(transport) => transport.into(),
267 AdnlError::Handshake(_) => Self::Handshake,
268 // Kept apart from the rest because the remedy differs: this connection is
269 // finished and no retry on it will work, where a framing failure may be one
270 // bad answer.
271 AdnlError::Desynchronized => Self::ConnectionLost,
272 // A framing, checksum, or malformed-message failure is a decode failure at
273 // this layer.
274 other => Self::Decode(other.to_string()),
275 }
276 }
277}
278
279impl From<ton_net_lite::LiteError> for Error {
280 fn from(error: ton_net_lite::LiteError) -> Self {
281 use ton_net_lite::LiteError;
282 match error {
283 LiteError::Adnl(adnl) => adnl.into(),
284 LiteError::LiteServer { code, message } => Self::LiteServer { code, message },
285 LiteError::Decode(decode) => Self::Decode(decode.to_string()),
286 other => Self::Decode(other.to_string()),
287 }
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::Error;
294 use ton_net_block::BlockError;
295
296 #[test]
297 fn a_failed_proof_never_arrives_as_something_softer() {
298 // Every way a proof can fail has to reach the caller as a proof failure. Any of
299 // these landing in `Decode` or `Cell` would read as bad bytes rather than as a
300 // server that did not prove its answer.
301 for failure in [
302 BlockError::NotAMerkleProof,
303 BlockError::ProofInconsistent,
304 BlockError::ProofNotAnchored,
305 BlockError::NotCovered,
306 BlockError::NotBound,
307 BlockError::WrongConstructor { expected: "block" },
308 BlockError::Malformed("shard state"),
309 BlockError::Cell(ton_net_cell::CellError::LabelTooLong),
310 // Bytes that are not cells belong on this list too. The engine parses the
311 // proof with no precondition, so four bytes of junk where a shard proof
312 // should be is a server failing to prove its answer in the cheapest way
313 // there is, and a caller weighing whether to keep asking this server has to
314 // see it alongside the rest.
315 BlockError::Cell(ton_net_cell::CellError::NotABagOfCells),
316 BlockError::Cell(ton_net_cell::CellError::Truncated),
317 ] {
318 let mapped = Error::from(failure.clone());
319 assert!(
320 matches!(mapped, Error::Proof(_)),
321 "{failure:?} became {mapped:?}"
322 );
323 }
324 }
325
326 #[test]
327 fn a_read_that_checked_nothing_reports_no_proof_failure() {
328 // The mirror of the rule above. `account_reported` verifies nothing, so the same
329 // failure out of it is bytes that did not read, and calling it a proof failure
330 // would report a check that never ran.
331 for failure in [
332 BlockError::Malformed("account address"),
333 BlockError::Cell(ton_net_cell::CellError::NotABagOfCells),
334 ] {
335 let mapped = Error::decoding(&failure);
336 assert!(
337 matches!(mapped, Error::Cell(_)),
338 "{failure:?} became {mapped:?}"
339 );
340 }
341 }
342}