hyprstream_pds/ledger/mod.rs
1//! `ai.hyprstream.ledger.*` — the cellular-ledger inventory lexicons (#924).
2//!
3//! Three DAG-CBOR record types form the **holder-controlled inventory**: the
4//! signed entitlements, usage receipts, and ledger heads that live in a holder's
5//! own atproto repo (its signed PDS commit is the only signature these records
6//! need — see [`crate::commit`]).
7//!
8//! - [`allocation::AllocationRecord`] (`ai.hyprstream.ledger.allocation`) — an
9//! issuer-signed grant: the held entitlement. References the UCAN grant CID,
10//! carries the issuer-named [`allocation::Unit`], amount, epoch, issuer DID,
11//! holder (subject), and the grant [`allocation::GrantClass`].
12//! - [`receipt::ReceiptRecord`] (`ai.hyprstream.ledger.receipt`) — a dual-signed
13//! usage record binding **both** principals (spender + host, the #681
14//! two-principal vocabulary), the referenced allocation CID, the transfer id,
15//! and the quantum spent.
16//! - [`checkpoint::CheckpointRecord`] (`ai.hyprstream.ledger.checkpoint`) — a
17//! signed ledger head (seq, head hash, state roots) that **references** — never
18//! embeds — an external anchor.
19//!
20//! # Pseudonymity constraints (the #928 charter — review-blockers)
21//!
22//! These lexicons are the P0 target of the pseudonymity charter. The rules are
23//! enforced **structurally** — by the shape of the records, not by a runtime
24//! check that could be bypassed:
25//!
26//! 1. **No legal-identity field, anywhere.** Every record has a frozen field set
27//! and decoding rejects unknown fields, so a `legalName`/`kyc`/… field is not
28//! representable: it fails to decode. Audit binds pseudonyms only.
29//! 2. **Pairwise per-cell subject identifiers.** The `holder`/`spender`/`host`
30//! fields are validated by [`validate_subject_id`], which accepts a `did:key`
31//! / `did:at9p` *or* an opaque pairwise identifier — it never *requires* a
32//! DID, let alone a `did:web`. A cell-scoped pairwise ID drops straight in.
33//! 3. **The unit names its issuer.** [`allocation::Unit`] bakes the issuer DID
34//! into the unit itself — there is no bare unit string. Credits are issuer
35//! *liabilities* (D8-1), never bearer tokens; [`allocation::AllocationRecord`]
36//! additionally requires the top-level `issuer` to equal `unit.issuer`.
37//! 4. **Grant class couples anonymity to spend mode.**
38//! [`allocation::GrantClass::Prepaid`] is bearer-like, issuable to a bare
39//! `did:key`, and lease-mode-only; [`allocation::GrantClass::Underwritten`]
40//! is the only detect-mode-eligible class (see
41//! [`allocation::GrantClass::detect_mode_eligible`]).
42//!
43//! # Encoding
44//!
45//! Like the other hyprstream lexicons, every record is **DAG-CBOR** with
46//! canonical (pure-lexicographic) map-key order applied by the encoder, so
47//! callers construct fields in any order. Each record has a frozen field set:
48//! decoding rejects unknown fields. Optional fields are *omitted* from the
49//! encoded map when absent (never encoded as `null`). CID references are carried
50//! as `format: "cid"` **strings** (not DAG-CBOR links): the referenced blocks
51//! (UCAN grants, allocations, external ledger state) live outside this repo's
52//! MST, so a tag-42 link would be a false claim of local containment — the same
53//! reasoning [`crate::record::ModelRecord::current_oid`] documents.
54
55use anyhow::{bail, ensure, Result};
56
57use crate::dag_cbor::DagCbor;
58
59pub mod allocation;
60pub mod checkpoint;
61pub mod receipt;
62
63pub use allocation::{AllocationRecord, GrantClass, Unit};
64pub use checkpoint::{CheckpointRecord, StateRoot};
65pub use receipt::ReceiptRecord;
66
67// ── shared field accessors ──────────────────────────────────────────────────
68
69/// Read a required string field, attributing errors to `nsid`.
70pub(crate) fn map_get_str<'a>(value: &'a DagCbor, key: &str, nsid: &str) -> Result<&'a str> {
71 value
72 .get(key)
73 .ok_or_else(|| anyhow::anyhow!("{nsid}: missing required field {key:?}"))?
74 .as_str()
75}
76
77/// Read a required unsigned-integer field, attributing errors to `nsid`.
78pub(crate) fn map_get_uint(value: &DagCbor, key: &str, nsid: &str) -> Result<u64> {
79 value
80 .get(key)
81 .ok_or_else(|| anyhow::anyhow!("{nsid}: missing required field {key:?}"))?
82 .as_unsigned()
83}
84
85/// Read an optional string field. Returns `None` when omitted; an error if it is
86/// present but not a text string.
87pub(crate) fn map_get_opt_str<'a>(value: &'a DagCbor, key: &str) -> Result<Option<&'a str>> {
88 match value.get(key) {
89 None => Ok(None),
90 Some(v) => Ok(Some(v.as_str()?)),
91 }
92}
93
94// ── field validators (lexicon formats) ──────────────────────────────────────
95
96/// A DID string — must start with `did:` and carry a non-empty, whitespace-free
97/// `method:identifier`. Both `did:web`, `did:key`, and `did:at9p` are accepted.
98/// Used for fields that name a *real, signing* identity (an issuer), never for a
99/// pseudonymous subject (see [`validate_subject_id`]).
100pub(crate) fn validate_did(s: &str) -> Result<()> {
101 ensure!(s.starts_with("did:"), "did must start with \"did:\": {s:?}");
102 let rest = &s[4..];
103 ensure!(!rest.is_empty(), "did must have a method: {s:?}");
104 ensure!(
105 !rest.chars().any(char::is_whitespace),
106 "did must not contain whitespace: {s:?}"
107 );
108 let mut parts = rest.splitn(2, ':');
109 let method = parts.next().unwrap_or("");
110 let id = parts.next().unwrap_or("");
111 ensure!(
112 !method.is_empty() && !id.is_empty(),
113 "did must be \"did:<method>:<id>\": {s:?}"
114 );
115 Ok(())
116}
117
118/// A **pseudonymous subject identifier** (`holder`/`spender`/`host`).
119///
120/// The #928 charter (rule 3) requires these fields to carry either a
121/// pseudonymous DID (`did:key`/`did:at9p`) *or* an opaque **pairwise per-cell
122/// identifier** — an issuer-linkable, cell-unlinkable string the subject
123/// presents differently to each cell. We therefore accept any non-empty,
124/// whitespace-free token and deliberately **do not** require a DID shape: forcing
125/// a DID here would forbid the pairwise-ID presentation the charter mandates and
126/// would push subjects toward a stable global identity. (A `did:web` — an opt-in
127/// linkage to a domain — is likewise never required for participation.)
128pub(crate) fn validate_subject_id(s: &str, field: &str) -> Result<()> {
129 ensure!(!s.is_empty(), "{field} must not be empty");
130 ensure!(
131 !s.chars().any(char::is_whitespace),
132 "{field} must not contain whitespace: {s:?}"
133 );
134 Ok(())
135}
136
137/// `format: "cid"` — a CIDv1 (`b…`/`z…`) or CIDv0 (`Qm…`) string. Mirrors the
138/// `currentOid` validation in [`crate::record`]: we carry external content
139/// addresses as strings and reject the obviously-bogus forms.
140pub(crate) fn validate_cid_string(s: &str, field: &str) -> Result<()> {
141 ensure!(!s.is_empty(), "{field} cid string must be non-empty");
142 let ok = (s.starts_with('b') && s.len() > 8)
143 || (s.starts_with('z') && s.len() > 8)
144 || (s.starts_with("Qm") && s.len() > 8);
145 ensure!(
146 ok,
147 "{field} must be a CIDv1 (b/z…) or CIDv0 (Qm…) string: {s:?}"
148 );
149 Ok(())
150}
151
152/// A required free-form string that must not be empty or contain whitespace
153/// (`field` names it for the error message). Used for opaque locators (transfer
154/// ids, anchor references) that are neither DIDs nor CIDs.
155pub(crate) fn validate_token(s: &str, field: &str) -> Result<()> {
156 ensure!(!s.is_empty(), "{field} must not be empty");
157 ensure!(
158 !s.chars().any(char::is_whitespace),
159 "{field} must not contain whitespace: {s:?}"
160 );
161 Ok(())
162}
163
164/// Reject any map key not in `allowed`, attributing the error to `nsid`.
165pub(crate) fn reject_unknown_fields(value: &DagCbor, allowed: &[&str], nsid: &str) -> Result<()> {
166 let map = value.as_map()?;
167 for (k, _v) in map {
168 let key = k.as_str()?;
169 if !allowed.contains(&key) {
170 bail!("{nsid}: unknown field {key:?} (frozen lexicon fields: {allowed:?})");
171 }
172 }
173 Ok(())
174}