From b0ded945158711ebdee0fb81671da846ce0544b7 Mon Sep 17 00:00:00 2001 From: Mhidesav Date: Wed, 25 Nov 2026 09:13:41 +0000 Subject: [PATCH] feat(access-control): shared two-tier circuit breaker with timelocked unpause - add a reusable circuit_breaker module: guardian or admin pauses instantly, admin-only unpause requires a 24h proposal, and guardians can never unpause - integrate the AMM and lending pool, mapping pause rejections into each contract's existing error space - keep emergency exits open while paused: AMM liquidity removal and lending pool emergency_withdraw (unencumbered collateral only) - fix the AMM pause test that was missing #[test] and add regression coverage Closes #1871 --- contracts/Cargo.lock | 2 + .../access_control/src/circuit_breaker.rs | 175 ++++++++++++++++++ contracts/access_control/src/lib.rs | 17 +- contracts/access_control/src/roles.rs | 37 +--- contracts/access_control/src/test.rs | 147 +++++++++++++++ contracts/amm/Cargo.toml | 1 + contracts/amm/src/circuit_breaker.rs | 48 +---- contracts/amm/src/lib.rs | 71 ++++--- contracts/amm/src/test.rs | 28 ++- contracts/lending_pool/Cargo.toml | 1 + contracts/lending_pool/src/lib.rs | 155 +++++++++++++--- docs/contracts/SC-023-CIRCUIT-BREAKER.md | 53 +++++- docs/deployment/DEPLOYMENT_CHECKLIST.md | 7 +- 13 files changed, 596 insertions(+), 146 deletions(-) create mode 100644 contracts/access_control/src/circuit_breaker.rs diff --git a/contracts/Cargo.lock b/contracts/Cargo.lock index 9404948b1..e383f0702 100644 --- a/contracts/Cargo.lock +++ b/contracts/Cargo.lock @@ -31,6 +31,7 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" name = "amm" version = "0.1.0" dependencies = [ + "access-control", "contract-events", "proptest", "soroban-sdk", @@ -1202,6 +1203,7 @@ dependencies = [ name = "lending-pool" version = "0.1.0" dependencies = [ + "access-control", "proptest", "soroban-sdk", ] diff --git a/contracts/access_control/src/circuit_breaker.rs b/contracts/access_control/src/circuit_breaker.rs new file mode 100644 index 000000000..1368dcafe --- /dev/null +++ b/contracts/access_control/src/circuit_breaker.rs @@ -0,0 +1,175 @@ +//! Reusable two-tier emergency circuit breaker. +//! +//! A designated guardian (or the admin) can pause a contract instantly, but +//! resuming requires the admin — the "security council" — to propose the +//! unpause and wait out [`UNPAUSE_TIMELOCK_SECONDS`]. This keeps a compromised +//! guardian from flipping the protocol back on during an incident while still +//! allowing a single operator to stop the bleeding immediately. +//! +//! Consuming contracts initialise the breaker once, gate state-mutating +//! entrypoints with [`crate::require_not_paused!`], and deliberately leave +//! emergency-exit paths ungated. +//! +//! State lives under a dedicated key namespace so it cannot collide with the +//! host contract's own storage. + +use crate::AcError; +use soroban_sdk::{contracttype, panic_with_error, symbol_short, Address, Env}; + +/// Delay between proposing and executing an unpause: 24 hours. +pub const UNPAUSE_TIMELOCK_SECONDS: u64 = 24 * 60 * 60; + +const CB_TOPIC: soroban_sdk::Symbol = symbol_short!("CB"); + +#[contracttype] +#[derive(Clone)] +enum BreakerKey { + Admin, + Guardian, + Paused, + UnpauseUnlockAt, +} + +/// Initialise the breaker for the calling contract. +/// +/// The caller (the host contract's `initialize`) is responsible for +/// authenticating `admin`; this function only stores the hierarchy. The admin +/// is also the initial guardian so a fresh deployment can always pause. +pub fn initialize(env: &Env, admin: &Address, guardian: &Address) { + env.storage().instance().set(&BreakerKey::Admin, admin); + env.storage() + .instance() + .set(&BreakerKey::Guardian, guardian); + env.storage().instance().set(&BreakerKey::Paused, &false); + env.storage() + .instance() + .remove(&BreakerKey::UnpauseUnlockAt); +} + +/// Returns the configured breaker admin, if initialised. +pub fn admin(env: &Env) -> Option
{ + env.storage().instance().get(&BreakerKey::Admin) +} + +/// Returns the configured guardian, if any. +pub fn guardian(env: &Env) -> Option
{ + env.storage().instance().get(&BreakerKey::Guardian) +} + +/// Replace the guardian. Admin only; a new guardian can pause but never unpause. +pub fn set_guardian(env: &Env, caller: &Address, new_guardian: &Address) { + require_admin(env, caller); + env.storage() + .instance() + .set(&BreakerKey::Guardian, new_guardian); + env.events().publish( + (CB_TOPIC, symbol_short!("guardian")), + (caller.clone(), new_guardian.clone()), + ); +} + +/// Pause immediately. The admin and the guardian may call this; anyone else is +/// rejected. Re-pausing clears any pending unpause so the timelock restarts. +pub fn pause(env: &Env, caller: &Address) { + caller.require_auth(); + let is_admin = admin(env).as_ref() == Some(caller); + let is_guardian = guardian(env).as_ref() == Some(caller); + if !is_admin && !is_guardian { + panic_with_error!(env, AcError::Unauthorized); + } + env.storage().instance().set(&BreakerKey::Paused, &true); + env.storage() + .instance() + .remove(&BreakerKey::UnpauseUnlockAt); + env.events() + .publish((CB_TOPIC, symbol_short!("pause")), (caller.clone(), true)); +} + +/// Schedule an unpause and return the timestamp at which it becomes executable. +/// +/// Admin only. Requires the contract to be paused, otherwise there is nothing +/// to resume and the call likely indicates a mistaken operator. +pub fn propose_unpause(env: &Env, caller: &Address) -> u64 { + require_admin(env, caller); + if !is_paused(env) { + panic_with_error!(env, AcError::NotPaused); + } + let unlock_at = env + .ledger() + .timestamp() + .checked_add(UNPAUSE_TIMELOCK_SECONDS) + .unwrap_or_else(|| panic_with_error!(env, AcError::Overflow)); + env.storage() + .instance() + .set(&BreakerKey::UnpauseUnlockAt, &unlock_at); + env.events().publish( + (CB_TOPIC, symbol_short!("propose")), + (caller.clone(), unlock_at), + ); + unlock_at +} + +/// Resume the contract. Admin only, and only after the unpause proposal has +/// passed its timelock. A guardian can never unpause. +pub fn unpause(env: &Env, caller: &Address) { + require_admin(env, caller); + if !is_paused(env) { + panic_with_error!(env, AcError::NotPaused); + } + let unlock_at: u64 = env + .storage() + .instance() + .get(&BreakerKey::UnpauseUnlockAt) + .unwrap_or_else(|| panic_with_error!(env, AcError::NoPendingUnpause)); + if env.ledger().timestamp() < unlock_at { + panic_with_error!(env, AcError::TimelockNotExpired); + } + env.storage().instance().set(&BreakerKey::Paused, &false); + env.storage() + .instance() + .remove(&BreakerKey::UnpauseUnlockAt); + env.events().publish( + (CB_TOPIC, symbol_short!("unpause")), + (caller.clone(), false), + ); +} + +/// Cancel a pending unpause while remaining paused. Admin only. +pub fn cancel_unpause(env: &Env, caller: &Address) { + require_admin(env, caller); + if !env.storage().instance().has(&BreakerKey::UnpauseUnlockAt) { + panic_with_error!(env, AcError::NoPendingUnpause); + } + env.storage() + .instance() + .remove(&BreakerKey::UnpauseUnlockAt); + env.events() + .publish((CB_TOPIC, symbol_short!("cancel")), (caller.clone(), true)); +} + +/// Returns the timestamp at which a pending unpause becomes executable. +pub fn unpause_unlock_at(env: &Env) -> Option { + env.storage().instance().get(&BreakerKey::UnpauseUnlockAt) +} + +/// Returns true while the breaker is active. +pub fn is_paused(env: &Env) -> bool { + env.storage() + .instance() + .get(&BreakerKey::Paused) + .unwrap_or(false) +} + +/// Panics with [`AcError::ContractPaused`] while the breaker is active. +pub fn assert_not_paused(env: &Env) { + if is_paused(env) { + panic_with_error!(env, AcError::ContractPaused); + } +} + +fn require_admin(env: &Env, caller: &Address) { + caller.require_auth(); + if admin(env).as_ref() != Some(caller) { + panic_with_error!(env, AcError::Unauthorized); + } +} diff --git a/contracts/access_control/src/lib.rs b/contracts/access_control/src/lib.rs index 7265a2f9b..22f70d6de 100644 --- a/contracts/access_control/src/lib.rs +++ b/contracts/access_control/src/lib.rs @@ -6,10 +6,15 @@ use soroban_sdk::{contracterror, Env}; +pub mod circuit_breaker; pub mod roles; pub mod timelock; -pub use roles::{grant_role, has_role, initialize, is_paused, pause, revoke_role, unpause, Role}; +pub use circuit_breaker::{ + assert_not_paused, cancel_unpause, is_paused, pause, propose_unpause, unpause, + unpause_unlock_at, +}; +pub use roles::{grant_role, has_role, initialize, revoke_role, Role}; pub use timelock::{ admin, cancel_admin_proposal, claim_admin, pending_admin, propose_admin, AdminProposal, ADMIN_HANDOVER_DELAY, @@ -27,9 +32,14 @@ pub enum AcError { RoleNotGranted = 306, InvalidRole = 307, InvalidAdminProposal = 308, + NoPendingUnpause = 309, + NotPaused = 310, } /// Panics with `AcError::ContractPaused` if the circuit-breaker is active. +/// +/// A second form lets a host contract surface the pause in its own error +/// space: `require_not_paused!(&env, AmmError::ContractPaused)`. #[macro_export] macro_rules! require_not_paused { ($env:expr) => { @@ -37,6 +47,11 @@ macro_rules! require_not_paused { soroban_sdk::panic_with_error!($env, $crate::AcError::ContractPaused); } }; + ($env:expr, $error:expr) => { + if $crate::is_paused($env) { + soroban_sdk::panic_with_error!($env, $error); + } + }; } /// Panics with `AcError::Unauthorized` if `addr` does not hold `role`. diff --git a/contracts/access_control/src/roles.rs b/contracts/access_control/src/roles.rs index a857b0721..7f7951840 100644 --- a/contracts/access_control/src/roles.rs +++ b/contracts/access_control/src/roles.rs @@ -1,5 +1,5 @@ use crate::AcError; -use soroban_sdk::{contracttype, symbol_short, Address, Env, Symbol}; +use soroban_sdk::{contracttype, symbol_short, Address, Env}; /// Roles supported by the shared access-control module. /// @@ -21,12 +21,9 @@ pub enum Role { #[derive(Clone)] pub(crate) enum StorageKey { Admin, - Paused, RoleMember(Role, Address), } -pub(crate) const PAUSED_KEY: Symbol = symbol_short!("AC_PAUSED"); - /// Initializes access control once. Repeated calls never replace the admin. pub fn initialize(env: &Env, initial_admin: &Address) { let key = StorageKey::Admin; @@ -35,7 +32,9 @@ pub fn initialize(env: &Env, initial_admin: &Address) { } initial_admin.require_auth(); env.storage().instance().set(&key, initial_admin); - env.storage().instance().set(&PAUSED_KEY, &false); + // The admin is the initial guardian; the breaker's unpause timelock lives + // in `circuit_breaker`. + crate::circuit_breaker::initialize(env, initial_admin, initial_admin); env.events().publish( (symbol_short!("AC_ROLE"), Role::Admin), (initial_admin.clone(), true, initial_admin.clone()), @@ -109,31 +108,3 @@ pub fn revoke_role(env: &Env, caller: &Address, role: Role, account: &Address) { (account.clone(), false, caller.clone()), ); } - -/// Returns true if the contract is currently paused. -pub fn is_paused(env: &Env) -> bool { - env.storage() - .instance() - .get::(&PAUSED_KEY) - .unwrap_or(false) -} - -/// Pause application operations. Admins and guardians may pause. -pub fn pause(env: &Env, caller: &Address) { - caller.require_auth(); - if !has_role(env, caller, Role::Admin) && !has_role(env, caller, Role::Guardian) { - soroban_sdk::panic_with_error!(env, AcError::Unauthorized); - } - env.storage().instance().set(&PAUSED_KEY, &true); - env.events() - .publish((symbol_short!("AC_PAUSE"),), caller.clone()); -} - -/// Resume application operations. Only the admin may unpause. -pub fn unpause(env: &Env, caller: &Address) { - caller.require_auth(); - crate::require_admin(env, caller); - env.storage().instance().set(&PAUSED_KEY, &false); - env.events() - .publish((symbol_short!("AC_UNPAUS"),), caller.clone()); -} diff --git a/contracts/access_control/src/test.rs b/contracts/access_control/src/test.rs index 4d39d3a9c..efdbebde3 100644 --- a/contracts/access_control/src/test.rs +++ b/contracts/access_control/src/test.rs @@ -1,4 +1,5 @@ use super::*; +use crate::circuit_breaker::UNPAUSE_TIMELOCK_SECONDS; use soroban_sdk::{ contract, contractimpl, testutils::{Address as _, Ledger as _}, @@ -45,6 +46,42 @@ impl TestContract { pub fn pending_admin(env: Env) -> Option { crate::pending_admin(&env) } + + // ── Circuit breaker surface ─────────────────────────────────────────── + + pub fn set_breaker_guardian(env: Env, caller: Address, guardian: Address) { + crate::circuit_breaker::set_guardian(&env, &caller, &guardian); + } + + pub fn pause(env: Env, caller: Address) { + crate::circuit_breaker::pause(&env, &caller); + } + + pub fn propose_unpause(env: Env, caller: Address) -> u64 { + crate::circuit_breaker::propose_unpause(&env, &caller) + } + + pub fn unpause(env: Env, caller: Address) { + crate::circuit_breaker::unpause(&env, &caller); + } + + pub fn cancel_unpause(env: Env, caller: Address) { + crate::circuit_breaker::cancel_unpause(&env, &caller); + } + + pub fn unpause_unlock_at(env: Env) -> Option { + crate::circuit_breaker::unpause_unlock_at(&env) + } + + pub fn is_paused(env: Env) -> bool { + crate::circuit_breaker::is_paused(&env) + } + + /// Example gated entrypoint: must revert while paused. + pub fn guarded_action(env: Env) -> bool { + crate::require_not_paused!(&env); + true + } } fn setup_test(env: &Env) -> TestContractClient<'_> { @@ -166,6 +203,116 @@ fn current_admin_can_cancel_a_pending_handover() { assert_eq!(client.admin(), Some(current_admin.clone())); } +// ── Circuit breaker ────────────────────────────────────────────────────────── + +#[test] +fn guardian_pauses_instantly_but_cannot_unpause() { + let env = Env::default(); + env.mock_all_auths(); + let admin = Address::generate(&env); + let guardian = Address::generate(&env); + + let client = setup_test(&env); + client.initialize(&admin); + client.set_breaker_guardian(&admin, &guardian); + client.pause(&guardian); + + assert!(client.is_paused()); + assert!(client.try_guarded_action().is_err()); + assert!(client.try_unpause(&guardian).is_err()); + assert!(client.try_unpause(&admin).is_err()); // no proposal yet + assert!(client.try_guarded_action().is_err()); +} + +#[test] +fn admin_unpauses_only_after_the_timelock() { + let env = Env::default(); + env.mock_all_auths(); + let admin = Address::generate(&env); + let guardian = Address::generate(&env); + + let client = setup_test(&env); + client.initialize(&admin); + client.set_breaker_guardian(&admin, &guardian); + client.pause(&guardian); + + let unlock_at = client.propose_unpause(&admin); + assert_eq!( + unlock_at, + env.ledger().timestamp() + UNPAUSE_TIMELOCK_SECONDS + ); + assert_eq!(client.unpause_unlock_at(), Some(unlock_at)); + assert!(client.try_unpause(&admin).is_err()); // too early + + env.ledger().with_mut(|ledger| ledger.timestamp = unlock_at); + client.unpause(&admin); + + assert!(!client.is_paused()); + assert!(client.unpause_unlock_at().is_none()); + assert!(client.guarded_action()); +} + +#[test] +fn re_pausing_restarts_the_unpause_timelock() { + let env = Env::default(); + env.mock_all_auths(); + let admin = Address::generate(&env); + let guardian = Address::generate(&env); + + let client = setup_test(&env); + client.initialize(&admin); + client.set_breaker_guardian(&admin, &guardian); + client.pause(&guardian); + let first_unlock = client.propose_unpause(&admin); + + env.ledger() + .with_mut(|ledger| ledger.timestamp = first_unlock / 2); + // A second pause (e.g. attack still in progress) must invalidate the + // pending unpause instead of letting it fire on the original schedule. + client.pause(&guardian); + assert!(client.unpause_unlock_at().is_none()); + assert!(client.try_unpause(&admin).is_err()); +} + +#[test] +#[should_panic(expected = "Error(Contract, #300)")] +fn non_guardian_cannot_pause() { + let env = Env::default(); + env.mock_all_auths(); + let admin = Address::generate(&env); + let stranger = Address::generate(&env); + + let client = setup_test(&env); + client.initialize(&admin); + client.pause(&stranger); +} + +#[test] +#[should_panic(expected = "Error(Contract, #310)")] +fn cannot_propose_unpause_while_running() { + let env = Env::default(); + env.mock_all_auths(); + let admin = Address::generate(&env); + + let client = setup_test(&env); + client.initialize(&admin); + client.propose_unpause(&admin); +} + +#[test] +#[should_panic(expected = "Error(Contract, #300)")] +fn only_admin_can_rotate_the_guardian() { + let env = Env::default(); + env.mock_all_auths(); + let admin = Address::generate(&env); + let guardian = Address::generate(&env); + let attacker = Address::generate(&env); + + let client = setup_test(&env); + client.initialize(&admin); + client.set_breaker_guardian(&attacker, &guardian); +} + #[test] #[should_panic(expected = "Error(Contract, #300)")] fn non_admin_cannot_grant_roles() { diff --git a/contracts/amm/Cargo.toml b/contracts/amm/Cargo.toml index 9ce6c99d2..dfc6df7ab 100644 --- a/contracts/amm/Cargo.toml +++ b/contracts/amm/Cargo.toml @@ -8,6 +8,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] soroban-sdk = "28.0.0" +access-control = { path = "../access_control" } contract-events = { path = "../contract_events" } [dev-dependencies] diff --git a/contracts/amm/src/circuit_breaker.rs b/contracts/amm/src/circuit_breaker.rs index 35bb4afae..dd2676286 100644 --- a/contracts/amm/src/circuit_breaker.rs +++ b/contracts/amm/src/circuit_breaker.rs @@ -1,33 +1,20 @@ -use crate::{AmmError, DataKey}; -use soroban_sdk::{panic_with_error, symbol_short, Address, Env, Symbol}; +//! AMM-specific rolling outflow budget. +//! +//! Pause state and the guardian/admin hierarchy live in the shared +//! `access_control::circuit_breaker`; this module only tracks how much of each +//! reserve may leave the pool in a 24-hour window. + +use crate::AmmError; +use soroban_sdk::{panic_with_error, symbol_short, Env, Symbol}; pub const WITHDRAWAL_WINDOW_SECONDS: u64 = 24 * 60 * 60; -const PAUSED: Symbol = symbol_short!("amm_pause"); const WINDOW_START: Symbol = symbol_short!("wstart"); const WINDOW_LIMIT_A: Symbol = symbol_short!("wla"); const WINDOW_LIMIT_B: Symbol = symbol_short!("wlb"); const WINDOW_USED_A: Symbol = symbol_short!("wua"); const WINDOW_USED_B: Symbol = symbol_short!("wub"); -pub fn is_paused(env: &Env) -> bool { - env.storage() - .instance() - .get::<_, bool>(&PAUSED) - .unwrap_or(false) -} - -pub fn set_paused(env: &Env, paused: bool, caller: &Address) { - env.storage().instance().set(&PAUSED, &paused); - crate::events::pause_changed(env, caller, paused); -} - -pub fn assert_not_paused(env: &Env) { - if is_paused(env) { - panic_with_error!(env, AmmError::ContractPaused); - } -} - /// Limit token outflows independently because the AMM has no common price /// oracle for comparing reserves denominated in different assets. pub fn record_outflow(env: &Env, reserve_a: i128, reserve_b: i128, amount_a: i128, amount_b: i128) { @@ -88,22 +75,3 @@ fn daily_limit(env: &Env, reserve: i128) -> i128 { .checked_div(10) .unwrap_or_else(|| panic_with_error!(env, AmmError::Overflow)) } - -pub fn admin(env: &Env) -> Address { - env.storage() - .instance() - .get(&DataKey::Admin) - .unwrap_or_else(|| panic_with_error!(env, AmmError::NotInitialized)) -} - -pub fn set_guardian(env: &Env, guardian: &Address) { - env.storage().instance().set(&DataKey::Guardian, guardian); -} - -pub fn is_guardian(env: &Env, account: &Address) -> bool { - env.storage() - .instance() - .get::<_, Address>(&DataKey::Guardian) - .as_ref() - == Some(account) -} diff --git a/contracts/amm/src/lib.rs b/contracts/amm/src/lib.rs index a1a1cf1dc..b5daacb9f 100644 --- a/contracts/amm/src/lib.rs +++ b/contracts/amm/src/lib.rs @@ -113,7 +113,8 @@ impl AMMContract { } env.storage().instance().set(&DataKey::Admin, &admin); - circuit_breaker::set_guardian(&env, &admin); + // Admin is the initial guardian; unpausing is admin-only and timelocked. + access_control::circuit_breaker::initialize(&env, &admin, &admin); env.storage().instance().set(&DataKey::TokenA, &token_a); env.storage().instance().set(&DataKey::TokenB, &token_b); env.storage() @@ -147,36 +148,56 @@ impl AMMContract { Self::unlock(&env); } - /// Set the address authorized to trigger the emergency pause. + /// Set the address authorized to trigger the emergency pause. Admin only; + /// the guardian can pause but can never unpause. pub fn set_guardian(env: Env, admin: Address, guardian: Address) { Self::lock(&env); - admin.require_auth(); - if admin != circuit_breaker::admin(&env) { - panic_with_error!(&env, AmmError::Unauthorized); - } - circuit_breaker::set_guardian(&env, &guardian); + access_control::circuit_breaker::set_guardian(&env, &admin, &guardian); events::guardian_changed(&env, &admin, &guardian); Self::unlock(&env); } - /// Pause swaps and liquidity changes immediately. The admin or designated - /// guardian can pause; only the admin can unpause. - pub fn set_paused(env: Env, caller: Address, paused: bool) { + /// Pause swaps and liquidity additions immediately. The admin or the + /// designated guardian may call this. Liquidity removal stays available so + /// providers can exit their position during an incident. + pub fn pause(env: Env, caller: Address) { Self::lock(&env); - caller.require_auth(); - let is_admin = caller == circuit_breaker::admin(&env); - if !is_admin && !circuit_breaker::is_guardian(&env, &caller) { - panic_with_error!(&env, AmmError::Unauthorized); - } - if !paused && !is_admin { - panic_with_error!(&env, AmmError::Unauthorized); - } - circuit_breaker::set_paused(&env, paused, &caller); + access_control::circuit_breaker::pause(&env, &caller); + events::pause_changed(&env, &caller, true); + Self::unlock(&env); + } + + /// Propose resuming the pool. Admin only; the proposal becomes executable + /// after `access_control::circuit_breaker::UNPAUSE_TIMELOCK_SECONDS`. + pub fn propose_unpause(env: Env, admin: Address) -> u64 { + Self::lock(&env); + let unlock_at = access_control::circuit_breaker::propose_unpause(&env, &admin); + Self::unlock(&env); + unlock_at + } + + /// Cancel a pending unpause while staying paused. Admin only. + pub fn cancel_unpause(env: Env, admin: Address) { + Self::lock(&env); + access_control::circuit_breaker::cancel_unpause(&env, &admin); Self::unlock(&env); } + /// Resume swaps after the unpause timelock has elapsed. Admin only. + pub fn unpause(env: Env, admin: Address) { + Self::lock(&env); + access_control::circuit_breaker::unpause(&env, &admin); + events::pause_changed(&env, &admin, false); + Self::unlock(&env); + } + + /// Timestamp at which a pending unpause becomes executable, if any. + pub fn unpause_unlock_at(env: Env) -> Option { + access_control::circuit_breaker::unpause_unlock_at(&env) + } + pub fn is_paused(env: Env) -> bool { - circuit_breaker::is_paused(&env) + access_control::circuit_breaker::is_paused(&env) } /// Adds liquidity and mints pool shares. Requires equal value deposit (x * y = k maintained). @@ -189,7 +210,7 @@ impl AMMContract { ) -> i128 { provider.require_auth(); Self::lock(&env); - circuit_breaker::assert_not_paused(&env); + access_control::require_not_paused!(&env, AmmError::ContractPaused); if amount_a <= 0 || amount_b <= 0 { Self::unlock(&env); panic_with_error!(&env, AmmError::InvalidAmount); @@ -286,7 +307,9 @@ impl AMMContract { ) -> (i128, i128) { provider.require_auth(); Self::lock(&env); - circuit_breaker::assert_not_paused(&env); + // Deliberately not gated by the pause: liquidity providers must be + // able to exit during an incident. The rolling outflow budget below + // still rate-limits the exit. if shares <= 0 { Self::unlock(&env); panic_with_error!(&env, AmmError::InvalidAmount); @@ -363,7 +386,7 @@ impl AMMContract { pub fn swap_a_for_b(env: Env, user: Address, amount_in: i128, min_amount_out: i128) -> i128 { user.require_auth(); Self::lock(&env); - circuit_breaker::assert_not_paused(&env); + access_control::require_not_paused!(&env, AmmError::ContractPaused); if amount_in <= 0 { panic_with_error!(&env, AmmError::InvalidAmount); } @@ -454,7 +477,7 @@ impl AMMContract { pub fn swap_b_for_a(env: Env, user: Address, amount_in: i128, min_amount_out: i128) -> i128 { user.require_auth(); Self::lock(&env); - circuit_breaker::assert_not_paused(&env); + access_control::require_not_paused!(&env, AmmError::ContractPaused); if amount_in <= 0 { panic_with_error!(&env, AmmError::InvalidAmount); } diff --git a/contracts/amm/src/test.rs b/contracts/amm/src/test.rs index 4f59a910e..99e6623f7 100644 --- a/contracts/amm/src/test.rs +++ b/contracts/amm/src/test.rs @@ -496,14 +496,15 @@ fn test_bidirectional_trade_allowed_in_different_blocks() { assert!(out2 > 0); } -fn test_guardian_pause_blocks_amm_operations() { +#[test] +fn test_guardian_pause_blocks_swaps_but_allows_liquidity_exit() { let env = Env::default(); let (admin, client, token_a, _, _) = setup(&env); - let shares = client.add_liquidity(&admin, &1_000_000, &1_000_000, &0); + client.add_liquidity(&admin, &1_000_000, &1_000_000, &0); let guardian = Address::generate(&env); client.set_guardian(&admin, &guardian); - client.set_paused(&guardian, &true); + client.pause(&guardian); assert!(client.is_paused()); let user = Address::generate(&env); @@ -512,12 +513,23 @@ fn test_guardian_pause_blocks_amm_operations() { assert!(client .try_add_liquidity(&admin, &1_000, &1_000, &0) .is_err()); - assert!(client - .try_remove_liquidity(&admin, &shares, &0, &0) - .is_err()); + assert!(client.try_pause(&user).is_err()); + + // Emergency exit: removing liquidity still works while paused, subject to + // the rolling 24-hour outflow budget. + let (out_a, out_b) = client.remove_liquidity(&admin, &1_000, &0, &0); + assert!(out_a > 0 && out_b > 0); + + // A guardian can never resume the pool, and the admin must wait out the + // unpause timelock. + assert!(client.try_unpause(&guardian).is_err()); + let unlock_at = client.propose_unpause(&admin); + assert_eq!(client.unpause_unlock_at(), Some(unlock_at)); + assert!(client.try_unpause(&admin).is_err()); + + env.ledger().with_mut(|ledger| ledger.timestamp = unlock_at); + client.unpause(&admin); - assert!(client.try_set_paused(&user, &true).is_err()); - client.set_paused(&admin, &false); assert!(!client.is_paused()); assert!(client.swap_a_for_b(&user, &1_000, &0) > 0); } diff --git a/contracts/lending_pool/Cargo.toml b/contracts/lending_pool/Cargo.toml index 63d89021a..1410a6f87 100644 --- a/contracts/lending_pool/Cargo.toml +++ b/contracts/lending_pool/Cargo.toml @@ -8,6 +8,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] soroban-sdk = "28.0.0" +access-control = { path = "../access_control" } [dev-dependencies] soroban-sdk = { version = "28.0.0", features = ["testutils"] } diff --git a/contracts/lending_pool/src/lib.rs b/contracts/lending_pool/src/lib.rs index f34104c8e..619e21e86 100644 --- a/contracts/lending_pool/src/lib.rs +++ b/contracts/lending_pool/src/lib.rs @@ -27,10 +27,12 @@ //! `checked_div`. Overflow / underflow / division-by-zero produce typed //! `LPError` variants instead of panicking. //! -//! ## Pause (SC-HARD-19) +//! ## Pause (SC-HARD-19, SC-074) //! State-mutating entry points call `check_not_paused()` and revert with -//! `LPError::ContractPaused` when the circuit-breaker is active. -//! `emergency_withdraw` is exempt. +//! `LPError::ContractPaused` when the circuit-breaker is active. The breaker is +//! the shared `access_control::circuit_breaker`: a guardian or the admin pauses +//! instantly, while unpausing is admin-only and timelocked. `emergency_withdraw` +//! and unstaking are exempt so users can exit during an incident. #![no_std] @@ -55,8 +57,6 @@ const SCALE: i128 = 1_000_000_000_000; // 1e12 const SECS_PER_YEAR: i128 = 31_536_000; /// Temporary-storage key for the reentrancy guard mutex. const RG_KEY: Symbol = symbol_short!("lp_rg"); -/// Instance-storage key for the circuit-breaker pause flag. -const PAUSED_KEY: Symbol = symbol_short!("lp_pause"); // ── Storage keys ───────────────────────────────────────────────────────────── @@ -121,6 +121,8 @@ pub enum LPError { DivisionByZero = 13, /// `14` — Contract is paused by the circuit breaker. ContractPaused = 14, + /// `15` — Emergency withdrawal blocked by an outstanding borrow. + DebtOutstanding = 15, } // ── Fixed-point math helpers (SC-HARD-18) ───────────────────────────────────── @@ -177,7 +179,8 @@ impl LendingPool { .instance() .set(&Key::MinCollRatio, &min_coll_ratio); env.storage().instance().set(&Key::LiqBonus, &liq_bonus); - env.storage().instance().set(&PAUSED_KEY, &false); + // Admin is the initial guardian; unpausing is admin-only and timelocked. + access_control::circuit_breaker::initialize(&env, &admin, &admin); } /// Register a token as an accepted collateral / borrow asset. @@ -424,15 +427,29 @@ impl LendingPool { ); } - /// Emergency collateral withdrawal — available even when the circuit - /// breaker is active, so admin can recover funds during a pause. + /// Emergency collateral withdrawal for a depositor, available even when + /// the circuit breaker is active so users can exit during an incident. + /// + /// Collateral cannot be withdrawn while it backs an outstanding borrow in + /// that token: this stops a paused pool from being drained by underwater + /// positions while still giving unencumbered depositors an exit. pub fn emergency_withdraw(env: Env, user: Address, collateral_token: Address, amount: i128) { user.require_auth(); // NOTE: intentionally does NOT call check_not_paused — this is the // exempted emergency path (SC-HARD-19). - Self::only_admin(&env); + Self::check_nonzero(&env, amount); Self::lock(&env); + let debt: i128 = env + .storage() + .persistent() + .get(&Key::Debt(user.clone(), collateral_token.clone())) + .unwrap_or(0); + if debt != 0 { + Self::unlock(&env); + panic_with_error!(&env, LPError::DebtOutstanding); + } + let coll_key = Key::Collateral(user.clone(), collateral_token.clone()); let bal: i128 = env.storage().persistent().get(&coll_key).unwrap_or(0); if amount > bal { @@ -457,12 +474,42 @@ impl LendingPool { ); } - /// Pause the contract (admin only). - pub fn set_paused(env: Env, admin: Address, paused: bool) { - admin.require_auth(); - Self::only_admin(&env); - env.storage().instance().set(&PAUSED_KEY, &paused); - env.events().publish((symbol_short!("lp_pause"),), paused); + /// Pause deposits, borrows, withdrawals, liquidations and flash loans + /// immediately. The admin or the designated guardian may call this. + /// Unstaking, reward claims, and `emergency_withdraw` remain available. + pub fn pause(env: Env, caller: Address) { + access_control::circuit_breaker::pause(&env, &caller); + env.events().publish((symbol_short!("lp_pause"),), true); + } + + /// Set the guardian allowed to pause the pool. Admin only; the guardian can + /// never unpause. + pub fn set_guardian(env: Env, admin: Address, guardian: Address) { + // The breaker authenticates `admin` and checks it against the stored + // breaker admin (set to the pool admin during initialize). + access_control::circuit_breaker::set_guardian(&env, &admin, &guardian); + } + + /// Propose resuming the pool. Admin only; executable after the unpause + /// timelock. + pub fn propose_unpause(env: Env, admin: Address) -> u64 { + access_control::circuit_breaker::propose_unpause(&env, &admin) + } + + /// Cancel a pending unpause while staying paused. Admin only. + pub fn cancel_unpause(env: Env, admin: Address) { + access_control::circuit_breaker::cancel_unpause(&env, &admin); + } + + /// Resume operations after the unpause timelock. Admin only. + pub fn unpause(env: Env, admin: Address) { + access_control::circuit_breaker::unpause(&env, &admin); + env.events().publish((symbol_short!("lp_pause"),), false); + } + + /// Timestamp at which a pending unpause becomes executable, if any. + pub fn unpause_unlock_at(env: Env) -> Option { + access_control::circuit_breaker::unpause_unlock_at(&env) } // ── Flash Loan (SC-031) ─────────────────────────────────────────────────── @@ -545,10 +592,7 @@ impl LendingPool { } pub fn paused(env: Env) -> bool { - env.storage() - .instance() - .get::(&PAUSED_KEY) - .unwrap_or(false) + access_control::circuit_breaker::is_paused(&env) } // ── Internal helpers ────────────────────────────────────────────────────── @@ -720,16 +764,9 @@ impl LendingPool { } } - /// Check circuit-breaker pause state. + /// Check circuit-breaker pause state, surfacing the pool's own error code. fn check_not_paused(env: &Env) { - let paused: bool = env - .storage() - .instance() - .get::(&PAUSED_KEY) - .unwrap_or(false); - if paused { - panic_with_error!(env, LPError::ContractPaused); - } + access_control::require_not_paused!(env, LPError::ContractPaused); } /// Acquire the reentrancy guard using temporary storage (SC-HARD-17). @@ -899,10 +936,70 @@ mod tests { let token = add_token(&env, &client); let user = Address::generate(&env); - client.set_paused(&admin, &true); + client.pause(&admin); client.deposit_collateral(&user, &token, &1_000); } + #[test] + fn guardian_pause_blocks_lending_but_allows_emergency_exit() { + let env = Env::default(); + env.mock_all_auths(); + let (client, admin, _) = setup(&env); + let token = add_token(&env, &client); + let user = Address::generate(&env); + + client.deposit_collateral(&user, &token, &1_000); + let guardian = Address::generate(&env); + client.set_guardian(&admin, &guardian); + client.pause(&guardian); + assert!(client.paused()); + + assert!(client + .try_deposit_collateral(&user, &token, &1_000) + .is_err()); + assert!(client + .try_withdraw_collateral(&user, &token, &token, &100) + .is_err()); + + // Emergency exit stays open while paused. + client.emergency_withdraw(&user, &token, &400); + assert_eq!(client.collateral_of(&user, &token), 600); + + // A guardian can never resume the pool; the admin must wait out the + // unpause timelock. + assert!(client.try_unpause(&guardian).is_err()); + let unlock_at = client.propose_unpause(&admin); + assert_eq!( + unlock_at, + env.ledger().timestamp() + access_control::circuit_breaker::UNPAUSE_TIMELOCK_SECONDS + ); + assert_eq!(client.unpause_unlock_at(), Some(unlock_at)); + assert!(client.try_unpause(&admin).is_err()); + + env.ledger().with_mut(|ledger| ledger.timestamp = unlock_at); + client.unpause(&admin); + + assert!(!client.paused()); + client.deposit_collateral(&user, &token, &100); + assert_eq!(client.collateral_of(&user, &token), 700); + } + + #[test] + #[should_panic(expected = "Error(Contract, #15)")] + fn emergency_withdraw_rejected_with_outstanding_debt() { + let env = Env::default(); + env.mock_all_auths(); + let (client, admin, _) = setup(&env); + let token = add_token(&env, &client); + let user = Address::generate(&env); + + client.deposit_collateral(&user, &token, &1_000); + client.borrow(&user, &token, &token, &100); + client.pause(&admin); + + client.emergency_withdraw(&user, &token, &100); + } + // ── SC-007 acceptance-criteria tests ────────────────────────────────────── /// Pool configured with a hard 75 % LTV cap: collateral factor 7_500 BPS diff --git a/docs/contracts/SC-023-CIRCUIT-BREAKER.md b/docs/contracts/SC-023-CIRCUIT-BREAKER.md index 4528a0077..ead930542 100644 --- a/docs/contracts/SC-023-CIRCUIT-BREAKER.md +++ b/docs/contracts/SC-023-CIRCUIT-BREAKER.md @@ -1,9 +1,30 @@ # SC-023: Emergency Circuit Breaker and Withdrawal Limits -The SmartVault and AMM contracts each expose an immediate pause and a rolling -24-hour outflow budget. A pause blocks deposits, withdrawals, swaps, liquidity -changes, and other user-facing payout or asset mutations. Read-only queries and -guardian/admin control calls remain available while paused. +The SmartVault, AMM, and lending-pool contracts expose an immediate pause and a +rolling 24-hour outflow budget. Read-only queries and emergency control calls +remain available while paused. + +## Shared breaker (SC-074) + +The AMM and lending pool use the reusable two-tier breaker in +`contracts/access_control/src/circuit_breaker.rs`. State lives under its own +storage namespace, so host contracts do not need to share storage keys. + +- **Pause (instant).** The configured guardian or the admin can call `pause()`. + Anyone else reverts with `AcError::Unauthorized` (`300`). +- **Unpause (timelocked).** Only the admin can `propose_unpause()`, which + returns an unlock timestamp 24 hours (`UNPAUSE_TIMELOCK_SECONDS`) in the + future. `unpause()` before that timestamp reverts with + `AcError::TimelockNotExpired` (`302`); without a proposal it reverts with + `AcError::NoPendingUnpause` (`309`). A guardian can never unpause. +- **Re-pausing** clears any pending unpause, so a second incident cannot ride + the original unlock schedule. +- **Guardian rotation** is admin-only. The admin is the initial guardian. +- Consuming contracts gate state-mutating entrypoints with + `require_not_paused!()`; a second form takes the host contract's error so the + ABI keeps its own error space (`AmmError::ContractPaused` `409`, + `LPError::ContractPaused` `14`). +- Emergency-exit paths deliberately do **not** call the macro. ## SmartVault @@ -20,8 +41,12 @@ reports an exceeded budget. ## AMM The admin designates one guardian with `set_guardian`. That guardian or the -admin can pause swaps and liquidity changes in one call. Only the admin can -unpause. The admin is the initial guardian. +admin can `pause()` swaps and liquidity additions in one call. Resuming requires +the admin to `propose_unpause()` and wait out the 24-hour timelock before +`unpause()`. The admin is the initial guardian. + +Liquidity removal stays available while paused so providers can exit during an +incident; it is still rate-limited by the outflow budget below. Because the AMM has no shared price oracle, token A and token B outflows are limited independently to 10% of each reserve at the start of the 24-hour @@ -29,4 +54,18 @@ window. Swap output plus its fee counts against the relevant token's budget; liquidity removals count against both budgets. `AmmError::WithdrawalLimitExceeded` (`407`) identifies a rejected outflow. -Both contracts publish pause-state events and expose an `is_paused` view. +## Lending pool + +The admin designates a guardian with `set_guardian`; the guardian or admin can +`pause()` and only the admin can resume after the same 24-hour timelock. +Pausing blocks `deposit_collateral`, `borrow`, `withdraw_collateral`, +`liquidate`, `flash_loan`, and `stake`. Unstaking, reward claims, and +`emergency_withdraw` remain available. + +`emergency_withdraw` lets a depositor recover collateral that does not back an +outstanding borrow in that token. If debt is still outstanding it reverts with +`LPError::DebtOutstanding` (`15`), so a paused pool cannot be drained by +underwater positions. + +All three contracts publish pause-state events and expose an `is_paused` (or +`paused`) view. diff --git a/docs/deployment/DEPLOYMENT_CHECKLIST.md b/docs/deployment/DEPLOYMENT_CHECKLIST.md index 6fe197d8f..22a46b290 100644 --- a/docs/deployment/DEPLOYMENT_CHECKLIST.md +++ b/docs/deployment/DEPLOYMENT_CHECKLIST.md @@ -232,11 +232,10 @@ soroban events \ ```bash soroban contract invoke \ --id \ - --source \ + --source \ -- \ - set_paused \ - --caller \ - --paused true + pause \ + --caller ``` 2. Investigate issue