diff --git a/daemons/README.md b/daemons/README.md index 816e4ef..bc842e9 100644 --- a/daemons/README.md +++ b/daemons/README.md @@ -201,7 +201,9 @@ requires it, each new key's proof of possession (`--possession-seed-envs`), as ` lines that signers on separate machines append to. `pq-rotate-submit` re-reads the chain, checks the quorum and the possession lines under the ledger's rules and sends the rotation through `rand-node bridge-gov rotate-pq|rotate-pause submit`; `pq-cancel-rotation` is the pause key's -cancel of a pending one. Runbook: `docs/pq-rotation.md`. +cancel of a pending one. `pq-rotate-status` reads the chain and says whether the expected keys are +in force, pending or absent, whether any retired key remains, and whether a seed on this host is +one the chain counts (read-only). Runbook: `docs/pq-rotation.md`. ## Audit diff --git a/daemons/src/bin/gov.rs b/daemons/src/bin/gov.rs index 01c16be..f594f10 100644 --- a/daemons/src/bin/gov.rs +++ b/daemons/src/bin/gov.rs @@ -384,6 +384,31 @@ enum Command { #[arg(long)] dry_run: bool, }, + /// Rand-only (BRG-14): read what the chain serves and say whether a rotation is in + /// effect, pending or absent. Read-only; signs and sends nothing. Exits 0 only when + /// every expectation given holds. + PqRotateStatus { + #[arg(long)] + rand_rpc: String, + /// The set the rotation was to install, `{"pq_guardians": [...]}`: must be in force. + #[arg(long)] + expect_pq_guardians_file: Option, + /// The pause key the rotation was to install, hex or `@file`: must be in force. + #[arg(long)] + expect_pause_key: Option, + /// The set from before the rotation: none of its keys may remain in force, as a + /// guardian key or as the pause key. + #[arg(long)] + retired_pq_guardians_file: Option, + /// The pause key from before the rotation: it must no longer be in force. + #[arg(long)] + retired_pause_key: Option, + /// Environment variables holding Dilithium2 seeds (comma-separated): each must + /// derive a key in force, and its index is printed. For a guardian to check, on its + /// own host, that the seed it runs is the one the chain counts. + #[arg(long, value_delimiter = ',')] + seed_envs: Vec, + }, /// Print the Dilithium2 public key a seed derives (and its sha256 prefix), never the seed. PqPublicKey { #[arg(long)] @@ -992,6 +1017,132 @@ async fn main() -> Result<()> { bail!("{} exited with {status}", rand_node.display()); } } + Command::PqRotateStatus { + rand_rpc, + expect_pq_guardians_file, + expect_pause_key, + retired_pq_guardians_file, + retired_pause_key, + seed_envs, + } => { + use bridge_daemons::pq_gov::{fingerprint, rotation_outcome, RotationOutcome}; + let view = rotation_view(&rand_rpc).await?; + let state = bridge_daemons::rpc::JsonRpc::new(&rand_rpc) + .call("rand_getBridgeState", serde_json::json!([])) + .await?; + let key_list = |v: &serde_json::Value| -> Result>> { + v.as_array() + .ok_or_else(|| anyhow!("not an array"))? + .iter() + .map(|k| hex::decode(k.as_str().unwrap_or_default()).context("not hex")) + .collect() + }; + let mut pending_pq: Option<(Vec>, u64)> = None; + let mut pending_pause: Option<(Vec>, u64)> = None; + for p in state["pending_rotations"].as_array().map(Vec::as_slice).unwrap_or_default() { + let at = p["effective_at_secs"].as_u64().ok_or_else(|| anyhow!("a pending rotation without effective_at_secs"))?; + match p["kind"].as_str() { + Some("pq_guardians") => pending_pq = Some((key_list(&p["new_pq_guardians"]).context("new_pq_guardians")?, at)), + Some("pause_key") => { + let k = hex::decode(p["new_pause_key"].as_str().unwrap_or_default()).context("new_pause_key")?; + pending_pause = Some((vec![k], at)); + } + other => bail!("a pending rotation of unknown kind {other:?}"), + } + } + let quorum = view.pq_guardians.len() * 2 / 3 + 1; + println!("Rand chain {} ({}), rotation_nonce {}", view.chain_id, view.binding.describe(), view.nonce); + println!( + "rotation rules: delay {} s, possession {}", + state["rotation_rules"]["delay_secs"].as_u64().map_or_else(|| "?".into(), |d| d.to_string()), + if view.needs_possession { "required" } else { "not required" } + ); + println!("PQ guardian set in force: {} keys, quorum {quorum}", view.pq_guardians.len()); + for (i, k) in view.pq_guardians.iter().enumerate() { + println!(" [{i}] {}", fingerprint(k)); + } + match &view.pause_key { + Some(k) => println!("pause key in force: {}", fingerprint(k)), + None => println!("pause key in force: none"), + } + if let Some((keys, at)) = &pending_pq { + let prints: Vec = keys.iter().map(|k| fingerprint(k)).collect(); + println!("PENDING PQ set rotation, in force from unix time {at}: {}", prints.join(" ")); + } + if let Some((keys, at)) = &pending_pause { + println!("PENDING pause key rotation, in force from unix time {at}: {}", fingerprint(&keys[0])); + } + if pending_pq.is_none() && pending_pause.is_none() { + println!("no rotation is pending"); + } + + let mut failed = Vec::new(); + let mut judge = |what: &str, outcome: RotationOutcome| match outcome { + RotationOutcome::InEffect => println!("PASS: the expected {what} is in force"), + RotationOutcome::Pending { effective_at_secs } => { + println!( + "WAIT: the expected {what} is pending, in force from unix time {effective_at_secs} \ + unless the current pause key cancels it first" + ); + failed.push(format!("the expected {what} is pending, not yet in force")); + } + RotationOutcome::NotRotated => { + println!("FAIL: the expected {what} is neither in force nor pending"); + failed.push(format!("the expected {what} is not on the chain")); + } + }; + if let Some(path) = &expect_pq_guardians_file { + let expected = pq_guardians(path)?; + let pending = pending_pq.as_ref().map(|(k, at)| (k.as_slice(), *at)); + judge("PQ guardian set", rotation_outcome(&view.pq_guardians, pending, &expected)); + } + if let Some(arg) = &expect_pause_key { + let expected = vec![pq_key_arg(arg)?]; + let in_force: Vec> = view.pause_key.clone().into_iter().collect(); + let pending = pending_pause.as_ref().map(|(k, at)| (k.as_slice(), *at)); + judge("pause key", rotation_outcome(&in_force, pending, &expected)); + } + let mut retired = match &retired_pq_guardians_file { + Some(path) => pq_guardians(path)?, + None => Vec::new(), + }; + let had_retired = !retired.is_empty() || retired_pause_key.is_some(); + if let Some(arg) = &retired_pause_key { + retired.push(pq_key_arg(arg)?); + } + let mut still = Vec::new(); + for k in &retired { + if let Some(i) = view.pq_guardians.iter().position(|g| g == k) { + still.push(format!("{} (guardian index {i})", fingerprint(k))); + } + if view.pause_key.as_ref() == Some(k) { + still.push(format!("{} (the pause key)", fingerprint(k))); + } + } + if had_retired { + if still.is_empty() { + println!("PASS: no retired key is in force"); + } else { + println!("FAIL: retired keys still in force: {}", still.join(", ")); + failed.push(format!("{} retired key(s) still in force", still.len())); + } + } + for name in &seed_envs { + let key = bridge_daemons::pq::PqKey::from_seed_hex(&take_env(name)?)?.public_key(); + let print = fingerprint(&key); + if let Some(i) = view.pq_guardians.iter().position(|g| *g == key) { + println!("PASS: {name} derives {print}, in force at guardian index {i}"); + } else if view.pause_key.as_ref() == Some(&key) { + println!("PASS: {name} derives {print}, the pause key in force"); + } else { + println!("FAIL: {name} derives {print}, which is not in force: co-signatures from this seed do not count"); + failed.push(format!("{name} is not a key in force")); + } + } + if !failed.is_empty() { + bail!("{}", failed.join("; ")); + } + } Command::PqPublicKey { seed_env } => { use sha2::{Digest, Sha256}; let key = bridge_daemons::pq::PqKey::from_seed_hex(&take_env(&seed_env)?)?; diff --git a/daemons/src/pq_gov.rs b/daemons/src/pq_gov.rs index 83f64b9..5c4e56b 100644 --- a/daemons/src/pq_gov.rs +++ b/daemons/src/pq_gov.rs @@ -427,3 +427,38 @@ pub fn sign_quorum( } Ok(quorum) } + +/// Where a rotation stands on the chain, against the keys it was meant to install (BRG-14). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RotationOutcome { + /// The chain's keys are exactly the expected ones, in order. + InEffect, + /// Accepted and waiting out the delay: in force from `effective_at_secs` unless the + /// current pause key cancels it first. + Pending { effective_at_secs: u64 }, + /// Neither in force nor pending. + NotRotated, +} + +/// Compares what the chain serves — the keys in force and, if any, the pending rotation of +/// the same kind — with `expected`. Order matters: a PQ key is bound to its guardian index. +pub fn rotation_outcome( + in_force: &[Vec], + pending: Option<(&[Vec], u64)>, + expected: &[Vec], +) -> RotationOutcome { + if in_force == expected { + return RotationOutcome::InEffect; + } + match pending { + Some((keys, effective_at_secs)) if keys == expected => RotationOutcome::Pending { effective_at_secs }, + _ => RotationOutcome::NotRotated, + } +} + +/// The first eight hex digits of a key's sha256: what `pq-public-key` prints, short enough +/// to read aloud when two people compare a set. +pub fn fingerprint(key: &[u8]) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(key))[..8].to_string() +} diff --git a/daemons/tests/pq_rotation.rs b/daemons/tests/pq_rotation.rs index 98de238..8101d45 100644 --- a/daemons/tests/pq_rotation.rs +++ b/daemons/tests/pq_rotation.rs @@ -314,3 +314,117 @@ fn the_rotation_messages_match_the_vectors() { assert_eq!(hex::encode(built), v["message"].as_str().unwrap(), "{} {}", v["kind"], v["form"]); } } + +// ---- pq-rotate-status --------------------------------------------------------- + +#[test] +fn a_rotation_is_in_effect_pending_or_absent() { + use pq_gov::{rotation_outcome, RotationOutcome}; + let (old, new) = (vec![pk(1), pk(2)], vec![pk(3), pk(4)]); + assert_eq!(rotation_outcome(&new, None, &new), RotationOutcome::InEffect); + assert_eq!( + rotation_outcome(&old, Some((&new, 99)), &new), + RotationOutcome::Pending { effective_at_secs: 99 } + ); + assert_eq!(rotation_outcome(&old, None, &new), RotationOutcome::NotRotated); + // Another pending set is not the expected one, and order is part of the set. + assert_eq!(rotation_outcome(&old, Some((&old, 99)), &new), RotationOutcome::NotRotated); + let swapped = vec![pk(4), pk(3)]; + assert_eq!(rotation_outcome(&swapped, None, &new), RotationOutcome::NotRotated); + assert_eq!(pq_gov::fingerprint(&pk(1)).len(), 8); +} + +/// A node serving `current` as the set in force with pause key `pause`, and `pending`. +fn status_node(current: &[u8], pause: u8, pending: serde_json::Value) -> Fake { + let pq: Vec = current.iter().map(|i| hex::encode(pk(*i))).collect(); + let guardians: Vec = current.iter().map(|i| format!("0x{:040x}", i)).collect(); + rpc(move |m, _| match m { + "rand_chainId" => Some(Ok(json!(21))), + "rand_getGenesisHash" => Some(Ok(json!(CHAIN21_GENESIS))), + "rand_getBridgeState" => Some(Ok(json!({ + "enabled": true, "guardian_set_index": 1, "guardians": guardians, "burn_sequence": 0, + "pq_guardians": pq, "pause_key": hex::encode(pk(pause)), "rotation_nonce": 4, + "rules_v2": { "cap_window_secs": 86400 }, + "rotation_rules": { "delay_secs": 86400, "needs_possession": true }, + "pending_rotations": pending, + }))), + _ => None, + }) +} + +fn status(node: &Fake, args: &[&str], env: &[(&str, String)]) -> Output { + let mut c = gov(); + c.args(["pq-rotate-status", "--rand-rpc", &node.url]).args(args); + for (k, v) in env { + c.env(k, v); + } + c.output().unwrap() +} + +#[test] +fn the_status_passes_only_when_the_new_keys_are_in_force_and_the_old_ones_gone() { + let dir = tempfile::tempdir().unwrap(); + let old = set_file(dir.path(), "old.json", &[1, 2, 3]); + let new = set_file(dir.path(), "new.json", &[11, 12, 13]); + let (old, new) = (old.to_str().unwrap(), new.to_str().unwrap()); + let (old_pause, new_pause) = (hex::encode(pk(50)), hex::encode(pk(60))); + + // Before: nothing rotated. + let before = status_node(&[1, 2, 3], 50, json!([])); + let o = status(&before, &["--expect-pq-guardians-file", new, "--expect-pause-key", &new_pause], &[]); + assert!(!o.status.success()); + assert_eq!(out(&o).matches("FAIL: the expected").count(), 2, "{}", out(&o)); + assert!(out(&o).contains("rotation_nonce 4") && out(&o).contains("no rotation is pending"), "{}", out(&o)); + + // Accepted, waiting out the delay: not a pass, and the time is printed. + let pending = status_node( + &[1, 2, 3], + 50, + json!([{ "kind": "pq_guardians", "new_pq_guardians": [hex::encode(pk(11)), hex::encode(pk(12)), hex::encode(pk(13))], "effective_at_secs": 1_800_000_000u64 }, + { "kind": "pause_key", "new_pause_key": new_pause, "effective_at_secs": 1_800_000_001u64 }]), + ); + let o = status(&pending, &["--expect-pq-guardians-file", new, "--expect-pause-key", &new_pause], &[]); + assert!(!o.status.success()); + assert!(out(&o).contains("WAIT: the expected PQ guardian set is pending, in force from unix time 1800000000"), "{}", out(&o)); + assert!(out(&o).contains("WAIT: the expected pause key is pending, in force from unix time 1800000001"), "{}", out(&o)); + + // After: in force, nothing retired remains, and a guardian's own seed is at its index. + let after = status_node(&[11, 12, 13], 60, json!([])); + let o = status( + &after, + &["--expect-pq-guardians-file", new, "--expect-pause-key", &new_pause, "--retired-pq-guardians-file", old, + "--retired-pause-key", &old_pause, "--seed-envs", "G12,PAUSE"], + &[("G12", seed(12)), ("PAUSE", seed(60))], + ); + assert!(o.status.success(), "{}\n{}", out(&o), err(&o)); + let text = out(&o); + assert_eq!(text.matches("PASS").count(), 5, "{text}"); + assert!(text.contains("G12 derives") && text.contains("guardian index 1") && text.contains("the pause key in force"), "{text}"); + assert!(!text.contains(&seed(12)) && !err(&o).contains(&seed(12)), "a seed is never printed"); + // Reads only. + for m in after.rpc_methods() { + assert!(m.starts_with("rand_get") || m == "rand_chainId", "{m}"); + } +} + +#[test] +fn the_status_fails_on_a_retired_key_left_in_force_or_a_seed_the_chain_does_not_count() { + let dir = tempfile::tempdir().unwrap(); + let old = set_file(dir.path(), "old.json", &[1, 2, 3]); + // Key 2 survived the rotation, and the old pause key is still the pause key. + let node = status_node(&[11, 2, 13], 50, json!([])); + let o = status( + &node, + &["--retired-pq-guardians-file", old.to_str().unwrap(), "--retired-pause-key", &hex::encode(pk(50)), "--seed-envs", "STALE"], + &[("STALE", seed(1))], + ); + assert!(!o.status.success()); + let text = out(&o); + assert!(text.contains("FAIL: retired keys still in force") && text.contains("(guardian index 1)") && text.contains("(the pause key)"), "{text}"); + assert!(text.contains("FAIL: STALE derives") && text.contains("do not count"), "{text}"); + assert!(err(&o).contains("2 retired key(s) still in force") && err(&o).contains("STALE is not a key in force"), "{}", err(&o)); + // With no expectation it reports and exits 0. + let o = status(&node, &[], &[]); + assert!(o.status.success(), "{}", err(&o)); + assert!(out(&o).contains("PQ guardian set in force: 3 keys, quorum 3"), "{}", out(&o)); +} diff --git a/docs/pq-rotation.md b/docs/pq-rotation.md index 4acb3d3..e77b893 100644 --- a/docs/pq-rotation.md +++ b/docs/pq-rotation.md @@ -71,6 +71,51 @@ rand-bridge-gov pq-cancel-rotation --rand-chain-id 21 --rand-rpc http://127.0.0. rand-node bridge-gov cancel-rotation submit --kind pq --signature @cancel.txt --rpc http://127.0.0.1:8545 ``` +## Verify: `pq-rotate-status` + +Read-only; it signs and sends nothing, and never prints a seed. + +```sh +rand-bridge-gov pq-rotate-status --rand-rpc http://127.0.0.1:8545 # what the chain serves +rand-bridge-gov pq-rotate-status --rand-rpc http://127.0.0.1:8545 \ + --expect-pq-guardians-file new.json --retired-pq-guardians-file current.json \ + --expect-pause-key @new-pause.hex --retired-pause-key @old-pause.hex # the rotation's result +rand-bridge-gov pq-rotate-status --rand-rpc http://127.0.0.1:8545 --seed-envs GUARDIAN3_PQ_SEED # on a guardian host +``` + +It prints the chain id and binding, `rotation_nonce`, the rules, each key in force as its index +and sha256 prefix (the one `pq-public-key` prints), and any pending rotation with the time it +takes effect. With expectations it exits 0 only when all hold: + +- `PASS: the expected … is in force` — the chain's keys are exactly the expected ones, in order. + `WAIT` (pending, with the time) and `FAIL` (neither) both exit non-zero. +- `PASS: no retired key is in force` — no key of the old set, and not the old pause key, is still + a guardian key or the pause key. +- `PASS: derives , in force at guardian index ` — the seed this host runs is one + the chain counts. Run it on each guardian host after its restart: a host still on its old seed + co-signs nothing that counts, and with six of six needed that stops every mint. + +## The ceremony, in order + +The rotation exists to move the keys from one operator to separate holders (BRG-14). The tool +makes each step checkable; who holds what is the part no tool does. + +1. **Before.** `pq-rotate-status` with no expectation: record the nonce, the set and the pause key. + Confirm no rotation is pending. +2. **New keys.** Each new holder generates a seed on their own machine and sends only + `pq-public-key`'s output. Compare the sha256 prefixes by voice. The pause key's new holder is + not a guardian operator. +3. **Sign.** A quorum of the current set, and every new key for possession, sign the same printed + `message` hex (above). The pause key rotation is a second message at the next nonce. +4. **Submit**, `--dry-run` first. +5. **Wait out the delay.** `pq-rotate-status --expect-…` prints `WAIT` and the time. During it the + current pause key can cancel; say who watches. +6. **Switch.** At the effective time each guardian sets its new seed and restarts, one host at a + time; on each, `pq-rotate-status --seed-envs ` must pass before the next host. + Mints wait while fewer than a quorum run a key in force; nothing is lost. +7. **After.** `pq-rotate-status` with every `--expect-…` and `--retired-…` must exit 0. Record the + output. Then destroy the old seeds and re-make the kept-ready pause signature. + ## Afterwards - Each guardian whose PQ key changed sets its new seed (`pq_seed_env`) and restarts