diff --git a/pkgs/id/src/currency_poc/executor.rs b/pkgs/id/src/currency_poc/executor.rs new file mode 100644 index 0000000000..8ae4e6047c --- /dev/null +++ b/pkgs/id/src/currency_poc/executor.rs @@ -0,0 +1,286 @@ +//! The conversion executor: pre-flight, write-ahead intent, linked +//! batch submission. +//! +//! A conversion is the composed pair from the TigerBeetle Currency +//! Exchange recipe (see the #2040 investigation): T1 moves the source +//! amount from the user to the liquidity provider (LP) on the source +//! ledger, an optional fee leg moves the fee from the user to the fee +//! account on the source ledger, and T3 moves the converted amount +//! from the LP to the user on the destination ledger. All legs are +//! stamped `user_data_128 = conversion_id` and submitted as ONE linked +//! batch, so either every leg posts or none does. +//! +//! Cross-ledger transfers do not exist in TigerBeetle; the exchange +//! rate and its authorisation are control-plane data (#2063), carried +//! here as a [`RateQuote`] and recorded on the intent record. + +use anyhow::{Context, Result, bail}; + +use super::intent::{IntentRecord, IntentState, IntentStore}; +use super::ledger::{AccountId, LedgerBackend, Transfer, TransferError}; + +/// Transfer `code` for conversion legs (chart-of-accounts, #2063). +pub const TRANSFER_CODE_CONVERSION: u16 = 1; + +/// An authorised rate: `amount_out = amount_in * numerator / denominator`, +/// rounded down — in the LP's favour, per the Currency Exchange recipe. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RateQuote { + pub numerator: u128, + pub denominator: u128, + pub authorisation_id: String, +} + +impl RateQuote { + /// The converted amount, or `None` when the quote is malformed + /// (zero denominator) or the multiplication overflows `u128`. + /// Overflow is an explicit failure, never a silent saturation: + /// a saturated product would silently change the authorised rate. + pub fn amount_out(&self, amount_in: u128) -> Option { + if self.denominator == 0 { + return None; + } + amount_in + .checked_mul(self.numerator) + .map(|product| product / self.denominator) + } +} + +/// Everything needed to execute one conversion. Accounts are stub +/// TigerBeetle accounts created by the caller (the PoC sanctions stub +/// accounts; real account/LP representation comes from #2062). +#[derive(Clone, Debug)] +pub struct ConversionRequest { + pub conversion_id: u128, + /// Pre-generated transfer IDs, one per leg, in leg order + /// (T1, fee leg if any, T3). Generated by the caller and persisted + /// on the intent record before submission. + pub transfer_ids: Vec, + pub user_source: AccountId, + pub lp_source: AccountId, + pub fee_account: Option, + pub lp_dest: AccountId, + pub user_dest: AccountId, + pub source_ledger: u32, + pub dest_ledger: u32, + pub amount_in: u128, + /// Fee taken on the source ledger; 0 means no fee leg. + pub fee_amount: u128, + pub quote: RateQuote, +} + +/// Executes conversions against a [`LedgerBackend`], writing intent +/// records to an [`IntentStore`] ahead of every submission. +pub struct ConversionExecutor { + pub backend: B, + pub store: S, +} + +impl ConversionExecutor { + pub fn new(backend: B, store: S) -> Self { + Self { backend, store } + } + + /// Build the legs for a request. Every leg but the last is + /// `linked`; the batch is submitted as one chain. + pub fn build_legs(request: &ConversionRequest) -> Result> { + let amount_out = request.quote.amount_out(request.amount_in).context( + "rate quote is malformed (zero denominator) or its multiplication overflows", + )?; + let mut legs = Vec::with_capacity(3); + let mut ids = request.transfer_ids.iter(); + let mut next_id = move || -> Result { + ids.next() + .copied() + .context("transfer_ids must cover every leg (T1, fee, T3)") + }; + legs.push(Transfer { + id: next_id()?, + debit_account_id: request.user_source, + credit_account_id: request.lp_source, + amount: request.amount_in, + ledger: request.source_ledger, + user_data_128: request.conversion_id, + code: TRANSFER_CODE_CONVERSION, + linked: true, + }); + if request.fee_amount > 0 { + legs.push(Transfer { + id: next_id()?, + debit_account_id: request.user_source, + credit_account_id: request + .fee_account + .context("fee_amount > 0 requires a fee_account")?, + amount: request.fee_amount, + ledger: request.source_ledger, + user_data_128: request.conversion_id, + code: TRANSFER_CODE_CONVERSION, + linked: true, + }); + } + legs.push(Transfer { + id: next_id()?, + debit_account_id: request.lp_dest, + credit_account_id: request.user_dest, + amount: amount_out, + ledger: request.dest_ledger, + user_data_128: request.conversion_id, + code: TRANSFER_CODE_CONVERSION, + linked: false, + }); + Ok(legs) + } + + /// Pre-flight (§4 of #2063): every account exists on the right + /// ledger, the user can cover amount + fee, and the LP holds + /// enough destination inventory. Failing here means no intent is + /// written and nothing is submitted. + pub fn preflight(&self, request: &ConversionRequest) -> Result<()> { + if request.quote.denominator == 0 { + bail!("preflight: rate quote has a zero denominator"); + } + let amount_out = request + .quote + .amount_out(request.amount_in) + .context("preflight: rate quote multiplication overflows")?; + if amount_out == 0 { + bail!("preflight: rate quote produces a zero destination amount"); + } + let check_account = |id: AccountId, ledger: u32, role: &str| -> Result<()> { + let account = self + .backend + .lookup_account(id) + .with_context(|| format!("preflight: {role} account {id} does not exist"))?; + if account.ledger != ledger { + bail!( + "preflight: {role} account {id} is on ledger {}, expected {ledger}", + account.ledger + ); + } + Ok(()) + }; + check_account(request.user_source, request.source_ledger, "user source")?; + check_account(request.lp_source, request.source_ledger, "LP source")?; + if let Some(fee_account) = request.fee_account { + check_account(fee_account, request.source_ledger, "fee")?; + } + check_account(request.lp_dest, request.dest_ledger, "LP destination")?; + check_account(request.user_dest, request.dest_ledger, "user destination")?; + + let user_balance = self + .backend + .account_balance(request.user_source) + .context("preflight: user source balance missing")?; + let needed = request + .amount_in + .checked_add(request.fee_amount) + .context("preflight: amount + fee overflow")?; + if user_balance.spendable() < needed { + bail!( + "preflight: user source spendable {} < amount + fee {needed}", + user_balance.spendable() + ); + } + let lp_balance = self + .backend + .account_balance(request.lp_dest) + .context("preflight: LP destination balance missing")?; + if lp_balance.spendable() < amount_out { + bail!( + "preflight: insufficient LP inventory — LP destination spendable {} < amount_out {amount_out}", + lp_balance.spendable() + ); + } + Ok(()) + } + + /// Write-ahead phase: pre-flight, build the legs, and persist the + /// intent record (state `Recorded`) BEFORE any submission. Kept + /// separate from [`Self::submit`] so the crash window between + /// intent and submission is directly testable. + pub fn prepare(&mut self, request: &ConversionRequest) -> Result { + self.preflight(request)?; + let legs = Self::build_legs(request)?; + let amount_out = request.quote.amount_out(request.amount_in).context( + "rate quote is malformed (zero denominator) or its multiplication overflows", + )?; + let record = IntentRecord { + conversion_id: request.conversion_id, + legs, + user_source: request.user_source, + lp_source: request.lp_source, + fee_account: request.fee_account, + lp_dest: request.lp_dest, + user_dest: request.user_dest, + source_ledger: request.source_ledger, + dest_ledger: request.dest_ledger, + amount_in: request.amount_in, + amount_out, + fee_amount: request.fee_amount, + authorisation_id: request.quote.authorisation_id.clone(), + state: IntentState::Recorded, + }; + // A conversion ID is the identity of ONE conversion: never + // replace its persisted intent. An identical retry reuses the + // original record (with its state); a conflicting request is + // rejected, so a retry can never erase the recovery record of + // an earlier, possibly-posted submission. + if let Some(existing) = self + .store + .get(record.conversion_id) + .context("intent lookup before persist failed")? + { + let mut comparable = existing.clone(); + comparable.state = record.state; + if comparable == record { + return Ok(existing); + } + bail!( + "prepare: conversion {} already has a persisted intent with different legs or amounts; refusing to replace it", + record.conversion_id + ); + } + self.store + .put(&record) + .context("write-ahead intent persist failed")?; + Ok(record) + } + + /// Submission phase: mark the record `Submitted` (still ahead of + /// the ledger call), submit the linked batch, then mark `Posted`. + /// A crash between the ledger call and the `Posted` write leaves a + /// `Submitted` record the recovery scanner reconciles by lookup — + /// it never resubmits blindly, and idempotent IDs make even a + /// resubmission safe. + pub fn submit(&mut self, record: &mut IntentRecord) -> Result<()> { + record.state = IntentState::Submitted; + self.store + .put(record) + .context("intent state persist (Submitted) failed")?; + let results = self.backend.create_transfers(&record.legs); + for (leg, result) in record.legs.iter().zip(results.iter()) { + match result { + Ok(()) | Err(TransferError::Exists) => {} + Err(error) => { + bail!( + "conversion {} leg {} failed: {error:?}", + record.conversion_id, + leg.id + ); + } + } + } + record.state = IntentState::Posted; + self.store + .put(record) + .context("intent state persist (Posted) failed")?; + Ok(()) + } + + /// The normal path: prepare (write-ahead) then submit. + pub fn execute(&mut self, request: &ConversionRequest) -> Result { + let mut record = self.prepare(request)?; + self.submit(&mut record)?; + Ok(record) + } +} diff --git a/pkgs/id/src/currency_poc/harness.rs b/pkgs/id/src/currency_poc/harness.rs new file mode 100644 index 0000000000..d5d87ffcb1 --- /dev/null +++ b/pkgs/id/src/currency_poc/harness.rs @@ -0,0 +1,166 @@ +//! Step 0 — the TigerBeetle test harness. +//! +//! A throwaway single-replica TigerBeetle dev cluster the PoC test +//! suite can start and stop, sanctioned for the PoC by the cluster +//! topology investigation (`doc/2026-10-29T11-57-00Z_investigation_tigerbeetle_cluster_topology`: +//! "A separate throwaway 3-replica (or single-replica) dev cluster for +//! the PoC is fine"). It holds no real value and is deleted, never +//! migrated. +//! +//! The binary is pinned: [`TIGERBEETLE_PINNED_VERSION`] is verified +//! against `tigerbeetle version` output before a cluster starts, so a +//! developer-machine-only or drifted binary fails loudly instead of +//! silently testing against the wrong release. Acquisition is either +//! the release zip (URL pattern below, the one the TigerBeetle +//! upgrading docs use) or a nix-provided binary — in both cases the +//! path is supplied via `TIGERBEETLE_POC_BINARY` or `PATH`. + +use std::fs; +use std::net::TcpStream; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; + +/// The pinned TigerBeetle release for the PoC harness (latest release +/// at the time of pinning, verified via the GitHub releases API). +pub const TIGERBEETLE_PINNED_VERSION: &str = "0.17.9"; + +/// Release-zip URL for the pinned version on x86_64 Linux (asset +/// naming follows the TigerBeetle upgrading documentation). +pub const TIGERBEETLE_RELEASE_ZIP: &str = "https://github.com/tigerbeetle/tigerbeetle/releases/download/0.17.9/tigerbeetle-x86_64-linux.zip"; + +/// Environment variable naming an explicit binary path. +pub const BINARY_ENV: &str = "TIGERBEETLE_POC_BINARY"; + +/// Resolve the harness binary: `$TIGERBEETLE_POC_BINARY`, else +/// `tigerbeetle` on `PATH`. +pub fn binary_path() -> PathBuf { + std::env::var_os(BINARY_ENV) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("tigerbeetle")) +} + +/// Verify the resolved binary reports the pinned version. +pub fn verify_pinned_version(binary: &PathBuf) -> Result<()> { + let output = Command::new(binary) + .arg("version") + .output() + .with_context(|| format!("running {} version", binary.display()))?; + let text = String::from_utf8_lossy(&output.stdout); + if !output.status.success() || !text.contains(TIGERBEETLE_PINNED_VERSION) { + bail!( + "tigerbeetle binary at {} reports {:?}, expected pinned version {} \ + (acquire it from {})", + binary.display(), + text.trim(), + TIGERBEETLE_PINNED_VERSION, + TIGERBEETLE_RELEASE_ZIP + ); + } + Ok(()) +} + +/// A running throwaway single-replica cluster. Killed and deleted on drop. +pub struct TestCluster { + dir: PathBuf, + child: Option, + /// The `host:port` address clients should connect to. + pub address: String, +} + +impl TestCluster { + /// Format a fresh data file and start one replica on a loopback + /// port. `port` is chosen by the caller (tests use distinct ports). + pub fn start(port: u16) -> Result { + let binary = binary_path(); + verify_pinned_version(&binary)?; + let dir = + std::env::temp_dir().join(format!("id-currency-poc-tb-{}-{port}", std::process::id())); + if dir.exists() { + fs::remove_dir_all(&dir)?; + } + fs::create_dir_all(&dir)?; + let data_file = dir.join("0_0.tigerbeetle"); + let format = Command::new(&binary) + .args(["format", "--cluster=0", "--replica=0", "--replica-count=1"]) + .arg(&data_file) + .output() + .context("tigerbeetle format")?; + if !format.status.success() { + bail!( + "tigerbeetle format failed: {}", + String::from_utf8_lossy(&format.stderr) + ); + } + let address = format!("127.0.0.1:{port}"); + let child = Command::new(&binary) + .arg("start") + .arg(format!("--addresses={address}")) + .arg(&data_file) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .context("tigerbeetle start")?; + let mut cluster = Self { + dir, + child: Some(child), + address, + }; + cluster.wait_ready(Duration::from_secs(30))?; + Ok(cluster) + } + + fn wait_ready(&mut self, timeout: Duration) -> Result<()> { + let deadline = Instant::now() + timeout; + loop { + if let Ok(_stream) = TcpStream::connect(&self.address) { + // A successful TCP connect is the readiness signal. + // The replica sends no unsolicited bytes, so any read + // here would block unboundedly and defeat the deadline + // this loop is supposed to enforce. + return Ok(()); + } + if Instant::now() > deadline { + bail!( + "tigerbeetle replica at {} did not become ready", + self.address + ); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + + /// Stop the replica (the data directory is removed on drop). + pub fn stop(&mut self) { + if let Some(mut child) = self.child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +impl Drop for TestCluster { + fn drop(&mut self) { + self.stop(); + let _ = fs::remove_dir_all(&self.dir); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Step-0 smoke test: the pinned binary formats and starts a + /// single-replica cluster and stops cleanly. Ignored by default — + /// it needs the pinned TigerBeetle binary (see module docs). + /// Run with: `cargo test -p id currency_poc -- --ignored` + #[test] + #[ignore = "requires the pinned tigerbeetle binary (TIGERBEETLE_POC_BINARY or PATH)"] + fn cluster_starts_and_stops() { + let mut cluster = TestCluster::start(30011).expect("cluster should start"); + assert!(cluster.address.starts_with("127.0.0.1:")); + cluster.stop(); + } +} diff --git a/pkgs/id/src/currency_poc/intent.rs b/pkgs/id/src/currency_poc/intent.rs new file mode 100644 index 0000000000..9904fa8f9e --- /dev/null +++ b/pkgs/id/src/currency_poc/intent.rs @@ -0,0 +1,181 @@ +//! Write-ahead intent records for the conversion-executor PoC. +//! +//! The executor persists an [`IntentRecord`] — conversion ID, the +//! pre-generated transfer IDs of every leg, amounts, and the +//! authorisation ID — *before* any ledger submission, and advances its +//! state as submission proceeds. A crash therefore always leaves a +//! durable record the recovery scanner (`super::recovery`) can +//! reconcile against the ledger by transfer-ID lookup: present means +//! POSTED, absent means the same IDs may be safely resubmitted +//! (TigerBeetle transfer creation is idempotent by ID) or the record +//! abandoned. + +use std::collections::HashMap; +use std::fs; +use std::io; +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +use super::ledger::{AccountId, Transfer}; + +/// Lifecycle of a conversion intent. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum IntentState { + /// Persisted, not yet submitted. A crash in this state means the + /// ledger was never touched; resubmission uses the same IDs. + Recorded, + /// Submission was attempted; the outcome is unknown until the + /// scanner (or a retry) looks the transfer IDs up. + Submitted, + /// Every leg is present in the ledger. + Posted, + /// The scanner (or an operator) decided not to resubmit. + Abandoned, +} + +impl IntentState { + /// States the recovery scanner still has to reconcile. + pub fn is_unresolved(self) -> bool { + matches!(self, IntentState::Recorded | IntentState::Submitted) + } +} + +/// The write-ahead record for one conversion. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct IntentRecord { + pub conversion_id: u128, + /// The full legs, with their pre-generated transfer IDs. Storing + /// the legs (not just the IDs) is what lets the scanner resubmit + /// byte-identical transfers after a crash. + pub legs: Vec, + pub user_source: AccountId, + pub lp_source: AccountId, + pub fee_account: Option, + pub lp_dest: AccountId, + pub user_dest: AccountId, + pub source_ledger: u32, + pub dest_ledger: u32, + pub amount_in: u128, + pub amount_out: u128, + pub fee_amount: u128, + /// The control-plane rate authorisation this conversion executes + /// under (#2063: rates and authorisations live outside TigerBeetle). + pub authorisation_id: String, + pub state: IntentState, +} + +impl IntentRecord { + pub fn transfer_ids(&self) -> Vec { + self.legs.iter().map(|leg| leg.id).collect() + } +} + +/// Persistence seam for intent records. +pub trait IntentStore { + /// Insert or replace a record. Must be durable before returning: + /// the write-ahead guarantee depends on it. + fn put(&mut self, record: &IntentRecord) -> io::Result<()>; + fn get(&self, conversion_id: u128) -> io::Result>; + fn unresolved(&self) -> io::Result>; +} + +/// In-memory store for tests and demos. +#[derive(Default)] +pub struct InMemoryIntentStore { + records: HashMap, +} + +impl InMemoryIntentStore { + pub fn new() -> Self { + Self::default() + } +} + +impl IntentStore for InMemoryIntentStore { + fn put(&mut self, record: &IntentRecord) -> io::Result<()> { + self.records.insert(record.conversion_id, record.clone()); + Ok(()) + } + + fn get(&self, conversion_id: u128) -> io::Result> { + Ok(self.records.get(&conversion_id).cloned()) + } + + fn unresolved(&self) -> io::Result> { + Ok(self + .records + .values() + .filter(|record| record.state.is_unresolved()) + .cloned() + .collect()) + } +} + +/// File-backed store: one JSON file per conversion under a directory, +/// written via a temporary file + rename + fsync so a crash mid-write +/// never leaves a torn record behind. +pub struct FileIntentStore { + dir: PathBuf, +} + +impl FileIntentStore { + pub fn open(dir: PathBuf) -> io::Result { + fs::create_dir_all(&dir)?; + Ok(Self { dir }) + } + + fn path_for(&self, conversion_id: u128) -> PathBuf { + self.dir.join(format!("{conversion_id:032x}.json")) + } +} + +impl IntentStore for FileIntentStore { + fn put(&mut self, record: &IntentRecord) -> io::Result<()> { + let path = self.path_for(record.conversion_id); + let tmp = path.with_extension("json.tmp"); + let bytes = serde_json::to_vec_pretty(record) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + fs::write(&tmp, bytes)?; + let file = fs::File::open(&tmp)?; + file.sync_all()?; + drop(file); + fs::rename(&tmp, &path)?; + // Sync the containing directory so the rename itself is + // durable: syncing the file alone does not guarantee the new + // directory entry survives a machine crash, and the + // write-ahead guarantee depends on the record being findable + // by the recovery scanner afterwards. + let dir = fs::File::open(&self.dir)?; + dir.sync_all()?; + Ok(()) + } + + fn get(&self, conversion_id: u128) -> io::Result> { + let path = self.path_for(conversion_id); + if !path.exists() { + return Ok(None); + } + let bytes = fs::read(path)?; + let record = serde_json::from_slice(&bytes) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + Ok(Some(record)) + } + + fn unresolved(&self) -> io::Result> { + let mut records = Vec::new(); + for entry in fs::read_dir(&self.dir)? { + let path = entry?.path(); + if path.extension().and_then(|ext| ext.to_str()) != Some("json") { + continue; + } + let bytes = fs::read(&path)?; + let record: IntentRecord = serde_json::from_slice(&bytes) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + if record.state.is_unresolved() { + records.push(record); + } + } + Ok(records) + } +} diff --git a/pkgs/id/src/currency_poc/ledger.rs b/pkgs/id/src/currency_poc/ledger.rs new file mode 100644 index 0000000000..18ff9e995b --- /dev/null +++ b/pkgs/id/src/currency_poc/ledger.rs @@ -0,0 +1,328 @@ +//! Ledger types and the backend seam for the conversion-executor PoC. +//! +//! The types mirror TigerBeetle's data model (see the #2040 backend +//! investigation, `doc/2026-10-28T23-34-15Z_investigation_tigerbeetle_currency_backend`): +//! a currency is a bare `ledger: u32`, amounts are `u128`, and the link +//! between a conversion and its transfers is stamped into +//! `user_data_128`, because TigerBeetle does not persist linked-chain +//! membership itself. +//! +//! [`LedgerBackend`] is the seam the executor works against. +//! [`InMemoryLedger`] implements the TigerBeetle semantics the PoC +//! depends on — atomic linked chains, idempotent transfer IDs, and +//! balance-invariant flags — so the scenario tests in `tests` run +//! anywhere. A production binding would implement the same trait over +//! the official TigerBeetle Rust client against the test cluster +//! managed by `super::harness`. + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +/// TigerBeetle account ID (128-bit). +pub type AccountId = u128; +/// TigerBeetle transfer ID (128-bit), generated and persisted by the +/// originating client before submission (write-ahead discipline). +pub type TransferId = u128; + +/// Account flags the PoC relies on (a subset of TigerBeetle's). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct AccountFlags { + /// Reject a transfer whose posting would make debits exceed credits. + pub debits_must_not_exceed_credits: bool, + /// Reject a transfer whose posting would make credits exceed debits. + pub credits_must_not_exceed_debits: bool, +} + +/// A TigerBeetle-shaped account. `code` is the application chart-of- +/// accounts code (issuer / liquidity / user / fee, per #2063). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Account { + pub id: AccountId, + pub ledger: u32, + pub code: u16, + pub flags: AccountFlags, +} + +/// A TigerBeetle-shaped transfer. When `linked` is set on every leg of +/// a batch except the last, the batch is one linked chain: either all +/// legs post or none do. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Transfer { + pub id: TransferId, + pub debit_account_id: AccountId, + pub credit_account_id: AccountId, + pub amount: u128, + pub ledger: u32, + /// The conversion ID on every leg of a conversion (see module docs). + pub user_data_128: u128, + pub code: u16, + pub linked: bool, +} + +/// Posted balance totals for one account. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AccountBalance { + pub debits_posted: u128, + pub credits_posted: u128, +} + +impl AccountBalance { + /// Funds available to spend under a debits-must-not-exceed-credits + /// reading: credits received minus debits already posted. + pub fn spendable(&self) -> u128 { + self.credits_posted.saturating_sub(self.debits_posted) + } +} + +/// Per-account creation failures (subset of TigerBeetle's result codes). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AccountError { + /// An account with this ID already exists with identical fields — + /// idempotent retry, treated as success by callers. + Exists, + /// An account with this ID exists but with different fields. + ExistsWithDifferentFields, + /// `ledger` must be non-zero. + LedgerMustNotBeZero, +} + +/// Per-transfer failures (subset of TigerBeetle's result codes). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TransferError { + /// A transfer with this ID already exists with identical fields — + /// idempotent retry, treated as success by callers. This is the + /// property that makes crash-recovery resubmission safe. + Exists, + /// A transfer with this ID exists but with different fields. + ExistsWithDifferentFields, + /// Another leg of the same linked chain failed; this leg did not post. + LinkedEventFailed, + DebitAccountNotFound, + CreditAccountNotFound, + AccountsMustBeDifferent, + AmountMustNotBeZero, + /// A transfer's ledger must match both accounts' ledgers; + /// cross-ledger transfers are forbidden (conversions are composed + /// pairs of same-ledger transfers, per the #2040 investigation). + LedgerMismatch, + DebitsMustNotExceedCredits, + CreditsMustNotExceedDebits, +} + +/// The ledger operations the conversion executor needs. +pub trait LedgerBackend { + fn create_accounts(&mut self, accounts: &[Account]) -> Vec>; + /// Submit a batch. Contiguous runs ending at a transfer with + /// `linked == false` form linked chains and post atomically. + fn create_transfers(&mut self, batch: &[Transfer]) -> Vec>; + fn lookup_transfer(&self, id: TransferId) -> Option; + fn lookup_account(&self, id: AccountId) -> Option; + fn account_balance(&self, id: AccountId) -> Option; + /// All posted transfers stamped with the given `user_data_128` + /// (the conversion lookup the acceptance criteria ask for). + fn transfers_with_user_data_128(&self, value: u128) -> Vec; +} + +/// In-memory backend implementing the TigerBeetle semantics listed in +/// the module docs. Used by the PoC scenario tests and usable as a +/// reference for a real client binding. +#[derive(Default)] +pub struct InMemoryLedger { + accounts: HashMap, + balances: HashMap, + transfers: HashMap, + transfer_order: Vec, +} + +impl InMemoryLedger { + pub fn new() -> Self { + Self::default() + } + + /// Validate one transfer against a scratch balance map; on success + /// apply its balance effects to the scratch map. Nothing touches + /// the real state until a whole chain validates. + fn validate_and_stage( + &self, + transfer: &Transfer, + staged: &mut HashMap, + staged_transfers: &HashMap, + ) -> Result<(), TransferError> { + if let Some(existing) = self.transfers.get(&transfer.id) { + return if existing == transfer { + Err(TransferError::Exists) + } else { + Err(TransferError::ExistsWithDifferentFields) + }; + } + // A transfer ID may appear at most once per chain: without + // this check two legs sharing an ID would both stage balance + // changes while only the first is journaled at commit. + if let Some(staged_transfer) = staged_transfers.get(&transfer.id) { + return if staged_transfer == transfer { + Err(TransferError::Exists) + } else { + Err(TransferError::ExistsWithDifferentFields) + }; + } + if transfer.amount == 0 { + return Err(TransferError::AmountMustNotBeZero); + } + if transfer.debit_account_id == transfer.credit_account_id { + return Err(TransferError::AccountsMustBeDifferent); + } + let debit = self + .accounts + .get(&transfer.debit_account_id) + .ok_or(TransferError::DebitAccountNotFound)?; + let credit = self + .accounts + .get(&transfer.credit_account_id) + .ok_or(TransferError::CreditAccountNotFound)?; + if transfer.ledger == 0 + || transfer.ledger != debit.ledger + || transfer.ledger != credit.ledger + { + return Err(TransferError::LedgerMismatch); + } + let debit_balance = staged + .get(&transfer.debit_account_id) + .copied() + .unwrap_or_default(); + let credit_balance = staged + .get(&transfer.credit_account_id) + .copied() + .unwrap_or_default(); + let new_debit = AccountBalance { + debits_posted: debit_balance + .debits_posted + .checked_add(transfer.amount) + .ok_or(TransferError::DebitsMustNotExceedCredits)?, + ..debit_balance + }; + if debit.flags.debits_must_not_exceed_credits + && new_debit.debits_posted > new_debit.credits_posted + { + return Err(TransferError::DebitsMustNotExceedCredits); + } + let new_credit = AccountBalance { + credits_posted: credit_balance + .credits_posted + .checked_add(transfer.amount) + .ok_or(TransferError::CreditsMustNotExceedDebits)?, + ..credit_balance + }; + if credit.flags.credits_must_not_exceed_debits + && new_credit.credits_posted > new_credit.debits_posted + { + return Err(TransferError::CreditsMustNotExceedDebits); + } + staged.insert(transfer.debit_account_id, new_debit); + staged.insert(transfer.credit_account_id, new_credit); + Ok(()) + } +} + +impl LedgerBackend for InMemoryLedger { + fn create_accounts(&mut self, accounts: &[Account]) -> Vec> { + accounts + .iter() + .map(|account| { + if account.ledger == 0 { + return Err(AccountError::LedgerMustNotBeZero); + } + if let Some(existing) = self.accounts.get(&account.id) { + return if existing == account { + Err(AccountError::Exists) + } else { + Err(AccountError::ExistsWithDifferentFields) + }; + } + self.accounts.insert(account.id, account.clone()); + self.balances.entry(account.id).or_default(); + Ok(()) + }) + .collect() + } + + fn create_transfers(&mut self, batch: &[Transfer]) -> Vec> { + let mut results = Vec::with_capacity(batch.len()); + let mut chain_start = 0; + while chain_start < batch.len() { + // A chain runs until (and including) the first unlinked leg. + let mut chain_end = chain_start; + while batch[chain_end].linked && chain_end + 1 < batch.len() { + chain_end += 1; + } + let chain = &batch[chain_start..=chain_end]; + let mut staged = self.balances.clone(); + let mut staged_transfers: HashMap = HashMap::new(); + // Per-leg validation outcome. An idempotent `Exists` leg + // does not fail the chain: its effects are already in the + // real balances, so it is reported as `Err(Exists)` (as + // TigerBeetle reports it) without staging anything. + let mut leg_outcomes: Vec> = Vec::with_capacity(chain.len()); + let mut failure: Option<(usize, TransferError)> = None; + for (offset, transfer) in chain.iter().enumerate() { + match self.validate_and_stage(transfer, &mut staged, &staged_transfers) { + Ok(()) => { + staged_transfers.insert(transfer.id, transfer.clone()); + leg_outcomes.push(Ok(())); + } + Err(TransferError::Exists) => { + leg_outcomes.push(Err(TransferError::Exists)); + } + Err(error) => { + failure = Some((offset, error)); + break; + } + } + } + match failure { + None => { + self.balances = staged; + for transfer in chain { + if !self.transfers.contains_key(&transfer.id) { + self.transfers.insert(transfer.id, transfer.clone()); + self.transfer_order.push(transfer.id); + } + } + results.extend(leg_outcomes); + } + Some((failing_offset, error)) => { + for (offset, _) in chain.iter().enumerate() { + results.push(Err(if offset == failing_offset { + error + } else { + TransferError::LinkedEventFailed + })); + } + } + } + chain_start = chain_end + 1; + } + results + } + + fn lookup_transfer(&self, id: TransferId) -> Option { + self.transfers.get(&id).cloned() + } + + fn lookup_account(&self, id: AccountId) -> Option { + self.accounts.get(&id).cloned() + } + + fn account_balance(&self, id: AccountId) -> Option { + self.balances.get(&id).copied() + } + + fn transfers_with_user_data_128(&self, value: u128) -> Vec { + self.transfer_order + .iter() + .filter_map(|id| self.transfers.get(id)) + .filter(|transfer| transfer.user_data_128 == value) + .cloned() + .collect() + } +} diff --git a/pkgs/id/src/currency_poc/mod.rs b/pkgs/id/src/currency_poc/mod.rs new file mode 100644 index 0000000000..e83d92e5ec --- /dev/null +++ b/pkgs/id/src/currency_poc/mod.rs @@ -0,0 +1,37 @@ +//! Conversion-executor proof of concept (#2289, from the #2063 design). +//! +//! **This is a PoC, not the permanent feature.** Per the program rule +//! on #2056, nothing production-shaped may be built on top of it +//! without a review round. +//! +//! Contents: +//! - `ledger` — TigerBeetle-shaped types, the [`ledger::LedgerBackend`] +//! seam, and an in-memory backend implementing the TigerBeetle +//! semantics the executor relies on (atomic linked chains, +//! idempotent transfer IDs, balance-invariant flags). +//! - `intent` — write-ahead intent records, persisted before any +//! submission, with in-memory and file-backed stores. +//! - `executor` — the conversion executor: LP pre-flight, write-ahead +//! intent, one linked batch (T1 user→LP, optional fee leg, T3 +//! LP→user), every leg stamped `user_data_128 = conversion_id`. +//! - `recovery` — the recovery scanner reconciling unresolved intents +//! by pre-generated transfer-ID lookup. +//! - `harness` — step 0: a throwaway single-replica TigerBeetle test +//! cluster (pinned binary, start/stop) for running the same +//! scenarios against a real cluster once a client binding lands. +//! +//! Scenario coverage (the #2063 §4 cases) is in `tests`: a posted +//! conversion findable by `user_data_128`, atomic failure moving +//! nothing, crash-recovery without double-posting (both crash +//! windows), and LP pre-flight rejection. +//! +//! Results are reported on #2289 and linked from #2063. + +pub mod executor; +pub mod harness; +pub mod intent; +pub mod ledger; +pub mod recovery; + +#[cfg(test)] +mod tests; diff --git a/pkgs/id/src/currency_poc/recovery.rs b/pkgs/id/src/currency_poc/recovery.rs new file mode 100644 index 0000000000..e0d551cf61 --- /dev/null +++ b/pkgs/id/src/currency_poc/recovery.rs @@ -0,0 +1,109 @@ +//! Recovery scanner: reconciles unresolved intent records against +//! the ledger by pre-generated transfer ID. +//! +//! For every `Recorded` / `Submitted` record (#2289): +//! - every leg present in the ledger ⇒ the conversion POSTED (the +//! crash happened after submission but before the state write); +//! - no leg present ⇒ the submission never landed; resubmit the same +//! byte-identical legs (same IDs — idempotent by construction) or +//! abandon the record, per [`RecoveryPolicy`]; +//! - some legs present ⇒ impossible for an atomic linked chain, so it +//! is reported as [`ReconcileOutcome::Inconsistent`] for a human +//! rather than guessed at. + +use anyhow::{Context, Result}; + +use super::intent::{IntentState, IntentStore}; +use super::ledger::{LedgerBackend, TransferError}; + +/// What the scanner does with a record whose legs never landed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RecoveryPolicy { + /// Resubmit the persisted legs with their original transfer IDs. + Resubmit, + /// Mark the record `Abandoned` and move on. + Abandon, +} + +/// The reconciliation result for one intent record. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReconcileOutcome { + /// All legs were already in the ledger; state advanced to Posted. + AlreadyPosted, + /// No legs were present; the scanner resubmitted them and they posted. + Resubmitted, + /// No legs were present; the record was abandoned by policy. + Abandoned, + /// A partial leg set was found — not possible for an atomic linked + /// chain; left unresolved for investigation. + Inconsistent, + /// Resubmission of this record was rejected by the ledger; the + /// record stays unresolved and the scan continued with the + /// remaining records instead of aborting. + ResubmissionRejected, +} + +/// Reconcile every unresolved record in `store` against `backend`. +/// Returns one `(conversion_id, outcome)` pair per unresolved record. +pub fn reconcile( + backend: &mut B, + store: &mut S, + policy: RecoveryPolicy, +) -> Result> { + let mut outcomes = Vec::new(); + for mut record in store.unresolved().context("listing unresolved intents")? { + // Existence by ID is not proof of posting: a looked-up + // transfer must equal the persisted leg, otherwise the ID + // collided with an unrelated transfer. + let mut present = 0usize; + let mut matched = 0usize; + for leg in &record.legs { + if let Some(found) = backend.lookup_transfer(leg.id) { + present += 1; + if found == *leg { + matched += 1; + } + } + } + let outcome = if matched == record.legs.len() { + record.state = IntentState::Posted; + store + .put(&record) + .context("persist Posted after reconcile")?; + ReconcileOutcome::AlreadyPosted + } else if present == 0 { + match policy { + RecoveryPolicy::Resubmit => { + let results = backend.create_transfers(&record.legs); + let failed = results + .iter() + .find(|result| !matches!(result, Ok(()) | Err(TransferError::Exists))); + if failed.is_some() { + // One rejected resubmission must not abort + // recovery of every later record: leave this + // record unresolved, report it, and continue. + outcomes + .push((record.conversion_id, ReconcileOutcome::ResubmissionRejected)); + continue; + } + record.state = IntentState::Posted; + store + .put(&record) + .context("persist Posted after resubmission")?; + ReconcileOutcome::Resubmitted + } + RecoveryPolicy::Abandon => { + record.state = IntentState::Abandoned; + store + .put(&record) + .context("persist Abandoned after reconcile")?; + ReconcileOutcome::Abandoned + } + } + } else { + ReconcileOutcome::Inconsistent + }; + outcomes.push((record.conversion_id, outcome)); + } + Ok(outcomes) +} diff --git a/pkgs/id/src/currency_poc/tests.rs b/pkgs/id/src/currency_poc/tests.rs new file mode 100644 index 0000000000..e352511a4f --- /dev/null +++ b/pkgs/id/src/currency_poc/tests.rs @@ -0,0 +1,472 @@ +//! Scenario tests for the conversion-executor PoC: the #2063 §4 +//! failure cases plus the posted-conversion acceptance check. +//! +//! These run against [`InMemoryLedger`], which implements the +//! TigerBeetle semantics the executor relies on (atomic linked +//! chains, idempotent transfer IDs). The same scenarios are the ones +//! to run against a real test cluster once a `LedgerBackend` binding +//! for the official Rust client lands; the harness that starts that +//! cluster lives in `super::harness` and has its own ignored smoke +//! test. + +use super::executor::{ConversionExecutor, ConversionRequest, RateQuote}; +use super::intent::{FileIntentStore, InMemoryIntentStore, IntentState, IntentStore}; +use super::ledger::{ + Account, AccountFlags, AccountId, InMemoryLedger, LedgerBackend, Transfer, TransferError, +}; +use super::recovery::{ReconcileOutcome, RecoveryPolicy, reconcile}; + +const SRC: u32 = 101; +const DST: u32 = 102; + +const USER_SRC: AccountId = 1001; +const LP_SRC: AccountId = 1002; +const FEE: AccountId = 1003; +const LP_DST: AccountId = 2001; +const USER_DST: AccountId = 2002; +const ISSUER_SRC: AccountId = 9001; +const ISSUER_DST: AccountId = 9002; + +fn account(id: AccountId, ledger: u32, guarded: bool) -> Account { + Account { + id, + ledger, + code: 0, + flags: AccountFlags { + debits_must_not_exceed_credits: guarded, + credits_must_not_exceed_debits: false, + }, + } +} + +fn funding_transfer( + id: u128, + from: AccountId, + to: AccountId, + amount: u128, + ledger: u32, +) -> Transfer { + Transfer { + id, + debit_account_id: from, + credit_account_id: to, + amount, + ledger, + user_data_128: 0, + code: 0, + linked: false, + } +} + +/// A ledger with stub accounts (#2289 sanctions stubs): the user holds +/// 10_000 source units, the LP holds 50_000 destination units. +fn funded_ledger() -> InMemoryLedger { + let mut ledger = InMemoryLedger::new(); + let results = ledger.create_accounts(&[ + account(ISSUER_SRC, SRC, false), + account(ISSUER_DST, DST, false), + account(USER_SRC, SRC, true), + account(LP_SRC, SRC, false), + account(FEE, SRC, false), + account(LP_DST, DST, true), + account(USER_DST, DST, false), + ]); + assert!(results.iter().all(|result| result.is_ok())); + let results = ledger.create_transfers(&[ + funding_transfer(501, ISSUER_SRC, USER_SRC, 10_000, SRC), + funding_transfer(502, ISSUER_DST, LP_DST, 50_000, DST), + ]); + assert!(results.iter().all(|result| result.is_ok())); + ledger +} + +fn request() -> ConversionRequest { + ConversionRequest { + conversion_id: 777, + transfer_ids: vec![601, 602, 603], + user_source: USER_SRC, + lp_source: LP_SRC, + fee_account: Some(FEE), + lp_dest: LP_DST, + user_dest: USER_DST, + source_ledger: SRC, + dest_ledger: DST, + amount_in: 1_000, + fee_amount: 25, + quote: RateQuote { + numerator: 2, + denominator: 1, + authorisation_id: "auth-777".to_string(), + }, + } +} + +type TestExecutor = ConversionExecutor; + +fn executor() -> TestExecutor { + ConversionExecutor::new(funded_ledger(), InMemoryIntentStore::new()) +} + +#[test] +fn posted_conversion_legs_findable_by_user_data_128() { + let mut executor = executor(); + let record = executor.execute(&request()).expect("conversion posts"); + assert_eq!(record.state, IntentState::Posted); + assert_eq!(record.amount_out, 2_000); + + // Acceptance: both legs (all three, with the fee leg) findable by + // user_data_128 = conversion_id. + let legs = executor.backend.transfers_with_user_data_128(777); + assert_eq!(legs.len(), 3); + assert!(legs.iter().all(|leg| leg.user_data_128 == 777)); + + // Balances moved exactly once, on the right ledgers. + assert_eq!( + executor + .backend + .account_balance(USER_SRC) + .unwrap() + .spendable(), + 8_975 + ); + assert_eq!( + executor + .backend + .account_balance(LP_SRC) + .unwrap() + .credits_posted, + 1_000 + ); + assert_eq!( + executor + .backend + .account_balance(FEE) + .unwrap() + .credits_posted, + 25 + ); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 2_000 + ); + assert_eq!( + executor + .backend + .account_balance(LP_DST) + .unwrap() + .spendable(), + 48_000 + ); +} + +#[test] +fn atomic_failure_moves_nothing() { + // #2063 §4: one leg of a linked batch is forced to fail (the LP + // leg exceeds the LP's guarded balance) — no balance moves and no + // leg is stored. + let mut executor = executor(); + let mut record = executor.prepare(&request()).expect("intent prepared"); + + // Drain the LP destination account after the write-ahead intent, + // so T3 must fail inside the batch. + let drain = funding_transfer(900, LP_DST, USER_DST, 49_000, DST); + assert!(executor.backend.create_transfers(&[drain])[0].is_ok()); + + let before_user = executor.backend.account_balance(USER_SRC).unwrap(); + let before_lp_src = executor.backend.account_balance(LP_SRC).unwrap(); + assert!(executor.submit(&mut record).is_err()); + + assert_eq!( + executor.backend.account_balance(USER_SRC).unwrap(), + before_user + ); + assert_eq!( + executor.backend.account_balance(LP_SRC).unwrap(), + before_lp_src + ); + assert!( + executor + .backend + .transfers_with_user_data_128(777) + .is_empty(), + "no leg of a failed linked batch may be stored" + ); + // The record stays Submitted (unresolved) for the recovery scanner. + assert_eq!(record.state, IntentState::Submitted); +} + +#[test] +fn linked_chain_failure_marks_other_legs_linked_event_failed() { + let mut ledger = funded_ledger(); + let chain = vec![ + Transfer { + id: 700, + debit_account_id: USER_SRC, + credit_account_id: LP_SRC, + amount: 100, + ledger: SRC, + user_data_128: 42, + code: 1, + linked: true, + }, + Transfer { + id: 701, + debit_account_id: LP_DST, + credit_account_id: USER_DST, + amount: 999_999, + ledger: DST, + user_data_128: 42, + code: 1, + linked: false, + }, + ]; + let results = ledger.create_transfers(&chain); + assert_eq!(results[0], Err(TransferError::LinkedEventFailed)); + assert_eq!(results[1], Err(TransferError::DebitsMustNotExceedCredits)); + assert!(ledger.transfers_with_user_data_128(42).is_empty()); +} + +#[test] +fn crash_after_submission_recovers_without_double_posting() { + // #2063 §4: crash between submission and the Posted state write. + // The legs are in the ledger; the record still says Submitted. + // The scanner must mark it Posted by lookup and move nothing again. + let mut executor = executor(); + let mut record = executor.prepare(&request()).expect("intent prepared"); + record.state = IntentState::Submitted; + executor.store.put(&record).unwrap(); + let results = executor.backend.create_transfers(&record.legs); + assert!( + results + .iter() + .all(|result| matches!(result, Ok(()) | Err(TransferError::Exists))) + ); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("reconcile"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::AlreadyPosted)]); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 2_000, + "balances must reflect exactly one posting" + ); + assert_eq!( + executor.store.get(777).unwrap().unwrap().state, + IntentState::Posted + ); +} + +#[test] +fn crash_before_submission_resubmits_same_ids() { + // Crash after the write-ahead intent but before submission: no + // legs in the ledger. The scanner resubmits the persisted legs + // with their original IDs; a second scan finds nothing unresolved. + let mut executor = executor(); + let record = executor.prepare(&request()).expect("intent prepared"); + assert_eq!(record.state, IntentState::Recorded); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("reconcile"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::Resubmitted)]); + assert_eq!(executor.backend.transfers_with_user_data_128(777).len(), 3); + assert_eq!( + executor + .backend + .account_balance(USER_DST) + .unwrap() + .credits_posted, + 2_000 + ); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("second reconcile is a no-op"); + assert!(outcomes.is_empty()); +} + +#[test] +fn insufficient_lp_inventory_fails_preflight() { + // #2063 §4: LP pre-flight — a conversion the LP cannot cover is + // rejected before any intent is written or transfer submitted. + let mut executor = executor(); + let mut big = request(); + big.amount_in = 40_000; // amount_out = 80_000 > LP's 50_000 + assert!(executor.prepare(&big).is_err()); + assert!(executor.store.get(777).unwrap().is_none()); + assert!( + executor + .backend + .transfers_with_user_data_128(777) + .is_empty() + ); +} + +#[test] +fn file_intent_store_write_ahead_survives_reopen() { + // The write-ahead record is the crash-recovery contract: prepare + // with a file store, drop everything, reopen, and reconcile. + let dir = std::env::temp_dir().join(format!("id-currency-poc-intents-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut backend = funded_ledger(); + { + let store = FileIntentStore::open(dir.clone()).expect("open store"); + let mut executor = ConversionExecutor::new(funded_ledger(), store); + // Prepare against a throwaway ledger; only the intent matters here. + let record = executor.prepare(&request()).expect("intent prepared"); + assert_eq!(record.state, IntentState::Recorded); + } + let mut store = FileIntentStore::open(dir.clone()).expect("reopen store"); + let outcomes = reconcile(&mut backend, &mut store, RecoveryPolicy::Resubmit) + .expect("reconcile after reopen"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::Resubmitted)]); + assert_eq!(backend.transfers_with_user_data_128(777).len(), 3); + let _ = std::fs::remove_dir_all(&dir); +} + +// --- Regression tests for the Codex review findings on PR #3873 --- + +#[test] +fn zero_denominator_quote_is_rejected_not_a_panic() { + let mut executor = executor(); + let mut bad = request(); + bad.quote.denominator = 0; + assert!(executor.prepare(&bad).is_err()); + assert!(executor.store.get(777).unwrap().is_none()); +} + +#[test] +fn overflowing_quote_is_rejected_not_saturated() { + let mut executor = executor(); + let mut bad = request(); + bad.quote.numerator = u128::MAX; + bad.quote.denominator = 1; + assert!(executor.prepare(&bad).is_err()); + assert!(executor.store.get(777).unwrap().is_none()); +} + +#[test] +fn duplicate_transfer_id_in_one_chain_is_rejected() { + // Two legs sharing one transfer ID must not both stage balance + // changes while only the first is journaled. + let mut ledger = funded_ledger(); + let first = Transfer { + id: 700, + debit_account_id: ISSUER_SRC, + credit_account_id: USER_SRC, + amount: 100, + ledger: SRC, + user_data_128: 43, + code: 1, + linked: true, + }; + let second = Transfer { + id: 700, + debit_account_id: ISSUER_SRC, + credit_account_id: LP_SRC, + amount: 200, + ledger: SRC, + user_data_128: 43, + code: 1, + linked: false, + }; + let results = ledger.create_transfers(&[first, second]); + assert!(results.iter().all(|result| result.is_err())); + assert!(ledger.transfers_with_user_data_128(43).is_empty()); + assert_eq!( + ledger.account_balance(USER_SRC).unwrap().spendable(), + 10_000, + "no balance may move for a rejected duplicate-ID chain" + ); +} + +#[test] +fn recovery_does_not_trust_transfer_id_existence_alone() { + // A prepared no-fee conversion whose transfer IDs collide with + // the fixture's funding transfers (501/502, different contents) + // is Inconsistent, never AlreadyPosted. + let mut executor = executor(); + let mut colliding = request(); + colliding.fee_amount = 0; + colliding.fee_account = None; + colliding.transfer_ids = vec![501, 502]; + let record = executor.prepare(&colliding).expect("intent prepared"); + assert_eq!(record.legs.len(), 2); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("reconcile"); + assert_eq!(outcomes, vec![(777, ReconcileOutcome::Inconsistent)]); + assert_eq!( + executor.store.get(777).unwrap().unwrap().state, + IntentState::Recorded, + "a mismatched record stays unresolved" + ); +} + +#[test] +fn conversion_id_reuse_cannot_replace_persisted_intent() { + let mut executor = executor(); + let record = executor.execute(&request()).expect("conversion posts"); + + // An identical retry reuses the original record, state included. + let again = executor + .prepare(&request()) + .expect("identical retry reuses the persisted intent"); + assert_eq!(again, record); + + // A conflicting retry is rejected and the original survives. + let mut conflicting = request(); + conflicting.amount_in = 500; + conflicting.transfer_ids = vec![611, 612, 613]; + assert!(executor.prepare(&conflicting).is_err()); + assert_eq!(executor.store.get(777).unwrap().unwrap(), record); +} + +#[test] +fn recovery_scan_continues_after_a_rejected_resubmission() { + let mut executor = executor(); + let _record_a = executor.prepare(&request()).expect("intent A prepared"); + let mut request_b = request(); + request_b.conversion_id = 888; + request_b.transfer_ids = vec![604, 605, 606]; + request_b.amount_in = 100; + let _record_b = executor.prepare(&request_b).expect("intent B prepared"); + + // Drain the LP destination so A's resubmission (amount_out 2_000) + // is rejected while B's (200) still posts. + let drain = funding_transfer(900, LP_DST, USER_DST, 49_000, DST); + assert!(executor.backend.create_transfers(&[drain])[0].is_ok()); + + let outcomes = reconcile( + &mut executor.backend, + &mut executor.store, + RecoveryPolicy::Resubmit, + ) + .expect("one rejected resubmission must not abort the scan"); + assert_eq!(outcomes.len(), 2); + assert!(outcomes.contains(&(777, ReconcileOutcome::ResubmissionRejected))); + assert!(outcomes.contains(&(888, ReconcileOutcome::Resubmitted))); + assert_eq!(executor.backend.transfers_with_user_data_128(888).len(), 3); +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 1ce9e5e772..39ea5a3650 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -169,6 +169,7 @@ pub mod cli; pub mod commands; pub use id_core::connectivity; pub mod currency; +pub mod currency_poc; pub mod dht; #[cfg(feature = "world")] pub mod directory;