From 5d90f37e32d10a76026ea21fd46e663ecad76903 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:43:12 +0800 Subject: [PATCH 1/2] BR-3: rand-bridge-audit --handover says which step of the governance handover each endpoint is at MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The handover tooling (Governance.s.sol, tron-ops.js, rand-bridge-cli) and the end-state audit (--governance) exist. Nothing said how far along an endpoint is: --governance fails every rule until the last step, and a scheduled acceptAdmin() whose delay has passed looks the same as one never started, while the single key is still admin. --handover reads admin(), pendingAdmin(), pauser(), their code, and the timelock's getTimestamp of the acceptAdmin() operation against the latest block time (Solana: the Config's admin and pending admin, the upgrade authority and the configured Squads vault), and prints one stage per endpoint with the next command of docs/governance.md §4. It exits non-zero until the admin has moved on every endpoint. It sends nothing and needs no key. The operation id is computed as the timelock's hashOperation; a test holds it to the id recorded for the live Tron endpoint. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YGaYNQ4cvFtg2UmokVgrAN --- daemons/src/bin/audit.rs | 156 +++++++++++++++++++++++ daemons/src/handover.rs | 259 ++++++++++++++++++++++++++++++++++++++ daemons/src/lib.rs | 1 + daemons/tests/handover.rs | 197 +++++++++++++++++++++++++++++ docs/governance.md | 39 ++++++ 5 files changed, 652 insertions(+) create mode 100644 daemons/src/handover.rs create mode 100644 daemons/tests/handover.rs diff --git a/daemons/src/bin/audit.rs b/daemons/src/bin/audit.rs index b764583..55a83a1 100644 --- a/daemons/src/bin/audit.rs +++ b/daemons/src/bin/audit.rs @@ -27,6 +27,7 @@ use std::path::PathBuf; use anyhow::{anyhow, bail, Context, Result}; use base64::Engine; use bridge_daemons::config::{address20, pubkey32, Config, EvmConfig, EvmKind, GovernanceConfig}; +use bridge_daemons::handover; use bridge_daemons::gov_audit::{self, EvmReads, Flavor, Rule, SafeReads, SolanaReads, Status}; use bridge_daemons::rpc::{hex_data, quantity, JsonRpc}; use bridge_daemons::sources::solana::find_program_address; @@ -46,6 +47,15 @@ struct Cli { /// multisig and upgrade authority on every endpoint. #[arg(long)] governance: bool, + /// Print where each endpoint stands in the governance handover (BR-3) + /// and the next step, instead of custody: admin, pendingAdmin, and the + /// timelock's `acceptAdmin()` operation. Read-only; exits non-zero until + /// the admin has moved on every endpoint. `--governance` judges the end state. + #[arg(long, conflicts_with = "governance")] + handover: bool, + /// The salt the `acceptAdmin()` operation was scheduled with (`--handover`). + #[arg(long, default_value = "0x0000000000000000000000000000000000000000000000000000000000000000")] + salt: String, } /// The approved backings: (bridge chain, symbol, token, decimals). @@ -640,6 +650,145 @@ async fn solana_governance( /// can change the endpoints, not who can move custody. const GOVERNANCE_CAVEAT: &str = "caveat: custody is still authorised by the guardian quorum, whose keys are not yet distributed (BR-4)"; +// ---- --handover -------------------------------------------------------------- + +async fn evm_handover(endpoint: &EvmConfig, salt: &[u8; 32]) -> Result<(handover::EvmHandover, String)> { + let url = match endpoint.kind { + EvmKind::Evm => endpoint.rpc.clone(), + EvmKind::Tron => format!("{}/jsonrpc", endpoint.rpc.trim_end_matches('/')), + }; + let rpc = JsonRpc::new(&url); + let bridge = address20(&endpoint.contract)?; + let read = |sig: &'static str| { + let rpc = rpc.clone(); + async move { + let w = eth_call(&rpc, &bridge, selector(sig).to_vec()).await.context(sig)?; + word_to_address(&w).ok_or_else(|| anyhow!("{sig}: not an address")) + } + }; + let admin = read("admin()").await?; + let pending_admin = read("pendingAdmin()").await?; + let pauser = read("pauser()").await?; + let admin_has_code = !eth_get_code(&rpc, &admin).await.context("eth_getCode(admin)")?.is_empty(); + let pending = pending_admin != [0u8; 20]; + let pending_has_code = + pending && !eth_get_code(&rpc, &pending_admin).await.context("eth_getCode(pendingAdmin)")?.is_empty(); + let id = handover::operation_id(&bridge, &handover::ACCEPT_ADMIN, salt); + let mut detail = String::new(); + let accept = if pending_has_code { + let mut call = selector("getTimestamp(bytes32)").to_vec(); + call.extend_from_slice(&id); + let ts = eth_call(&rpc, &pending_admin, call).await.ok().and_then(|w| word_u128(&w).ok()); + let block = rpc.call("eth_getBlockByNumber", json!(["latest", false])).await.context("the latest block")?; + let now = quantity(&block["timestamp"]).context("the latest block's timestamp")?; + let delay = try_call(&rpc, &pending_admin, "getMinDelay()").await.ok().and_then(|w| word_u128(&w).ok()); + detail = format!( + " acceptAdmin() operation 0x{} on pendingAdmin; chain time {now}; timelock delay {}\n", + hex::encode(id), + delay.map_or_else(|| "not answered".to_string(), |d| format!("{d} s")) + ); + ts.map(|t| handover::operation(t, now)) + } else { + None + }; + let show = |a: &[u8; 20]| match endpoint.kind { + EvmKind::Evm => format!("0x{}", hex::encode(a)), + EvmKind::Tron => gov_audit::tron_base58(a), + }; + let text = format!( + " admin {} ({})\n pendingAdmin {}\n pauser {}\n{detail}", + show(&admin), + if admin_has_code { "a contract" } else { "no code: a key or a native account" }, + if pending { show(&pending_admin) } else { "none".into() }, + show(&pauser), + ); + Ok((handover::EvmHandover { admin, admin_has_code, pending_admin, pending_has_code, accept }, text)) +} + +async fn solana_handover( + sol: &bridge_daemons::config::SolanaConfig, + policy: &GovernanceConfig, +) -> Result<(handover::SolanaHandover, String)> { + let rpc = JsonRpc::new(&sol.rpc); + let program = pubkey32(&sol.program)?; + let (config_key, _) = find_program_address(&[b"config"], &program)?; + let (owner, data) = solana_account_owned(&rpc, &config_key, Some(97)) + .await? + .ok_or_else(|| anyhow!("config PDA {} not found", bs58::encode(config_key).into_string()))?; + if owner != sol.program { + bail!("config PDA is owned by {owner}, not the bridge program"); + } + let keys = gov_audit::decode_bridge_config(&data)?; + let loader = gov_audit::BPF_LOADER_UPGRADEABLE; + let (owner, data) = solana_account_owned(&rpc, &program, Some(36)) + .await? + .ok_or_else(|| anyhow!("program account not found"))?; + let upgrade_authority = if owner != loader { + None + } else { + let programdata = gov_audit::decode_program_account(&data)?; + let (_, data) = solana_account_owned(&rpc, &programdata, Some(45)) + .await? + .ok_or_else(|| anyhow!("ProgramData account not found"))?; + gov_audit::decode_programdata_authority(&data)? + }; + let vault = policy + .solana_multisig + .as_deref() + .map(pubkey32) + .transpose()? + .map(|ms| gov_audit::squads_vault(&ms, policy.solana_vault_index)) + .transpose()?; + let b58 = |k: &[u8; 32]| bs58::encode(k).into_string(); + let text = format!( + " admin {}\n pending_admin {}\n upgrade authority {}\n configured vault {}\n", + b58(&keys.admin), + if keys.pending_admin == [0u8; 32] { "none".into() } else { b58(&keys.pending_admin) }, + upgrade_authority.as_ref().map_or_else(|| "none (not upgradeable)".into(), b58), + vault.as_ref().map_or_else(|| "(no [governance].solana_multisig)".into(), b58), + ); + Ok((handover::SolanaHandover { admin: keys.admin, pending_admin: keys.pending_admin, upgrade_authority, vault }, text)) +} + +/// The `--handover` report. `Ok(false)` until the admin has moved on every endpoint. +async fn handover_report(config: &Config, salt: &[u8; 32], out: &mut impl std::io::Write) -> Result { + let mut complete = true; + let mut section = |out: &mut dyn std::io::Write, title: String, r: Result<(handover::Stage, String, String)>| { + let _ = writeln!(out, "== {title} =="); + match r { + Ok((stage, reads, next)) => { + complete &= stage == handover::Stage::Complete; + let _ = write!(out, "{reads}"); + let _ = writeln!(out, " stage: {}\n {next}\n", stage.label()); + } + Err(e) => { + complete = false; + let _ = writeln!(out, " stage: UNKNOWN\n the endpoint could not be read: {e:#}\n"); + } + } + }; + for endpoint in &config.evm { + let tron = matches!(endpoint.kind, EvmKind::Tron); + let r = evm_handover(endpoint, salt).await.map(|(h, reads)| { + let (stage, next) = handover::evm_stage(&h, tron); + (stage, reads, next) + }); + section(out, format!("{} (chain {})", endpoint.name, endpoint.chain), r); + } + if let Some(sol) = &config.solana { + let r = solana_handover(sol, &config.governance_policy()).await.map(|(h, reads)| { + let (stage, next) = handover::solana_stage(&h); + (stage, reads, next) + }); + section(out, format!("{} (chain 5)", sol.name), r); + } + writeln!( + out, + "Read-only: nothing was signed or sent. ADMIN MOVED means the admin is no longer a single key here; whether what holds it is sound is `--governance`." + )?; + Ok(complete) +} + /// Writes the BR-4 caveat after a `--governance` run, however it ended (an /// early error included), and hands the verdict back unchanged. fn with_caveat(result: Result, out: &mut dyn std::io::Write) -> Result { @@ -736,6 +885,13 @@ async fn main() -> Result<()> { let result = governance(&config).await; return with_caveat(result, &mut std::io::stdout()); } + if cli.handover { + let salt = bridge_daemons::config::hex32(&cli.salt).context("--salt")?; + if !handover_report(&config, &salt, &mut std::io::stdout()).await? { + bail!("the governance handover is not complete on every endpoint (BR-3)"); + } + 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/handover.rs b/daemons/src/handover.rs new file mode 100644 index 0000000..3099cfd --- /dev/null +++ b/daemons/src/handover.rs @@ -0,0 +1,259 @@ +//! Where each endpoint stands in the governance handover (BR-3), and the +//! next step: `rand-bridge-audit --handover`. Read-only. +//! +//! The handover on Ethereum, BSC and Tron (`docs/governance.md` §4) moves the +//! bridge's admin from a key to a timelock in five steps: deploy the timelock, +//! set the pauser, `transferAdmin(timelock)` (the timelock becomes +//! `pendingAdmin`), then the admin multisig schedules `acceptAdmin()` on the +//! timelock and, after its delay, executes it. On Solana the admin moves to a +//! Squads vault in two steps and the upgrade authority follows. +//! +//! `rand-bridge-audit --governance` says whether the end state holds. This +//! says which step an endpoint is at while it does not. A stage of +//! [`Stage::Complete`] here is not a governance PASS: it means the admin +//! moved; the audit judges what it moved to. + +use sha3::{Digest, Keccak256}; + +/// `acceptAdmin()`. +pub const ACCEPT_ADMIN: [u8; 4] = [0x0e, 0x18, 0xb6, 0x81]; + +fn keccak(data: &[u8]) -> [u8; 32] { + Keccak256::digest(data).into() +} + +/// The timelock's id of `target.call(data)` with value 0 and no predecessor: +/// OZ `hashOperation` = `keccak256(abi.encode(target, 0, data, 0, salt))`. +pub fn operation_id(target: &[u8; 20], data: &[u8], salt: &[u8; 32]) -> [u8; 32] { + let mut enc = Vec::with_capacity(32 * 7 + data.len()); + enc.extend_from_slice(&[0u8; 12]); + enc.extend_from_slice(target); + enc.extend_from_slice(&[0u8; 32]); // value + let mut offset = [0u8; 32]; + offset[31] = 0xa0; // five head words + enc.extend_from_slice(&offset); + enc.extend_from_slice(&[0u8; 32]); // predecessor + enc.extend_from_slice(salt); + let mut len = [0u8; 32]; + len[24..].copy_from_slice(&(data.len() as u64).to_be_bytes()); + enc.extend_from_slice(&len); + enc.extend_from_slice(data); + enc.resize(enc.len() + (32 - data.len() % 32) % 32, 0); + keccak(&enc) +} + +/// A timelock operation, from `getTimestamp(id)` and the chain's clock. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Operation { + /// Never scheduled under this id, or cancelled. + Unset, + /// Scheduled; executable from `ready_at` (unix seconds). + Waiting { ready_at: u64 }, + /// Scheduled and executable since `ready_at`. + Ready { ready_at: u64 }, + /// Executed. + Done, +} + +/// OZ `TimelockController`: timestamp 0 is unset, 1 is done, anything else is +/// when the operation becomes ready. +pub fn operation(timestamp: u128, now: u64) -> Operation { + match timestamp { + 0 => Operation::Unset, + 1 => Operation::Done, + t if t > u128::from(now) => Operation::Waiting { ready_at: u64::try_from(t).unwrap_or(u64::MAX) }, + t => Operation::Ready { ready_at: t as u64 }, + } +} + +/// What was read from one EVM or Tron endpoint. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EvmHandover { + pub admin: [u8; 20], + pub admin_has_code: bool, + /// Zero when no transfer is under way. + pub pending_admin: [u8; 20], + pub pending_has_code: bool, + /// The `acceptAdmin()` operation on the pending admin, when that is a contract that + /// answered `getTimestamp`; `None` when it was not asked or did not answer. + pub accept: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + /// The admin is a key and no transfer is under way. + NotStarted, + /// `transferAdmin` ran: a contract is `pendingAdmin`; the accept is not scheduled. + Transferred, + /// The accept is scheduled and waiting out the delay. + Scheduled, + /// The accept is executable now. Until it is executed the old key is still admin. + Executable, + /// The admin is a contract and nothing is pending. + Complete, + /// A state the handover does not pass through; the text says what. + Unexpected, +} + +impl Stage { + pub fn label(self) -> &'static str { + match self { + Stage::NotStarted => "NOT STARTED", + Stage::Transferred => "TRANSFERRED, ACCEPT NOT SCHEDULED", + Stage::Scheduled => "ACCEPT SCHEDULED, WAITING", + Stage::Executable => "ACCEPT EXECUTABLE NOW", + Stage::Complete => "ADMIN MOVED", + Stage::Unexpected => "UNEXPECTED", + } + } +} + +/// The stage of an EVM or Tron endpoint, and what to do next. `tron`: which +/// commands the text names. +pub fn evm_stage(r: &EvmHandover, tron: bool) -> (Stage, String) { + let pending = r.pending_admin != [0u8; 20]; + let (schedule, execute) = if tron { + ( + "node deploy/tron-ops.js timelock-schedule-accept --from ", + "node deploy/tron-ops.js timelock-execute-accept --from ", + ) + } else { + ( + "the admin Safe signs deploy/governance/-schedule-accept.json (Governance.s.sol acceptProposal())", + "the admin Safe signs deploy/governance/-execute-accept.json", + ) + }; + match (r.admin_has_code, pending, r.pending_has_code, r.accept) { + (true, false, _, _) => ( + Stage::Complete, + "the admin is a contract and nothing is pending. Run --governance: it judges whether that \ + contract is the pinned timelock under a multisig." + .into(), + ), + (false, false, _, _) => ( + Stage::NotStarted, + "the admin is a single key. Next: docs/governance.md §4 steps 1-3 (deploy the timelock, set the \ + pauser, transferAdmin to the timelock)." + .into(), + ), + (_, true, false, _) => ( + Stage::Unexpected, + "pendingAdmin is an account without code, so a key could accept the admin role. Unless that is \ + intended, the current admin cancels with transferAdmin(0)." + .into(), + ), + (true, true, true, _) => ( + Stage::Unexpected, + "the admin is already a contract and a further transfer is pending. Check that it was announced." + .into(), + ), + (false, true, true, Some(Operation::Unset)) => ( + Stage::Transferred, + format!( + "the timelock is pendingAdmin; acceptAdmin() is not scheduled under this salt. The single key \ + is still admin. Next (step 4): {schedule}." + ), + ), + (false, true, true, Some(Operation::Waiting { ready_at })) => ( + Stage::Scheduled, + format!( + "acceptAdmin() is scheduled and executable from unix time {ready_at}. The single key is still \ + admin until then. Next (step 5), after that time: {execute}." + ), + ), + (false, true, true, Some(Operation::Ready { ready_at })) => ( + Stage::Executable, + format!( + "acceptAdmin() has been executable since unix time {ready_at} and has not been executed. The \ + single key is still admin. Next (step 5): {execute}." + ), + ), + (false, true, true, Some(Operation::Done)) => ( + Stage::Unexpected, + "the timelock reports acceptAdmin() executed, yet it is still only pendingAdmin: a second \ + transferAdmin followed the accept, or this is another salt's operation. Read the bridge's \ + AdminTransferStarted / AdminTransferred events." + .into(), + ), + (false, true, true, None) => ( + Stage::Unexpected, + "pendingAdmin is a contract that did not answer getTimestamp: it may not be a timelock. \ + handover() and transfer-admin refuse such a target; check how it got there." + .into(), + ), + } +} + +/// What was read from the Solana program. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SolanaHandover { + pub admin: [u8; 32], + /// The default key when no transfer is under way. + pub pending_admin: [u8; 32], + /// `None`: the program is not upgradeable. + pub upgrade_authority: Option<[u8; 32]>, + /// The Squads vault of `[governance].solana_multisig`, when configured. + pub vault: Option<[u8; 32]>, +} + +pub fn solana_stage(r: &SolanaHandover) -> (Stage, String) { + let Some(vault) = r.vault else { + return ( + Stage::NotStarted, + "no [governance].solana_multisig is configured, so there is no vault to hand over to. Create \ + the Squads v4 multisig (docs/governance.md §2) and set it." + .into(), + ); + }; + let pending = r.pending_admin != [0u8; 32]; + let authority_moved = r.upgrade_authority.is_none_or(|a| a == vault); + if r.admin == vault && !pending { + return if authority_moved { + ( + Stage::Complete, + "the admin and the upgrade authority are the Squads vault. Run --governance: it judges the \ + multisig's threshold, time lock and config authority." + .into(), + ) + } else { + ( + Stage::Transferred, + "the admin is the Squads vault; the upgrade authority is still another key, which can \ + replace the program. Next: rand-bridge-cli set-upgrade-authority (docs/governance.md §4, \ + Solana step 2; irreversible)." + .into(), + ) + }; + } + if r.admin != vault && authority_moved && r.upgrade_authority.is_some() { + return ( + Stage::Unexpected, + "the upgrade authority is the vault but the admin is not: set-upgrade-authority refuses that \ + order. Check how it got there." + .into(), + ); + } + if pending && r.pending_admin == vault { + return ( + Stage::Scheduled, + "transfer-admin ran: the vault is pending_admin and a single key is still admin. Next: the \ + Squads members approve and, after the time lock, execute the AcceptAdmin vault transaction \ + (rand-bridge-cli --as accept-admin prints it)." + .into(), + ); + } + if pending { + return ( + Stage::Unexpected, + "pending_admin is set to a key that is not the configured vault. Unless that is intended, the \ + admin starts the transfer again with the vault." + .into(), + ); + } + ( + Stage::NotStarted, + "the admin is a single key. Next: rand-bridge-cli transfer-admin --to \ + (docs/governance.md §4, Solana step 1)." + .into(), + ) +} diff --git a/daemons/src/lib.rs b/daemons/src/lib.rs index 0388b07..758be0f 100644 --- a/daemons/src/lib.rs +++ b/daemons/src/lib.rs @@ -14,6 +14,7 @@ pub mod crypto; pub mod gov_audit; pub mod governance; pub mod guardian; +pub mod handover; pub mod isolate; pub mod limits; pub mod message; diff --git a/daemons/tests/handover.rs b/daemons/tests/handover.rs new file mode 100644 index 0000000..7ce0361 --- /dev/null +++ b/daemons/tests/handover.rs @@ -0,0 +1,197 @@ +//! BR-3: `rand-bridge-audit --handover` says which step of the governance +//! handover each endpoint is at, from chain reads alone. + +mod common; + +use std::process::Command; + +use bridge_daemons::handover::{self, evm_stage, operation, operation_id, solana_stage, EvmHandover, Operation, SolanaHandover, Stage}; +use bridge_daemons::submit::selector; +use common::*; +use serde_json::{json, Value}; + +const BRIDGE: &str = "0x6410797df959987a5baf65b5fab97edeb34d5163"; + +fn a20(hex40: &str) -> [u8; 20] { + hex::decode(hex40.trim_start_matches("0x")).unwrap().try_into().unwrap() +} + +/// The id recorded in docs/mainnet-deployment.md for the Tron endpoint's acceptAdmin() +/// (bridge TK6JJ… = 0x6410797d…, salt 0), as the live timelock's hashOperation gave it. +#[test] +fn the_operation_id_is_the_timelocks_own() { + let id = operation_id(&a20(BRIDGE), &handover::ACCEPT_ADMIN, &[0u8; 32]); + assert_eq!(hex::encode(id), "816a8de4fcd4e876409596609f9021a4771b20f6c0ec745a885f6fa281672d88"); + assert_eq!(handover::ACCEPT_ADMIN, selector("acceptAdmin()")); + // Another salt is another operation. + assert_ne!(operation_id(&a20(BRIDGE), &handover::ACCEPT_ADMIN, &[1u8; 32]), id); +} + +#[test] +fn a_timelock_timestamp_reads_as_unset_done_waiting_or_ready() { + assert_eq!(operation(0, 100), Operation::Unset); + assert_eq!(operation(1, 100), Operation::Done); + assert_eq!(operation(101, 100), Operation::Waiting { ready_at: 101 }); + assert_eq!(operation(100, 100), Operation::Ready { ready_at: 100 }); + assert_eq!(operation(50, 100), Operation::Ready { ready_at: 50 }); +} + +fn evm(admin_code: bool, pending: bool, pending_code: bool, accept: Option) -> EvmHandover { + EvmHandover { + admin: [1; 20], + admin_has_code: admin_code, + pending_admin: if pending { [2; 20] } else { [0; 20] }, + pending_has_code: pending_code, + accept, + } +} + +#[test] +fn each_step_of_the_evm_handover_is_told_apart() { + let stage = |r: EvmHandover| evm_stage(&r, false); + assert_eq!(stage(evm(false, false, false, None)).0, Stage::NotStarted); + assert_eq!(stage(evm(false, true, true, Some(Operation::Unset))).0, Stage::Transferred); + let (s, next) = stage(evm(false, true, true, Some(Operation::Waiting { ready_at: 1_759_465_440 }))); + assert_eq!(s, Stage::Scheduled); + assert!(next.contains("1759465440") && next.contains("still admin"), "{next}"); + let (s, next) = stage(evm(false, true, true, Some(Operation::Ready { ready_at: 5 }))); + assert_eq!(s, Stage::Executable); + assert!(next.contains("execute-accept.json") && next.contains("single key is still admin"), "{next}"); + assert_eq!(stage(evm(true, false, false, None)).0, Stage::Complete); + // States the handover never passes through are not called progress. + for odd in [ + evm(false, true, false, None), // a key is pending admin + evm(false, true, true, None), // a contract that is no timelock + evm(false, true, true, Some(Operation::Done)), // "done" but still pending + evm(true, true, true, Some(Operation::Unset)), // a further transfer + ] { + assert_eq!(stage(odd.clone()).0, Stage::Unexpected, "{odd:?}"); + } + // Tron names its own commands. + let (_, next) = evm_stage(&evm(false, true, true, Some(Operation::Ready { ready_at: 5 })), true); + assert!(next.contains("tron-ops.js timelock-execute-accept"), "{next}"); +} + +#[test] +fn each_step_of_the_solana_handover_is_told_apart() { + let (key, vault, other) = ([1u8; 32], [2u8; 32], [3u8; 32]); + let s = |admin, pending, authority: Option<[u8; 32]>, v: Option<[u8; 32]>| { + solana_stage(&SolanaHandover { admin, pending_admin: pending, upgrade_authority: authority, vault: v }).0 + }; + assert_eq!(s(key, [0; 32], Some(other), None), Stage::NotStarted, "no multisig configured"); + assert_eq!(s(key, [0; 32], Some(other), Some(vault)), Stage::NotStarted); + assert_eq!(s(key, vault, Some(other), Some(vault)), Stage::Scheduled); + assert_eq!(s(key, other, Some(other), Some(vault)), Stage::Unexpected, "pending is not the vault"); + assert_eq!(s(vault, [0; 32], Some(other), Some(vault)), Stage::Transferred, "the authority is last"); + assert_eq!(s(vault, [0; 32], Some(vault), Some(vault)), Stage::Complete); + assert_eq!(s(vault, [0; 32], None, Some(vault)), Stage::Complete, "not upgradeable"); + assert_eq!(s(key, [0; 32], Some(vault), Some(vault)), Stage::Unexpected, "authority before admin"); +} + +// ---- the binary against a loopback node ----------------------------------------- + +const KEY: &str = "e49bd2571a549e8797be649229f62891fe300d0e"; +const TIMELOCK: &str = "6b81056c29c2f131f823f04107747b47d4f22fea"; + +fn word20(hex40: &str) -> Value { + json!(format!("0x{}{hex40}", "00".repeat(12))) +} + +/// A bridge whose admin is `admin`, with `pending` as pendingAdmin; `TIMELOCK` has code and +/// answers getTimestamp with `timestamp`. The chain's clock reads 1_000. +fn node(admin: &'static str, pending: Option<&'static str>, timestamp: u128) -> Fake { + let id = hex::encode(operation_id(&a20(BRIDGE), &handover::ACCEPT_ADMIN, &[0u8; 32])); + rpc(move |m, p| match m { + "eth_call" => { + let data = p[0]["data"].as_str().unwrap().trim_start_matches("0x").to_string(); + let sel = |s: &str| data.starts_with(&hex::encode(selector(s))); + Some(Ok(if sel("admin()") { + word20(admin) + } else if sel("pendingAdmin()") { + word20(pending.unwrap_or(&"0".repeat(40))) + } else if sel("pauser()") { + word20(&"9".repeat(40)) + } else if sel("getTimestamp(bytes32)") { + assert!(data.ends_with(&id), "asked for another operation: {data}"); + json!(format!("0x{timestamp:064x}")) + } else if sel("getMinDelay()") { + json!(format!("0x{:064x}", 172_800)) + } else { + return Some(Err(json!({ "code": 3, "message": "reverted" }))); + })) + } + "eth_getCode" => { + let who = p[0].as_str().unwrap().trim_start_matches("0x").to_lowercase(); + Some(Ok(json!(if who == TIMELOCK { "0x6080" } else { "0x" }))) + } + "eth_getBlockByNumber" => Some(Ok(json!({ "timestamp": "0x3e8" }))), + _ => None, + }) +} + +fn run(node: &Fake, kind: &str, extra: &[&str]) -> (bool, String, String) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + format!( + "data_dir = {:?}\n[rand]\nrpc = \"http://127.0.0.1:1\"\nemitter = {:?}\n[[evm]]\nname = \"endpoint\"\nchain = {}\nkind = {kind:?}\nrpc = {:?}\ncontract = {BRIDGE:?}\nfinality = 0\n", + dir.path().join("data"), + hex::encode(RAND_EMITTER), + if kind == "tron" { 4 } else { 2 }, + node.url + ), + ) + .unwrap(); + let o = Command::new(env!("CARGO_BIN_EXE_rand-bridge-audit")) + .env_remove("RAND_BRIDGE_CONFIG") + .arg("--config") + .arg(&path) + .arg("--handover") + .args(extra) + .output() + .unwrap(); + (o.status.success(), String::from_utf8_lossy(&o.stdout).into(), String::from_utf8_lossy(&o.stderr).into()) +} + +#[test] +fn the_report_walks_the_handover_and_fails_until_the_admin_has_moved() { + for (n, stage) in [ + (node(KEY, None, 0), "stage: NOT STARTED"), + (node(KEY, Some(TIMELOCK), 0), "stage: TRANSFERRED, ACCEPT NOT SCHEDULED"), + (node(KEY, Some(TIMELOCK), 2_000), "stage: ACCEPT SCHEDULED, WAITING"), + (node(KEY, Some(TIMELOCK), 900), "stage: ACCEPT EXECUTABLE NOW"), + (node(KEY, Some(KEY), 0), "stage: UNEXPECTED"), + ] { + let (ok, out, err) = run(&n, "evm", &[]); + assert!(!ok && err.contains("BR-3"), "{stage}: {out}\n{err}"); + assert!(out.contains(stage), "{stage}: {out}"); + assert!(out.contains("nothing was signed or sent"), "{out}"); + // Reads only. + for m in n.rpc_methods() { + assert!(["eth_call", "eth_getCode", "eth_getBlockByNumber"].contains(&m.as_str()), "{m}"); + } + } + let (ok, out, err) = run(&node(TIMELOCK, None, 1), "evm", &[]); + assert!(ok, "{out}\n{err}"); + assert!(out.contains("stage: ADMIN MOVED") && out.contains("--governance"), "{out}"); +} + +#[test] +fn a_tron_endpoint_is_shown_in_tron_form_and_the_salt_selects_the_operation() { + let n = node(KEY, Some(TIMELOCK), 900); + let (_, out, _) = run(&n, "tron", &[]); + assert!(out.contains("TKmds8i5UPQDaV3YghCVJUMomHeQzJzV7k"), "pendingAdmin as T…: {out}"); + assert!(out.contains("0x816a8de4fcd4e876409596609f9021a4771b20f6c0ec745a885f6fa281672d88"), "{out}"); + assert!(out.contains("tron-ops.js timelock-execute-accept") && out.contains("delay 172800 s"), "{out}"); + assert!(n.requests().iter().all(|r| r.path.ends_with("/jsonrpc")), "Tron is read through /jsonrpc"); + // A malformed salt is refused before anything is read. + let (ok, _, err) = run(&n, "tron", &["--salt", "0x12"]); + assert!(!ok && err.contains("--salt"), "{err}"); +} + +#[test] +fn an_endpoint_that_cannot_be_read_is_unknown() { + let (ok, out, _) = run(&rpc(|_, _| None), "evm", &[]); + assert!(!ok && out.contains("stage: UNKNOWN"), "{out}"); +} diff --git a/docs/governance.md b/docs/governance.md index a03187c..bc6f9f9 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -189,6 +189,45 @@ correct reading of the current state. The role check reads `RoleGranted`/`RoleRe timelock's deployment block, so on BSC it needs an RPC that serves logs that old (a keyed one); a deploy block after the real one fails the "role history starts at the timelock constructor" rule. +## 5a. Where the handover stands: `--handover` + +`--governance` fails on every rule until a chain is finished, which does not say how far along it +is. For that: + +```bash +rand-bridge-audit --config daemons/mainnet/relayer.toml --handover # [--salt 0x<32 bytes>] +``` + +It reads, per endpoint, `admin()`, `pendingAdmin()`, `pauser()`, whether each has code, and on the +pending admin the timelock's `getTimestamp` of the `acceptAdmin()` operation (id computed as the +timelock's `hashOperation(bridge, 0, acceptAdmin(), 0, salt)`) against the chain's latest block +time; on Solana the bridge `Config`'s admin and pending admin, the program's upgrade authority and +the configured Squads vault. It prints one stage per endpoint and the next command of §4: + +| stage | meaning | who is admin now | +|---|---|---| +| `NOT STARTED` | no transfer under way | the single key | +| `TRANSFERRED, ACCEPT NOT SCHEDULED` | the timelock is `pendingAdmin`; step 4 not done under this salt (Solana: the admin is the vault, the upgrade authority is not) | the single key (Solana: the vault) | +| `ACCEPT SCHEDULED, WAITING` | step 4 done; prints the unix time it becomes executable (Solana: the vault is `pending_admin`) | the single key | +| `ACCEPT EXECUTABLE NOW` | the delay has passed and step 5 has not run | **the single key, until step 5** | +| `ADMIN MOVED` | the admin is a contract (Solana: the vault, with the upgrade authority) and nothing is pending | not a single key | +| `UNEXPECTED` | a state the handover does not pass through; the text says which | read the text | +| `UNKNOWN` | the endpoint could not be read | | + +It sends nothing and needs no key. It exits non-zero until every endpoint is at `ADMIN MOVED`, so +it can sit in a daily job next to `--governance`. `ADMIN MOVED` is not a governance PASS: it says +the admin left the single key, and `--governance` judges what holds it now. + +**Order of work, per chain, each step checked before the next:** + +1. `--handover` → `NOT STARTED`. Do §4 steps 1–3. `--handover` → `TRANSFERRED`. +2. The admin multisig signs the schedule. `--handover` → `ACCEPT SCHEDULED`, with the time. +3. After that time `--handover` → `ACCEPT EXECUTABLE NOW`. The multisig signs the execute. Do not + leave an endpoint in this stage: the delay has been served and the single key still rules. +4. `--handover` → `ADMIN MOVED`; then that chain's section of `--governance` must be all PASS. +5. Record the transaction ids and both outputs in `docs/mainnet-deployment.md`, and only then + retire the old admin key. + ## 6. After the handover: operating through the delay Every admin action now takes a proposal, 48 h, and an execution: From c37f033010e26bd3a76d037676c432a39382e1ba Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:03:31 +0800 Subject: [PATCH 2/2] BR-3: an admin multisig is 5 signers of 6, and the governance audit reports any other shape The owner's standing rule: a multisig account is 5 of 6, never 2 of 3. The audit accepted any admin multisig with a threshold of at least min_threshold (2), so 2 of 3 and 3 of 5 passed every row. rand-bridge-audit --governance gains a last row on every endpoint, "admin multisig is 5 of 6 (owner's rule)": PASS only for a Safe with threshold 5 and 6 owners, a Tron account whose owner and every active permission need 5 signatures of 6 keys, or a Squads multisig with threshold 5 and 6 members. Any other shape it can read is a FAIL that prints the shape; signers it cannot read are UNKNOWN; no multisig configured is a FAIL. The row is not configurable. The pause multisig and the 6-of-8 guardian quorum are not touched. tron-ops.js multisig-permissions defaults both thresholds to 5, and docs/governance.md names 5 of 6 with six signers wherever it named 3 of 5 for the admin multisig. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YGaYNQ4cvFtg2UmokVgrAN --- daemons/config.example.toml | 2 + daemons/src/bin/audit.rs | 13 ++- daemons/src/gov_audit.rs | 190 +++++++++++++++++++++++++++++++++++- deploy/tron-ops.js | 6 +- docs/governance.md | 25 +++-- 5 files changed, 221 insertions(+), 15 deletions(-) diff --git a/daemons/config.example.toml b/daemons/config.example.toml index d5af3c9..0053bac 100644 --- a/daemons/config.example.toml +++ b/daemons/config.example.toml @@ -150,6 +150,8 @@ listen = "127.0.0.1:7080" # POST /v1/recipients {recipient_hash, addr # [governance] # min_delay_secs = 172800 # 48 h # min_threshold = 2 +# Not configurable: the admin multisig on every chain must be 5 signers of 6 (the owner's rule). +# The last row of each endpoint reports any other shape as FAIL. # timelock_deploy_block = { 2 = 0, 3 = 0, 4 = 0 } # per bridge chain: where the role logs start # admin_multisig = { 2 = "0x…", 3 = "0x…", 4 = "T…" } # per bridge chain: the timelock's only proposer/executor/canceller # solana_multisig = "" diff --git a/daemons/src/bin/audit.rs b/daemons/src/bin/audit.rs index 55a83a1..dbccfc3 100644 --- a/daemons/src/bin/audit.rs +++ b/daemons/src/bin/audit.rs @@ -346,6 +346,11 @@ async fn safe_reads(rpc: &JsonRpc, safe: &[u8; 20]) -> SafeReads { /// Tron `wallet/getaccount`: how many signatures the account needs, or /// `None` when the API is not served (or the account does not exist). async fn tron_signers(api: &str, address: &[u8; 20]) -> Option { + gov_audit::tron_min_signers(&tron_account(api, address).await?) +} + +/// `wallet/getaccount` for `address`, or `None` when the API does not serve it. +async fn tron_account(api: &str, address: &[u8; 20]) -> Option { let http = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(30)) .build() @@ -361,7 +366,7 @@ async fn tron_signers(api: &str, address: &[u8; 20]) -> Option { .json() .await .ok()?; - gov_audit::tron_min_signers(&account) + Some(account) } /// `[from, to]` in inclusive chunks of at most `max` blocks. @@ -503,6 +508,7 @@ async fn evm_governance(endpoint: &EvmConfig, policy: &GovernanceConfig) -> Resu SafeReads::not_asked("no admin multisig configured"), None, ); + let mut tron_admin_multisig_shapes = None; if let Some(ms) = &admin_multisig { admin_multisig_code = eth_get_code(&rpc, ms) .await @@ -515,7 +521,9 @@ async fn evm_governance(endpoint: &EvmConfig, policy: &GovernanceConfig) -> Resu Flavor::Tron => { admin_multisig_safe = SafeReads::not_asked("not asked on Tron"); if admin_multisig_code.is_empty() { - tron_admin_multisig_signers = tron_signers(&endpoint.rpc, ms).await; + let account = tron_account(&endpoint.rpc, ms).await; + tron_admin_multisig_signers = account.as_ref().and_then(gov_audit::tron_min_signers); + tron_admin_multisig_shapes = account.as_ref().and_then(gov_audit::tron_permission_shapes); } } } @@ -541,6 +549,7 @@ async fn evm_governance(endpoint: &EvmConfig, policy: &GovernanceConfig) -> Resu admin_multisig_code, admin_multisig_safe, tron_admin_multisig_signers, + tron_admin_multisig_shapes, pauser, pauser_code, pauser_safe, diff --git a/daemons/src/gov_audit.rs b/daemons/src/gov_audit.rs index 20d9de8..86c864d 100644 --- a/daemons/src/gov_audit.rs +++ b/daemons/src/gov_audit.rs @@ -616,6 +616,9 @@ pub struct EvmReads { pub admin_multisig_safe: SafeReads, /// Tron: signatures the admin multisig account needs; `None` unknown. pub tron_admin_multisig_signers: Option, + /// Tron: the admin multisig account's permissions as `(signatures needed, keys)` + /// ([`tron_permission_shapes`]); `None` unknown. + pub tron_admin_multisig_shapes: Option>, pub pauser: Vec, pub pauser_code: Vec, /// The pauser's Safe reads (EVM only). @@ -1117,9 +1120,94 @@ pub fn evm_rules(reads: &EvmReads, flavor: Flavor, policy: &GovernanceConfig) -> ), None => rule("no pendingAdmin", false, "pendingAdmin(): unreadable"), }); + + // 15. The admin multisig is 5 of 6 (the owner's rule), reported whatever it is. + rules.push(match (ms, flavor) { + (None, _) => rule( + admin_shape_rule_name(), + false, + "no [governance].admin_multisig configured for this chain", + ), + (Some(ms), Flavor::Evm) => { + let safe = &reads.admin_multisig_safe; + let shape = safe + .threshold + .as_ref() + .ok() + .and_then(|w| word_uint(w)) + .zip(safe.owners.as_ref().ok().and_then(|r| decode_owners(r))) + .map(|(t, owners)| vec![(u32::try_from(t).unwrap_or(u32::MAX), owners.len() as u32)]); + admin_shape_rule(shape, &format!("admin multisig {}", show(&ms, flavor))) + } + (Some(ms), Flavor::Tron) => admin_shape_rule( + reads.tron_admin_multisig_shapes.clone(), + &format!("admin multisig {} (owner, then active permissions)", show(&ms, flavor)), + ), + }); rules } +/// The owner's standing rule for an admin (governance) multisig: 5 signers of 6. A multisig +/// of any other shape is reported as a FAIL by the last rule of each endpoint, never passed +/// in silence. This is not the guardian quorum, which is 6 of 8 and is not judged here. +pub const ADMIN_MULTISIG_SIGNERS: u32 = 5; +pub const ADMIN_MULTISIG_OF: u32 = 6; + +/// The name of that rule. +pub fn admin_shape_rule_name() -> String { + format!("admin multisig is {ADMIN_MULTISIG_SIGNERS} of {ADMIN_MULTISIG_OF} (owner's rule)") +} + +fn admin_shape_rule(observed: Option>, what: &str) -> Rule { + let name = admin_shape_rule_name(); + match observed { + None => Rule { name, status: Status::Unknown, observed: format!("{what}: its signers could not be read") }, + Some(shapes) => { + let shown: Vec = shapes.iter().map(|(t, n)| format!("{t} of {n}")).collect(); + rule( + name, + !shapes.is_empty() && shapes.iter().all(|s| *s == (ADMIN_MULTISIG_SIGNERS, ADMIN_MULTISIG_OF)), + format!("{what}: {}", shown.join(", ")), + ) + } + } +} + +/// Each permission of a Tron account (owner, then every active one) as `(fewest signatures +/// that satisfy it, number of keys)`, from `wallet/getaccount`. `None` under the same +/// conditions as [`tron_min_signers`]. An account without permissions is its own key: `(1, 1)`. +pub fn tron_permission_shapes(account: &serde_json::Value) -> Option> { + let obj = account.as_object()?; + obj.get("address")?.as_str()?; + let mut permissions: Vec<&serde_json::Value> = Vec::new(); + if let Some(owner) = obj.get("owner_permission") { + permissions.push(owner); + } + if let Some(active) = obj.get("active_permission") { + permissions.extend(active.as_array()?.iter()); + } + if permissions.is_empty() { + return Some(vec![(1, 1)]); + } + permissions + .into_iter() + .map(|p| { + let threshold = p.get("threshold")?.as_u64()?; + let mut weights = + p.get("keys")?.as_array()?.iter().map(|k| k.get("weight")?.as_u64()).collect::>>()?; + weights.sort_unstable_by(|a, b| b.cmp(a)); + let mut sum = 0u64; + for (i, w) in weights.iter().enumerate() { + sum = sum.saturating_add(*w); + if sum >= threshold { + return Some((i as u32 + 1, weights.len() as u32)); + } + } + None + }) + .collect() +} + /// With `--governance` every bridge chain must be audited: a FAIL row for /// each of 2, 3, 4 (`[[evm]]`) and 5 (`[solana]`) that is not configured. pub fn endpoint_coverage(evm_chains: &[u16], solana: bool) -> Vec { @@ -1282,6 +1370,13 @@ pub fn solana_rules(reads: &SolanaReads, policy: &GovernanceConfig) -> Vec format!("pauser == admin == {}", b58(admin)), ) }); + rules.push(match &reads.multisig_state { + Ok(ms) => admin_shape_rule( + Some(vec![(u32::from(ms.threshold), ms.members.len() as u32)]), + "Squads multisig (threshold of members)", + ), + Err(e) => rule(admin_shape_rule_name(), false, e.clone()), + }); rules } @@ -1560,6 +1655,7 @@ mod tests { admin_multisig_code: vec![], admin_multisig_safe: SafeReads::not_asked("no admin multisig configured"), tron_admin_multisig_signers: None, + tron_admin_multisig_shapes: None, pauser: word(&EOA), pauser_code: vec![], pauser_safe: SafeReads::not_asked("no code"), @@ -1577,8 +1673,9 @@ mod tests { roles: Ok(constructor_events()), admin_multisig: Some(ADMIN_SAFE), admin_multisig_code: proxy_130(), - admin_multisig_safe: safe(SAFE_130_L2, 3, 5, 0), + admin_multisig_safe: safe(SAFE_130_L2, 5, 6, 0), tron_admin_multisig_signers: None, + tron_admin_multisig_shapes: None, pauser: word(&SAFE), pauser_code: proxy_141(), pauser_safe: safe(SAFE_141, 2, 5, 0), @@ -1587,7 +1684,8 @@ mod tests { } } - const N_EVM: usize = 14; + const N_EVM: usize = 15; + const ADMIN_SHAPE: usize = N_EVM - 1; // Row indices. const NO_PROXY: usize = 1; const CODE_HASH: usize = 2; @@ -1740,6 +1838,11 @@ mod tests { fn only_fails(reads: &EvmReads, flavor: Flavor, index: usize) -> Vec { let rules = evm_rules(reads, flavor, &policy()); for (i, r) in rules.iter().enumerate() { + // The 5-of-6 row reports the same multisig the row under test may have broken; + // it has tests of its own below. + if i == ADMIN_SHAPE && index != ADMIN_SHAPE { + continue; + } let want_ok = i != index; assert_eq!( r.status != Status::Fail && r.status != Status::Unknown, @@ -1992,7 +2095,7 @@ mod tests { SAFE_141_L2, ] { let mut r = compliant_reads(); - r.admin_multisig_safe = safe(singleton, 2, 2, 0); + r.admin_multisig_safe = safe(singleton, 5, 6, 0); r.pauser_safe = safe(singleton, 2, 3, 0); assert_eq!(failures(&evm_rules(&r, Flavor::Evm, &policy())), 0); } @@ -2184,7 +2287,9 @@ mod tests { r.admin_code = tron_timelock_code(); r.admin_multisig_code.clear(); r.admin_multisig_safe = SafeReads::not_asked("not asked on Tron"); - r.tron_admin_multisig_signers = Some(3); + r.tron_admin_multisig_signers = Some(5); + // Owner and active permission, each 5 of 6 (the owner's rule). + r.tron_admin_multisig_shapes = Some(vec![(5, 6), (5, 6)]); r.pauser_safe = SafeReads::not_asked("not asked on Tron"); // The pause account: no code, owner 3 of 5 and active 2 of 5 need two signatures. r.pauser_code.clear(); @@ -2367,6 +2472,13 @@ mod tests { let mut ms = decode_squads_multisig(&b64(MS_5QPR)).unwrap(); ms.time_lock = 172_800; assert_eq!(ms.config_authority, [0u8; 32], "the fixture is autonomous"); + // The owner's rule: 5 of 6. + while ms.members.len() < 6 { + let m = ms.members[0].clone(); + ms.members.push(m); + } + ms.members.truncate(6); + ms.threshold = 5; SolanaReads { config: BridgeConfigKeys { admin: vault, @@ -2382,7 +2494,8 @@ mod tests { fn sol_fails(r: &SolanaReads) -> Vec { let rules = solana_rules(r, &policy()); - assert_eq!(rules.len(), N_SOL); + // The 5-of-6 row is the last one and has a test of its own. + assert_eq!(rules.len(), N_SOL + 1); (0..N_SOL) .filter(|i| rules[*i].status != Status::Pass) .collect() @@ -2447,4 +2560,71 @@ mod tests { r.config.pending_admin = pk("DvV45t4mfWKJvUXvFLoEuYgRqzmL1m6DaHbn8ZLw77kX"); assert_eq!(sol_fails(&r), vec![SOL_PENDING]); } + + // ---- the owner's rule: an admin multisig is 5 of 6 ------------------------- + + #[test] + fn an_admin_safe_that_is_not_5_of_6_is_reported_not_passed() { + let ok = evm_rules(&compliant_reads(), Flavor::Evm, &policy()); + assert_eq!(ok[ADMIN_SHAPE].name, "admin multisig is 5 of 6 (owner's rule)"); + assert_eq!(ok[ADMIN_SHAPE].status, Status::Pass); + assert!(ok[ADMIN_SHAPE].observed.contains("5 of 6"), "{:?}", ok[ADMIN_SHAPE]); + // Shapes every other rule accepts. + for (t, n) in [(2, 3), (3, 5), (5, 7), (6, 6), (4, 6)] { + let mut r = compliant_reads(); + r.admin_multisig_safe = safe(SAFE_130_L2, t, n, 0); + let rules = evm_rules(&r, Flavor::Evm, &policy()); + assert_eq!(rules[ADMIN_SHAPE].status, Status::Fail, "{t} of {n}"); + assert!(rules[ADMIN_SHAPE].observed.contains(&format!("{t} of {n}")), "{:?}", rules[ADMIN_SHAPE]); + assert_eq!(failures(&rules), 1, "{t} of {n}: only this row: {rules:#?}"); + } + // Unreadable is UNKNOWN, which also counts against the audit; none configured is a FAIL. + let mut r = compliant_reads(); + r.admin_multisig_safe.threshold = Err("execution reverted".into()); + assert_eq!(evm_rules(&r, Flavor::Evm, &policy())[ADMIN_SHAPE].status, Status::Unknown); + assert_eq!(evm_rules(&eoa_reads(), Flavor::Evm, &policy())[ADMIN_SHAPE].status, Status::Fail); + // The pause multisig is not held to it: 2 of 5 there still passes every row. + assert_eq!(failures(&ok), 0); + } + + #[test] + fn a_tron_admin_account_must_be_5_of_6_on_every_permission() { + let shape = |shapes: Option>| { + let mut r = tron_compliant(); + r.tron_admin_multisig_shapes = shapes; + evm_rules(&r, Flavor::Tron, &policy())[ADMIN_SHAPE].clone() + }; + assert_eq!(shape(Some(vec![(5, 6), (5, 6)])).status, Status::Pass); + let r = shape(Some(vec![(3, 5), (3, 5)])); + assert_eq!(r.status, Status::Fail); + assert!(r.observed.contains("3 of 5, 3 of 5"), "{r:?}"); + assert_eq!(shape(Some(vec![(5, 6), (2, 6)])).status, Status::Fail, "a weaker active permission"); + assert_eq!(shape(None).status, Status::Unknown); + + let account: serde_json::Value = serde_json::from_str( + r#"{"address":"41aa", + "owner_permission": {"threshold": 5,"keys": [{"address":"41a1","weight": 1},{"address":"41a2","weight": 1},{"address":"41a3","weight": 1},{"address":"41a4","weight": 1},{"address":"41a5","weight": 1},{"address":"41a6","weight": 1}]}, + "active_permission": [{"threshold": 3,"keys": [{"address":"41a1","weight": 2},{"address":"41a2","weight": 1},{"address":"41a3","weight": 1}]}]}"#, + ) + .unwrap(); + // The active permission: weights 2+1 reach 3 with two signatures, of three keys. + assert_eq!(tron_permission_shapes(&account), Some(vec![(5, 6), (2, 3)])); + assert_eq!(tron_permission_shapes(&serde_json::json!({"address": "41aa"})), Some(vec![(1, 1)])); + assert_eq!(tron_permission_shapes(&serde_json::json!({})), None); + } + + #[test] + fn a_squads_multisig_that_is_not_5_of_6_is_reported_not_passed() { + let last = |r: &SolanaReads| solana_rules(r, &policy()).last().unwrap().clone(); + let ok = last(&compliant_solana()); + assert_eq!((ok.name.as_str(), ok.status), ("admin multisig is 5 of 6 (owner's rule)", Status::Pass)); + let mut r = compliant_solana(); + r.multisig_state.as_mut().unwrap().threshold = 2; + r.multisig_state.as_mut().unwrap().members.truncate(3); + let row = last(&r); + assert_eq!(row.status, Status::Fail); + assert!(row.observed.contains("2 of 3"), "{row:?}"); + assert_eq!(sol_fails(&r), Vec::::new(), "2 of 3 passes every older rule"); + assert_eq!(last(&today_solana()).status, Status::Fail); + } } diff --git a/deploy/tron-ops.js b/deploy/tron-ops.js index b11d453..15f778e 100644 --- a/deploy/tron-ops.js +++ b/deploy/tron-ops.js @@ -24,7 +24,9 @@ // node deploy/tron-ops.js timelock-execute --from --call ... [--args ...] // making the multi-signature accounts themselves (unsigned, for the account's current key): // node deploy/tron-ops.js multisig-permissions --signers T1,T2,... \ -// [--owner-threshold 3] [--active-threshold 3] +// [--owner-threshold 5] [--active-threshold 5] +// (an admin multisig is 5 signers of 6, the owner's rule: give six --signers; the audit +// reports any other shape) // (the multisig commands also take [--bridge T...] [--salt 0x<32 bytes>] [--permission-id 2] // [--expire-hours 23] [--out-dir deploy/governance]; execute refuses unless the operation is // pending, and prints whether it is ready and from when) @@ -419,7 +421,7 @@ async function governance(tronWeb, command, argv, key) { const account = requireAddress(tronWeb, 'account', args[0]); const signers = String(flags.signers || '').split(',').filter(Boolean); const { owner, actives } = multisigPermissions(tronWeb, account, signers, - Number(flags['owner-threshold'] || 3), Number(flags['active-threshold'] || 3)); + Number(flags['owner-threshold'] || 5), Number(flags['active-threshold'] || 5)); const m = multisigFlags(flags); const acct = await tronWeb.trx.getAccount(account); if (!acct || !acct.address) throw new Error(`${account} is not activated: send it TRX first (>= 101 TRX)`); diff --git a/docs/governance.md b/docs/governance.md index bc6f9f9..42764cc 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -12,6 +12,9 @@ contracts; Solana upgrade authority". Design and rationale: > nothing in this repository settles it. Until someone reads `wallet/getaccount` for the two > accounts on Tron mainnet (or runs `rand-bridge-audit --governance`, whose Tron rules 10 and 13 > read exactly that) and corrects whichever document is wrong, treat neither statement as fact. +> Either way, 3 of 5 on the admin account is not the 5 of 6 the owner's rule now asks (§1): if +> that is what the chain has, the audit's last Tron row fails until the account's permissions +> are updated (`multisig-permissions`, signed under its current owner permission). **Tron steps 0–3 ran on mainnet on 2026-09-26** (timelock `TKmds8i5UPQDaV3YghCVJUMomHeQzJzV7k`, pauser and pending admin set; `docs/mainnet-deployment.md`); the multi-signature account permissions and the accept are still to do. **No other on-chain step below has been run.** They move control of live custody and are irreversible once a timelock or multisig accepts. Run them in the order given, one chain at a time, @@ -41,28 +44,38 @@ Rules the audit enforces (`rand-bridge-audit --governance`, §5): threshold; on Tron a multi-signature account — and the pauser is neither the admin nor the admin multisig; - on Solana the admin and the upgrade authority are the vault of a Squads multisig with no - `config_authority`, a threshold of at least 2 and a time lock of at least 48 h. + `config_authority`, a threshold of at least 2 and a time lock of at least 48 h; +- the admin multisig is 5 signers of 6 (the last row of every endpoint; a FAIL for any other + shape, UNKNOWN when unreadable). A PASS on every rule means **no single key can change an endpoint's configuration or code**. It does not mean no single party controls the funds: releases from custody are authorised by the guardian quorum, whose keys are not yet distributed (BR-4, §8). The audit prints that caveat on every run. -Recommended thresholds: admin 3 of 5, pause 2 of 5, **each signer a different person on a +**The admin multisig is 5 signers of 6** on every chain (the admin Safe, the Tron admin account on +both its owner and its active permission, the Squads multisig). This is the owner's standing rule, +not a recommendation, and the audit holds it: the last row of each endpoint, `admin multisig is 5 +of 6 (owner's rule)`, is a FAIL for any other shape it can read (3 of 5 and 2 of 3 included) and +UNKNOWN when it cannot read the signers, so nothing else passes in silence. It is separate from +the guardian quorum, which stays 6 of 8. The pause multisig is not held to it by the audit; this +page still suggests 2 of 5 there, so that a pause is quick, and whether the rule should cover it +too is the owner's call. **Each signer a different person on a different device**. That last clause is where BR-4 is closed for the endpoints: a multisig whose keys sit in one shell profile is still one key. ## 2. What the operator provides -- the owners of the admin and pause multisigs on each chain (5 addresses each is the - recommendation), created beforehand: Safes on Ethereum and BSC at safe.global (v1.3.0 or v1.4.1, +- the owners of the admin and pause multisigs on each chain (six for the admin multisig, of whom + five sign; five is the suggestion for the pause multisig), created beforehand: Safes on Ethereum and BSC at safe.global (v1.3.0 or v1.4.1, **no modules, no recovery or spending-limit add-ons**: the handover and the audit refuse a Safe with any module; a Safe of any other version, v1.5.0 included, is refused until its proxy code hash and singleton are added to both pins, `Governance.s.sol` `isSafeProxyCodehash` / `isCanonicalSafeSingleton` and `gov_audit.rs` `SAFE_PROXY_CODEHASHES` / `CANONICAL_SAFE_SINGLETONS`), native multi-signature accounts on Tron (active permission with the threshold, whose `operations` allow TriggerSmartContract), one Squads v4 multisig on Solana created - **without** a config authority and with a time lock of at least 172800 s; + **without** a config authority, with six members and a threshold of five, and with a time lock + of at least 172800 s; - **if the Safe web app offers only a newer version**, create the Safes at v1.4.1 explicitly with the Protocol Kit (`@safe-global/protocol-kit`): `Safe.init({ provider, signer, predictedSafe: { safeAccountConfig: { owners, threshold }, safeDeploymentConfig: { safeVersion: '1.4.1' } } })`, @@ -132,7 +145,7 @@ OPS_PRIVATE_KEY= node deploy/tron-ops.js set-pauser node deploy/tron-ops.js transfer-admin \ --admin-multisig --yes # 3b. make the two accounts multi-signature (unsigned, signed by each account's own key; burns 100 TRX each) -node deploy/tron-ops.js multisig-permissions --signers T1,...,T5 --owner-threshold 3 --active-threshold 3 +node deploy/tron-ops.js multisig-permissions --signers T1,...,T6 --owner-threshold 5 --active-threshold 5 node deploy/tron-ops.js multisig-permissions --signers T1,...,T5 --owner-threshold 3 --active-threshold 2 # 4. schedule the acceptance (unsigned, for the admin multisig) node deploy/tron-ops.js timelock-schedule-accept --from