diff --git a/contracts/invoice-escrow/src/escrow_timeout.rs b/contracts/invoice-escrow/src/escrow_timeout.rs new file mode 100644 index 00000000..47ddd482 --- /dev/null +++ b/contracts/invoice-escrow/src/escrow_timeout.rs @@ -0,0 +1,221 @@ +//! Escrow timeout and auto-release (issue #1218). +//! +//! An [`EscrowTimeout`] tracks funds held for an invoice and the period after +//! which they are released automatically. Funds can be released in parts +//! before the timeout; once it expires, [`EscrowTimeout::auto_release`] +//! releases whatever is still held, and [`EscrowTimeout::poll_notice`] reports +//! the expiry once so the caller can emit a notification. Not wired to +//! contract storage: callers persist the struct and pass the ledger time. + +#![allow(dead_code)] + +/// Errors returned by timeout operations. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TimeoutError { + /// Amount is zero or negative. + InvalidAmount, + /// Timeout period is zero. + InvalidTimeout, + /// Release amount is larger than what is still held. + ExceedsHeld, + /// The timeout has not expired yet. + NotExpired, + /// Nothing is left to release. + NothingToRelease, +} + +/// Result of an automatic release. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AutoRelease { + /// Amount released by this call. + pub amount: i128, + /// `true` if part of the escrow had already been released before. + pub after_partial: bool, +} + +/// Notification raised once when the timeout expires. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TimeoutNotice { + /// Timestamp at which the timeout expired. + pub expired_at: u64, + /// Amount still held at expiry. + pub outstanding: i128, +} + +/// Timeout state for one escrow. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EscrowTimeout { + held: i128, + released: i128, + started_at: u64, + timeout_secs: u64, + notified: bool, +} + +impl EscrowTimeout { + /// Starts tracking `held` funds at `started_at`, expiring after + /// `timeout_secs`. + pub fn new(held: i128, started_at: u64, timeout_secs: u64) -> Result { + if held <= 0 { + return Err(TimeoutError::InvalidAmount); + } + if timeout_secs == 0 { + return Err(TimeoutError::InvalidTimeout); + } + Ok(Self { + held, + released: 0, + started_at, + timeout_secs, + notified: false, + }) + } + + /// Timestamp at which the timeout expires. + pub fn expires_at(&self) -> u64 { + self.started_at.saturating_add(self.timeout_secs) + } + + /// `true` once `now` has reached the expiry. + pub fn is_expired(&self, now: u64) -> bool { + now >= self.expires_at() + } + + /// Seconds until expiry (0 once expired). + pub fn seconds_left(&self, now: u64) -> u64 { + self.expires_at().saturating_sub(now) + } + + /// Amount still held. + pub fn remaining(&self) -> i128 { + self.held - self.released + } + + /// Amount released so far. + pub fn released(&self) -> i128 { + self.released + } + + /// Releases `amount` of the held funds and returns what is still held. + pub fn release_partial(&mut self, amount: i128) -> Result { + if amount <= 0 { + return Err(TimeoutError::InvalidAmount); + } + if amount > self.remaining() { + return Err(TimeoutError::ExceedsHeld); + } + self.released += amount; + Ok(self.remaining()) + } + + /// Releases everything still held once the timeout has expired. + pub fn auto_release(&mut self, now: u64) -> Result { + if !self.is_expired(now) { + return Err(TimeoutError::NotExpired); + } + let amount = self.remaining(); + if amount == 0 { + return Err(TimeoutError::NothingToRelease); + } + let after_partial = self.released > 0; + self.released = self.held; + Ok(AutoRelease { + amount, + after_partial, + }) + } + + /// Returns the expiry notice the first time it is polled after expiry, + /// then `None`. + pub fn poll_notice(&mut self, now: u64) -> Option { + if self.notified || !self.is_expired(now) { + return None; + } + self.notified = true; + Some(TimeoutNotice { + expired_at: self.expires_at(), + outstanding: self.remaining(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tracks_timeout_period() { + let t = EscrowTimeout::new(1_000, 100, 50).unwrap(); + assert_eq!(t.expires_at(), 150); + assert!(!t.is_expired(149)); + assert!(t.is_expired(150)); + assert_eq!(t.seconds_left(120), 30); + assert_eq!(t.seconds_left(200), 0); + } + + #[test] + fn auto_release_blocked_before_timeout() { + let mut t = EscrowTimeout::new(1_000, 100, 50).unwrap(); + assert_eq!(t.auto_release(149), Err(TimeoutError::NotExpired)); + assert_eq!(t.remaining(), 1_000); + } + + #[test] + fn auto_release_after_timeout_releases_all() { + let mut t = EscrowTimeout::new(1_000, 100, 50).unwrap(); + assert_eq!( + t.auto_release(150), + Ok(AutoRelease { + amount: 1_000, + after_partial: false + }) + ); + assert_eq!(t.remaining(), 0); + assert_eq!(t.auto_release(160), Err(TimeoutError::NothingToRelease)); + } + + #[test] + fn partial_release_then_auto_release_rest() { + let mut t = EscrowTimeout::new(1_000, 100, 50).unwrap(); + assert_eq!(t.release_partial(300), Ok(700)); + assert_eq!( + t.auto_release(200), + Ok(AutoRelease { + amount: 700, + after_partial: true + }) + ); + assert_eq!(t.released(), 1_000); + } + + #[test] + fn notice_sent_once_on_timeout() { + let mut t = EscrowTimeout::new(1_000, 100, 50).unwrap(); + t.release_partial(400).unwrap(); + assert_eq!(t.poll_notice(149), None); + assert_eq!( + t.poll_notice(155), + Some(TimeoutNotice { + expired_at: 150, + outstanding: 600 + }) + ); + assert_eq!(t.poll_notice(160), None); + } + + #[test] + fn rejects_invalid_inputs() { + assert_eq!( + EscrowTimeout::new(0, 0, 10), + Err(TimeoutError::InvalidAmount) + ); + assert_eq!( + EscrowTimeout::new(10, 0, 0), + Err(TimeoutError::InvalidTimeout) + ); + let mut t = EscrowTimeout::new(100, 0, 10).unwrap(); + assert_eq!(t.release_partial(0), Err(TimeoutError::InvalidAmount)); + assert_eq!(t.release_partial(101), Err(TimeoutError::ExceedsHeld)); + assert_eq!(t.remaining(), 100); + } +} diff --git a/contracts/invoice-escrow/src/lib.rs b/contracts/invoice-escrow/src/lib.rs index a2bfec2b..4e9efc87 100644 --- a/contracts/invoice-escrow/src/lib.rs +++ b/contracts/invoice-escrow/src/lib.rs @@ -24,6 +24,8 @@ #![no_std] mod errors; +// Issue #1218: Escrow timeout and auto-release. +mod escrow_timeout; mod oracle; mod types; diff --git a/contracts/split/src/multi_token_distribution.rs b/contracts/split/src/multi_token_distribution.rs new file mode 100644 index 00000000..d1cb8111 --- /dev/null +++ b/contracts/split/src/multi_token_distribution.rs @@ -0,0 +1,304 @@ +//! Multi-token payment distribution (issue #1217). +//! +//! Splits payments in several token assets across the same recipients in one +//! call. Each asset carries its own platform fee (in basis points) and the +//! balance available to pay it; every balance is checked before anything is +//! computed, so either all assets distribute or none do. The net amount of +//! each asset is split by the recipients' shares with the largest-remainder +//! method used in `calc.rs`, so each asset's payouts sum to its net exactly. +//! Not wired to contract storage or token transfers. + +#![allow(dead_code)] + +use crate::calc::calc_platform_fee; +use crate::constants::{MAX_PLATFORM_FEE_BPS, TOTAL_BPS}; +use crate::math::{mul_div, mul_mod, BPS_DENOMINATOR}; + +/// Maximum token assets in one distribution. +pub const MAX_TOKENS: usize = 4; +/// Maximum recipients in one distribution. +pub const MAX_RECIPIENTS: usize = 8; + +/// Errors returned by distribution. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DistributionError { + /// No tokens, or more than [`MAX_TOKENS`]. + InvalidTokenCount, + /// No recipients, more than [`MAX_RECIPIENTS`], or shares not summing to + /// 10 000 bps. + InvalidShares, + /// The same token appears twice. + DuplicateToken, + /// Amount is zero or negative. + InvalidAmount, + /// Fee is above `MAX_PLATFORM_FEE_BPS`. + InvalidFee, + /// Balance is lower than the amount to distribute. + InsufficientBalance, + /// Arithmetic overflowed. + Overflow, +} + +/// One token asset to distribute. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TokenPayment { + /// Token identifier (caller-defined). + pub token: u32, + /// Gross amount to distribute. + pub amount: i128, + /// Platform fee for this token, in basis points. + pub fee_bps: u32, + /// Balance available for this token. + pub balance: i128, +} + +/// Distribution result for one token asset. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TokenPayout { + /// Token identifier. + pub token: u32, + /// Fee deducted from the gross amount. + pub fee: i128, + /// Amount split across recipients (gross minus fee). + pub net: i128, + shares: [i128; MAX_RECIPIENTS], + recipients: usize, +} + +impl TokenPayout { + /// Payout per recipient, in the order of the shares passed in. + pub fn shares(&self) -> &[i128] { + &self.shares[..self.recipients] + } +} + +/// Payouts for every token asset of a distribution. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Distribution { + payouts: [TokenPayout; MAX_TOKENS], + len: usize, +} + +impl Distribution { + /// Payouts in the order the tokens were passed in. + pub fn payouts(&self) -> &[TokenPayout] { + &self.payouts[..self.len] + } + + /// Payout for `token`, if it was part of the distribution. + pub fn get(&self, token: u32) -> Option<&TokenPayout> { + self.payouts().iter().find(|p| p.token == token) + } + + /// Total fee deducted for `token` (0 if absent). + pub fn fee_for(&self, token: u32) -> i128 { + self.get(token).map(|p| p.fee).unwrap_or(0) + } +} + +/// Validates every token's amount, fee and balance against `shares_bps`. +pub fn validate(payments: &[TokenPayment], shares_bps: &[u32]) -> Result<(), DistributionError> { + if payments.is_empty() || payments.len() > MAX_TOKENS { + return Err(DistributionError::InvalidTokenCount); + } + if shares_bps.is_empty() || shares_bps.len() > MAX_RECIPIENTS { + return Err(DistributionError::InvalidShares); + } + let total: u32 = shares_bps + .iter() + .fold(0u32, |acc, s| acc.saturating_add(*s)); + if total != TOTAL_BPS { + return Err(DistributionError::InvalidShares); + } + for (i, p) in payments.iter().enumerate() { + if payments[..i].iter().any(|q| q.token == p.token) { + return Err(DistributionError::DuplicateToken); + } + if p.amount <= 0 { + return Err(DistributionError::InvalidAmount); + } + if p.fee_bps > MAX_PLATFORM_FEE_BPS { + return Err(DistributionError::InvalidFee); + } + if p.balance < p.amount { + return Err(DistributionError::InsufficientBalance); + } + } + Ok(()) +} + +/// Distributes every token in `payments` across recipients by `shares_bps`, +/// after deducting each token's fee. +pub fn distribute( + payments: &[TokenPayment], + shares_bps: &[u32], +) -> Result { + validate(payments, shares_bps)?; + let empty = TokenPayout { + token: 0, + fee: 0, + net: 0, + shares: [0; MAX_RECIPIENTS], + recipients: 0, + }; + let mut out = Distribution { + payouts: [empty; MAX_TOKENS], + len: payments.len(), + }; + for (i, p) in payments.iter().enumerate() { + let fee = + calc_platform_fee(p.amount, p.fee_bps).map_err(|_| DistributionError::Overflow)?; + let net = p.amount - fee; + out.payouts[i] = TokenPayout { + token: p.token, + fee, + net, + shares: split_net(net, shares_bps)?, + recipients: shares_bps.len(), + }; + } + Ok(out) +} + +/// Largest-remainder split of `net` by `shares_bps`; ties go to the lower +/// index. +fn split_net(net: i128, shares_bps: &[u32]) -> Result<[i128; MAX_RECIPIENTS], DistributionError> { + let mut shares = [0i128; MAX_RECIPIENTS]; + let mut rems = [0i128; MAX_RECIPIENTS]; + let mut assigned = 0i128; + for (i, s) in shares_bps.iter().enumerate() { + shares[i] = + mul_div(net, *s as i128, BPS_DENOMINATOR).map_err(|_| DistributionError::Overflow)?; + rems[i] = + mul_mod(net, *s as i128, BPS_DENOMINATOR).map_err(|_| DistributionError::Overflow)?; + assigned += shares[i]; + } + let mut leftover = net - assigned; + let mut given = [false; MAX_RECIPIENTS]; + while leftover > 0 { + let mut best = 0usize; + let mut found = false; + for i in 0..shares_bps.len() { + if !given[i] && (!found || rems[i] > rems[best]) { + best = i; + found = true; + } + } + if !found { + break; + } + shares[best] += 1; + given[best] = true; + leftover -= 1; + } + Ok(shares) +} + +#[cfg(test)] +mod tests { + use super::*; + + const XLM: u32 = 1; + const USDC: u32 = 2; + + fn pay(token: u32, amount: i128, fee_bps: u32) -> TokenPayment { + TokenPayment { + token, + amount, + fee_bps, + balance: amount, + } + } + + #[test] + fn distributes_each_token() { + let d = distribute(&[pay(XLM, 1_000, 0), pay(USDC, 2_000, 0)], &[6_000, 4_000]).unwrap(); + assert_eq!(d.payouts().len(), 2); + assert_eq!(d.get(XLM).unwrap().shares(), &[600, 400]); + assert_eq!(d.get(USDC).unwrap().shares(), &[1_200, 800]); + } + + #[test] + fn fees_calculated_per_token() { + let d = distribute(&[pay(XLM, 10_000, 100), pay(USDC, 10_000, 250)], &[10_000]).unwrap(); + assert_eq!(d.fee_for(XLM), 100); + assert_eq!(d.fee_for(USDC), 250); + assert_eq!(d.get(XLM).unwrap().net, 9_900); + assert_eq!(d.get(USDC).unwrap().shares(), &[9_750]); + } + + #[test] + fn payouts_sum_to_net() { + let d = distribute(&[pay(XLM, 10, 0)], &[3_334, 3_333, 3_333]).unwrap(); + let p = d.get(XLM).unwrap(); + assert_eq!(p.shares(), &[4, 3, 3]); + assert_eq!(p.shares().iter().sum::(), p.net); + } + + #[test] + fn insufficient_balance_rejected() { + let mut short = pay(USDC, 500, 0); + short.balance = 499; + assert_eq!( + distribute(&[pay(XLM, 100, 0), short], &[10_000]), + Err(DistributionError::InsufficientBalance) + ); + } + + #[test] + fn invalid_shares_rejected() { + let p = [pay(XLM, 100, 0)]; + assert_eq!( + distribute(&p, &[5_000]), + Err(DistributionError::InvalidShares) + ); + assert_eq!(distribute(&p, &[]), Err(DistributionError::InvalidShares)); + assert_eq!( + distribute(&p, &[1_250; MAX_RECIPIENTS + 1]), + Err(DistributionError::InvalidShares) + ); + } + + #[test] + fn duplicate_and_token_count_rejected() { + assert_eq!( + distribute(&[pay(XLM, 1, 0), pay(XLM, 2, 0)], &[10_000]), + Err(DistributionError::DuplicateToken) + ); + assert_eq!( + distribute(&[], &[10_000]), + Err(DistributionError::InvalidTokenCount) + ); + let many = [ + pay(1, 1, 0), + pay(2, 1, 0), + pay(3, 1, 0), + pay(4, 1, 0), + pay(5, 1, 0), + ]; + assert_eq!( + distribute(&many, &[10_000]), + Err(DistributionError::InvalidTokenCount) + ); + } + + #[test] + fn invalid_amount_and_fee_rejected() { + assert_eq!( + distribute(&[pay(XLM, 0, 0)], &[10_000]), + Err(DistributionError::InvalidAmount) + ); + assert_eq!( + distribute(&[pay(XLM, 100, MAX_PLATFORM_FEE_BPS + 1)], &[10_000]), + Err(DistributionError::InvalidFee) + ); + } + + #[test] + fn single_token_matches_multi_token() { + let one = distribute(&[pay(USDC, 7_777, 30)], &[2_500, 7_500]).unwrap(); + let both = + distribute(&[pay(XLM, 1_234, 0), pay(USDC, 7_777, 30)], &[2_500, 7_500]).unwrap(); + assert_eq!(one.get(USDC), both.get(USDC)); + } +} diff --git a/contracts/split/src/upgrade_toolkit.rs b/contracts/split/src/upgrade_toolkit.rs new file mode 100644 index 00000000..9ab0b6b8 --- /dev/null +++ b/contracts/split/src/upgrade_toolkit.rs @@ -0,0 +1,261 @@ +//! Contract upgrade and migration toolkit (issue #1192). +//! +//! Pure helpers around the upgrade flow in `docs/UPGRADE_MIGRATION_GUIDE.md` +//! and the schema migrations in `migrations.rs`: +//! +//! - [`plan_migration`] checks a stored schema version against a target and +//! lists the `migration_vN` steps that `migrate` will run. +//! - [`MigrationCursor`] splits an invoice id range into fixed-size batches, +//! for migrations too large for one transaction. +//! - [`next_action`] maps what an operator reads from the contract views to +//! the next upgrade call, so a script can drive the upgrade step by step. +//! +//! See `docs/UPGRADE_TOOLKIT.md` for usage and examples. Not wired to contract +//! storage: callers pass in the values they read. + +#![allow(dead_code)] + +use crate::migrations::CURRENT_SCHEMA_VERSION; + +/// Default number of invoice ids processed per migration batch. +pub const DEFAULT_BATCH_SIZE: u64 = 50; + +/// Errors returned by toolkit helpers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToolkitError { + /// Target schema is lower than the stored one; migrations only go forward. + Downgrade, + /// Target schema is newer than this build understands. + UnknownTarget, + /// Batch size is zero. + InvalidBatch, +} + +/// The migration steps between two schema versions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MigrationPlan { + /// Schema version stored on chain. + pub from: u32, + /// Schema version after all steps have run. + pub to: u32, +} + +impl MigrationPlan { + /// Number of `migration_vN` steps to run. + pub fn step_count(&self) -> u32 { + self.to - self.from + } + + /// `true` when the stored schema is already at the target. + pub fn is_noop(&self) -> bool { + self.from == self.to + } + + /// Target version of the `index`-th step (0-based), i.e. the `N` of the + /// `migration_vN` that runs, or `None` past the last step. + pub fn step(&self, index: u32) -> Option { + if index < self.step_count() { + Some(self.from + index + 1) + } else { + None + } + } +} + +/// Plans the migration from `stored` to `target`. A stored version of 0 is +/// treated as 1, matching `migrations::schema_version` for contracts that +/// never wrote the key. +pub fn plan_migration(stored: u32, target: u32) -> Result { + let from = stored.max(1); + if target > CURRENT_SCHEMA_VERSION { + return Err(ToolkitError::UnknownTarget); + } + if from > target { + return Err(ToolkitError::Downgrade); + } + Ok(MigrationPlan { from, to: target }) +} + +/// Walks invoice ids `1..=last_id` in batches of `batch` ids. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MigrationCursor { + next_id: u64, + last_id: u64, + batch: u64, +} + +impl MigrationCursor { + /// Creates a cursor over `1..=last_id` (the invoice counter holds the + /// highest assigned id). + pub fn new(last_id: u64, batch: u64) -> Result { + Self::resume(1, last_id, batch) + } + + /// Resumes a cursor at `next_id`, e.g. from a stored checkpoint. + pub fn resume(next_id: u64, last_id: u64, batch: u64) -> Result { + if batch == 0 { + return Err(ToolkitError::InvalidBatch); + } + Ok(Self { + next_id: next_id.max(1), + last_id, + batch, + }) + } + + /// Next id to process; store it to resume later. + pub fn next_id(&self) -> u64 { + self.next_id + } + + /// `true` once every id has been handed out. + pub fn is_done(&self) -> bool { + self.next_id > self.last_id + } + + /// Ids not yet handed out. + pub fn remaining(&self) -> u64 { + if self.is_done() { + 0 + } else { + self.last_id - self.next_id + 1 + } + } + + /// Returns the next inclusive `(start, end)` range and advances, or `None` + /// when done. + pub fn next_range(&mut self) -> Option<(u64, u64)> { + if self.is_done() { + return None; + } + let start = self.next_id; + let end = start.saturating_add(self.batch - 1).min(self.last_id); + self.next_id = end.saturating_add(1); + Some((start, end)) + } +} + +/// What an operator reads from the contract before deciding the next step. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UpgradeSnapshot { + /// The deployed WASM is the new build. + pub upgraded: bool, + /// `get_upgrade_proposal` returned a proposal. + pub proposal_pending: bool, + /// `eligible_at` of the pending proposal. + pub eligible_at: u64, + /// Current ledger timestamp. + pub now: u64, + /// `get_schema_version`. + pub stored_schema: u32, + /// Schema version the new build expects. + pub target_schema: u32, + /// `get_upgrade_checkpoint` returned a hash. + pub frozen: bool, +} + +/// The next upgrade call to make. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UpgradeAction { + /// Call `propose_upgrade`. + Propose, + /// Wait until `eligible_at`. + WaitTimelock, + /// Call `execute_upgrade`. + Execute, + /// Call `migrate`. + Migrate, + /// Call `thaw_contract`. + Thaw, + /// Nothing left to do; run the post-upgrade checks. + Done, +} + +/// Returns the next step of the upgrade flow for `s`. +pub fn next_action(s: &UpgradeSnapshot) -> UpgradeAction { + if !s.upgraded { + if !s.proposal_pending { + UpgradeAction::Propose + } else if s.now < s.eligible_at { + UpgradeAction::WaitTimelock + } else { + UpgradeAction::Execute + } + } else if s.stored_schema.max(1) < s.target_schema { + UpgradeAction::Migrate + } else if s.frozen { + UpgradeAction::Thaw + } else { + UpgradeAction::Done + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plans_pending_steps() { + let p = plan_migration(1, CURRENT_SCHEMA_VERSION).unwrap(); + assert_eq!(p.from, 1); + assert_eq!(p.step_count(), CURRENT_SCHEMA_VERSION - 1); + assert_eq!(p.step(0), Some(2)); + assert_eq!(p.step(p.step_count()), None); + assert!( + plan_migration(CURRENT_SCHEMA_VERSION, CURRENT_SCHEMA_VERSION) + .unwrap() + .is_noop() + ); + assert_eq!(plan_migration(0, 1).unwrap().from, 1); + } + + #[test] + fn rejects_bad_targets() { + assert_eq!(plan_migration(3, 2), Err(ToolkitError::Downgrade)); + assert_eq!( + plan_migration(1, CURRENT_SCHEMA_VERSION + 1), + Err(ToolkitError::UnknownTarget) + ); + } + + #[test] + fn cursor_batches_and_resumes() { + let mut c = MigrationCursor::new(7, 3).unwrap(); + assert_eq!(c.remaining(), 7); + assert_eq!(c.next_range(), Some((1, 3))); + assert_eq!(c.next_range(), Some((4, 6))); + let saved = c.next_id(); + let mut r = MigrationCursor::resume(saved, 7, 3).unwrap(); + assert_eq!(r.next_range(), Some((7, 7))); + assert!(r.is_done()); + assert_eq!(r.next_range(), None); + assert_eq!(MigrationCursor::new(0, 3).unwrap().next_range(), None); + assert_eq!(MigrationCursor::new(5, 0), Err(ToolkitError::InvalidBatch)); + } + + #[test] + fn next_action_follows_flow() { + let mut s = UpgradeSnapshot { + upgraded: false, + proposal_pending: false, + eligible_at: 0, + now: 100, + stored_schema: 2, + target_schema: 3, + frozen: true, + }; + assert_eq!(next_action(&s), UpgradeAction::Propose); + s.proposal_pending = true; + s.eligible_at = 200; + assert_eq!(next_action(&s), UpgradeAction::WaitTimelock); + s.now = 200; + assert_eq!(next_action(&s), UpgradeAction::Execute); + s.upgraded = true; + s.proposal_pending = false; + assert_eq!(next_action(&s), UpgradeAction::Migrate); + s.stored_schema = 3; + assert_eq!(next_action(&s), UpgradeAction::Thaw); + s.frozen = false; + assert_eq!(next_action(&s), UpgradeAction::Done); + } +} diff --git a/docs/INCIDENT_RESPONSE_PLAYBOOK.md b/docs/INCIDENT_RESPONSE_PLAYBOOK.md new file mode 100644 index 00000000..73121988 --- /dev/null +++ b/docs/INCIDENT_RESPONSE_PLAYBOOK.md @@ -0,0 +1,161 @@ +# Incident response playbook + +What to do when something goes wrong with a deployed `split` contract: who acts, which entry points to +call, and how to recover. Every call below exists in `contracts/split/src/lib.rs` today. + +## Roles + +| Role | Can do in an incident | +|---|---| +| Admin (the `admin_key` address) | `pause`, `unpause`, `propose_upgrade`, `cancel_upgrade`, `propose_admin` | +| Operator | `pause` and `unpause` (when no single admin is stored), `pause_function`, `unpause_function`, `set_pause_exempt` | +| SuperAdmin | The Operator calls above, plus `freeze_for_upgrade`, `thaw_contract`, `migrate`, `add_admin`, `remove_admin`, `set_sweep_timeout`, `sweep_unclaimed_funds` | + +Keep the keys for at least two SuperAdmins reachable at all times. `remove_admin` refuses to remove the +last SuperAdmin. + +## Procedure + +Every incident follows the same five steps. + +1. **Detect.** An alert, a user report, or an unexpected event. Note the time, ledger, and transaction + hashes. +2. **Contain.** Stop the damage first, investigate second. Use the smallest switch that does it: + + | Scope | Call | Effect | + |---|---|---| + | One entry point | `pause_function(admin, fn_name)` | That function panics with `function paused` | + | All guarded writes | `pause(admin)` | Entry points that check the pause flag fail with `ContractPaused` | + | Everything except admin actions, during an upgrade | `freeze_for_upgrade(admin, checkpoint_hash)` | Writes that call `require_not_frozen` fail | + +3. **Assess.** Work out which invoices, tokens, and addresses are affected, and whether funds left the + contract. Read-only calls such as `is_paused`, `get_schema_version`, `get_failed_payouts` and + `get_upgrade_proposal` work while the contract is paused. +4. **Recover.** Follow the matching scenario below. +5. **Review.** Unpause, watch the contract for a while, and write up the incident (see the template at the + end). + +## Scenarios + +### 1. Bug in a payment or release path + +- **Signs:** wrong amounts paid out, a release that should have failed, an invariant broken. +- **Contain:** `pause_function(admin, "")` for the affected entry point, or `pause(admin)` if the + bug can be reached from several. +- **Recover:** + 1. Fix the bug and test the new build (`cargo test --workspace`). + 2. Upgrade as described in [`UPGRADE_MIGRATION_GUIDE.md`](./UPGRADE_MIGRATION_GUIDE.md). The 48 hour + timelock still applies, so the contract stays paused meanwhile. + 3. After `execute_upgrade`, run `migrate(admin)` if the schema changed. + 4. `unpause_function` / `unpause`. + +### 2. Compromised admin key + +- **Signs:** admin calls nobody on the team made, an unexpected `propose_upgrade` or `propose_admin`. +- **Contain:** from a SuperAdmin key that is still safe, `pause(admin)`. If an upgrade was proposed, call + `cancel_upgrade(admin)` before its `eligible_at`. +- **Recover:** + 1. `remove_admin(admin, compromised)` from a safe SuperAdmin. + 2. If the compromised address is the stored admin, move it with `propose_admin(admin, new_admin)` and + `accept_admin()` signed by the new address. + 3. Check `set_treasury`, `add_allowed_token`, `add_trusted_caller` and fee settings for changes the + attacker made, and revert them. + 4. `unpause(admin)`. + +### 3. Failed payouts to recipients + +- **Signs:** `get_failed_payouts(invoice_id)` returns addresses, usually accounts that did not exist on the + ledger at release time. +- **Contain:** nothing to stop; the funds stay in the contract. +- **Recover:** + 1. Ask the recipient to create the account, then call `retry_failed_payout(invoice_id, recipient)`. + 2. If the recipient never appears, a SuperAdmin calls `sweep_unclaimed_funds(admin, invoice_id)` once the + sweep timeout has passed since the last failure (default 120 960 ledgers, set with + `set_sweep_timeout`). + +### 4. Upgrade went wrong + +- **Signs:** every call panics with `MigrationRequired`, reads panic on decode, or the new build misbehaves. +- **Contain:** `pause(admin)`, or `freeze_for_upgrade` if not already frozen. +- **Recover:** + 1. `MigrationRequired`: a SuperAdmin calls `migrate(admin)` and checks `get_schema_version()`. + 2. `migrate` keeps failing: a step is too large for one transaction. See "A migration must fit in one + transaction" in the upgrade guide. + 3. The new build misbehaves: propose the previous WASM hash, as in the guide's rollback section. + 4. `thaw_contract(admin)` and `unpause(admin)` once the checks pass. + +### 5. Problem with a token + +- **Signs:** a token contract misbehaves, is upgraded maliciously, or is reported as compromised. +- **Contain:** `remove_allowed_token(admin, token)` so no new invoice uses it. Pause the payment entry + points if existing invoices in that token are at risk. +- **Recover:** settle or refund the affected invoices once the token is safe again, then add it back with + `add_allowed_token` if wanted. + +## Automation + +All calls go through the Stellar CLI, so a runbook can be scripted. Set the variables once: + +```sh +CONTRACT= +NETWORK=mainnet +ADMIN= +ADMIN_ADDR=$(stellar keys address "$ADMIN") + +invoke() { + stellar contract invoke --id "$CONTRACT" --network "$NETWORK" --source "$ADMIN" -- "$@" +} +``` + +Contain: + +```sh +invoke pause --admin "$ADMIN_ADDR" +invoke pause_function --admin "$ADMIN_ADDR" --function release +invoke cancel_upgrade --admin "$ADMIN_ADDR" +``` + +Check state: + +```sh +invoke is_paused +invoke get_schema_version +invoke get_upgrade_proposal +invoke get_failed_payouts --invoice_id 42 +``` + +Recover: + +```sh +invoke migrate --admin "$ADMIN_ADDR" +invoke retry_failed_payout --invoice_id 42 --recipient
+invoke thaw_contract --admin "$ADMIN_ADDR" +invoke unpause_function --admin "$ADMIN_ADDR" --function release +invoke unpause --admin "$ADMIN_ADDR" +``` + +Contract events (`contract_paused`, `contract_unpaused`, upgrade and admin-transfer events) can be watched +with `stellar events --id "$CONTRACT"` to alert on admin actions nobody on the team made. + +## Checklist + +- [ ] Incident time, ledger and transaction hashes written down +- [ ] Contained with the smallest switch that stops the damage +- [ ] Affected invoices, tokens and addresses listed +- [ ] Fix tested on a copy of the data before mainnet +- [ ] Contract unpaused / thawed and watched afterwards +- [ ] Write-up done + +## Write-up template + +```text +Title: +Detected at (time, ledger): +Contained at (time, call): +Resolved at: +What happened: +Impact (invoices, amounts, users): +Root cause: +Recovery steps taken: +Follow-ups: +``` diff --git a/docs/UPGRADE_TOOLKIT.md b/docs/UPGRADE_TOOLKIT.md new file mode 100644 index 00000000..1cadb020 --- /dev/null +++ b/docs/UPGRADE_TOOLKIT.md @@ -0,0 +1,126 @@ +# Upgrade migration toolkit + +Helpers and runbook for upgrading a deployed `split` contract. The upgrade flow itself is described in +[`UPGRADE_MIGRATION_GUIDE.md`](./UPGRADE_MIGRATION_GUIDE.md). This page covers the toolkit in +`contracts/split/src/upgrade_toolkit.rs`, the existing migrations, and how to script an upgrade. + +## Migrations + +`CURRENT_SCHEMA_VERSION` in `contracts/split/src/migrations.rs` is 3. `migrate(admin)` runs every step +between the stored version and that one, in order. + +| Step | From → to | What it does | Idempotent because | +|---|---|---|---| +| `migration_v2` | 1 → 2 | Writes a default `InvoiceMeta` (`note = ""`, `priority = 0`) under `inv_meta` for every existing invoice id | Skips ids that already have a record | +| `migration_v3` | 2 → 3 | Moves each `InvoiceMeta` from `inv_meta` to `inv_note` and removes the old key | Only ids still under `inv_meta` are moved | + +A contract that never wrote `schm_ver` reads as version 1. A fresh `initialize` stamps version 3, so new +deployments run no migration. + +Per-invoice legacy records (no `version` field) are upgraded one at a time with +`migrate_invoice(admin, invoice_id)`, which is a no-op for an invoice that is already current. + +## Utilities + +All helpers are pure functions: pass in the values read from the contract views. + +### `plan_migration(stored, target)` + +Returns a `MigrationPlan` with the steps `migrate` will run, or an error: + +- `Downgrade` if `target` is below `stored`. Migrations only go forward; see the rollback section of the + guide. +- `UnknownTarget` if `target` is above `CURRENT_SCHEMA_VERSION` of the build you are using. + +```rust +let plan = plan_migration(1, 3)?; +assert_eq!(plan.step_count(), 2); +assert_eq!(plan.step(0), Some(2)); // migration_v2 runs first +assert_eq!(plan.step(1), Some(3)); // then migration_v3 +``` + +### `MigrationCursor` + +Splits invoice ids `1..=last_id` into batches, for a migration step that is too large for one transaction. +`last_id` is the invoice counter (`peek_next_invoice_id` minus one). Store `next_id()` between calls and +rebuild the cursor with `MigrationCursor::resume`. + +```rust +let mut cursor = MigrationCursor::new(last_id, DEFAULT_BATCH_SIZE)?; +while let Some((start, end)) = cursor.next_range() { + // migrate ids start..=end in one transaction +} +``` + +### `next_action(&UpgradeSnapshot)` + +Maps the contract state to the next upgrade call: + +| State | `UpgradeAction` | Call | +|---|---|---| +| New WASM not deployed, no proposal | `Propose` | `propose_upgrade(admin, hash)` | +| Proposal pending, `now < eligible_at` | `WaitTimelock` | none, wait | +| Proposal pending, timelock elapsed | `Execute` | `execute_upgrade()` | +| New WASM deployed, `get_schema_version` behind | `Migrate` | `migrate(admin)` | +| Migrated, checkpoint still set | `Thaw` | `thaw_contract(admin)` | +| Otherwise | `Done` | run the post-upgrade checks | + +## Automation + +A script can drive an upgrade by reading the views, calling `next_action`, and making the matching call +until it returns `Done`. The view calls with the Stellar CLI: + +```sh +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" -- get_upgrade_proposal +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" -- get_schema_version +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" -- get_upgrade_checkpoint +``` + +The write calls: + +```sh +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" --source "$ADMIN" -- \ + propose_upgrade --admin "$ADMIN_ADDR" --new_wasm_hash "$NEW_HASH" +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" --source "$ADMIN" -- execute_upgrade +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" --source "$ADMIN" -- migrate --admin "$ADMIN_ADDR" +stellar contract invoke --id "$CONTRACT" --network "$NETWORK" --source "$ADMIN" -- thaw_contract --admin "$ADMIN_ADDR" +``` + +`upgraded` in the snapshot is known to the script: it is true once `execute_upgrade` has succeeded for the +new hash. Keep the previous WASM hash before proposing, as the guide's rollback section explains. + +## Examples + +### Upgrade from schema 1 with no freeze + +```text +plan_migration(1, 3) -> steps v2, v3 +next_action(...) -> Propose -> propose_upgrade +next_action(...) -> WaitTimelock (48 hours) +next_action(...) -> Execute -> execute_upgrade +next_action(...) -> Migrate -> migrate, returns 3 +next_action(...) -> Done +``` + +### Frozen upgrade + +```text +freeze_for_upgrade(admin, checkpoint) +propose_upgrade / wait / execute_upgrade +migrate(admin) -> schema current +next_action(...) -> Thaw -> thaw_contract +next_action(...) -> Done +``` + +### Batching a new migration step + +A new `migration_vN` that walks every invoice can take its id range from a cursor, with the cursor's +`next_id()` stored between calls and the schema version bumped only after the last range: + +```text +MigrationCursor::new(last_id = 120, batch = 50) + next_range() -> (1, 50) + next_range() -> (51, 100) + next_range() -> (101, 120) + next_range() -> None, bump the schema version +```