diff --git a/contracts/split/src/escrow_arbitration.rs b/contracts/split/src/escrow_arbitration.rs new file mode 100644 index 0000000..9087ea3 --- /dev/null +++ b/contracts/split/src/escrow_arbitration.rs @@ -0,0 +1,282 @@ +//! Issue #1184: arbitrated escrow for disputed invoices (first slice). +//! +//! Pure helpers: a dispute stage machine, arbiter assignment from a candidate +//! pool (never a party to the dispute), bounded evidence submission per side, +//! an escrow lock check, ruling-based division of the escrowed amount and +//! dispute counters. + +use soroban_sdk::Address; + +/// Maximum evidence items each side may submit. +pub const MAX_EVIDENCE_PER_SIDE: u32 = 10; + +/// Maximum arbiter candidates considered per assignment. +pub const MAX_ARBITER_CANDIDATES: usize = 20; + +const BPS_DENOMINATOR: i128 = 10_000; + +/// Dispute lifecycle, in order. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum DisputeStage { + /// Raised; waiting for an arbiter. + Open, + /// Arbiter assigned; both sides may submit evidence. + Evidence, + /// Evidence closed; arbiter is deciding. + Deliberation, + /// Ruling issued; escrow may be paid out. + Resolved, +} + +/// Side of the dispute. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Party { + /// Invoice creator (payee). + Creator, + /// Payer. + Payer, +} + +/// Errors for arbitration helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ArbitrationError { + /// Action not allowed in the current stage. + WrongStage, + /// Evidence window has not closed yet. + EvidenceWindowOpen, + /// Evidence window has closed. + EvidenceWindowClosed, + /// Side reached [`MAX_EVIDENCE_PER_SIDE`]. + EvidenceLimit, + /// No eligible arbiter in the pool. + NoEligibleArbiter, + /// Too many candidates supplied. + TooManyCandidates, + /// Ruling bps above 10_000. + InvalidRuling, + /// Escrowed amount is negative. + InvalidAmount, + /// Arithmetic overflow. + Overflow, +} + +/// Picks an arbiter from `candidates`, skipping the creator and payer. +/// `seed` selects among eligible candidates (e.g. the invoice id). +pub fn assign_arbiter( + candidates: &[Address], + creator: &Address, + payer: &Address, + seed: u64, +) -> Result { + if candidates.len() > MAX_ARBITER_CANDIDATES { + return Err(ArbitrationError::TooManyCandidates); + } + let eligible = |a: &&Address| *a != creator && *a != payer; + let count = candidates.iter().filter(eligible).count(); + if count == 0 { + return Err(ArbitrationError::NoEligibleArbiter); + } + let pick = (seed % count as u64) as usize; + Ok(candidates.iter().filter(eligible).nth(pick).unwrap().clone()) +} + +/// Moves `Open` to `Evidence` once an arbiter is assigned. +pub fn start_evidence(stage: DisputeStage) -> Result { + match stage { + DisputeStage::Open => Ok(DisputeStage::Evidence), + _ => Err(ArbitrationError::WrongStage), + } +} + +/// Moves `Evidence` to `Deliberation` once `now` reaches `evidence_deadline`. +pub fn close_evidence( + stage: DisputeStage, + now: u64, + evidence_deadline: u64, +) -> Result { + if stage != DisputeStage::Evidence { + return Err(ArbitrationError::WrongStage); + } + if now < evidence_deadline { + return Err(ArbitrationError::EvidenceWindowOpen); + } + Ok(DisputeStage::Deliberation) +} + +/// Evidence counts per side. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct EvidenceLog { + /// Items submitted by the creator. + pub creator_items: u32, + /// Items submitted by the payer. + pub payer_items: u32, +} + +impl EvidenceLog { + /// Records one evidence item from `party`. Allowed only in the + /// `Evidence` stage before `evidence_deadline`. + pub fn submit( + &mut self, + stage: DisputeStage, + party: Party, + now: u64, + evidence_deadline: u64, + ) -> Result<(), ArbitrationError> { + if stage != DisputeStage::Evidence { + return Err(ArbitrationError::WrongStage); + } + if now >= evidence_deadline { + return Err(ArbitrationError::EvidenceWindowClosed); + } + let count = match party { + Party::Creator => &mut self.creator_items, + Party::Payer => &mut self.payer_items, + }; + if *count >= MAX_EVIDENCE_PER_SIDE { + return Err(ArbitrationError::EvidenceLimit); + } + *count += 1; + Ok(()) + } +} + +/// True when escrowed funds may leave the contract: never while a dispute +/// is unresolved. +pub fn escrow_releasable(stage: DisputeStage) -> bool { + stage == DisputeStage::Resolved +} + +/// Division of the escrowed amount decided by a ruling. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RulingPayout { + /// Returned to the payer. + pub to_payer: i128, + /// Paid to the creator. + pub to_creator: i128, +} + +/// Issues a ruling in `Deliberation`: the payer receives `payer_bps` of +/// `escrowed` (rounded down) and the creator the rest. Returns the payout +/// and the `Resolved` stage. +pub fn issue_ruling( + stage: DisputeStage, + escrowed: i128, + payer_bps: u32, +) -> Result<(RulingPayout, DisputeStage), ArbitrationError> { + if stage != DisputeStage::Deliberation { + return Err(ArbitrationError::WrongStage); + } + if payer_bps as i128 > BPS_DENOMINATOR { + return Err(ArbitrationError::InvalidRuling); + } + if escrowed < 0 { + return Err(ArbitrationError::InvalidAmount); + } + let to_payer = escrowed + .checked_mul(payer_bps as i128) + .ok_or(ArbitrationError::Overflow)? + / BPS_DENOMINATOR; + Ok(( + RulingPayout { to_payer, to_creator: escrowed - to_payer }, + DisputeStage::Resolved, + )) +} + +/// Dispute counters. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct DisputeStats { + /// Disputes raised. + pub opened: u32, + /// Disputes resolved. + pub resolved: u32, + /// Rulings giving the payer more than half. + pub favoured_payer: u32, + /// Rulings giving the creator at least half. + pub favoured_creator: u32, +} + +impl DisputeStats { + /// Records a newly raised dispute (saturating). + pub fn record_opened(&mut self) { + self.opened = self.opened.saturating_add(1); + } + + /// Records a ruling (saturating). + pub fn record_ruling(&mut self, payout: &RulingPayout) { + self.resolved = self.resolved.saturating_add(1); + if payout.to_payer > payout.to_creator { + self.favoured_payer = self.favoured_payer.saturating_add(1); + } else { + self.favoured_creator = self.favoured_creator.saturating_add(1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use soroban_sdk::testutils::Address as _; + use soroban_sdk::Env; + + #[test] + fn arbiter_is_never_a_party() { + let env = Env::default(); + let creator = Address::generate(&env); + let payer = Address::generate(&env); + let arb = Address::generate(&env); + let pool = [creator.clone(), payer.clone(), arb.clone()]; + for seed in 0..5 { + assert_eq!(assign_arbiter(&pool, &creator, &payer, seed).unwrap(), arb); + } + assert_eq!( + assign_arbiter(&pool[..2], &creator, &payer, 0), + Err(ArbitrationError::NoEligibleArbiter) + ); + } + + #[test] + fn full_lifecycle() { + let stage = start_evidence(DisputeStage::Open).unwrap(); + assert!(!escrow_releasable(stage)); + + let mut log = EvidenceLog::default(); + log.submit(stage, Party::Payer, 10, 100).unwrap(); + log.submit(stage, Party::Creator, 20, 100).unwrap(); + assert_eq!(log, EvidenceLog { creator_items: 1, payer_items: 1 }); + assert_eq!( + log.submit(stage, Party::Payer, 100, 100), + Err(ArbitrationError::EvidenceWindowClosed) + ); + + assert_eq!(close_evidence(stage, 50, 100), Err(ArbitrationError::EvidenceWindowOpen)); + let stage = close_evidence(stage, 100, 100).unwrap(); + assert_eq!(stage, DisputeStage::Deliberation); + + let (payout, stage) = issue_ruling(stage, 1_001, 7_000).unwrap(); + assert_eq!(payout, RulingPayout { to_payer: 700, to_creator: 301 }); + assert!(escrow_releasable(stage)); + + let mut stats = DisputeStats::default(); + stats.record_opened(); + stats.record_ruling(&payout); + assert_eq!(stats.favoured_payer, 1); + assert_eq!(stats.resolved, 1); + } + + #[test] + fn evidence_limit_and_bad_ruling() { + let mut log = EvidenceLog::default(); + for _ in 0..MAX_EVIDENCE_PER_SIDE { + log.submit(DisputeStage::Evidence, Party::Creator, 0, 1).unwrap(); + } + assert_eq!( + log.submit(DisputeStage::Evidence, Party::Creator, 0, 1), + Err(ArbitrationError::EvidenceLimit) + ); + assert_eq!( + issue_ruling(DisputeStage::Deliberation, 100, 10_001), + Err(ArbitrationError::InvalidRuling) + ); + assert_eq!(issue_ruling(DisputeStage::Evidence, 100, 0), Err(ArbitrationError::WrongStage)); + } +} diff --git a/contracts/split/src/lib.rs b/contracts/split/src/lib.rs index 888d6f6..9ee0109 100644 --- a/contracts/split/src/lib.rs +++ b/contracts/split/src/lib.rs @@ -91,6 +91,9 @@ pub mod payment_tracking; pub mod velocity; mod invoice_compliance_checklist; pub mod split_rules; +mod split_strategies; +mod escrow_arbitration; +mod tiered_refund; pub mod pool; mod batch_verify; pub mod compression; diff --git a/contracts/split/src/split_strategies.rs b/contracts/split/src/split_strategies.rs new file mode 100644 index 0000000..f1c259d --- /dev/null +++ b/contracts/split/src/split_strategies.rs @@ -0,0 +1,250 @@ +//! Issue #1186: payment splitting strategies (first slice). +//! +//! Pure helpers: split an amount across recipients with an equal, weighted +//! or waterfall strategy, pick a strategy from conditional rules, and count +//! completed splits with [`SplitTracker`]. + +/// Maximum number of recipients per split. +pub const MAX_SPLIT_RECIPIENTS: usize = 50; + +/// Maximum number of strategy rules evaluated per selection. +pub const MAX_STRATEGY_RULES: usize = 20; + +const BPS_DENOMINATOR: i128 = 10_000; + +/// How an amount is divided between recipients. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SplitStrategy { + /// Same share for everyone; leftover units go to the earliest recipients. + Equal, + /// Share proportional to `params[i]` in bps (must sum to 10_000); + /// rounding dust goes to the earliest recipients with a non-zero weight. + Weighted, + /// Recipients are filled in order, each up to its cap `params[i]`. + Waterfall, +} + +/// Errors for split helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SplitError { + /// Amount must be positive. + InvalidAmount, + /// No recipients supplied. + NoRecipients, + /// More than [`MAX_SPLIT_RECIPIENTS`] recipients. + TooManyRecipients, + /// `params` and `out` lengths differ. + LengthMismatch, + /// Weights are negative or do not sum to 10_000. + InvalidWeights, + /// A waterfall cap is negative. + InvalidCap, + /// Too many rules supplied. + TooManyRules, + /// No rule matched. + NoMatch, + /// Arithmetic overflow. + Overflow, +} + +/// Condition under which a strategy rule applies. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum StrategyCondition { + /// Always matches. + Always, + /// Matches when amount >= value. + AmountAtLeast(i128), + /// Matches when amount < value. + AmountBelow(i128), +} + +/// Chooses `strategy` when `condition` holds. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct StrategyRule { + /// Condition to evaluate. + pub condition: StrategyCondition, + /// Strategy used when matched. + pub strategy: SplitStrategy, +} + +/// Returns true when `condition` holds for `amount`. +pub fn condition_matches(condition: StrategyCondition, amount: i128) -> bool { + match condition { + StrategyCondition::Always => true, + StrategyCondition::AmountAtLeast(v) => amount >= v, + StrategyCondition::AmountBelow(v) => amount < v, + } +} + +/// Returns the strategy of the first rule whose condition matches `amount`. +pub fn select_strategy(rules: &[StrategyRule], amount: i128) -> Result { + if rules.len() > MAX_STRATEGY_RULES { + return Err(SplitError::TooManyRules); + } + rules + .iter() + .find(|r| condition_matches(r.condition, amount)) + .map(|r| r.strategy) + .ok_or(SplitError::NoMatch) +} + +/// Splits `amount` into `out` using `strategy`. `params` holds the weights +/// (Weighted) or caps (Waterfall) and is ignored for Equal, but must have the +/// same length as `out`. Returns the undistributed remainder, which is only +/// non-zero for Waterfall when the caps total less than `amount`. +pub fn apply_strategy( + strategy: SplitStrategy, + amount: i128, + params: &[i128], + out: &mut [i128], +) -> Result { + if amount <= 0 { + return Err(SplitError::InvalidAmount); + } + let n = out.len(); + if n == 0 { + return Err(SplitError::NoRecipients); + } + if n > MAX_SPLIT_RECIPIENTS { + return Err(SplitError::TooManyRecipients); + } + if params.len() != n { + return Err(SplitError::LengthMismatch); + } + match strategy { + SplitStrategy::Equal => { + let base = amount / n as i128; + let extra = (amount % n as i128) as usize; + for (i, slot) in out.iter_mut().enumerate() { + *slot = if i < extra { base + 1 } else { base }; + } + Ok(0) + } + SplitStrategy::Weighted => { + let mut total_weight: i128 = 0; + for w in params { + if *w < 0 { + return Err(SplitError::InvalidWeights); + } + total_weight = total_weight.checked_add(*w).ok_or(SplitError::InvalidWeights)?; + } + if total_weight != BPS_DENOMINATOR { + return Err(SplitError::InvalidWeights); + } + let mut assigned: i128 = 0; + for (slot, w) in out.iter_mut().zip(params) { + *slot = amount.checked_mul(*w).ok_or(SplitError::Overflow)? / BPS_DENOMINATOR; + assigned += *slot; + } + // Dust is below the number of non-zero weights, so one pass suffices. + let mut dust = amount - assigned; + for (slot, w) in out.iter_mut().zip(params) { + if dust == 0 { + break; + } + if *w > 0 { + *slot += 1; + dust -= 1; + } + } + Ok(0) + } + SplitStrategy::Waterfall => { + let mut remaining = amount; + for (slot, cap) in out.iter_mut().zip(params) { + if *cap < 0 { + return Err(SplitError::InvalidCap); + } + *slot = remaining.min(*cap); + remaining -= *slot; + } + Ok(remaining) + } + } +} + +/// Running totals of completed splits. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct SplitTracker { + /// Number of splits recorded. + pub splits: u32, + /// Total amount paid to recipients. + pub distributed: i128, + /// Total amount left undistributed. + pub undistributed: i128, +} + +impl SplitTracker { + /// Records one split of `amount` that left `undistributed` unassigned (saturating). + pub fn record(&mut self, amount: i128, undistributed: i128) { + self.splits = self.splits.saturating_add(1); + self.distributed = self.distributed.saturating_add(amount - undistributed); + self.undistributed = self.undistributed.saturating_add(undistributed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn equal_split_spreads_dust() { + let mut out = [0i128; 3]; + assert_eq!(apply_strategy(SplitStrategy::Equal, 10, &[0, 0, 0], &mut out), Ok(0)); + assert_eq!(out, [4, 3, 3]); + } + + #[test] + fn weighted_split() { + let mut out = [0i128; 3]; + let weights = [5_000, 3_000, 2_000]; + assert_eq!(apply_strategy(SplitStrategy::Weighted, 101, &weights, &mut out), Ok(0)); + assert_eq!(out.iter().sum::(), 101); + assert_eq!(out, [51, 30, 20]); + assert_eq!( + apply_strategy(SplitStrategy::Weighted, 100, &[5_000, 4_000, 0], &mut out), + Err(SplitError::InvalidWeights) + ); + } + + #[test] + fn waterfall_split() { + let mut out = [0i128; 2]; + assert_eq!(apply_strategy(SplitStrategy::Waterfall, 100, &[60, 30], &mut out), Ok(10)); + assert_eq!(out, [60, 30]); + assert_eq!(apply_strategy(SplitStrategy::Waterfall, 50, &[60, 30], &mut out), Ok(0)); + assert_eq!(out, [50, 0]); + } + + #[test] + fn input_errors() { + let mut out = [0i128; 2]; + assert_eq!( + apply_strategy(SplitStrategy::Equal, 0, &[0, 0], &mut out), + Err(SplitError::InvalidAmount) + ); + assert_eq!( + apply_strategy(SplitStrategy::Equal, 10, &[0], &mut out), + Err(SplitError::LengthMismatch) + ); + assert_eq!( + apply_strategy(SplitStrategy::Equal, 10, &[], &mut []), + Err(SplitError::NoRecipients) + ); + } + + #[test] + fn rule_selection_and_tracking() { + let rules = [ + StrategyRule { condition: StrategyCondition::AmountAtLeast(1_000), strategy: SplitStrategy::Waterfall }, + StrategyRule { condition: StrategyCondition::Always, strategy: SplitStrategy::Equal }, + ]; + assert_eq!(select_strategy(&rules, 1_000), Ok(SplitStrategy::Waterfall)); + assert_eq!(select_strategy(&rules, 10), Ok(SplitStrategy::Equal)); + assert_eq!(select_strategy(&rules[..1], 10), Err(SplitError::NoMatch)); + + let mut t = SplitTracker::default(); + t.record(100, 10); + assert_eq!(t, SplitTracker { splits: 1, distributed: 90, undistributed: 10 }); + } +} diff --git a/contracts/split/src/tiered_refund.rs b/contracts/split/src/tiered_refund.rs new file mode 100644 index 0000000..a763c35 --- /dev/null +++ b/contracts/split/src/tiered_refund.rs @@ -0,0 +1,242 @@ +//! Issue #1183: tiered refund processing (first slice). +//! +//! Pure helpers: a refund schedule whose tiers lower the refundable share as +//! time since payment grows, processing rules (fee, minimum, cap) applied on +//! top of the tier, a quote calculator and refund counters. + +/// Maximum number of tiers in a schedule. +pub const MAX_REFUND_TIERS: usize = 10; + +const BPS_DENOMINATOR: i128 = 10_000; + +/// One refund tier: from `min_elapsed` seconds after payment, the payer may +/// recover `refund_bps` of the amount paid. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RefundTier { + /// Seconds since payment at which this tier starts. + pub min_elapsed: u64, + /// Refundable share in bps. + pub refund_bps: u32, +} + +/// Default schedule: full refund on day 0, 75% after 1 day, 50% after 7 +/// days, nothing after 30 days. +pub const DEFAULT_REFUND_TIERS: [RefundTier; 4] = [ + RefundTier { min_elapsed: 0, refund_bps: 10_000 }, + RefundTier { min_elapsed: 86_400, refund_bps: 7_500 }, + RefundTier { min_elapsed: 604_800, refund_bps: 5_000 }, + RefundTier { min_elapsed: 2_592_000, refund_bps: 0 }, +]; + +/// Processing rules applied after the tier share. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RefundRules { + /// Processing fee in bps of the tier amount, kept by the contract. + pub fee_bps: u32, + /// Net refunds below this are rejected. + pub min_refund: i128, + /// Upper bound on the net refund, if any. + pub max_refund: Option, +} + +impl Default for RefundRules { + fn default() -> Self { + RefundRules { fee_bps: 0, min_refund: 1, max_refund: None } + } +} + +/// Errors for refund helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RefundError { + /// Schedule is empty or has more than [`MAX_REFUND_TIERS`] tiers. + InvalidTierCount, + /// Tier starts are not strictly increasing. + UnorderedTiers, + /// A tier's bps exceeds 10_000 or is higher than an earlier tier's. + InvalidTierBps, + /// Rules are out of range. + InvalidRules, + /// Paid amount must be positive. + InvalidAmount, + /// No tier covers the elapsed time. + NoTier, + /// Net refund is below `min_refund`. + BelowMinimum, + /// Arithmetic overflow. + Overflow, +} + +/// Checks that tiers start in strictly increasing order and that the +/// refundable share never rises over time. +pub fn validate_tiers(tiers: &[RefundTier]) -> Result<(), RefundError> { + if tiers.is_empty() || tiers.len() > MAX_REFUND_TIERS { + return Err(RefundError::InvalidTierCount); + } + for (i, tier) in tiers.iter().enumerate() { + if tier.refund_bps as i128 > BPS_DENOMINATOR { + return Err(RefundError::InvalidTierBps); + } + if i > 0 { + let prev = tiers[i - 1]; + if tier.min_elapsed <= prev.min_elapsed { + return Err(RefundError::UnorderedTiers); + } + if tier.refund_bps > prev.refund_bps { + return Err(RefundError::InvalidTierBps); + } + } + } + Ok(()) +} + +/// Checks the processing rules. +pub fn validate_rules(rules: &RefundRules) -> Result<(), RefundError> { + if rules.fee_bps as i128 > BPS_DENOMINATOR || rules.min_refund < 0 { + return Err(RefundError::InvalidRules); + } + if let Some(max) = rules.max_refund { + if max < rules.min_refund { + return Err(RefundError::InvalidRules); + } + } + Ok(()) +} + +/// Index of the tier that applies after `elapsed` seconds: the last tier +/// whose `min_elapsed` is `<= elapsed`. +pub fn tier_for(tiers: &[RefundTier], elapsed: u64) -> Option { + tiers.iter().rposition(|t| t.min_elapsed <= elapsed) +} + +/// Breakdown of a refund. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RefundQuote { + /// Index of the applied tier. + pub tier_index: u32, + /// Amount allowed by the tier before fees. + pub gross: i128, + /// Processing fee withheld. + pub fee: i128, + /// Amount returned to the payer. + pub net: i128, +} + +/// Computes the refund for `paid` after `elapsed` seconds under `tiers` and +/// `rules`. All divisions round down, in the contract's favour by at most +/// one unit each. +pub fn quote_refund( + tiers: &[RefundTier], + rules: &RefundRules, + paid: i128, + elapsed: u64, +) -> Result { + validate_tiers(tiers)?; + validate_rules(rules)?; + if paid <= 0 { + return Err(RefundError::InvalidAmount); + } + let index = tier_for(tiers, elapsed).ok_or(RefundError::NoTier)?; + let gross = paid + .checked_mul(tiers[index].refund_bps as i128) + .ok_or(RefundError::Overflow)? + / BPS_DENOMINATOR; + let fee = gross + .checked_mul(rules.fee_bps as i128) + .ok_or(RefundError::Overflow)? + / BPS_DENOMINATOR; + let mut net = gross - fee; + if let Some(max) = rules.max_refund { + net = net.min(max); + } + if net < rules.min_refund { + return Err(RefundError::BelowMinimum); + } + Ok(RefundQuote { tier_index: index as u32, gross, fee, net }) +} + +/// Refund counters. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct RefundTracker { + /// Refunds processed. + pub processed: u32, + /// Refund requests rejected. + pub rejected: u32, + /// Total returned to payers. + pub total_refunded: i128, + /// Total fees withheld. + pub total_fees: i128, +} + +impl RefundTracker { + /// Records the outcome of one refund request (saturating). + pub fn record(&mut self, outcome: &Result) { + match outcome { + Ok(q) => { + self.processed = self.processed.saturating_add(1); + self.total_refunded = self.total_refunded.saturating_add(q.net); + self.total_fees = self.total_fees.saturating_add(q.fee); + } + Err(_) => self.rejected = self.rejected.saturating_add(1), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_schedule_tiers() { + let rules = RefundRules::default(); + let q = quote_refund(&DEFAULT_REFUND_TIERS, &rules, 1_000, 0).unwrap(); + assert_eq!((q.tier_index, q.net), (0, 1_000)); + let q = quote_refund(&DEFAULT_REFUND_TIERS, &rules, 1_000, 86_400).unwrap(); + assert_eq!((q.tier_index, q.net), (1, 750)); + let q = quote_refund(&DEFAULT_REFUND_TIERS, &rules, 1_000, 700_000).unwrap(); + assert_eq!((q.tier_index, q.net), (2, 500)); + assert_eq!( + quote_refund(&DEFAULT_REFUND_TIERS, &rules, 1_000, 2_592_000), + Err(RefundError::BelowMinimum) + ); + } + + #[test] + fn rules_apply_fee_and_cap() { + let rules = RefundRules { fee_bps: 100, min_refund: 10, max_refund: Some(700) }; + let q = quote_refund(&DEFAULT_REFUND_TIERS, &rules, 1_000, 0).unwrap(); + assert_eq!(q, RefundQuote { tier_index: 0, gross: 1_000, fee: 10, net: 700 }); + let bad = RefundRules { fee_bps: 10_001, ..rules }; + assert_eq!( + quote_refund(&DEFAULT_REFUND_TIERS, &bad, 1_000, 0), + Err(RefundError::InvalidRules) + ); + } + + #[test] + fn custom_schedule_validation() { + let late_start = [RefundTier { min_elapsed: 60, refund_bps: 5_000 }]; + assert_eq!( + quote_refund(&late_start, &RefundRules::default(), 100, 30), + Err(RefundError::NoTier) + ); + let rising = [ + RefundTier { min_elapsed: 0, refund_bps: 5_000 }, + RefundTier { min_elapsed: 10, refund_bps: 6_000 }, + ]; + assert_eq!(validate_tiers(&rising), Err(RefundError::InvalidTierBps)); + let unordered = [ + RefundTier { min_elapsed: 10, refund_bps: 5_000 }, + RefundTier { min_elapsed: 10, refund_bps: 4_000 }, + ]; + assert_eq!(validate_tiers(&unordered), Err(RefundError::UnorderedTiers)); + assert_eq!(validate_tiers(&[]), Err(RefundError::InvalidTierCount)); + } + + #[test] + fn tracker_counts_outcomes() { + let mut t = RefundTracker::default(); + t.record(&Ok(RefundQuote { tier_index: 0, gross: 100, fee: 1, net: 99 })); + t.record(&Err(RefundError::NoTier)); + assert_eq!(t, RefundTracker { processed: 1, rejected: 1, total_refunded: 99, total_fees: 1 }); + } +} diff --git a/docs/SECURITY_AUDIT_CHECKLIST.md b/docs/SECURITY_AUDIT_CHECKLIST.md new file mode 100644 index 0000000..f11bebc --- /dev/null +++ b/docs/SECURITY_AUDIT_CHECKLIST.md @@ -0,0 +1,135 @@ +# Contract security audit checklist + +A checklist for reviewing the contracts in this workspace before a release or after a +significant change. Each item has an ID, a severity, and a verification step. It builds on +[`SECURITY_BEST_PRACTICES.md`](SECURITY_BEST_PRACTICES.md), which explains the reasoning behind +most of these items. + +## How to use this checklist + +1. Copy the [template](#audit-record-template) into the PR, issue or audit report. +2. Set the scope: which workspace members (see the root `Cargo.toml`) and which commit. +3. Work through each section. For every item, run the verification step and record + `Pass`, `Fail` or `N/A` with a short note (file and line, command output, test name). +4. Any `Fail` on a `Critical` or `High` item blocks the release until it is fixed or + explicitly accepted by a maintainer, with the reason written down. +5. Attach the filled-in record to the release notes or the PR. + +Severities follow `AuditSeverity` in `contracts/split/src/security_audit.rs`: +`Critical`, `High`, `Medium`, `Low`, `Info`. + +## 1. Authorization + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| AUTH-1 | Critical | Every entry point that moves funds or changes privileged state calls `require_auth()` on the acting address before any storage write or token transfer. | For each `pub fn` in the `#[contractimpl]` block that writes storage or calls `token::Client::transfer`, confirm a `require_auth()` (or `require_admin`) call comes first. `grep -n "pub fn" contracts//src/lib.rs` lists the entry points. | +| AUTH-2 | Critical | Address parameters that claim a role (admin, arbiter, creator) are compared with stored state, not trusted as passed. | Check the role check reads the stored address (e.g. `arbiter_key()` in `invoice-escrow`) and compares it to the parameter before `require_auth()`. | +| AUTH-3 | High | Admin-only functions share one helper rather than repeating the check. | Confirm admin functions call `require_admin` (both `split` and `invoice-escrow` have one). | +| AUTH-4 | High | Privileged singleton roles use a two-step handover or are admin-replaceable. | Review `transfer_admin` / `accept_admin` / `cancel_transfer` in `invoice-escrow`; apply the same check to any new privileged address. | +| AUTH-5 | Medium | Negative tests exist: a non-authorized caller is rejected. | Find a test per privileged entry point that expects a panic or `Err` for the wrong caller. | + +## 2. Input validation + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| VAL-1 | High | Amounts are checked to be positive where zero or negative values make no sense. | Trace each amount parameter to an explicit `> 0` check or a validator in `contracts/split/src/validation.rs`. | +| VAL-2 | High | Basis-point values are bounded to `10_000`. | Confirm bps inputs go through `assert_valid_bps` (split) or an equivalent check. | +| VAL-3 | Medium | Caller-supplied lists (recipients, payers, rules) have an upper bound. | Look for a `MAX_*` constant checked before the list is stored or iterated. | +| VAL-4 | Medium | Duplicate entries are rejected where they would double-count (e.g. recipients). | Check for a duplicate check, or the `inv_dupe` finding in `run_invoice_audit`. | +| VAL-5 | Medium | All preconditions are checked before the first mutation. | In each fund-moving function, confirm every `Err`/`panic!` return sits above the first `storage().set` or `transfer`. | + +## 3. Arithmetic + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| ARI-1 | Critical | Balance, counter and fee math uses `checked_*` or saturating operations. | `grep -nE "[a-z_]+ (\+|-|\*) [a-z_]+" contracts//src/lib.rs` and review each hit that touches an amount. | +| ARI-2 | High | `overflow-checks = true` is still set in the workspace release profile. | Check `[profile.release]` in the root `Cargo.toml`. | +| ARI-3 | High | Split and fee rounding never pays out more than was funded. | Review `contracts/split/src/calc.rs` and run the `fuzz_split_arithmetic` and `fuzz_fee_deduct` targets. | +| ARI-4 | Medium | Division by a caller-controlled value is guarded against zero. | Find each `/` and `checked_div` on an input-derived divisor and confirm a zero check. | + +## 4. State and fund flow + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| ST-1 | Critical | Status is updated and saved before tokens are transferred (checks-effects-interactions). | In release, refund and dispute paths, confirm `save_invoice` (or equivalent) precedes `transfer`. | +| ST-2 | Critical | Funds cannot be released or refunded twice. | Confirm terminal statuses cannot be left (see the transition rules in `contracts/split/src/lib.rs`) and that a double-refund test exists (e.g. `double_refund_is_rejected`). | +| ST-3 | High | Disputed invoices block pay, release, refund and cancel. | Check each of those entry points for a disputed-status guard. | +| ST-4 | High | The sum of payouts equals the funded amount minus fees. | Trace the release path and confirm a test asserts token balances after release. | +| ST-5 | Medium | Time windows use ledger sequence where validator time drift matters. | Review new deadlines or windows and compare with `APPEAL_WINDOW_LEDGERS` in `invoice-escrow`. | + +## 5. Storage + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| STO-1 | High | Storage keys are unique and do not collide across modules. | Cross-check new keys against [`STORAGE_KEY_CONVENTIONS.md`](STORAGE_KEY_CONVENTIONS.md) and `STORAGE_KEY_REGISTRY.md`. | +| STO-2 | Medium | Persistent entries that must outlive the default TTL are extended. | Check `extend_ttl` calls on long-lived records. | +| STO-3 | Medium | Per-invoice data growth is bounded. | Confirm the storage quota (`DEFAULT_INVOICE_STORAGE_QUOTA` in split) or a list cap covers new data. | +| STO-4 | Low | Instance storage holds only small, contract-wide values. | Review any new `storage().instance().set` call. | + +## 6. Emergency controls and upgrades + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| EMR-1 | High | New fund-moving entry points respect the global pause. | Confirm `require_not_paused` (split) is called at the top of each new entry point. | +| EMR-2 | High | Pause, unpause and upgrade are admin-only. | Review `pause`, `unpause`, `pause_function`, `unpause_function` and `contracts/split/src/contract_upgrade.rs`. | +| EMR-3 | Medium | Storage layout changes ship with a migration. | Check `contracts/split/src/migrations.rs` and [`UPGRADE_MIGRATION_GUIDE.md`](UPGRADE_MIGRATION_GUIDE.md). | + +## 7. Events and observability + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| EVT-1 | Medium | Every state change emits an event. | For each new mutation, find the matching `events::` or `emit_*` call. | +| EVT-2 | Low | Events do not leak data meant to stay private (e.g. encrypted metadata in plain form). | Review event payloads in `contracts/split/src/events.rs` for new fields. | + +## 8. Error handling + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| ERR-1 | Medium | No `.unwrap()` / `.expect()` on values derived directly from caller input. | `grep -n "unwrap()\|expect(" contracts//src/lib.rs` and check each new hit. | +| ERR-2 | Low | New error variants are documented. | Confirm [`ERROR_CODES.md`](ERROR_CODES.md) / [`ERROR_CODES_SPLIT.md`](ERROR_CODES_SPLIT.md) list them. | + +## 9. Testing + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| TST-1 | High | The workspace test suite passes. | `cargo test --workspace` | +| TST-2 | Medium | Fuzz targets run without new crashes. | `cargo fuzz run ` for the targets in `fuzz/fuzz_targets/` (e.g. `fuzz_pay`, `fuzz_refund`, `fuzz_release`). | +| TST-3 | Medium | Changed code paths have a regression test. | Check the PR adds or updates tests next to the changed contract. | + +## 10. On-chain audit run (split contract) + +| ID | Severity | Item | Verification | +|----|----------|------|--------------| +| OCA-1 | High | The contract-level audit reports no failed `Critical` or `High` checks. | A registered auditor (`add_auditor`) calls `run_contract_audit` and reviews the stored `SecurityAuditReport`. | +| OCA-2 | Medium | Sampled invoices pass the invoice-level audit. | Call `run_invoice_audit` on a sample of live invoices and review the findings. | + +## Customizing the checklist + +- **Scope by contract.** Mark items that do not apply to a contract as `N/A` with a reason + (for example, OCA items only apply to `contracts/split`). +- **Add project items.** Append rows to the relevant section using the next free ID + (e.g. `ST-6`). Keep the same columns so records stay comparable between audits. +- **Adjust severity.** A team may raise an item's severity for a release; lowering one + should be recorded in the audit record with the reason. +- **Change the blocking rule.** The default blocks on failed `Critical` and `High` items. + Record any different rule at the top of the audit record. + +## Audit record template + +```text +Audit: +Commit: +Scope: +Auditor: +Date: +Blocking rule: Critical + High (default) + +ID | Result | Notes +--------|--------|------------------------------ +AUTH-1 | | +AUTH-2 | | +... | | + +Accepted risks: +- : +```