Skip to main content

ant_node/payment/
quote.rs

1//! Payment quote generation for ant-node.
2//!
3//! Generates `PaymentQuote` values that clients use to pay for data storage.
4//! Compatible with the Autonomi payment system.
5//!
6//! NOTE: Quote generation requires integration with the node's signing
7//! capabilities from saorsa-core. This module provides the interface
8//! and will be fully integrated when the node is initialized.
9
10use crate::error::{Error, Result};
11use crate::logging::debug;
12use crate::payment::metrics::QuotingMetricsTracker;
13use crate::payment::pricing::calculate_price;
14use evmlib::merkle_payments::MerklePaymentCandidateNode;
15use evmlib::PaymentQuote;
16use evmlib::RewardsAddress;
17use parking_lot::RwLock;
18use saorsa_core::MlDsa65;
19use saorsa_pqc::pqc::types::MlDsaSecretKey;
20use saorsa_pqc::pqc::MlDsaOperations;
21use std::sync::Arc;
22use std::time::SystemTime;
23
24/// Content address type (32-byte `XorName`).
25pub type XorName = [u8; 32];
26
27/// Signing function type that takes bytes and returns a signature.
28pub type SignFn = Box<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;
29
30/// The commitment binding a quote prices against (ADR-0004).
31///
32/// `key_count` is the leaf count of the pinned commitment and the sole input to
33/// the price formula; `pin` is that commitment's hash. A quote carries both,
34/// signed, so any receiver can recompute the price and resolve the pin to the
35/// signed commitment.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct QuoteBinding {
38    /// Number of keys in the pinned commitment (the price driver).
39    pub key_count: u32,
40    /// Hash of the pinned commitment.
41    pub pin: [u8; 32],
42}
43
44/// Source of the live storage commitment a quote prices against (ADR-0004).
45///
46/// Implemented by the responder-side commitment state. Decouples
47/// [`QuoteGenerator`] from replication internals: the generator only needs the
48/// current commitment's `(key_count, pin)` and the guarantee that asking for it
49/// refreshes its answerability ("quoting is advertising"). Returns `None` when
50/// there is no live current commitment (never rotated, or retired), in which
51/// case the node quotes the baseline with no pin.
52pub trait CommitmentSource: Send + Sync {
53    /// Snapshot the current commitment's binding AND refresh its answerability,
54    /// atomically. `None` if there is no live current commitment.
55    fn current_binding_for_quote(&self) -> Option<QuoteBinding>;
56
57    /// ADR-0004: the serialized signed commitment for `pin`, if it is still
58    /// retained, so the quote response can ship it as a sidecar ("the commitment
59    /// arrived with the quote"). Returns the same canonical bytes a peer would
60    /// receive via `GetCommitmentByPin`, so the client's pin match is identical
61    /// across both resolution paths. `None` if the pin is no longer retained
62    /// (in which case the response carries no commitment and the client falls
63    /// back to gossip/fetch). Kept separate from [`Self::current_binding_for_quote`]
64    /// so the ~5 KB blob is only materialised when a response is being built,
65    /// never on the `Copy` pricing path.
66    fn commitment_blob_for_pin(&self, pin: [u8; 32]) -> Option<Vec<u8>>;
67}
68
69/// Quote generator for creating payment quotes.
70///
71/// Uses the node's signing capabilities to sign quotes, which clients
72/// use to pay for storage on the Arbitrum network.
73pub struct QuoteGenerator {
74    /// The rewards address for receiving payments.
75    rewards_address: RewardsAddress,
76    /// In-memory record counter, retained for the `records_stored` /
77    /// `record_store` / `resync_records` accounting surface the storage handler
78    /// drives.
79    ///
80    /// ADR-0004: this is NO LONGER a pricing input. A quote's price is bound to
81    /// the live storage commitment via [`Self::commitment_source`] (or baseline
82    /// when none); the on-disk/side record count no longer sets the price.
83    metrics_tracker: QuotingMetricsTracker,
84    /// ADR-0004 commitment source: the live storage commitment the price is
85    /// bound to. When attached, a quote prices against the committed
86    /// (responsible) key count and pins that commitment, refreshing its
87    /// answerability on issuance. `None` until [`Self::attach_commitment_source`]
88    /// is called — in which case the node falls back to baseline pricing with no
89    /// pin (observe-only / pre-rotation / unit tests).
90    commitment_source: RwLock<Option<Arc<dyn CommitmentSource>>>,
91    /// Signing function provided by the node.
92    /// Takes bytes and returns a signature.
93    sign_fn: Option<SignFn>,
94    /// Public key bytes for the quote.
95    pub_key: Vec<u8>,
96}
97
98impl QuoteGenerator {
99    /// Create a new quote generator without signing capability.
100    ///
101    /// Call `set_signer` to enable quote signing.
102    ///
103    /// # Arguments
104    ///
105    /// * `rewards_address` - The EVM address for receiving payments
106    /// * `metrics_tracker` - Tracker for quoting metrics
107    #[must_use]
108    pub fn new(rewards_address: RewardsAddress, metrics_tracker: QuotingMetricsTracker) -> Self {
109        Self {
110            rewards_address,
111            metrics_tracker,
112            commitment_source: RwLock::new(None),
113            sign_fn: None,
114            pub_key: Vec::new(),
115        }
116    }
117
118    /// Attach the ADR-0004 commitment source so quotes bind their price to the
119    /// node's live storage commitment.
120    ///
121    /// Idempotent: calling twice replaces the handle. Uses interior mutability
122    /// so it can be called on an `Arc` after construction. When attached,
123    /// [`Self::create_quote`] and [`Self::create_merkle_candidate_quote`] price
124    /// against the committed responsible key count, pin the current commitment,
125    /// and refresh its answerability. When absent, both fall back to baseline
126    /// (no-pin) quotes.
127    pub fn attach_commitment_source(&self, source: Arc<dyn CommitmentSource>) {
128        *self.commitment_source.write() = Some(source);
129        debug!("QuoteGenerator: ADR-0004 commitment source attached");
130    }
131
132    /// ADR-0004: the serialized signed commitment for `pin`, so the quote
133    /// response can ship it as a sidecar. `None` when no commitment source is
134    /// attached (baseline / pre-rotation / tests) or the pin is no longer
135    /// retained — in which case the response carries no commitment and the
136    /// client falls back to gossip/fetch. Lock is dropped before the (heavier)
137    /// blob materialisation in the impl.
138    #[must_use]
139    pub fn commitment_blob_for_pin(&self, pin: [u8; 32]) -> Option<Vec<u8>> {
140        let source = self.commitment_source.read().as_ref().map(Arc::clone);
141        source.and_then(|src| src.commitment_blob_for_pin(pin))
142    }
143
144    /// Resolve the ADR-0004 pricing inputs a quote should carry, refreshing the
145    /// pinned commitment's answerability as a side effect.
146    ///
147    /// Returns `(committed_key_count, commitment_pin, price_count)`:
148    /// - with a live commitment, the price is driven by the committed key count
149    ///   and the quote pins that commitment (the ADR-0004 forced price);
150    /// - with no commitment source or no live current commitment, the node
151    ///   emits a true **baseline** quote: `(0, None)` priced at
152    ///   `calculate_price(0)`.
153    ///
154    /// Critically, the no-commitment branch prices at `0`, NOT at the on-disk
155    /// record count. A `(committed_key_count = 0, commitment_pin = None)` quote
156    /// is the canonical baseline shape, and ADR-0004's forced-price rule binds
157    /// that shape to `calculate_price(0)`. Pricing the no-pin quote off the disk
158    /// count would mint a `(0, None, price > baseline)` quote — a shape a
159    /// modified node could forge to charge above baseline while carrying no
160    /// auditable pin. A node that genuinely holds data prices through its
161    /// commitment (the `Some` branch) once it has rotated one; until then it can
162    /// only charge baseline, which is correct: it has nothing it can prove.
163    ///
164    /// Shared by both quote-generation paths so they stay byte-for-byte
165    /// consistent in how they bind price to commitment.
166    fn resolve_quote_pricing(&self) -> (u32, Option<[u8; 32]>, usize) {
167        // Resolve (and drop) the lock guard before branching: the binding is a
168        // plain `Copy` value, so the commitment-source lock is never held.
169        let binding = self
170            .commitment_source
171            .read()
172            .as_ref()
173            .and_then(|src| src.current_binding_for_quote());
174        binding.map_or((0u32, None, 0usize), |binding| {
175            (
176                binding.key_count,
177                Some(binding.pin),
178                usize::try_from(binding.key_count).unwrap_or(usize::MAX),
179            )
180        })
181    }
182
183    /// Set the signing function for quote generation.
184    ///
185    /// # Arguments
186    ///
187    /// * `pub_key` - The node's public key bytes
188    /// * `sign_fn` - Function that signs bytes and returns signature
189    pub fn set_signer<F>(&mut self, pub_key: Vec<u8>, sign_fn: F)
190    where
191        F: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
192    {
193        self.pub_key = pub_key;
194        self.sign_fn = Some(Box::new(sign_fn));
195    }
196
197    /// Check if the generator has signing capability.
198    #[must_use]
199    pub fn can_sign(&self) -> bool {
200        self.sign_fn.is_some()
201    }
202
203    /// Probe the signer with test data to verify it produces a non-empty signature.
204    ///
205    /// # Errors
206    ///
207    /// Returns an error if no signer is set or if signing produces an empty signature.
208    pub fn probe_signer(&self) -> Result<()> {
209        let sign_fn = self
210            .sign_fn
211            .as_ref()
212            .ok_or_else(|| Error::Payment("Signer not set".to_string()))?;
213        let test_msg = b"ant-signing-probe";
214        let test_sig = sign_fn(test_msg);
215        if test_sig.is_empty() {
216            return Err(Error::Payment(
217                "ML-DSA-65 signing probe failed: empty signature produced".to_string(),
218            ));
219        }
220        Ok(())
221    }
222
223    /// Generate a payment quote for storing data.
224    ///
225    /// # Arguments
226    ///
227    /// * `content` - The `XorName` of the content to store
228    /// * `data_size` - Size of the data in bytes
229    /// * `data_type` - Type index of the data (0 for chunks)
230    ///
231    /// # Returns
232    ///
233    /// A signed `PaymentQuote` that the client can use to pay on-chain.
234    ///
235    /// # Errors
236    ///
237    /// Returns an error if signing is not configured.
238    pub fn create_quote(
239        &self,
240        content: XorName,
241        data_size: usize,
242        data_type: u32,
243    ) -> Result<PaymentQuote> {
244        let sign_fn = self
245            .sign_fn
246            .as_ref()
247            .ok_or_else(|| Error::Payment("Quote signing not configured".to_string()))?;
248
249        let timestamp = SystemTime::now();
250
251        // ADR-0004 forced price: when a live commitment exists, the price is a
252        // deterministic function of its committed (responsible) key count, and
253        // the quote pins that commitment (refreshing its answerability). Absent
254        // a commitment source — observe-only, pre-first-rotation, or unit tests
255        // — the node emits the canonical baseline quote `(0, None)` priced at
256        // `calculate_price(0)`, NOT a price off the on-disk count (see
257        // `resolve_quote_pricing`: an unpinned, above-baseline price would be a
258        // forgeable shape).
259        let (committed_key_count, commitment_pin, price_count) = self.resolve_quote_pricing();
260        let price = calculate_price(price_count);
261
262        // Convert XorName to xor_name::XorName
263        let xor_name = xor_name::XorName(content);
264
265        // Create bytes for signing (following autonomi's pattern)
266        let bytes = PaymentQuote::bytes_for_signing(
267            xor_name,
268            timestamp,
269            &price,
270            &self.rewards_address,
271            committed_key_count,
272            &commitment_pin,
273        );
274
275        // Sign the bytes
276        let signature = sign_fn(&bytes);
277        if signature.is_empty() {
278            return Err(Error::Payment(
279                "Signing produced empty signature".to_string(),
280            ));
281        }
282
283        let quote = PaymentQuote {
284            content: xor_name,
285            timestamp,
286            price,
287            rewards_address: self.rewards_address,
288            committed_key_count,
289            commitment_pin,
290            pub_key: self.pub_key.clone(),
291            signature,
292        };
293
294        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
295            let content_hex = hex::encode(content);
296            debug!("Generated quote for {content_hex} (size: {data_size}, type: {data_type})");
297        }
298
299        Ok(quote)
300    }
301
302    /// Get the rewards address.
303    #[must_use]
304    pub fn rewards_address(&self) -> &RewardsAddress {
305        &self.rewards_address
306    }
307
308    /// Get the current number of records stored.
309    #[must_use]
310    pub fn records_stored(&self) -> usize {
311        self.metrics_tracker.records_stored()
312    }
313
314    /// Record data stored (delegates to metrics tracker).
315    pub fn record_store(&self) {
316        self.metrics_tracker.record_store();
317    }
318
319    /// Resync the quoting metric to an authoritative count of held records.
320    ///
321    /// ADR-0004: `records_stored()` is NO LONGER a pricing input — the quote
322    /// price is a function of the node's committed key count (see
323    /// `resolve_quote_pricing`), not this counter. This resync just keeps the
324    /// accounting/telemetry metric honest against what the node ACTUALLY HOLDS
325    /// (from the storage layer), including deletions and pruning, so a monotonic
326    /// store counter can't drift from reality.
327    pub fn resync_records(&self, count: usize) {
328        self.metrics_tracker.set_records(count);
329    }
330
331    /// Create a merkle candidate quote for batch payment using ML-DSA-65.
332    ///
333    /// Returns a `MerklePaymentCandidateNode` constructed with the node's
334    /// ML-DSA-65 public key and signature. This uses the same post-quantum
335    /// signing stack as regular payment quotes, rather than the ed25519
336    /// signing that the upstream `ant-evm` library assumes.
337    ///
338    /// The `pub_key` field stores the raw ML-DSA-65 public key bytes,
339    /// and `signature` stores the ML-DSA-65 signature over `bytes_to_sign()`.
340    /// Clients verify these using `verify_merkle_candidate_signature()`.
341    ///
342    /// # Errors
343    ///
344    /// Returns an error if signing is not configured.
345    pub fn create_merkle_candidate_quote(
346        &self,
347        data_size: usize,
348        data_type: u32,
349        merkle_payment_timestamp: u64,
350    ) -> Result<MerklePaymentCandidateNode> {
351        let sign_fn = self
352            .sign_fn
353            .as_ref()
354            .ok_or_else(|| Error::Payment("Quote signing not configured".to_string()))?;
355
356        // ADR-0004 forced price for the merkle-batch candidate, mirroring the
357        // single-node path: bind to the live commitment when present, else
358        // baseline with no pin.
359        let (committed_key_count, commitment_pin, price_count) = self.resolve_quote_pricing();
360        let price = calculate_price(price_count);
361
362        // ADR-0004: sign the commitment binding into the merkle candidate
363        // payload too (5-field `bytes_to_sign`), so a count/pin mismatch is
364        // genuine same-key-signed evidence. ant-protocol verifies this same
365        // 5-field message.
366        let msg = MerklePaymentCandidateNode::bytes_to_sign(
367            &price,
368            &self.rewards_address,
369            merkle_payment_timestamp,
370            committed_key_count,
371            &commitment_pin,
372        );
373
374        // Sign with ML-DSA-65
375        let signature = sign_fn(&msg);
376        if signature.is_empty() {
377            return Err(Error::Payment(
378                "ML-DSA-65 signing produced empty signature for merkle candidate".to_string(),
379            ));
380        }
381
382        let candidate = MerklePaymentCandidateNode {
383            pub_key: self.pub_key.clone(),
384            price,
385            reward_address: self.rewards_address,
386            merkle_payment_timestamp,
387            committed_key_count,
388            commitment_pin,
389            signature,
390        };
391
392        if crate::logging::enabled!(crate::logging::Level::DEBUG) {
393            debug!(
394                "Generated ML-DSA-65 merkle candidate quote (size: {data_size}, type: {data_type}, ts: {merkle_payment_timestamp})"
395            );
396        }
397
398        Ok(candidate)
399    }
400}
401
402// Wire-side signature verification (`verify_quote_content`,
403// `verify_quote_signature`, `verify_merkle_candidate_signature`) lives
404// in `ant_protocol::payment::verify`. Re-exported from
405// `crate::payment` for backwards compatibility.
406
407/// Wire ML-DSA-65 signing from a node identity into a `QuoteGenerator`.
408///
409/// This is the shared setup used by both production nodes and devnet nodes
410/// to configure quote signing from a `NodeIdentity`.
411///
412/// # Arguments
413///
414/// * `generator` - The quote generator to configure
415/// * `identity` - The node identity providing signing keys
416///
417/// # Errors
418///
419/// Returns an error if the secret key cannot be deserialized or if the
420/// signing probe (a test signature at startup) fails.
421pub fn wire_ml_dsa_signer(
422    generator: &mut QuoteGenerator,
423    identity: &saorsa_core::identity::NodeIdentity,
424) -> Result<()> {
425    let pub_key_bytes = identity.public_key().as_bytes().to_vec();
426    let sk_bytes = identity.secret_key_bytes().to_vec();
427    let sk = MlDsaSecretKey::from_bytes(&sk_bytes)
428        .map_err(|e| Error::Crypto(format!("Failed to deserialize ML-DSA-65 secret key: {e}")))?;
429    let ml_dsa = MlDsa65::new();
430    generator.set_signer(pub_key_bytes, move |msg| match ml_dsa.sign(&sk, msg) {
431        Ok(sig) => sig.as_bytes().to_vec(),
432        Err(e) => {
433            crate::logging::error!("ML-DSA-65 signing failed: {e}");
434            vec![]
435        }
436    });
437    generator.probe_signer()?;
438    Ok(())
439}
440
441#[cfg(test)]
442#[allow(clippy::expect_used)]
443mod tests {
444    use super::*;
445    use crate::payment::metrics::QuotingMetricsTracker;
446    // Verification helpers live in ant-protocol; import them here so the
447    // long-standing node-side negative tests (tampered keys, swapped
448    // pub keys, wrong timestamp, etc.) keep running against the canonical
449    // wire-side implementation.
450    use ant_protocol::payment::verify::{
451        verify_merkle_candidate_signature, verify_quote_content, verify_quote_signature,
452    };
453    use evmlib::common::Amount;
454    use saorsa_pqc::pqc::types::MlDsaSecretKey;
455
456    fn create_test_generator() -> QuoteGenerator {
457        let rewards_address = RewardsAddress::new([1u8; 20]);
458        let metrics_tracker = QuotingMetricsTracker::new(100);
459
460        let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
461
462        // Set up a dummy signer for testing
463        generator.set_signer(vec![0u8; 64], |bytes| {
464            // Dummy signature - just return hash of bytes
465            let mut sig = vec![0u8; 64];
466            for (i, b) in bytes.iter().take(64).enumerate() {
467                sig[i] = *b;
468            }
469            sig
470        });
471
472        generator
473    }
474
475    /// Fixed-binding [`CommitmentSource`] for tests: always reports the same
476    /// `(key_count, pin)` so we can assert the forced-price wiring exactly.
477    struct FixedCommitmentSource {
478        key_count: u32,
479        pin: [u8; 32],
480    }
481    impl CommitmentSource for FixedCommitmentSource {
482        fn current_binding_for_quote(&self) -> Option<QuoteBinding> {
483            Some(QuoteBinding {
484                key_count: self.key_count,
485                pin: self.pin,
486            })
487        }
488
489        fn commitment_blob_for_pin(&self, _pin: [u8; 32]) -> Option<Vec<u8>> {
490            // The fixed source has no real commitment to serialize; the
491            // forced-price tests assert on the binding, not the sidecar.
492            None
493        }
494    }
495
496    /// ADR-0004 forced price (single-node): with a commitment source attached,
497    /// the quote price is exactly `calculate_price(committed_key_count)`, the
498    /// quote carries that count, and it pins the commitment hash. This replaces
499    /// the pre-ADR-0004 "price tracks on-disk count" behaviour — pricing is now
500    /// bound to the signed commitment, not the raw store count.
501    #[test]
502    fn test_forced_price_binds_to_commitment() {
503        let mut generator = QuoteGenerator::new(
504            RewardsAddress::new([1u8; 20]),
505            QuotingMetricsTracker::new(3),
506        );
507        generator.set_signer(vec![0u8; 64], |bytes| {
508            let mut sig = vec![0u8; 64];
509            for (i, b) in bytes.iter().take(64).enumerate() {
510                sig[i] = *b;
511            }
512            sig
513        });
514
515        let pin = [7u8; 32];
516        generator.attach_commitment_source(Arc::new(FixedCommitmentSource { key_count: 25, pin }));
517
518        let quote = generator
519            .create_quote([42u8; 32], 1024, 0)
520            .expect("create quote");
521
522        assert_eq!(
523            quote.price,
524            calculate_price(25),
525            "price must be calculate_price(committed_key_count)"
526        );
527        assert_eq!(
528            quote.committed_key_count, 25,
529            "quote carries committed count"
530        );
531        assert_eq!(quote.commitment_pin, Some(pin), "quote pins the commitment");
532    }
533
534    /// ADR-0004 baseline: with NO commitment source (fresh node, pre first
535    /// rotation), the quote is the canonical baseline shape — `(0, None)` priced
536    /// at `calculate_price(0)` — NOT priced off the on-disk count. A node can
537    /// only charge baseline until it has a commitment it can be audited against.
538    #[test]
539    fn test_no_commitment_source_prices_baseline() {
540        let mut generator = QuoteGenerator::new(
541            RewardsAddress::new([1u8; 20]),
542            QuotingMetricsTracker::new(99),
543        );
544        generator.set_signer(vec![0u8; 64], |bytes| {
545            let mut sig = vec![0u8; 64];
546            for (i, b) in bytes.iter().take(64).enumerate() {
547                sig[i] = *b;
548            }
549            sig
550        });
551
552        let quote = generator
553            .create_quote([42u8; 32], 1024, 0)
554            .expect("create quote");
555
556        assert_eq!(
557            quote.price,
558            calculate_price(0),
559            "no commitment source must price at baseline calculate_price(0)"
560        );
561        assert_eq!(quote.committed_key_count, 0);
562        assert_eq!(quote.commitment_pin, None);
563    }
564
565    #[test]
566    fn test_create_quote() {
567        let generator = create_test_generator();
568        let content = [42u8; 32];
569
570        let quote = generator.create_quote(content, 1024, 0);
571        assert!(quote.is_ok());
572
573        let quote = quote.expect("valid quote");
574        assert_eq!(quote.content.0, content);
575    }
576
577    #[test]
578    fn test_verify_quote_content() {
579        let generator = create_test_generator();
580        let content = [42u8; 32];
581
582        let quote = generator
583            .create_quote(content, 1024, 0)
584            .expect("valid quote");
585        assert!(verify_quote_content(&quote, &content));
586
587        // Wrong content should fail
588        let wrong_content = [99u8; 32];
589        assert!(!verify_quote_content(&quote, &wrong_content));
590    }
591
592    #[test]
593    fn test_generator_without_signer() {
594        let rewards_address = RewardsAddress::new([1u8; 20]);
595        let metrics_tracker = QuotingMetricsTracker::new(100);
596        let generator = QuoteGenerator::new(rewards_address, metrics_tracker);
597
598        assert!(!generator.can_sign());
599
600        let content = [42u8; 32];
601        let result = generator.create_quote(content, 1024, 0);
602        assert!(result.is_err());
603    }
604
605    #[test]
606    fn test_quote_signature_round_trip_real_keys() {
607        let ml_dsa = MlDsa65::new();
608        let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keypair generation");
609
610        let rewards_address = RewardsAddress::new([2u8; 20]);
611        let metrics_tracker = QuotingMetricsTracker::new(100);
612        let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
613
614        let pub_key_bytes = public_key.as_bytes().to_vec();
615        let sk_bytes = secret_key.as_bytes().to_vec();
616        generator.set_signer(pub_key_bytes, move |msg| {
617            let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("secret key parse");
618            let ml_dsa = MlDsa65::new();
619            ml_dsa.sign(&sk, msg).expect("signing").as_bytes().to_vec()
620        });
621
622        let content = [7u8; 32];
623        let quote = generator
624            .create_quote(content, 2048, 0)
625            .expect("create quote");
626
627        // Valid signature should verify
628        assert!(verify_quote_signature(&quote));
629
630        // Tamper with the signature — flip a byte
631        let mut tampered_quote = quote;
632        if let Some(byte) = tampered_quote.signature.first_mut() {
633            *byte ^= 0xFF;
634        }
635        assert!(!verify_quote_signature(&tampered_quote));
636    }
637
638    #[test]
639    fn test_empty_signature_fails_verification() {
640        let generator = create_test_generator();
641        let content = [42u8; 32];
642
643        let quote = generator
644            .create_quote(content, 1024, 0)
645            .expect("create quote");
646
647        // The dummy signer produces a 64-byte fake signature, not a valid
648        // ML-DSA-65 signature (3309 bytes), so verification must fail.
649        assert!(!verify_quote_signature(&quote));
650    }
651
652    #[test]
653    fn test_rewards_address_getter() {
654        let addr = RewardsAddress::new([42u8; 20]);
655        let metrics_tracker = QuotingMetricsTracker::new(0);
656        let generator = QuoteGenerator::new(addr, metrics_tracker);
657
658        assert_eq!(*generator.rewards_address(), addr);
659    }
660
661    #[test]
662    fn test_records_stored() {
663        let rewards_address = RewardsAddress::new([1u8; 20]);
664        let metrics_tracker = QuotingMetricsTracker::new(50);
665        let generator = QuoteGenerator::new(rewards_address, metrics_tracker);
666
667        assert_eq!(generator.records_stored(), 50);
668    }
669
670    #[test]
671    fn test_record_store_delegation() {
672        let rewards_address = RewardsAddress::new([1u8; 20]);
673        let metrics_tracker = QuotingMetricsTracker::new(0);
674        let generator = QuoteGenerator::new(rewards_address, metrics_tracker);
675
676        generator.record_store();
677        generator.record_store();
678        generator.record_store();
679
680        assert_eq!(generator.records_stored(), 3);
681    }
682
683    #[test]
684    fn test_create_quote_different_data_types() {
685        let generator = create_test_generator();
686        let content = [10u8; 32];
687
688        // All data types produce the same price (price depends on records_stored, not data_type)
689        let q0 = generator.create_quote(content, 1024, 0).expect("type 0");
690        let q1 = generator.create_quote(content, 512, 1).expect("type 1");
691        let q2 = generator.create_quote(content, 256, 2).expect("type 2");
692
693        // All quotes should have a valid price (minimum floor of 1)
694        assert!(q0.price >= Amount::from(1u64));
695        assert!(q1.price >= Amount::from(1u64));
696        assert!(q2.price >= Amount::from(1u64));
697    }
698
699    #[test]
700    fn test_create_quote_zero_size() {
701        let generator = create_test_generator();
702        let content = [11u8; 32];
703
704        // Price depends on records_stored, not data size
705        let quote = generator.create_quote(content, 0, 0).expect("zero size");
706        assert!(quote.price >= Amount::from(1u64));
707    }
708
709    #[test]
710    fn test_create_quote_large_size() {
711        let generator = create_test_generator();
712        let content = [12u8; 32];
713
714        // Price depends on records_stored, not data size
715        let quote = generator
716            .create_quote(content, 10_000_000, 0)
717            .expect("large size");
718        assert!(quote.price >= Amount::from(1u64));
719    }
720
721    #[test]
722    fn test_verify_quote_signature_empty_pub_key() {
723        let quote = PaymentQuote {
724            content: xor_name::XorName([0u8; 32]),
725            timestamp: SystemTime::now(),
726            price: Amount::from(1u64),
727            rewards_address: RewardsAddress::new([0u8; 20]),
728            committed_key_count: 0,
729            commitment_pin: None,
730            pub_key: vec![],
731            signature: vec![],
732        };
733
734        // Empty pub key should fail parsing
735        assert!(!verify_quote_signature(&quote));
736    }
737
738    #[test]
739    fn test_can_sign_after_set_signer() {
740        let rewards_address = RewardsAddress::new([1u8; 20]);
741        let metrics_tracker = QuotingMetricsTracker::new(0);
742        let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
743
744        assert!(!generator.can_sign());
745
746        generator.set_signer(vec![0u8; 32], |_| vec![0u8; 32]);
747
748        assert!(generator.can_sign());
749    }
750
751    #[test]
752    fn test_wire_ml_dsa_signer_returns_ok_with_valid_identity() {
753        let identity = saorsa_core::identity::NodeIdentity::generate().expect("keypair generation");
754        let rewards_address = RewardsAddress::new([3u8; 20]);
755        let metrics_tracker = QuotingMetricsTracker::new(0);
756        let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
757
758        let result = wire_ml_dsa_signer(&mut generator, &identity);
759        assert!(
760            result.is_ok(),
761            "wire_ml_dsa_signer should succeed: {result:?}"
762        );
763        assert!(generator.can_sign());
764    }
765
766    #[test]
767    fn test_probe_signer_fails_without_signer() {
768        let rewards_address = RewardsAddress::new([1u8; 20]);
769        let metrics_tracker = QuotingMetricsTracker::new(0);
770        let generator = QuoteGenerator::new(rewards_address, metrics_tracker);
771
772        let result = generator.probe_signer();
773        assert!(result.is_err());
774    }
775
776    #[test]
777    fn test_probe_signer_fails_with_empty_signature() {
778        let rewards_address = RewardsAddress::new([1u8; 20]);
779        let metrics_tracker = QuotingMetricsTracker::new(0);
780        let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
781
782        generator.set_signer(vec![0u8; 32], |_| vec![]);
783
784        let result = generator.probe_signer();
785        assert!(result.is_err());
786    }
787
788    #[test]
789    fn test_create_merkle_candidate_quote_with_ml_dsa() {
790        let ml_dsa = MlDsa65::new();
791        let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keypair generation");
792
793        let rewards_address = RewardsAddress::new([0x42u8; 20]);
794        let metrics_tracker = QuotingMetricsTracker::new(50);
795        let mut generator = QuoteGenerator::new(rewards_address, metrics_tracker);
796
797        // Wire ML-DSA-65 signing (same as production nodes)
798        let pub_key_bytes = public_key.as_bytes().to_vec();
799        let sk_bytes = secret_key.as_bytes().to_vec();
800        generator.set_signer(pub_key_bytes.clone(), move |msg| {
801            let sk = MlDsaSecretKey::from_bytes(&sk_bytes).expect("sk parse");
802            let ml_dsa = MlDsa65::new();
803            ml_dsa.sign(&sk, msg).expect("sign").as_bytes().to_vec()
804        });
805
806        let timestamp = std::time::SystemTime::now()
807            .duration_since(std::time::UNIX_EPOCH)
808            .expect("system time")
809            .as_secs();
810
811        let result = generator.create_merkle_candidate_quote(2048, 0, timestamp);
812
813        assert!(
814            result.is_ok(),
815            "create_merkle_candidate_quote should succeed: {result:?}"
816        );
817
818        let candidate = result.expect("valid candidate");
819
820        // Verify the returned node has the correct reward address
821        assert_eq!(candidate.reward_address, rewards_address);
822
823        // Verify the timestamp was set correctly
824        assert_eq!(candidate.merkle_payment_timestamp, timestamp);
825
826        // ADR-0004: with no commitment source attached, the merkle candidate is
827        // a baseline quote — price `calculate_price(0)`, count 0, no pin —
828        // regardless of the side counter. Pricing is bound to the commitment,
829        // not the metrics tracker.
830        assert_eq!(candidate.price, calculate_price(0));
831        assert_eq!(candidate.committed_key_count, 0);
832        assert_eq!(candidate.commitment_pin, None);
833
834        // Verify the public key is the ML-DSA-65 public key (not ed25519)
835        assert_eq!(
836            candidate.pub_key, pub_key_bytes,
837            "Public key should be raw ML-DSA-65 bytes"
838        );
839
840        // Verify ML-DSA-65 signature is valid using our verifier
841        assert!(
842            verify_merkle_candidate_signature(&candidate),
843            "ML-DSA-65 merkle candidate signature must be valid"
844        );
845
846        // Verify tampered timestamp invalidates ML-DSA signature
847        let mut tampered = candidate;
848        tampered.merkle_payment_timestamp = timestamp + 1;
849        assert!(
850            !verify_merkle_candidate_signature(&tampered),
851            "Tampered timestamp should invalidate the ML-DSA-65 signature"
852        );
853    }
854
855    // =========================================================================
856    // verify_merkle_candidate_signature — direct tests
857    // =========================================================================
858
859    /// Helper: create a validly-signed `MerklePaymentCandidateNode`.
860    fn make_valid_merkle_candidate() -> MerklePaymentCandidateNode {
861        let ml_dsa = MlDsa65::new();
862        let (public_key, secret_key) = ml_dsa.generate_keypair().expect("keygen");
863
864        let rewards_address = RewardsAddress::new([0xABu8; 20]);
865        let timestamp = std::time::SystemTime::now()
866            .duration_since(std::time::UNIX_EPOCH)
867            .expect("system time")
868            .as_secs();
869        let price = Amount::from(42u64);
870
871        let msg = MerklePaymentCandidateNode::bytes_to_sign(
872            &price,
873            &rewards_address,
874            timestamp,
875            0,
876            &None,
877        );
878        let sk = MlDsaSecretKey::from_bytes(secret_key.as_bytes()).expect("sk");
879        let signature = ml_dsa.sign(&sk, &msg).expect("sign").as_bytes().to_vec();
880
881        MerklePaymentCandidateNode {
882            pub_key: public_key.as_bytes().to_vec(),
883            price,
884            reward_address: rewards_address,
885            merkle_payment_timestamp: timestamp,
886            committed_key_count: 0,
887            commitment_pin: None,
888            signature,
889        }
890    }
891
892    #[test]
893    fn test_verify_merkle_candidate_valid_signature() {
894        let candidate = make_valid_merkle_candidate();
895        assert!(
896            verify_merkle_candidate_signature(&candidate),
897            "Freshly signed merkle candidate must verify"
898        );
899    }
900
901    #[test]
902    fn test_verify_merkle_candidate_tampered_pub_key() {
903        let mut candidate = make_valid_merkle_candidate();
904        // Flip a byte in the public key
905        if let Some(byte) = candidate.pub_key.first_mut() {
906            *byte ^= 0xFF;
907        }
908        assert!(
909            !verify_merkle_candidate_signature(&candidate),
910            "Tampered pub_key must invalidate the signature"
911        );
912    }
913
914    #[test]
915    fn test_verify_merkle_candidate_tampered_reward_address() {
916        let mut candidate = make_valid_merkle_candidate();
917        candidate.reward_address = RewardsAddress::new([0xFFu8; 20]);
918        assert!(
919            !verify_merkle_candidate_signature(&candidate),
920            "Tampered reward_address must invalidate the signature"
921        );
922    }
923
924    #[test]
925    fn test_verify_merkle_candidate_tampered_price() {
926        let mut candidate = make_valid_merkle_candidate();
927        candidate.price = Amount::from(999_999u64);
928        assert!(
929            !verify_merkle_candidate_signature(&candidate),
930            "Tampered price must invalidate the signature"
931        );
932    }
933
934    #[test]
935    fn test_verify_merkle_candidate_tampered_signature_byte() {
936        let mut candidate = make_valid_merkle_candidate();
937        if let Some(byte) = candidate.signature.first_mut() {
938            *byte ^= 0xFF;
939        }
940        assert!(
941            !verify_merkle_candidate_signature(&candidate),
942            "Tampered signature byte must fail verification"
943        );
944    }
945
946    #[test]
947    fn test_verify_merkle_candidate_empty_pub_key() {
948        let mut candidate = make_valid_merkle_candidate();
949        candidate.pub_key = vec![];
950        assert!(
951            !verify_merkle_candidate_signature(&candidate),
952            "Empty pub_key must fail verification"
953        );
954    }
955
956    #[test]
957    fn test_verify_merkle_candidate_empty_signature() {
958        let mut candidate = make_valid_merkle_candidate();
959        candidate.signature = vec![];
960        assert!(
961            !verify_merkle_candidate_signature(&candidate),
962            "Empty signature must fail verification"
963        );
964    }
965
966    #[test]
967    fn test_verify_merkle_candidate_wrong_length_signature() {
968        let mut candidate = make_valid_merkle_candidate();
969        // ML-DSA-65 signatures are 3309 bytes; use a truncated one
970        candidate.signature = vec![0xAA; 100];
971        assert!(
972            !verify_merkle_candidate_signature(&candidate),
973            "Wrong-length signature must fail verification"
974        );
975    }
976
977    #[test]
978    fn test_verify_merkle_candidate_wrong_length_pub_key() {
979        let mut candidate = make_valid_merkle_candidate();
980        // ML-DSA-65 pub keys are 1952 bytes; use a truncated one
981        candidate.pub_key = vec![0xBB; 100];
982        assert!(
983            !verify_merkle_candidate_signature(&candidate),
984            "Wrong-length pub_key must fail verification"
985        );
986    }
987
988    #[test]
989    fn test_verify_merkle_candidate_cross_key_rejection() {
990        // Sign with one key pair, then swap in a different valid public key
991        let candidate = make_valid_merkle_candidate();
992        let ml_dsa = MlDsa65::new();
993        let (other_pk, _) = ml_dsa.generate_keypair().expect("keygen");
994
995        let mut swapped = candidate;
996        swapped.pub_key = other_pk.as_bytes().to_vec();
997        assert!(
998            !verify_merkle_candidate_signature(&swapped),
999            "Signature from key A must not verify under key B"
1000        );
1001    }
1002}