Skip to main content

hyprstream_pds/ledger/
allocation.rs

1//! `ai.hyprstream.ledger.allocation` — an issuer-signed grant record (the held
2//! entitlement / inventory line).
3//!
4//! ```json
5//! {
6//!   "lexicon": 1,
7//!   "id": "ai.hyprstream.ledger.allocation",
8//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
9//!     "type": "object",
10//!     "required": ["grant", "unit", "amount", "epoch", "issuer", "holder", "class"],
11//!     "properties": {
12//!       "grant":  { "type": "string", "format": "cid" },
13//!       "unit":   { "type": "object",
14//!                   "required": ["code", "issuer"], "properties": {
15//!                     "code":   { "type": "string" },
16//!                     "issuer": { "type": "string", "format": "did" } } },
17//!       "amount": { "type": "integer", "minimum": 0 },
18//!       "epoch":  { "type": "integer", "minimum": 0 },
19//!       "issuer": { "type": "string", "format": "did" },
20//!       "holder": { "type": "string" },
21//!       "class":  { "type": "string", "enum": ["prepaid", "underwritten"] }
22//!     }
23//! }}}
24//! ```
25//!
26//! - `grant` — the CID of the UCAN grant this allocation realizes (`format: "cid"`
27//!   string; the UCAN lives outside this repo's MST).
28//! - `unit` — the credit unit, which **names its issuer** ([`Unit`]): credits are
29//!   issuer *liabilities* (D8-1), never bearer tokens. There is no bare unit.
30//! - `amount` — the granted amount, in the unit's smallest quantum (`u64`).
31//! - `epoch` — the issuance epoch (`u64`).
32//! - `issuer` — the issuing DID. Must equal `unit.issuer` (an allocation is only
33//!   ever the unit-issuer's own liability).
34//! - `holder` — the subject: a pseudonymous `did:key`/`did:at9p` **or** a pairwise
35//!   per-cell identifier (#928 rule 3). Never forced to a root/`did:web` identity.
36//! - `class` — the grant [`GrantClass`]: `prepaid` (bearer-like, lease-mode-only,
37//!   issuable to a bare `did:key`, needs no identity) vs `underwritten`
38//!   (issuer-relationship, the only detect-mode-eligible class). The class↔mode
39//!   coupling is a protocol rule (#928 rule 4).
40
41use anyhow::{bail, Result};
42
43use super::{
44    map_get_str, map_get_uint, reject_unknown_fields, validate_cid_string, validate_did,
45    validate_subject_id,
46};
47use crate::cid::Cid;
48use crate::dag_cbor::DagCbor;
49
50/// The NSID of this record type.
51pub const COLLECTION_NSID: &str = "ai.hyprstream.ledger.allocation";
52
53/// A credit unit that **names its issuer**.
54///
55/// The issuer is baked into the unit itself, so a credit is inseparable from the
56/// party liable for it (D8-1). `code` is the issuer-scoped unit label (e.g.
57/// `"compute-second"`, `"usd-cents"`) — it is only meaningful relative to
58/// `issuer`, never a global bearer denomination.
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct Unit {
61    /// Issuer-scoped unit label. Non-empty.
62    pub code: String,
63    /// The DID liable for credits denominated in this unit. `format: "did"`.
64    pub issuer: String,
65}
66
67/// The grant class — couples anonymity to spend mode (#928 rule 4).
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub enum GrantClass {
70    /// Bearer-like: paid up front, so the issuer bears no credit risk and needs
71    /// no recourse relationship — issuable to a bare `did:key` with no identity.
72    /// **Restricted to lease/prevention mode**: overspend is made impossible, not
73    /// detected after the fact.
74    Prepaid,
75    /// Postpaid: the issuer has a real bilateral relationship (employment,
76    /// contract, billing) and recovers from cheaters itself. The only
77    /// **detect-mode-eligible** class. The issuer's knowledge of its holder is a
78    /// bilateral relationship, never protocol data.
79    Underwritten,
80}
81
82impl GrantClass {
83    /// The lexicon string form.
84    pub fn as_str(self) -> &'static str {
85        match self {
86            GrantClass::Prepaid => "prepaid",
87            GrantClass::Underwritten => "underwritten",
88        }
89    }
90
91    /// Parse the lexicon string form.
92    pub fn parse(s: &str) -> Result<Self> {
93        match s {
94            "prepaid" => Ok(GrantClass::Prepaid),
95            "underwritten" => Ok(GrantClass::Underwritten),
96            other => bail!("{COLLECTION_NSID}: unknown grant class {other:?}"),
97        }
98    }
99
100    /// Whether this class may be spent in **detect mode**.
101    ///
102    /// Detect mode observes overspend after it happens and relies on *recourse*
103    /// to recover — which requires a relationship with the holder. A prepaid
104    /// bearer grant has no such relationship, so detect mode on it is worthless
105    /// (detection without recourse) *and* impossible to act on (recourse without
106    /// identity). The coupling is therefore a protocol rule, not a policy knob:
107    /// only [`GrantClass::Underwritten`] is detect-mode-eligible.
108    pub fn detect_mode_eligible(self) -> bool {
109        matches!(self, GrantClass::Underwritten)
110    }
111}
112
113/// An `ai.hyprstream.ledger.allocation` record.
114#[derive(Clone, Debug, Eq, PartialEq)]
115pub struct AllocationRecord {
116    /// CID of the UCAN grant this allocation realizes. `format: "cid"`.
117    pub grant: String,
118    /// The credit unit (names its issuer).
119    pub unit: Unit,
120    /// Granted amount, in the unit's smallest quantum.
121    pub amount: u64,
122    /// Issuance epoch.
123    pub epoch: u64,
124    /// Issuing DID. Must equal `unit.issuer`. `format: "did"`.
125    pub issuer: String,
126    /// Subject: a pseudonymous DID or a pairwise per-cell identifier.
127    pub holder: String,
128    /// The grant class.
129    pub class: GrantClass,
130}
131
132impl AllocationRecord {
133    /// Validate and construct a record.
134    pub fn new(
135        grant: impl Into<String>,
136        unit: Unit,
137        amount: u64,
138        epoch: u64,
139        issuer: impl Into<String>,
140        holder: impl Into<String>,
141        class: GrantClass,
142    ) -> Result<Self> {
143        let grant = grant.into();
144        let issuer = issuer.into();
145        let holder = holder.into();
146        validate_cid_string(&grant, "grant")?;
147        validate_did(&issuer)?;
148        validate_did(&unit.issuer)?;
149        if unit.code.is_empty() {
150            bail!("{COLLECTION_NSID}: unit.code must not be empty");
151        }
152        // D8-1: a credit is the *unit-issuer's* liability, so an allocation can
153        // only be issued by that same issuer. This binds the record to its
154        // liability holder structurally rather than by convention.
155        if issuer != unit.issuer {
156            bail!(
157                "{COLLECTION_NSID}: issuer {issuer:?} must equal unit.issuer {:?} \
158                 (credits are the unit-issuer's liability, D8-1)",
159                unit.issuer
160            );
161        }
162        validate_subject_id(&holder, "holder")?;
163        Ok(AllocationRecord {
164            grant,
165            unit,
166            amount,
167            epoch,
168            issuer,
169            holder,
170            class,
171        })
172    }
173
174    /// Encode to canonical DAG-CBOR bytes (deterministic).
175    pub fn to_dag_cbor(&self) -> Vec<u8> {
176        self.to_value().encode()
177    }
178
179    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
180    pub fn cid(&self) -> Cid {
181        Cid::from_dag_cbor(&self.to_dag_cbor())
182    }
183
184    /// Build the typed [`DagCbor`] value form.
185    pub fn to_value(&self) -> DagCbor {
186        let unit = DagCbor::str_map([
187            ("code", DagCbor::Text(self.unit.code.clone())),
188            ("issuer", DagCbor::Text(self.unit.issuer.clone())),
189        ]);
190        DagCbor::str_map([
191            ("grant", DagCbor::Text(self.grant.clone())),
192            ("unit", unit),
193            ("amount", DagCbor::Unsigned(self.amount)),
194            ("epoch", DagCbor::Unsigned(self.epoch)),
195            ("issuer", DagCbor::Text(self.issuer.clone())),
196            ("holder", DagCbor::Text(self.holder.clone())),
197            ("class", DagCbor::Text(self.class.as_str().to_owned())),
198        ])
199    }
200
201    /// Decode canonical DAG-CBOR bytes into a record, validating all fields.
202    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
203        let value = DagCbor::decode(bytes)?;
204        Self::from_value(&value)
205    }
206
207    pub fn from_value(value: &DagCbor) -> Result<Self> {
208        reject_unknown_fields(
209            value,
210            &[
211                "grant", "unit", "amount", "epoch", "issuer", "holder", "class",
212            ],
213            COLLECTION_NSID,
214        )?;
215        let grant = map_get_str(value, "grant", COLLECTION_NSID)?.to_owned();
216        let unit = parse_unit(value.get("unit").ok_or_else(|| {
217            anyhow::anyhow!("{COLLECTION_NSID}: missing required field \"unit\"")
218        })?)?;
219        let amount = map_get_uint(value, "amount", COLLECTION_NSID)?;
220        let epoch = map_get_uint(value, "epoch", COLLECTION_NSID)?;
221        let issuer = map_get_str(value, "issuer", COLLECTION_NSID)?.to_owned();
222        let holder = map_get_str(value, "holder", COLLECTION_NSID)?.to_owned();
223        let class = GrantClass::parse(map_get_str(value, "class", COLLECTION_NSID)?)?;
224        Self::new(grant, unit, amount, epoch, issuer, holder, class)
225    }
226}
227
228fn parse_unit(value: &DagCbor) -> Result<Unit> {
229    reject_unknown_fields(value, &["code", "issuer"], COLLECTION_NSID)?;
230    let code = map_get_str(value, "code", COLLECTION_NSID)?.to_owned();
231    let issuer = map_get_str(value, "issuer", COLLECTION_NSID)?.to_owned();
232    Ok(Unit { code, issuer })
233}
234
235#[cfg(test)]
236mod tests {
237    #![allow(
238        clippy::unwrap_used,
239        clippy::expect_used,
240        clippy::indexing_slicing,
241        clippy::panic
242    )]
243    use super::*;
244
245    const ISSUER: &str = "did:web:issuer.example.com";
246
247    fn unit() -> Unit {
248        Unit {
249            code: "compute-second".into(),
250            issuer: ISSUER.into(),
251        }
252    }
253
254    fn sample() -> AllocationRecord {
255        AllocationRecord::new(
256            "bafyreiexamplegrantcid1234567890abcdef",
257            unit(),
258            1_000,
259            7,
260            ISSUER,
261            "did:key:zHolderSubject",
262            GrantClass::Underwritten,
263        )
264        .expect("valid sample")
265    }
266
267    #[test]
268    fn record_round_trip_same_cid() {
269        let r = sample();
270        let bytes = r.to_dag_cbor();
271        let back = AllocationRecord::from_dag_cbor(&bytes).expect("round-trip");
272        assert_eq!(r, back);
273        assert_eq!(r.cid(), back.cid());
274        // Canonical: reserialize(decode(bytes)) == bytes.
275        assert_eq!(back.to_dag_cbor(), bytes);
276    }
277
278    #[test]
279    fn record_fields_canonical_order() {
280        let r = sample();
281        let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
282        let map = v.as_map().expect("map");
283        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
284        // pure lexicographic byte order.
285        assert_eq!(
286            keys,
287            vec!["amount", "class", "epoch", "grant", "holder", "issuer", "unit"]
288        );
289    }
290
291    #[test]
292    fn no_legal_identity_field_is_representable() {
293        // A record carrying a legal-identity-looking field must not decode: the
294        // schema has no such field, and unknown fields are rejected (#928 rule 1).
295        let mut v = sample().to_value();
296        if let DagCbor::Map(ref mut pairs) = v {
297            pairs.push((
298                DagCbor::Text("legalName".into()),
299                DagCbor::Text("Jane Doe".into()),
300            ));
301            pairs.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
302        }
303        let err =
304            AllocationRecord::from_value(&v).expect_err("legal-identity field must be rejected");
305        assert!(
306            err.to_string().contains("unknown field"),
307            "unexpected: {err:#}"
308        );
309    }
310
311    #[test]
312    fn pairwise_holder_accepted() {
313        // A pairwise per-cell identifier (not a DID) is a valid holder (#928 rule 3).
314        let r = AllocationRecord::new(
315            "bafyreiexamplegrantcid1234567890abcdef",
316            unit(),
317            5,
318            1,
319            ISSUER,
320            "pairwise:cell42:8f3ad9c0e1",
321            GrantClass::Prepaid,
322        )
323        .expect("pairwise holder must be accepted");
324        assert_eq!(
325            AllocationRecord::from_dag_cbor(&r.to_dag_cbor()).expect("round-trip"),
326            r
327        );
328    }
329
330    #[test]
331    fn prepaid_issuable_to_bare_did_key() {
332        // Prepaid (bearer-like) is issuable to a bare did:key with no identity.
333        AllocationRecord::new(
334            "bafyreiexamplegrantcid1234567890abcdef",
335            unit(),
336            5,
337            1,
338            ISSUER,
339            "did:key:zBareKeyNoIdentity",
340            GrantClass::Prepaid,
341        )
342        .expect("prepaid to bare did:key must be accepted");
343    }
344
345    #[test]
346    fn class_mode_coupling() {
347        // Only underwritten is detect-mode eligible (#928 rule 4).
348        assert!(!GrantClass::Prepaid.detect_mode_eligible());
349        assert!(GrantClass::Underwritten.detect_mode_eligible());
350    }
351
352    #[test]
353    fn unit_names_its_issuer_and_binds_liability() {
354        // The unit carries its issuer, and the top-level issuer must match it
355        // (D8-1: a credit is the unit-issuer's liability).
356        let mismatched = AllocationRecord::new(
357            "bafyreiexamplegrantcid1234567890abcdef",
358            unit(),
359            5,
360            1,
361            "did:web:other.example.com",
362            "did:key:zHolder",
363            GrantClass::Underwritten,
364        );
365        assert!(
366            mismatched.is_err(),
367            "issuer != unit.issuer must be rejected"
368        );
369    }
370
371    #[test]
372    fn record_validates_formats() {
373        // Bad grant cid.
374        assert!(
375            AllocationRecord::new("x", unit(), 1, 1, ISSUER, "did:key:z", GrantClass::Prepaid)
376                .is_err()
377        );
378        // Bad issuer did.
379        assert!(AllocationRecord::new(
380            "bafyreiexamplegrantcid1234567890abcdef",
381            unit(),
382            1,
383            1,
384            "not-a-did",
385            "did:key:z",
386            GrantClass::Prepaid
387        )
388        .is_err());
389        // Empty holder.
390        assert!(AllocationRecord::new(
391            "bafyreiexamplegrantcid1234567890abcdef",
392            unit(),
393            1,
394            1,
395            ISSUER,
396            "",
397            GrantClass::Prepaid
398        )
399        .is_err());
400        // Unknown class string on decode.
401        let mut v = sample().to_value();
402        if let DagCbor::Map(ref mut pairs) = v {
403            for (k, val) in pairs.iter_mut() {
404                if k.as_str().ok() == Some("class") {
405                    *val = DagCbor::Text("overdraft".into());
406                }
407            }
408        }
409        assert!(AllocationRecord::from_value(&v).is_err());
410    }
411
412    #[test]
413    fn grant_and_cids_are_strings_not_links() {
414        let v = sample().to_value();
415        assert!(matches!(v.get("grant"), Some(DagCbor::Text(_))));
416    }
417}