1use 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#[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 mint_authority: Option<crate::mint::MintAuthority>,
47}
48
49impl MemLedger {
50 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 pub fn ledger_id(&self) -> &Did {
74 &self.ledger_id
75 }
76
77 pub fn advance_clock(&mut self, to: u64) {
82 self.clock = self.clock.max(to);
83 }
84
85 pub fn clock(&self) -> u64 {
87 self.clock
88 }
89
90 pub fn journal(&self) -> &[JournalEntry] {
92 &self.journal
93 }
94
95 pub fn accounts(&self) -> impl Iterator<Item = &Account> {
97 self.accounts.values()
98 }
99
100 pub fn last_checkpoint(&self) -> Option<&SignedCheckpoint> {
102 self.last_checkpoint.as_ref()
103 }
104
105 fn commit(&mut self, op: Op) -> Outcome {
110 if let Some(id) = op.idempotency_id() {
113 if let Some(prior) = self.outcomes.get(&id) {
114 return prior.clone();
115 }
116 }
117
118 let staged = engine::stage(self, &op);
120
121 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 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 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 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 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}