Skip to main content

ant_node/replication/
commitment.rs

1//! Storage-bound audit via piggybacked commitments.
2//!
3//! Implements the v12 storage-bound audit design: it closes the
4//! storage-binding holes where a node could pass audits while holding chunk
5//! addresses (not bytes), or answer against a commitment it never gossiped.
6//!
7//! ## What this module provides
8//!
9//! - [`StorageCommitment`] — the wire type sent on neighbour-sync gossip
10//!   and embedded in commitment-bound audit responses. `ML-DSA-65` signed
11//!   over `(root, key_count, sender_peer_id)` with explicit domain separation.
12//! - [`MerkleTree`] — an in-memory Merkle tree over `(key, BLAKE3(bytes))`
13//!   leaves. Rebuilt by the responder when its key set changes; produces
14//!   inclusion paths used in audit responses.
15//! - [`commitment_hash`] — the auditor's pin: a `BLAKE3` digest over the
16//!   full signed commitment blob. Audit challenges carry this; audit
17//!   responses must include a commitment that hashes to the same value.
18//! - [`verify_path`] — auditor's per-key check: rebuilds the leaf from
19//!   `(key, bytes_hash)` and verifies the inclusion path against the
20//!   committed root.
21//!
22//! Nothing else (responder gossip loop, auditor verify path,
23//! reward-eligibility cache) lives here yet — that's the next phase.
24
25use blake3::Hasher;
26use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaSecretKey};
27
28use crate::ant_protocol::XorName;
29
30// ADR-0004: the commitment wire type, its pin (`commitment_hash`), its
31// signature verification, and the key-count cap are the SINGLE SOURCE OF TRUTH
32// in `ant-protocol` so the paying client and the node verify identically.
33// Re-exported here so all existing `crate::replication::commitment::…` callers
34// keep resolving. The Merkle tree, inclusion paths, and signing stay node-side
35// below (the client never builds or signs a commitment, only verifies one).
36pub use ::ant_protocol::payment::commitment::{
37    commitment_hash, verify_commitment_signature, StorageCommitment, DOMAIN_COMMITMENT,
38    DOMAIN_COMMITMENT_HASH, MAX_COMMITMENT_KEY_COUNT, MAX_COMMITMENT_SIDECAR_BYTES,
39};
40
41/// Domain-separation tag for Merkle leaves: `BLAKE3(this || key || H(bytes))`.
42pub const DOMAIN_LEAF: &[u8] = b"autonomi.ant.replication.storage_leaf.v1";
43
44/// Domain-separation tag for Merkle internal nodes: `BLAKE3(this || left || right)`.
45pub const DOMAIN_NODE: &[u8] = b"autonomi.ant.replication.storage_node.v1";
46
47// `MAX_COMMITMENT_KEY_COUNT` and `StorageCommitment` are re-exported from
48// `ant-protocol` above (single source of truth); their fields and wire size are
49// documented there.
50
51// ---------------------------------------------------------------------------
52// Hashing helpers
53// ---------------------------------------------------------------------------
54
55/// Compute the Merkle leaf hash for `(key, bytes_hash)`.
56///
57/// `bytes_hash` is BLAKE3 over the record bytes; the leaf binds the key to
58/// the content so an adversary cannot reuse a leaf for a different chunk.
59#[must_use]
60pub fn leaf_hash(key: &XorName, bytes_hash: &[u8; 32]) -> [u8; 32] {
61    let mut h = Hasher::new();
62    h.update(DOMAIN_LEAF);
63    h.update(key);
64    h.update(bytes_hash);
65    *h.finalize().as_bytes()
66}
67
68/// Combine two child hashes into a Merkle internal-node hash.
69#[must_use]
70pub fn node_hash(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
71    let mut h = Hasher::new();
72    h.update(DOMAIN_NODE);
73    h.update(left);
74    h.update(right);
75    *h.finalize().as_bytes()
76}
77
78// `commitment_hash` is re-exported from `ant-protocol` above (single source of
79// truth for the pin), so the paying client and the node compute the same pin.
80
81/// Canonical bytes the ML-DSA signature covers: the commitment fields
82/// minus the signature itself.
83///
84/// `sender_public_key` is included so an adversary cannot keep the body
85/// and re-sign under a different key (the audit-time verifier would
86/// otherwise accept the swap because verification uses the embedded key).
87fn commitment_signed_payload(
88    root: &[u8; 32],
89    key_count: u32,
90    sender_peer_id: &[u8; 32],
91    sender_public_key: &[u8],
92) -> Vec<u8> {
93    let mut v = Vec::with_capacity(32 + 4 + 32 + 4 + sender_public_key.len());
94    v.extend_from_slice(root);
95    v.extend_from_slice(&key_count.to_le_bytes());
96    v.extend_from_slice(sender_peer_id);
97    // Length-prefix the pubkey so two different (key, suffix) splits cannot
98    // produce the same byte stream (canonical encoding).
99    let pk_len = u32::try_from(sender_public_key.len()).unwrap_or(u32::MAX);
100    v.extend_from_slice(&pk_len.to_le_bytes());
101    v.extend_from_slice(sender_public_key);
102    v
103}
104
105// ---------------------------------------------------------------------------
106// Merkle tree
107// ---------------------------------------------------------------------------
108
109/// In-memory Merkle tree over the responder's claimed keys.
110///
111/// Leaves are `BLAKE3(DOMAIN_LEAF || key || BLAKE3(bytes))`, sorted by
112/// `key`. Internal nodes are `BLAKE3(DOMAIN_NODE || left || right)`. When
113/// a level has an odd number of nodes, the last node is paired with
114/// **itself** — i.e. `node_hash(x, x)` — so the level above has
115/// `ceil(n/2)` nodes. This is a standard self-pair construction (NOT
116/// node promotion) and deterministically maps any non-empty key set to
117/// a single root.
118///
119/// Rebuilt by the responder whenever its key set changes meaningfully
120/// (debounced in the integration layer; not this module's concern).
121pub struct MerkleTree {
122    /// Sorted leaves, indexed by their position in the sorted key set.
123    ///
124    /// `leaves[i] = (key_i, leaf_hash(key_i, bytes_hash_i))`.
125    leaves: Vec<(XorName, [u8; 32])>,
126    /// Tree levels, level 0 is the leaves and the last level is the root.
127    ///
128    /// `levels[0].len() == leaves.len()`; `levels[L].len() == 1` where L
129    /// is the root level.
130    levels: Vec<Vec<[u8; 32]>>,
131}
132
133impl MerkleTree {
134    /// Build a Merkle tree over `(key, bytes_hash)` pairs.
135    ///
136    /// `entries` does not need to be sorted; this method sorts internally
137    /// so the produced root is deterministic per key set. Duplicate keys
138    /// are an error: the responder must deduplicate before calling.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error if `entries` is empty (no commitment to make), if
143    /// `entries.len() > MAX_COMMITMENT_KEY_COUNT`, or if it contains
144    /// duplicate keys.
145    pub fn build(mut entries: Vec<(XorName, [u8; 32])>) -> Result<Self, CommitmentError> {
146        if entries.is_empty() {
147            return Err(CommitmentError::EmptyKeySet);
148        }
149        if entries.len() > MAX_COMMITMENT_KEY_COUNT as usize {
150            return Err(CommitmentError::TooManyKeys(entries.len()));
151        }
152
153        entries.sort_by_key(|a| a.0);
154        for w in entries.windows(2) {
155            if let [a, b] = w {
156                if a.0 == b.0 {
157                    return Err(CommitmentError::DuplicateKey(a.0));
158                }
159            }
160        }
161
162        let leaves: Vec<(XorName, [u8; 32])> = entries
163            .into_iter()
164            .map(|(k, bh)| {
165                let lh = leaf_hash(&k, &bh);
166                (k, lh)
167            })
168            .collect();
169
170        let mut level: Vec<[u8; 32]> = leaves.iter().map(|(_, h)| *h).collect();
171        let mut levels = vec![level.clone()];
172        while level.len() > 1 {
173            level = build_next_level(&level);
174            levels.push(level.clone());
175        }
176
177        Ok(Self { leaves, levels })
178    }
179
180    /// The Merkle root of this tree.
181    ///
182    /// `unwrap`-free: `build` guarantees at least one level with at least
183    /// one entry, so `last().first()` is always `Some`.
184    #[must_use]
185    pub fn root(&self) -> [u8; 32] {
186        // SAFETY: build() enforces non-empty entries → non-empty leaves →
187        // non-empty levels → last level has exactly one hash.
188        self.levels
189            .last()
190            .and_then(|l| l.first())
191            .copied()
192            .unwrap_or([0u8; 32])
193    }
194
195    /// The number of leaves (== claimed keys).
196    #[must_use]
197    pub fn key_count(&self) -> u32 {
198        // Cast is safe because build() rejects > MAX_COMMITMENT_KEY_COUNT.
199        u32::try_from(self.leaves.len()).unwrap_or(u32::MAX)
200    }
201
202    /// The committed leaf keys, in the tree's sorted order. Lets a persisted
203    /// commitment be rebuilt from its key set alone — `MerkleTree::build(keys
204    /// .map(|k| (k, k)))` for content-addressed leaves — without re-reading
205    /// chunks, so a restart can restore the exact signed root (ADR-0004 A1).
206    #[must_use]
207    pub fn leaf_keys(&self) -> Vec<XorName> {
208        self.leaves.iter().map(|(k, _)| *k).collect()
209    }
210
211    /// Inclusion path for `key` from its leaf up to (but not including)
212    /// the root.
213    ///
214    /// Returns `None` if `key` is not in this tree.
215    #[must_use]
216    pub fn path_for(&self, key: &XorName) -> Option<Vec<[u8; 32]>> {
217        let idx = self.leaves.binary_search_by(|(k, _)| k.cmp(key)).ok()?;
218
219        let mut path = Vec::with_capacity(self.levels.len());
220        let mut i = idx;
221        for level in &self.levels[..self.levels.len().saturating_sub(1)] {
222            // Sibling is the *other* half of the pair containing `i`. If
223            // `i` is the unpaired last node at this level, its sibling is
224            // itself (matches the self-pair construction in
225            // `build_next_level`).
226            let sibling_idx = if i % 2 == 0 {
227                if i + 1 < level.len() {
228                    i + 1
229                } else {
230                    i
231                }
232            } else {
233                i - 1
234            };
235            path.push(level[sibling_idx]);
236            i /= 2;
237        }
238        Some(path)
239    }
240
241    /// Iterate over `(key, leaf_hash)` pairs in sorted order. Test-only.
242    #[cfg(test)]
243    pub(crate) fn iter_leaves(&self) -> impl Iterator<Item = &(XorName, [u8; 32])> {
244        self.leaves.iter()
245    }
246
247    /// The keys this tree commits to, in sorted order.
248    ///
249    /// `sorted_keys()[i]` is the key at leaf index `i`. Used by the
250    /// responder's audit-answer path to recover the `leaf_index` field
251    /// for a challenged key in `O(log n)` via binary search.
252    #[must_use]
253    pub fn sorted_keys(&self) -> Vec<XorName> {
254        self.leaves.iter().map(|(k, _)| *k).collect()
255    }
256
257    /// The key at sorted leaf index `idx`, if in range.
258    ///
259    /// Used by the subtree-proof builder to enumerate the keys of a
260    /// contiguous leaf range without cloning the whole key list.
261    #[must_use]
262    pub fn key_at(&self, idx: usize) -> Option<XorName> {
263        self.leaves.get(idx).map(|(k, _)| *k)
264    }
265
266    /// The sorted leaf index of `key`, if committed. `O(log n)` binary search
267    /// over the (key-sorted) leaves — no separate key list needed, so callers
268    /// don't have to keep a duplicate `sorted_keys` Vec alongside the tree.
269    #[must_use]
270    pub fn key_index(&self, key: &XorName) -> Option<usize> {
271        self.leaves.binary_search_by(|(k, _)| k.cmp(key)).ok()
272    }
273
274    /// Whether `key` is committed. Allocation-free membership check via the same
275    /// binary search as [`Self::key_index`].
276    #[must_use]
277    pub fn contains_key(&self, key: &XorName) -> bool {
278        self.key_index(key).is_some()
279    }
280
281    /// The node hash at `(level, index)`, where `level` counts up from the
282    /// leaves (`level == 0` is the leaf level, the last level is the root).
283    ///
284    /// Returns `None` if out of range. Used by the subtree-proof builder to
285    /// read sibling cut-hashes along the path from the root to the selected
286    /// subtree; honours the same left-packed self-pair construction as the
287    /// rest of the tree (a caller asking for an out-of-range sibling on an
288    /// odd-length level should substitute the node itself).
289    #[must_use]
290    pub fn node_at(&self, level: usize, index: u64) -> Option<[u8; 32]> {
291        let index = usize::try_from(index).ok()?;
292        self.levels.get(level).and_then(|l| l.get(index)).copied()
293    }
294
295    /// The number of levels in the tree (`1` for a single-leaf tree; the
296    /// last index is the root level). `depth == levels_count() - 1`.
297    #[must_use]
298    pub fn levels_count(&self) -> usize {
299        self.levels.len()
300    }
301}
302
303/// Build the next level up from `cur`. Odd-length levels pair the last
304/// node with itself (`node_hash(x, x)`) so the level above has
305/// `ceil(n/2)` nodes. Keeps the tree balanced without needing a dummy
306/// leaf domain.
307///
308/// `pub(crate)` so the subtree-proof verifier folds a contiguous leaf block to
309/// its subtree root with the EXACT same self-pair rule (§10 — previously
310/// duplicated as `fold_levels`'s inner loop), guaranteeing the rebuilt node
311/// matches the committed tree bit-for-bit.
312pub(crate) fn build_next_level(cur: &[[u8; 32]]) -> Vec<[u8; 32]> {
313    let mut next = Vec::with_capacity(cur.len().div_ceil(2));
314    let mut i = 0;
315    while i < cur.len() {
316        let left = &cur[i];
317        let right = if i + 1 < cur.len() { &cur[i + 1] } else { left };
318        next.push(node_hash(left, right));
319        i += 2;
320    }
321    next
322}
323
324/// Verify an inclusion path against a commitment of size `key_count`.
325///
326/// `leaf_index` is the responder's position of this leaf in the sorted
327/// leaf set; the commitment's `key_count` comes from
328/// `StorageCommitment.key_count`.
329/// At each level of the path, if the current index is even, the current
330/// hash is the left child and we compute `node_hash(self, sibling)`;
331/// otherwise it is the right child and we compute `node_hash(sibling, self)`.
332///
333/// Returns `true` iff:
334///   - `leaf_index < key_count` (rejects out-of-range claims), AND
335///   - `path.len() == ceil(log2(key_count))` for `key_count > 1`, or
336///     `path.is_empty()` for `key_count == 1` (rejects wrong-shape paths
337///     before doing any hashing), AND
338///   - the recomputed root equals `expected_root`.
339#[must_use]
340pub fn verify_path(
341    leaf: &[u8; 32],
342    path: &[[u8; 32]],
343    leaf_index: usize,
344    key_count: u32,
345    expected_root: &[u8; 32],
346) -> bool {
347    if key_count == 0
348        || key_count > MAX_COMMITMENT_KEY_COUNT
349        || (leaf_index as u64) >= u64::from(key_count)
350    {
351        return false;
352    }
353    // Tree depth = ceil(log2(key_count)). For a power-of-two `n`,
354    // `n.next_power_of_two() == n` so trailing_zeros == log2(n). For non
355    // powers-of-two, next_power_of_two rounds up so trailing_zeros gives
356    // ceil(log2). Special case: key_count == 1 → next_power_of_two == 1
357    // → trailing_zeros == 0 → empty path, which matches the single-leaf
358    // tree's root == leaf invariant.
359    //
360    // `checked_next_power_of_two` returns None on overflow; combined with
361    // the MAX_COMMITMENT_KEY_COUNT cap above it cannot fail in practice,
362    // but the explicit check is profile-independent (release vs debug
363    // would otherwise differ on overflow per Rust's primitive docs).
364    let Some(rounded) = key_count.checked_next_power_of_two() else {
365        return false;
366    };
367    let expected_path_len = rounded.trailing_zeros() as usize;
368    if path.len() != expected_path_len {
369        return false;
370    }
371
372    let mut cur = *leaf;
373    let mut i = leaf_index;
374    for sibling in path {
375        cur = if i % 2 == 0 {
376            node_hash(&cur, sibling)
377        } else {
378            node_hash(sibling, &cur)
379        };
380        i /= 2;
381    }
382    cur == *expected_root
383}
384
385// ---------------------------------------------------------------------------
386// Sign + verify
387// ---------------------------------------------------------------------------
388
389/// Sign a commitment's `(root, key_count, sender_peer_id, sender_public_key)`
390/// with `secret_key`.
391///
392/// The signature is over the canonical signed payload (see
393/// `commitment_signed_payload`) under [`DOMAIN_COMMITMENT`].
394///
395/// # Errors
396///
397/// Returns an error if the underlying ML-DSA-65 signer fails.
398pub fn sign_commitment(
399    secret_key: &MlDsaSecretKey,
400    root: &[u8; 32],
401    key_count: u32,
402    sender_peer_id: &[u8; 32],
403    sender_public_key: &[u8],
404) -> Result<Vec<u8>, CommitmentError> {
405    let payload = commitment_signed_payload(root, key_count, sender_peer_id, sender_public_key);
406    let dsa = ml_dsa_65();
407    let sig = dsa
408        .sign_with_context(secret_key, &payload, DOMAIN_COMMITMENT)
409        .map_err(|e| CommitmentError::SignatureFailed(e.to_string()))?;
410    Ok(sig.to_bytes())
411}
412
413// `verify_commitment_signature` (embedded-key) is re-exported from
414// `ant-protocol` above (single source of truth), so the paying client and the
415// node accept exactly the same commitments. The externally-keyed variant was
416// removed in the ADR-0004 move — it had no remaining callers once the embedded-
417// key verify moved to `ant-protocol`.
418
419// ---------------------------------------------------------------------------
420// Errors
421// ---------------------------------------------------------------------------
422
423/// Errors from commitment construction or verification.
424#[derive(Debug, Clone, thiserror::Error)]
425pub enum CommitmentError {
426    /// `MerkleTree::build` was called with an empty key set.
427    #[error("cannot build commitment over empty key set")]
428    EmptyKeySet,
429    /// Key set exceeds [`MAX_COMMITMENT_KEY_COUNT`].
430    #[error("commitment key count {0} exceeds MAX_COMMITMENT_KEY_COUNT")]
431    TooManyKeys(usize),
432    /// `MerkleTree::build` received the same key twice.
433    #[error("duplicate key in commitment: {}", hex::encode(.0))]
434    DuplicateKey(XorName),
435    /// Underlying ML-DSA-65 signer failed.
436    #[error("commitment signing failed: {0}")]
437    SignatureFailed(String),
438}
439
440// ---------------------------------------------------------------------------
441// Tests
442// ---------------------------------------------------------------------------
443
444#[cfg(test)]
445#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
446mod tests {
447    use super::*;
448    use saorsa_pqc::api::sig::MlDsaPublicKey;
449
450    fn xn(byte: u8) -> XorName {
451        [byte; 32]
452    }
453
454    fn bh(byte: u8) -> [u8; 32] {
455        [byte ^ 0x5A; 32]
456    }
457
458    #[test]
459    fn empty_key_set_rejected() {
460        let result = MerkleTree::build(vec![]);
461        assert!(matches!(result, Err(CommitmentError::EmptyKeySet)));
462    }
463
464    #[test]
465    fn duplicate_keys_rejected() {
466        let result = MerkleTree::build(vec![(xn(1), bh(1)), (xn(1), bh(2))]);
467        assert!(matches!(result, Err(CommitmentError::DuplicateKey(_))));
468    }
469
470    #[test]
471    fn single_leaf_tree_root_is_leaf_hash() {
472        let key = xn(1);
473        let bytes_hash = bh(1);
474        let tree = MerkleTree::build(vec![(key, bytes_hash)]).unwrap();
475        assert_eq!(tree.root(), leaf_hash(&key, &bytes_hash));
476        assert_eq!(tree.key_count(), 1);
477        assert_eq!(tree.path_for(&key), Some(vec![]));
478        // Empty path verifies trivially (root == leaf).
479        assert!(verify_path(
480            &leaf_hash(&key, &bytes_hash),
481            &[],
482            0,
483            1,
484            &tree.root()
485        ));
486    }
487
488    #[test]
489    fn two_leaf_tree_root_combines_both_leaves() {
490        let entries = vec![(xn(1), bh(1)), (xn(2), bh(2))];
491        let tree = MerkleTree::build(entries).unwrap();
492        // Sorted order: xn(1), xn(2).
493        let l1 = leaf_hash(&xn(1), &bh(1));
494        let l2 = leaf_hash(&xn(2), &bh(2));
495        assert_eq!(tree.root(), node_hash(&l1, &l2));
496    }
497
498    #[test]
499    fn root_is_deterministic_regardless_of_input_order() {
500        let mut a = vec![(xn(3), bh(3)), (xn(1), bh(1)), (xn(2), bh(2))];
501        let mut b = vec![(xn(2), bh(2)), (xn(3), bh(3)), (xn(1), bh(1))];
502        let tree_a = MerkleTree::build(a.clone()).unwrap();
503        let tree_b = MerkleTree::build(b.clone()).unwrap();
504        a.sort_by_key(|x| x.0);
505        b.sort_by_key(|x| x.0);
506        assert_eq!(tree_a.root(), tree_b.root());
507    }
508
509    fn xn_u32(i: u32) -> XorName {
510        let mut k = [0u8; 32];
511        k[..4].copy_from_slice(&i.to_le_bytes());
512        k
513    }
514
515    fn bh_u32(i: u32) -> [u8; 32] {
516        let mut h = [0u8; 32];
517        h[..4].copy_from_slice(&i.to_le_bytes());
518        h[4] = 0x5A;
519        h
520    }
521
522    #[test]
523    fn paths_verify_for_every_key_at_various_sizes() {
524        for n in [1u32, 2, 3, 4, 5, 7, 8, 16, 17, 100, 333] {
525            let entries: Vec<_> = (0..n).map(|i| (xn_u32(i), bh_u32(i))).collect();
526            let tree = MerkleTree::build(entries.clone()).unwrap();
527            let root = tree.root();
528            let key_count = tree.key_count();
529            for (idx, (k, _)) in tree.iter_leaves().enumerate() {
530                let path = tree.path_for(k).expect("path for present key");
531                let bytes_hash = entries.iter().find(|(kk, _)| kk == k).unwrap().1;
532                let lh = leaf_hash(k, &bytes_hash);
533                assert!(
534                    verify_path(&lh, &path, idx, key_count, &root),
535                    "path verify failed at n={n} idx={idx}",
536                );
537            }
538        }
539    }
540
541    #[test]
542    fn path_for_absent_key_is_none() {
543        let tree = MerkleTree::build(vec![(xn(1), bh(1)), (xn(2), bh(2))]).unwrap();
544        assert!(tree.path_for(&xn(99)).is_none());
545    }
546
547    #[test]
548    fn tampered_bytes_hash_breaks_path_verify() {
549        // Use 8 distinct sorted keys so the index in `entries` matches the
550        // sorted leaf index in the tree.
551        let entries: Vec<_> = (1..=8u8).map(|i| (xn(i), bh(i))).collect();
552        let tree = MerkleTree::build(entries.clone()).unwrap();
553        let root = tree.root();
554        let (k, _) = &entries[3];
555        let path = tree.path_for(k).unwrap();
556
557        let wrong_bytes_hash = [0xFFu8; 32];
558        let lh = leaf_hash(k, &wrong_bytes_hash);
559        assert!(!verify_path(&lh, &path, 3, 8, &root));
560    }
561
562    #[test]
563    fn tampered_path_node_breaks_verify() {
564        let entries: Vec<_> = (1..=8u8).map(|i| (xn(i), bh(i))).collect();
565        let tree = MerkleTree::build(entries.clone()).unwrap();
566        let root = tree.root();
567        let (k, _) = &entries[3];
568        let mut path = tree.path_for(k).unwrap();
569        path[0][0] ^= 0x01;
570        let lh = leaf_hash(k, &bh(4));
571        assert!(!verify_path(&lh, &path, 3, 8, &root));
572    }
573
574    #[test]
575    fn wrong_leaf_index_breaks_verify() {
576        let entries: Vec<_> = (1..=8u8).map(|i| (xn(i), bh(i))).collect();
577        let tree = MerkleTree::build(entries.clone()).unwrap();
578        let root = tree.root();
579        let (k, _) = &entries[3];
580        let path = tree.path_for(k).unwrap();
581        let lh = leaf_hash(k, &bh(4));
582        // Correct index is 3; using 2 should fail because the left/right
583        // child ordering swaps.
584        assert!(!verify_path(&lh, &path, 2, 8, &root));
585        assert!(verify_path(&lh, &path, 3, 8, &root));
586    }
587
588    #[test]
589    fn out_of_range_leaf_index_rejected() {
590        let entries: Vec<_> = (1..=8u8).map(|i| (xn(i), bh(i))).collect();
591        let tree = MerkleTree::build(entries.clone()).unwrap();
592        let root = tree.root();
593        let (k, _) = &entries[3];
594        let path = tree.path_for(k).unwrap();
595        let lh = leaf_hash(k, &bh(4));
596        // leaf_index >= key_count must be rejected without even hashing.
597        assert!(!verify_path(&lh, &path, 8, 8, &root));
598        assert!(!verify_path(&lh, &path, 99, 8, &root));
599        // Valid baseline.
600        assert!(verify_path(&lh, &path, 3, 8, &root));
601    }
602
603    #[test]
604    fn wrong_path_length_rejected_pre_hashing() {
605        let entries: Vec<_> = (1..=8u8).map(|i| (xn(i), bh(i))).collect();
606        let tree = MerkleTree::build(entries.clone()).unwrap();
607        let root = tree.root();
608        let (k, _) = &entries[3];
609        let path = tree.path_for(k).unwrap();
610        let lh = leaf_hash(k, &bh(4));
611        // For key_count=8 the expected path length is 3 (ceil(log2(8))=3).
612        assert_eq!(path.len(), 3);
613        // Truncating breaks structural check.
614        let short: Vec<_> = path.iter().take(2).copied().collect();
615        assert!(!verify_path(&lh, &short, 3, 8, &root));
616        // Padding too long also breaks structural check.
617        let mut long = path;
618        long.push([0; 32]);
619        assert!(!verify_path(&lh, &long, 3, 8, &root));
620    }
621
622    #[test]
623    fn zero_key_count_rejected() {
624        // Defensive: even with an empty path and correct-shape root, a
625        // commitment claiming zero keys is nonsensical.
626        let lh = [0u8; 32];
627        assert!(!verify_path(&lh, &[], 0, 0, &[0u8; 32]));
628    }
629
630    #[test]
631    fn out_of_protocol_key_count_rejected() {
632        // Wire-supplied key_count exceeding MAX_COMMITMENT_KEY_COUNT is
633        // refused before any hashing. Guards an overflow found in review:
634        // `next_power_of_two()` would otherwise panic in debug and wrap in
635        // release on key_count > 1 << 31.
636        let lh = [0u8; 32];
637        assert!(!verify_path(
638            &lh,
639            &[],
640            0,
641            MAX_COMMITMENT_KEY_COUNT + 1,
642            &[0u8; 32]
643        ));
644        assert!(!verify_path(&lh, &[], 0, u32::MAX, &[0u8; 32]));
645    }
646
647    fn pk_bytes(pk: &MlDsaPublicKey) -> Vec<u8> {
648        pk.to_bytes()
649    }
650
651    #[test]
652    fn sign_and_verify_roundtrip() {
653        let dsa = ml_dsa_65();
654        let (pk, sk) = dsa.generate_keypair().unwrap();
655        let entries: Vec<_> = (0..5u8).map(|i| (xn(i), bh(i))).collect();
656        let tree = MerkleTree::build(entries).unwrap();
657        let root = tree.root();
658        let key_count = tree.key_count();
659        let peer_id = [0xAB; 32];
660        let pk_b = pk_bytes(&pk);
661        let signature = sign_commitment(&sk, &root, key_count, &peer_id, &pk_b).unwrap();
662        let c = StorageCommitment {
663            root,
664            key_count,
665            sender_peer_id: peer_id,
666            sender_public_key: pk_b,
667            signature,
668        };
669        // Verifies via embedded key, no external lookup needed.
670        assert!(verify_commitment_signature(&c));
671    }
672
673    #[test]
674    fn signature_fails_when_root_tampered() {
675        let dsa = ml_dsa_65();
676        let (pk, sk) = dsa.generate_keypair().unwrap();
677        let root = [0u8; 32];
678        let pk_b = pk_bytes(&pk);
679        let signature = sign_commitment(&sk, &root, 1, &[0; 32], &pk_b).unwrap();
680        let c = StorageCommitment {
681            root: [1u8; 32], // tampered
682            key_count: 1,
683            sender_peer_id: [0; 32],
684            sender_public_key: pk_b,
685            signature,
686        };
687        assert!(!verify_commitment_signature(&c));
688    }
689
690    #[test]
691    fn signature_fails_under_swapped_public_key() {
692        let dsa = ml_dsa_65();
693        let (pk1, sk1) = dsa.generate_keypair().unwrap();
694        let (pk2, _sk2) = dsa.generate_keypair().unwrap();
695        let pk1_b = pk_bytes(&pk1);
696        let pk2_b = pk_bytes(&pk2);
697        // Sign under pk1 but embed pk2 — verification (using embedded key)
698        // should fail because pk2 didn't sign this payload AND because the
699        // signed payload binds pk1, not pk2.
700        let signature = sign_commitment(&sk1, &[0u8; 32], 1, &[0; 32], &pk1_b).unwrap();
701        let c = StorageCommitment {
702            root: [0u8; 32],
703            key_count: 1,
704            sender_peer_id: [0; 32],
705            sender_public_key: pk2_b,
706            signature,
707        };
708        assert!(!verify_commitment_signature(&c));
709    }
710
711    #[test]
712    fn signature_fails_with_garbage_bytes() {
713        let dsa = ml_dsa_65();
714        let (pk, _sk) = dsa.generate_keypair().unwrap();
715        let c = StorageCommitment {
716            root: [0u8; 32],
717            key_count: 1,
718            sender_peer_id: [0; 32],
719            sender_public_key: pk_bytes(&pk),
720            signature: vec![0u8; 100], // too short and zero-filled
721        };
722        assert!(!verify_commitment_signature(&c));
723    }
724
725    #[test]
726    fn signature_fails_with_garbage_public_key() {
727        // Embedded pubkey is wrong length / invalid → from_bytes fails →
728        // verify returns false. Defends against malformed gossip.
729        let c = StorageCommitment {
730            root: [0u8; 32],
731            key_count: 1,
732            sender_peer_id: [0; 32],
733            sender_public_key: vec![0u8; 100], // wrong length
734            signature: vec![0u8; 3293],
735        };
736        assert!(!verify_commitment_signature(&c));
737    }
738
739    #[test]
740    fn commitment_hash_differs_on_any_field_change() {
741        let dsa = ml_dsa_65();
742        let (pk, sk) = dsa.generate_keypair().unwrap();
743        let pk_b = pk_bytes(&pk);
744        let sig = sign_commitment(&sk, &[0; 32], 1, &[0; 32], &pk_b).unwrap();
745        let c1 = StorageCommitment {
746            root: [0; 32],
747            key_count: 1,
748            sender_peer_id: [0; 32],
749            sender_public_key: pk_b,
750            signature: sig,
751        };
752        let h1 = commitment_hash(&c1).unwrap();
753
754        let mut c2 = c1.clone();
755        c2.root = [1; 32];
756        assert_ne!(h1, commitment_hash(&c2).unwrap());
757
758        let mut c3 = c1.clone();
759        c3.key_count = 2;
760        assert_ne!(h1, commitment_hash(&c3).unwrap());
761
762        let mut c4 = c1.clone();
763        c4.sender_peer_id = [1; 32];
764        assert_ne!(h1, commitment_hash(&c4).unwrap());
765
766        let mut c5 = c1.clone();
767        c5.signature[0] ^= 1;
768        assert_ne!(h1, commitment_hash(&c5).unwrap());
769
770        let (pk_other, _) = dsa.generate_keypair().unwrap();
771        let mut c6 = c1;
772        c6.sender_public_key = pk_bytes(&pk_other);
773        assert_ne!(h1, commitment_hash(&c6).unwrap());
774    }
775
776    #[test]
777    fn commitment_hash_stable_for_identical_input() {
778        let dsa = ml_dsa_65();
779        let (pk, sk) = dsa.generate_keypair().unwrap();
780        let pk_b = pk_bytes(&pk);
781        let sig = sign_commitment(&sk, &[7; 32], 42, &[3; 32], &pk_b).unwrap();
782        let c = StorageCommitment {
783            root: [7; 32],
784            key_count: 42,
785            sender_peer_id: [3; 32],
786            sender_public_key: pk_b,
787            signature: sig,
788        };
789        assert_eq!(commitment_hash(&c), commitment_hash(&c));
790    }
791
792    #[test]
793    fn commitment_hash_signature_length_change_changes_hash() {
794        // Postcard's varint length prefix means hashing a 1-byte signature
795        // and a 2-byte signature whose first byte is the same produces
796        // different commitment hashes — a hash that omitted the serialized
797        // length prefix would let boundary-shifted fields collide.
798        let c1 = StorageCommitment {
799            root: [0; 32],
800            key_count: 1,
801            sender_peer_id: [0; 32],
802            sender_public_key: vec![0u8; 1952],
803            signature: vec![0xAB],
804        };
805        let c2 = StorageCommitment {
806            root: [0; 32],
807            key_count: 1,
808            sender_peer_id: [0; 32],
809            sender_public_key: vec![0u8; 1952],
810            signature: vec![0xAB, 0x00],
811        };
812        assert_ne!(commitment_hash(&c1).unwrap(), commitment_hash(&c2).unwrap());
813    }
814
815    #[test]
816    fn too_many_keys_rejected() {
817        let mut entries = Vec::with_capacity(MAX_COMMITMENT_KEY_COUNT as usize + 1);
818        for i in 0..=MAX_COMMITMENT_KEY_COUNT {
819            let mut k = [0u8; 32];
820            k[..4].copy_from_slice(&i.to_le_bytes());
821            entries.push((k, [0; 32]));
822        }
823        let result = MerkleTree::build(entries);
824        assert!(matches!(result, Err(CommitmentError::TooManyKeys(_))));
825    }
826}