Skip to main content

hyprstream_ledger/
types.rs

1//! Core data model for the accounting plane (plan §2.0).
2//!
3//! Everything here is `no_std`-friendly in spirit (no I/O, no clock, no tokio) so
4//! the whole crate builds for `wasm32-unknown-unknown`. Amounts are `u128` minor
5//! units; **no floats anywhere** (INV grep-gate: `f32|f64` forbidden outside
6//! benches).
7
8use bitflags::bitflags;
9use ciborium::value::Value;
10use serde::{Deserialize, Serialize};
11
12use crate::errors::LedgerError;
13
14/// A decentralized identifier, carried opaquely (`did:web` / `did:key` /
15/// `did:at9p`). The ledger crate treats DIDs as pseudonymous strings and never
16/// resolves or interprets them — per the #924 P0 constraint, **no legal-identity
17/// fields** live in this model; a DID is the only principal handle.
18#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
19pub struct Did(pub String);
20
21impl Did {
22    /// Borrow the DID string.
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26}
27
28impl From<&str> for Did {
29    fn from(s: &str) -> Self {
30        Did(s.to_owned())
31    }
32}
33
34/// Opaque content identifier for a UCAN allocation grant. Kept as raw bytes so
35/// this crate carries **no `hyprstream-pds` dependency** (D3 crate boundary): the
36/// ledger only correlates a spend to its grant, it never parses the CID.
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
38pub struct Cid(pub Vec<u8>);
39
40/// A resource unit. INV-1(a): **the unit names its issuer.** Two units with
41/// different issuers are different units, full stop — there is no bearer-token
42/// representation of value that omits the issuer.
43#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
44pub struct UnitId {
45    /// The resource authority — the liability holder for this unit.
46    pub issuer: Did,
47    /// e.g. `"gpu.h100.seconds"`.
48    pub resource_class: String,
49}
50
51/// What an account is *for*. The purpose participates in the account id, so two
52/// accounts of the same owner/unit but different purpose are distinct rows.
53#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
54pub enum Purpose {
55    /// Spendable balance held by an owner.
56    Available,
57    /// Funds escrowed toward a peer cell (home side of a tranche, §2f).
58    Escrow {
59        /// The peer cell the escrow is pledged to.
60        peer_cell: Did,
61    },
62    /// The issuer's own liability account — issuance debits this (INV-1). Grows
63    /// as supply is issued; the "money supply" per unit *is* this balance.
64    IssuerLiability,
65    /// Remotely-funded spendable balance (remote side of a tranche, §2f).
66    Remote {
67        /// The home cell that pre-funded this balance.
68        home_cell: Did,
69    },
70    /// A posted bond (Phase 3 slashing collateral); modelled as a ledger account
71    /// so a slash is just a transfer to the injured party.
72    Bond,
73}
74
75/// 128-bit account identity. Deterministic function of the canonical tuple, so
76/// any party that knows `(ledger_id, owner, unit, purpose)` can derive it with
77/// no allocation-time coordination, and it is TigerBeetle-compatible (TB account
78/// ids are `u128`).
79///
80/// PLAN DECISION 1: `AccountId = blake3_128(canonical_dag_cbor(ledger_id,
81/// owner, unit, purpose))`. The unit already names its issuer (INV-1), so the
82/// issuer is baked into the id transitively.
83///
84/// # Interop contract — normative account-id encoding
85///
86/// The hashed body is **canonical DAG-CBOR** (the same wire format
87/// `hyprstream-pds::dag_cbor` emits: sorted map keys, minimal-width integers,
88/// definite lengths). Account ids are a contract other implementations
89/// re-derive, so the byte layout below is normative — it supersedes the earlier
90/// bespoke length-prefixed encoding.
91///
92/// The body is a single definite-length DAG-CBOR **array** in this fixed order
93/// (no maps, so canonicality needs no key-sorting):
94///
95/// ```text
96/// [
97///   "hs-ledger-account-id-v1",   // domain-separation tag
98///   <ledger_id  : tstr>,
99///   <owner      : tstr>,
100///   <unit_issuer: tstr>,          // unit.issuer
101///   <unit_code  : tstr>,          // unit.resource_class
102///   <purpose    : purpose-encoding>
103/// ]
104/// ```
105///
106/// where `purpose-encoding` is itself canonical DAG-CBOR:
107///
108/// | `Purpose` | encoding |
109/// |---|---|
110/// | `Available` | unsigned `0` |
111/// | `Escrow { peer_cell }` | `[1, <peer_cell:tstr>]` |
112/// | `IssuerLiability` | unsigned `2` |
113/// | `Remote { home_cell }` | `[3, <home_cell:tstr>]` |
114/// | `Bond` | unsigned `4` |
115///
116/// The id is the 128-bit blake3 XOF (`blake3::Hasher::finalize_xof`, 16 bytes,
117/// read big-endian into a `u128`) of those bytes. Two implementations that agree
118/// on this layout derive byte-identical ids.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
120pub struct AccountId(pub u128);
121
122impl AccountId {
123    /// Derive the canonical account id over the normative DAG-CBOR encoding
124    /// (see the [`AccountId`] rustdoc for the interop wire format).
125    ///
126    /// Returns `Result` because the CBOR serializer is fallible at the API
127    /// level (`ciborium::into_writer`). Over this fixed set of small types
128    /// (text strings, small unsigned ints, definite-length arrays) an encode
129    /// error is unreachable in practice; rather than `unwrap` (lint-denied) we
130    /// map the impossible failure to [`LedgerError::Internal`], which is
131    /// fail-closed and retryable. Call sites propagate it.
132    pub fn derive(
133        ledger_id: &Did,
134        owner: &Did,
135        unit: &UnitId,
136        purpose: &Purpose,
137    ) -> Result<Self, LedgerError> {
138        let value = Value::Array(vec![
139            // Domain-separation tag, carried inside the canonical body so the
140            // entire hashed input is canonical DAG-CBOR.
141            Value::Text("hs-ledger-account-id-v1".to_owned()),
142            Value::Text(ledger_id.0.clone()),
143            Value::Text(owner.0.clone()),
144            Value::Text(unit.issuer.0.clone()),
145            Value::Text(unit.resource_class.clone()),
146            canonical_purpose(purpose),
147        ]);
148        let mut h = blake3::Hasher::new();
149        ciborium::into_writer(&value, &mut h).map_err(|e| {
150            LedgerError::Internal(format!("account-id DAG-CBOR encode failed: {e}"))
151        })?;
152        let mut out = [0u8; 16];
153        h.finalize_xof().fill(&mut out);
154        Ok(AccountId(u128::from_be_bytes(out)))
155    }
156}
157
158/// Canonical DAG-CBOR encoding of [`Purpose`] (see the [`AccountId`] interop
159/// table). Fixed-shape: a bare unsigned int for the leaf purposes, a
160/// `[tag, did]` array for the carried-DID purposes — definite-length and
161/// minimal-width, so ciborium emits canonical bytes with no map sorting needed.
162fn canonical_purpose(purpose: &Purpose) -> Value {
163    match purpose {
164        Purpose::Available => Value::Integer(0u64.into()),
165        Purpose::Escrow { peer_cell } => Value::Array(vec![
166            Value::Integer(1u64.into()),
167            Value::Text(peer_cell.0.clone()),
168        ]),
169        Purpose::IssuerLiability => Value::Integer(2u64.into()),
170        Purpose::Remote { home_cell } => Value::Array(vec![
171            Value::Integer(3u64.into()),
172            Value::Text(home_cell.0.clone()),
173        ]),
174        Purpose::Bond => Value::Integer(4u64.into()),
175    }
176}
177
178bitflags! {
179    /// TigerBeetle-compatible account flags.
180    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
181    pub struct AccountFlags: u32 {
182        /// The normal case: a debit-constrained account may never let
183        /// `debits_posted + debits_pending` exceed `credits_posted`. Issuer
184        /// liability accounts clear this flag (they are the source of supply).
185        const DEBITS_MUST_NOT_EXCEED_CREDITS = 0b0000_0001;
186    }
187}
188
189impl AccountFlags {
190    /// The default flags for a purpose: everything is debit-constrained except an
191    /// issuer's own liability account.
192    pub fn for_purpose(purpose: &Purpose) -> Self {
193        match purpose {
194            Purpose::IssuerLiability => AccountFlags::empty(),
195            _ => AccountFlags::DEBITS_MUST_NOT_EXCEED_CREDITS,
196        }
197    }
198}
199
200/// TigerBeetle-compatible account state (plan §2.0). The four counters are `u128`
201/// minor units. `*_posted` only ever grow; `*_pending` rise on reserve and fall
202/// on post/void/expire. Balances are differences of counters, never stored.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct Account {
205    /// Derived identity (see [`AccountId::derive`]).
206    pub id: AccountId,
207    /// Denormalized unit; checked to match on every transfer touching this account.
208    pub unit: UnitId,
209    /// Denormalized purpose; issuance checks this directly instead of inferring
210    /// authority from flags.
211    pub purpose: Purpose,
212    /// Held-but-not-settled debits (outstanding reservations on the debit side).
213    pub debits_pending: u128,
214    /// Settled debits — monotonically increasing.
215    pub debits_posted: u128,
216    /// Held-but-not-settled credits.
217    pub credits_pending: u128,
218    /// Settled credits — monotonically increasing.
219    pub credits_posted: u128,
220    /// Behavioural flags (overdraft constraint, …).
221    pub flags: AccountFlags,
222}
223
224impl Account {
225    /// A freshly opened account with zeroed counters.
226    pub fn new(id: AccountId, unit: UnitId, purpose: Purpose, flags: AccountFlags) -> Self {
227        Account {
228            id,
229            unit,
230            purpose,
231            debits_pending: 0,
232            debits_posted: 0,
233            credits_pending: 0,
234            credits_posted: 0,
235            flags,
236        }
237    }
238
239    /// Amount available to spend for a debit-constrained account: settled net
240    /// credit minus everything already promised. Pending **credits** do NOT count
241    /// (they may still void) — the TigerBeetle rule. Saturating so it can never
242    /// underflow into a huge number.
243    pub fn available(&self) -> u128 {
244        self.credits_posted
245            .saturating_sub(self.debits_posted)
246            .saturating_sub(self.debits_pending)
247    }
248
249    /// Whether this account enforces the overdraft floor.
250    pub fn is_debit_constrained(&self) -> bool {
251        self.flags
252            .contains(AccountFlags::DEBITS_MUST_NOT_EXCEED_CREDITS)
253    }
254
255    /// A read-only projection of balances at a given journal sequence.
256    pub fn view(&self, as_of_seq: u64) -> BalanceView {
257        BalanceView {
258            debits_pending: self.debits_pending,
259            debits_posted: self.debits_posted,
260            credits_pending: self.credits_pending,
261            credits_posted: self.credits_posted,
262            available: self.available(),
263            as_of_seq,
264        }
265    }
266}
267
268/// Everything needed to open (or idempotently re-open) an account.
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270pub struct AccountSpec {
271    /// The cell ledger this account lives in.
272    pub ledger_id: Did,
273    /// The owning principal (a pseudonymous DID; may be a group owner DID).
274    pub owner: Did,
275    /// The unit (names its issuer).
276    pub unit: UnitId,
277    /// What the account is for.
278    pub purpose: Purpose,
279    /// Flags; use [`AccountFlags::for_purpose`] for the sensible default.
280    pub flags: AccountFlags,
281}
282
283impl AccountSpec {
284    /// Convenience constructor deriving default flags from the purpose.
285    pub fn new(ledger_id: Did, owner: Did, unit: UnitId, purpose: Purpose) -> Self {
286        let flags = AccountFlags::for_purpose(&purpose);
287        AccountSpec {
288            ledger_id,
289            owner,
290            unit,
291            purpose,
292            flags,
293        }
294    }
295
296    /// The derived id for this spec (see [`AccountId::derive`]).
297    pub fn account_id(&self) -> Result<AccountId, LedgerError> {
298        AccountId::derive(&self.ledger_id, &self.owner, &self.unit, &self.purpose)
299    }
300}
301
302/// Client-supplied 128-bit transfer id (plan §2c). **The id IS the idempotency
303/// key**: replaying it returns the original outcome (including original errors).
304#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
305pub struct TransferId(pub u128);
306
307/// Single-phase issuance (INV-1): the only entry point that grows a unit's
308/// supply. The debit side MUST be the issuer's `IssuerLiability` account for the
309/// unit; the credit side is the destination.
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311pub struct IssueTransfer {
312    /// Idempotency key.
313    pub id: TransferId,
314    /// The issuer's liability account (debit side; must be `Purpose::IssuerLiability`).
315    pub issuer_liability: AccountId,
316    /// Where the freshly-issued credit lands.
317    pub destination: AccountId,
318    /// The unit being issued (issuer must match the liability account owner).
319    pub unit: UnitId,
320    /// Amount in minor units; must be `> 0`.
321    pub amount: u128,
322    /// The grant this issuance backs, if any.
323    pub grant_cid: Option<Cid>,
324    /// Opaque correlation (e.g. request hash).
325    pub user_data: [u8; 32],
326}
327
328/// A value movement between two accounts of the **same unit** (INV-1(b): one
329/// `unit` field, never two — cross-issuer movement is two linked transfers).
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331pub struct Transfer {
332    /// Idempotency key (for `reserve` this is also the pending reservation id).
333    pub id: TransferId,
334    /// Account debited.
335    pub debit_account: AccountId,
336    /// Account credited.
337    pub credit_account: AccountId,
338    /// The unit; must equal both accounts' unit.
339    pub unit: UnitId,
340    /// Amount in minor units; must be `> 0`.
341    pub amount: u128,
342    /// The UCAN allocation this spend draws on.
343    pub grant_cid: Option<Cid>,
344    /// Opaque correlation.
345    pub user_data: [u8; 32],
346}
347
348/// The lifecycle state of a two-phase reservation (plan §2b).
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
350pub enum PendingState {
351    /// Held, not yet resolved.
352    Pending,
353    /// Second phase committed as a post (full or partial).
354    Posted,
355    /// Second phase committed as a void.
356    Voided,
357    /// Deadline passed before a second phase committed.
358    Expired,
359}
360
361impl PendingState {
362    /// Whether the reservation has reached a terminal state.
363    pub fn is_terminal(self) -> bool {
364        !matches!(self, PendingState::Pending)
365    }
366}
367
368/// A tracked phase-1 reservation. Held in `CF(pending)` in RocksLedger; a
369/// `BTreeMap` entry in MemLedger.
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371pub struct PendingReservation {
372    /// The reserve transfer (its `id` is the pending id).
373    pub transfer: Transfer,
374    /// Logical deadline (ledger clock seconds) after which the hold expires.
375    pub deadline: u64,
376    /// Current lifecycle state.
377    pub state: PendingState,
378}
379
380/// What a successful op did — the positive half of an [`Outcome`].
381#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
382pub enum TransferResult {
383    /// Supply issued (`credit`).
384    Issued,
385    /// A single-phase or posted two-phase settlement.
386    Applied {
387        /// Amount moved to posted.
388        posted: u128,
389        /// Amount released back from pending (partial-post remainder; `0` for
390        /// single-phase and full posts).
391        released: u128,
392    },
393    /// A phase-1 hold was placed (`reserve`).
394    Reserved,
395    /// A reservation was cancelled (`void`).
396    Voided,
397    /// A reservation expired (produced by the sweep or on-touch).
398    Expired,
399    /// An account was created (`open_account` via the journal).
400    Opened,
401}
402
403/// The recorded result of an operation. Stored under the op's `TransferId`; a
404/// replay returns this **verbatim** (PLAN DECISION 3 — original result, including
405/// original errors).
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407pub struct Outcome {
408    /// The business result: `Ok` with what happened, or the deterministic error.
409    pub result: Result<TransferResult, crate::errors::LedgerError>,
410    /// The journal sequence that recorded this outcome.
411    pub seq: u64,
412}
413
414impl Outcome {
415    /// Whether the op succeeded.
416    pub fn is_ok(&self) -> bool {
417        self.result.is_ok()
418    }
419}
420
421/// Read-only balance projection returned by [`crate::LedgerBackend::balance`].
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
423pub struct BalanceView {
424    /// Outstanding debit holds.
425    pub debits_pending: u128,
426    /// Settled debits.
427    pub debits_posted: u128,
428    /// Outstanding credit holds.
429    pub credits_pending: u128,
430    /// Settled credits.
431    pub credits_posted: u128,
432    /// Spendable amount (see [`Account::available`]).
433    pub available: u128,
434    /// The journal sequence this view reflects.
435    pub as_of_seq: u64,
436}