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