diff --git a/contracts/split/src/invoice_compliance_checklist.rs b/contracts/split/src/invoice_compliance_checklist.rs new file mode 100644 index 0000000..d9f9a5e --- /dev/null +++ b/contracts/split/src/invoice_compliance_checklist.rs @@ -0,0 +1,85 @@ +//! Issue #1168: invoice compliance checklist (first slice). +//! +//! Pure helpers over a caller-held slice of checklist items: a default +//! template, completion tracking and verification. Not covered: persistent +//! storage, per-invoice assignment, custom template management entry points +//! and events. + +/// Maximum items in one checklist. +pub const MAX_CHECKLIST_ITEMS: usize = 32; + +/// Errors for checklist helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ChecklistError { + /// Item id not present. + ItemNotFound, +} + +/// One compliance item. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ChecklistItem { + /// Item identifier. + pub id: u32, + /// Whether the item must be done for verification to pass. + pub required: bool, + /// Whether the item is done. + pub done: bool, +} + +/// Default template: items 1-3 required, item 4 optional. +pub fn standard_template() -> [ChecklistItem; 4] { + [ + ChecklistItem { id: 1, required: true, done: false }, + ChecklistItem { id: 2, required: true, done: false }, + ChecklistItem { id: 3, required: true, done: false }, + ChecklistItem { id: 4, required: false, done: false }, + ] +} + +/// Marks the item with `id` as done. +pub fn mark_done(items: &mut [ChecklistItem], id: u32) -> Result<(), ChecklistError> { + for item in items.iter_mut() { + if item.id == id { + item.done = true; + return Ok(()); + } + } + Err(ChecklistError::ItemNotFound) +} + +/// Number of required items not yet done. +pub fn missing_required(items: &[ChecklistItem]) -> u32 { + items.iter().filter(|i| i.required && !i.done).count() as u32 +} + +/// True when every required item is done. +pub fn is_compliant(items: &[ChecklistItem]) -> bool { + missing_required(items) == 0 +} + +/// Completion of all items in basis points (10_000 = all done; empty = 10_000). +pub fn completion_bps(items: &[ChecklistItem]) -> u32 { + if items.is_empty() { + return 10_000; + } + let done = items.iter().filter(|i| i.done).count() as u32; + done * 10_000 / items.len() as u32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tracks_and_verifies() { + let mut t = standard_template(); + assert!(!is_compliant(&t)); + assert_eq!(missing_required(&t), 3); + for id in 1..=3 { + mark_done(&mut t, id).unwrap(); + } + assert!(is_compliant(&t)); + assert_eq!(completion_bps(&t), 7_500); + assert_eq!(mark_done(&mut t, 99), Err(ChecklistError::ItemNotFound)); + } +} diff --git a/contracts/split/src/invoice_routing_rules.rs b/contracts/split/src/invoice_routing_rules.rs new file mode 100644 index 0000000..5173fb3 --- /dev/null +++ b/contracts/split/src/invoice_routing_rules.rs @@ -0,0 +1,130 @@ +//! Issue #1167: condition-based payment routing (first slice). +//! +//! Pure helpers: given an ordered rule list, an amount and a payer, pick the +//! destination of the matching rule with the lowest `priority` value (first +//! rule wins ties). Not covered: contract entry points, persistent rule +//! storage, persisted decision history and events. + +use soroban_sdk::Address; + +/// Maximum number of rules evaluated per routing call. +pub const MAX_ROUTING_RULES: usize = 50; + +/// Errors for routing helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RoutingError { + /// Amount must be positive. + InvalidAmount, + /// Too many rules supplied. + TooManyRules, + /// No rule matched. + NoMatch, +} + +/// Condition under which a rule applies. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RoutingCondition { + /// Always matches. + Always, + /// Matches when amount >= value. + AmountAtLeast(i128), + /// Matches when amount < value. + AmountBelow(i128), + /// Matches when the payer equals the address. + PayerIs(Address), +} + +/// A single routing rule. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RoutingRule { + /// Condition to evaluate. + pub condition: RoutingCondition, + /// Destination when matched. + pub destination: Address, + /// Lower value is evaluated as higher priority. + pub priority: u32, +} + +/// Record of a routing decision (for tracking by the caller). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RoutingDecision { + /// Index of the winning rule in the input slice. + pub rule_index: u32, + /// Chosen destination. + pub destination: Address, +} + +/// Returns true when `condition` holds for the amount and payer. +pub fn condition_matches(condition: &RoutingCondition, amount: i128, payer: &Address) -> bool { + match condition { + RoutingCondition::Always => true, + RoutingCondition::AmountAtLeast(v) => amount >= *v, + RoutingCondition::AmountBelow(v) => amount < *v, + RoutingCondition::PayerIs(a) => a == payer, + } +} + +/// Selects the destination for a payment from `rules`. +pub fn route_payment( + rules: &[RoutingRule], + amount: i128, + payer: &Address, +) -> Result { + if amount <= 0 { + return Err(RoutingError::InvalidAmount); + } + if rules.len() > MAX_ROUTING_RULES { + return Err(RoutingError::TooManyRules); + } + let mut best: Option<(usize, u32)> = None; + for (i, rule) in rules.iter().enumerate() { + if !condition_matches(&rule.condition, amount, payer) { + continue; + } + let better = match best { + None => true, + Some((_, p)) => rule.priority < p, + }; + if better { + best = Some((i, rule.priority)); + } + } + match best { + Some((i, _)) => Ok(RoutingDecision { + rule_index: i as u32, + destination: rules[i].destination.clone(), + }), + None => Err(RoutingError::NoMatch), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use soroban_sdk::testutils::Address as _; + use soroban_sdk::Env; + + #[test] + fn priority_and_conditions() { + let env = Env::default(); + let payer = Address::generate(&env); + let a = Address::generate(&env); + let b = Address::generate(&env); + let rules = [ + RoutingRule { condition: RoutingCondition::Always, destination: a.clone(), priority: 5 }, + RoutingRule { condition: RoutingCondition::AmountAtLeast(100), destination: b.clone(), priority: 1 }, + ]; + assert_eq!(route_payment(&rules, 100, &payer).unwrap().destination, b); + let d = route_payment(&rules, 10, &payer).unwrap(); + assert_eq!(d.destination, a); + assert_eq!(d.rule_index, 0); + } + + #[test] + fn errors() { + let env = Env::default(); + let payer = Address::generate(&env); + assert_eq!(route_payment(&[], 0, &payer), Err(RoutingError::InvalidAmount)); + assert_eq!(route_payment(&[], 5, &payer), Err(RoutingError::NoMatch)); + } +} diff --git a/contracts/split/src/lib.rs b/contracts/split/src/lib.rs index 68e5675..a868839 100644 --- a/contracts/split/src/lib.rs +++ b/contracts/split/src/lib.rs @@ -82,15 +82,18 @@ mod validation; mod calc; mod tx_result_cache; mod math; +mod invoice_routing_rules; mod stats; mod storage_layout_opt; pub mod security_audit; pub mod payment_tracking; pub mod velocity; +mod invoice_compliance_checklist; pub mod split_rules; pub mod pool; mod batch_verify; pub mod compression; +mod zk_commitment_verifier; pub mod aggregation; pub mod template_library; diff --git a/contracts/split/src/tiered_access.rs b/contracts/split/src/tiered_access.rs new file mode 100644 index 0000000..9613746 --- /dev/null +++ b/contracts/split/src/tiered_access.rs @@ -0,0 +1,120 @@ +//! Issue #1170: tiered access control (first slice). +//! +//! Pure helpers: an ordered tier ladder, permission-to-minimum-tier mapping, +//! delegation rules and grant/deny counters. Not covered: storing tier +//! assignments per address, entry points enforcing tiers, signature checks +//! (`require_auth`), persisted access logs and events. + +/// Access tiers, ordered lowest to highest. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum AccessTier { + /// Read-only. + Viewer = 0, + /// Day-to-day operations. + Operator = 1, + /// May delegate lower tiers. + Manager = 2, + /// Full access. + Admin = 3, +} + +/// Permissions mapped to a minimum tier. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Permission { + /// View invoices. + ViewInvoice, + /// Record payments. + RecordPayment, + /// Change invoice configuration. + ConfigureInvoice, + /// Change contract-wide settings. + ManageSettings, +} + +/// Errors for tier helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AccessError { + /// Tier too low for the permission. + Unauthorized, + /// Delegation not permitted. + InvalidDelegation, +} + +/// Minimum tier required for a permission. +pub fn min_tier(permission: Permission) -> AccessTier { + match permission { + Permission::ViewInvoice => AccessTier::Viewer, + Permission::RecordPayment => AccessTier::Operator, + Permission::ConfigureInvoice => AccessTier::Manager, + Permission::ManageSettings => AccessTier::Admin, + } +} + +/// True when `tier` grants `permission`. +pub fn is_allowed(tier: AccessTier, permission: Permission) -> bool { + tier >= min_tier(permission) +} + +/// Returns an error when `tier` does not grant `permission`. +pub fn require_permission(tier: AccessTier, permission: Permission) -> Result<(), AccessError> { + if is_allowed(tier, permission) { + Ok(()) + } else { + Err(AccessError::Unauthorized) + } +} + +/// Checks that `granter` may delegate `target` tier: granter must be at least +/// Manager and `target` must be strictly below the granter's own tier. +pub fn check_delegation(granter: AccessTier, target: AccessTier) -> Result<(), AccessError> { + if granter >= AccessTier::Manager && target < granter { + Ok(()) + } else { + Err(AccessError::InvalidDelegation) + } +} + +/// Access counters. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct AccessStats { + /// Allowed checks. + pub granted: u32, + /// Denied checks. + pub denied: u32, +} + +impl AccessStats { + /// Records one check outcome (saturating). + pub fn record(&mut self, allowed: bool) { + if allowed { + self.granted = self.granted.saturating_add(1); + } else { + self.denied = self.denied.saturating_add(1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tiers_and_delegation() { + assert!(is_allowed(AccessTier::Operator, Permission::RecordPayment)); + assert_eq!( + require_permission(AccessTier::Operator, Permission::ManageSettings), + Err(AccessError::Unauthorized) + ); + assert!(check_delegation(AccessTier::Manager, AccessTier::Operator).is_ok()); + assert!(check_delegation(AccessTier::Manager, AccessTier::Manager).is_err()); + assert!(check_delegation(AccessTier::Operator, AccessTier::Viewer).is_err()); + } + + #[test] + fn stats() { + let mut s = AccessStats::default(); + s.record(true); + s.record(false); + assert_eq!(s, AccessStats { granted: 1, denied: 1 }); + } +} diff --git a/contracts/split/src/zk_commitment_verifier.rs b/contracts/split/src/zk_commitment_verifier.rs new file mode 100644 index 0000000..ed8fbdc --- /dev/null +++ b/contracts/split/src/zk_commitment_verifier.rs @@ -0,0 +1,86 @@ +//! Issue #1169: hash-commitment verifier (first slice, NOT zero-knowledge). +//! +//! This is a salted SHA-256 commit/reveal check plus a verification-key hash +//! allow-list and proof counters. A reveal discloses the secret, so it does +//! NOT preserve privacy and there is no circuit or ZK proof system here. +//! Not covered: real ZK proofs, circuits, on-chain verifier keys, storage. + +use soroban_sdk::{Bytes, BytesN, Env}; + +/// Errors for the verifier helpers. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ZkError { + /// Verification key hash not in the registry. + UnknownKey, +} + +/// Counters of verification attempts. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct ProofStats { + /// Successful verifications. + pub verified: u32, + /// Failed verifications. + pub rejected: u32, +} + +impl ProofStats { + /// Records one outcome (saturating). + pub fn record(&mut self, ok: bool) { + if ok { + self.verified = self.verified.saturating_add(1); + } else { + self.rejected = self.rejected.saturating_add(1); + } + } +} + +/// Computes `sha256(salt || secret)`. +pub fn commit(env: &Env, secret: &Bytes, salt: &BytesN<32>) -> BytesN<32> { + let mut data = Bytes::from_slice(env, &salt.to_array()); + data.append(secret); + env.crypto().sha256(&data).into() +} + +/// Checks that revealing `secret`/`salt` matches `commitment`. +pub fn verify_reveal(env: &Env, commitment: &BytesN<32>, secret: &Bytes, salt: &BytesN<32>) -> bool { + commit(env, secret, salt) == *commitment +} + +/// Checks a key hash against an allow-list of registered key hashes. +pub fn require_registered_key( + registry: &[BytesN<32>], + key_hash: &BytesN<32>, +) -> Result<(), ZkError> { + if registry.iter().any(|k| k == key_hash) { + Ok(()) + } else { + Err(ZkError::UnknownKey) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reveal_and_stats() { + let env = Env::default(); + let salt = BytesN::from_array(&env, &[7u8; 32]); + let secret = Bytes::from_slice(&env, b"hello"); + let c = commit(&env, &secret, &salt); + let mut stats = ProofStats::default(); + stats.record(verify_reveal(&env, &c, &secret, &salt)); + stats.record(verify_reveal(&env, &c, &Bytes::from_slice(&env, b"nope"), &salt)); + assert_eq!(stats, ProofStats { verified: 1, rejected: 1 }); + } + + #[test] + fn key_registry() { + let env = Env::default(); + let k = BytesN::from_array(&env, &[1u8; 32]); + let other = BytesN::from_array(&env, &[2u8; 32]); + let reg = [k.clone()]; + assert!(require_registered_key(®, &k).is_ok()); + assert_eq!(require_registered_key(®, &other), Err(ZkError::UnknownKey)); + } +}