From 8ccad86805ac38e518f5d3d6cc617f4b142dfe01 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:25:53 +0800 Subject: [PATCH] BRG-1: an all-token window and a delay for large transfers at the guardian, and an audit of the chain-side caps Main already has a per-transfer cap (withheld for an operator), a rolling per-token window (deferred), a manual signing pause, and the endpoints' release caps and pause. It had no delay anywhere, no bound across tokens, and no check that the chain-side caps are set. This adds the three. [guardian.limits] gains two optional bounds, off unless configured: - per_window_total: what the guardian signs across all tokens together, per direction, in the same rolling window. A transfer over it is deferred like one over its token's window. - delay_above + delay_secs: a transfer above the threshold is signed only delay_secs after the guardian first read it, on its own clock. The first-read time is kept in delayed//.json under the guardian's seal; a record that is backdated, unsealed, from the future or unreadable starts the wait again. A delayed transfer is listed with the deferred ones and holds back no other transfer; if its window is full once the delay has passed it queues like any other. rand-bridge-audit --limits reads each endpoint's per-transfer and daily release cap per approved backing and Rand's daily mint cap, prints them in attested units next to the config's [guardian.limits], and exits non-zero when an enabled backing has an unlimited cap or a bound cannot be read. A config without the new keys behaves as before. A build older than this one refuses a config that has them (the section denies unknown fields), so a rollback removes the keys first. Co-Authored-By: Claude Fable 5.2 --- daemons/README.md | 11 ++ daemons/config.example.toml | 5 + daemons/src/bin/audit.rs | 207 +++++++++++++++++++++++++++ daemons/src/bin/guardian.rs | 29 +++- daemons/src/guardian.rs | 51 ++++++- daemons/src/limits.rs | 184 +++++++++++++++++++++++- daemons/tests/audit_bin.rs | 86 ++++++++++++ daemons/tests/audit_v14.rs | 3 + daemons/tests/limits.rs | 261 +++++++++++++++++++++++++++++++++++ daemons/tests/stale_store.rs | 3 + docs/architecture.md | 13 ++ 11 files changed, 838 insertions(+), 15 deletions(-) diff --git a/daemons/README.md b/daemons/README.md index 816e4ef..c0366c8 100644 --- a/daemons/README.md +++ b/daemons/README.md @@ -52,6 +52,17 @@ relayer ◀──GET /v1/signature/{emitter_chain}/{sequence}────── a guardian without the section warns at startup. - Persists the signature before it advances its cursor, and refuses — fatally — to sign a second body under an `(emitter chain, sequence)` it has already signed. +- **Two further bounds, off unless configured** (BRG-1, `[guardian.limits]`): + `per_window_total` caps what the guardian signs across all tokens together, per direction, in + the same rolling window; without it the bound is the per-token cap times the number of tokens. + `delay_above` with `delay_secs` makes a transfer above that amount wait `delay_secs` on the + guardian's clock, counted from when it first read it, before it is signed: the time an operator + has to look and to `--pause-signing`. The first-read time is kept in + `data_dir/delayed//.json` under the guardian's seal; a record that is missing + its seal, backdated, or unreadable starts the wait again. A delayed transfer is listed with the + deferred ones and holds back nothing else. `rand-bridge-audit --config --limits` reads the + bounds the chains themselves enforce (each endpoint's release caps, Rand's daily mint cap) and + fails when an enabled backing has none. - **Asks its peers before a first signature** (BR-502, `guardian.peers`): replay protection on the destinations is by body digest, so two bodies of one lock could each be redeemed. The guardian's own `signed/` record stops a second body only while it exists; a `data_dir` restored diff --git a/daemons/config.example.toml b/daemons/config.example.toml index d5af3c9..b1e1e3d 100644 --- a/daemons/config.example.toml +++ b/daemons/config.example.toml @@ -95,6 +95,11 @@ pq_seed_env = "GUARDIAN_PQ_SEED" # 32-byte Dilithium2 seed, generated ON thi # per_transfer = 10000000000 # 100 tokens # per_window = 100000000000 # 1,000 tokens per window # window_secs = 86400 +# per_window_total = 300000000000 # optional: all tokens together, per direction, per window. +# # Absent, the bound is per_window times the number of tokens. +# delay_above = 5000000000 # optional, with delay_secs: a transfer above this amount is +# delay_secs = 3600 # signed only this long after the guardian first read it +# # (data_dir/delayed/, sealed). It holds back no other transfer. # [[guardian.limits.token]] # optional per-token override # chain = 2 # address = "0x…" # EVM 0x+40 hex, 0x+64 hex wire word, Tron T…, Solana mint diff --git a/daemons/src/bin/audit.rs b/daemons/src/bin/audit.rs index b764583..ea3bad2 100644 --- a/daemons/src/bin/audit.rs +++ b/daemons/src/bin/audit.rs @@ -21,6 +21,14 @@ //! autonomous Squads vault. It does not cover custody, which the guardian //! quorum authorises (BR-4). Read-only; exits non-zero when any rule is FAIL //! or UNKNOWN. The rules live in `bridge_daemons::gov_audit`. +//! +//! `--limits` instead reads the loss bounds that are in force on chain +//! (BRG-1): each endpoint's per-transfer and daily release cap for each +//! approved backing, and Rand's daily mint cap, in attested 8-decimal units, +//! next to the config's `[guardian.limits]` when it has one. A cap of 0 on an +//! endpoint means unlimited, so an enabled backing without both release caps, +//! or a Rand side without a mint cap, is a FAIL. Read-only; exits non-zero on +//! any FAIL or UNKNOWN. use std::path::PathBuf; @@ -46,6 +54,11 @@ struct Cli { /// multisig and upgrade authority on every endpoint. #[arg(long)] governance: bool, + /// Check the loss bounds in force (BRG-1) instead of custody: every + /// enabled backing's release caps on its endpoint and Rand's daily mint + /// cap, next to this config's `[guardian.limits]`. + #[arg(long, conflicts_with = "governance")] + limits: bool, } /// The approved backings: (bridge chain, symbol, token, decimals). @@ -268,6 +281,194 @@ fn attested(native: u128, decimals: u32) -> u128 { } } +// ---- --limits ---------------------------------------------------------------- + +/// The release caps an endpoint holds a backing to, in the token's native +/// units; 0 is unlimited on every endpoint. +struct CapRow { + chain: u16, + symbol: &'static str, + token_word: [u8; 32], + decimals: u32, + /// `None`: the endpoint could not be read. + caps: Option<(bool, u128, u128)>, +} + +async fn evm_caps(config: &Config) -> Vec { + let mut rows = Vec::new(); + for endpoint in &config.evm { + let url = match endpoint.kind { + EvmKind::Evm => endpoint.rpc.clone(), + EvmKind::Tron => format!("{}/jsonrpc", endpoint.rpc.trim_end_matches('/')), + }; + let rpc = JsonRpc::new(&url); + for (chain, symbol, token, decimals) in EVM_TOKENS.iter().filter(|t| t.0 == endpoint.chain) { + let mut token_word = [0u8; 32]; + // tokenConfig(address) -> (enabled, decimals, perTransferCap, dailyCap, windowStart, windowUsed) + let caps = async { + let bridge = address20(&endpoint.contract)?; + let token20 = address20(token)?; + token_word[12..].copy_from_slice(&token20); + let cfg = eth_call(&rpc, &bridge, call_with_address("tokenConfig(address)", &token20)).await?; + if cfg.len() < 128 { + bail!("tokenConfig returned {} bytes, expected at least 128", cfg.len()); + } + anyhow::Ok((cfg[31] == 1, word_u128(&cfg[64..96])?, word_u128(&cfg[96..128])?)) + } + .await; + if let Err(e) = &caps { + eprintln!("{} {symbol}: {e:#}", endpoint.name); + } + rows.push(CapRow { chain: *chain, symbol, token_word, decimals: *decimals, caps: caps.ok() }); + } + } + rows +} + +async fn solana_caps(config: &Config) -> Vec { + let Some(sol) = &config.solana else { + return Vec::new(); + }; + let rpc = JsonRpc::new(&sol.rpc); + let mut rows = Vec::new(); + for (symbol, mint, decimals) in SOLANA_TOKENS { + let mut token_word = [0u8; 32]; + // TokenRegistry: tag, mint (32), enabled, decimals, per_transfer_cap u64, daily_cap u64, … + let caps = async { + let program = pubkey32(&sol.program)?; + token_word = pubkey32(mint)?; + let (registry_key, _) = find_program_address(&[b"token", &token_word], &program)?; + let le64 = |d: &[u8], at: usize| -> Result { + Ok(u128::from(u64::from_le_bytes( + d.get(at..at + 8).ok_or_else(|| anyhow!("account too short"))?.try_into().expect("8"), + ))) + }; + anyhow::Ok(match solana_account(&rpc, ®istry_key).await? { + Some(d) => (d.get(33) == Some(&1), le64(&d, 35)?, le64(&d, 43)?), + None => (false, 0, 0), + }) + } + .await; + if let Err(e) = &caps { + eprintln!("solana {symbol}: {e:#}"); + } + rows.push(CapRow { chain: 5, symbol, token_word, decimals: *decimals, caps: caps.ok() }); + } + rows +} + +/// `(chain, token word) -> (mint_cap_per_day, minted_today)` from `rand_getTokenSupply`. +async fn rand_mint_caps(config: &Config, token: &str) -> Option, Option)>> { + let rpc = JsonRpc::new(&config.rand.rpc); + let param = token.parse::().map(|i| json!(i)).unwrap_or_else(|_| json!(token)); + let v = rpc.call("rand_getTokenSupply", json!([param])).await.ok()?; + v["backings"] + .as_array()? + .iter() + .map(|a| { + let chain = a["chain"].as_u64()? as u16; + let word: [u8; 32] = hex::decode(a["token"].as_str()?).ok()?.try_into().ok()?; + Some((chain, word, amount(&a["mint_cap_per_day"]), amount(&a["minted_today"]))) + }) + .collect() +} + +fn cap_text(v: u128) -> String { + if v == 0 { + "UNLIMITED".into() + } else { + v.to_string() + } +} + +/// The `--limits` report. `Ok(false)` when a bound is missing or unreadable. +async fn limits_report(config: &Config, token: &str, out: &mut impl std::io::Write) -> Result { + let mut rows = evm_caps(config).await; + rows.extend(solana_caps(config).await); + let rand = rand_mint_caps(config, token).await; + let mut ok = true; + writeln!( + out, + "{:<5} {:<5} {:<8} {:>22} {:>22} {:>22} {:>18} verdict", + "chain", "coin", "enabled", "release cap/transfer", "release cap/day", "Rand mint cap/day", "minted today" + )?; + for r in &rows { + let mint = rand.as_ref().and_then(|m| m.iter().find(|(c, t, _, _)| *c == r.chain && *t == r.token_word)); + let mint_cap = mint.and_then(|m| m.2); + let minted = mint.and_then(|m| m.3); + let (enabled, per_transfer, per_day, mut verdict) = match r.caps { + None => { + ok = false; + ("?".to_string(), "?".to_string(), "?".to_string(), vec!["UNKNOWN: the endpoint could not be read".to_string()]) + } + Some((enabled, per_transfer, per_day)) => { + let mut v = Vec::new(); + if enabled && per_transfer == 0 { + v.push("FAIL: no per-transfer release cap".to_string()); + } + if enabled && per_day == 0 { + v.push("FAIL: no daily release cap".to_string()); + } + ( + enabled.to_string(), + cap_text(attested(per_transfer, r.decimals)), + cap_text(attested(per_day, r.decimals)), + v, + ) + } + }; + let is_enabled = matches!(r.caps, Some((true, _, _))); + if is_enabled { + match (&rand, mint_cap) { + (None, _) => verdict.push("UNKNOWN: the Rand node did not serve the mint caps".into()), + (Some(_), None | Some(0)) => verdict.push("FAIL: no daily mint cap on Rand".into()), + (Some(_), Some(_)) => {} + } + } + if verdict.is_empty() { + verdict.push(if is_enabled { "PASS".into() } else { "not enabled".into() }); + } else { + ok = false; + } + writeln!( + out, + "{:<5} {:<5} {:<8} {:>22} {:>22} {:>22} {:>18} {}", + r.chain, + r.symbol, + enabled, + per_transfer, + per_day, + mint_cap.map(cap_text).unwrap_or_else(|| "n/a".into()), + minted.map(|v| v.to_string()).unwrap_or_else(|| "n/a".into()), + verdict.join("; ") + )?; + } + writeln!(out, "Amounts are attested 8-decimal units. The endpoint caps bound releases; the Rand cap bounds mints, per backing and UTC day.")?; + match config.guardian.as_ref().and_then(|g| g.limits.as_ref()) { + Some(l) => { + writeln!( + out, + "[guardian.limits] in this config: {} per transfer, {} per {} s per token and direction, {} across all tokens, {}; {} token override(s).", + l.per_transfer, + l.per_window, + l.window_secs, + l.per_window_total.map_or_else(|| "no cap".to_string(), |t| t.to_string()), + match (l.delay_above, l.delay_secs) { + (Some(a), Some(s)) => format!("transfers above {a} wait {s} s"), + _ => "no delay".to_string(), + }, + l.token.len() + )?; + writeln!(out, "That is what this file asks of one guardian. Whether a running guardian has it is in its own startup log (`caps:`), not here.")?; + } + None => writeln!( + out, + "This config has no [guardian.limits]: pass a guardian's config to print the caps it asks for next to the chains'." + )?, + } + Ok(ok) +} + // ---- --governance ------------------------------------------------------------ async fn eth_get_code(rpc: &JsonRpc, address: &[u8; 20]) -> Result> { @@ -736,6 +937,12 @@ async fn main() -> Result<()> { let result = governance(&config).await; return with_caveat(result, &mut std::io::stdout()); } + if cli.limits { + if !limits_report(&config, &cli.token, &mut std::io::stdout()).await? { + bail!("at least one loss bound is missing or could not be read (BRG-1)"); + } + return Ok(()); + } let mut rows = evm_rows(&config).await?; rows.extend(solana_rows(&config).await?); let rand = rand_side(&config, &cli.token).await; diff --git a/daemons/src/bin/guardian.rs b/daemons/src/bin/guardian.rs index 202dac1..c6141ef 100644 --- a/daemons/src/bin/guardian.rs +++ b/daemons/src/bin/guardian.rs @@ -131,13 +131,28 @@ async fn main() -> Result<()> { .map(bridge_daemons::limits::Limits::new) .transpose()?; match §ion.limits { - Some(l) => tracing::info!( - "caps: {} per transfer, {} per {} s per token and direction ({} token overrides)", - l.per_transfer, - l.per_window, - l.window_secs, - l.token.len() - ), + Some(l) => { + tracing::info!( + "caps: {} per transfer, {} per {} s per token and direction ({} token overrides)", + l.per_transfer, + l.per_window, + l.window_secs, + l.token.len() + ); + match l.per_window_total { + Some(total) => tracing::info!( + "caps: {total} per {} s across all tokens, per direction", + l.window_secs + ), + None => tracing::info!("caps: no per_window_total, so each token's window is the only bound"), + } + match (l.delay_above, l.delay_secs) { + (Some(above), Some(secs)) => { + tracing::info!("caps: a transfer above {above} is signed {secs} s after it is first read") + } + _ => tracing::info!("caps: no delay_above, so nothing waits before it is signed"), + } + } None => tracing::warn!( "no [guardian.limits]: this guardian signs without per-transfer or per-window caps (BRG-1)" ), diff --git a/daemons/src/guardian.rs b/daemons/src/guardian.rs index 34c14d7..6784d80 100644 --- a/daemons/src/guardian.rs +++ b/daemons/src/guardian.rs @@ -241,13 +241,17 @@ pub struct Deferred { pub chain: u16, pub sequence: u64, pub reason: String, + /// It waits out its delay (`guardian.limits.delay_above`), not for room in a window, and + /// holds back no later transfer of its token. + pub delay: bool, } impl std::fmt::Display for Deferred { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let until = if self.delay { "its delay has passed" } else { "its window has room" }; write!( f, - "chain {} sequence {} deferred until its window has room: {}", + "chain {} sequence {} deferred until {until}: {}", self.chain, self.sequence, self.reason ) } @@ -325,9 +329,19 @@ pub async fn step_guarded( } } Err(e) if e.downcast_ref::().is_some() => { + let delay = e.downcast_ref::().is_some_and(|d| d.delay); tracing::warn!("{}: {e:#}", source.name()); - limits::defer(store, key, &message, limits::now(), limits::DeferKind::Window, &format!("{e:#}"))?; - if let Some(w) = limits::window_of(&message) { + limits::defer_as( + store, + key, + &message, + limits::now(), + limits::DeferKind::Window, + &format!("{e:#}"), + delay, + )?; + // One that waits out its delay holds nothing back. + if let Some(w) = limits::window_of(&message).filter(|_| !delay) { waiting.insert(w); } } @@ -353,8 +367,9 @@ fn deferred_windows(store: &Store) -> Result> let mut out = std::collections::BTreeSet::new(); for (chain, sequence) in limits::listed(store, limits::DEFERRED)? { if let Some(d) = store.read_message::(limits::DEFERRED, chain, sequence)? { - // Whatever it waits for, later transfers of its token wait behind it. - if let Some(w) = limits::window_of(&d.message) { + // Whether it waits for room or for its peers, later transfers of its token wait + // behind it. One that only waits out its delay holds nothing back. + if let Some(w) = limits::window_of(&d.message).filter(|_| !d.delay) { out.insert(w); } } @@ -424,7 +439,13 @@ pub async fn retry_deferred( limits::remove(store, limits::DEFERRED, chain, sequence)?; } Err(e) if e.downcast_ref::().is_some() => { - if let Some(w) = window { + let delay = e.downcast_ref::().is_some_and(|w| w.delay); + if delay != d.delay { + // What it waits for changed (its delay passed and its window is full): + // the record says so, so later transfers of its token queue behind it. + limits::defer_as(store, key, &d.message, d.at, d.kind, &format!("{e:#}"), delay)?; + } + if let Some(w) = window.filter(|_| !delay) { blocked.insert(w); } } @@ -593,6 +614,19 @@ fn sign_checked( return Ok(false); } if let Some(limits) = guards.limits { + // The delay first: a transfer that still waits is not counted in a window yet. An + // operator's release of a held transfer is a review, and skips it. + if !released { + if let Some(reason) = limits.delay(store, key, message, now)? { + return Err(Deferred { + chain, + sequence, + reason, + delay: true, + } + .into()); + } + } let verdict = match limits.admit(store, message, now, released) { Ok(v) => v, // A broken window record holds back its own token only. @@ -624,6 +658,7 @@ fn sign_checked( chain, sequence, reason, + delay: false, } .into()) } @@ -644,6 +679,10 @@ fn sign_checked( pq_signature, }; store.write_message(SIGNED, chain, sequence, &signed)?; + // Its delay record, if it had one, has done its work. + if guards.limits.is_some_and(|l| l.delay_rule().is_some()) { + let _ = limits::remove(store, limits::DELAYED, chain, sequence); + } tracing::info!(chain, sequence, digest = %hex::encode(message.digest), "signed"); Ok(true) } diff --git a/daemons/src/limits.rs b/daemons/src/limits.rs index 5964513..bb65445 100644 --- a/daemons/src/limits.rs +++ b/daemons/src/limits.rs @@ -19,6 +19,20 @@ //! signed on its own once its window has room — in sequence order per token, //! while the source's cursor moves on for every other transfer. The global pause (`limits/paused.json`) //! is never set automatically, only by `rand-guardian --pause-signing`. +//! +//! Two further bounds are optional, off unless configured: +//! +//! - `per_window_total`: a cap on what this guardian signs across **all** +//! tokens together, per direction, in the same rolling window. The +//! per-token cap bounds one token; with n tokens listed the guardian would +//! otherwise sign n times that. A transfer that would overrun the total is +//! deferred like one that overruns its token's window. +//! - `delay_above` with `delay_secs`: a transfer above `delay_above` is signed +//! only once `delay_secs` have passed on this guardian's clock since it +//! first read it (`delayed//.json`, sealed by the guardian +//! so a planted record cannot shorten the wait). The wait is the time an +//! operator has to look and to pause. A delayed transfer holds back nothing +//! else: later transfers of its token are signed as usual. use anyhow::{anyhow, bail, Context, Result}; use bridge_codec::{Payload, CHAIN_RAND, CHAIN_SOLANA}; @@ -39,6 +53,18 @@ pub struct LimitsConfig { pub per_window: u64, #[serde(default = "default_window_secs")] pub window_secs: u64, + /// Most signed across all tokens together, per direction, in any + /// `window_secs`. Absent: only the per-token windows bound it. + #[serde(default)] + pub per_window_total: Option, + /// A transfer above this amount waits `delay_secs` before it is signed. + /// Absent: nothing is delayed. Set together with `delay_secs`. + #[serde(default)] + pub delay_above: Option, + /// How long a transfer above `delay_above` waits, in seconds on this + /// guardian's clock, counted from when it first read the transfer. + #[serde(default)] + pub delay_secs: Option, /// Per-token overrides. #[serde(default)] pub token: Vec, @@ -139,6 +165,34 @@ pub struct Deferral { /// one is never signed by a retry. #[serde(default, skip_serializing_if = "Option::is_none")] pub seal: Option, + /// It waits out its delay (`delay_above`), not for room in a window: later transfers of + /// its token do not queue behind it. Left out when false, so a record written without a + /// delay reads the same under an older build. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub delay: bool, +} + +/// When a transfer above `delay_above` was first read, as written to +/// `delayed//.json`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct Delayed { + /// The digest of the body the delay belongs to. + pub digest: String, + /// First read at, unix seconds on this guardian's clock. + pub at: u64, + /// This guardian's seal over `(chain, sequence, digest, at)`: a record without a valid one + /// did not come from this daemon and starts the delay again. + pub seal: String, +} + +pub const DELAYED: &str = "delayed"; + +fn delayed_seal(key: &GuardianKey, message: &Observed, at: u64) -> String { + let mut data = message.emitter_chain.to_be_bytes().to_vec(); + data.extend_from_slice(&message.sequence.to_be_bytes()); + data.extend_from_slice(&message.digest); + data.extend_from_slice(&at.to_be_bytes()); + hex::encode(key.seal(b"delayed", &data)) } /// The seal a deferred record of `message` carries under `key`. @@ -192,6 +246,20 @@ pub fn defer( now: u64, kind: DeferKind, reason: &str, +) -> Result<()> { + defer_as(store, key, message, now, kind, reason, false) +} + +/// [`defer`], saying whether the transfer waits out a delay (`delay`: it holds back no later +/// transfer of its token) or waits for room. +pub fn defer_as( + store: &Store, + key: &GuardianKey, + message: &Observed, + now: u64, + kind: DeferKind, + reason: &str, + delay: bool, ) -> Result<()> { store.write_message( DEFERRED, @@ -203,6 +271,7 @@ pub fn defer( kind, reason: reason.to_string(), seal: Some(deferral_seal(key, message)), + delay, }, ) } @@ -294,6 +363,15 @@ impl Limits { if cfg.per_transfer > cfg.per_window { bail!("guardian.limits: per_transfer is above per_window"); } + if cfg.per_window_total.is_some_and(|total| cfg.per_transfer > total) { + bail!("guardian.limits: per_transfer is above per_window_total"); + } + match (cfg.delay_above, cfg.delay_secs) { + (None, None) => {} + (Some(_), Some(secs)) if secs > 0 => {} + (Some(_), Some(_)) => bail!("guardian.limits.delay_secs must be positive"), + _ => bail!("guardian.limits: delay_above and delay_secs are set together or not at all"), + } let mut overrides = Vec::new(); for t in &cfg.token { if !(2..=5).contains(&t.chain) { @@ -327,6 +405,84 @@ impl Limits { self.cfg.window_secs } + /// `(delay_above, delay_secs)`, when a delay is configured. + pub fn delay_rule(&self) -> Option<(u64, u64)> { + self.cfg.delay_above.zip(self.cfg.delay_secs) + } + + pub fn per_window_total(&self) -> Option { + self.cfg.per_window_total + } + + /// Whether `message` must still wait out its delay at `now`: `Some(why)` + /// while it must, `None` when it has no delay or the delay has passed. + /// The first call for a transfer above `delay_above` records when this + /// guardian first read it; the wait is counted from that record, so a + /// restart does not start it again. A record that is unreadable, names + /// another body, lies in the future or is not sealed by `key` is replaced + /// and the wait starts again: a fault here delays, it never shortens. + pub fn delay( + &self, + store: &Store, + key: &GuardianKey, + message: &Observed, + now: u64, + ) -> Result> { + let Some((above, secs)) = self.delay_rule() else { + return Ok(None); + }; + let Ok(Payload::Transfer(t)) = Payload::decode(&message.decoded().payload) else { + return Ok(None); // not a transfer: `admit` withholds it + }; + let Some(amount) = t.amount_u128().and_then(|a| u64::try_from(a).ok()) else { + return Ok(None); // above u64: `admit` withholds it + }; + if amount <= above { + return Ok(None); + } + let (chain, sequence) = (message.emitter_chain, message.sequence); + let digest = hex::encode(message.digest); + let known = match store.read_message::(DELAYED, chain, sequence) { + Ok(Some(d)) if d.digest == digest && d.at <= now && d.seal == delayed_seal(key, message, d.at) => Some(d.at), + Ok(None) => None, + Ok(Some(_)) => { + tracing::error!( + "delayed/{chain}/{sequence:020}.json is not this guardian's record of this transfer; the delay starts again" + ); + None + } + Err(e) => { + tracing::error!("delayed/{chain}/{sequence:020}.json is unreadable ({e:#}); the delay starts again"); + None + } + }; + let at = match known { + Some(at) => at, + None => { + store.write_message( + DELAYED, + chain, + sequence, + &Delayed { + digest, + at: now, + seal: delayed_seal(key, message, now), + }, + )?; + now + } + }; + let until = at.saturating_add(secs); + if now < until { + return Ok(Some(format!( + "{} of {amount} is above delay_above {above}: first read at {at}, signed no earlier than {until} ({} s from now)", + Direction::of(message).label(), + until - now + ))); + } + Ok(None) + } + /// Checks `message` against the caps at `now` and, when it is admitted, /// counts it in its window (before the signature is made: a crash in /// between over-counts, never under-counts). `released`: an operator @@ -381,12 +537,36 @@ impl Limits { used.saturating_add(amount) ))); } - entries.push(Entry { + let entry = Entry { at: now, amount, chain: message.emitter_chain, sequence: message.sequence, - }); + }; + // Every token together, per direction. Written before the token's own window: a crash + // in between over-counts the total, never under-counts it. + if let Some(cap) = self.cfg.per_window_total { + let name = format!("{}-total.json", direction.label()); + let total_parts = ["limits", "window", name.as_str()]; + let mut all: Vec = store + .read(&total_parts) + .context("reading the all-token cap window (nothing in this direction is signed until it is repaired)")? + .unwrap_or_default(); + all.retain(|e| e.at > since); + let used_all: u64 = all.iter().map(|e| e.amount).fold(0u64, u64::saturating_add); + if used_all.saturating_add(amount) > cap && !released { + return Ok(Verdict::Defer(format!( + "{} of {amount} on {token} would bring the last {} s across all tokens to {} \ + (per_window_total {cap})", + direction.label(), + self.cfg.window_secs, + used_all.saturating_add(amount) + ))); + } + all.push(entry.clone()); + store.write(&total_parts, &all)?; + } + entries.push(entry); store.write(&parts, &entries)?; Ok(Verdict::Admit) } diff --git a/daemons/tests/audit_bin.rs b/daemons/tests/audit_bin.rs index cac1c36..1d3dc5d 100644 --- a/daemons/tests/audit_bin.rs +++ b/daemons/tests/audit_bin.rs @@ -771,3 +771,89 @@ fn solana_governance_reports_what_is_missing_or_misowned() { let (_, out, _) = run_solana(&solana_node(wrong_pd), ""); assert!(out.contains("ProgramData is owned by"), "{out}"); } + +// ---- --limits (BRG-1) -------------------------------------------------------- + +/// An Ethereum endpoint whose two coins carry these release caps (native 6-decimal units), +/// and a Rand node serving `mint_cap` per backing (`None`: the method is not served). +fn caps_node(per_transfer: u128, per_day: u128, enabled: bool, mint_cap: Option<&'static str>) -> Fake { + rpc(move |m, p| match m { + "eth_call" => { + let data = hex::decode(p[0]["data"].as_str().unwrap().trim_start_matches("0x")).unwrap(); + let sel: [u8; 4] = data[..4].try_into().unwrap(); + if sel != selector("tokenConfig(address)") { + return Some(Err(json!({ "code": 3, "message": "reverted" }))); + } + let words = [u128::from(enabled), 6, per_transfer, per_day, 0, 0]; + Some(Ok(json!(format!("0x{}", words.iter().map(|w| format!("{w:064x}")).collect::())))) + } + "rand_getTokenSupply" => mint_cap.map(|cap| { + let row = |token: &str| json!({ "chain": 2, "token": format!("{}{token}", "00".repeat(12)), "decimals": 6, "locked": "0", "mint_cap_per_day": cap, "minted_today": "5" }); + Ok(json!({ "total_supply": "0", "backings": [row(USDT), row(USDC)] })) + }), + _ => None, + }) +} + +fn run_limits(node: &Fake, guardian: &str) -> Output { + let dir = tempfile::tempdir().unwrap(); + let cfg = config(dir.path(), &node.url, &format!("{}{guardian}", evm_section("eth", 2, "evm", &node.url))); + audit().arg("--config").arg(&cfg).arg("--limits").output().unwrap() +} + +#[test] +fn the_limits_check_passes_when_every_bound_is_set_and_prints_them_in_one_unit() { + // 100 and 1,000 USDT at 6 decimals; Rand's cap is 100,000 at 8. + let node = caps_node(100_000_000, 1_000_000_000, true, Some("10000000000000")); + let o = run_limits(&node, ""); + let (out, err) = text(&o); + assert!(o.status.success(), "{err}\n{out}"); + assert_eq!(out.matches("PASS").count(), 2, "{out}"); + // Attested 8-decimal units: 100 -> 10_000_000_000, 1,000 -> 100_000_000_000. + assert!(out.contains("10000000000 ") && out.contains("100000000000 ") && out.contains("10000000000000"), "{out}"); + assert!(out.contains("no [guardian.limits]"), "{out}"); +} + +#[test] +fn an_unlimited_release_cap_or_a_missing_mint_cap_fails_the_limits_check() { + for (node, named) in [ + (caps_node(0, 1_000_000_000, true, Some("10000000000000")), "FAIL: no per-transfer release cap"), + (caps_node(100_000_000, 0, true, Some("10000000000000")), "FAIL: no daily release cap"), + (caps_node(100_000_000, 1_000_000_000, true, Some("0")), "FAIL: no daily mint cap on Rand"), + (caps_node(100_000_000, 1_000_000_000, true, None), "UNKNOWN: the Rand node did not serve the mint caps"), + ] { + let o = run_limits(&node, ""); + let (out, err) = text(&o); + assert!(!o.status.success(), "{named}: {out}"); + assert!(out.contains(named), "{named}: {out}"); + assert!(err.contains("BRG-1"), "{err}"); + } + // A backing that is not enabled needs no cap: nothing can be released against it. + let o = run_limits(&caps_node(0, 0, false, None), ""); + let (out, err) = text(&o); + assert!(o.status.success(), "{err}\n{out}"); + assert_eq!(out.matches("not enabled").count(), 2, "{out}"); +} + +#[test] +fn an_endpoint_that_cannot_be_read_is_unknown_not_a_pass() { + let node = rpc(|_, _| None); + let o = run_limits(&node, ""); + let (out, _) = text(&o); + assert!(!o.status.success()); + assert_eq!(out.matches("UNKNOWN: the endpoint could not be read").count(), 2, "{out}"); +} + +#[test] +fn the_limits_check_prints_the_guardian_caps_the_config_asks_for() { + let node = caps_node(100_000_000, 1_000_000_000, true, Some("10000000000000")); + let guardian = "[guardian]\nlisten = \"127.0.0.1:0\"\n[guardian.limits]\nper_transfer = 10000000000\nper_window = 100000000000\nper_window_total = 300000000000\ndelay_above = 5000000000\ndelay_secs = 3600\n"; + let o = run_limits(&node, guardian); + let (out, err) = text(&o); + assert!(o.status.success(), "{err}\n{out}"); + assert!(out.contains("300000000000 across all tokens") && out.contains("transfers above 5000000000 wait 3600 s"), "{out}"); + // --limits and --governance are two different reports. + let dir = tempfile::tempdir().unwrap(); + let cfg = config(dir.path(), &node.url, &evm_section("eth", 2, "evm", &node.url)); + assert!(!audit().arg("--config").arg(&cfg).args(["--limits", "--governance"]).output().unwrap().status.success()); +} diff --git a/daemons/tests/audit_v14.rs b/daemons/tests/audit_v14.rs index 12ff09d..654d6ce 100644 --- a/daemons/tests/audit_v14.rs +++ b/daemons/tests/audit_v14.rs @@ -438,6 +438,9 @@ mod br1004 { per_transfer: 1_000_000_000, per_window: 1_000_000_000, window_secs: 2, + per_window_total: None, + delay_above: None, + delay_secs: None, token: vec![], }) .unwrap(); diff --git a/daemons/tests/limits.rs b/daemons/tests/limits.rs index a108db7..296ed34 100644 --- a/daemons/tests/limits.rs +++ b/daemons/tests/limits.rs @@ -35,6 +35,9 @@ fn published() -> Limits { per_transfer: 100 * UNIT, per_window: 1_000 * UNIT, window_secs: 86_400, + per_window_total: None, + delay_above: None, + delay_secs: None, token: vec![], }) .unwrap() @@ -128,6 +131,9 @@ fn a_token_override_has_its_own_caps() { per_transfer: UNIT, per_window: UNIT, window_secs: 60, + per_window_total: None, + delay_above: None, + delay_secs: None, token: vec![TokenLimit { chain: 2, address: token.into(), @@ -146,6 +152,9 @@ fn bad_limits_are_refused() { per_transfer: 2, per_window: 1, window_secs: 60, + per_window_total: None, + delay_above: None, + delay_secs: None, token: vec![], }; assert!(Limits::new(&base).is_err(), "per_transfer above per_window"); @@ -232,6 +241,9 @@ async fn a_full_window_defers_only_its_token_and_signs_it_later_on_its_own() { per_transfer: 10 * UNIT, per_window: 10 * UNIT, window_secs: 3, + per_window_total: None, + delay_above: None, + delay_secs: None, token: vec![], }) .unwrap(); @@ -324,3 +336,252 @@ fn the_mainnet_guardian_configs_carry_the_published_caps() { ); } } + +// ---- the all-token cap and the delay (BRG-1) ------------------------------------- + +fn with(per_window_total: Option, delay: Option<(u64, u64)>) -> Limits { + Limits::new(&LimitsConfig { + per_transfer: 100 * UNIT, + per_window: 1_000 * UNIT, + window_secs: 86_400, + per_window_total, + delay_above: delay.map(|d| d.0), + delay_secs: delay.map(|d| d.1), + token: vec![], + }) + .unwrap() +} + +fn deferred(r: anyhow::Result) -> guardian::Deferred { + let e = r.unwrap_err(); + let d = e.downcast_ref::().unwrap_or_else(|| panic!("not deferred: {e:#}")); + guardian::Deferred { chain: d.chain, sequence: d.sequence, reason: d.reason.clone(), delay: d.delay } +} + +#[test] +fn the_all_token_cap_bounds_every_token_together_per_direction() { + let (_dir, store) = store(); + // Each token may move 1,000 a day; all of them together 250. + let l = with(Some(250 * UNIT), None); + let t0 = 5_000_000; + assert!(sign(&store, &l, &lock_tok(0, 100, 0xa1), t0)); + assert!(sign(&store, &l, &lock_tok(1, 100, 0xb2), t0 + 1)); + // A third token: its own window is empty, the total is not. + let d = deferred(try_sign(&store, &l, &lock_tok(2, 51, 0xc3), t0 + 2)); + assert!(d.reason.contains("across all tokens") && d.reason.contains("per_window_total"), "{}", d.reason); + assert!(!d.delay); + assert!(!is_signed(&store, 2, 2)); + assert!(sign(&store, &l, &lock_tok(3, 50, 0xc3), t0 + 3), "exactly the total is fine"); + // Releases are counted on their own. + assert!(sign(&store, &l, &burn(0, 2, u128::from(100 * UNIT), 0), t0 + 4)); + // Once the first deposit has left the window there is room again. + assert!(try_sign(&store, &l, &lock_tok(2, 51, 0xc3), t0 + 86_400).is_ok_and(|s| s)); + assert!(try_sign(&store, &l, &lock_tok(4, 100, 0xa1), t0 + 86_400).is_err(), "the rest still counts"); +} + +#[test] +fn a_deferred_transfer_is_counted_in_neither_window() { + let (dir, store) = store(); + let l = with(Some(100 * UNIT), None); + assert!(sign(&store, &l, &lock_tok(0, 100, 0xa1), 1_000)); + deferred(try_sign(&store, &l, &lock_tok(1, 1, 0xb2), 1_001)); + // Token B's window was never written: a deferral over the total leaves no count behind. + let windows: Vec = std::fs::read_dir(dir.path().join("data/limits/window")) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .collect(); + assert_eq!(windows.len(), 2, "{windows:?}"); + assert!(windows.contains(&"deposit-total.json".to_string()), "{windows:?}"); +} + +#[test] +fn an_unreadable_all_token_window_defers_its_direction_only() { + let (dir, store) = store(); + let l = with(Some(250 * UNIT), None); + assert!(sign(&store, &l, &lock_tok(0, 1, 0xa1), 1_000)); + std::fs::write(dir.path().join("data/limits/window/deposit-total.json"), b"").unwrap(); + let d = deferred(try_sign(&store, &l, &lock_tok(1, 1, 0xa1), 1_001)); + assert!(d.reason.contains("cannot be read"), "{}", d.reason); + assert!(sign(&store, &l, &burn(0, 2, u128::from(UNIT), 0), 1_002), "releases have their own total"); +} + +#[test] +fn a_transfer_above_the_delay_threshold_waits_on_the_guardians_clock() { + let (dir, store) = store(); + // Above 50, wait an hour. + let l = with(None, Some((50 * UNIT, 3_600))); + let t0 = 7_000_000; + assert!(sign(&store, &l, &lock_of(0, 50), t0), "exactly the threshold is not delayed"); + let d = deferred(try_sign(&store, &l, &lock_of(1, 51), t0)); + assert!(d.delay, "it waits out a delay, not a window"); + assert!(d.reason.contains("delay_above") && d.reason.contains(&(t0 + 3_600).to_string()), "{}", d.reason); + assert!(!is_signed(&store, 2, 1)); + // The wait is counted from the first read, whatever happens in between: a later look, or + // a restart, does not start it again. + deferred(try_sign(&store, &l, &lock_of(1, 51), t0 + 3_599)); + drop(store); + let store = Store::open(&dir.path().join("data")).unwrap(); + assert!(try_sign(&store, &l, &lock_of(1, 51), t0 + 3_600).unwrap()); + assert!(is_signed(&store, 2, 1)); + assert!( + store.read_message::(limits::DELAYED, 2, 1).unwrap().is_none(), + "the delay record goes once the transfer is signed" + ); + // It was counted in its window only when it was signed. + assert!(sign(&store, &l, &lock_of(2, 1), t0 + 3_601)); +} + +#[test] +fn a_delay_record_this_guardian_did_not_write_starts_the_wait_again() { + let (_dir, store) = store(); + let l = with(None, Some((50 * UNIT, 3_600))); + let m = lock_of(1, 51); + let t0 = 7_000_000; + deferred(try_sign(&store, &l, &m, t0)); + let honest: limits::Delayed = store.read_message(limits::DELAYED, 2, 1).unwrap().unwrap(); + assert_eq!(honest.at, t0); + // Someone who can write the data directory backdates the record to skip the wait. + let planted = limits::Delayed { at: t0 - 3_600, ..honest.clone() }; + store.write_message(limits::DELAYED, 2, 1, &planted).unwrap(); + deferred(try_sign(&store, &l, &m, t0 + 10)); + let again: limits::Delayed = store.read_message(limits::DELAYED, 2, 1).unwrap().unwrap(); + assert_eq!(again.at, t0 + 10, "the wait starts again from now"); + assert!(!is_signed(&store, 2, 1)); + // A record from the future (the clock was set back) starts again too. + deferred(try_sign(&store, &l, &m, t0 + 5)); + // An empty record likewise. + let path = store.root().join("delayed/2").read_dir().unwrap().next().unwrap().unwrap().path(); + std::fs::write(path, b"").unwrap(); + deferred(try_sign(&store, &l, &m, t0 + 20)); + deferred(try_sign(&store, &l, &m, t0 + 3_619)); + assert!(try_sign(&store, &l, &m, t0 + 3_620).unwrap()); +} + +#[test] +fn an_operators_release_of_a_held_transfer_is_not_delayed_and_small_ones_never_are() { + let (_dir, store) = store(); + let l = with(None, Some((50 * UNIT, 3_600))); + let key = &guardian_keys(1)[0]; + let guards = Guards { limits: Some(&l), ..Default::default() }; + // 101 is over the per-transfer cap once its delay has passed: it is then held like any other. + deferred(try_sign(&store, &l, &lock_of(0, 101), 1_000)); + assert!(!try_sign(&store, &l, &lock_of(0, 101), 4_600).unwrap()); + assert_eq!(limits::held(&store).unwrap(), vec![(2, 0)]); + assert!(guardian::release_held(&store, key, None, &emitters(), &guards, 2, 0, 4_601).unwrap()); + assert!(sign(&store, &l, &lock_of(1, 50), 4_602)); +} + +#[test] +fn the_delay_and_the_all_token_cap_are_checked_in_the_config() { + let base = LimitsConfig { + per_transfer: 10, + per_window: 100, + window_secs: 60, + per_window_total: None, + delay_above: None, + delay_secs: None, + token: vec![], + }; + assert!(Limits::new(&base).is_ok()); + assert!(Limits::new(&LimitsConfig { per_window_total: Some(9), ..base.clone() }).is_err(), "below per_transfer"); + assert!(Limits::new(&LimitsConfig { per_window_total: Some(10), ..base.clone() }).is_ok()); + assert!(Limits::new(&LimitsConfig { delay_above: Some(5), ..base.clone() }).is_err(), "no delay_secs"); + assert!(Limits::new(&LimitsConfig { delay_secs: Some(5), ..base.clone() }).is_err(), "no delay_above"); + assert!(Limits::new(&LimitsConfig { delay_above: Some(5), delay_secs: Some(0), ..base.clone() }).is_err()); + let l = Limits::new(&LimitsConfig { delay_above: Some(5), delay_secs: Some(7), ..base.clone() }).unwrap(); + assert_eq!(l.delay_rule(), Some((5, 7))); + // And from TOML, where all three are optional. + let parsed: LimitsConfig = toml::from_str( + "per_transfer = 10\nper_window = 100\nper_window_total = 300\ndelay_above = 5\ndelay_secs = 3600\n", + ) + .unwrap(); + assert_eq!((parsed.per_window_total, parsed.delay_above, parsed.delay_secs), (Some(300), Some(5), Some(3_600))); + let plain: LimitsConfig = toml::from_str("per_transfer = 10\nper_window = 100\n").unwrap(); + assert_eq!((plain.per_window_total, plain.delay_above, plain.delay_secs), (None, None, None)); +} + +#[tokio::test] +async fn a_delayed_transfer_holds_back_nothing_and_signs_on_its_own_later() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(dir.path()).unwrap(); + // Above 5, wait 2 s; the window is 3 s and holds 10 per token. + let l = Limits::new(&LimitsConfig { + per_transfer: 10 * UNIT, + per_window: 10 * UNIT, + window_secs: 3, + per_window_total: None, + delay_above: Some(5 * UNIT), + delay_secs: Some(2), + token: vec![], + }) + .unwrap(); + let source = Batch { + polls: Default::default(), + located: vec![ + at_msg(lock_tok(0, 6, 0xa1), 10), // delayed + at_msg(lock_tok(1, 2, 0xa1), 11), // same token, small: not held back + at_msg(lock_tok(2, 3, 0xb2), 12), + ], + next: Cursor { next_block: 13, next_sequence: 3 }, + }; + let key = &guardian_keys(1)[0]; + let guards = Guards { limits: Some(&l), ..Default::default() }; + let n = guardian::step_guarded(&source, &store, key, None, &emitters(), &guards).await.unwrap(); + assert_eq!(n, 2, "locks 1 and 2"); + assert!(!is_signed(&store, 2, 0) && is_signed(&store, 2, 1) && is_signed(&store, 2, 2)); + assert_eq!(limits::listed(&store, limits::DEFERRED).unwrap(), vec![(2, 0)]); + let record: limits::Deferral = store.read_message(limits::DEFERRED, 2, 0).unwrap().unwrap(); + assert!(record.delay && record.seal.is_some()); + assert_eq!(store.cursor("batch").unwrap(), Some(Cursor { next_block: 13, next_sequence: 3 })); + // A later poll brings another small transfer of the same token: still not held back. + let later = Batch { + polls: Default::default(), + located: vec![at_msg(lock_tok(3, 1, 0xa1), 14)], + next: Cursor { next_block: 15, next_sequence: 4 }, + }; + assert_eq!(guardian::step_guarded(&later, &store, key, None, &emitters(), &guards).await.unwrap(), 1); + assert_eq!(guardian::retry_deferred(&store, key, None, &emitters(), &guards).await.unwrap(), 0, "not yet"); + // After the delay (and, here, after the small ones have left the 3 s window) it signs. + std::thread::sleep(std::time::Duration::from_millis(4100)); + assert_eq!(guardian::retry_deferred(&store, key, None, &emitters(), &guards).await.unwrap(), 1); + assert!(is_signed(&store, 2, 0)); + assert!(limits::listed(&store, limits::DEFERRED).unwrap().is_empty()); +} + +#[tokio::test] +async fn a_delayed_transfer_that_then_meets_a_full_window_queues_like_any_other() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(dir.path()).unwrap(); + let l = Limits::new(&LimitsConfig { + per_transfer: 10 * UNIT, + per_window: 10 * UNIT, + window_secs: 6, + per_window_total: None, + delay_above: Some(5 * UNIT), + delay_secs: Some(1), + token: vec![], + }) + .unwrap(); + let key = &guardian_keys(1)[0]; + let guards = Guards { limits: Some(&l), ..Default::default() }; + let first = Batch { + polls: Default::default(), + located: vec![at_msg(lock_tok(0, 6, 0xa1), 10), at_msg(lock_tok(1, 5, 0xa1), 11)], + next: Cursor { next_block: 12, next_sequence: 2 }, + }; + // Lock 0 is delayed; lock 1 (5, not above the threshold) signs and takes half the window. + assert_eq!(guardian::step_guarded(&first, &store, key, None, &emitters(), &guards).await.unwrap(), 1); + std::thread::sleep(std::time::Duration::from_millis(1100)); + // Its delay has passed, but 5 + 6 is over the window: now it waits for room … + assert_eq!(guardian::retry_deferred(&store, key, None, &emitters(), &guards).await.unwrap(), 0); + let record: limits::Deferral = store.read_message(limits::DEFERRED, 2, 0).unwrap().unwrap(); + assert!(!record.delay, "the record says it waits for room now"); + // … and a later transfer of its token queues behind it. + let second = Batch { + polls: Default::default(), + located: vec![at_msg(lock_tok(2, 1, 0xa1), 13)], + next: Cursor { next_block: 14, next_sequence: 3 }, + }; + assert_eq!(guardian::step_guarded(&second, &store, key, None, &emitters(), &guards).await.unwrap(), 0); + assert_eq!(limits::listed(&store, limits::DEFERRED).unwrap(), vec![(2, 0), (2, 2)]); +} diff --git a/daemons/tests/stale_store.rs b/daemons/tests/stale_store.rs index 949b37a..1b0d279 100644 --- a/daemons/tests/stale_store.rs +++ b/daemons/tests/stale_store.rs @@ -192,6 +192,9 @@ async fn a_window_deferred_transfer_is_peer_checked_before_it_signs() { per_transfer: 10 * UNIT as u64, per_window: 10 * UNIT as u64, window_secs: 3, + per_window_total: None, + delay_above: None, + delay_secs: None, token: vec![], }) .unwrap(); diff --git a/docs/architecture.md b/docs/architecture.md index 34184aa..e87f1b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -79,6 +79,19 @@ that. Three independent bounds sit under the guardians on each source chain: can leave across midnight), on releases only. Locks are not capped: releases are the loss surface. +A fourth bound sits in each guardian, before it signs, and needs no contract change (BRG-1, +`daemons/README.md`, `[guardian.limits]`): a per-transfer cap (over it, the transfer is withheld +for an operator), a rolling per-token window (over it, deferred), and, when configured, a window +across all tokens (`per_window_total`) and a wait before a large transfer is signed +(`delay_above`, `delay_secs`). These are bounds on honest guardians only: a quorum that colludes +ignores them, and they are in force on a guardian only while its config has the section. +`rand-bridge-audit --limits` reads the chain-side bounds (each endpoint's release caps, Rand's +daily mint cap) and fails when an enabled backing has none. + +What the endpoints do not have, and cannot get without a new deployment because they are not +upgradeable: a delay between an accepted release and its payout, a cap on locks, and a cap across +tokens. The guardian-side delay and all-token window are the stand-ins until then. + On Rand there is no custody to bound. A mint appends one deposit note of the bridged asset to the shielded pool (the asset is `(home chain, token)`, carried in the note as a dense registry index); the bound is that a burn back to the home chain can only release what that chain's