Skip to main content

hyprstream_ledger/
backend.rs

1//! The `LedgerBackend` trait — the load-bearing accounting-plane surface every
2//! backend (MemLedger now; RocksLedger, TigerBeetleLedger later) implements, and
3//! the enforcer builds on (plan §3.2).
4//!
5//! PLAN DECISION 8: the trait is **synchronous and blocking**. Every backend is
6//! single-writer anyway (plan §2a), so the service layer owns the actor thread
7//! and exposes the async facade (`LedgerHandle::submit → oneshot`). Keeping the
8//! core sync is what keeps it tokio-free (the WASM requirement), matches
9//! RocksDB's sync API, and confines TigerBeetle's async client inside its feature
10//! gate.
11
12use crate::errors::LedgerError;
13use crate::journal::{
14    ChainHead, CheckpointSigner, JournalEntry, OutboxItem, OutboxSeq, SignedCheckpoint, TickReport,
15};
16use crate::mint::MintCapability;
17use crate::types::{
18    Account, AccountId, AccountSpec, BalanceView, IssueTransfer, Outcome, Transfer, TransferId,
19};
20
21/// A single-writer double-entry ledger over one consistency domain (one cell).
22///
23/// # Idempotency contract (plan §2c)
24///
25/// Every mutating method carries a client-supplied [`TransferId`]. Replaying a
26/// `TransferId` returns the **original** [`Outcome`] verbatim — including the
27/// original error. This is a trait contract, property-tested against every
28/// backend against the MemLedger oracle. (Backends may return
29/// [`LedgerError::IdTooOld`] once the outcome row is pruned past the retention
30/// horizon — a later work item; MemLedger keeps everything and never prunes.)
31pub trait LedgerBackend: Send {
32    /// Idempotent. Creates the account iff absent and returns it; if it already
33    /// exists the existing row is returned (its unit must match, else
34    /// [`LedgerError::AccountUnitConflict`]).
35    fn open_account(&mut self, spec: AccountSpec) -> Result<Account, LedgerError>;
36
37    /// Single-phase issuance: issuer liability → destination. INV-1: the only
38    /// entry point that grows a unit's supply; the debit side MUST be the
39    /// issuer's `IssuerLiability` account for the unit (checked).
40    ///
41    /// **Sealed.** This takes a [`MintCapability`], which has no public
42    /// constructor — the only way to obtain one is [`Self::authorize_mint`],
43    /// which verifies a hybrid-PQC signature bound to that exact transfer
44    /// against the [`MintAuthority`](crate::mint::MintAuthority) this backend
45    /// was **constructed** with. Holding a backend is therefore not sufficient
46    /// to mint, and neither is holding a `&mut` to one: the authority is fixed
47    /// at construction and there is no setter. See [`crate::mint`].
48    fn credit(&mut self, cap: MintCapability<'_>) -> Outcome;
49
50    /// Verify an issuance authorization against this backend's mint authority,
51    /// yielding the capability [`Self::credit`] requires.
52    ///
53    /// `sig` must be a COSE composite signature over
54    /// [`crate::mint_signing_input`] for `t`. Verification is a concrete
55    /// in-crate check against fixed key material — there is no injectable
56    /// verifier to replace it with a permissive one, which is what makes this
57    /// the sole route to a [`MintCapability`]. A backend with no authority
58    /// refuses every authorization.
59    fn authorize_mint<'a>(
60        &self,
61        t: &'a IssueTransfer,
62        sig: &[u8],
63    ) -> Result<MintCapability<'a>, LedgerError>;
64
65    /// Single-phase spend. Overdraft-checked on the debit side (plan §2b.1).
66    fn debit(&mut self, t: Transfer) -> Outcome;
67
68    /// Two-phase phase 1: places pending holds on both sides (plan §2b). The
69    /// transfer's `id` is also the reservation id used by `post`/`void`.
70    fn reserve(&mut self, t: Transfer, timeout_s: u32) -> Outcome;
71
72    /// Two-phase phase 2. `amount: None` = full post; `Some(p)` = partial, the
73    /// remainder released. At most one second phase succeeds per reservation.
74    fn post(&mut self, id: TransferId, pending: TransferId, amount: Option<u128>) -> Outcome;
75
76    /// Two-phase phase 2 cancel: releases the pending holds.
77    fn void(&mut self, id: TransferId, pending: TransferId) -> Outcome;
78
79    /// Read-only balance projection (served from a consistent snapshot; safe
80    /// concurrent with the writer).
81    fn balance(&self, account: AccountId) -> Result<BalanceView, LedgerError>;
82
83    /// Force a signed checkpoint now and return it. Periodic checkpoints are the
84    /// backend's own duty (driven from `tick`).
85    fn checkpoint(
86        &mut self,
87        signer: &dyn CheckpointSigner,
88    ) -> Result<SignedCheckpoint, LedgerError>;
89
90    /// Housekeeping: expiry sweep (plan §2b.4), outcome pruning (plan §2c — later
91    /// item), and scheduled checkpoints. Called by the actor on an interval.
92    fn tick(&mut self, signer: &dyn CheckpointSigner) -> Result<TickReport, LedgerError>;
93
94    /// Ordered peek at committed-but-unemitted proof-plane items (plan §2e).
95    fn outbox_peek(&self, max: usize) -> Result<Vec<OutboxItem>, LedgerError>;
96
97    /// Acknowledge (drop) drained outbox items up to and including `up_to`.
98    fn outbox_ack(&mut self, up_to: OutboxSeq) -> Result<(), LedgerError>;
99
100    /// Replay/inspection window into the journal (for verify tools and
101    /// settlement framing).
102    fn journal_range(&self, from_seq: u64, max: usize) -> Result<Vec<JournalEntry>, LedgerError>;
103
104    /// The current head of the hash chain.
105    fn head(&self) -> ChainHead;
106}