ant-node 0.10.1

Pure quantum-proof network node for the Autonomi decentralized network
Documentation
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Chunk message types for the ANT protocol.
//!
//! Chunks are immutable, content-addressed data blocks where the address
//! is the BLAKE3 hash of the content. Maximum size is 4MB.
//!
//! This module defines the wire protocol messages for chunk operations
//! using postcard serialization for compact, fast encoding.

use serde::{Deserialize, Serialize};

/// Protocol identifier for chunk operations.
pub const CHUNK_PROTOCOL_ID: &str = "autonomi.ant.chunk.v1";

/// Current protocol version.
pub const PROTOCOL_VERSION: u16 = 1;

/// Maximum chunk size in bytes (4MB).
pub const MAX_CHUNK_SIZE: usize = 4 * 1024 * 1024;

/// Maximum wire message size in bytes (5MB).
///
/// Limits the input buffer accepted by [`ChunkMessage::decode`] to prevent
/// unbounded allocation from malicious or corrupted payloads. Set slightly
/// above [`MAX_CHUNK_SIZE`] to accommodate message envelope overhead.
pub const MAX_WIRE_MESSAGE_SIZE: usize = 5 * 1024 * 1024;

/// Data type identifier for chunks.
pub const DATA_TYPE_CHUNK: u32 = 0;

/// Content-addressed identifier (32 bytes).
pub type XorName = [u8; 32];

/// Byte length of an [`XorName`].
pub const XORNAME_LEN: usize = std::mem::size_of::<XorName>();

/// Enum of all chunk protocol message types.
///
/// Uses a single-byte discriminant for efficient wire encoding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ChunkMessageBody {
    /// Request to store a chunk.
    PutRequest(ChunkPutRequest),
    /// Response to a PUT request.
    PutResponse(ChunkPutResponse),
    /// Request to retrieve a chunk.
    GetRequest(ChunkGetRequest),
    /// Response to a GET request.
    GetResponse(ChunkGetResponse),
    /// Request a storage quote.
    QuoteRequest(ChunkQuoteRequest),
    /// Response with a storage quote.
    QuoteResponse(ChunkQuoteResponse),
    /// Request a merkle candidate quote for batch payments.
    MerkleCandidateQuoteRequest(MerkleCandidateQuoteRequest),
    /// Response with a merkle candidate quote.
    MerkleCandidateQuoteResponse(MerkleCandidateQuoteResponse),
}

/// Wire-format wrapper that pairs a sender-assigned `request_id` with
/// a [`ChunkMessageBody`].
///
/// The sender picks a unique `request_id`; the handler echoes it back
/// in the response so callers can correlate replies by ID rather than
/// by source peer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkMessage {
    /// Sender-assigned identifier, echoed back in the response.
    pub request_id: u64,
    /// The protocol message body.
    pub body: ChunkMessageBody,
}

impl ChunkMessage {
    /// Encode the message to bytes using postcard.
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails.
    pub fn encode(&self) -> Result<Vec<u8>, ProtocolError> {
        postcard::to_stdvec(self).map_err(|e| ProtocolError::SerializationFailed(e.to_string()))
    }

    /// Decode a message from bytes using postcard.
    ///
    /// Rejects payloads larger than [`MAX_WIRE_MESSAGE_SIZE`] before
    /// attempting deserialization.
    ///
    /// # Errors
    ///
    /// Returns [`ProtocolError::MessageTooLarge`] if the input exceeds the
    /// size limit, or [`ProtocolError::DeserializationFailed`] if postcard
    /// cannot parse the data.
    pub fn decode(data: &[u8]) -> Result<Self, ProtocolError> {
        if data.len() > MAX_WIRE_MESSAGE_SIZE {
            return Err(ProtocolError::MessageTooLarge {
                size: data.len(),
                max_size: MAX_WIRE_MESSAGE_SIZE,
            });
        }
        postcard::from_bytes(data).map_err(|e| ProtocolError::DeserializationFailed(e.to_string()))
    }
}

// =============================================================================
// PUT Request/Response
// =============================================================================

/// Request to store a chunk.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkPutRequest {
    /// The content-addressed identifier (BLAKE3 of content).
    pub address: XorName,
    /// The chunk data.
    pub content: Vec<u8>,
    /// Optional payment proof (serialized `ProofOfPayment`).
    /// Required for new chunks unless already verified.
    pub payment_proof: Option<Vec<u8>>,
}

impl ChunkPutRequest {
    /// Create a new PUT request.
    #[must_use]
    pub fn new(address: XorName, content: Vec<u8>) -> Self {
        Self {
            address,
            content,
            payment_proof: None,
        }
    }

    /// Create a new PUT request with payment proof.
    #[must_use]
    pub fn with_payment(address: XorName, content: Vec<u8>, payment_proof: Vec<u8>) -> Self {
        Self {
            address,
            content,
            payment_proof: Some(payment_proof),
        }
    }
}

/// Response to a PUT request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ChunkPutResponse {
    /// Chunk stored successfully.
    Success {
        /// The address where the chunk was stored.
        address: XorName,
    },
    /// Chunk already exists (idempotent success).
    AlreadyExists {
        /// The existing chunk address.
        address: XorName,
    },
    /// Payment is required to store this chunk.
    PaymentRequired {
        /// Error message.
        message: String,
    },
    /// An error occurred.
    Error(ProtocolError),
}

// =============================================================================
// GET Request/Response
// =============================================================================

/// Request to retrieve a chunk.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkGetRequest {
    /// The content-addressed identifier to retrieve.
    pub address: XorName,
}

impl ChunkGetRequest {
    /// Create a new GET request.
    #[must_use]
    pub fn new(address: XorName) -> Self {
        Self { address }
    }
}

/// Response to a GET request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ChunkGetResponse {
    /// Chunk found and returned.
    Success {
        /// The chunk address.
        address: XorName,
        /// The chunk data.
        content: Vec<u8>,
    },
    /// Chunk not found.
    NotFound {
        /// The requested address.
        address: XorName,
    },
    /// An error occurred.
    Error(ProtocolError),
}

// =============================================================================
// Quote Request/Response
// =============================================================================

/// Request a storage quote for a chunk.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkQuoteRequest {
    /// The content address of the data to store.
    pub address: XorName,
    /// Size of the data in bytes.
    pub data_size: u64,
    /// Data type identifier (0 for chunks).
    pub data_type: u32,
}

impl ChunkQuoteRequest {
    /// Create a new quote request.
    #[must_use]
    pub fn new(address: XorName, data_size: u64) -> Self {
        Self {
            address,
            data_size,
            data_type: DATA_TYPE_CHUNK,
        }
    }
}

/// Response with a storage quote.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ChunkQuoteResponse {
    /// Quote generated successfully.
    ///
    /// When `already_stored` is `true` the node already holds this chunk and no
    /// payment is required — the client should skip the pay-then-PUT cycle for
    /// this address. The quote is still included for informational purposes.
    Success {
        /// Serialized `PaymentQuote`.
        quote: Vec<u8>,
        /// `true` when the chunk already exists on this node (skip payment).
        already_stored: bool,
    },
    /// Quote generation failed.
    Error(ProtocolError),
}

// =============================================================================
// Merkle Candidate Quote Request/Response
// =============================================================================

/// Request a merkle candidate quote for batch payments.
///
/// Part of the merkle batch payment system where clients collect
/// signed candidate quotes from 16 closest peers per pool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MerkleCandidateQuoteRequest {
    /// The candidate pool address (hash of midpoint || root || timestamp).
    pub address: XorName,
    /// Data type identifier (0 for chunks).
    pub data_type: u32,
    /// Size of the data in bytes.
    pub data_size: u64,
    /// Client-provided merkle payment timestamp (unix seconds).
    pub merkle_payment_timestamp: u64,
}

/// Response with a merkle candidate quote.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MerkleCandidateQuoteResponse {
    /// Candidate quote generated successfully.
    /// Contains the serialized `MerklePaymentCandidateNode`.
    Success {
        /// Serialized `MerklePaymentCandidateNode`.
        candidate_node: Vec<u8>,
    },
    /// Quote generation failed.
    Error(ProtocolError),
}

// =============================================================================
// Payment Proof Type Tags
// =============================================================================

/// Version byte prefix for payment proof serialization.
/// Allows the verifier to detect proof type before deserialization.
pub const PROOF_TAG_SINGLE_NODE: u8 = 0x01;
/// Version byte prefix for merkle payment proofs.
pub const PROOF_TAG_MERKLE: u8 = 0x02;

// =============================================================================
// Protocol Errors
// =============================================================================

/// Errors that can occur during protocol operations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ProtocolError {
    /// Message serialization failed.
    SerializationFailed(String),
    /// Message deserialization failed.
    DeserializationFailed(String),
    /// Wire message exceeds the maximum allowed size.
    MessageTooLarge {
        /// Actual size of the message in bytes.
        size: usize,
        /// Maximum allowed size.
        max_size: usize,
    },
    /// Chunk exceeds maximum size.
    ChunkTooLarge {
        /// Size of the chunk in bytes.
        size: usize,
        /// Maximum allowed size.
        max_size: usize,
    },
    /// Content address mismatch (hash(content) != address).
    AddressMismatch {
        /// Expected address.
        expected: XorName,
        /// Actual address computed from content.
        actual: XorName,
    },
    /// Storage operation failed.
    StorageFailed(String),
    /// Payment verification failed.
    PaymentFailed(String),
    /// Quote generation failed.
    QuoteFailed(String),
    /// Internal error.
    Internal(String),
}

impl std::fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SerializationFailed(msg) => write!(f, "serialization failed: {msg}"),
            Self::DeserializationFailed(msg) => write!(f, "deserialization failed: {msg}"),
            Self::MessageTooLarge { size, max_size } => {
                write!(f, "message size {size} exceeds maximum {max_size}")
            }
            Self::ChunkTooLarge { size, max_size } => {
                write!(f, "chunk size {size} exceeds maximum {max_size}")
            }
            Self::AddressMismatch { expected, actual } => {
                write!(
                    f,
                    "address mismatch: expected {}, got {}",
                    hex::encode(expected),
                    hex::encode(actual)
                )
            }
            Self::StorageFailed(msg) => write!(f, "storage failed: {msg}"),
            Self::PaymentFailed(msg) => write!(f, "payment failed: {msg}"),
            Self::QuoteFailed(msg) => write!(f, "quote failed: {msg}"),
            Self::Internal(msg) => write!(f, "internal error: {msg}"),
        }
    }
}

impl std::error::Error for ProtocolError {}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn test_put_request_encode_decode() {
        let address = [0xAB; 32];
        let content = vec![1, 2, 3, 4, 5];
        let request = ChunkPutRequest::new(address, content.clone());
        let msg = ChunkMessage {
            request_id: 42,
            body: ChunkMessageBody::PutRequest(request),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 42);
        if let ChunkMessageBody::PutRequest(req) = decoded.body {
            assert_eq!(req.address, address);
            assert_eq!(req.content, content);
            assert!(req.payment_proof.is_none());
        } else {
            panic!("expected PutRequest");
        }
    }

    #[test]
    fn test_put_request_with_payment() {
        let address = [0xAB; 32];
        let content = vec![1, 2, 3, 4, 5];
        let payment = vec![10, 20, 30];
        let request = ChunkPutRequest::with_payment(address, content.clone(), payment.clone());

        assert_eq!(request.address, address);
        assert_eq!(request.content, content);
        assert_eq!(request.payment_proof, Some(payment));
    }

    #[test]
    fn test_get_request_encode_decode() {
        let address = [0xCD; 32];
        let request = ChunkGetRequest::new(address);
        let msg = ChunkMessage {
            request_id: 7,
            body: ChunkMessageBody::GetRequest(request),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 7);
        if let ChunkMessageBody::GetRequest(req) = decoded.body {
            assert_eq!(req.address, address);
        } else {
            panic!("expected GetRequest");
        }
    }

    #[test]
    fn test_put_response_success() {
        let address = [0xEF; 32];
        let response = ChunkPutResponse::Success { address };
        let msg = ChunkMessage {
            request_id: 99,
            body: ChunkMessageBody::PutResponse(response),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 99);
        if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: addr }) =
            decoded.body
        {
            assert_eq!(addr, address);
        } else {
            panic!("expected PutResponse::Success");
        }
    }

    #[test]
    fn test_get_response_not_found() {
        let address = [0x12; 32];
        let response = ChunkGetResponse::NotFound { address };
        let msg = ChunkMessage {
            request_id: 0,
            body: ChunkMessageBody::GetResponse(response),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 0);
        if let ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: addr }) =
            decoded.body
        {
            assert_eq!(addr, address);
        } else {
            panic!("expected GetResponse::NotFound");
        }
    }

    #[test]
    fn test_quote_request_encode_decode() {
        let address = [0x34; 32];
        let request = ChunkQuoteRequest::new(address, 1024);
        let msg = ChunkMessage {
            request_id: 1,
            body: ChunkMessageBody::QuoteRequest(request),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 1);
        if let ChunkMessageBody::QuoteRequest(req) = decoded.body {
            assert_eq!(req.address, address);
            assert_eq!(req.data_size, 1024);
            assert_eq!(req.data_type, DATA_TYPE_CHUNK);
        } else {
            panic!("expected QuoteRequest");
        }
    }

    #[test]
    fn test_protocol_error_display() {
        let err = ProtocolError::ChunkTooLarge {
            size: 5_000_000,
            max_size: MAX_CHUNK_SIZE,
        };
        assert!(err.to_string().contains("5000000"));
        assert!(err.to_string().contains(&MAX_CHUNK_SIZE.to_string()));

        let err = ProtocolError::AddressMismatch {
            expected: [0xAA; 32],
            actual: [0xBB; 32],
        };
        let display = err.to_string();
        assert!(display.contains("address mismatch"));
    }

    #[test]
    fn test_decode_rejects_oversized_payload() {
        let oversized = vec![0u8; MAX_WIRE_MESSAGE_SIZE + 1];
        let result = ChunkMessage::decode(&oversized);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, ProtocolError::MessageTooLarge { .. }),
            "expected MessageTooLarge, got {err:?}"
        );
    }

    #[test]
    fn test_invalid_decode() {
        let invalid_data = vec![0xFF, 0xFF, 0xFF];
        let result = ChunkMessage::decode(&invalid_data);
        assert!(result.is_err());
    }

    #[test]
    fn test_constants() {
        assert_eq!(CHUNK_PROTOCOL_ID, "autonomi.ant.chunk.v1");
        assert_eq!(PROTOCOL_VERSION, 1);
        assert_eq!(MAX_CHUNK_SIZE, 4 * 1024 * 1024);
        assert_eq!(DATA_TYPE_CHUNK, 0);
    }

    #[test]
    fn test_proof_tag_constants() {
        // Tags must be distinct non-zero bytes
        assert_ne!(PROOF_TAG_SINGLE_NODE, PROOF_TAG_MERKLE);
        assert_ne!(PROOF_TAG_SINGLE_NODE, 0x00);
        assert_ne!(PROOF_TAG_MERKLE, 0x00);
        assert_eq!(PROOF_TAG_SINGLE_NODE, 0x01);
        assert_eq!(PROOF_TAG_MERKLE, 0x02);
    }

    #[test]
    fn test_merkle_candidate_quote_request_encode_decode() {
        let address = [0x56; 32];
        let request = MerkleCandidateQuoteRequest {
            address,
            data_type: DATA_TYPE_CHUNK,
            data_size: 2048,
            merkle_payment_timestamp: 1_700_000_000,
        };
        let msg = ChunkMessage {
            request_id: 500,
            body: ChunkMessageBody::MerkleCandidateQuoteRequest(request),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 500);
        if let ChunkMessageBody::MerkleCandidateQuoteRequest(req) = decoded.body {
            assert_eq!(req.address, address);
            assert_eq!(req.data_type, DATA_TYPE_CHUNK);
            assert_eq!(req.data_size, 2048);
            assert_eq!(req.merkle_payment_timestamp, 1_700_000_000);
        } else {
            panic!("expected MerkleCandidateQuoteRequest");
        }
    }

    #[test]
    fn test_merkle_candidate_quote_response_success_encode_decode() {
        let candidate_node_bytes = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let response = MerkleCandidateQuoteResponse::Success {
            candidate_node: candidate_node_bytes.clone(),
        };
        let msg = ChunkMessage {
            request_id: 501,
            body: ChunkMessageBody::MerkleCandidateQuoteResponse(response),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 501);
        if let ChunkMessageBody::MerkleCandidateQuoteResponse(
            MerkleCandidateQuoteResponse::Success { candidate_node },
        ) = decoded.body
        {
            assert_eq!(candidate_node, candidate_node_bytes);
        } else {
            panic!("expected MerkleCandidateQuoteResponse::Success");
        }
    }

    #[test]
    fn test_merkle_candidate_quote_response_error_encode_decode() {
        let error = ProtocolError::QuoteFailed("no libp2p keypair".to_string());
        let response = MerkleCandidateQuoteResponse::Error(error.clone());
        let msg = ChunkMessage {
            request_id: 502,
            body: ChunkMessageBody::MerkleCandidateQuoteResponse(response),
        };

        let encoded = msg.encode().expect("encode should succeed");
        let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");

        assert_eq!(decoded.request_id, 502);
        if let ChunkMessageBody::MerkleCandidateQuoteResponse(
            MerkleCandidateQuoteResponse::Error(err),
        ) = decoded.body
        {
            assert_eq!(err, error);
        } else {
            panic!("expected MerkleCandidateQuoteResponse::Error");
        }
    }
}