Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 103 additions & 2 deletions pkgs/id/crates/id-currency-registry/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,14 +195,28 @@ 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.
currency_id: String,
/// 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.
Expand All @@ -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}"),
Expand Down Expand Up @@ -333,6 +356,84 @@ impl<S: Store> Registry<S> {
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<String>,
) -> Result<CurrencyRecord, RegistryError> {
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<String>,
) -> Result<CurrencyRecord, RegistryError> {
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Record lifecycle decisions in the required dated design document

This adds public lifecycle APIs and decides terminal-sunset, repeat-idempotence, and restart-replay semantics, but records those decisions only in Rust comments. The earlier control-plane design defines the status flags and signed writes, not these transition/recovery choices; a repository-wide documentation search found no corresponding dated record. Add the dated design document required by pkgs/id/AGENTS.md, explaining the transition table and retry/replay rationale, so this behavioral/API change has the required architecture history.

AGENTS.md reference: pkgs/id/AGENTS.md:L159-L168

Useful? React with 👍 / 👎.

///
/// - `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<String>,
) -> Result<CurrencyRecord, RegistryError> {
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.
Expand Down
36 changes: 35 additions & 1 deletion pkgs/id/crates/id-currency-registry/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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>;

Expand Down Expand Up @@ -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(&currency_id) {
record.status = status;
}
Ok(())
}

fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord> {
self.currencies_by_id.get(currency_id)
}
Expand Down Expand Up @@ -268,6 +294,14 @@ impl<T: Store + ?Sized> 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)
}
Expand Down
102 changes: 102 additions & 0 deletions pkgs/id/crates/id-currency-registry/tests/acceptance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Comment on lines +248 to +249

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add generated coverage for the currency lifecycle model

The new lifecycle is a specified state machine with terminal-state, authorization, and idempotence invariants, but its coverage consists solely of hand-written examples. AGENTS.md requires property tests for invariants and model-based tests where a specification exists; the existing gateway property tests do not exercise lifecycle transitions. Add generated issuer/non-issuer freeze/sunset sequences against a three-state reference model, checking terminal-state monotonicity, idempotence, unchanged state after rejection, and equivalence after restart replay.

AGENTS.md reference: AGENTS.md:L37-L39

Useful? React with 👍 / 👎.

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())
);
}
38 changes: 36 additions & 2 deletions pkgs/id/src/currency/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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(&reg, "issuer-account", &freeze).is_ok());
assert!(authorize(&reg, "issuer-account", &sunset).is_ok());
assert!(matches!(
authorize(&reg, "stranger-account", &freeze),
Err(GatewayError::NotIssuer)
));
assert!(matches!(
authorize(&reg, "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;
Expand Down
Loading