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 /// Serialization error.
68 #[error("serialization error: {0}")]
69 Serialization(String),
70
71 /// Cryptographic error.
72 #[error("crypto error: {0}")]
73 Crypto(String),
74
75 /// I/O error.
76 #[error("I/O error: {0}")]
77 Io(#[from] std::io::Error),
78
79 /// Configuration error.
80 #[error("configuration error: {0}")]
81 Config(String),
82
83 /// Timeout waiting for a response.
84 #[error("timeout: {0}")]
85 Timeout(String),
86
87 /// Insufficient peers for the operation.
88 #[error("insufficient peers: {0}")]
89 InsufficientPeers(String),
90
91 /// BLS signature verification failed.
92 #[error("signature verification failed: {0}")]
93 SignatureVerification(String),
94
95 /// Self-encryption operation failed.
96 #[error("encryption error: {0}")]
97 Encryption(String),
98
99 /// The operation was cancelled by the caller rather than failing.
100 ///
101 /// Returned, for example, by streaming downloads when the consumer drops
102 /// its receiver (a client disconnect) — distinct from a transport
103 /// [`Error::Network`] failure, since nothing went wrong on the wire.
104 #[error("operation cancelled: {0}")]
105 Cancelled(String),
106
107 /// Data already exists on the network — no payment needed.
108 #[error("already stored on network")]
109 AlreadyStored,
110
111 /// A peer's quote `pub_key` does not BLAKE3-hash to the peer ID. The
112 /// storer would reject any `ProofOfPayment` containing this quote, so
113 /// the client drops the response before payment.
114 #[error("bad quote binding from peer {peer_id}: {detail}")]
115 BadQuoteBinding {
116 /// The peer ID we got the quote from (claimed identity).
117 peer_id: String,
118 /// Diagnostic detail (e.g. "BLAKE3(pub_key) = …, peer_id = …").
119 detail: String,
120 },
121
122 /// ADR-0004: a quote's commitment binding does not hold — its price is not
123 /// `calculate_price(committed_key_count)`, its `(count, pin)` shape is
124 /// incoherent, or a shipped commitment does not match the pinned count/hash.
125 /// The storer's arithmetic gate would reject such a quote, so the client
126 /// drops it before paying ("the client pays nothing it cannot resolve").
127 #[error("bad quote commitment from peer {peer_id}: {detail}")]
128 BadQuoteCommitment {
129 /// The peer ID we got the quote from.
130 peer_id: String,
131 /// Diagnostic detail (which binding rule failed).
132 detail: String,
133 },
134
135 /// Not enough disk space for the operation.
136 #[error("insufficient disk space: {0}")]
137 InsufficientDiskSpace(String),
138
139 /// Cost estimation could not reach a representative quote.
140 ///
141 /// Returned by [`crate::data::Client::estimate_upload_cost`] when every
142 /// sampled chunk address reported `AlreadyStored`, so the network price
143 /// for the remainder of the file cannot be inferred from a sample.
144 /// The attached message describes how many addresses were tried.
145 #[error("cost estimation inconclusive: {0}")]
146 CostEstimationInconclusive(String),
147
148 /// Upload partially succeeded -- some chunks stored, some failed after retries.
149 ///
150 /// The `stored` addresses can be used for progress tracking and resume.
151 #[error(
152 "partial upload: {stored_count}/{total_chunks} stored, {failed_count} failed: {reason}"
153 )]
154 PartialUpload {
155 /// Addresses of successfully stored chunks.
156 stored: Vec<[u8; 32]>,
157 /// Number of successfully stored chunks.
158 stored_count: usize,
159 /// Addresses and error messages of chunks that failed after retries.
160 failed: Vec<([u8; 32], String)>,
161 /// Number of failed chunks.
162 failed_count: usize,
163 /// Total number of chunks the upload was attempting to store.
164 total_chunks: usize,
165 /// On-chain spend incurred so far. Boxed to keep the `Error` enum small
166 /// (the variant is returned in `Result` across the crate; without the
167 /// box the two cost fields would trip `clippy::result_large_err`).
168 spend: Box<PartialUploadSpend>,
169 /// Root cause description.
170 reason: String,
171 },
172}
173
174/// On-chain spend recorded on a [`Error::PartialUpload`].
175///
176/// A partial upload still spends money for the chunks it paid for. In the
177/// single-node path payment precedes store, so this includes a failed wave's
178/// chunks; surfacing it lets the caller report real spend rather than silently
179/// dropping it.
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct PartialUploadSpend {
182 /// Storage cost paid on-chain so far, in atto-tokens.
183 pub storage_cost_atto: String,
184 /// Gas cost paid on-chain so far, in wei.
185 pub gas_cost_wei: u128,
186}
187
188// ant-node is only linked when the `devnet` feature is on, so the
189// blanket `From` impl follows that gate. LocalDevnet maps node errors
190// to `Error::Network` via this conversion; default builds never see it.
191#[cfg(feature = "devnet")]
192impl From<ant_node::Error> for Error {
193 fn from(e: ant_node::Error) -> Self {
194 Self::Network(e.to_string())
195 }
196}
197
198#[cfg(test)]
199#[allow(clippy::unwrap_used, clippy::expect_used)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn test_display_network() {
205 let err = Error::Network("connection refused".to_string());
206 assert_eq!(err.to_string(), "network error: connection refused");
207 }
208
209 #[test]
210 fn test_display_storage() {
211 let err = Error::Storage("disk full".to_string());
212 assert_eq!(err.to_string(), "storage error: disk full");
213 }
214
215 #[test]
216 fn test_display_payment() {
217 let err = Error::Payment("insufficient funds".to_string());
218 assert_eq!(err.to_string(), "payment error: insufficient funds");
219 }
220
221 #[test]
222 fn test_display_protocol() {
223 let err = Error::Protocol("invalid message".to_string());
224 assert_eq!(err.to_string(), "protocol error: invalid message");
225 }
226
227 #[test]
228 fn test_display_invalid_data() {
229 let err = Error::InvalidData("bad hash".to_string());
230 assert_eq!(err.to_string(), "invalid data: bad hash");
231 }
232
233 #[test]
234 fn test_display_serialization() {
235 let err = Error::Serialization("decode failed".to_string());
236 assert_eq!(err.to_string(), "serialization error: decode failed");
237 }
238
239 #[test]
240 fn test_display_crypto() {
241 let err = Error::Crypto("key mismatch".to_string());
242 assert_eq!(err.to_string(), "crypto error: key mismatch");
243 }
244
245 #[test]
246 fn test_display_io() {
247 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
248 let err = Error::Io(io_err);
249 assert_eq!(err.to_string(), "I/O error: file missing");
250 }
251
252 #[test]
253 fn test_display_config() {
254 let err = Error::Config("bad value".to_string());
255 assert_eq!(err.to_string(), "configuration error: bad value");
256 }
257
258 #[test]
259 fn test_display_timeout() {
260 let err = Error::Timeout("30s elapsed".to_string());
261 assert_eq!(err.to_string(), "timeout: 30s elapsed");
262 }
263
264 #[test]
265 fn test_display_insufficient_peers() {
266 let err = Error::InsufficientPeers("need 5, got 2".to_string());
267 assert_eq!(err.to_string(), "insufficient peers: need 5, got 2");
268 }
269
270 #[test]
271 fn test_display_close_group_shortfall() {
272 let err = Error::CloseGroupShortfall("Stored on 3 peers, need 4".to_string());
273 assert_eq!(
274 err.to_string(),
275 "close-group PUT shortfall (dial churn): Stored on 3 peers, need 4"
276 );
277 }
278
279 #[test]
280 fn test_display_signature_verification() {
281 let err = Error::SignatureVerification("invalid sig".to_string());
282 assert_eq!(
283 err.to_string(),
284 "signature verification failed: invalid sig"
285 );
286 }
287
288 #[test]
289 fn test_display_encryption() {
290 let err = Error::Encryption("decrypt failed".to_string());
291 assert_eq!(err.to_string(), "encryption error: decrypt failed");
292 }
293
294 #[test]
295 fn test_display_cancelled() {
296 let err = Error::Cancelled("download stream receiver dropped".to_string());
297 assert_eq!(
298 err.to_string(),
299 "operation cancelled: download stream receiver dropped"
300 );
301 }
302
303 #[test]
304 fn test_display_insufficient_disk_space() {
305 let err = Error::InsufficientDiskSpace("need 100 MB but only 10 MB available".to_string());
306 assert_eq!(
307 err.to_string(),
308 "insufficient disk space: need 100 MB but only 10 MB available"
309 );
310 }
311
312 #[test]
313 fn test_display_cost_estimation_inconclusive() {
314 let err = Error::CostEstimationInconclusive(
315 "sampled 5 addresses, all already stored".to_string(),
316 );
317 assert_eq!(
318 err.to_string(),
319 "cost estimation inconclusive: sampled 5 addresses, all already stored"
320 );
321 }
322
323 #[test]
324 fn test_from_io_error() {
325 let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
326 let err: Error = io_err.into();
327 assert!(matches!(err, Error::Io(_)));
328 }
329}