Skip to main content

hyprstream_ledger/
engine.rs

1//! The pure, backend-agnostic transfer state machine (plan §2a step 2, §2b).
2//!
3//! `stage` is a **total, default-deny** function of `(current state, op)` →
4//! `(result, deltas)`. It performs no I/O and no mutation: it reads the current
5//! state through [`StateView`] and returns the deltas a backend must apply
6//! atomically inside its serialized commit. RocksLedger and MemLedger share this
7//! module verbatim, which is what makes "same op sequence ⇒ same outcomes"
8//! true by construction (backend-equivalence).
9//!
10//! There are no TOCTOU races here: within one cell ledger there is a single
11//! writer, so every interleaving question reduces to an *ordering* question, and
12//! the ordering is fixed by the sequence in which ops reach `stage`.
13
14use crate::errors::LedgerError;
15use crate::types::{
16    Account, AccountId, AccountSpec, IssueTransfer, PendingReservation, PendingState, Purpose,
17    Transfer, TransferId, TransferResult,
18};
19
20/// Minimum reservation timeout (plan §2b.6).
21pub const MIN_TIMEOUT_S: u32 = 1;
22/// Maximum reservation timeout — day-plus holds are tranches, not reservations.
23pub const MAX_TIMEOUT_S: u32 = 24 * 60 * 60;
24
25/// Read-only view of ledger state the engine needs. Backends implement this over
26/// their own storage (a `BTreeMap` for MemLedger, RocksDB point-reads for
27/// RocksLedger).
28pub trait StateView {
29    /// Look up an account by id.
30    fn account(&self, id: AccountId) -> Option<&Account>;
31    /// Look up a pending reservation by its phase-1 transfer id.
32    fn pending(&self, id: TransferId) -> Option<&PendingReservation>;
33    /// The ledger's logical commit clock (seconds). Deadlines are judged against
34    /// this at apply time (plan §2b.5) — never a caller clock.
35    fn now(&self) -> u64;
36}
37
38/// An op the engine can stage. The idempotency key (where present) is the
39/// carried `TransferId`; `stage` never dedups — that is the commit loop's job
40/// (it checks the outcome index before calling `stage`).
41#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
42pub enum Op {
43    /// Create an account (boxed to keep the enum small). Idempotent by derived
44    /// id; the backend's fast path returns an existing account without a journal
45    /// entry, so this variant is only committed on real creation.
46    OpenAccount(Box<AccountSpec>),
47    /// Single-phase issuance (supply growth).
48    Credit(IssueTransfer),
49    /// Single-phase spend.
50    Debit(Transfer),
51    /// Phase-1 reservation.
52    Reserve {
53        /// The reserve transfer.
54        transfer: Transfer,
55        /// Timeout in seconds (validated against `[MIN,MAX]_TIMEOUT_S`).
56        timeout_s: u32,
57    },
58    /// Phase-2 post. `amount: None` = full; `Some(p)` = partial (remainder released).
59    Post {
60        /// This post's own idempotency id.
61        id: TransferId,
62        /// The phase-1 reservation being resolved.
63        pending: TransferId,
64        /// Optional partial amount.
65        amount: Option<u128>,
66    },
67    /// Phase-2 void (release the hold).
68    Void {
69        /// This void's own idempotency id.
70        id: TransferId,
71        /// The phase-1 reservation being cancelled.
72        pending: TransferId,
73    },
74    /// Sweep-driven expiry of a single reservation (plan §2b.4). Emitted by the
75    /// backend's `tick`, not by callers; it has no external idempotency id.
76    Expire {
77        /// The reservation to expire.
78        pending: TransferId,
79    },
80}
81
82impl Op {
83    /// The idempotency key for this op, if it carries one. `Expire` is
84    /// internally generated and has none.
85    pub fn idempotency_id(&self) -> Option<TransferId> {
86        // `Credit`/`Debit` carry different payload types, so their identical
87        // bodies cannot be merged into one arm.
88        #[allow(clippy::match_same_arms)]
89        match self {
90            Op::OpenAccount(_) | Op::Expire { .. } => None,
91            Op::Credit(t) => Some(t.id),
92            Op::Debit(t) => Some(t.id),
93            Op::Reserve { transfer, .. } => Some(transfer.id),
94            Op::Post { id, .. } | Op::Void { id, .. } => Some(*id),
95        }
96    }
97}
98
99/// A single state mutation the commit loop must apply atomically.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum Delta {
102    /// Upsert an account row (keyed by `account.id`).
103    Account(Account),
104    /// Upsert a pending reservation row (keyed by `reservation.transfer.id`).
105    Pending(PendingReservation),
106}
107
108/// The output of [`stage`]: the business result plus the deltas to apply. On an
109/// error result `deltas` is usually empty, but not always — an on-touch expiry
110/// (plan §2b.4) both fails the second phase *and* releases the hold, so a failed
111/// post can carry the expiry delta.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Staged {
114    /// The result recorded under the op's idempotency id.
115    pub result: Result<TransferResult, LedgerError>,
116    /// State mutations to commit atomically with the journal entry.
117    pub deltas: Vec<Delta>,
118}
119
120impl Staged {
121    fn err(e: LedgerError) -> Self {
122        Staged {
123            result: Err(e),
124            deltas: Vec::new(),
125        }
126    }
127}
128
129/// Stage an op against the current state. Pure: no mutation, no I/O.
130pub fn stage(view: &dyn StateView, op: &Op) -> Staged {
131    match op {
132        Op::OpenAccount(spec) => stage_open(view, spec),
133        Op::Credit(t) => stage_credit(view, t),
134        Op::Debit(t) => stage_debit(view, t),
135        Op::Reserve {
136            transfer,
137            timeout_s,
138        } => stage_reserve(view, transfer, *timeout_s),
139        Op::Post {
140            pending, amount, ..
141        } => stage_second_phase(view, *pending, Phase::Post(*amount)),
142        Op::Void { pending, .. } => stage_second_phase(view, *pending, Phase::Void),
143        Op::Expire { pending } => stage_second_phase(view, *pending, Phase::Expire),
144    }
145}
146
147fn stage_open(view: &dyn StateView, spec: &AccountSpec) -> Staged {
148    let id = match spec.account_id() {
149        Ok(id) => id,
150        Err(e) => return Staged::err(e),
151    };
152    if let Some(existing) = view.account(id) {
153        if existing.unit != spec.unit {
154            return Staged::err(LedgerError::AccountUnitConflict { id });
155        }
156        // Idempotent no-op (the backend fast-paths this before staging, so this
157        // arm is defensive).
158        return Staged {
159            result: Ok(TransferResult::Opened),
160            deltas: Vec::new(),
161        };
162    }
163    let account = Account::new(id, spec.unit.clone(), spec.purpose.clone(), spec.flags);
164    Staged {
165        result: Ok(TransferResult::Opened),
166        deltas: vec![Delta::Account(account)],
167    }
168}
169
170fn stage_credit(view: &dyn StateView, t: &IssueTransfer) -> Staged {
171    if t.amount == 0 {
172        return Staged::err(LedgerError::ZeroAmount);
173    }
174    let (liability, dest) = match (
175        view.account(t.issuer_liability),
176        view.account(t.destination),
177    ) {
178        (Some(l), Some(d)) => (l, d),
179        (None, _) => return Staged::err(LedgerError::UnknownAccount(t.issuer_liability)),
180        (_, None) => return Staged::err(LedgerError::UnknownAccount(t.destination)),
181    };
182    // The debit side must be an issuer-liability account (INV-1).
183    if t.issuer_liability == t.destination {
184        return Staged::err(LedgerError::AccountsMustDiffer(t.issuer_liability));
185    }
186    if liability.purpose != Purpose::IssuerLiability {
187        return Staged::err(LedgerError::NotIssuerLiability(t.issuer_liability));
188    }
189    if let Err(e) = check_unit(liability, &t.unit) {
190        return Staged::err(e);
191    }
192    if let Err(e) = check_unit(dest, &t.unit) {
193        return Staged::err(e);
194    }
195    let mut liability = liability.clone();
196    let mut dest = dest.clone();
197    liability.debits_posted = liability.debits_posted.saturating_add(t.amount);
198    dest.credits_posted = dest.credits_posted.saturating_add(t.amount);
199    Staged {
200        result: Ok(TransferResult::Issued),
201        deltas: vec![Delta::Account(liability), Delta::Account(dest)],
202    }
203}
204
205fn stage_debit(view: &dyn StateView, t: &Transfer) -> Staged {
206    let (debit, credit) = match resolve_pair(view, t.debit_account, t.credit_account, &t.unit) {
207        Ok(p) => p,
208        Err(e) => return Staged::err(e),
209    };
210    if t.amount == 0 {
211        return Staged::err(LedgerError::ZeroAmount);
212    }
213    if debit.is_debit_constrained() && t.amount > debit.available() {
214        return Staged::err(LedgerError::InsufficientBalance {
215            account: debit.id,
216            needed: t.amount,
217            available: debit.available(),
218        });
219    }
220    let mut debit = debit.clone();
221    let mut credit = credit.clone();
222    debit.debits_posted = debit.debits_posted.saturating_add(t.amount);
223    credit.credits_posted = credit.credits_posted.saturating_add(t.amount);
224    Staged {
225        result: Ok(TransferResult::Applied {
226            posted: t.amount,
227            released: 0,
228        }),
229        deltas: vec![Delta::Account(debit), Delta::Account(credit)],
230    }
231}
232
233fn stage_reserve(view: &dyn StateView, t: &Transfer, timeout_s: u32) -> Staged {
234    if !(MIN_TIMEOUT_S..=MAX_TIMEOUT_S).contains(&timeout_s) {
235        return Staged::err(LedgerError::TimeoutOutOfBounds(timeout_s));
236    }
237    let (debit, credit) = match resolve_pair(view, t.debit_account, t.credit_account, &t.unit) {
238        Ok(p) => p,
239        Err(e) => return Staged::err(e),
240    };
241    if t.amount == 0 {
242        return Staged::err(LedgerError::ZeroAmount);
243    }
244    // Overdraft check counts pending (plan §2b.1): `available` already subtracts
245    // `debits_pending`, so back-to-back reserves cannot over-commit.
246    if debit.is_debit_constrained() && t.amount > debit.available() {
247        return Staged::err(LedgerError::InsufficientBalance {
248            account: debit.id,
249            needed: t.amount,
250            available: debit.available(),
251        });
252    }
253    let mut debit = debit.clone();
254    let mut credit = credit.clone();
255    debit.debits_pending = debit.debits_pending.saturating_add(t.amount);
256    credit.credits_pending = credit.credits_pending.saturating_add(t.amount);
257    let reservation = PendingReservation {
258        transfer: t.clone(),
259        deadline: view.now().saturating_add(timeout_s as u64),
260        state: PendingState::Pending,
261    };
262    Staged {
263        result: Ok(TransferResult::Reserved),
264        deltas: vec![
265            Delta::Account(debit),
266            Delta::Account(credit),
267            Delta::Pending(reservation),
268        ],
269    }
270}
271
272/// The three second-phase resolutions, unified because they share the
273/// terminal-state and on-touch-expiry rules.
274enum Phase {
275    Post(Option<u128>),
276    Void,
277    Expire,
278}
279
280fn stage_second_phase(view: &dyn StateView, pending_id: TransferId, phase: Phase) -> Staged {
281    let reservation = match view.pending(pending_id) {
282        Some(r) => r,
283        None => return Staged::err(LedgerError::UnknownPendingTransfer(pending_id)),
284    };
285
286    // Already terminal ⇒ deterministic loser error (plan §2b.5). The first
287    // terminal commit won; this op observes that state.
288    match reservation.state {
289        PendingState::Pending => {}
290        PendingState::Posted => {
291            return Staged::err(LedgerError::PendingTransferAlreadyPosted(pending_id))
292        }
293        PendingState::Voided => {
294            return Staged::err(LedgerError::PendingTransferAlreadyVoided(pending_id))
295        }
296        PendingState::Expired => {
297            return Staged::err(LedgerError::PendingTransferExpired(pending_id))
298        }
299    }
300
301    let t = &reservation.transfer;
302    let debit = match view.account(t.debit_account) {
303        Some(a) => a,
304        None => return Staged::err(LedgerError::UnknownAccount(t.debit_account)),
305    };
306    let credit = match view.account(t.credit_account) {
307        Some(a) => a,
308        None => return Staged::err(LedgerError::UnknownAccount(t.credit_account)),
309    };
310
311    // On-touch expiry (plan §2b.4): if the deadline has passed by the logical
312    // commit clock, expire the reservation *in this same commit* and fail the
313    // second phase (unless the op itself is the expiry). This is what makes the
314    // expiry-vs-post race deterministic: whichever commits first wins.
315    let expired_now = view.now() >= reservation.deadline;
316    if matches!(phase, Phase::Expire) || expired_now {
317        let released = release(debit, credit, t.amount);
318        let mut res = reservation.clone();
319        res.state = PendingState::Expired;
320        let deltas = vec![released.0, released.1, Delta::Pending(res)];
321        // A caller's post/void that lost to expiry gets the deterministic error;
322        // the sweep-driven `Expire` op reports success.
323        let result = if matches!(phase, Phase::Expire) {
324            Ok(TransferResult::Expired)
325        } else {
326            Err(LedgerError::PendingTransferExpired(pending_id))
327        };
328        return Staged { result, deltas };
329    }
330
331    match phase {
332        Phase::Void => {
333            let (d_delta, c_delta) = release(debit, credit, t.amount);
334            let mut res = reservation.clone();
335            res.state = PendingState::Voided;
336            Staged {
337                result: Ok(TransferResult::Voided),
338                deltas: vec![d_delta, c_delta, Delta::Pending(res)],
339            }
340        }
341        Phase::Post(amount) => {
342            let reserved = t.amount;
343            let post_amt = amount.unwrap_or(reserved);
344            if post_amt == 0 {
345                return Staged::err(LedgerError::ZeroAmount);
346            }
347            if post_amt > reserved {
348                return Staged::err(LedgerError::PostExceedsReservation {
349                    requested: post_amt,
350                    reserved,
351                });
352            }
353            let released = reserved - post_amt;
354            let mut debit = debit.clone();
355            let mut credit = credit.clone();
356            // The full reserved amount leaves pending; `post_amt` becomes posted,
357            // the remainder is simply released.
358            debit.debits_pending = debit.debits_pending.saturating_sub(reserved);
359            credit.credits_pending = credit.credits_pending.saturating_sub(reserved);
360            debit.debits_posted = debit.debits_posted.saturating_add(post_amt);
361            credit.credits_posted = credit.credits_posted.saturating_add(post_amt);
362            let mut res = reservation.clone();
363            res.state = PendingState::Posted;
364            Staged {
365                result: Ok(TransferResult::Applied {
366                    posted: post_amt,
367                    released,
368                }),
369                deltas: vec![
370                    Delta::Account(debit),
371                    Delta::Account(credit),
372                    Delta::Pending(res),
373                ],
374            }
375        }
376        Phase::Expire => unreachable_expire(),
377    }
378}
379
380/// Release a full pending hold on both sides (void / expire).
381fn release(debit: &Account, credit: &Account, amount: u128) -> (Delta, Delta) {
382    let mut debit = debit.clone();
383    let mut credit = credit.clone();
384    debit.debits_pending = debit.debits_pending.saturating_sub(amount);
385    credit.credits_pending = credit.credits_pending.saturating_sub(amount);
386    (Delta::Account(debit), Delta::Account(credit))
387}
388
389/// The `Phase::Expire` arm inside the non-expired branch is unreachable: the
390/// expiry path is handled before the `match phase` above. We return a fail-closed
391/// internal error rather than panic (clippy forbids `unreachable!` here anyway).
392fn unreachable_expire() -> Staged {
393    Staged::err(LedgerError::Internal(
394        "expire reached the non-expired second-phase arm".to_owned(),
395    ))
396}
397
398fn resolve_pair<'a>(
399    view: &'a dyn StateView,
400    debit_id: AccountId,
401    credit_id: AccountId,
402    unit: &crate::types::UnitId,
403) -> Result<(&'a Account, &'a Account), LedgerError> {
404    if debit_id == credit_id {
405        return Err(LedgerError::AccountsMustDiffer(debit_id));
406    }
407    let debit = view
408        .account(debit_id)
409        .ok_or(LedgerError::UnknownAccount(debit_id))?;
410    let credit = view
411        .account(credit_id)
412        .ok_or(LedgerError::UnknownAccount(credit_id))?;
413    check_unit(debit, unit)?;
414    check_unit(credit, unit)?;
415    Ok((debit, credit))
416}
417
418fn check_unit(account: &Account, unit: &crate::types::UnitId) -> Result<(), LedgerError> {
419    if &account.unit != unit {
420        return Err(LedgerError::UnitMismatch {
421            transfer: unit.clone(),
422            account: account.unit.clone(),
423        });
424    }
425    Ok(())
426}