Skip to main content

hyprstream_pds/ledger/
receipt.rs

1//! `ai.hyprstream.ledger.receipt` — a dual-signed usage record.
2//!
3//! ```json
4//! {
5//!   "lexicon": 1,
6//!   "id": "ai.hyprstream.ledger.receipt",
7//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
8//!     "type": "object",
9//!     "required": ["allocation", "spender", "host", "transferId", "quantum"],
10//!     "properties": {
11//!       "allocation": { "type": "string", "format": "cid" },
12//!       "spender":    { "type": "string" },
13//!       "host":       { "type": "string" },
14//!       "transferId": { "type": "string" },
15//!       "quantum":    { "type": "integer", "minimum": 0 }
16//!     }
17//! }}}
18//! ```
19//!
20//! A receipt records one spend against a held [`crate::ledger::AllocationRecord`].
21//! It binds **both** principals — the #681 two-principal vocabulary — so the
22//! record attests who spent and who served:
23//!
24//! - `allocation` — CID of the allocation/grant the spend draws down (`format:
25//!   "cid"` string).
26//! - `spender` — the spending principal. For a **pseudonymous-tier** service this
27//!   is the subject's **pairwise per-cell identifier** (#928 rule 7), never a
28//!   root DID — a cell sees only the identifier the subject presents to it.
29//! - `host` — the serving principal (the second of the two principals; the party
30//!   on whose infrastructure the spend occurred).
31//! - `transferId` — the spend's idempotency key. The write path derives the
32//!   receipt's rkey from it, giving at-least-once (idempotent) receipt delivery:
33//!   re-publishing the same `transferId` advances the same record.
34//! - `quantum` — the amount spent, in the allocation unit's smallest quantum.
35
36use anyhow::Result;
37
38use super::{
39    map_get_str, map_get_uint, reject_unknown_fields, validate_cid_string, validate_subject_id,
40    validate_token,
41};
42use crate::cid::Cid;
43use crate::dag_cbor::DagCbor;
44
45/// The NSID of this record type.
46pub const COLLECTION_NSID: &str = "ai.hyprstream.ledger.receipt";
47
48/// An `ai.hyprstream.ledger.receipt` record.
49#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct ReceiptRecord {
51    /// CID of the allocation/grant this spend draws down. `format: "cid"`.
52    pub allocation: String,
53    /// Spending principal — a pairwise per-cell id for pseudonymous-tier spends.
54    pub spender: String,
55    /// Serving principal (the second of the two #681 principals).
56    pub host: String,
57    /// Idempotency key; the receipt's rkey is derived from it.
58    pub transfer_id: String,
59    /// Amount spent, in the allocation unit's smallest quantum.
60    pub quantum: u64,
61}
62
63impl ReceiptRecord {
64    /// Validate and construct a record.
65    pub fn new(
66        allocation: impl Into<String>,
67        spender: impl Into<String>,
68        host: impl Into<String>,
69        transfer_id: impl Into<String>,
70        quantum: u64,
71    ) -> Result<Self> {
72        let allocation = allocation.into();
73        let spender = spender.into();
74        let host = host.into();
75        let transfer_id = transfer_id.into();
76        validate_cid_string(&allocation, "allocation")?;
77        validate_subject_id(&spender, "spender")?;
78        validate_subject_id(&host, "host")?;
79        validate_token(&transfer_id, "transferId")?;
80        Ok(ReceiptRecord {
81            allocation,
82            spender,
83            host,
84            transfer_id,
85            quantum,
86        })
87    }
88
89    /// Encode to canonical DAG-CBOR bytes (deterministic).
90    pub fn to_dag_cbor(&self) -> Vec<u8> {
91        self.to_value().encode()
92    }
93
94    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
95    pub fn cid(&self) -> Cid {
96        Cid::from_dag_cbor(&self.to_dag_cbor())
97    }
98
99    /// Build the typed [`DagCbor`] value form.
100    pub fn to_value(&self) -> DagCbor {
101        DagCbor::str_map([
102            ("allocation", DagCbor::Text(self.allocation.clone())),
103            ("spender", DagCbor::Text(self.spender.clone())),
104            ("host", DagCbor::Text(self.host.clone())),
105            ("transferId", DagCbor::Text(self.transfer_id.clone())),
106            ("quantum", DagCbor::Unsigned(self.quantum)),
107        ])
108    }
109
110    /// Decode canonical DAG-CBOR bytes into a record, validating all fields.
111    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
112        let value = DagCbor::decode(bytes)?;
113        Self::from_value(&value)
114    }
115
116    pub fn from_value(value: &DagCbor) -> Result<Self> {
117        reject_unknown_fields(
118            value,
119            &["allocation", "spender", "host", "transferId", "quantum"],
120            COLLECTION_NSID,
121        )?;
122        let allocation = map_get_str(value, "allocation", COLLECTION_NSID)?.to_owned();
123        let spender = map_get_str(value, "spender", COLLECTION_NSID)?.to_owned();
124        let host = map_get_str(value, "host", COLLECTION_NSID)?.to_owned();
125        let transfer_id = map_get_str(value, "transferId", COLLECTION_NSID)?.to_owned();
126        let quantum = map_get_uint(value, "quantum", COLLECTION_NSID)?;
127        Self::new(allocation, spender, host, transfer_id, quantum)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    #![allow(
134        clippy::unwrap_used,
135        clippy::expect_used,
136        clippy::indexing_slicing,
137        clippy::panic
138    )]
139    use super::*;
140
141    fn sample() -> ReceiptRecord {
142        ReceiptRecord::new(
143            "bafyreiexamplealloccid1234567890abcdef",
144            "pairwise:cell42:8f3ad9c0e1",
145            "did:key:zHostNode",
146            "transfer-01HXYZ",
147            25,
148        )
149        .expect("valid sample")
150    }
151
152    #[test]
153    fn record_round_trip_same_cid() {
154        let r = sample();
155        let bytes = r.to_dag_cbor();
156        let back = ReceiptRecord::from_dag_cbor(&bytes).expect("round-trip");
157        assert_eq!(r, back);
158        assert_eq!(r.cid(), back.cid());
159        assert_eq!(back.to_dag_cbor(), bytes);
160    }
161
162    #[test]
163    fn record_fields_canonical_order() {
164        let r = sample();
165        let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
166        let map = v.as_map().expect("map");
167        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
168        assert_eq!(
169            keys,
170            vec!["allocation", "host", "quantum", "spender", "transferId"]
171        );
172    }
173
174    #[test]
175    fn pairwise_spender_accepted() {
176        // Receipts for pseudonymous-tier services bind the pairwise id, not a
177        // root DID (#928 rule 7). A non-DID pairwise spender must be accepted.
178        let r = sample();
179        assert!(!r.spender.starts_with("did:"));
180        assert_eq!(
181            ReceiptRecord::from_dag_cbor(&r.to_dag_cbor()).expect("round-trip"),
182            r
183        );
184    }
185
186    #[test]
187    fn no_legal_identity_field_is_representable() {
188        let mut v = sample().to_value();
189        if let DagCbor::Map(ref mut pairs) = v {
190            pairs.push((
191                DagCbor::Text("payerLegalId".into()),
192                DagCbor::Text("SSN".into()),
193            ));
194            pairs.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
195        }
196        assert!(ReceiptRecord::from_value(&v).is_err());
197    }
198
199    #[test]
200    fn record_validates_formats() {
201        // Bad allocation cid.
202        assert!(ReceiptRecord::new("x", "did:key:z", "did:key:h", "t", 1).is_err());
203        // Empty spender.
204        assert!(ReceiptRecord::new(
205            "bafyreiexamplealloccid1234567890abcdef",
206            "",
207            "did:key:h",
208            "t",
209            1
210        )
211        .is_err());
212        // Empty transferId.
213        assert!(ReceiptRecord::new(
214            "bafyreiexamplealloccid1234567890abcdef",
215            "did:key:z",
216            "did:key:h",
217            "",
218            1
219        )
220        .is_err());
221    }
222}