Skip to main content

hyprstream_ledger/
mem.rs

1//! `MemLedger` — the in-memory reference implementation.
2//!
3//! Two jobs (plan §3.3):
4//! 1. The **WASM-capable** backend: a browser cell / Wanix guest can run a real
5//!    ledger for local-first quota. It uses no tokio, no I/O, and no wall clock —
6//!    the logical clock is driven explicitly via [`MemLedger::advance_clock`], so
7//!    behaviour is fully deterministic and reproducible.
8//! 2. The **proptest oracle**: every other backend is equivalence-tested against
9//!    it, so its commit loop is the canonical interpretation of `engine::stage`.
10//!
11//! It keeps *everything* — journal, outcomes, terminal reservations, outbox — in
12//! memory forever (outcome-retention pruning is a later work item). The commit
13//! loop mirrors the RocksLedger one (idempotency-check → stage → single atomic
14//! apply → advance head), so the two stay observably identical.
15
16use std::collections::BTreeMap;
17
18use crate::backend::LedgerBackend;
19use crate::engine::{self, Op};
20use crate::errors::LedgerError;
21use crate::journal::{
22    balances_root, pending_root, ChainHead, CheckpointContent, CheckpointSigner, JournalEntry,
23    OutboxItem, OutboxKind, OutboxSeq, SignedCheckpoint, TickReport,
24};
25use crate::types::{
26    Account, AccountId, AccountSpec, BalanceView, Did, IssueTransfer, Outcome, PendingReservation,
27    PendingState, Transfer, TransferId, TransferResult,
28};
29
30/// An in-memory single-writer double-entry ledger.
31#[derive(Debug)]
32pub struct MemLedger {
33    ledger_id: Did,
34    accounts: BTreeMap<AccountId, Account>,
35    pending: BTreeMap<TransferId, PendingReservation>,
36    outcomes: BTreeMap<TransferId, Outcome>,
37    journal: Vec<JournalEntry>,
38    outbox: BTreeMap<u64, OutboxItem>,
39    outbox_next: u64,
40    head: ChainHead,
41    clock: u64,
42    last_checkpoint: Option<SignedCheckpoint>,
43    /// The issuance authority, fixed at construction. `None` means this ledger
44    /// cannot mint at all — the fail-closed default for a ledger nobody
45    /// deliberately granted an issuance authority.
46    mint_authority: Option<crate::mint::MintAuthority>,
47}
48
49impl MemLedger {
50    /// Create an empty ledger for the given cell identity (logical clock at 0)
51    /// with the given issuance authority.
52    ///
53    /// The authority is a **construction parameter, not a setter**: once a
54    /// `MemLedger` exists, what it will accept as a mint authorization cannot
55    /// be changed. `None` yields a ledger that cannot mint at all.
56    pub fn new(ledger_id: Did, mint_authority: Option<crate::mint::MintAuthority>) -> Self {
57        MemLedger {
58            ledger_id,
59            accounts: BTreeMap::new(),
60            pending: BTreeMap::new(),
61            outcomes: BTreeMap::new(),
62            journal: Vec::new(),
63            outbox: BTreeMap::new(),
64            outbox_next: 0,
65            head: ChainHead::default(),
66            clock: 0,
67            last_checkpoint: None,
68            mint_authority,
69        }
70    }
71
72    /// The cell identity.
73    pub fn ledger_id(&self) -> &Did {
74        &self.ledger_id
75    }
76
77    /// Advance the logical commit clock to at least `to` (monotone — the clock
78    /// never regresses). This is the WASM-safe substitute for a wall clock:
79    /// tests and the actor drive time explicitly, which is what makes the
80    /// expiry-vs-post race deterministic.
81    pub fn advance_clock(&mut self, to: u64) {
82        self.clock = self.clock.max(to);
83    }
84
85    /// The current logical clock.
86    pub fn clock(&self) -> u64 {
87        self.clock
88    }
89
90    /// The full journal (reference/oracle inspection).
91    pub fn journal(&self) -> &[JournalEntry] {
92        &self.journal
93    }
94
95    /// Iterator over all accounts (for conservation checks in tests).
96    pub fn accounts(&self) -> impl Iterator<Item = &Account> {
97        self.accounts.values()
98    }
99
100    /// The last signed checkpoint, if any.
101    pub fn last_checkpoint(&self) -> Option<&SignedCheckpoint> {
102        self.last_checkpoint.as_ref()
103    }
104
105    // --- the serialized commit loop (plan §2a, in-memory) ---
106
107    /// Apply one op atomically: idempotency-check → stage → apply deltas + append
108    /// journal + record outcome + stage outbox, all as one logical commit.
109    fn commit(&mut self, op: Op) -> Outcome {
110        // 1. Idempotency FIRST (plan §2c): a replay returns the ORIGINAL outcome,
111        //    including original errors, without a new journal entry.
112        if let Some(id) = op.idempotency_id() {
113            if let Some(prior) = self.outcomes.get(&id) {
114                return prior.clone();
115            }
116        }
117
118        // 2. Stage against current state (pure).
119        let staged = engine::stage(self, &op);
120
121        // 3. Build the journal entry and its hash BEFORE mutating, so an
122        //    (unreachable) encoding failure aborts cleanly with no state change.
123        let seq = self.head.seq + 1;
124        let entry = JournalEntry {
125            seq,
126            prev_hash: self.head.head_hash,
127            ts: self.clock,
128            op: op.clone(),
129            result: staged.result.clone(),
130        };
131        let head_hash = match entry.hash() {
132            Ok(h) => h,
133            Err(e) => {
134                return Outcome {
135                    result: Err(e),
136                    seq: self.head.seq,
137                }
138            }
139        };
140
141        // 4. Apply deltas + advance the chain (the atomicity unit).
142        for delta in staged.deltas {
143            match delta {
144                engine::Delta::Account(a) => {
145                    self.accounts.insert(a.id, a);
146                }
147                engine::Delta::Pending(r) => {
148                    self.pending.insert(r.transfer.id, r);
149                }
150            }
151        }
152        self.journal.push(entry);
153        self.head = ChainHead { seq, head_hash };
154
155        let outcome = Outcome {
156            result: staged.result,
157            seq,
158        };
159
160        // 5. Record the outcome (successes AND rejections — plan §2c) and stage a
161        //    receipt for settled value (posted spends / issuance, plan §2e).
162        if let Some(id) = op.idempotency_id() {
163            self.outcomes.insert(id, outcome.clone());
164        }
165        if matches!(
166            outcome.result,
167            Ok(TransferResult::Issued) | Ok(TransferResult::Applied { .. })
168        ) {
169            self.enqueue_outbox(OutboxKind::Receipt, op.idempotency_id(), seq);
170        }
171
172        outcome
173    }
174
175    fn enqueue_outbox(
176        &mut self,
177        kind: OutboxKind,
178        transfer_id: Option<TransferId>,
179        journal_seq: u64,
180    ) {
181        let seq = OutboxSeq(self.outbox_next);
182        self.outbox_next += 1;
183        self.outbox.insert(
184            seq.0,
185            OutboxItem {
186                seq,
187                kind,
188                transfer_id,
189                journal_seq,
190            },
191        );
192    }
193}
194
195impl engine::StateView for MemLedger {
196    fn account(&self, id: AccountId) -> Option<&Account> {
197        self.accounts.get(&id)
198    }
199
200    fn pending(&self, id: TransferId) -> Option<&PendingReservation> {
201        self.pending.get(&id)
202    }
203
204    fn now(&self) -> u64 {
205        self.clock
206    }
207}
208
209impl LedgerBackend for MemLedger {
210    fn open_account(&mut self, spec: AccountSpec) -> Result<Account, LedgerError> {
211        let id = spec.account_id()?;
212        // Fast path: idempotent return of an existing account, with NO journal
213        // growth (the property the idempotency proptest checks for opens).
214        if let Some(existing) = self.accounts.get(&id) {
215            if existing.unit != spec.unit {
216                return Err(LedgerError::AccountUnitConflict { id });
217            }
218            return Ok(existing.clone());
219        }
220        let outcome = self.commit(Op::OpenAccount(Box::new(spec)));
221        match outcome.result {
222            Ok(_) => self
223                .accounts
224                .get(&id)
225                .cloned()
226                .ok_or_else(|| LedgerError::Internal("account absent after open".to_owned())),
227            Err(e) => Err(e),
228        }
229    }
230
231    fn credit(&mut self, cap: crate::mint::MintCapability<'_>) -> Outcome {
232        self.commit(Op::Credit(cap.transfer().clone()))
233    }
234
235    fn authorize_mint<'a>(
236        &self,
237        t: &'a IssueTransfer,
238        sig: &[u8],
239    ) -> Result<crate::mint::MintCapability<'a>, LedgerError> {
240        crate::mint::authorize(self.mint_authority.as_ref(), t, sig)
241    }
242
243    fn debit(&mut self, t: Transfer) -> Outcome {
244        self.commit(Op::Debit(t))
245    }
246
247    fn reserve(&mut self, t: Transfer, timeout_s: u32) -> Outcome {
248        self.commit(Op::Reserve {
249            transfer: t,
250            timeout_s,
251        })
252    }
253
254    fn post(&mut self, id: TransferId, pending: TransferId, amount: Option<u128>) -> Outcome {
255        self.commit(Op::Post {
256            id,
257            pending,
258            amount,
259        })
260    }
261
262    fn void(&mut self, id: TransferId, pending: TransferId) -> Outcome {
263        self.commit(Op::Void { id, pending })
264    }
265
266    fn balance(&self, account: AccountId) -> Result<BalanceView, LedgerError> {
267        self.accounts
268            .get(&account)
269            .map(|a| a.view(self.head.seq))
270            .ok_or(LedgerError::UnknownAccount(account))
271    }
272
273    fn checkpoint(
274        &mut self,
275        signer: &dyn CheckpointSigner,
276    ) -> Result<SignedCheckpoint, LedgerError> {
277        let balances = balances_root(self.accounts.values())?;
278        let pending = pending_root(self.pending.values())?;
279        let prev_checkpoint_hash = match &self.last_checkpoint {
280            Some(cp) => cp.digest()?,
281            None => [0u8; 32],
282        };
283        let content = CheckpointContent {
284            ledger_id: signer.ledger_id(),
285            seq: self.head.seq,
286            head_hash: self.head.head_hash,
287            balances_root: balances,
288            pending_root: pending,
289            ts: self.clock,
290            prev_checkpoint_hash,
291        };
292        let sig = signer.sign(&content.signing_input()?)?;
293        let cp = SignedCheckpoint {
294            ledger_id: signer.ledger_id().clone(),
295            seq: self.head.seq,
296            head_hash: self.head.head_hash,
297            balances_root: balances,
298            pending_root: pending,
299            ts: self.clock,
300            prev_checkpoint_hash,
301            sig,
302        };
303        self.last_checkpoint = Some(cp.clone());
304        self.enqueue_outbox(OutboxKind::Checkpoint, None, self.head.seq);
305        Ok(cp)
306    }
307
308    fn tick(&mut self, _signer: &dyn CheckpointSigner) -> Result<TickReport, LedgerError> {
309        // Expiry sweep (plan §2b.4): every open reservation whose deadline the
310        // logical clock has reached is expired, one journal entry each. (Scheduled
311        // checkpoint cadence is a later work item; explicit `checkpoint` covers
312        // the skeleton.)
313        let now = self.clock;
314        let due: Vec<TransferId> = self
315            .pending
316            .iter()
317            .filter(|(_, r)| r.state == PendingState::Pending && now >= r.deadline)
318            .map(|(id, _)| *id)
319            .collect();
320        let mut expired = 0usize;
321        for id in due {
322            if self.commit(Op::Expire { pending: id }).is_ok() {
323                expired += 1;
324            }
325        }
326        Ok(TickReport {
327            expired,
328            checkpointed: None,
329        })
330    }
331
332    fn outbox_peek(&self, max: usize) -> Result<Vec<OutboxItem>, LedgerError> {
333        Ok(self.outbox.values().take(max).cloned().collect())
334    }
335
336    fn outbox_ack(&mut self, up_to: OutboxSeq) -> Result<(), LedgerError> {
337        self.outbox.retain(|&seq, _| seq > up_to.0);
338        Ok(())
339    }
340
341    fn journal_range(&self, from_seq: u64, max: usize) -> Result<Vec<JournalEntry>, LedgerError> {
342        Ok(self
343            .journal
344            .iter()
345            .filter(|e| e.seq >= from_seq)
346            .take(max)
347            .cloned()
348            .collect())
349    }
350
351    fn head(&self) -> ChainHead {
352        self.head
353    }
354}