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