From 07571539829316a82f2a888fa31b939d3366ec6f Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 17 Nov 2026 03:58:38 -0600 Subject: [PATCH] =?UTF-8?q?feat(id):=20grant=20service=20core=20=E2=80=94?= =?UTF-8?q?=20grant=20record,=20store,=20pending-ledger=20seam,=20register?= =?UTF-8?q?/vest/void/partial-refund=20(#2294)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/id/Cargo.lock | 1 + .../id/crates/id-currency-registry/Cargo.toml | 1 + .../migrations/0002_grants.down.sql | 6 + .../migrations/0002_grants.up.sql | 48 + .../crates/id-currency-registry/src/grants.rs | 1108 +++++++++++++++++ .../id/crates/id-currency-registry/src/lib.rs | 15 + .../tests/grants_acceptance.rs | 228 ++++ 7 files changed, 1407 insertions(+) create mode 100644 pkgs/id/crates/id-currency-registry/migrations/0002_grants.down.sql create mode 100644 pkgs/id/crates/id-currency-registry/migrations/0002_grants.up.sql create mode 100644 pkgs/id/crates/id-currency-registry/src/grants.rs create mode 100644 pkgs/id/crates/id-currency-registry/tests/grants_acceptance.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index fdf3fd1ebd..8f95ce5b0f 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4778,6 +4778,7 @@ name = "id-currency-registry" version = "0.1.0" dependencies = [ "blake3", + "sha2 0.11.0", ] [[package]] diff --git a/pkgs/id/crates/id-currency-registry/Cargo.toml b/pkgs/id/crates/id-currency-registry/Cargo.toml index 543463e4db..45e569a7f7 100644 --- a/pkgs/id/crates/id-currency-registry/Cargo.toml +++ b/pkgs/id/crates/id-currency-registry/Cargo.toml @@ -11,6 +11,7 @@ default = [] [dependencies] blake3 = "1" +sha2 = "0.11" [lints.rust] unsafe_code = "warn" diff --git a/pkgs/id/crates/id-currency-registry/migrations/0002_grants.down.sql b/pkgs/id/crates/id-currency-registry/migrations/0002_grants.down.sql new file mode 100644 index 0000000000..35c325923c --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/migrations/0002_grants.down.sql @@ -0,0 +1,6 @@ +-- Reverse of migration 0002 (grant table, issue #2294). + +DROP INDEX IF EXISTS grant_record_pending_window; +DROP INDEX IF EXISTS grant_record_user; +DROP INDEX IF EXISTS grant_record_live_key_hash; +DROP TABLE IF EXISTS grant_record; diff --git a/pkgs/id/crates/id-currency-registry/migrations/0002_grants.up.sql b/pkgs/id/crates/id-currency-registry/migrations/0002_grants.up.sql new file mode 100644 index 0000000000..54615c8a9b --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/migrations/0002_grants.up.sql @@ -0,0 +1,48 @@ +-- Migration 0002: the grant table (design +-- 2026-10-29T12-10-00Z_design_refundable_grants_pending_transfers, +-- section 2.3; slice G1 of the grant service, issue #2294). +-- +-- The control-plane record TigerBeetle cannot hold: which Steam +-- key (by hash — the key itself is never stored) a pending +-- transfer's value came from, and whether it is still revocable. +-- Ids and transfer ids are TigerBeetle u128s, stored as decimal +-- text like migration 0001's account_id; amounts are u128, +-- stored as numeric(39,0). Times are unix seconds (bigint), +-- matching the in-memory store's record exactly. + +CREATE TABLE grant_record ( + id text PRIMARY KEY, + steam_key_hash bytea NOT NULL CHECK (octet_length(steam_key_hash) = 32), + user_id text NOT NULL, + ledger bigint NOT NULL CHECK (ledger BETWEEN 1 AND 4294967295), + amount numeric(39, 0) NOT NULL CHECK (amount > 0), + state text NOT NULL DEFAULT 'pending' + CHECK (state IN ('pending', 'posted', 'voided', 'expired', + 'clawback_pending', 'clawback_settled', 'debt')), + pending_transfer_id text NOT NULL UNIQUE, + resolution_transfer_id text UNIQUE, + window_started_at bigint NOT NULL, + window_ends_at bigint NOT NULL CHECK (window_ends_at >= window_started_at), + created_at bigint NOT NULL, + updated_at bigint NOT NULL, + attempt_count integer NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), + last_error text, + correction_of text REFERENCES grant_record (id) +); + +-- A key redeems once, ever: at most one live (non-voided) grant +-- per steam_key_hash. A voided grant's hash may recur only on its +-- own correction chain (enforced by the store seam; this index is +-- the schema half of the rule). +CREATE UNIQUE INDEX grant_record_live_key_hash + ON grant_record (steam_key_hash) + WHERE state <> 'voided'; + +-- The GET /users/{id}/grants read. +CREATE INDEX grant_record_user ON grant_record (user_id, id); + +-- The reconciler's sweep (design section 6.3): pending grants +-- whose window has closed. +CREATE INDEX grant_record_pending_window + ON grant_record (window_ends_at) + WHERE state = 'pending'; diff --git a/pkgs/id/crates/id-currency-registry/src/grants.rs b/pkgs/id/crates/id-currency-registry/src/grants.rs new file mode 100644 index 0000000000..5f7e80bb67 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/src/grants.rs @@ -0,0 +1,1108 @@ +//! Grant service — slice G1 of the refundable-grants design +//! (#2065, issue #2294). +//! +//! The design (`doc/2026-10-29T12-10-00Z_design_refundable_grants_pending_transfers`, +//! sections 2.2–2.4, 4, and 6.3) grants premium tokens as one +//! `TigerBeetle` *pending* transfer per Steam key, so a refund that +//! arrives inside the window can void the hold instead of clawing +//! back posted balance. This module is the control-plane half of +//! that design: +//! +//! - the `grant` record of design section 2.3 ([`Grant`]), with the +//! `correction_of` lineage field section 4 adds for +//! void-and-reissue partial refunds; +//! - a store seam ([`GrantStore`]) with an in-memory implementation +//! ([`InMemoryGrantStore`]) enforcing the same rules migration +//! `0002` enforces — one live grant per `steam_key_hash`, a key +//! redeems once ever — so the acceptance behaviour is testable +//! without a database, exactly like the registry's [`Store`] +//! seam; +//! - a pending-transfer ledger seam ([`PendingLedger`]) with an +//! in-memory stub ([`StubLedger`]) enforcing `TigerBeetle`'s +//! at-most-once resolution, so the service can be proven against +//! the design's stub direction (issue #2292 gates only the +//! dev-cluster acceptance runs, not this build); +//! - the service itself ([`GrantService`]): register / vest / void +//! / partial refund, with the gateway's HTTP mapping (design +//! section 2.4) left to the gateway layer — an +//! [`GrantError::AlreadyResolved`] *is* the API's `409` outcome. +//! +//! The rule section 4 states plainly, enforced here: **partial +//! posting is for policy, void-and-reissue is for refunds.** This +//! slice implements the refund path; a policy partial-vest is a +//! follow-on. The vesting automation / reconciler that sweeps +//! expired holds (section 6.3) is likewise a separate issue; the +//! `Expired` state and the intent-first write order here are what +//! it will reconcile against. +//! +//! [`Store`]: crate::store::Store + +use std::collections::BTreeMap; +use std::fmt; + +use sha2::{Digest, Sha256}; + +use crate::factory::transfer_code; + +/// The `TigerBeetle` transfer `code` for a grant's pending transfer. +/// +/// The first code of the reserved pending-hold redemption range +/// (design section 2.2 asks for a dedicated grant range; the +/// factory's reserved table already sets `0xF000..=0xFFFF` aside +/// for pending-hold redemption, #2065). +pub const GRANT_TRANSFER_CODE: u16 = transfer_code::PENDING_HOLD_REDEMPTION_START; + +/// Default slack added to the vesting window. +/// +/// It forms a pending transfer's `TigerBeetle` timeout (design +/// section 6.3 recommends +72h): the timeout is a safety net +/// against a dead service, never the vesting trigger. +pub const DEFAULT_TIMEOUT_SLACK_SECONDS: u64 = 72 * 60 * 60; + +/// The `sha256` of a Steam key. +/// +/// Design section 2.3: the key itself is never stored in the +/// ledger or the control plane, only its hash; the same hash's +/// first eight bytes ride on the transfer as `user_data_64`. +#[must_use] +pub fn steam_key_hash(steam_key: &str) -> [u8; 32] { + let digest = Sha256::digest(steam_key.as_bytes()); + let mut hash = [0u8; 32]; + hash.copy_from_slice(&digest); + hash +} + +/// The `user_data_64` form of a steam key hash: its first eight +/// bytes as a big-endian `u64`. +#[must_use] +pub fn steam_key_hash_u64(hash: &[u8; 32]) -> u64 { + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(&hash[..8]); + u64::from_be_bytes(bytes) +} + +/// The lifecycle state of a grant (design sections 2.1 and 2.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum GrantState { + /// The pending transfer is submitted; the hold is unresolved. + Pending, + /// The hold posted (`post_pending_transfer`); tokens are + /// ordinary posted balance from here on. + Posted, + /// The hold was voided (`void_pending_transfer`) — the refund + /// path. + Voided, + /// The hold hit its `TigerBeetle` timeout unresolved; a + /// reconcilable state, not a loss (section 6.3). + Expired, + /// A late refund (after posting) is being clawed back. + ClawbackPending, + /// The clawback transfer settled. + ClawbackSettled, + /// The clawback failed because the holder already spent the + /// balance; the bounded-exposure debt record (section 6). + Debt, +} + +impl GrantState { + /// The state as stored in the `grant` table (migration `0002` + /// checks `state` against exactly these strings). + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Posted => "posted", + Self::Voided => "voided", + Self::Expired => "expired", + Self::ClawbackPending => "clawback_pending", + Self::ClawbackSettled => "clawback_settled", + Self::Debt => "debt", + } + } + + /// Whether the grant's hold is already resolved (a further + /// vest/void is the idempotent `409` outcome, never a second + /// resolution). + #[must_use] + pub const fn is_resolved(self) -> bool { + !matches!(self, Self::Pending) + } +} + +impl fmt::Display for GrantState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// One row of the `grant` table. +/// +/// Covers design section 2.3, plus `correction_of` from section +/// 4. The database is a projection with intent; `TigerBeetle` is +/// the truth about money — every state change is written +/// intent-first, transfer-second, confirm-third, so a crash in +/// between leaves a reconcilable row rather than an orphaned hold. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Grant { + /// Control-plane grant id; also `user_data_128` on the + /// transfer. + pub id: u128, + /// `sha256` of the Steam key (the key itself is never stored). + pub steam_key_hash: [u8; 32], + /// The user the grant is for. + pub user_id: String, + /// The premium-token ledger (`TigerBeetle` ledger u32). + pub ledger: u32, + /// Grant amount in the ledger's smallest unit. + pub amount: u128, + /// Current lifecycle state. + pub state: GrantState, + /// The pending transfer holding the grant's value. + pub pending_transfer_id: u128, + /// The post or void transfer that resolved the hold, once + /// resolved. + pub resolution_transfer_id: Option, + /// Window start (unix seconds): when the key was redeemed. + pub window_started_at: u64, + /// Window end (unix seconds): when the grant may vest. A + /// reissue keeps its original grant's window — the refund + /// window is anchored at redemption, not at reissue. + pub window_ends_at: u64, + /// Row creation time (unix seconds). + pub created_at: u64, + /// Row last-update time (unix seconds). + pub updated_at: u64, + /// How many times a ledger operation for this grant has been + /// attempted (the reconciler's retry signal). + pub attempt_count: u32, + /// The most recent ledger error, if any. + pub last_error: Option, + /// For a reissue after a partial refund: the grant it corrects + /// (design section 4's lineage link). + pub correction_of: Option, +} + +/// A grant-store failure. Each variant mirrors a constraint in +/// migration `0002`, named so a caller can tell a uniqueness +/// rejection (a verdict about the request) from an unknown +/// reference. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GrantStoreError { + /// A grant with this id already exists; ids are never reused. + DuplicateGrantId(u128), + /// A live grant already holds this `steam_key_hash` (a key + /// redeems once, ever — design section 2.4). + DuplicateKeyHash, + /// No grant exists for this id. + UnknownGrant(u128), +} + +impl fmt::Display for GrantStoreError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DuplicateGrantId(id) => write!(f, "grant {id} already exists"), + Self::DuplicateKeyHash => { + write!(f, "a live grant already holds this steam_key_hash") + } + Self::UnknownGrant(id) => write!(f, "grant {id} does not exist"), + } + } +} + +impl std::error::Error for GrantStoreError {} + +/// The grant store seam: the operations the service needs, with +/// migration `0002`'s constraints as the contract. +pub trait GrantStore { + /// Insert a new grant row. + /// + /// # Errors + /// + /// [`GrantStoreError::DuplicateGrantId`] if the id is taken; + /// [`GrantStoreError::DuplicateKeyHash`] if a live grant + /// already holds the key hash. A *voided* grant's hash may be + /// re-inserted only by its own correction (a reissue whose + /// `correction_of` names the voided grant). + fn insert_grant(&mut self, grant: &Grant) -> Result<(), GrantStoreError>; + + /// Replace an existing grant row (the service's + /// confirm-third write). + /// + /// # Errors + /// + /// [`GrantStoreError::UnknownGrant`] if the id does not exist. + fn update_grant(&mut self, grant: &Grant) -> Result<(), GrantStoreError>; + + /// The grant with this id, if any. + fn grant(&self, id: u128) -> Option; + + /// The most recent grant recorded for this key hash, if any + /// (live or resolved — register's idempotency check reads + /// every state). + fn grant_by_key_hash(&self, hash: &[u8; 32]) -> Option; + + /// Every grant recorded for a user, in grant-id order (the + /// `GET /users/{id}/grants` read). + fn grants_for_user(&self, user_id: &str) -> Vec; +} + +/// In-memory [`GrantStore`] enforcing migration `0002`'s rules, so +/// behaviour proven against it is the behaviour the schema +/// enforces. +#[derive(Debug, Default)] +pub struct InMemoryGrantStore { + by_id: BTreeMap, + /// Key hash -> grant ids in insertion order (a hash can recur + /// only across a voided grant and its corrections). + by_hash: BTreeMap<[u8; 32], Vec>, +} + +impl InMemoryGrantStore { + /// A new, empty store. + #[must_use] + pub fn new() -> Self { + Self::default() + } +} + +impl GrantStore for InMemoryGrantStore { + fn insert_grant(&mut self, grant: &Grant) -> Result<(), GrantStoreError> { + if self.by_id.contains_key(&grant.id) { + return Err(GrantStoreError::DuplicateGrantId(grant.id)); + } + if let Some(ids) = self.by_hash.get(&grant.steam_key_hash) { + for id in ids { + if let Some(existing) = self.by_id.get(id) { + let is_own_correction = existing.state == GrantState::Voided + && grant.correction_of == Some(existing.id); + if existing.state != GrantState::Voided || !is_own_correction { + return Err(GrantStoreError::DuplicateKeyHash); + } + } + } + } + self.by_id.insert(grant.id, grant.clone()); + self.by_hash + .entry(grant.steam_key_hash) + .or_default() + .push(grant.id); + Ok(()) + } + + fn update_grant(&mut self, grant: &Grant) -> Result<(), GrantStoreError> { + if !self.by_id.contains_key(&grant.id) { + return Err(GrantStoreError::UnknownGrant(grant.id)); + } + self.by_id.insert(grant.id, grant.clone()); + Ok(()) + } + + fn grant(&self, id: u128) -> Option { + self.by_id.get(&id).cloned() + } + + fn grant_by_key_hash(&self, hash: &[u8; 32]) -> Option { + self.by_hash + .get(hash) + .and_then(|ids| ids.last()) + .and_then(|id| self.by_id.get(id).cloned()) + } + + fn grants_for_user(&self, user_id: &str) -> Vec { + self.by_id + .values() + .filter(|grant| grant.user_id == user_id) + .cloned() + .collect() + } +} + +/// One pending transfer to submit (design section 2.2): the whole +/// grant as a single hold, never a stream of small ones. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PendingTransferSpec { + /// The transfer's id (also the grant row's + /// `pending_transfer_id`). + pub id: u128, + /// Debits side: the issuer grant-pool account. + pub debit_account_id: u128, + /// Credits side: the holder's premium account. + pub credit_account_id: u128, + /// Hold amount. + pub amount: u128, + /// The premium-token ledger. + pub ledger: u32, + /// Transfer code ([`GRANT_TRANSFER_CODE`]). + pub code: u16, + /// The control-plane grant id. + pub user_data_128: u128, + /// Hash of the Steam key (never the key itself). + pub user_data_64: u64, + /// Safety-net timeout in seconds (window + slack, section + /// 6.3). + pub timeout_seconds: u64, +} + +/// A pending-ledger failure. +/// +/// The `Already*` variants are *verdicts* — `TigerBeetle`'s +/// at-most-once resolution answering a repeat attempt — not +/// transport failures; the service maps them to its own +/// already-resolved outcome. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LedgerError { + /// The hold already posted (a repeat resolution attempt). + AlreadyPosted(u128), + /// The hold already voided (a repeat resolution attempt). + AlreadyVoided(u128), + /// The hold already expired (a repeat resolution attempt). + AlreadyExpired(u128), + /// No transfer exists with this id. + UnknownTransfer(u128), + /// The resolution amount exceeds the held amount. + AmountExceedsHold { + /// The pending transfer. + pending_id: u128, + /// The held amount. + held: u128, + /// The attempted resolution amount. + attempted: u128, + }, + /// A non-verdict cluster failure (transport, timeout, + /// unavailable). + Cluster(String), +} + +impl fmt::Display for LedgerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AlreadyPosted(id) => write!(f, "pending transfer {id} already posted"), + Self::AlreadyVoided(id) => write!(f, "pending transfer {id} already voided"), + Self::AlreadyExpired(id) => write!(f, "pending transfer {id} already expired"), + Self::UnknownTransfer(id) => write!(f, "pending transfer {id} does not exist"), + Self::AmountExceedsHold { + pending_id, + held, + attempted, + } => write!( + f, + "resolution amount {attempted} exceeds the {held} held by transfer {pending_id}" + ), + Self::Cluster(message) => write!(f, "cluster error: {message}"), + } + } +} + +impl std::error::Error for LedgerError {} + +/// The pending-transfer ledger seam: the three `TigerBeetle` +/// operations the grant service needs. The production +/// implementation is the gateway's `TigerBeetle` client; tests +/// substitute [`StubLedger`]. +pub trait PendingLedger { + /// Submit a pending transfer. Submitting the same transfer id + /// twice with the same spec is an idempotent success (the + /// service's intent-first retry path relies on it). + /// + /// # Errors + /// + /// [`LedgerError::Cluster`] on a non-verdict failure, or if + /// the id is taken by a *different* spec. + fn create_pending(&mut self, spec: &PendingTransferSpec) -> Result<(), LedgerError>; + + /// Post a hold (`post_pending_transfer`): all of `amount` + /// becomes posted balance on the credit account; any unposted + /// remainder of the hold is restored. + /// + /// # Errors + /// + /// The `Already*` verdicts on a repeat resolution; + /// [`LedgerError::UnknownTransfer`] for an unknown id; + /// [`LedgerError::AmountExceedsHold`] if `amount` exceeds the + /// hold. + fn post_pending( + &mut self, + pending_id: u128, + resolution_id: u128, + amount: u128, + ) -> Result<(), LedgerError>; + + /// Void a hold (`void_pending_transfer`): the whole hold is + /// released; nothing posts. Voiding is all-or-nothing — a + /// partial refund voids and reissues (design section 4). + /// + /// # Errors + /// + /// The `Already*` verdicts on a repeat resolution; + /// [`LedgerError::UnknownTransfer`] for an unknown id. + fn void_pending(&mut self, pending_id: u128, resolution_id: u128) -> Result<(), LedgerError>; +} + +/// The stub's record of one transfer. +#[derive(Debug, Clone, PartialEq, Eq)] +struct StubTransfer { + spec: PendingTransferSpec, + state: GrantState, + resolution_id: Option, +} + +/// In-memory [`PendingLedger`] enforcing `TigerBeetle`'s two-phase semantics. +/// +/// As the design states them: a hold reserves `credits_pending` +/// on the credit account; exactly one resolution (post / void / +/// timeout) releases it, at most once; posting part restores the +/// remainder. The balances it tracks are the test oracle for "a +/// refund left no posted credit behind". +#[derive(Debug, Default)] +pub struct StubLedger { + transfers: BTreeMap, + credits_pending: BTreeMap, + credits_posted: BTreeMap, + debits_pending: BTreeMap, +} + +impl StubLedger { + /// A new, empty stub ledger. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Posted balance of an account (the spendable truth). + #[must_use] + pub fn credits_posted(&self, account_id: u128) -> u128 { + self.credits_posted.get(&account_id).copied().unwrap_or(0) + } + + /// Pending (held, unspendable) balance of an account. + #[must_use] + pub fn credits_pending(&self, account_id: u128) -> u128 { + self.credits_pending.get(&account_id).copied().unwrap_or(0) + } + + /// Simulate the safety-net timeout firing on a hold: the hold + /// expires and the reservation is restored, unresolved + /// (design section 2.1). A resolved hold ignores the timeout, + /// as in `TigerBeetle`. + pub fn expire_pending(&mut self, pending_id: u128) { + let Some(transfer) = self.transfers.get_mut(&pending_id) else { + return; + }; + if transfer.state == GrantState::Pending { + transfer.state = GrantState::Expired; + let amount = transfer.spec.amount; + let credit = transfer.spec.credit_account_id; + let debit = transfer.spec.debit_account_id; + release(&mut self.credits_pending, credit, amount); + release(&mut self.debits_pending, debit, amount); + } + } + + fn resolution_verdict(&self, pending_id: u128) -> Result<&StubTransfer, LedgerError> { + let transfer = self + .transfers + .get(&pending_id) + .ok_or(LedgerError::UnknownTransfer(pending_id))?; + match transfer.state { + GrantState::Pending => Ok(transfer), + GrantState::Posted => Err(LedgerError::AlreadyPosted(pending_id)), + GrantState::Voided => Err(LedgerError::AlreadyVoided(pending_id)), + _ => Err(LedgerError::AlreadyExpired(pending_id)), + } + } +} + +fn release(map: &mut BTreeMap, account: u128, amount: u128) { + if let Some(balance) = map.get_mut(&account) { + *balance = balance.saturating_sub(amount); + } +} + +fn add(map: &mut BTreeMap, account: u128, amount: u128) { + *map.entry(account).or_insert(0) += amount; +} + +impl PendingLedger for StubLedger { + fn create_pending(&mut self, spec: &PendingTransferSpec) -> Result<(), LedgerError> { + if let Some(existing) = self.transfers.get(&spec.id) { + if existing.spec == *spec { + return Ok(()); + } + return Err(LedgerError::Cluster(format!( + "transfer {} already exists with a different spec", + spec.id + ))); + } + self.transfers.insert( + spec.id, + StubTransfer { + spec: spec.clone(), + state: GrantState::Pending, + resolution_id: None, + }, + ); + add( + &mut self.credits_pending, + spec.credit_account_id, + spec.amount, + ); + add(&mut self.debits_pending, spec.debit_account_id, spec.amount); + Ok(()) + } + + fn post_pending( + &mut self, + pending_id: u128, + resolution_id: u128, + amount: u128, + ) -> Result<(), LedgerError> { + let spec = self.resolution_verdict(pending_id)?.spec.clone(); + if amount > spec.amount { + return Err(LedgerError::AmountExceedsHold { + pending_id, + held: spec.amount, + attempted: amount, + }); + } + if let Some(transfer) = self.transfers.get_mut(&pending_id) { + transfer.state = GrantState::Posted; + transfer.resolution_id = Some(resolution_id); + } + release( + &mut self.credits_pending, + spec.credit_account_id, + spec.amount, + ); + release(&mut self.debits_pending, spec.debit_account_id, spec.amount); + add(&mut self.credits_posted, spec.credit_account_id, amount); + Ok(()) + } + + fn void_pending(&mut self, pending_id: u128, resolution_id: u128) -> Result<(), LedgerError> { + let spec = self.resolution_verdict(pending_id)?.spec.clone(); + if let Some(transfer) = self.transfers.get_mut(&pending_id) { + transfer.state = GrantState::Voided; + transfer.resolution_id = Some(resolution_id); + } + release( + &mut self.credits_pending, + spec.credit_account_id, + spec.amount, + ); + release(&mut self.debits_pending, spec.debit_account_id, spec.amount); + Ok(()) + } +} + +/// Grant-service configuration. +/// +/// The window length is a product pin (design section 3), ruled +/// on issue #2296 to come from config — 14 days, the Steam refund +/// window — and *never* be hard-coded in the service; it arrives +/// here from the caller. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct GrantConfig { + /// Vesting window in seconds (window start = key redemption). + pub window_seconds: u64, + /// Slack added to the window to form the pending transfer's + /// timeout (section 6.3). + pub timeout_slack_seconds: u64, +} + +impl GrantConfig { + /// A config with the design's recommended timeout slack + /// ([`DEFAULT_TIMEOUT_SLACK_SECONDS`]). + #[must_use] + pub const fn new(window_seconds: u64) -> Self { + Self { + window_seconds, + timeout_slack_seconds: DEFAULT_TIMEOUT_SLACK_SECONDS, + } + } +} + +/// A grant-service failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GrantError { + /// The grant is already resolved; vest/void on it is the + /// idempotent `409` outcome of design section 2.4, carrying + /// the state the grant actually reached. + AlreadyResolved { + /// The grant. + grant_id: u128, + /// The state it already reached. + state: GrantState, + }, + /// No grant exists for this id. + UnknownGrant(u128), + /// The amount is not usable for this operation (a zero grant, + /// or a refund that is not a proper partial amount). + InvalidAmount { + /// What was attempted. + attempted: u128, + /// The grant's amount (the bound the attempt violated). + grant_amount: u128, + }, + /// The store rejected the write. + Store(GrantStoreError), + /// The ledger rejected the transfer — a non-verdict failure; + /// the grant row keeps the attempt and the error for the + /// reconciler. + Ledger(LedgerError), +} + +impl fmt::Display for GrantError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AlreadyResolved { grant_id, state } => { + write!(f, "grant {grant_id} is already resolved ({state})") + } + Self::UnknownGrant(id) => write!(f, "grant {id} does not exist"), + Self::InvalidAmount { + attempted, + grant_amount, + } => write!( + f, + "amount {attempted} is not valid against a grant amount of {grant_amount}" + ), + Self::Store(err) => write!(f, "{err}"), + Self::Ledger(err) => write!(f, "{err}"), + } + } +} + +impl std::error::Error for GrantError {} + +impl From for GrantError { + fn from(err: GrantStoreError) -> Self { + Self::Store(err) + } +} + +impl From for GrantError { + fn from(err: LedgerError) -> Self { + Self::Ledger(err) + } +} + +/// What a caller asks [`GrantService::register`] to grant. +/// +/// The account ids are the factory's derived ids (grant pool on +/// the issuer side, the holder's premium account on the credit +/// side); deriving them is the factory's job, not the service's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RegisterGrant { + /// The Steam key being redeemed (hashed by the service, never + /// stored). + pub steam_key: String, + /// The user the grant is for. + pub user_id: String, + /// The premium-token ledger. + pub ledger: u32, + /// Grant amount. + pub amount: u128, + /// Debits side: the issuer grant-pool account id. + pub grant_pool_account_id: u128, + /// Credits side: the holder's premium account id. + pub holder_account_id: u128, +} + +/// The grant service, over a [`GrantStore`] and a [`PendingLedger`]. +/// +/// Stateless apart from its id counters: grant ids and transfer +/// ids are allocated monotonically from 1 in their own domains +/// (the production store allocates grant ids from the `grant` +/// table's sequence — migration `0002` — and transfer ids are +/// the caller's `TigerBeetle` ids; the counters here are the +/// in-memory slice's allocator, and the seam is the store/ledger +/// pair, not the counters). +#[derive(Debug)] +pub struct GrantService { + store: S, + ledger: L, + config: GrantConfig, + next_grant_id: u128, + next_transfer_id: u128, +} + +impl GrantService { + /// A service over the given store, ledger, and config. + pub const fn new(store: S, ledger: L, config: GrantConfig) -> Self { + Self { + store, + ledger, + config, + next_grant_id: 1, + next_transfer_id: 1, + } + } + + /// The store (read access for callers and tests). + pub const fn store(&self) -> &S { + &self.store + } + + /// The ledger (read access for callers and tests). + pub const fn ledger(&self) -> &L { + &self.ledger + } + + /// The ledger, mutably (the reconciler's and tests' handle — + /// e.g. firing a stub hold's timeout). + pub const fn ledger_mut(&mut self) -> &mut L { + &mut self.ledger + } + + /// Register a grant for a redeemed Steam key (`POST /grants`, + /// design section 2.4): record the intent, submit the pending + /// transfer, confirm the row. Idempotent on `steam_key_hash` — + /// a key redeems once, ever, so a repeat registration returns + /// the existing grant unchanged instead of holding twice. + /// + /// # Errors + /// + /// [`GrantError::InvalidAmount`] for a zero amount; + /// [`GrantError::Ledger`] if the cluster rejects the hold (the + /// row remains, pending, with the attempt recorded for the + /// reconciler). + pub fn register(&mut self, request: &RegisterGrant, now: u64) -> Result { + let hash = steam_key_hash(&request.steam_key); + if let Some(existing) = self.store.grant_by_key_hash(&hash) { + return Ok(existing); + } + if request.amount == 0 { + return Err(GrantError::InvalidAmount { + attempted: 0, + grant_amount: 0, + }); + } + let grant_id = self.alloc_grant_id(); + let pending_id = self.alloc_transfer_id(); + let mut grant = Grant { + id: grant_id, + steam_key_hash: hash, + user_id: request.user_id.clone(), + ledger: request.ledger, + amount: request.amount, + state: GrantState::Pending, + pending_transfer_id: pending_id, + resolution_transfer_id: None, + window_started_at: now, + window_ends_at: now.saturating_add(self.config.window_seconds), + created_at: now, + updated_at: now, + attempt_count: 0, + last_error: None, + correction_of: None, + }; + self.store.insert_grant(&grant)?; + let spec = self.pending_spec( + &grant, + request.grant_pool_account_id, + request.holder_account_id, + ); + grant.attempt_count += 1; + if let Err(err) = self.ledger.create_pending(&spec) { + grant.last_error = Some(err.to_string()); + grant.updated_at = now; + self.store.update_grant(&grant)?; + return Err(GrantError::Ledger(err)); + } + grant.updated_at = now; + self.store.update_grant(&grant)?; + Ok(grant) + } + + /// Vest a grant (`POST /grants/{id}/vest`): post its hold in + /// full. The caller owns the window policy — the reconciler + /// calls this at window close; the service enforces only + /// at-most-once resolution. + /// + /// # Errors + /// + /// [`GrantError::UnknownGrant`]; [`GrantError::AlreadyResolved`] + /// (the `409`) if the grant already resolved — including when + /// the *ledger* reports the resolution the row had not yet + /// confirmed, in which case the row is first synced to the + /// ledger's truth. + pub fn vest(&mut self, grant_id: u128, now: u64) -> Result { + self.resolve(grant_id, now, Resolution::Vest) + } + + /// Void a grant (`POST /grants/{id}/void`): release its hold + /// in full — the refund path. + /// + /// # Errors + /// + /// As [`GrantService::vest`]. + pub fn void(&mut self, grant_id: u128, now: u64) -> Result { + self.resolve(grant_id, now, Resolution::Void) + } + + /// Refund a proper part of a pending grant (design section + /// 4): void the whole hold, then reissue the remainder as a + /// new pending grant linked by `correction_of`, keeping the + /// original window. Returns the voided original and the + /// reissue. Nothing posts, so a refund can never leave posted + /// credit behind. + /// + /// # Errors + /// + /// [`GrantError::UnknownGrant`]; + /// [`GrantError::AlreadyResolved`] if the grant already + /// resolved; [`GrantError::InvalidAmount`] unless + /// `0 < refund_amount < grant.amount` (a full refund is a + /// plain [`GrantService::void`]). + pub fn refund_partial( + &mut self, + grant_id: u128, + refund_amount: u128, + grant_pool_account_id: u128, + holder_account_id: u128, + now: u64, + ) -> Result<(Grant, Grant), GrantError> { + let original = self + .store + .grant(grant_id) + .ok_or(GrantError::UnknownGrant(grant_id))?; + if original.state.is_resolved() { + return Err(GrantError::AlreadyResolved { + grant_id, + state: original.state, + }); + } + if refund_amount == 0 || refund_amount >= original.amount { + return Err(GrantError::InvalidAmount { + attempted: refund_amount, + grant_amount: original.amount, + }); + } + let voided = self.resolve(grant_id, now, Resolution::Void)?; + let reissue_id = self.alloc_grant_id(); + let reissue_pending_id = self.alloc_transfer_id(); + let mut reissue = Grant { + id: reissue_id, + steam_key_hash: voided.steam_key_hash, + user_id: voided.user_id.clone(), + ledger: voided.ledger, + amount: voided.amount - refund_amount, + state: GrantState::Pending, + pending_transfer_id: reissue_pending_id, + resolution_transfer_id: None, + window_started_at: voided.window_started_at, + window_ends_at: voided.window_ends_at, + created_at: now, + updated_at: now, + attempt_count: 0, + last_error: None, + correction_of: Some(voided.id), + }; + self.store.insert_grant(&reissue)?; + let spec = self.reissue_spec(&reissue, &voided, grant_pool_account_id, holder_account_id); + reissue.attempt_count += 1; + if let Err(err) = self.ledger.create_pending(&spec) { + reissue.last_error = Some(err.to_string()); + reissue.updated_at = now; + self.store.update_grant(&reissue)?; + return Err(GrantError::Ledger(err)); + } + reissue.updated_at = now; + self.store.update_grant(&reissue)?; + Ok((voided, reissue)) + } + + /// One grant by id (`GET /grants/{id}`). + #[must_use] + pub fn get(&self, grant_id: u128) -> Option { + self.store.grant(grant_id) + } + + /// Every grant for a user (`GET /users/{id}/grants`). + #[must_use] + pub fn grants_for_user(&self, user_id: &str) -> Vec { + self.store.grants_for_user(user_id) + } + + fn resolve( + &mut self, + grant_id: u128, + now: u64, + resolution: Resolution, + ) -> Result { + let mut grant = self + .store + .grant(grant_id) + .ok_or(GrantError::UnknownGrant(grant_id))?; + if grant.state.is_resolved() { + return Err(GrantError::AlreadyResolved { + grant_id, + state: grant.state, + }); + } + let resolution_id = self.alloc_transfer_id(); + grant.attempt_count += 1; + let outcome = match resolution { + Resolution::Vest => { + self.ledger + .post_pending(grant.pending_transfer_id, resolution_id, grant.amount) + } + Resolution::Void => self + .ledger + .void_pending(grant.pending_transfer_id, resolution_id), + }; + match outcome { + Ok(()) => { + grant.state = match resolution { + Resolution::Vest => GrantState::Posted, + Resolution::Void => GrantState::Voided, + }; + grant.resolution_transfer_id = Some(resolution_id); + grant.last_error = None; + grant.updated_at = now; + self.store.update_grant(&grant)?; + Ok(grant) + } + Err( + err @ (LedgerError::AlreadyPosted(_) + | LedgerError::AlreadyVoided(_) + | LedgerError::AlreadyExpired(_)), + ) => { + // The ledger resolved the hold but the row never + // confirmed it (a crash between transfer and + // confirm): sync the row to the ledger's truth, + // then answer with the same 409 outcome. + grant.state = match err { + LedgerError::AlreadyPosted(_) => GrantState::Posted, + LedgerError::AlreadyVoided(_) => GrantState::Voided, + _ => GrantState::Expired, + }; + grant.updated_at = now; + self.store.update_grant(&grant)?; + Err(GrantError::AlreadyResolved { + grant_id, + state: grant.state, + }) + } + Err(err) => { + grant.last_error = Some(err.to_string()); + grant.updated_at = now; + self.store.update_grant(&grant)?; + Err(GrantError::Ledger(err)) + } + } + } + + fn pending_spec( + &self, + grant: &Grant, + grant_pool_account_id: u128, + holder_account_id: u128, + ) -> PendingTransferSpec { + PendingTransferSpec { + id: grant.pending_transfer_id, + debit_account_id: grant_pool_account_id, + credit_account_id: holder_account_id, + amount: grant.amount, + ledger: grant.ledger, + code: GRANT_TRANSFER_CODE, + user_data_128: grant.id, + user_data_64: steam_key_hash_u64(&grant.steam_key_hash), + timeout_seconds: self + .config + .window_seconds + .saturating_add(self.config.timeout_slack_seconds), + } + } + + fn reissue_spec( + &self, + reissue: &Grant, + original: &Grant, + grant_pool_account_id: u128, + holder_account_id: u128, + ) -> PendingTransferSpec { + // The reissue holds the remainder of the original grant's + // value between the same two accounts (the caller + // re-derives them through the factory, as at register — + // the grant row carries no account columns, design section + // 2.3). Its timeout covers the *remaining* window: the + // refund window is anchored at the original redemption. + let remaining_window = original + .window_ends_at + .saturating_sub(original.window_started_at); + PendingTransferSpec { + id: reissue.pending_transfer_id, + debit_account_id: grant_pool_account_id, + credit_account_id: holder_account_id, + amount: reissue.amount, + ledger: reissue.ledger, + code: GRANT_TRANSFER_CODE, + user_data_128: reissue.id, + user_data_64: steam_key_hash_u64(&reissue.steam_key_hash), + timeout_seconds: remaining_window.saturating_add(self.config.timeout_slack_seconds), + } + } + + const fn alloc_grant_id(&mut self) -> u128 { + let id = self.next_grant_id; + self.next_grant_id += 1; + id + } + + const fn alloc_transfer_id(&mut self) -> u128 { + let id = self.next_transfer_id; + self.next_transfer_id += 1; + id + } +} + +/// Which resolution a `resolve` call performs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Resolution { + Vest, + Void, +} + +/// Forwarding so a caller can keep a handle to the store (the +/// gateway wiring and the acceptance tests both do). +impl GrantStore for &mut T { + fn insert_grant(&mut self, grant: &Grant) -> Result<(), GrantStoreError> { + (**self).insert_grant(grant) + } + + fn update_grant(&mut self, grant: &Grant) -> Result<(), GrantStoreError> { + (**self).update_grant(grant) + } + + fn grant(&self, id: u128) -> Option { + (**self).grant(id) + } + + fn grant_by_key_hash(&self, hash: &[u8; 32]) -> Option { + (**self).grant_by_key_hash(hash) + } + + fn grants_for_user(&self, user_id: &str) -> Vec { + (**self).grants_for_user(user_id) + } +} + +/// Forwarding so a caller can keep a handle to the ledger. +impl PendingLedger for &mut T { + fn create_pending(&mut self, spec: &PendingTransferSpec) -> Result<(), LedgerError> { + (**self).create_pending(spec) + } + + fn post_pending( + &mut self, + pending_id: u128, + resolution_id: u128, + amount: u128, + ) -> Result<(), LedgerError> { + (**self).post_pending(pending_id, resolution_id, amount) + } + + fn void_pending(&mut self, pending_id: u128, resolution_id: u128) -> Result<(), LedgerError> { + (**self).void_pending(pending_id, resolution_id) + } +} diff --git a/pkgs/id/crates/id-currency-registry/src/lib.rs b/pkgs/id/crates/id-currency-registry/src/lib.rs index 1ad790937d..675c913f58 100644 --- a/pkgs/id/crates/id-currency-registry/src/lib.rs +++ b/pkgs/id/crates/id-currency-registry/src/lib.rs @@ -28,6 +28,7 @@ pub mod allocator; pub mod factory; +pub mod grants; pub mod registry; pub mod store; @@ -36,6 +37,12 @@ pub use factory::{ ACCOUNT_DOMAIN_SEP, AccountCluster, AccountFlags, AccountSpec, ClusterError, CreateOutcome, CurrencyAccounts, Factory, FactoryError, PLATFORM_OWNER_ID, account_spec, derive_account_id, }; +pub use grants::{ + DEFAULT_TIMEOUT_SLACK_SECONDS, GRANT_TRANSFER_CODE, Grant, GrantConfig, GrantError, + GrantService, GrantState, GrantStore, GrantStoreError, InMemoryGrantStore, LedgerError, + PendingLedger, PendingTransferSpec, RegisterGrant, StubLedger, steam_key_hash, + steam_key_hash_u64, +}; pub use registry::{ AccountKind, AccountRecord, CurrencyRecord, CurrencyStatus, IssuerGrant, IssuerRole, RegisterAccount, RegisterCurrency, Registry, RegistryError, SupplyPolicy, @@ -46,6 +53,14 @@ pub use store::{InMemoryStore, Store, StoreError}; /// sequences and function, and the never-delete guard. pub const MIGRATION_0001_UP: &str = include_str!("../migrations/0001_currency_registry.up.sql"); +/// The second migration: the `grant` table of the refundable- +/// grants design (section 2.3), its live-key-hash uniqueness +/// index, and the reconciler's pending-window sweep index. +pub const MIGRATION_0002_UP: &str = include_str!("../migrations/0002_grants.up.sql"); + +/// The reverse of [`MIGRATION_0002_UP`]. +pub const MIGRATION_0002_DOWN: &str = include_str!("../migrations/0002_grants.down.sql"); + /// The reverse of [`MIGRATION_0001_UP`]. pub const MIGRATION_0001_DOWN: &str = include_str!("../migrations/0001_currency_registry.down.sql"); diff --git a/pkgs/id/crates/id-currency-registry/tests/grants_acceptance.rs b/pkgs/id/crates/id-currency-registry/tests/grants_acceptance.rs new file mode 100644 index 0000000000..2993eeccb0 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/tests/grants_acceptance.rs @@ -0,0 +1,228 @@ +//! Acceptance tests for the grant service (slice G1, issue +//! #2294), against the design +//! `doc/2026-10-29T12-10-00Z_design_refundable_grants_pending_transfers`. +//! +//! Every test names its oracle: the grant row's state (the +//! control-plane projection) and the stub ledger's balances (the +//! money truth — pending is held and unspendable, posted is +//! spendable). The brief's named cases are register-vest, +//! register-void, double-resolution 409, and partial refund +//! leaving no posted credit. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use id_currency_registry::grants::{ + GrantConfig, GrantError, GrantService, GrantState, InMemoryGrantStore, RegisterGrant, + StubLedger, steam_key_hash, +}; + +const POOL: u128 = 1001; +const HOLDER: u128 = 2002; +const LEDGER: u32 = 7; +const WINDOW_SECONDS: u64 = 14 * 24 * 60 * 60; +const NOW: u64 = 1_000_000; + +fn service() -> GrantService { + GrantService::new( + InMemoryGrantStore::new(), + StubLedger::new(), + GrantConfig::new(WINDOW_SECONDS), + ) +} + +fn request(key: &str, user: &str, amount: u128) -> RegisterGrant { + RegisterGrant { + steam_key: key.to_string(), + user_id: user.to_string(), + ledger: LEDGER, + amount, + grant_pool_account_id: POOL, + holder_account_id: HOLDER, + } +} + +#[test] +fn register_then_vest_posts_full_amount() { + // Oracle: the stub ledger's balances + the grant row's state. + let mut svc = service(); + let grant = svc + .register(&request("key-vest", "user-1", 500), NOW) + .expect("register"); + assert_eq!(grant.state, GrantState::Pending); + assert_eq!(grant.window_ends_at, NOW + WINDOW_SECONDS); + assert_eq!(svc.ledger().credits_pending(HOLDER), 500); + assert_eq!(svc.ledger().credits_posted(HOLDER), 0); + + let vested = svc.vest(grant.id, NOW + 60).expect("vest"); + assert_eq!(vested.state, GrantState::Posted); + assert!(vested.resolution_transfer_id.is_some()); + assert_eq!(svc.ledger().credits_pending(HOLDER), 0); + assert_eq!(svc.ledger().credits_posted(HOLDER), 500); +} + +#[test] +fn register_then_void_releases_hold_and_posts_nothing() { + // Oracle: after a void, the holder has no posted credit and + // no pending hold — the refund path of design section 2.1. + let mut svc = service(); + let grant = svc + .register(&request("key-void", "user-1", 500), NOW) + .expect("register"); + let voided = svc.void(grant.id, NOW + 60).expect("void"); + assert_eq!(voided.state, GrantState::Voided); + assert_eq!(svc.ledger().credits_pending(HOLDER), 0); + assert_eq!(svc.ledger().credits_posted(HOLDER), 0); +} + +#[test] +fn double_resolution_is_already_resolved() { + // Oracle: the GrantError::AlreadyResolved verdict (the API's + // 409) carrying the state the grant actually reached, for + // every second resolution attempt. + let mut svc = service(); + let voided = svc + .register(&request("key-dr-void", "user-1", 10), NOW) + .expect("register"); + svc.void(voided.id, NOW).expect("void"); + assert_eq!( + svc.vest(voided.id, NOW), + Err(GrantError::AlreadyResolved { + grant_id: voided.id, + state: GrantState::Voided, + }) + ); + + let posted = svc + .register(&request("key-dr-vest", "user-1", 10), NOW) + .expect("register"); + svc.vest(posted.id, NOW).expect("vest"); + assert_eq!( + svc.void(posted.id, NOW), + Err(GrantError::AlreadyResolved { + grant_id: posted.id, + state: GrantState::Posted, + }) + ); + assert_eq!( + svc.vest(posted.id, NOW), + Err(GrantError::AlreadyResolved { + grant_id: posted.id, + state: GrantState::Posted, + }) + ); +} + +#[test] +fn partial_refund_leaves_no_posted_credit() { + // Oracle: design section 4 — void-and-reissue. After a + // partial refund of a pending grant, posted credit is zero, + // the original is voided, and the remainder rides a new + // pending grant linked by correction_of, in the same window. + let mut svc = service(); + let grant = svc + .register(&request("key-partial", "user-1", 100), NOW) + .expect("register"); + let (voided, reissue) = svc + .refund_partial(grant.id, 30, POOL, HOLDER, NOW + 60) + .expect("partial refund"); + assert_eq!(voided.state, GrantState::Voided); + assert_eq!(reissue.state, GrantState::Pending); + assert_eq!(reissue.amount, 70); + assert_eq!(reissue.correction_of, Some(grant.id)); + assert_eq!(reissue.window_ends_at, grant.window_ends_at); + assert_eq!(svc.ledger().credits_posted(HOLDER), 0); + assert_eq!(svc.ledger().credits_pending(HOLDER), 70); + + // The reissue still vests normally at window close. + let vested = svc.vest(reissue.id, NOW + 120).expect("vest reissue"); + assert_eq!(vested.state, GrantState::Posted); + assert_eq!(svc.ledger().credits_posted(HOLDER), 70); + assert_eq!(svc.ledger().credits_pending(HOLDER), 0); +} + +#[test] +fn register_is_idempotent_on_steam_key() { + // Oracle: one key, one grant, one hold — a repeat + // registration returns the existing grant and the pending + // balance is the grant amount once, not twice. + let mut svc = service(); + let first = svc + .register(&request("key-same", "user-1", 250), NOW) + .expect("register"); + let second = svc + .register(&request("key-same", "user-1", 250), NOW + 10) + .expect("re-register"); + assert_eq!(first.id, second.id); + assert_eq!(svc.ledger().credits_pending(HOLDER), 250); + assert_eq!(svc.grants_for_user("user-1").len(), 1); + + let other = svc + .register(&request("key-other", "user-1", 5), NOW) + .expect("other key"); + assert_ne!(other.id, first.id); + assert_eq!(svc.grants_for_user("user-1").len(), 2); +} + +#[test] +fn refund_amount_must_be_a_proper_partial() { + // Oracle: InvalidAmount for a zero refund and for a full + // refund (a full refund is a plain void, not a reissue). + let mut svc = service(); + let grant = svc + .register(&request("key-bounds", "user-1", 100), NOW) + .expect("register"); + assert_eq!( + svc.refund_partial(grant.id, 0, POOL, HOLDER, NOW), + Err(GrantError::InvalidAmount { + attempted: 0, + grant_amount: 100, + }) + ); + assert_eq!( + svc.refund_partial(grant.id, 100, POOL, HOLDER, NOW), + Err(GrantError::InvalidAmount { + attempted: 100, + grant_amount: 100, + }) + ); + // Neither attempt resolved or reissued anything. + assert_eq!(svc.get(grant.id).expect("grant").state, GrantState::Pending); + assert_eq!(svc.ledger().credits_pending(HOLDER), 100); +} + +#[test] +fn expired_hold_syncs_row_and_reports_already_resolved() { + // Oracle: when the ledger's timeout fires first (section + // 6.3), a vest attempt syncs the row to the ledger's truth + // (Expired) and answers AlreadyResolved — never a late post. + let mut svc = service(); + let grant = svc + .register(&request("key-expire", "user-1", 40), NOW) + .expect("register"); + svc.ledger_mut().expire_pending(grant.pending_transfer_id); + assert_eq!( + svc.vest(grant.id, NOW + WINDOW_SECONDS + 1), + Err(GrantError::AlreadyResolved { + grant_id: grant.id, + state: GrantState::Expired, + }) + ); + assert_eq!(svc.get(grant.id).expect("grant").state, GrantState::Expired); + assert_eq!(svc.ledger().credits_posted(HOLDER), 0); + assert_eq!(svc.ledger().credits_pending(HOLDER), 0); +} + +#[test] +fn unknown_grant_is_unknown() { + let mut svc = service(); + assert_eq!(svc.vest(999, NOW), Err(GrantError::UnknownGrant(999))); + assert_eq!(svc.void(999, NOW), Err(GrantError::UnknownGrant(999))); +} + +#[test] +fn key_hash_is_sha256() { + // Oracle: the published sha256 test vector for "test". + let hash = steam_key_hash("test"); + let expected_prefix: [u8; 8] = [0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65]; + assert_eq!(hash[..8], expected_prefix); +}