ant_core/data/error.rs
1//! Error types for data operations.
2
3use thiserror::Error;
4
5/// Result type alias using the data Error type.
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// Errors that can occur in data operations.
9#[derive(Error, Debug)]
10pub enum Error {
11 /// Network operation failed.
12 #[error("network error: {0}")]
13 Network(String),
14
15 /// Storage operation failed.
16 #[error("storage error: {0}")]
17 Storage(String),
18
19 /// Payment operation failed.
20 #[error("payment error: {0}")]
21 Payment(String),
22
23 /// Protocol error.
24 #[error("protocol error: {0}")]
25 Protocol(String),
26
27 /// A remote node rejected a chunk PUT at the application layer.
28 ///
29 /// The node responded with a structured `ProtocolError`, so the
30 /// transport round-trip succeeded — this is an application-level
31 /// rejection (payment-failed, storage/disk-full, quote-stale,
32 /// merkle-pool-rejected), NOT evidence the client is sending too
33 /// fast. It therefore classifies as `Outcome::ApplicationError`
34 /// (see `classify_error`) and does not push the adaptive store
35 /// limiter down. The structured `source` is preserved (rather than
36 /// flattened into `Protocol`) so the controller — and a future
37 /// full-node skip-list (V2-469) — can key on the reason.
38 #[error("remote PUT rejected for {address}: {source}")]
39 RemotePut {
40 /// Hex-encoded chunk address the rejection was for.
41 address: String,
42 /// The structured remote rejection reason.
43 source: ant_protocol::ProtocolError,
44 },
45
46 /// A chunk PUT missed its close-group quorum, and the shortfall was
47 /// caused by close-group **dial/relay churn** — dead or stale relayed
48 /// peer addresses that could not be dialled — with **no** evidence of
49 /// local backpressure (no PUT-response timeouts among the failures).
50 ///
51 /// This is remote peer churn (the same dead relayed DHT addresses as
52 /// V2-551), NOT evidence the client is sending too fast. More local send
53 /// concurrency neither causes nor fixes it, so it classifies as
54 /// `Outcome::ApplicationError` (see `classify_error`) and does NOT push
55 /// the adaptive store limiter down (V2-554). Distinct from
56 /// [`Error::InsufficientPeers`], which a close-group shortfall keeps when
57 /// any PUT-response *timeout* is present (genuine local backpressure that
58 /// must still cut the cap). Like `InsufficientPeers`, it is a recoverable
59 /// quorum shortfall and is deferred/retried, not fatal.
60 #[error("close-group PUT shortfall (dial churn): {0}")]
61 CloseGroupShortfall(String),
62
63 /// Invalid data received.
64 #[error("invalid data: {0}")]
65 InvalidData(String),
66
67 /// The requested record does not exist on the network.
68 ///
69 /// A well-formed address with nothing stored at it — e.g. a `DataMap`
70 /// chunk lookup or a reconstruction fetch that came back empty from
71 /// every queried peer. Distinct from [`Error::InvalidData`], which means
72 /// content WAS retrieved but is malformed or fails integrity checks, so
73 /// callers can show "not found — check the address" instead of a
74 /// caller-bug message.
75 #[error("not found: {0}")]
76 NotFound(String),
77
78 /// Serialization error.
79 #[error("serialization error: {0}")]
80 Serialization(String),
81
82 /// Cryptographic error.
83 #[error("crypto error: {0}")]
84 Crypto(String),
85
86 /// I/O error.
87 #[error("I/O error: {0}")]
88 Io(#[from] std::io::Error),
89
90 /// Configuration error.
91 #[error("configuration error: {0}")]
92 Config(String),
93
94 /// Timeout waiting for a response.
95 #[error("timeout: {0}")]
96 Timeout(String),
97
98 /// Insufficient peers for the operation.
99 #[error("insufficient peers: {0}")]
100 InsufficientPeers(String),
101
102 /// BLS signature verification failed.
103 #[error("signature verification failed: {0}")]
104 SignatureVerification(String),
105
106 /// Self-encryption operation failed.
107 #[error("encryption error: {0}")]
108 Encryption(String),
109
110 /// The operation was cancelled by the caller rather than failing.
111 ///
112 /// Returned, for example, by streaming downloads when the consumer drops
113 /// its receiver (a client disconnect) — distinct from a transport
114 /// [`Error::Network`] failure, since nothing went wrong on the wire.
115 #[error("operation cancelled: {0}")]
116 Cancelled(String),
117
118 /// Data already exists on the network — no payment needed.
119 #[error("already stored on network")]
120 AlreadyStored,
121
122 /// A peer's quote `pub_key` does not BLAKE3-hash to the peer ID. The
123 /// storer would reject any `ProofOfPayment` containing this quote, so
124 /// the client drops the response before payment.
125 #[error("bad quote binding from peer {peer_id}: {detail}")]
126 BadQuoteBinding {
127 /// The peer ID we got the quote from (claimed identity).
128 peer_id: String,
129 /// Diagnostic detail (e.g. "BLAKE3(pub_key) = …, peer_id = …").
130 detail: String,
131 },
132
133 /// ADR-0004: a quote's commitment binding does not hold — its price is not
134 /// `calculate_price(committed_key_count)`, its `(count, pin)` shape is
135 /// incoherent, or a shipped commitment does not match the pinned count/hash.
136 /// The storer's arithmetic gate would reject such a quote, so the client
137 /// drops it before paying ("the client pays nothing it cannot resolve").
138 #[error("bad quote commitment from peer {peer_id}: {detail}")]
139 BadQuoteCommitment {
140 /// The peer ID we got the quote from.
141 peer_id: String,
142 /// Diagnostic detail (which binding rule failed).
143 detail: String,
144 },
145
146 /// Not enough disk space for the operation.
147 #[error("insufficient disk space: {0}")]
148 InsufficientDiskSpace(String),
149
150 /// Cost estimation could not reach a representative quote.
151 ///
152 /// Returned by [`crate::data::Client::estimate_upload_cost`] when every
153 /// sampled chunk address reported `AlreadyStored`, so the network price
154 /// for the remainder of the file cannot be inferred from a sample.
155 /// The attached message describes how many addresses were tried.
156 #[error("cost estimation inconclusive: {0}")]
157 CostEstimationInconclusive(String),
158
159 /// Upload partially succeeded -- some chunks stored, some failed after retries.
160 ///
161 /// The `stored` addresses can be used for progress tracking and resume.
162 #[error(
163 "partial upload: {stored_count}/{total_chunks} stored, {failed_count} failed: {reason}"
164 )]
165 PartialUpload {
166 /// Addresses of successfully stored chunks.
167 stored: Vec<[u8; 32]>,
168 /// Number of successfully stored chunks.
169 stored_count: usize,
170 /// Addresses and error messages of chunks that failed after retries.
171 failed: Vec<([u8; 32], String)>,
172 /// Number of failed chunks.
173 failed_count: usize,
174 /// Total number of chunks the upload was attempting to store.
175 total_chunks: usize,
176 /// On-chain spend incurred so far. Boxed to keep the `Error` enum small
177 /// (the variant is returned in `Result` across the crate; without the
178 /// box the two cost fields would trip `clippy::result_large_err`).
179 spend: Box<PartialUploadSpend>,
180 /// Root cause description.
181 reason: String,
182 },
183}
184
185/// On-chain spend recorded on a [`Error::PartialUpload`].
186///
187/// A partial upload still spends money for the chunks it paid for. In the
188/// single-node path payment precedes store, so this includes a failed wave's
189/// chunks; surfacing it lets the caller report real spend rather than silently
190/// dropping it.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct PartialUploadSpend {
193 /// Storage cost paid on-chain so far, in atto-tokens.
194 pub storage_cost_atto: String,
195 /// Gas cost paid on-chain so far, in wei.
196 pub gas_cost_wei: u128,
197}
198
199// ant-node is only linked when the `devnet` feature is on, so the
200// blanket `From` impl follows that gate. LocalDevnet maps node errors
201// to `Error::Network` via this conversion; default builds never see it.
202#[cfg(feature = "devnet")]
203impl From<ant_node::Error> for Error {
204 fn from(e: ant_node::Error) -> Self {
205 Self::Network(e.to_string())
206 }
207}
208
209#[cfg(test)]
210#[allow(clippy::unwrap_used, clippy::expect_used)]
211mod tests {
212 use super::*;
213
214 #[test]
215 fn test_display_network() {
216 let err = Error::Network("connection refused".to_string());
217 assert_eq!(err.to_string(), "network error: connection refused");
218 }
219
220 #[test]
221 fn test_display_storage() {
222 let err = Error::Storage("disk full".to_string());
223 assert_eq!(err.to_string(), "storage error: disk full");
224 }
225
226 #[test]
227 fn test_display_payment() {
228 let err = Error::Payment("insufficient funds".to_string());
229 assert_eq!(err.to_string(), "payment error: insufficient funds");
230 }
231
232 #[test]
233 fn test_display_protocol() {
234 let err = Error::Protocol("invalid message".to_string());
235 assert_eq!(err.to_string(), "protocol error: invalid message");
236 }
237
238 #[test]
239 fn test_display_invalid_data() {
240 let err = Error::InvalidData("bad hash".to_string());
241 assert_eq!(err.to_string(), "invalid data: bad hash");
242 }
243
244 #[test]
245 fn test_display_not_found() {
246 let err = Error::NotFound("DataMap chunk not found at abcd".to_string());
247 assert_eq!(
248 err.to_string(),
249 "not found: DataMap chunk not found at abcd"
250 );
251 }
252
253 #[test]
254 fn test_display_serialization() {
255 let err = Error::Serialization("decode failed".to_string());
256 assert_eq!(err.to_string(), "serialization error: decode failed");
257 }
258
259 #[test]
260 fn test_display_crypto() {
261 let err = Error::Crypto("key mismatch".to_string());
262 assert_eq!(err.to_string(), "crypto error: key mismatch");
263 }
264
265 #[test]
266 fn test_display_io() {
267 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
268 let err = Error::Io(io_err);
269 assert_eq!(err.to_string(), "I/O error: file missing");
270 }
271
272 #[test]
273 fn test_display_config() {
274 let err = Error::Config("bad value".to_string());
275 assert_eq!(err.to_string(), "configuration error: bad value");
276 }
277
278 #[test]
279 fn test_display_timeout() {
280 let err = Error::Timeout("30s elapsed".to_string());
281 assert_eq!(err.to_string(), "timeout: 30s elapsed");
282 }
283
284 #[test]
285 fn test_display_insufficient_peers() {
286 let err = Error::InsufficientPeers("need 5, got 2".to_string());
287 assert_eq!(err.to_string(), "insufficient peers: need 5, got 2");
288 }
289
290 #[test]
291 fn test_display_close_group_shortfall() {
292 let err = Error::CloseGroupShortfall("Stored on 3 peers, need 4".to_string());
293 assert_eq!(
294 err.to_string(),
295 "close-group PUT shortfall (dial churn): Stored on 3 peers, need 4"
296 );
297 }
298
299 #[test]
300 fn test_display_signature_verification() {
301 let err = Error::SignatureVerification("invalid sig".to_string());
302 assert_eq!(
303 err.to_string(),
304 "signature verification failed: invalid sig"
305 );
306 }
307
308 #[test]
309 fn test_display_encryption() {
310 let err = Error::Encryption("decrypt failed".to_string());
311 assert_eq!(err.to_string(), "encryption error: decrypt failed");
312 }
313
314 #[test]
315 fn test_display_cancelled() {
316 let err = Error::Cancelled("download stream receiver dropped".to_string());
317 assert_eq!(
318 err.to_string(),
319 "operation cancelled: download stream receiver dropped"
320 );
321 }
322
323 #[test]
324 fn test_display_insufficient_disk_space() {
325 let err = Error::InsufficientDiskSpace("need 100 MB but only 10 MB available".to_string());
326 assert_eq!(
327 err.to_string(),
328 "insufficient disk space: need 100 MB but only 10 MB available"
329 );
330 }
331
332 #[test]
333 fn test_display_cost_estimation_inconclusive() {
334 let err = Error::CostEstimationInconclusive(
335 "sampled 5 addresses, all already stored".to_string(),
336 );
337 assert_eq!(
338 err.to_string(),
339 "cost estimation inconclusive: sampled 5 addresses, all already stored"
340 );
341 }
342
343 #[test]
344 fn test_from_io_error() {
345 let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
346 let err: Error = io_err.into();
347 assert!(matches!(err, Error::Io(_)));
348 }
349}