Skip to main content

ant_protocol/payment/
commitment.rs

1//! The signed storage commitment — shared between node and client (ADR-0004).
2//!
3//! ADR-0004 makes a quote's price a function of the node's audited storage
4//! commitment, and requires the **client** to fully verify that commitment
5//! before paying ("the client pays nothing it cannot resolve" — the ceiling's
6//! load-bearing wall). To do that the client needs the commitment type, its
7//! pin (hash), and its signature/peer-binding check — exactly the pieces here.
8//!
9//! This is the **single source of truth** for the commitment wire type and its
10//! verification: `ant-node` re-exports [`StorageCommitment`], [`commitment_hash`],
11//! [`verify_commitment_signature`], and [`MAX_COMMITMENT_KEY_COUNT`] from this
12//! module so the node (gossip/audit) and the client (resolve-before-pay) can
13//! never disagree on what a valid commitment is or what pin it hashes to.
14//!
15//! Only the *verification* surface lives here. The Merkle tree, inclusion
16//! paths, and signing live in `ant-node` (the responder/auditor own those);
17//! the client never builds or signs a commitment, it only verifies one.
18
19use blake3::Hasher;
20use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaPublicKey, MlDsaSignature, MlDsaVariant};
21use serde::{Deserialize, Serialize};
22
23/// Domain-separation tag for the commitment signature.
24///
25/// Signed payload is verified under this context tag.
26pub const DOMAIN_COMMITMENT: &[u8] = b"autonomi.ant.replication.storage_commitment.v1";
27
28/// Domain-separation tag for the auditor's pin: BLAKE3 over (this tag ||
29/// canonical commitment blob).
30pub const DOMAIN_COMMITMENT_HASH: &[u8] = b"autonomi.ant.replication.commitment_hash.v1";
31
32/// Maximum number of keys a single commitment may cover.
33///
34/// Bounds the Merkle path depth and responder-side tree memory. A node storing
35/// more keys than this would need to split its claim. The client rejects any
36/// quote whose `committed_key_count` exceeds this before paying, exactly as the
37/// node does.
38pub const MAX_COMMITMENT_KEY_COUNT: u32 = 1_000_000;
39
40/// Maximum serialized size of a single commitment sidecar blob (ADR-0004).
41///
42/// A well-formed `StorageCommitment` is ~5.3 KiB (root 32 + `key_count` 4 +
43/// `peer_id` 32 + pubkey 1952 + signature 3293 + serde framing). 8 KiB leaves
44/// generous headroom while bounding the deserialize/verify work a malicious
45/// quote responder or client can force on the hot verification path. A sidecar
46/// larger than this is rejected before any parse attempt.
47pub const MAX_COMMITMENT_SIDECAR_BYTES: usize = 8 * 1024;
48
49/// Signed storage commitment.
50///
51/// Piggybacked on neighbour-sync gossip and shipped alongside a quote (ADR-0004).
52/// The signature commits to the Merkle root, key count, sender peer ID, **and
53/// the sender's ML-DSA-65 public key** under [`DOMAIN_COMMITMENT`].
54///
55/// Embedding the public key lets any receiver (including the paying client)
56/// verify the signature without an external `PeerId → MlDsaPublicKey` lookup.
57/// Binding the public key in the signed payload prevents a key-swap attack.
58///
59/// Wire size ≈ 5.3 KiB (root 32 B + `key_count` 4 B + `peer_id` 32 B + pubkey
60/// 1952 B + signature 3293 B).
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
62pub struct StorageCommitment {
63    /// Merkle root over the responder's claimed keys.
64    pub root: [u8; 32],
65    /// Number of leaves committed over.
66    pub key_count: u32,
67    /// Sender peer ID, bound to the signature.
68    pub sender_peer_id: [u8; 32],
69    /// Sender's ML-DSA-65 public key bytes (1952 bytes). Embedded so receivers
70    /// can verify the signature without a separate pubkey directory. Bound by
71    /// the signature.
72    pub sender_public_key: Vec<u8>,
73    /// ML-DSA-65 signature over canonical commitment fields. 3293 bytes.
74    pub signature: Vec<u8>,
75}
76
77/// The pin: `BLAKE3(DOMAIN_COMMITMENT_HASH || postcard(commitment))`.
78///
79/// Equal commitments produce equal hashes; any change to `root`, `key_count`,
80/// peer ID, pubkey, or signature changes the hash. A quote pins a commitment by
81/// this value; resolving the quote means finding a commitment that hashes to
82/// the pin.
83///
84/// # Errors
85///
86/// Returns `None` only if postcard fails to serialize the commitment — not
87/// reachable for a well-formed ML-DSA-65 commitment. Callers treat `None` as a
88/// malformed commitment and drop it.
89#[must_use]
90pub fn commitment_hash(c: &StorageCommitment) -> Option<[u8; 32]> {
91    let serialized = postcard::to_allocvec(c).ok()?;
92    let mut h = Hasher::new();
93    h.update(DOMAIN_COMMITMENT_HASH);
94    h.update(&serialized);
95    Some(*h.finalize().as_bytes())
96}
97
98/// Canonical bytes the ML-DSA signature covers: the commitment fields minus the
99/// signature itself.
100///
101/// `sender_public_key` is length-prefixed and included so an adversary cannot
102/// keep the body and re-sign under a different key.
103fn commitment_signed_payload(
104    root: &[u8; 32],
105    key_count: u32,
106    sender_peer_id: &[u8; 32],
107    sender_public_key: &[u8],
108) -> Vec<u8> {
109    let mut v = Vec::with_capacity(32 + 4 + 32 + 4 + sender_public_key.len());
110    v.extend_from_slice(root);
111    v.extend_from_slice(&key_count.to_le_bytes());
112    v.extend_from_slice(sender_peer_id);
113    let pk_len = u32::try_from(sender_public_key.len()).unwrap_or(u32::MAX);
114    v.extend_from_slice(&pk_len.to_le_bytes());
115    v.extend_from_slice(sender_public_key);
116    v
117}
118
119/// Verify a commitment's ML-DSA-65 signature against its **embedded** public
120/// key. Does NOT check the peer binding (`BLAKE3(pubkey) == sender_peer_id`) —
121/// callers that need it (the client, the node) check it separately so the same
122/// function serves both the "trust the embedded key" and "bind to a peer" uses.
123#[must_use]
124pub fn verify_commitment_signature(c: &StorageCommitment) -> bool {
125    let Ok(public_key) = MlDsaPublicKey::from_bytes(MlDsaVariant::MlDsa65, &c.sender_public_key)
126    else {
127        return false;
128    };
129    let payload = commitment_signed_payload(
130        &c.root,
131        c.key_count,
132        &c.sender_peer_id,
133        &c.sender_public_key,
134    );
135    let Ok(sig) = MlDsaSignature::from_bytes(MlDsaVariant::MlDsa65, &c.signature) else {
136        return false;
137    };
138    ml_dsa_65()
139        .verify_with_context(&public_key, &payload, &sig, DOMAIN_COMMITMENT)
140        .unwrap_or(false)
141}
142
143#[cfg(test)]
144#[allow(clippy::unwrap_used, clippy::expect_used)]
145mod tests {
146    use super::*;
147    use saorsa_pqc::api::sig::ml_dsa_65;
148
149    /// Build a genuinely-signed commitment (fresh ML-DSA-65 keypair, signed over
150    /// the exact `commitment_signed_payload` under `DOMAIN_COMMITMENT`) — the same
151    /// thing the node produces. Returns the commitment and the keypair's public
152    /// bytes so tamper tests can key-swap.
153    fn signed_commitment(root: [u8; 32], key_count: u32, peer_id: [u8; 32]) -> StorageCommitment {
154        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
155        let pk_bytes = pk.to_bytes();
156        let payload = commitment_signed_payload(&root, key_count, &peer_id, &pk_bytes);
157        let sig = ml_dsa_65()
158            .sign_with_context(&sk, &payload, DOMAIN_COMMITMENT)
159            .unwrap();
160        StorageCommitment {
161            root,
162            key_count,
163            sender_peer_id: peer_id,
164            sender_public_key: pk_bytes,
165            signature: sig.to_bytes(),
166        }
167    }
168
169    /// A malformed commitment (bad pubkey / signature) fails verification
170    /// rather than panicking — the client runs this on untrusted bytes.
171    #[test]
172    fn verify_rejects_malformed_without_panic() {
173        let c = StorageCommitment {
174            root: [0u8; 32],
175            key_count: 1,
176            sender_peer_id: [0u8; 32],
177            sender_public_key: vec![0u8; 10],
178            signature: vec![0u8; 10],
179        };
180        assert!(!verify_commitment_signature(&c));
181        // hash is still computable over any well-formed struct.
182        assert!(commitment_hash(&c).is_some());
183    }
184
185    /// The pin is deterministic and changes when any field changes.
186    #[test]
187    fn commitment_hash_is_deterministic_and_field_sensitive() {
188        let c = StorageCommitment {
189            root: [1u8; 32],
190            key_count: 5,
191            sender_peer_id: [2u8; 32],
192            sender_public_key: vec![3u8; 20],
193            signature: vec![4u8; 20],
194        };
195        let h1 = commitment_hash(&c).unwrap();
196        let h2 = commitment_hash(&c).unwrap();
197        assert_eq!(h1, h2, "same commitment -> same pin");
198
199        let mut c2 = c.clone();
200        c2.key_count = 6;
201        assert_ne!(
202            commitment_hash(&c2).unwrap(),
203            h1,
204            "changing key_count must change the pin"
205        );
206    }
207
208    /// A correctly-signed commitment verifies. Without this, a regression that
209    /// made `verify_commitment_signature` always return `false` (or ignore the
210    /// signature) would pass every other test in this module.
211    #[test]
212    fn verify_accepts_a_correctly_signed_commitment() {
213        let c = signed_commitment([7u8; 32], 42, [9u8; 32]);
214        assert!(
215            verify_commitment_signature(&c),
216            "a genuinely signed commitment must verify"
217        );
218    }
219
220    /// The signature covers `root`, `key_count`, `peer_id`, and the embedded
221    /// pubkey — mutating any of them after signing must fail verification. This
222    /// is the ADR-0004 "the fields are covered by the signature" invariant.
223    #[test]
224    fn verify_rejects_any_field_tampered_after_signing() {
225        // key_count
226        let mut c = signed_commitment([1u8; 32], 100, [2u8; 32]);
227        c.key_count = c.key_count.wrapping_add(1);
228        assert!(
229            !verify_commitment_signature(&c),
230            "tampered key_count must fail"
231        );
232
233        // root
234        let mut c = signed_commitment([1u8; 32], 100, [2u8; 32]);
235        c.root[0] ^= 0xff;
236        assert!(!verify_commitment_signature(&c), "tampered root must fail");
237
238        // sender_peer_id
239        let mut c = signed_commitment([1u8; 32], 100, [2u8; 32]);
240        c.sender_peer_id[0] ^= 0xff;
241        assert!(
242            !verify_commitment_signature(&c),
243            "tampered peer_id must fail"
244        );
245
246        // key-swap: keep the body + signature, swap in a different valid pubkey.
247        // The pubkey is bound into the signed payload, so this must fail.
248        let mut c = signed_commitment([1u8; 32], 100, [2u8; 32]);
249        let (other_pk, _) = ml_dsa_65().generate_keypair().unwrap();
250        c.sender_public_key = other_pk.to_bytes();
251        assert!(
252            !verify_commitment_signature(&c),
253            "swapping the embedded pubkey must fail"
254        );
255    }
256}