Skip to main content

ant_node/payment/
proof.rs

1//! Payment proof wrapper that includes transaction hashes.
2//!
3//! `PaymentProof` bundles a `ProofOfPayment` (quotes + peer IDs) with the
4//! on-chain transaction hashes returned by the wallet after payment.
5
6use crate::ant_protocol::{PROOF_TAG_MERKLE, PROOF_TAG_SINGLE_NODE};
7use evmlib::common::TxHash;
8use evmlib::merkle_payments::MerklePaymentProof;
9use evmlib::ProofOfPayment;
10use serde::{Deserialize, Serialize};
11
12/// A payment proof that includes both the quote-based proof and on-chain tx hashes.
13///
14/// This replaces the bare `ProofOfPayment` in serialized proof bytes, adding
15/// the transaction hashes that were previously discarded after `payment.pay()`.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct PaymentProof {
18    /// The original quote-based proof (peer IDs + quotes with ML-DSA-65 signatures).
19    pub proof_of_payment: ProofOfPayment,
20    /// Transaction hashes from the on-chain payment.
21    /// Typically contains one hash for the median (non-zero) quote.
22    pub tx_hashes: Vec<TxHash>,
23}
24
25/// The detected type of a payment proof.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ProofType {
28    /// `SingleNode` payment (5 quotes, median-paid).
29    SingleNode,
30    /// Merkle batch payment (one tx for many chunks).
31    Merkle,
32}
33
34/// Detect the proof type from the first byte (version tag).
35///
36/// Returns `None` if the tag byte is unrecognized or the slice is empty.
37#[must_use]
38pub fn detect_proof_type(bytes: &[u8]) -> Option<ProofType> {
39    match bytes.first() {
40        Some(&PROOF_TAG_SINGLE_NODE) => Some(ProofType::SingleNode),
41        Some(&PROOF_TAG_MERKLE) => Some(ProofType::Merkle),
42        _ => None,
43    }
44}
45
46/// Serialize a `PaymentProof` (single-node) with the version tag prefix.
47///
48/// # Errors
49///
50/// Returns an error if serialization fails.
51pub fn serialize_single_node_proof(
52    proof: &PaymentProof,
53) -> std::result::Result<Vec<u8>, rmp_serde::encode::Error> {
54    let body = rmp_serde::to_vec(proof)?;
55    let mut tagged = Vec::with_capacity(1 + body.len());
56    tagged.push(PROOF_TAG_SINGLE_NODE);
57    tagged.extend_from_slice(&body);
58    Ok(tagged)
59}
60
61/// Serialize a `MerklePaymentProof` with the version tag prefix.
62///
63/// # Errors
64///
65/// Returns an error if serialization fails.
66pub fn serialize_merkle_proof(
67    proof: &MerklePaymentProof,
68) -> std::result::Result<Vec<u8>, rmp_serde::encode::Error> {
69    let body = rmp_serde::to_vec(proof)?;
70    let mut tagged = Vec::with_capacity(1 + body.len());
71    tagged.push(PROOF_TAG_MERKLE);
72    tagged.extend_from_slice(&body);
73    Ok(tagged)
74}
75
76/// Deserialize proof bytes from the `PaymentProof` format (single-node).
77///
78/// Expects the first byte to be `PROOF_TAG_SINGLE_NODE`.
79/// Returns `(ProofOfPayment, Vec<TxHash>)`.
80///
81/// # Errors
82///
83/// Returns an error if the tag is missing or the bytes cannot be deserialized.
84pub fn deserialize_proof(bytes: &[u8]) -> Result<(ProofOfPayment, Vec<TxHash>), String> {
85    if bytes.first() != Some(&PROOF_TAG_SINGLE_NODE) {
86        return Err("Missing single-node proof tag byte".to_string());
87    }
88    let payload = bytes
89        .get(1..)
90        .ok_or_else(|| "Single-node proof tag present but no payload".to_string())?;
91    let proof = rmp_serde::from_slice::<PaymentProof>(payload)
92        .map_err(|e| format!("Failed to deserialize single-node proof: {e}"))?;
93    Ok((proof.proof_of_payment, proof.tx_hashes))
94}
95
96/// Deserialize proof bytes as a `MerklePaymentProof`.
97///
98/// Expects the first byte to be `PROOF_TAG_MERKLE`.
99///
100/// # Errors
101///
102/// Returns an error if the bytes cannot be deserialized or the tag is wrong.
103pub fn deserialize_merkle_proof(bytes: &[u8]) -> std::result::Result<MerklePaymentProof, String> {
104    if bytes.first() != Some(&PROOF_TAG_MERKLE) {
105        return Err("Missing merkle proof tag byte".to_string());
106    }
107    let payload = bytes
108        .get(1..)
109        .ok_or_else(|| "Merkle proof tag present but no payload".to_string())?;
110    rmp_serde::from_slice::<MerklePaymentProof>(payload)
111        .map_err(|e| format!("Failed to deserialize merkle proof: {e}"))
112}
113
114#[cfg(test)]
115#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
116mod tests {
117    use super::*;
118    use alloy::primitives::FixedBytes;
119    use evmlib::merkle_payments::{
120        MerklePaymentCandidateNode, MerklePaymentCandidatePool, MerklePaymentProof, MerkleTree,
121        CANDIDATES_PER_POOL,
122    };
123    use evmlib::quoting_metrics::QuotingMetrics;
124    use evmlib::EncodedPeerId;
125    use evmlib::PaymentQuote;
126    use evmlib::RewardsAddress;
127    use saorsa_core::MlDsa65;
128    use saorsa_pqc::pqc::types::MlDsaSecretKey;
129    use saorsa_pqc::pqc::MlDsaOperations;
130    use std::time::SystemTime;
131    use xor_name::XorName;
132
133    fn make_test_quote() -> PaymentQuote {
134        PaymentQuote {
135            content: XorName::random(&mut rand::thread_rng()),
136            timestamp: SystemTime::now(),
137            quoting_metrics: QuotingMetrics {
138                data_size: 1024,
139                data_type: 0,
140                close_records_stored: 0,
141                records_per_type: vec![],
142                max_records: 1000,
143                received_payment_count: 0,
144                live_time: 0,
145                network_density: None,
146                network_size: None,
147            },
148            rewards_address: RewardsAddress::new([1u8; 20]),
149            pub_key: vec![],
150            signature: vec![],
151        }
152    }
153
154    fn make_proof_of_payment() -> ProofOfPayment {
155        let random_peer = EncodedPeerId::new(rand::random());
156        ProofOfPayment {
157            peer_quotes: vec![(random_peer, make_test_quote())],
158        }
159    }
160
161    #[test]
162    fn test_payment_proof_serialization_roundtrip() {
163        let tx_hash = FixedBytes::from([0xABu8; 32]);
164        let proof = PaymentProof {
165            proof_of_payment: make_proof_of_payment(),
166            tx_hashes: vec![tx_hash],
167        };
168
169        let bytes = serialize_single_node_proof(&proof).unwrap();
170        let (pop, hashes) = deserialize_proof(&bytes).unwrap();
171
172        assert_eq!(pop.peer_quotes.len(), 1);
173        assert_eq!(hashes.len(), 1);
174        assert_eq!(hashes.first().unwrap(), &tx_hash);
175    }
176
177    #[test]
178    fn test_payment_proof_with_empty_tx_hashes() {
179        let proof = PaymentProof {
180            proof_of_payment: make_proof_of_payment(),
181            tx_hashes: vec![],
182        };
183
184        let bytes = serialize_single_node_proof(&proof).unwrap();
185        let (pop, hashes) = deserialize_proof(&bytes).unwrap();
186
187        assert_eq!(pop.peer_quotes.len(), 1);
188        assert!(hashes.is_empty());
189    }
190
191    #[test]
192    fn test_deserialize_proof_rejects_garbage() {
193        let garbage = vec![0xFF, 0x00, 0x01, 0x02];
194        let result = deserialize_proof(&garbage);
195        assert!(result.is_err());
196    }
197
198    #[test]
199    fn test_deserialize_proof_rejects_untagged() {
200        // Raw msgpack without tag byte must be rejected
201        let proof = PaymentProof {
202            proof_of_payment: make_proof_of_payment(),
203            tx_hashes: vec![],
204        };
205        let raw_bytes = rmp_serde::to_vec(&proof).unwrap();
206        let result = deserialize_proof(&raw_bytes);
207        assert!(result.is_err());
208    }
209
210    #[test]
211    fn test_payment_proof_multiple_tx_hashes() {
212        let tx1 = FixedBytes::from([0x11u8; 32]);
213        let tx2 = FixedBytes::from([0x22u8; 32]);
214        let proof = PaymentProof {
215            proof_of_payment: make_proof_of_payment(),
216            tx_hashes: vec![tx1, tx2],
217        };
218
219        let bytes = serialize_single_node_proof(&proof).unwrap();
220        let (_, hashes) = deserialize_proof(&bytes).unwrap();
221
222        assert_eq!(hashes.len(), 2);
223        assert_eq!(hashes.first().unwrap(), &tx1);
224        assert_eq!(hashes.get(1).unwrap(), &tx2);
225    }
226
227    // =========================================================================
228    // detect_proof_type tests
229    // =========================================================================
230
231    #[test]
232    fn test_detect_proof_type_single_node() {
233        let bytes = [PROOF_TAG_SINGLE_NODE, 0x00, 0x01];
234        let result = detect_proof_type(&bytes);
235        assert_eq!(result, Some(ProofType::SingleNode));
236    }
237
238    #[test]
239    fn test_detect_proof_type_merkle() {
240        let bytes = [PROOF_TAG_MERKLE, 0x00, 0x01];
241        let result = detect_proof_type(&bytes);
242        assert_eq!(result, Some(ProofType::Merkle));
243    }
244
245    #[test]
246    fn test_detect_proof_type_unknown_tag() {
247        let bytes = [0xFF, 0x00, 0x01];
248        let result = detect_proof_type(&bytes);
249        assert_eq!(result, None);
250    }
251
252    #[test]
253    fn test_detect_proof_type_empty_bytes() {
254        let bytes: &[u8] = &[];
255        let result = detect_proof_type(bytes);
256        assert_eq!(result, None);
257    }
258
259    // =========================================================================
260    // Tagged serialize/deserialize round-trip tests
261    // =========================================================================
262
263    #[test]
264    fn test_serialize_single_node_proof_roundtrip_with_tag() {
265        let tx_hash = FixedBytes::from([0xCCu8; 32]);
266        let proof = PaymentProof {
267            proof_of_payment: make_proof_of_payment(),
268            tx_hashes: vec![tx_hash],
269        };
270
271        let tagged_bytes = serialize_single_node_proof(&proof).unwrap();
272
273        // First byte must be the single-node tag
274        assert_eq!(
275            tagged_bytes.first().copied(),
276            Some(PROOF_TAG_SINGLE_NODE),
277            "Tagged proof must start with PROOF_TAG_SINGLE_NODE"
278        );
279
280        // detect_proof_type should identify it
281        assert_eq!(
282            detect_proof_type(&tagged_bytes),
283            Some(ProofType::SingleNode)
284        );
285
286        // deserialize_proof handles the tag transparently
287        let (pop, hashes) = deserialize_proof(&tagged_bytes).unwrap();
288        assert_eq!(pop.peer_quotes.len(), 1);
289        assert_eq!(hashes.len(), 1);
290        assert_eq!(hashes.first().unwrap(), &tx_hash);
291    }
292
293    // =========================================================================
294    // Merkle proof serialize/deserialize round-trip tests
295    // =========================================================================
296
297    /// Create a minimal valid `MerklePaymentProof` from a small merkle tree.
298    fn make_test_merkle_proof() -> MerklePaymentProof {
299        let timestamp = std::time::SystemTime::now()
300            .duration_since(std::time::UNIX_EPOCH)
301            .unwrap()
302            .as_secs();
303
304        // Build a tree with 4 addresses (minimal depth)
305        let addresses: Vec<xor_name::XorName> = (0..4u8)
306            .map(|i| xor_name::XorName::from_content(&[i]))
307            .collect();
308        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
309
310        // Build candidate nodes with ML-DSA-65 signing (matching production)
311        let candidate_nodes: [MerklePaymentCandidateNode; CANDIDATES_PER_POOL] =
312            std::array::from_fn(|i| {
313                let ml_dsa = MlDsa65::new();
314                let (pub_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
315                let metrics = QuotingMetrics {
316                    data_size: 1024,
317                    data_type: 0,
318                    close_records_stored: i * 10,
319                    records_per_type: vec![],
320                    max_records: 500,
321                    received_payment_count: 0,
322                    live_time: 100,
323                    network_density: None,
324                    network_size: None,
325                };
326                #[allow(clippy::cast_possible_truncation)]
327                let reward_address = RewardsAddress::new([i as u8; 20]);
328                let msg =
329                    MerklePaymentCandidateNode::bytes_to_sign(&metrics, &reward_address, timestamp);
330                let sk = MlDsaSecretKey::from_bytes(secret_key.as_bytes()).expect("sk");
331                let signature = ml_dsa.sign(&sk, &msg).expect("sign").as_bytes().to_vec();
332
333                MerklePaymentCandidateNode {
334                    pub_key: pub_key.as_bytes().to_vec(),
335                    quoting_metrics: metrics,
336                    reward_address,
337                    merkle_payment_timestamp: timestamp,
338                    signature,
339                }
340            });
341
342        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
343        let midpoint_proof = reward_candidates.first().unwrap().clone();
344
345        let pool = MerklePaymentCandidatePool {
346            midpoint_proof,
347            candidate_nodes,
348        };
349
350        let first_address = *addresses.first().unwrap();
351        let address_proof = tree.generate_address_proof(0, first_address).unwrap();
352
353        MerklePaymentProof::new(first_address, address_proof, pool)
354    }
355
356    #[test]
357    fn test_serialize_merkle_proof_roundtrip() {
358        let merkle_proof = make_test_merkle_proof();
359
360        let tagged_bytes = serialize_merkle_proof(&merkle_proof).unwrap();
361
362        // First byte must be the merkle tag
363        assert_eq!(
364            tagged_bytes.first().copied(),
365            Some(PROOF_TAG_MERKLE),
366            "Tagged merkle proof must start with PROOF_TAG_MERKLE"
367        );
368
369        // detect_proof_type should identify it as merkle
370        assert_eq!(detect_proof_type(&tagged_bytes), Some(ProofType::Merkle));
371
372        // deserialize_merkle_proof should recover the original proof
373        let recovered = deserialize_merkle_proof(&tagged_bytes).unwrap();
374        assert_eq!(recovered.address, merkle_proof.address);
375        assert_eq!(
376            recovered.winner_pool.candidate_nodes.len(),
377            CANDIDATES_PER_POOL
378        );
379    }
380
381    #[test]
382    fn test_deserialize_merkle_proof_rejects_wrong_tag() {
383        let merkle_proof = make_test_merkle_proof();
384        let mut tagged_bytes = serialize_merkle_proof(&merkle_proof).unwrap();
385
386        // Replace the tag with the single-node tag
387        if let Some(first) = tagged_bytes.first_mut() {
388            *first = PROOF_TAG_SINGLE_NODE;
389        }
390
391        let result = deserialize_merkle_proof(&tagged_bytes);
392        assert!(result.is_err(), "Should reject wrong tag byte");
393        let err_msg = result.unwrap_err();
394        assert!(
395            err_msg.contains("Missing merkle proof tag"),
396            "Error should mention missing tag: {err_msg}"
397        );
398    }
399
400    #[test]
401    fn test_deserialize_merkle_proof_rejects_empty() {
402        let result = deserialize_merkle_proof(&[]);
403        assert!(result.is_err());
404    }
405}