From a435fa68be7e660d4253aeff884cce1c8dc4a577 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 11:59:18 -0600 Subject: [PATCH] feat(id): currency status transitions (freeze/sunset) in the registry and gateway service (#13342) Registry (id-currency-registry): - Store::set_currency_status is the status-transition write (InMemoryStore implements it against the currency row). - Registry::freeze_currency / sunset_currency share one issuer-only set_status with a documented transition table: Active -> Frozen, Active -> Sunset, Frozen -> Sunset (sunset stays reachable from frozen); sunset is terminal (InvalidTransition); repeats are idempotent successes. - RegistryError::InvalidTransition names the from/to statuses. Gateway service (pkgs/id): - handle() executes Freeze/Sunset through the registry write and records each as a posted intent (posted_simple, like registration and grants); the transition's idempotence is the write-ahead answer for a retry whose intent finalize was lost. - open() replays posted freeze/sunset intents over the rebuilt registry records (freezes before sunsets; the transitions are monotone), so a status survives restart. - F3 authorize(): lifecycle ops are authorized on existence plus issuer only (they are how a currency leaves Active); value ops keep requiring Active, and RegistryView already maps the registry status onto the view's active flag, so issue/transfer on a frozen or sunset currency refuse with InactiveCurrency. Layering documented in the module docs. Tests: 5 new registry acceptance tests (happy paths, non-issuer refusal, idempotent repeats, unknown currency, sunset terminal); a gateway authorize test pinning lifecycle authorization on an inactive currency; 3 new gateway-service tests (execute + value ops refuse, issuer- only + retry/repeat answers, restart replay). The old unsupported_ops_refuse_by_name test now pins a balance read instead of freeze/sunset. --- .../id-currency-registry/src/registry.rs | 105 ++++- .../crates/id-currency-registry/src/store.rs | 36 +- .../id-currency-registry/tests/acceptance.rs | 102 +++++ pkgs/id/src/currency/gateway.rs | 38 +- pkgs/id/src/currency/gateway_service.rs | 377 ++++++++++++++++-- 5 files changed, 626 insertions(+), 32 deletions(-) diff --git a/pkgs/id/crates/id-currency-registry/src/registry.rs b/pkgs/id/crates/id-currency-registry/src/registry.rs index a0f8956b6e..336aa40c03 100644 --- a/pkgs/id/crates/id-currency-registry/src/registry.rs +++ b/pkgs/id/crates/id-currency-registry/src/registry.rs @@ -195,7 +195,8 @@ pub struct RegisterAccount { pub enum RegistryError { /// No currency is registered under this id. UnknownCurrency(String), - /// `grant_minter` was attempted by an account that is not the + /// An issuer-only write (`grant_minter`, or a status + /// transition) was attempted by an account that is not the /// currency's issuer (design section 4.2). NotIssuer { /// The currency whose issuer set was checked. @@ -203,6 +204,19 @@ pub enum RegistryError { /// The account that attempted the grant. account_id: String, }, + /// A status transition the lifecycle does not allow. + /// Sunset is terminal: a sunset currency cannot be frozen or + /// otherwise moved. Repeating the transition that produced + /// the current status is not an error — it succeeds without + /// a write (see [`Registry::freeze_currency`]). + InvalidTransition { + /// The currency whose transition was refused. + currency_id: String, + /// The status the currency is in. + from: CurrencyStatus, + /// The status the caller tried to move it to. + to: CurrencyStatus, + }, /// The store rejected the write. Store(StoreError), /// The allocator could not hand out a ledger. @@ -216,10 +230,19 @@ impl fmt::Display for RegistryError { Self::NotIssuer { currency_id, account_id, + } => { + write!(f, "account {account_id} is not the issuer of {currency_id}") + } + Self::InvalidTransition { + currency_id, + from, + to, } => { write!( f, - "account {account_id} is not the issuer of {currency_id} and cannot grant minters" + "currency {currency_id} is {} and cannot become {}", + from.as_str(), + to.as_str() ) } Self::Store(err) => write!(f, "{err}"), @@ -333,6 +356,84 @@ impl Registry { Ok(()) } + /// Freeze a currency (design section 2.2): while frozen the + /// gateway refuses new writes. Issuer-only. See + /// [`Registry::set_status`] for the transition table. + pub fn freeze_currency( + &mut self, + currency_id: &str, + requested_by: impl Into, + ) -> Result { + self.set_status(currency_id, CurrencyStatus::Frozen, requested_by) + } + + /// Sunset a currency (design section 2.2): no new writes; + /// redemption window only. Issuer-only, and terminal — a + /// sunset currency cannot be frozen or otherwise moved. See + /// [`Registry::set_status`] for the transition table. + pub fn sunset_currency( + &mut self, + currency_id: &str, + requested_by: impl Into, + ) -> Result { + self.set_status(currency_id, CurrencyStatus::Sunset, requested_by) + } + + /// The one status-transition write (issue #13342). Only the + /// currency's issuer may move its status — the same + /// issuer-only rule as `grant_minter` (design section 4.2). + /// + /// The transition table, decided here: + /// + /// - `Active -> Frozen` (freeze) and `Active -> Sunset` + /// (sunset) are the moves out of active. + /// - `Frozen -> Sunset` is allowed: sunset stays reachable + /// from frozen, so freezing is never a trap short of the + /// terminal state. + /// - Sunset is terminal: `Sunset -> Frozen` is refused with + /// [`RegistryError::InvalidTransition`]. + /// - Repeating the transition that produced the current + /// status (freeze on frozen, sunset on sunset) is an + /// idempotent success, not an error: the caller is told + /// the record as it stands, with no second write. This is + /// what lets the gateway service answer a retry whose + /// intent finalize was lost after the transition landed. + fn set_status( + &mut self, + currency_id: &str, + target: CurrencyStatus, + requested_by: impl Into, + ) -> Result { + let requested_by = requested_by.into(); + let currency = self + .store + .currency_by_id(currency_id) + .ok_or_else(|| RegistryError::UnknownCurrency(currency_id.to_owned()))? + .clone(); + if currency.issuer_id != requested_by { + return Err(RegistryError::NotIssuer { + currency_id: currency_id.to_owned(), + account_id: requested_by, + }); + } + match (currency.status, target) { + (from, to) if from == to => Ok(currency), + (CurrencyStatus::Active, CurrencyStatus::Frozen | CurrencyStatus::Sunset) + | (CurrencyStatus::Frozen, CurrencyStatus::Sunset) => { + self.store.set_currency_status(currency.ledger_id, target)?; + Ok(CurrencyRecord { + status: target, + ..currency + }) + } + (from, to) => Err(RegistryError::InvalidTransition { + currency_id: currency_id.to_owned(), + from, + to, + }), + } + } + /// Record a factory account in the registry index (design /// section 3). The account id itself is derived by the factory /// (slice F2); this records that it exists for a currency. diff --git a/pkgs/id/crates/id-currency-registry/src/store.rs b/pkgs/id/crates/id-currency-registry/src/store.rs index 2eb5a7bc96..245cb71c7e 100644 --- a/pkgs/id/crates/id-currency-registry/src/store.rs +++ b/pkgs/id/crates/id-currency-registry/src/store.rs @@ -12,7 +12,7 @@ use std::collections::BTreeMap; use std::fmt; use crate::LedgerKind; -use crate::registry::{AccountRecord, CurrencyRecord, IssuerGrant}; +use crate::registry::{AccountRecord, CurrencyRecord, CurrencyStatus, IssuerGrant}; /// One row of `ledger_allocation` (design section 2.1). #[derive(Debug, Clone, PartialEq, Eq)] @@ -110,6 +110,16 @@ pub trait Store { /// Record a currency row for an allocated currency ledger. fn insert_currency(&mut self, record: CurrencyRecord) -> Result<(), StoreError>; + /// Set the lifecycle status of the currency recorded for + /// `ledger_id` (the registry's status-transition write, + /// #13342). Fails with [`StoreError::UnknownLedger`] if no + /// currency row exists for the ledger. + fn set_currency_status( + &mut self, + ledger_id: u32, + status: CurrencyStatus, + ) -> Result<(), StoreError>; + /// Look up a currency by its semantic id. fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord>; @@ -193,6 +203,22 @@ impl Store for InMemoryStore { Ok(()) } + fn set_currency_status( + &mut self, + ledger_id: u32, + status: CurrencyStatus, + ) -> Result<(), StoreError> { + let currency_id = self + .currencies_by_ledger + .get(&ledger_id) + .cloned() + .ok_or(StoreError::UnknownLedger(ledger_id))?; + if let Some(record) = self.currencies_by_id.get_mut(¤cy_id) { + record.status = status; + } + Ok(()) + } + fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord> { self.currencies_by_id.get(currency_id) } @@ -268,6 +294,14 @@ impl Store for &mut T { (**self).insert_currency(record) } + fn set_currency_status( + &mut self, + ledger_id: u32, + status: CurrencyStatus, + ) -> Result<(), StoreError> { + (**self).set_currency_status(ledger_id, status) + } + fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord> { (**self).currency_by_id(currency_id) } diff --git a/pkgs/id/crates/id-currency-registry/tests/acceptance.rs b/pkgs/id/crates/id-currency-registry/tests/acceptance.rs index bbad4f6de0..0afcff0dec 100644 --- a/pkgs/id/crates/id-currency-registry/tests/acceptance.rs +++ b/pkgs/id/crates/id-currency-registry/tests/acceptance.rs @@ -240,3 +240,105 @@ fn migration_creates_the_four_tables_with_the_named_constraints() { // Design section 6: the allocator entry point exists. assert!(sql.contains("create function allocate_ledger")); } + +// Status transitions (issue #13342). The oracle is the issue's +// Acceptance list: "Registry tests: transition happy paths, +// non-issuer refusal, repeat-transition behavior as documented." + +#[test] +fn issuer_can_freeze_then_sunset_and_sunset_is_terminal() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + // Sunset is reachable from frozen: freeze first. + let frozen = registry.freeze_currency("abc", "alice").unwrap(); + assert_eq!(frozen.status, CurrencyStatus::Frozen); + assert_eq!( + registry.resolve("abc").unwrap().status, + CurrencyStatus::Frozen, + "the store carries the new status" + ); + let sunset = registry.sunset_currency("abc", "alice").unwrap(); + assert_eq!(sunset.status, CurrencyStatus::Sunset); + // Sunset is terminal: freezing a sunset currency is a typed + // refusal naming the from/to statuses. + let err = registry.freeze_currency("abc", "alice").unwrap_err(); + assert_eq!( + err, + RegistryError::InvalidTransition { + currency_id: "abc".to_owned(), + from: CurrencyStatus::Sunset, + to: CurrencyStatus::Frozen, + } + ); +} + +#[test] +fn issuer_can_sunset_directly_from_active() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + let sunset = registry.sunset_currency("abc", "alice").unwrap(); + assert_eq!(sunset.status, CurrencyStatus::Sunset); + assert_eq!( + registry.resolve("abc").unwrap().status, + CurrencyStatus::Sunset + ); +} + +#[test] +fn only_the_issuer_can_transition_status() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + for attempt in [ + registry.freeze_currency("abc", "mallory"), + registry.sunset_currency("abc", "mallory"), + ] { + assert_eq!( + attempt.unwrap_err(), + RegistryError::NotIssuer { + currency_id: "abc".to_owned(), + account_id: "mallory".to_owned(), + } + ); + } + // The refusals moved nothing. + assert_eq!( + registry.resolve("abc").unwrap().status, + CurrencyStatus::Active + ); +} + +#[test] +fn repeat_transitions_are_idempotent_successes() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + // Freeze on frozen answers with the record as it stands. + let first = registry.freeze_currency("abc", "alice").unwrap(); + let repeat = registry.freeze_currency("abc", "alice").unwrap(); + assert_eq!(repeat, first); + // Sunset on sunset likewise. + let first = registry.sunset_currency("abc", "alice").unwrap(); + let repeat = registry.sunset_currency("abc", "alice").unwrap(); + assert_eq!(repeat, first); + assert_eq!(repeat.status, CurrencyStatus::Sunset); +} + +#[test] +fn transitions_on_an_unknown_currency_are_refused() { + let mut registry = Registry::new(InMemoryStore::new()); + assert_eq!( + registry.freeze_currency("nope", "alice").unwrap_err(), + RegistryError::UnknownCurrency("nope".to_owned()) + ); + assert_eq!( + registry.sunset_currency("nope", "alice").unwrap_err(), + RegistryError::UnknownCurrency("nope".to_owned()) + ); +} diff --git a/pkgs/id/src/currency/gateway.rs b/pkgs/id/src/currency/gateway.rs index c862c9888b..5ca1fcc5e3 100644 --- a/pkgs/id/src/currency/gateway.rs +++ b/pkgs/id/src/currency/gateway.rs @@ -654,14 +654,24 @@ pub fn authorize( read_check(registry, &history.currency, &history.account, account) } CurrencyOp::Freeze(freeze) => { - let record = active_currency(registry, &freeze.currency)?; + // Lifecycle ops are authorized on existence plus + // issuer only, not on the currency being active: + // freezing is how a currency leaves Active, and a + // repeat freeze must stay answerable. Transition + // legality (repeats, sunset terminal) is the + // registry's table (#13342); the value ops above + // keep requiring Active through `active_currency`. + let record = registered_currency(registry, &freeze.currency)?; if record.issuer_id != account { return Err(GatewayError::NotIssuer); } Ok(()) } CurrencyOp::Sunset(sunset) => { - let record = active_currency(registry, &sunset.currency)?; + // As freeze, and one step more: sunset must stay + // reachable from Frozen, so this arm cannot require + // Active either (#13342). + let record = registered_currency(registry, &sunset.currency)?; if record.issuer_id != account { return Err(GatewayError::NotIssuer); } @@ -1048,6 +1058,30 @@ mod tests { )); } + #[test] + fn lifecycle_ops_stay_authorized_for_the_issuer_on_an_inactive_currency() { + // Oracle: issue #13342 — freeze/sunset are how a currency + // leaves Active, so their authorization is existence plus + // issuer-only; requiring Active would make sunset + // unreachable from frozen and a repeat freeze + // unanswerable. Transition legality is the registry's + // table, not this layer's. + let mut reg = registry("issuer-account", &[]); + reg.currencies.get_mut(&[9; 32]).unwrap().active = false; + let freeze = CurrencyOp::Freeze(Freeze { currency: [9; 32] }); + let sunset = CurrencyOp::Sunset(Sunset { currency: [9; 32] }); + assert!(authorize(®, "issuer-account", &freeze).is_ok()); + assert!(authorize(®, "issuer-account", &sunset).is_ok()); + assert!(matches!( + authorize(®, "stranger-account", &freeze), + Err(GatewayError::NotIssuer) + )); + assert!(matches!( + authorize(®, "stranger-account", &sunset), + Err(GatewayError::NotIssuer) + )); + } + // Property-based coverage for the gateway protocol invariants // (Codex P1 on PR #7650). Oracles: (1) decode is the inverse of // encode for every operation schema and full-width u128 field; diff --git a/pkgs/id/src/currency/gateway_service.rs b/pkgs/id/src/currency/gateway_service.rs index 66b7ee069c..8a79d54602 100644 --- a/pkgs/id/src/currency/gateway_service.rs +++ b/pkgs/id/src/currency/gateway_service.rs @@ -55,17 +55,36 @@ //! property above this type, but the type is the seam it guards: //! there is no second write path around it. //! -//! **Scope, stated plainly.** The service executes the same op +//! **Scope, stated plainly.** The service executes the op //! set the PoC proved — `register_currency`, `grant_minter`, -//! `issue`, `transfer`. `convert` is phase 5 (#3801/#3802); -//! `freeze`/`sunset` are authorized by F3 but the registry crate -//! has no status-transition write yet, so the service refuses -//! them by name rather than pretending; `balance`/`history` are -//! reads and stay off the write pipeline (see +//! `issue`, `transfer` — plus the lifecycle ops `freeze` and +//! `sunset` (#13342, next bullet). `convert` is phase 5 +//! (#3801/#3802); `balance`/`history` are reads and stay off +//! the write pipeline (see //! [`GatewayService::holder_balance`]). Abuse controls (design //! §4.3 step 6) and graph chain-continuity validation remain as //! absent as the PoC left them (its write-up items 10–11). //! +//! - **Lifecycle ops (#13342).** `freeze`/`sunset` execute +//! through the registry's status-transition write and are +//! recorded as posted intents like registration and grants: +//! no ledger transfer exists to write ahead of, and the +//! transition itself is idempotent, so a retry whose intent +//! finalize was lost re-executes harmlessly and is answered +//! with the receipt it should have had. [`GatewayService::open`] +//! replays posted freeze/sunset intents over the rebuilt +//! registry records, so a status survives restart. Which +//! layer refuses what: F3 authorization refuses the value +//! ops (`issue`, `transfer`, `convert`, `grant_minter`) on a +//! non-active currency with `InactiveCurrency` — the view's +//! `active` flag is the registry record's status, so a +//! transition lands in authorization the moment it lands in +//! the registry; lifecycle ops are authorized on existence +//! plus issuer only (sunset must stay reachable from +//! frozen); the registry owns transition legality — +//! issuer-only there too, repeats idempotent, sunset +//! terminal ([`RegistryError::InvalidTransition`]). +//! //! **Idempotency-key discipline.** The idempotency ID is a hash //! of (account, op, client request id). A client that reuses a //! client request id for a *different* request gets the original @@ -79,7 +98,7 @@ use std::path::PathBuf; use std::time::Duration; use id_currency_registry::{ - AccountKind, Factory, FactoryError, InMemoryStore, RegisterAccount, + AccountKind, CurrencyStatus, Factory, FactoryError, InMemoryStore, RegisterAccount, RegisterCurrency as RegistryRegister, Registry, RegistryError, Store as _, StoreError, SupplyPolicy, }; @@ -840,6 +859,27 @@ impl GatewayService { ))); } } + // Replay posted lifecycle transitions over the rebuilt + // records (#13342). Transitions are monotone (Active -> + // Frozen -> Sunset, sunset terminal), so applying every + // posted freeze before every posted sunset reproduces + // the pre-restart status whatever order they posted in. + for target_op in ["freeze", "sunset"] { + for intent in &all { + if intent.state != IntentState::Posted || intent.op != target_op { + continue; + } + let Some(currency_id) = &intent.currency_id else { + continue; + }; + let moved = if target_op == "freeze" { + registry.freeze_currency(currency_id, intent.account.clone()) + } else { + registry.sunset_currency(currency_id, intent.account.clone()) + }; + moved.map_err(ServiceError::Registry)?; + } + } Ok(Self { registry, backend, @@ -1041,6 +1081,18 @@ impl GatewayService { CurrencyOp::GrantMinter(op) => self.grant_minter(&authorized, op), CurrencyOp::Issue(op) => self.issue(&authorized, op, graph), CurrencyOp::Transfer(op) => self.transfer(&authorized, op, graph), + CurrencyOp::Freeze(op) => self.set_status( + &authorized, + &verified.request.op, + &op.currency, + CurrencyStatus::Frozen, + ), + CurrencyOp::Sunset(op) => self.set_status( + &authorized, + &verified.request.op, + &op.currency, + CurrencyStatus::Sunset, + ), other => Err(ServiceError::Unsupported(other.name())), } } @@ -1284,6 +1336,69 @@ impl GatewayService { Ok(sign_receipt_with(&self.gateway_key, receipt)?) } + /// Execute a `freeze`/`sunset` (#13342): the registry's + /// status-transition write, recorded as a posted intent the + /// same way registration and grants are. There is no ledger + /// transfer to write ahead of; the write-ahead discipline + /// for these ops is the transition's own idempotence — if + /// the intent finalize is lost to a crash after the + /// transition landed, the client's retry re-executes a + /// repeat transition, which the registry answers as an + /// idempotent success, and the intent is recorded then. + /// [`GatewayService::open`] replays posted transitions over + /// the rebuilt registry records, so the status survives + /// restarts. + fn set_status( + &mut self, + authorized: &Authorized, + op: &CurrencyOp, + key: &[u8; 32], + target: CurrencyStatus, + ) -> Result { + let currency_id = self + .currency_ids + .get(key) + .cloned() + .ok_or(ServiceError::UnknownCurrencyKey)?; + let record = match target { + CurrencyStatus::Frozen => self + .registry + .freeze_currency(¤cy_id, authorized.account.clone())?, + CurrencyStatus::Sunset => self + .registry + .sunset_currency(¤cy_id, authorized.account.clone())?, + CurrencyStatus::Active => { + return Err(ServiceError::Unsupported( + "no gateway op transitions a currency to active", + )); + } + }; + let receipt = Receipt { + op: op.name().to_owned(), + account: authorized.account.clone(), + idempotency: hex_encode(&authorized.idempotency.to_be_bytes()), + currency_id: Some(currency_id.clone()), + currency: Some(hex_encode(key)), + ledger_id: Some(record.ledger_id), + transfer_id: None, + graph_object: None, + }; + let intent = GatewayIntent::posted_simple( + authorized, + op, + currency_id, + Some(key), + record.ledger_id, + None, + None, + receipt.clone(), + ); + self.intents + .put(&intent) + .map_err(ServiceError::IntentStore)?; + Ok(sign_receipt_with(&self.gateway_key, receipt)?) + } + fn issue( &mut self, authorized: &Authorized, @@ -1612,8 +1727,9 @@ impl GatewayService { mod tests { use super::*; use crate::currency::gateway::{ - CurrencyRequest, Freeze as GwFreeze, GrantMinter as GwGrantMinter, Issue as GwIssue, - RegisterCurrency as GwRegister, Sunset as GwSunset, Transfer as GwTransfer, sign_request, + Balance as GwBalance, CurrencyRequest, Freeze as GwFreeze, + GrantMinter as GwGrantMinter, Issue as GwIssue, RegisterCurrency as GwRegister, + Sunset as GwSunset, Transfer as GwTransfer, sign_request, }; use crate::currency::gateway_poc::verify_receipt; use crate::currency::graph::{SupplyCap, sign_definition, sign_issue, sign_transfer}; @@ -2368,28 +2484,235 @@ mod tests { /// Ops the envelope authorizes but this service does not /// execute are refused by name, not silently mishandled: - /// freeze/sunset wait on a registry status-transition write - /// that does not exist yet. + /// reads stay off the write pipeline (the module docs' + /// scope statement), so a balance read names itself + /// unsupported here. #[test] fn unsupported_ops_refuse_by_name() { let mut fx = fixture_with(InMemoryLedger::default(), InMemoryIntentStore::new()); let (_register, currency, _definition) = registered(&mut fx); let key = *currency.compact_hash().as_bytes(); - for (id, op) in [ - (2_u128, CurrencyOp::Freeze(GwFreeze { currency: key })), - (3_u128, CurrencyOp::Sunset(GwSunset { currency: key })), - ] { - let request = CurrencyRequest { - client_request_id: id, - op, - }; - let device_key = fx.issuer.device_key.clone(); - let error = send(&mut fx, &device_key, &request, None) - .expect_err("unsupported op refused"); - assert!( - matches!(error, ServiceError::Unsupported(_)), - "got {error:?}", - ); - } + let request = CurrencyRequest { + client_request_id: 2, + op: CurrencyOp::Balance(GwBalance { + currency: key, + account: fx.alice.account.clone(), + }), + }; + let device_key = fx.alice.device_key.clone(); + let error = send(&mut fx, &device_key, &request, None).expect_err("unsupported op refused"); + assert!( + matches!(error, ServiceError::Unsupported(_)), + "got {error:?}", + ); + } + + /// #13342: freeze executes through the registry transition + /// and is recorded as a posted intent; the value ops then + /// refuse at authorization (the F3 view's `active` flag is + /// the registry record's status); sunset stays reachable + /// from frozen; sunset is terminal. + #[test] + fn freeze_and_sunset_execute_and_value_ops_refuse() { + let mut fx = fixture_with(InMemoryLedger::default(), InMemoryIntentStore::new()); + let (_register, currency, definition) = registered(&mut fx); + let key = *currency.compact_hash().as_bytes(); + let (_receipt, _issue_event) = issue_to_alice(&mut fx, ¤cy, &definition, 2, 100, 1); + + // Freeze by the issuer posts, verifies, and lands in + // the registry record. + let freeze = CurrencyRequest { + client_request_id: 10, + op: CurrencyOp::Freeze(GwFreeze { currency: key }), + }; + let device_key = fx.issuer.device_key.clone(); + let receipt = send(&mut fx, &device_key, &freeze, None).expect("freeze posts"); + assert!(verify_receipt(&fx.gateway_vk, &receipt)); + assert_eq!(receipt.receipt.op, "freeze"); + assert_eq!( + fx.svc.registry_record(&key).map(|record| record.status), + Some(CurrencyStatus::Frozen) + ); + + // Issue and transfer now refuse at authorization. + let token = TokenIssue { + currency: currency.compact_hash(), + amount: 10, + to: issuer_id(&fx.alice.account_key), + memo: None, + }; + let event = sign_issue( + &fx.issuer.account_key, + 2, + Some(definition.id), + ¤cy, + &token, + vec![], + ) + .expect("issue signs"); + let body = token.body().expect("body"); + let request = CurrencyRequest { + client_request_id: 11, + op: CurrencyOp::Issue(GwIssue { + currency: key, + amount: 10, + to: fx.alice.account.clone(), + }), + }; + let device_key = fx.issuer.device_key.clone(); + let error = send(&mut fx, &device_key, &request, Some((&event, &body))) + .expect_err("issue on a frozen currency refused"); + assert!( + matches!(error, ServiceError::Gateway(GatewayError::InactiveCurrency)), + "got {error:?}", + ); + let error = transfer_alice_to_bob(&mut fx, ¤cy, 12, 10, 0, None) + .expect_err("transfer on a frozen currency refused"); + assert!( + matches!(error, ServiceError::Gateway(GatewayError::InactiveCurrency)), + "got {error:?}", + ); + + // Sunset from frozen posts; the currency is terminal. + let sunset = CurrencyRequest { + client_request_id: 13, + op: CurrencyOp::Sunset(GwSunset { currency: key }), + }; + let device_key = fx.issuer.device_key.clone(); + let receipt = send(&mut fx, &device_key, &sunset, None).expect("sunset posts"); + assert!(verify_receipt(&fx.gateway_vk, &receipt)); + assert_eq!(receipt.receipt.op, "sunset"); + assert_eq!( + fx.svc.registry_record(&key).map(|record| record.status), + Some(CurrencyStatus::Sunset) + ); + + // Freeze after sunset: the registry's typed refusal. + let freeze = CurrencyRequest { + client_request_id: 14, + op: CurrencyOp::Freeze(GwFreeze { currency: key }), + }; + let device_key = fx.issuer.device_key.clone(); + let error = send(&mut fx, &device_key, &freeze, None) + .expect_err("freeze on a sunset currency refused"); + assert!( + matches!( + error, + ServiceError::Registry(RegistryError::InvalidTransition { .. }) + ), + "got {error:?}", + ); + } + + /// #13342: freeze is issuer-only at authorization, an exact + /// retry answers from the intent record, and a repeat under + /// a fresh request id succeeds idempotently. + #[test] + fn freeze_is_issuer_only_and_repeats_answer() { + let mut fx = fixture_with(InMemoryLedger::default(), InMemoryIntentStore::new()); + let (_register, currency, _definition) = registered(&mut fx); + let key = *currency.compact_hash().as_bytes(); + let freeze = CurrencyRequest { + client_request_id: 10, + op: CurrencyOp::Freeze(GwFreeze { currency: key }), + }; + + // A non-issuer is refused at authorization; nothing moves. + let device_key = fx.mallory.device_key.clone(); + let error = + send(&mut fx, &device_key, &freeze, None).expect_err("non-issuer freeze refused"); + assert!( + matches!(error, ServiceError::Gateway(GatewayError::NotIssuer)), + "got {error:?}", + ); + assert_eq!( + fx.svc.registry_record(&key).map(|record| record.status), + Some(CurrencyStatus::Active) + ); + + // The issuer freezes; the exact retry replays the same + // receipt from the intent record. + let device_key = fx.issuer.device_key.clone(); + let receipt = send(&mut fx, &device_key, &freeze, None).expect("freeze posts"); + let replay = send(&mut fx, &device_key, &freeze, None).expect("freeze retry replays"); + assert_eq!(replay.receipt, receipt.receipt); + + // A repeat under a fresh request id is an idempotent + // success, not an error. + let repeat = CurrencyRequest { + client_request_id: 11, + op: CurrencyOp::Freeze(GwFreeze { currency: key }), + }; + let device_key = fx.issuer.device_key.clone(); + let receipt = send(&mut fx, &device_key, &repeat, None).expect("repeat freeze answers"); + assert!(verify_receipt(&fx.gateway_vk, &receipt)); + assert_eq!( + fx.svc.registry_record(&key).map(|record| record.status), + Some(CurrencyStatus::Frozen) + ); + } + + /// #13342: a posted freeze survives a restart — `open` + /// replays the transition over the registry record rebuilt + /// from the register intent, and value ops stay refused. + #[test] + fn freeze_survives_restart_via_intent_replay() { + let dir = temp_store_dir("freeze-restart"); + let mut fx = fixture_with( + InMemoryLedger::default(), + FileIntentStore::open(dir.clone()).expect("store opens"), + ); + let (_register, currency, definition) = registered(&mut fx); + let key = *currency.compact_hash().as_bytes(); + let freeze = CurrencyRequest { + client_request_id: 10, + op: CurrencyOp::Freeze(GwFreeze { currency: key }), + }; + let device_key = fx.issuer.device_key.clone(); + send(&mut fx, &device_key, &freeze, None).expect("freeze posts"); + let backend = fx.svc.into_backend(); + + // Restart: same backend, same store directory, fresh + // service state. + let mut fx = fixture_with(backend, FileIntentStore::open(dir.clone()).expect("reopen")); + assert_eq!( + fx.svc.registry_record(&key).map(|record| record.status), + Some(CurrencyStatus::Frozen), + "the freeze is replayed over the rebuilt registry record", + ); + + // And authorization still refuses value ops against it. + let token = TokenIssue { + currency: currency.compact_hash(), + amount: 10, + to: issuer_id(&fx.alice.account_key), + memo: None, + }; + let event = sign_issue( + &fx.issuer.account_key, + 1, + Some(definition.id), + ¤cy, + &token, + vec![], + ) + .expect("issue signs"); + let body = token.body().expect("body"); + let request = CurrencyRequest { + client_request_id: 11, + op: CurrencyOp::Issue(GwIssue { + currency: key, + amount: 10, + to: fx.alice.account.clone(), + }), + }; + let device_key = fx.issuer.device_key.clone(); + let error = send(&mut fx, &device_key, &request, Some((&event, &body))) + .expect_err("issue after restart on a frozen currency refused"); + assert!( + matches!(error, ServiceError::Gateway(GatewayError::InactiveCurrency)), + "got {error:?}", + ); + let _ = fs::remove_dir_all(&dir); } }