From 3f0dc876f38fb9e1ac119ce575a987ccf399c134 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Mon, 16 Nov 2026 03:23:28 -0600 Subject: [PATCH] feat(id): currency registry schema + ledger-u32 allocator (#2317) Slice F1 of the #2062 currency control-plane design: Postgres migration creating ledger_allocation, currency, currency_issuer and account with the ratified range split, plus the id-currency-registry crate stating the allocator/registry semantics (monotonic, never recycled, currency_id globally unique, symbol unique per issuer). --- pkgs/id/Cargo.lock | 4 + pkgs/id/Cargo.toml | 2 + .../id/crates/id-currency-registry/Cargo.toml | 40 ++ pkgs/id/crates/id-currency-registry/README.md | 52 +++ .../0001_currency_registry.down.sql | 19 + .../migrations/0001_currency_registry.up.sql | 166 ++++++++ .../scripts/test-migration.sh | 101 +++++ .../id-currency-registry/src/allocator.rs | 146 +++++++ .../id/crates/id-currency-registry/src/lib.rs | 93 +++++ .../id-currency-registry/src/registry.rs | 364 ++++++++++++++++++ .../crates/id-currency-registry/src/store.rs | 290 ++++++++++++++ .../id-currency-registry/tests/acceptance.rs | 242 ++++++++++++ 12 files changed, 1519 insertions(+) create mode 100644 pkgs/id/crates/id-currency-registry/Cargo.toml create mode 100644 pkgs/id/crates/id-currency-registry/README.md create mode 100644 pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.down.sql create mode 100644 pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.up.sql create mode 100755 pkgs/id/crates/id-currency-registry/scripts/test-migration.sh create mode 100644 pkgs/id/crates/id-currency-registry/src/allocator.rs create mode 100644 pkgs/id/crates/id-currency-registry/src/lib.rs create mode 100644 pkgs/id/crates/id-currency-registry/src/registry.rs create mode 100644 pkgs/id/crates/id-currency-registry/src/store.rs create mode 100644 pkgs/id/crates/id-currency-registry/tests/acceptance.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 4b6f071153..3d003cc612 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4773,6 +4773,10 @@ dependencies = [ "zeroize", ] +[[package]] +name = "id-currency-registry" +version = "0.1.0" + [[package]] name = "id-directory" version = "0.1.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 0394778f2d..e9e4b4ce71 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -25,6 +25,7 @@ members = [ "crates/id-sync", "crates/id-worlds", "crates/id-directory", + "crates/id-currency-registry", "crates/id-web", "crates/id-native-shell", "crates/id-cli", @@ -45,6 +46,7 @@ default-members = [ "crates/id-sync", "crates/id-worlds", "crates/id-directory", + "crates/id-currency-registry", "crates/id-web", "crates/id-cli", ] diff --git a/pkgs/id/crates/id-currency-registry/Cargo.toml b/pkgs/id/crates/id-currency-registry/Cargo.toml new file mode 100644 index 0000000000..240f3ec478 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "id-currency-registry" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +description = "Currency control-plane registry (F1 of #2062, issue #2317): Postgres schema + migrations for ledger_allocation/currency/currency_issuer/account and the monotonic, never-recycled ledger-u32 allocator" +license = "MIT OR Apache-2.0" + +[features] +default = [] + +[dependencies] + +[lints.rust] +unsafe_code = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } +rust_2024_compatibility = { level = "warn", priority = -1 } +missing_debug_implementations = "warn" +missing_docs = "warn" +trivial_casts = "warn" +trivial_numeric_casts = "warn" +unused_lifetimes = "warn" +unused_qualifications = "warn" + +[lints.clippy] +all = { level = "warn", priority = -1 } +pedantic = { level = "warn", priority = -1 } +nursery = { level = "warn", priority = -1 } +cargo = { level = "warn", priority = -1 } +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +unimplemented = "deny" +todo = "deny" +dbg_macro = "deny" +multiple_crate_versions = "allow" +cargo_common_metadata = "allow" +must_use_candidate = "allow" +missing_errors_doc = "allow" +missing_panics_doc = "allow" diff --git a/pkgs/id/crates/id-currency-registry/README.md b/pkgs/id/crates/id-currency-registry/README.md new file mode 100644 index 0000000000..8c32d2ca1b --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/README.md @@ -0,0 +1,52 @@ +# id-currency-registry + +Currency control-plane registry — slice **F1** of the currency +control-plane design (#2062, +`doc/2026-10-29T12-42-21Z_design_currency_control_plane`), filed as +issue **#2317**. It unblocks F2 (account factory) and F4 +(reconciliation + supply audit). + +TigerBeetle's `ledger` is a bare non-zero `u32` with no metadata. +This crate is the authority for which u32 means what. + +## What is here + +- `migrations/0001_currency_registry.up.sql` — the Postgres schema: + - `ledger_allocation` — the u32 allocator's ledger (design §2.1), + with the ratified range split as a check constraint + (`1..=0xFFFFF` tenancy/system, `0x100000..` currencies), the + `allocate_ledger(kind, owner_ref)` function over monotonic + sequences, and a trigger that refuses deletes — ledger ids are + **never recycled** (design §6). + - `currency` — the currency record (§2.2): `currency_id` globally + unique, `(issuer_id, symbol)` unique (symbol is per-issuer, + §2.3), `graph_object_id` linkage to the signed canonical record + (§2.4). + - `currency_issuer` — issuer/minter grants, drafted from §4.2. + - `account` — the index of deterministic factory accounts, + drafted from §3. (Derivation itself is F2.) +- `src/` — the allocator and registry semantics over a `Store` + seam, with an in-memory store enforcing the same constraints, so + the behaviour is testable without a database. Production writes + go through the gateway's signed path (design §2.5); this crate + states the registry rules that path must enforce. + +## Decisions applied + +From the ledger item `currency-registry-decisions-2317` (answered +2026-11-16, recorded on issue #2317): + +1. Registry store: **Postgres**. +2. Ledger u32: **bigint + `0..4294967295` check**; the design §6 + range split is ratified. +3. `currency_id` **globally unique**; `symbol` unique **per issuer**. +4. The `currency_issuer` / `account` columns the design does not + tabulate are **fleet-drafted** from design §2.1–2.2, §2.4, §3 + and §4.2 — they land here for ratification. + +## Verify + +```sh +cargo test -p id-currency-registry +scripts/test-migration.sh # needs initdb/pg_ctl/psql on PATH +``` diff --git a/pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.down.sql b/pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.down.sql new file mode 100644 index 0000000000..2005344575 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.down.sql @@ -0,0 +1,19 @@ +-- 0001_currency_registry.down.sql +-- Reverses 0001_currency_registry.up.sql. Dropping the schema is an +-- operator action on an empty/decommissioned registry only; the +-- never-recycle rule binds allocation while the registry lives, and a +-- down migration must never be used to re-issue ledger ids. + +BEGIN; + +DROP TABLE IF EXISTS account; +DROP TABLE IF EXISTS currency_issuer; +DROP TABLE IF EXISTS currency; +DROP TRIGGER IF EXISTS ledger_allocation_no_delete ON ledger_allocation; +DROP FUNCTION IF EXISTS ledger_allocation_no_delete(); +DROP FUNCTION IF EXISTS allocate_ledger(text, text); +DROP TABLE IF EXISTS ledger_allocation; +DROP SEQUENCE IF EXISTS ledger_currency_seq; +DROP SEQUENCE IF EXISTS ledger_system_seq; + +COMMIT; diff --git a/pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.up.sql b/pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.up.sql new file mode 100644 index 0000000000..107e334d03 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/migrations/0001_currency_registry.up.sql @@ -0,0 +1,166 @@ +-- 0001_currency_registry.up.sql +-- +-- Currency control-plane registry, slice F1 of the #2062 design +-- (doc/2026-10-29T12-42-21Z_design_currency_control_plane, sections 2 and 6), +-- filed as issue #2317. +-- +-- Decisions applied (ledger currency-registry-decisions-2317, answered +-- 2026-11-16, recorded on issue #2317 by triage task 15189): +-- 1. Registry store: Postgres (this migration). +-- 2. Ledger u32 is stored as bigint with a 0..4294967295 check constraint; +-- the design section 6 range split is ratified (see the per-kind range +-- check below). +-- 3. currency_id is globally unique; symbol is unique per issuer. +-- 4. currency_issuer / account columns, which the design names but does +-- not tabulate, are drafted here from design sections 2.1-2.2, 2.4, +-- 3 and 4.2 for ratification. +-- +-- Ledger range split (design section 6, ratified): +-- 0x00000001-0x000FFFFF tenancy / system +-- 0x00100000-0xFFFFFFFF currencies +-- Ledger 0 is invalid in TigerBeetle and is never allocated: both allocator +-- sequences start at or above 1 and the per-kind range check excludes 0 +-- from every allocation row. + +BEGIN; + +-- --------------------------------------------------------------------------- +-- ledger_allocation: the u32 allocator's ledger (design section 2.1) +-- --------------------------------------------------------------------------- +CREATE TABLE ledger_allocation ( + ledger_id bigint PRIMARY KEY + CHECK (ledger_id BETWEEN 0 AND 4294967295), + kind text NOT NULL + CHECK (kind IN ('currency', 'system', 'tenancy')), + owner_ref text NOT NULL, + allocated_at timestamptz NOT NULL DEFAULT now(), + -- Ratified range split: a row may only exist inside its kind's range. + CHECK ( + (kind = 'currency' AND ledger_id >= 1048576) + OR (kind IN ('system', 'tenancy') + AND ledger_id BETWEEN 1 AND 1048575) + ) +); + +COMMENT ON TABLE ledger_allocation IS + 'The only place a TigerBeetle ledger u32 is assigned (design #2062 s.2.1). Rows are never deleted and ids are never recycled (s.6).'; + +-- Monotonic allocator sequences. Sequences never go backwards and are +-- never reset by this schema, which is what makes allocation +-- never-recycled at the storage layer. +CREATE SEQUENCE ledger_system_seq + START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 1048575 NO CYCLE; +CREATE SEQUENCE ledger_currency_seq + START WITH 1048576 INCREMENT BY 1 MINVALUE 1048576 + MAXVALUE 4294967295 NO CYCLE; + +-- allocate_ledger(kind, owner_ref) -> the newly allocated ledger id. +-- Hands out non-zero ids monotonically inside the kind's ratified range +-- and records the allocation in the same statement's transaction. +CREATE FUNCTION allocate_ledger(p_kind text, p_owner_ref text) +RETURNS bigint +LANGUAGE plpgsql +AS $$ +DECLARE + v_id bigint; +BEGIN + IF p_kind = 'currency' THEN + v_id := nextval('ledger_currency_seq'); + ELSIF p_kind IN ('system', 'tenancy') THEN + v_id := nextval('ledger_system_seq'); + ELSE + RAISE EXCEPTION 'unknown ledger kind: %', p_kind + USING ERRCODE = 'check_violation'; + END IF; + INSERT INTO ledger_allocation (ledger_id, kind, owner_ref) + VALUES (v_id, p_kind, p_owner_ref); + RETURN v_id; +END; +$$; + +-- Never recycled, enforced: allocation rows cannot be deleted at all. +CREATE FUNCTION ledger_allocation_no_delete() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'ledger_allocation rows are never deleted (design #2062 s.6: ledger ids are never recycled)' + USING ERRCODE = 'restrict_violation'; +END; +$$; + +CREATE TRIGGER ledger_allocation_no_delete + BEFORE DELETE ON ledger_allocation + FOR EACH ROW EXECUTE FUNCTION ledger_allocation_no_delete(); + +-- --------------------------------------------------------------------------- +-- currency: the currency record (design section 2.2) +-- --------------------------------------------------------------------------- +CREATE TABLE currency ( + ledger_id bigint PRIMARY KEY + REFERENCES ledger_allocation (ledger_id), + -- Semantic identity (design s.2.3): minted by the registry at + -- registration, globally unique, never changes. + currency_id text NOT NULL UNIQUE, + name text NOT NULL, + -- Display label: unique per issuer, not globally (design s.2.3), so + -- two issuers may both register the symbol ABC. + symbol text NOT NULL, + -- Decimal places. Registry-only; immutable once balances exist (s.0). + scale smallint NOT NULL CHECK (scale >= 0), + issuer_id text NOT NULL, + supply_policy jsonb NOT NULL + DEFAULT '{"mintable": false, "cap": null, "policy_uri": null}'::jsonb, + status text NOT NULL DEFAULT 'active' + CHECK (status IN ('active', 'frozen', 'sunset')), + -- Linkage to the signed graph object that is the currency's canonical + -- record (design s.2.4); this row is a derived index over it. + graph_object_id text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (issuer_id, symbol) +); + +COMMENT ON TABLE currency IS + 'Currency metadata TigerBeetle does not hold (design #2062 s.2.2). currency_id globally unique; (issuer_id, symbol) unique.'; + +-- --------------------------------------------------------------------------- +-- currency_issuer: who may act for a currency (drafted, decision 4) +-- Drafted from design s.4.2: register_currency records the issuer here and +-- grant_minter writes rows with role = 'minter'. The registry, not the +-- signature, decides authority (s.4.2). +-- --------------------------------------------------------------------------- +CREATE TABLE currency_issuer ( + ledger_id bigint NOT NULL REFERENCES currency (ledger_id), + account_id text NOT NULL, + role text NOT NULL CHECK (role IN ('issuer', 'minter')), + granted_by text, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (ledger_id, account_id, role) +); + +COMMENT ON TABLE currency_issuer IS + 'Issuer/minter grants per currency (drafted from design #2062 s.4.2 for ratification, decision 4 on issue #2317).'; + +-- --------------------------------------------------------------------------- +-- account: the registry index of factory accounts (drafted, decision 4) +-- Drafted from design s.3: account ids are derived, not allocated +-- (s.3.1), so this table is an index of the accounts the factory has +-- ensured, keyed by the derived 128-bit account id (hex text), with the +-- (ledger, owner, kind, salt) tuple that derivation is a function of. +-- --------------------------------------------------------------------------- +CREATE TABLE account ( + account_id text PRIMARY KEY, + ledger_id bigint NOT NULL REFERENCES currency (ledger_id), + owner_id text NOT NULL, + kind text NOT NULL + CHECK (kind IN ('issuer', 'liquidity', 'fee', 'burn', 'holder')), + salt text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (ledger_id, owner_id, kind, salt) +); + +COMMENT ON TABLE account IS + 'Index of deterministic factory accounts (drafted from design #2062 s.3 for ratification, decision 4 on issue #2317). Derivation itself is slice F2.'; + +COMMIT; diff --git a/pkgs/id/crates/id-currency-registry/scripts/test-migration.sh b/pkgs/id/crates/id-currency-registry/scripts/test-migration.sh new file mode 100755 index 0000000000..8dad21cc43 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/scripts/test-migration.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# test-migration.sh — prove migration 0001 against a real Postgres. +# +# Oracle: issue #2317's acceptance list. +# - the migration creates the four tables with the uniqueness +# constraints the design names; +# - the allocator function hands out non-zero u32s monotonically +# and refuses to recycle (allocation rows cannot be deleted); +# - two issuers may both register symbol ABC, but a duplicate +# currency_id is rejected. +# +# Spins up a throwaway Postgres cluster in a mktemp dir owned by +# this script, runs the assertions, and tears it down. Requires +# initdb/pg_ctl/psql on PATH. Exits non-zero on the first failure. +set -euo pipefail + +CRATE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +UP="$CRATE_DIR/migrations/0001_currency_registry.up.sql" +DOWN="$CRATE_DIR/migrations/0001_currency_registry.down.sql" + +PGDATA="$(mktemp -d /tmp/id-currency-registry-pg.XXXXXX)" +PGPORT="${PGPORT:-55439}" +export PGDATA + +cleanup() { + pg_ctl -D "$PGDATA" -m immediate stop >/dev/null 2>&1 || true + case "$PGDATA" in + /tmp/id-currency-registry-pg.*) rm -rf "$PGDATA" ;; + esac +} +trap cleanup EXIT + +initdb -D "$PGDATA" --auth=trust >/dev/null +pg_ctl -D "$PGDATA" -o "-k $PGDATA -p $PGPORT" -l "$PGDATA/pg.log" -w start >/dev/null +PSQL="psql -h $PGDATA -p $PGPORT -d postgres -v ON_ERROR_STOP=1 -qAt" + +$PSQL -f "$UP" >/dev/null +echo "migration applied" + +# Allocator: non-zero, monotonic, range-split. +first="$($PSQL -c "SELECT allocate_ledger('currency', 'abc')")" +second="$($PSQL -c "SELECT allocate_ledger('currency', 'def')")" +system="$($PSQL -c "SELECT allocate_ledger('system', 'fees')")" +[ "$first" = "1048576" ] || { echo "FAIL: first currency ledger = $first, want 1048576"; exit 1; } +[ "$second" = "1048577" ] || { echo "FAIL: second currency ledger = $second, want 1048577"; exit 1; } +[ "$system" = "1" ] || { echo "FAIL: first system ledger = $system, want 1"; exit 1; } +echo "allocator: monotonic, non-zero, range-split OK" + +# Never recycled: allocation rows cannot be deleted. +if $PSQL -c "DELETE FROM ledger_allocation WHERE ledger_id = $first" >/dev/null 2>&1; then + echo "FAIL: ledger_allocation delete succeeded; ids could be recycled" + exit 1 +fi +echo "allocator: delete (recycle) refused OK" + +# Registry: two issuers may both register symbol ABC. +$PSQL >/dev/null <<'SQL' +INSERT INTO currency (ledger_id, currency_id, name, symbol, scale, issuer_id, graph_object_id) +VALUES (1048576, 'alice-abc', 'Alice ABC', 'ABC', 2, 'alice', 'graph-alice-abc'); +INSERT INTO currency (ledger_id, currency_id, name, symbol, scale, issuer_id, graph_object_id) +VALUES (1048577, 'bob-abc', 'Bob ABC', 'ABC', 2, 'bob', 'graph-bob-abc'); +INSERT INTO currency_issuer (ledger_id, account_id, role) +VALUES (1048576, 'alice', 'issuer'), (1048577, 'bob', 'issuer'); +INSERT INTO account (account_id, ledger_id, owner_id, kind) +VALUES ('0123456789abcdef0123456789abcdef', 1048576, 'alice', 'issuer'); +SQL +echo "registry: two issuers with symbol ABC OK" + +# Duplicate currency_id is rejected (globally unique, decision 3). +third="$($PSQL -c "SELECT allocate_ledger('currency', 'abc-again')")" +if $PSQL -c "INSERT INTO currency (ledger_id, currency_id, name, symbol, scale, issuer_id) + VALUES ($third, 'alice-abc', 'Copy', 'XYZ', 2, 'mallory')" >/dev/null 2>&1; then + echo "FAIL: duplicate currency_id was accepted" + exit 1 +fi +echo "registry: duplicate currency_id rejected OK" + +# Duplicate symbol for the same issuer is rejected. +fourth="$($PSQL -c "SELECT allocate_ledger('currency', 'alice-abc-2')")" +if $PSQL -c "INSERT INTO currency (ledger_id, currency_id, name, symbol, scale, issuer_id) + VALUES ($fourth, 'alice-abc-2', 'Copy', 'ABC', 2, 'alice')" >/dev/null 2>&1; then + echo "FAIL: duplicate (issuer, symbol) was accepted" + exit 1 +fi +echo "registry: duplicate (issuer, symbol) rejected OK" + +# Range split is a schema constraint, not a convention. +if $PSQL -c "INSERT INTO ledger_allocation (ledger_id, kind, owner_ref) + VALUES (7, 'currency', 'out-of-range')" >/dev/null 2>&1; then + echo "FAIL: out-of-range currency allocation was accepted" + exit 1 +fi +echo "schema: range split enforced OK" + +# Down migration removes the schema. +$PSQL -f "$DOWN" >/dev/null +remaining="$($PSQL -c "SELECT count(*) FROM information_schema.tables WHERE table_name IN ('ledger_allocation','currency','currency_issuer','account')")" +[ "$remaining" = "0" ] || { echo "FAIL: down migration left $remaining tables"; exit 1; } +echo "down migration OK" + +echo "PASS: migration 0001 satisfies the #2317 acceptance checks" diff --git a/pkgs/id/crates/id-currency-registry/src/allocator.rs b/pkgs/id/crates/id-currency-registry/src/allocator.rs new file mode 100644 index 0000000000..4432ef40f2 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/src/allocator.rs @@ -0,0 +1,146 @@ +//! The ledger-u32 allocator (design sections 2.1 and 6). +//! +//! Rules, all structural rather than conventional: +//! +//! - **Monotonic.** The next candidate is one past the highest id +//! ever allocated in the kind's range, so ids increase even when +//! specific ids were reserved out of band. +//! - **Never recycled.** There is deliberately no release or free +//! operation on this API, and the store refuses to insert an id +//! that is already allocated. A spent u32 stays spent; exhaustion +//! means a new cluster, not reuse (design section 6). +//! - **Non-zero.** Ledger 0 is invalid in `TigerBeetle`; both ranges +//! start at or above 1, so 0 can never be handed out. +//! - **Range-split.** Currencies allocate from +//! `0x00100000..=0xFFFFFFFF`; tenancy/system from +//! `0x00000001..=0x000FFFFF` (ratified, decision 2 on issue #2317). + +use std::fmt; + +use crate::LedgerKind; +use crate::store::{Allocation, Store, StoreError}; + +/// An allocation failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AllocError { + /// The kind's range has no unspent id left. + Exhausted { + /// The kind whose range is exhausted. + kind: LedgerKind, + }, + /// A specific-id reservation fell outside the kind's range. + OutOfRange { + /// The kind the reservation was requested for. + kind: LedgerKind, + /// The offending ledger id. + ledger_id: u32, + }, + /// The store rejected the allocation (e.g. already allocated). + Store(StoreError), +} + +impl fmt::Display for AllocError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Exhausted { kind } => { + write!(f, "ledger range for kind {} is exhausted", kind.as_str()) + } + Self::OutOfRange { kind, ledger_id } => { + write!( + f, + "ledger {ledger_id} is outside the {} range", + kind.as_str() + ) + } + Self::Store(err) => write!(f, "{err}"), + } + } +} + +impl std::error::Error for AllocError {} + +impl From for AllocError { + fn from(err: StoreError) -> Self { + Self::Store(err) + } +} + +/// The allocator, over any registry [`Store`]. +/// +/// In production the store is Postgres and `allocate_ledger` +/// (migration `0001`) is the same algorithm over sequences; this +/// type states the semantics the SQL implements and is what tests +/// exercise. +#[derive(Debug)] +pub struct Allocator { + store: S, +} + +impl Allocator { + /// Create an allocator over `store`. + pub const fn new(store: S) -> Self { + Self { store } + } + + /// Access the underlying store. + pub const fn store(&self) -> &S { + &self.store + } + + /// Mutably access the underlying store. + pub const fn store_mut(&mut self) -> &mut S { + &mut self.store + } + + /// Consume the allocator and return the store. + pub fn into_store(self) -> S { + self.store + } + + /// Allocate the next ledger id for `kind`, recorded against + /// `owner_ref`. Hands out non-zero ids monotonically inside the + /// kind's range and never reissues an id. + pub fn allocate( + &mut self, + kind: LedgerKind, + owner_ref: impl Into, + ) -> Result { + let (start, end) = kind.range(); + let next = match self.store.highest_in_range(kind) { + Some(highest) => highest + .checked_add(1) + .ok_or(AllocError::Exhausted { kind })?, + None => start, + }; + if next > end || next == 0 { + return Err(AllocError::Exhausted { kind }); + } + self.store.insert_allocation(Allocation { + ledger_id: next, + kind, + owner_ref: owner_ref.into(), + })?; + Ok(next) + } + + /// Reserve a specific ledger id for `kind` — the up-front range + /// reservation the design calls for (e.g. a tenancy block). The + /// id must lie inside the kind's range and be unspent; reserving + /// an allocated id fails rather than recycling it. + pub fn reserve_specific( + &mut self, + kind: LedgerKind, + ledger_id: u32, + owner_ref: impl Into, + ) -> Result<(), AllocError> { + if !kind.contains(ledger_id) { + return Err(AllocError::OutOfRange { kind, ledger_id }); + } + self.store.insert_allocation(Allocation { + ledger_id, + kind, + owner_ref: owner_ref.into(), + })?; + Ok(()) + } +} diff --git a/pkgs/id/crates/id-currency-registry/src/lib.rs b/pkgs/id/crates/id-currency-registry/src/lib.rs new file mode 100644 index 0000000000..83c7296ab3 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/src/lib.rs @@ -0,0 +1,93 @@ +//! Currency control-plane registry — slice F1 of the #2062 design +//! (issue #2317). +//! +//! The design (`doc/2026-10-29T12-42-21Z_design_currency_control_plane`, +//! sections 2 and 6) makes the registry the authority for *which u32 +//! means what*: `TigerBeetle` ledgers are bare non-zero `u32`s with no +//! metadata, so the meaning of a ledger — name, symbol, scale, issuer, +//! supply policy, status — lives here, and the ledger-u32 allocator +//! here is the only place a ledger value is assigned. +//! +//! This crate carries: +//! +//! - the Postgres migration that creates the registry tables +//! ([`MIGRATION_0001_UP`] / [`MIGRATION_0001_DOWN`], decision 1 on +//! issue #2317: the registry store is Postgres; ledger ids are +//! `bigint` with a `0..=4294967295` check, decision 2); +//! - the allocator and registry semantics over a [`store::Store`] +//! seam ([`allocator`], [`registry`]), with an in-memory store +//! ([`store::InMemoryStore`]) that enforces the same constraints +//! the migration enforces, so the acceptance behaviour is testable +//! without a database. The SQL behaviour itself is verified +//! against a real Postgres by `scripts/test-migration.sh`. +//! +//! Ratified range split (design section 6, decision 2): +//! `0x00000001..=0x000FFFFF` is tenancy/system, `0x00100000..` is +//! currencies. Allocation is monotonic and never recycled; ledger 0 +//! is invalid in `TigerBeetle` and never allocated. + +pub mod allocator; +pub mod registry; +pub mod store; + +pub use allocator::{AllocError, Allocator}; +pub use registry::{ + AccountKind, AccountRecord, CurrencyRecord, CurrencyStatus, IssuerGrant, IssuerRole, + RegisterAccount, RegisterCurrency, Registry, RegistryError, SupplyPolicy, +}; +pub use store::{InMemoryStore, Store, StoreError}; + +/// The first migration: the four registry tables, the allocator +/// sequences and function, and the never-delete guard. +pub const MIGRATION_0001_UP: &str = include_str!("../migrations/0001_currency_registry.up.sql"); + +/// The reverse of [`MIGRATION_0001_UP`]. +pub const MIGRATION_0001_DOWN: &str = include_str!("../migrations/0001_currency_registry.down.sql"); + +/// Largest valid `TigerBeetle` ledger value. +pub const LEDGER_ID_MAX: u32 = u32::MAX; + +/// First ledger id of the currency range (design section 6 split). +pub const CURRENCY_RANGE_START: u32 = 0x0010_0000; + +/// Last ledger id of the shared tenancy/system range. +pub const SYSTEM_RANGE_END: u32 = 0x000F_FFFF; + +/// Why a ledger u32 is spent (design section 2.1 `kind`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum LedgerKind { + /// A currency ledger. + Currency, + /// A platform system ledger. + System, + /// A tenant-partitioning ledger. + Tenancy, +} + +impl LedgerKind { + /// The `ledger_allocation.kind` text for this kind. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Currency => "currency", + Self::System => "system", + Self::Tenancy => "tenancy", + } + } + + /// The inclusive range this kind may be allocated from. + #[must_use] + pub const fn range(self) -> (u32, u32) { + match self { + Self::Currency => (CURRENCY_RANGE_START, LEDGER_ID_MAX), + Self::System | Self::Tenancy => (1, SYSTEM_RANGE_END), + } + } + + /// Whether `ledger_id` lies inside this kind's range. + #[must_use] + pub const fn contains(self, ledger_id: u32) -> bool { + let (start, end) = self.range(); + ledger_id >= start && ledger_id <= end + } +} diff --git a/pkgs/id/crates/id-currency-registry/src/registry.rs b/pkgs/id/crates/id-currency-registry/src/registry.rs new file mode 100644 index 0000000000..a0f8956b6e --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/src/registry.rs @@ -0,0 +1,364 @@ +//! The registry itself: currency records, issuer grants, and the +//! account index (design sections 2.2, 3, 4.2). +//! +//! `currency_issuer` and `account` are drafted tables (decision 4 on +//! issue #2317): the design names them and fixes their roles — +//! `currency_issuer` is where `register_currency` records the issuer +//! and `grant_minter` writes minters (section 4.2); `account` indexes +//! the deterministic factory accounts of section 3 — but does not +//! tabulate their columns, so the columns here and in migration +//! `0001` are the fleet draft for ratification. + +use std::fmt; + +use crate::LedgerKind; +use crate::allocator::Allocator; +use crate::store::{Store, StoreError}; + +/// Lifecycle status of a currency (design section 2.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurrencyStatus { + /// Gateway may write. + Active, + /// Gateway refuses new writes. + Frozen, + /// No new writes; redemption window only. + Sunset, +} + +impl CurrencyStatus { + /// The `currency.status` text for this status. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Active => "active", + Self::Frozen => "frozen", + Self::Sunset => "sunset", + } + } +} + +/// A currency's supply policy (design section 2.2 `supply_policy`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SupplyPolicy { + /// Whether minting is permitted at all. + pub mintable: bool, + /// Total supply cap in minor units, if capped. + pub cap: Option, + /// Off-registry policy document, if any. + pub policy_uri: Option, +} + +/// One row of `currency` (design section 2.2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurrencyRecord { + /// The ledger this currency is (PK, FK to `ledger_allocation`). + pub ledger_id: u32, + /// Semantic identity: minted by the registry at registration, + /// globally unique, never changes (decision 3, section 2.3). + pub currency_id: String, + /// Display name. Free-form; not unique. + pub name: String, + /// Short ticker. Unique per issuer, not globally (section 2.3). + pub symbol: String, + /// Decimal places. Registry-only; immutable once balances exist. + pub scale: u8, + /// The ID (account id) that owns issuance. + pub issuer_id: String, + /// Minting policy. + pub supply_policy: SupplyPolicy, + /// Lifecycle status. + pub status: CurrencyStatus, + /// The signed graph object that is this currency's canonical + /// record (section 2.4); this row is a derived index over it. + pub graph_object_id: Option, +} + +/// The input to [`Registry::register_currency`]. The `currency_id` +/// +/// is proposed by the caller and *minted* by the registry: it +/// becomes the currency's identity only when registration records +/// it, and a duplicate proposal is rejected. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RegisterCurrency { + /// Proposed semantic id (e.g. `abc`). + pub currency_id: String, + /// Display name. + pub name: String, + /// Ticker; must be free in the issuer's namespace. + pub symbol: String, + /// Decimal places. + pub scale: u8, + /// The registering issuer's account id. + pub issuer_id: String, + /// Minting policy. + pub supply_policy: SupplyPolicy, + /// Signed graph object recording the registration (section 2.4). + pub graph_object_id: Option, +} + +/// A role a `currency_issuer` row grants (design section 4.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IssuerRole { + /// The currency's issuer (recorded at registration). + Issuer, + /// A granted minter (`grant_minter`). + Minter, +} + +impl IssuerRole { + /// The `currency_issuer.role` text for this role. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Issuer => "issuer", + Self::Minter => "minter", + } + } +} + +/// One row of `currency_issuer` (drafted from design section 4.2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IssuerGrant { + /// The currency's ledger. + pub ledger_id: u32, + /// The account the role is granted to. + pub account_id: String, + /// The granted role. + pub role: IssuerRole, + /// Who made the grant (the issuer, for minters). + pub granted_by: Option, +} + +/// The per-currency account kinds (design section 3.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AccountKind { + /// Source of every mint. + Issuer, + /// Conversion-leg liquidity. + Liquidity, + /// Fee collection. + Fee, + /// Retirement destination. + Burn, + /// A user's holding account. + Holder, +} + +impl AccountKind { + /// The `account.kind` text for this kind. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Issuer => "issuer", + Self::Liquidity => "liquidity", + Self::Fee => "fee", + Self::Burn => "burn", + Self::Holder => "holder", + } + } +} + +/// One row of `account` (drafted from design section 3). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountRecord { + /// The derived 128-bit account id (hex text), section 3.1. + pub account_id: String, + /// The currency's ledger. + pub ledger_id: u32, + /// The account holder's id. + pub owner_id: String, + /// Which of the per-currency accounts this is. + pub kind: AccountKind, + /// Derivation salt; empty unless an owner has several accounts + /// of one kind (section 3.1). + pub salt: String, +} + +/// The input to [`Registry::register_account`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RegisterAccount { + /// The currency's semantic id. + pub currency_id: String, + /// The derived account id (hex text). + pub account_id: String, + /// The account holder's id. + pub owner_id: String, + /// Which per-currency account this is. + pub kind: AccountKind, + /// Derivation salt (default empty). + pub salt: String, +} + +/// A registry failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RegistryError { + /// No currency is registered under this id. + UnknownCurrency(String), + /// `grant_minter` 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, + }, + /// The store rejected the write. + Store(StoreError), + /// The allocator could not hand out a ledger. + Alloc(crate::allocator::AllocError), +} + +impl fmt::Display for RegistryError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnknownCurrency(id) => write!(f, "no currency registered as {id}"), + Self::NotIssuer { + currency_id, + account_id, + } => { + write!( + f, + "account {account_id} is not the issuer of {currency_id} and cannot grant minters" + ) + } + Self::Store(err) => write!(f, "{err}"), + Self::Alloc(err) => write!(f, "{err}"), + } + } +} + +impl std::error::Error for RegistryError {} + +impl From for RegistryError { + fn from(err: StoreError) -> Self { + Self::Store(err) + } +} + +impl From for RegistryError { + fn from(err: crate::allocator::AllocError) -> Self { + Self::Alloc(err) + } +} + +/// The currency registry over a [`Store`]. +#[derive(Debug)] +pub struct Registry { + store: S, +} + +impl Registry { + /// Create a registry over `store`. + pub const fn new(store: S) -> Self { + Self { store } + } + + /// Access the underlying store. + pub const fn store(&self) -> &S { + &self.store + } + + /// Register a currency: allocate its ledger from the currency + /// range, mint its `currency_id`, and record the issuer grant — + /// in that order, so a registration that fails on a duplicate + /// `currency_id` or a taken symbol never burns a ledger id. + pub fn register_currency( + &mut self, + input: RegisterCurrency, + ) -> Result { + // Check the uniqueness verdicts before spending a ledger id: + // a rejected registration must not consume from the finite, + // never-recycled u32 space. + if self.store.currency_by_id(&input.currency_id).is_some() { + return Err(StoreError::DuplicateCurrencyId(input.currency_id).into()); + } + if self.store.symbol_taken(&input.issuer_id, &input.symbol) { + return Err(StoreError::DuplicateSymbol { + issuer_id: input.issuer_id, + symbol: input.symbol, + } + .into()); + } + let ledger_id = { + let mut allocator = Allocator::new(&mut self.store); + allocator.allocate(LedgerKind::Currency, input.currency_id.clone())? + }; + let record = CurrencyRecord { + ledger_id, + currency_id: input.currency_id, + name: input.name, + symbol: input.symbol, + scale: input.scale, + issuer_id: input.issuer_id, + supply_policy: input.supply_policy, + status: CurrencyStatus::Active, + graph_object_id: input.graph_object_id, + }; + self.store.insert_currency(record.clone())?; + self.store.insert_grant(IssuerGrant { + ledger_id: record.ledger_id, + account_id: record.issuer_id.clone(), + role: IssuerRole::Issuer, + granted_by: None, + })?; + Ok(record) + } + + /// Grant the minter role for a currency. Only the currency's + /// issuer may grant (design section 4.2). + pub fn grant_minter( + &mut self, + currency_id: &str, + minter_account_id: impl Into, + granted_by: impl Into, + ) -> Result<(), RegistryError> { + let granted_by = granted_by.into(); + let currency = self + .store + .currency_by_id(currency_id) + .ok_or_else(|| RegistryError::UnknownCurrency(currency_id.to_owned()))?; + if currency.issuer_id != granted_by { + return Err(RegistryError::NotIssuer { + currency_id: currency_id.to_owned(), + account_id: granted_by, + }); + } + self.store.insert_grant(IssuerGrant { + ledger_id: currency.ledger_id, + account_id: minter_account_id.into(), + role: IssuerRole::Minter, + granted_by: Some(granted_by), + })?; + Ok(()) + } + + /// 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. + pub fn register_account( + &mut self, + input: RegisterAccount, + ) -> Result { + let currency = self + .store + .currency_by_id(&input.currency_id) + .ok_or_else(|| RegistryError::UnknownCurrency(input.currency_id.clone()))?; + let record = AccountRecord { + account_id: input.account_id, + ledger_id: currency.ledger_id, + owner_id: input.owner_id, + kind: input.kind, + salt: input.salt, + }; + self.store.insert_account(record.clone())?; + Ok(record) + } + + /// Resolve a `currency_id` to its record — the + /// `currency_id -> ledger_id` lookup the gateway performs before + /// any transfer (design section 2.3). + pub fn resolve(&self, currency_id: &str) -> Option<&CurrencyRecord> { + self.store.currency_by_id(currency_id) + } +} diff --git a/pkgs/id/crates/id-currency-registry/src/store.rs b/pkgs/id/crates/id-currency-registry/src/store.rs new file mode 100644 index 0000000000..2eb5a7bc96 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/src/store.rs @@ -0,0 +1,290 @@ +//! Storage seam for the registry. +//! +//! The production store is Postgres (migration `0001`); its +//! constraints are the authority. [`Store`] states the operations +//! the allocator and registry need, and [`InMemoryStore`] implements +//! them with exactly the migration's uniqueness and range rules, so +//! behaviour proven against the in-memory store is the behaviour the +//! schema enforces (the schema side is proven separately against a +//! real Postgres by `scripts/test-migration.sh`). + +use std::collections::BTreeMap; +use std::fmt; + +use crate::LedgerKind; +use crate::registry::{AccountRecord, CurrencyRecord, IssuerGrant}; + +/// One row of `ledger_allocation` (design section 2.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Allocation { + /// The allocated ledger u32 (never 0, never recycled). + pub ledger_id: u32, + /// Why this u32 was spent. + pub kind: LedgerKind, + /// Currency id, system-account purpose, or tenant id. + pub owner_ref: String, +} + +/// A store failure. Each variant mirrors a constraint in migration +/// `0001`, 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 StoreError { + /// The ledger id is already allocated; ids are never recycled. + AlreadyAllocated(u32), + /// A `currency_id` is already registered (globally unique, + /// decision 3 on issue #2317). + DuplicateCurrencyId(String), + /// The `(issuer_id, symbol)` pair is already registered; symbol + /// is unique per issuer, not globally (design section 2.3). + DuplicateSymbol { + /// The issuer whose namespace already holds the symbol. + issuer_id: String, + /// The conflicting symbol. + symbol: String, + }, + /// No allocation exists for this ledger id. + UnknownLedger(u32), + /// The ledger exists but is not a currency allocation. + LedgerNotCurrency(u32), + /// The derived account id is already recorded. + DuplicateAccountId(String), + /// An account already occupies this `(ledger, owner, kind, salt)` + /// slot. + DuplicateAccountSlot, + /// This `(ledger, account, role)` grant already exists. + DuplicateGrant, +} + +impl fmt::Display for StoreError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AlreadyAllocated(id) => { + write!(f, "ledger {id} is already allocated and never recycled") + } + Self::DuplicateCurrencyId(id) => { + write!(f, "currency_id {id} is already registered") + } + Self::DuplicateSymbol { issuer_id, symbol } => { + write!(f, "issuer {issuer_id} already registers symbol {symbol}") + } + Self::UnknownLedger(id) => write!(f, "ledger {id} is not allocated"), + Self::LedgerNotCurrency(id) => { + write!(f, "ledger {id} is not a currency allocation") + } + Self::DuplicateAccountId(id) => { + write!(f, "account {id} is already recorded") + } + Self::DuplicateAccountSlot => { + write!( + f, + "an account already occupies this (ledger, owner, kind, salt) slot" + ) + } + Self::DuplicateGrant => write!(f, "this issuer grant already exists"), + } + } +} + +impl std::error::Error for StoreError {} + +/// The operations the allocator and registry require of a store. +/// +/// Implementations must enforce the migration's constraints, not +/// just record rows: a store that accepts a duplicate `currency_id` +/// is not a registry store. +pub trait Store { + /// Record a new allocation. Fails with + /// [`StoreError::AlreadyAllocated`] if the id is taken — this is + /// the never-recycle rule at the storage layer. + fn insert_allocation(&mut self, allocation: Allocation) -> Result<(), StoreError>; + + /// Look up an allocation by ledger id. + fn allocation(&self, ledger_id: u32) -> Option<&Allocation>; + + /// The highest allocated id inside `kind`'s range, if any. The + /// allocator derives the next candidate from this, so allocation + /// stays monotonic even across reservations made out of band. + fn highest_in_range(&self, kind: LedgerKind) -> Option; + + /// Record a currency row for an allocated currency ledger. + fn insert_currency(&mut self, record: CurrencyRecord) -> Result<(), StoreError>; + + /// Look up a currency by its semantic id. + fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord>; + + /// Look up a currency by its ledger id. + fn currency_by_ledger(&self, ledger_id: u32) -> Option<&CurrencyRecord>; + + /// Whether `symbol` is already registered in `issuer_id`'s + /// namespace. Lets the registry reject before spending a ledger + /// id; [`Store::insert_currency`] still enforces the rule. + fn symbol_taken(&self, issuer_id: &str, symbol: &str) -> bool; + + /// Record an issuer/minter grant. + fn insert_grant(&mut self, grant: IssuerGrant) -> Result<(), StoreError>; + + /// Record a factory account index row. + fn insert_account(&mut self, account: AccountRecord) -> Result<(), StoreError>; +} + +/// In-memory [`Store`] enforcing the migration's constraints. Used +/// by tests and by any caller prototyping against the semantics +/// before the Postgres-backed store lands behind the same seam. +#[derive(Debug, Default)] +pub struct InMemoryStore { + allocations: BTreeMap, + currencies_by_id: BTreeMap, + currencies_by_ledger: BTreeMap, + grants: Vec, + accounts: Vec, +} + +impl InMemoryStore { + /// A new, empty store. + #[must_use] + pub fn new() -> Self { + Self::default() + } +} + +impl Store for InMemoryStore { + fn insert_allocation(&mut self, allocation: Allocation) -> Result<(), StoreError> { + if self.allocations.contains_key(&allocation.ledger_id) { + return Err(StoreError::AlreadyAllocated(allocation.ledger_id)); + } + self.allocations.insert(allocation.ledger_id, allocation); + Ok(()) + } + + fn allocation(&self, ledger_id: u32) -> Option<&Allocation> { + self.allocations.get(&ledger_id) + } + + fn highest_in_range(&self, kind: LedgerKind) -> Option { + self.allocations + .keys() + .filter(|id| kind.contains(**id)) + .max() + .copied() + } + + fn insert_currency(&mut self, record: CurrencyRecord) -> Result<(), StoreError> { + match self.allocations.get(&record.ledger_id) { + None => return Err(StoreError::UnknownLedger(record.ledger_id)), + Some(allocation) if allocation.kind != LedgerKind::Currency => { + return Err(StoreError::LedgerNotCurrency(record.ledger_id)); + } + Some(_) => {} + } + if self.currencies_by_id.contains_key(&record.currency_id) { + return Err(StoreError::DuplicateCurrencyId(record.currency_id)); + } + if self.symbol_taken(&record.issuer_id, &record.symbol) { + return Err(StoreError::DuplicateSymbol { + issuer_id: record.issuer_id, + symbol: record.symbol, + }); + } + self.currencies_by_ledger + .insert(record.ledger_id, record.currency_id.clone()); + self.currencies_by_id + .insert(record.currency_id.clone(), record); + Ok(()) + } + + fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord> { + self.currencies_by_id.get(currency_id) + } + + fn currency_by_ledger(&self, ledger_id: u32) -> Option<&CurrencyRecord> { + self.currencies_by_ledger + .get(&ledger_id) + .and_then(|id| self.currencies_by_id.get(id)) + } + + fn symbol_taken(&self, issuer_id: &str, symbol: &str) -> bool { + self.currencies_by_id + .values() + .any(|c| c.issuer_id == issuer_id && c.symbol == symbol) + } + + fn insert_grant(&mut self, grant: IssuerGrant) -> Result<(), StoreError> { + if self.currency_by_ledger(grant.ledger_id).is_none() { + return Err(StoreError::UnknownLedger(grant.ledger_id)); + } + if self.grants.iter().any(|g| { + g.ledger_id == grant.ledger_id + && g.account_id == grant.account_id + && g.role == grant.role + }) { + return Err(StoreError::DuplicateGrant); + } + self.grants.push(grant); + Ok(()) + } + + fn insert_account(&mut self, account: AccountRecord) -> Result<(), StoreError> { + if self.currency_by_ledger(account.ledger_id).is_none() { + return Err(StoreError::UnknownLedger(account.ledger_id)); + } + if self + .accounts + .iter() + .any(|a| a.account_id == account.account_id) + { + return Err(StoreError::DuplicateAccountId(account.account_id)); + } + if self.accounts.iter().any(|a| { + a.ledger_id == account.ledger_id + && a.owner_id == account.owner_id + && a.kind == account.kind + && a.salt == account.salt + }) { + return Err(StoreError::DuplicateAccountSlot); + } + self.accounts.push(account); + Ok(()) + } +} + +/// A mutable reference to a store is itself a store. This is what +/// lets [`crate::Allocator`] and [`crate::Registry`] share one store +/// without either owning it. +impl Store for &mut T { + fn insert_allocation(&mut self, allocation: Allocation) -> Result<(), StoreError> { + (**self).insert_allocation(allocation) + } + + fn allocation(&self, ledger_id: u32) -> Option<&Allocation> { + (**self).allocation(ledger_id) + } + + fn highest_in_range(&self, kind: LedgerKind) -> Option { + (**self).highest_in_range(kind) + } + + fn insert_currency(&mut self, record: CurrencyRecord) -> Result<(), StoreError> { + (**self).insert_currency(record) + } + + fn currency_by_id(&self, currency_id: &str) -> Option<&CurrencyRecord> { + (**self).currency_by_id(currency_id) + } + + fn currency_by_ledger(&self, ledger_id: u32) -> Option<&CurrencyRecord> { + (**self).currency_by_ledger(ledger_id) + } + + fn symbol_taken(&self, issuer_id: &str, symbol: &str) -> bool { + (**self).symbol_taken(issuer_id, symbol) + } + + fn insert_grant(&mut self, grant: IssuerGrant) -> Result<(), StoreError> { + (**self).insert_grant(grant) + } + + fn insert_account(&mut self, account: AccountRecord) -> Result<(), StoreError> { + (**self).insert_account(account) + } +} diff --git a/pkgs/id/crates/id-currency-registry/tests/acceptance.rs b/pkgs/id/crates/id-currency-registry/tests/acceptance.rs new file mode 100644 index 0000000000..bbad4f6de0 --- /dev/null +++ b/pkgs/id/crates/id-currency-registry/tests/acceptance.rs @@ -0,0 +1,242 @@ +//! Acceptance tests for issue #2317 (design #2062 slice F1). +//! +//! The oracle for each test is a line of the issue's Acceptance list +//! or of design sections 2/6: +//! +//! - "A migration creates the four tables with the uniqueness +//! constraints the design names" — the migration text is checked +//! here for the four tables and constraints, and proven against a +//! real Postgres by `scripts/test-migration.sh`. +//! - "An allocator API hands out non-zero u32s monotonically and +//! refuses to recycle" — the allocator tests below. +//! - "A test proves two issuers may both register symbol `ABC` but +//! a duplicate `currency_id` is rejected" — +//! `two_issuers_may_both_register_symbol_abc` and +//! `duplicate_currency_id_is_rejected`. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use id_currency_registry::{ + AccountKind, AllocError, Allocator, CURRENCY_RANGE_START, CurrencyStatus, InMemoryStore, + LedgerKind, MIGRATION_0001_UP, RegisterAccount, RegisterCurrency, Registry, RegistryError, + SYSTEM_RANGE_END, StoreError, SupplyPolicy, +}; + +fn register_input(currency_id: &str, issuer_id: &str, symbol: &str) -> RegisterCurrency { + RegisterCurrency { + currency_id: currency_id.to_owned(), + name: format!("{symbol} token"), + symbol: symbol.to_owned(), + scale: 2, + issuer_id: issuer_id.to_owned(), + supply_policy: SupplyPolicy { + mintable: true, + cap: None, + policy_uri: None, + }, + graph_object_id: Some(format!("graph-{currency_id}")), + } +} + +#[test] +fn allocator_hands_out_nonzero_monotonic_currency_ledgers() { + let mut allocator = Allocator::new(InMemoryStore::new()); + let first = allocator.allocate(LedgerKind::Currency, "abc").unwrap(); + let second = allocator.allocate(LedgerKind::Currency, "def").unwrap(); + let third = allocator.allocate(LedgerKind::Currency, "ghi").unwrap(); + assert_eq!(first, CURRENCY_RANGE_START); + assert!(first != 0 && second != 0 && third != 0); + assert!(first < second && second < third, "allocation is monotonic"); +} + +#[test] +fn allocator_keeps_the_ratified_range_split() { + let mut allocator = Allocator::new(InMemoryStore::new()); + let tenancy = allocator.allocate(LedgerKind::Tenancy, "tenant-1").unwrap(); + let system = allocator.allocate(LedgerKind::System, "fees").unwrap(); + let currency = allocator.allocate(LedgerKind::Currency, "abc").unwrap(); + assert_eq!(tenancy, 1); + assert!((1..=SYSTEM_RANGE_END).contains(&system)); + assert!(currency >= CURRENCY_RANGE_START); +} + +#[test] +fn allocator_refuses_to_recycle() { + let mut allocator = Allocator::new(InMemoryStore::new()); + let spent = allocator.allocate(LedgerKind::Currency, "abc").unwrap(); + // Reserving the spent id again is a recycle attempt: refused. + let err = allocator + .reserve_specific(LedgerKind::Currency, spent, "someone-else") + .unwrap_err(); + assert_eq!(err, AllocError::Store(StoreError::AlreadyAllocated(spent))); + // And sequential allocation never reissues it either. + let next = allocator.allocate(LedgerKind::Currency, "def").unwrap(); + assert_ne!(next, spent); + assert!(next > spent); +} + +#[test] +fn reserve_specific_validates_the_range() { + let mut allocator = Allocator::new(InMemoryStore::new()); + // A currency reservation inside the system range is out of range. + let err = allocator + .reserve_specific(LedgerKind::Currency, 7, "abc") + .unwrap_err(); + assert_eq!( + err, + AllocError::OutOfRange { + kind: LedgerKind::Currency, + ledger_id: 7 + } + ); + // Ledger 0 is in nobody's range: it can never be allocated. + let err = allocator + .reserve_specific(LedgerKind::System, 0, "zero") + .unwrap_err(); + assert_eq!( + err, + AllocError::OutOfRange { + kind: LedgerKind::System, + ledger_id: 0 + } + ); +} + +#[test] +fn two_issuers_may_both_register_symbol_abc() { + let mut registry = Registry::new(InMemoryStore::new()); + let alice = registry + .register_currency(register_input("alice-abc", "alice", "ABC")) + .unwrap(); + let bob = registry + .register_currency(register_input("bob-abc", "bob", "ABC")) + .unwrap(); + assert_eq!(alice.symbol, "ABC"); + assert_eq!(bob.symbol, "ABC"); + assert_ne!(alice.ledger_id, bob.ledger_id); + assert!(alice.ledger_id >= CURRENCY_RANGE_START); + assert_eq!(alice.status, CurrencyStatus::Active); + // The graph linkage (design section 2.4) is recorded at minting. + assert_eq!(alice.graph_object_id.as_deref(), Some("graph-alice-abc")); +} + +#[test] +fn duplicate_currency_id_is_rejected() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + // A different issuer proposing the same currency_id: rejected, + // because currency_id is globally unique (decision 3). + let err = registry + .register_currency(register_input("abc", "bob", "XYZ")) + .unwrap_err(); + assert_eq!( + err, + RegistryError::Store(StoreError::DuplicateCurrencyId("abc".to_owned())) + ); +} + +#[test] +fn duplicate_symbol_for_the_same_issuer_is_rejected() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("alice-abc", "alice", "ABC")) + .unwrap(); + let err = registry + .register_currency(register_input("alice-abc-2", "alice", "ABC")) + .unwrap_err(); + assert_eq!( + err, + RegistryError::Store(StoreError::DuplicateSymbol { + issuer_id: "alice".to_owned(), + symbol: "ABC".to_owned() + }) + ); +} + +#[test] +fn rejected_registration_does_not_burn_a_ledger_id() { + let mut registry = Registry::new(InMemoryStore::new()); + let first = registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + let _ = registry.register_currency(register_input("abc", "bob", "XYZ")); + let _ = registry.register_currency(register_input("alice-2", "alice", "ABC")); + let second = registry + .register_currency(register_input("def", "bob", "DEF")) + .unwrap(); + assert_eq!(second.ledger_id, first.ledger_id + 1); +} + +#[test] +fn only_the_issuer_can_grant_minters() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + registry.grant_minter("abc", "alice-ops", "alice").unwrap(); + let err = registry + .grant_minter("abc", "mallory", "mallory") + .unwrap_err(); + assert_eq!( + err, + RegistryError::NotIssuer { + currency_id: "abc".to_owned(), + account_id: "mallory".to_owned() + } + ); +} + +#[test] +fn account_index_records_factory_accounts() { + let mut registry = Registry::new(InMemoryStore::new()); + registry + .register_currency(register_input("abc", "alice", "ABC")) + .unwrap(); + let account = registry + .register_account(RegisterAccount { + currency_id: "abc".to_owned(), + account_id: "0123456789abcdef0123456789abcdef".to_owned(), + owner_id: "alice".to_owned(), + kind: AccountKind::Issuer, + salt: String::new(), + }) + .unwrap(); + assert_eq!(account.kind, AccountKind::Issuer); + // The same (ledger, owner, kind, salt) slot cannot be recorded + // twice under a different account id. + let err = registry + .register_account(RegisterAccount { + currency_id: "abc".to_owned(), + account_id: "fedcba9876543210fedcba9876543210".to_owned(), + owner_id: "alice".to_owned(), + kind: AccountKind::Issuer, + salt: String::new(), + }) + .unwrap_err(); + assert_eq!(err, RegistryError::Store(StoreError::DuplicateAccountSlot)); +} + +#[test] +fn migration_creates_the_four_tables_with_the_named_constraints() { + let sql = MIGRATION_0001_UP.to_lowercase(); + for table in [ + "create table ledger_allocation", + "create table currency", + "create table currency_issuer", + "create table account", + ] { + assert!(sql.contains(table), "migration is missing {table}"); + } + // Decision 2: bigint ledger id with the 0..4294967295 check. + assert!(sql.contains("bigint primary key")); + assert!(sql.contains("between 0 and 4294967295")); + // Decision 3: currency_id globally unique; symbol per issuer. + assert!(sql.contains("currency_id text not null unique")); + assert!(sql.contains("unique (issuer_id, symbol)")); + // Design section 2.4: the graph linkage column exists. + assert!(sql.contains("graph_object_id")); + // Design section 6: the allocator entry point exists. + assert!(sql.contains("create function allocate_ledger")); +}