Skip to main content

hyprstream_pay/
attestation.rs

1//! The settlement attestation: a canonical, self-contained, content-addressed
2//! record (PAY-ARCH-01 guard-rail).
3//!
4//! ## Why this exists
5//!
6//! `settlement.capnp` declares `attestation :Data`. An opaque byte blob is fine
7//! for "carry this to the verifier and back", but it is *not* fine for what the
8//! attestation is actually for: a future exchange record (#926) must be able to
9//! embed this blob **verbatim** and content-address it. That requires three
10//! properties an arbitrary `Data` payload does not have:
11//!
12//! 1. **Canonical.** One logical attestation has exactly one byte
13//!    representation, so its CID is a function of its meaning rather than of
14//!    whichever encoder produced it. [`SettlementAttestation::decode`] enforces
15//!    this by re-encoding what it parsed and rejecting any input that is not
16//!    already in canonical form — a non-canonical blob is refused rather than
17//!    silently normalized, because normalizing would change the CID a peer
18//!    already committed to.
19//! 2. **Self-contained.** Everything needed to decide what was settled — issuer,
20//!    settlement id, unit, destination, amount, grant — is inside the signed
21//!    body. Nothing is passed alongside it. A verifier that has to be told the
22//!    settlement id out of band cannot detect a blob presented under the wrong
23//!    id, so the id is bound in here instead.
24//! 3. **Domain-separated.** The signed bytes begin with a version tag unique to
25//!    this record type, so a signature over some other artifact can never be
26//!    replayed as a settlement attestation, and a future v2 body can never be
27//!    read as a v1 one.
28//!
29//! ## Normative encoding
30//!
31//! The body is canonical DAG-CBOR — the same discipline
32//! `hyprstream_ledger::AccountId::derive` and `hyprstream-pds` use (definite
33//! lengths, minimal-width integers, no maps so no key ordering to get wrong).
34//! A single definite-length array, in this fixed order:
35//!
36//! ```text
37//! [
38//!   "hs-pay-settlement-attestation-v1",  // domain + version tag
39//!   <issuer_did      : tstr>,
40//!   <settlement_id   : tstr>,
41//!   <unit_issuer_did : tstr>,
42//!   <unit_class      : tstr>,
43//!   <destination_did : tstr>,
44//!   <amount_minor    : bstr(16)>,        // big-endian u128
45//!   <grant_cid       : bstr>,            // empty when absent
46//!   <settled_at      : uint>,            // unix seconds
47//!   <signature       : bstr>             // COSE composite over the body below
48//! ]
49//! ```
50//!
51//! The **signing input** is the same array with the trailing `signature`
52//! element omitted (a 9-element array), so the signature covers every semantic
53//! field and nothing else. Amounts are 16-byte big-endian rather than CBOR
54//! integers because the ledger's amounts are `u128`, which CBOR's integer range
55//! cannot carry losslessly.
56//!
57//! ## CID
58//!
59//! [`SettlementAttestation::cid`] is `blake3(canonical bytes)`, 32 bytes. It is
60//! stable across encode/decode round-trips and across processes, so an exchange
61//! record can reference the attestation by CID and a peer can re-derive that CID
62//! from the embedded bytes with no re-encoding step.
63
64use ciborium::value::Value;
65use serde::{Deserialize, Serialize};
66
67use crate::{PayError, UnitRef};
68
69/// Domain-separation and version tag. Changing the body shape means minting a
70/// new tag, never reinterpreting this one.
71pub const ATTESTATION_V1_TAG: &str = "hs-pay-settlement-attestation-v1";
72
73/// A settlement attestation: the signed, self-contained claim that a specific
74/// settlement committed, and therefore that a specific issuance is owed.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct SettlementAttestation {
77    /// DID of the party that signed this attestation (the settlement
78    /// authority). Verification resolves key material from this, so it is part
79    /// of the signed body rather than supplied alongside it.
80    pub issuer_did: String,
81    /// The settlement row this attests to. Bound into the signed body so an
82    /// attestation cannot be presented under a different id.
83    pub settlement_id: String,
84    /// The credit unit to be issued.
85    pub unit: UnitRef,
86    /// The pseudonymous destination identity for the issued credits.
87    pub destination_did: String,
88    /// Amount in minor units.
89    pub amount_minor: u128,
90    /// The allocation grant this settlement backs, if any.
91    pub grant_cid: Option<Vec<u8>>,
92    /// When the settlement committed (unix seconds).
93    pub settled_at: u64,
94    /// COSE composite signature (EdDSA + ML-DSA-65) over [`Self::signing_input`].
95    pub signature: Vec<u8>,
96}
97
98impl SettlementAttestation {
99    /// The exact bytes a signature must cover: the canonical body **without**
100    /// the signature element.
101    pub fn signing_input(&self) -> Result<Vec<u8>, PayError> {
102        encode_canonical(&self.body_fields())
103    }
104
105    /// The canonical wire bytes, signature included. This is what travels in
106    /// the capnp `attestation :Data` field and what a future exchange record
107    /// embeds verbatim.
108    pub fn encode(&self) -> Result<Vec<u8>, PayError> {
109        let mut fields = self.body_fields();
110        fields.push(Value::Bytes(self.signature.clone()));
111        encode_canonical(&fields)
112    }
113
114    /// Parse canonical wire bytes.
115    ///
116    /// Rejects any input that is not already canonical. Accepting a
117    /// non-canonical encoding and normalizing it would give the same logical
118    /// attestation two different CIDs, which defeats content-addressing it.
119    pub fn decode(bytes: &[u8]) -> Result<Self, PayError> {
120        let value: Value = ciborium::from_reader(bytes)
121            .map_err(|e| PayError::AttestationInvalid(format!("attestation is not CBOR: {e}")))?;
122        let items = match value {
123            Value::Array(items) => items,
124            _ => {
125                return Err(PayError::AttestationInvalid(
126                    "attestation must be a CBOR array".to_owned(),
127                ))
128            }
129        };
130        if items.len() != 10 {
131            return Err(PayError::AttestationInvalid(format!(
132                "attestation must have 10 fields, found {}",
133                items.len()
134            )));
135        }
136        if text(&items[0])? != ATTESTATION_V1_TAG {
137            return Err(PayError::AttestationInvalid(
138                "attestation is not a hs-pay-settlement-attestation-v1 record".to_owned(),
139            ));
140        }
141
142        let parsed = SettlementAttestation {
143            issuer_did: text(&items[1])?.to_owned(),
144            settlement_id: text(&items[2])?.to_owned(),
145            unit: UnitRef {
146                issuer_did: text(&items[3])?.to_owned(),
147                resource_class: text(&items[4])?.to_owned(),
148            },
149            destination_did: text(&items[5])?.to_owned(),
150            amount_minor: amount(&items[6])?,
151            grant_cid: {
152                let g = bytes_of(&items[7])?;
153                if g.is_empty() {
154                    None
155                } else {
156                    Some(g.to_vec())
157                }
158            },
159            settled_at: uint(&items[8])?,
160            signature: bytes_of(&items[9])?.to_vec(),
161        };
162
163        // Canonicality: what we parsed must re-encode to exactly what we were
164        // given, byte for byte.
165        let reencoded = parsed.encode()?;
166        if reencoded != bytes {
167            return Err(PayError::AttestationInvalid(
168                "attestation bytes are not canonical (re-encoding differs); refusing to \
169                 normalize, because that would change the content address"
170                    .to_owned(),
171            ));
172        }
173        Ok(parsed)
174    }
175
176    /// Content address: `blake3` over the canonical bytes.
177    ///
178    /// Stable across processes and round-trips, so an exchange record can carry
179    /// the attestation and its CID together and any peer can re-derive one from
180    /// the other.
181    pub fn cid(&self) -> Result<[u8; 32], PayError> {
182        Ok(*blake3::hash(&self.encode()?).as_bytes())
183    }
184
185    /// The signed fields, in normative order, without the signature.
186    fn body_fields(&self) -> Vec<Value> {
187        vec![
188            Value::Text(ATTESTATION_V1_TAG.to_owned()),
189            Value::Text(self.issuer_did.clone()),
190            Value::Text(self.settlement_id.clone()),
191            Value::Text(self.unit.issuer_did.clone()),
192            Value::Text(self.unit.resource_class.clone()),
193            Value::Text(self.destination_did.clone()),
194            Value::Bytes(self.amount_minor.to_be_bytes().to_vec()),
195            Value::Bytes(self.grant_cid.clone().unwrap_or_default()),
196            Value::Integer(self.settled_at.into()),
197        ]
198    }
199}
200
201fn encode_canonical(fields: &[Value]) -> Result<Vec<u8>, PayError> {
202    let mut buf = Vec::new();
203    ciborium::into_writer(&Value::Array(fields.to_vec()), &mut buf)
204        .map_err(|e| PayError::Internal(format!("attestation encode failed: {e}")))?;
205    Ok(buf)
206}
207
208fn text(v: &Value) -> Result<&str, PayError> {
209    v.as_text()
210        .ok_or_else(|| PayError::AttestationInvalid("expected a text field".to_owned()))
211}
212
213fn bytes_of(v: &Value) -> Result<&[u8], PayError> {
214    v.as_bytes()
215        .map(Vec::as_slice)
216        .ok_or_else(|| PayError::AttestationInvalid("expected a byte-string field".to_owned()))
217}
218
219fn uint(v: &Value) -> Result<u64, PayError> {
220    let i = v
221        .as_integer()
222        .ok_or_else(|| PayError::AttestationInvalid("expected an integer field".to_owned()))?;
223    u64::try_from(i)
224        .map_err(|_| PayError::AttestationInvalid("integer field out of range".to_owned()))
225}
226
227/// Decode a 16-byte big-endian amount, requiring exactly 16 bytes so a short or
228/// long encoding cannot silently denote a different value.
229fn amount(v: &Value) -> Result<u128, PayError> {
230    let b = bytes_of(v)?;
231    if b.len() != 16 {
232        return Err(PayError::AttestationInvalid(format!(
233            "amount must be exactly 16 bytes, found {}",
234            b.len()
235        )));
236    }
237    let mut arr = [0u8; 16];
238    arr.copy_from_slice(b);
239    Ok(u128::from_be_bytes(arr))
240}
241
242#[cfg(test)]
243mod tests {
244    // A test asserting a known-good value legitimately unwraps.
245    #![allow(clippy::unwrap_used, clippy::expect_used)]
246
247    use super::*;
248
249    fn sample() -> SettlementAttestation {
250        SettlementAttestation {
251            issuer_did: "did:web:settlement.test".to_owned(),
252            settlement_id: "stl_01HQ".to_owned(),
253            unit: UnitRef {
254                issuer_did: "did:web:issuer.test".to_owned(),
255                resource_class: "gpu.h100.seconds".to_owned(),
256            },
257            destination_did: "did:key:zPurchaser".to_owned(),
258            amount_minor: 12_345_678_901_234_567_890_123_456_789,
259            grant_cid: Some(vec![0xde, 0xad, 0xbe, 0xef]),
260            settled_at: 1_753_600_000,
261            signature: vec![7u8; 96],
262        }
263    }
264
265    #[test]
266    fn encode_is_deterministic() {
267        assert_eq!(sample().encode().unwrap(), sample().encode().unwrap());
268    }
269
270    #[test]
271    fn roundtrips_through_the_wire_form() {
272        let a = sample();
273        let bytes = a.encode().unwrap();
274        assert_eq!(SettlementAttestation::decode(&bytes).unwrap(), a);
275    }
276
277    #[test]
278    fn a_large_u128_amount_survives_exactly() {
279        let a = sample();
280        let decoded = SettlementAttestation::decode(&a.encode().unwrap()).unwrap();
281        assert_eq!(
282            decoded.amount_minor, a.amount_minor,
283            "a u128 amount beyond the CBOR integer range must not be truncated"
284        );
285    }
286
287    #[test]
288    fn the_cid_is_stable_across_a_roundtrip() {
289        let a = sample();
290        let bytes = a.encode().unwrap();
291        let decoded = SettlementAttestation::decode(&bytes).unwrap();
292        assert_eq!(
293            a.cid().unwrap(),
294            decoded.cid().unwrap(),
295            "an embedded attestation must content-address identically after a roundtrip"
296        );
297        // ...and re-encoding must be byte-identical, so an exchange record can
298        // embed the bytes verbatim with no re-encoding step.
299        assert_eq!(decoded.encode().unwrap(), bytes);
300    }
301
302    #[test]
303    fn the_cid_changes_when_any_signed_field_changes() {
304        let base = sample().cid().unwrap();
305        let mut other = sample();
306        other.amount_minor += 1;
307        assert_ne!(base, other.cid().unwrap());
308        let mut other = sample();
309        other.destination_did = "did:key:zSomeoneElse".to_owned();
310        assert_ne!(base, other.cid().unwrap());
311        let mut other = sample();
312        other.settlement_id = "stl_other".to_owned();
313        assert_ne!(base, other.cid().unwrap());
314    }
315
316    #[test]
317    fn the_signing_input_excludes_the_signature() {
318        let mut a = sample();
319        let input = a.signing_input().unwrap();
320        a.signature = vec![9u8; 96];
321        assert_eq!(
322            input,
323            a.signing_input().unwrap(),
324            "changing the signature must not change what was signed"
325        );
326        assert_ne!(
327            input,
328            a.encode().unwrap(),
329            "the signing input must not be the full record"
330        );
331    }
332
333    #[test]
334    fn the_signing_input_covers_every_semantic_field() {
335        let base = sample().signing_input().unwrap();
336        for mutate in [
337            (|a: &mut SettlementAttestation| a.issuer_did.push('x'))
338                as fn(&mut SettlementAttestation),
339            |a| a.settlement_id.push('x'),
340            |a| a.unit.issuer_did.push('x'),
341            |a| a.unit.resource_class.push('x'),
342            |a| a.destination_did.push('x'),
343            |a| a.amount_minor += 1,
344            |a| a.settled_at += 1,
345            |a| a.grant_cid = Some(vec![1, 2, 3]),
346        ] {
347            let mut a = sample();
348            mutate(&mut a);
349            assert_ne!(
350                base,
351                a.signing_input().unwrap(),
352                "a semantic field is not covered by the signature"
353            );
354        }
355    }
356
357    #[test]
358    fn a_non_canonical_encoding_is_refused() {
359        // An indefinite-length array carries the same logical content but
360        // different bytes. Accepting it would give one attestation two CIDs.
361        let mut noncanonical = vec![0x9fu8]; // indefinite-length array header
362        let canonical = sample().encode().unwrap();
363        // Skip the definite-length array header (0x8a = array(10)).
364        noncanonical.extend_from_slice(&canonical[1..]);
365        noncanonical.push(0xff); // break
366
367        let err = SettlementAttestation::decode(&noncanonical).unwrap_err();
368        assert!(
369            matches!(err, PayError::AttestationInvalid(_)),
370            "a non-canonical encoding must be refused, got {err:?}"
371        );
372    }
373
374    #[test]
375    fn a_record_with_the_wrong_domain_tag_is_refused() {
376        let mut fields = sample().body_fields();
377        fields[0] = Value::Text("hs-pay-something-else-v1".to_owned());
378        fields.push(Value::Bytes(vec![7u8; 96]));
379        let bytes = encode_canonical(&fields).unwrap();
380        assert!(SettlementAttestation::decode(&bytes).is_err());
381    }
382
383    #[test]
384    fn a_truncated_amount_is_refused() {
385        let mut fields = sample().body_fields();
386        fields[6] = Value::Bytes(vec![0u8; 8]);
387        fields.push(Value::Bytes(vec![7u8; 96]));
388        let bytes = encode_canonical(&fields).unwrap();
389        let err = SettlementAttestation::decode(&bytes).unwrap_err();
390        assert!(matches!(err, PayError::AttestationInvalid(_)));
391    }
392}