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