From e4d3111760910855c05b9db0754cfa998f201d72 Mon Sep 17 00:00:00 2001 From: Muhammadcodes112 Date: Mon, 23 Nov 2026 23:06:37 +0100 Subject: [PATCH 1/4] Add performance profiling report helpers (#1190) --- contracts/split/src/lib.rs | 2 + contracts/split/src/perf_profiling.rs | 178 ++++++++++++++++++++++++++ 2 files changed, 180 insertions(+) create mode 100644 contracts/split/src/perf_profiling.rs diff --git a/contracts/split/src/lib.rs b/contracts/split/src/lib.rs index 888d6f6..b7d6e24 100644 --- a/contracts/split/src/lib.rs +++ b/contracts/split/src/lib.rs @@ -157,6 +157,8 @@ pub mod contract_upgrade; pub mod audit_logging; // Issue #1008: Enhanced per-user rate limiting and throttling. pub mod rate_limiting; +// Issue #1190: Performance profiling report helpers. +mod perf_profiling; use error::ContractError; use validation::assert_valid_bps; diff --git a/contracts/split/src/perf_profiling.rs b/contracts/split/src/perf_profiling.rs new file mode 100644 index 0000000..edcabbc --- /dev/null +++ b/contracts/split/src/perf_profiling.rs @@ -0,0 +1,178 @@ +//! Issue #1190: performance profiling report helpers (first slice). +//! +//! Builds on the per-operation profiles recorded by `record_compute_usage` +//! (issue #924). [`metrics`] derives averages, spread, estimate drift and +//! accuracy from an [`OperationProfile`], [`insight`] classifies them into an +//! actionable [`Insight`], and [`PerfTracker`] aggregates a whole report +//! (operations seen, samples, flagged operations and the hottest operation). + +#![allow(dead_code)] + +use crate::types::OperationProfile; + +/// Samples needed before an operation's metrics are trusted. +pub const MIN_SAMPLES: u32 = 5; +/// Spread (max - min) above this share of the average, in bps, is volatile. +pub const VOLATILE_SPREAD_BPS: u64 = 5_000; +/// Share of samples estimated within tolerance below which accuracy is low, in bps. +pub const LOW_ACCURACY_BPS: u64 = 8_000; + +/// Derived metrics for one profiled operation. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct ProfileMetrics { + /// Recorded samples. + pub samples: u32, + /// Average measured instructions per call. + pub avg_actual_insns: u64, + /// Average raw (uncalibrated) estimate per call. + pub avg_raw_estimated_insns: u64, + /// (max - min) as a share of the average, in bps. + pub spread_bps: u64, + /// |avg actual - avg raw estimate| as a share of avg actual, in bps. + pub drift_bps: u64, + /// Share of samples estimated within tolerance, in bps. + pub accuracy_bps: u64, +} + +/// Actionable classification of an operation's metrics. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Insight { + /// Fewer than [`MIN_SAMPLES`] samples; record more usage. + NeedsMoreSamples, + /// Cost varies widely between calls; inspect input-size dependence. + Volatile, + /// Estimates often miss; review the operation's cost model. + LowAccuracy, + /// Nothing to act on. + Healthy, +} + +fn ratio_bps(part: u64, whole: u64) -> u64 { + if whole == 0 { + return 0; + } + ((part as u128) * 10_000 / (whole as u128)).min(u64::MAX as u128) as u64 +} + +/// Derives [`ProfileMetrics`] from a recorded profile. +pub fn metrics(profile: &OperationProfile) -> ProfileMetrics { + if profile.samples == 0 { + return ProfileMetrics::default(); + } + let n = profile.samples as u64; + let avg_actual = profile.total_actual_insns / n; + let avg_raw = profile.total_raw_estimated_insns / n; + let spread = profile.max_actual_insns.saturating_sub(profile.min_actual_insns); + ProfileMetrics { + samples: profile.samples, + avg_actual_insns: avg_actual, + avg_raw_estimated_insns: avg_raw, + spread_bps: ratio_bps(spread, avg_actual), + drift_bps: ratio_bps(avg_actual.abs_diff(avg_raw), avg_actual), + accuracy_bps: ratio_bps(profile.within_tolerance as u64, n), + } +} + +/// Classifies metrics; sample count is checked first, then volatility, then accuracy. +pub fn insight(m: &ProfileMetrics) -> Insight { + if m.samples < MIN_SAMPLES { + Insight::NeedsMoreSamples + } else if m.spread_bps > VOLATILE_SPREAD_BPS { + Insight::Volatile + } else if m.accuracy_bps < LOW_ACCURACY_BPS { + Insight::LowAccuracy + } else { + Insight::Healthy + } +} + +/// Report-wide counters across profiled operations. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PerfTracker { + /// Operations added to the report. + pub operations: u32, + /// Total samples across operations (saturating). + pub total_samples: u64, + /// Operations whose insight is not [`Insight::Healthy`]. + pub flagged: u32, + /// Position (in add order) of the operation with the highest average cost. + pub hottest: Option, + /// Highest average cost seen. + pub hottest_avg_insns: u64, +} + +impl PerfTracker { + /// Adds one operation's metrics to the report and returns its insight. + pub fn add(&mut self, m: &ProfileMetrics) -> Insight { + let found = insight(m); + if self.hottest.is_none() || m.avg_actual_insns > self.hottest_avg_insns { + self.hottest = Some(self.operations); + self.hottest_avg_insns = m.avg_actual_insns; + } + self.operations = self.operations.saturating_add(1); + self.total_samples = self.total_samples.saturating_add(m.samples as u64); + if found != Insight::Healthy { + self.flagged = self.flagged.saturating_add(1); + } + found + } +} + +#[cfg(test)] +mod tests { + use super::*; + use soroban_sdk::symbol_short; + + fn profile( + samples: u32, + actual: u64, + raw: u64, + min: u64, + max: u64, + ok: u32, + ) -> OperationProfile { + OperationProfile { + operation: symbol_short!("pay"), + samples, + total_raw_estimated_insns: raw, + total_actual_insns: actual, + min_actual_insns: min, + max_actual_insns: max, + last_actual_insns: max, + last_error_bps: 0, + within_tolerance: ok, + } + } + + #[test] + fn metrics_and_insights() { + let m = metrics(&profile(10, 10_000, 9_000, 900, 1_100, 9)); + assert_eq!(m.avg_actual_insns, 1_000); + assert_eq!(m.avg_raw_estimated_insns, 900); + assert_eq!(m.spread_bps, 2_000); + assert_eq!(m.drift_bps, 1_000); + assert_eq!(m.accuracy_bps, 9_000); + assert_eq!(insight(&m), Insight::Healthy); + + let few = metrics(&profile(2, 2_000, 2_000, 1_000, 1_000, 2)); + assert_eq!(insight(&few), Insight::NeedsMoreSamples); + let volatile = metrics(&profile(5, 5_000, 5_000, 200, 2_000, 5)); + assert_eq!(insight(&volatile), Insight::Volatile); + let inaccurate = metrics(&profile(5, 5_000, 5_000, 900, 1_100, 1)); + assert_eq!(insight(&inaccurate), Insight::LowAccuracy); + let empty = metrics(&profile(0, 0, 0, u64::MAX, 0, 0)); + assert_eq!(empty, ProfileMetrics::default()); + } + + #[test] + fn tracker_reports_hottest_and_flagged() { + let mut t = PerfTracker::default(); + t.add(&metrics(&profile(10, 10_000, 10_000, 1_000, 1_000, 10))); + t.add(&metrics(&profile(2, 8_000, 8_000, 4_000, 4_000, 2))); + assert_eq!(t.operations, 2); + assert_eq!(t.total_samples, 12); + assert_eq!(t.flagged, 1); + assert_eq!(t.hottest, Some(1)); + assert_eq!(t.hottest_avg_insns, 4_000); + } +} From cf69515ace2ef114d0276d01608277cd9b6ce767 Mon Sep 17 00:00:00 2001 From: Muhammadcodes112 Date: Mon, 23 Nov 2026 23:07:38 +0100 Subject: [PATCH 2/4] Add advanced architecture documentation (#1188) --- docs/ADVANCED_ARCHITECTURE.md | 228 ++++++++++++++++++++++++++++++++++ docs/ARCHITECTURE.md | 1 + 2 files changed, 229 insertions(+) create mode 100644 docs/ADVANCED_ARCHITECTURE.md diff --git a/docs/ADVANCED_ARCHITECTURE.md b/docs/ADVANCED_ARCHITECTURE.md new file mode 100644 index 0000000..0049508 --- /dev/null +++ b/docs/ADVANCED_ARCHITECTURE.md @@ -0,0 +1,228 @@ +# Advanced Contract Architecture + +Patterns the `split` contract uses again and again, with diagrams, code taken from the repository, +an optimization guide and a quick reference. Read [`ARCHITECTURE.md`](./ARCHITECTURE.md) first: it +describes the system map, storage model and state flows that this page builds on. + +- [1. Patterns](#1-patterns) +- [2. Examples](#2-examples) +- [3. Optimization guide](#3-optimization-guide) +- [4. Reference](#4-reference) + +Diagrams use [Mermaid](https://mermaid.js.org/), which GitHub renders inline. + +--- + +## 1. Patterns + +### 1.1 Thin entry point, self-contained module + +Every public function lives in `lib.rs` and does three things: check authorisation, call into a +module, and emit an event. The module takes `&Env`, owns its storage keys and never checks auth +([ADR 0002](./adr/0002-single-contract-with-modules.md)). + +```mermaid +flowchart LR + C[Caller] --> EP["lib.rs entry point"] + EP -->|1. require_admin / require_auth| AUTH{Authorised?} + AUTH -- no --> P[panic / ContractError] + AUTH -- yes --> MOD["module fn(&Env, ...)"] + MOD --> ST[(storage keys owned by module)] + EP -->|3. publish| EV["(split, action, id?) event"] +``` + +Use it when the logic has its own state or can be unit-tested without the rest of the contract. + +### 1.2 Pure first slice + +New features often land as a module of pure functions and plain structs with no storage and no +entry points (for example `tiered_access`, `invoice_watermark`, `perf_profiling`). The module is +declared in `lib.rs` so it compiles and its `#[cfg(test)]` tests run, and a later change wires it +to storage and entry points. + +```mermaid +flowchart LR + S1["Slice 1
pure helpers + unit tests"] --> S2["Slice 2
storage keys + entry points"] --> S3["Slice 3
events, docs, API.md"] +``` + +Use it to agree on the rules of a feature before paying for storage layout and WASM size. + +### 1.3 Split record with a hot-path cache + +An invoice is spread over several keys so no entry grows past Soroban's size limit, and the four +fields `pay()` needs are cached in `InvoiceHot` in instance storage +([ADR 0004](./adr/0004-split-invoice-records.md)). + +```mermaid +flowchart TB + PAY["pay()"] -->|fast path| HOT["InvoiceHot (instance)
status, funded, total, recipients"] + PAY -->|only when needed| CORE["InvoiceCore (persistent)"] + GET["get_invoice()"] --> CORE & EXT["InvoiceExt"] & EXT2["InvoiceExt2"] + WRITE["any write to funded / status"] --> CORE & HOT +``` + +Rule: every write that changes a cached field writes the cache too, in the same call. + +### 1.4 Event-fed observability + +Lifecycle event helpers in `events.rs` also record usage in `analytics`, and `analytics` hands each +event to `monitoring` ([ADR 0003](./adr/0003-observability-from-event-helpers.md)). Entry points +never call analytics directly, so a new lifecycle event is counted as soon as it uses a helper. + +```mermaid +sequenceDiagram + participant EP as entry point + participant EV as events + participant AN as analytics + participant MON as monitoring + EP->>EV: payment_received(...) + EV->>AN: record(PaymentReceived, amount) + AN->>MON: on_usage(kind, amount) + Note over MON: returns after one instance read
when no rules exist +``` + +### 1.5 Non-reverting side effects + +Work that must never fail the caller (alert delivery, counters) is written so it cannot panic: +external calls use `try_invoke_contract` and counters saturate +([ADR 0005](./adr/0005-alert-delivery.md)). + +### 1.6 Bounded collections + +Any list that an entry point loops over has a cap constant (`MAX_ALERT_RULES`, +`MAX_PROFILED_OPERATIONS`, `MAX_SPLIT_RULES`, …). The cap is checked on insert, so the loop cost is +known when the budget is set. + +### 1.7 Schema-gated admin path + +`require_admin` calls `migrations::require_schema_current` before checking auth, so no admin action +runs against storage written by an older schema until the migration has run. + +```mermaid +stateDiagram-v2 + [*] --> Current: schema_version == CURRENT + Current --> Stale: upgrade with new CURRENT_SCHEMA_VERSION + Stale --> Stale: admin call panics "MigrationRequired" + Stale --> Current: migration runs +``` + +--- + +## 2. Examples + +### 2.1 Authorisation then schema check (`lib.rs`) + +```rust +fn require_admin(env: &Env) -> Address { + migrations::require_schema_current(env); + let admin: Address = env + .storage() + .instance() + .get(&admin_key()) + .expect("admin not set"); + admin.require_auth(); + admin +} +``` + +### 2.2 Delivery that cannot revert the caller (`monitoring.rs`) + +```rust +if let Some(receiver) = get_receiver(env) { + let mut args: Vec = Vec::new(env); + args.push_back(alert.clone().into_val(env)); + let res = env.try_invoke_contract::( + &receiver, + &Symbol::new(env, RECEIVER_FN), + args, + ); + let ok = matches!(res, Ok(Ok(_))); + alert.delivered = Some(ok); + if !ok { + stats.failed_deliveries = stats.failed_deliveries.saturating_add(1); + } +} +``` + +### 2.3 Bounded insert (`record_compute_usage` in `lib.rs`) + +```rust +if !ops.iter().any(|o| o == operation) { + assert!(ops.len() < MAX_PROFILED_OPERATIONS, "too many profiled operations"); + ops.push_back(operation.clone()); + env.storage().persistent().set(&cost_profiled_ops_key(), &ops); +} +``` + +### 2.4 TTL bump helper (`storage.rs`) + +```rust +pub fn bump_persistent_ttl(env: &Env, key: &K) +where + K: IntoVal + Clone, +{ + env.storage() + .persistent() + .extend_ttl(key, MIN_INVOICE_TTL_LEDGERS, MAX_INVOICE_TTL_LEDGERS); +} +``` + +### 2.5 Pure slice with tests (`tiered_access.rs`) + +```rust +/// 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) + } +} +``` + +### 2.6 Adding a feature end to end + +1. Add a module `my_feature.rs` with pure helpers and `#[cfg(test)] mod tests`. +2. Declare it in `lib.rs` next to the other modules, with an `// Issue #N:` comment. +3. Add storage keys through `storage_keys.rs` and list them in + [`STORAGE_KEY_REGISTRY.md`](../STORAGE_KEY_REGISTRY.md). +4. Add the entry point in `lib.rs`: auth check, module call, event through `events.rs`. +5. Append any new `ContractError` variant at the end (see [`CONTRIBUTING.md`](../CONTRIBUTING.md)). +6. Document the entry point in [`API.md`](./API.md). + +--- + +## 3. Optimization guide + +The full guide is [`PERFORMANCE_TUNING.md`](./PERFORMANCE_TUNING.md). The patterns above map to it +as follows: + +| Pattern | Saves | How | +|---|---|---| +| Hot-path cache (1.3) | Persistent reads on `pay()` | Read `InvoiceHot` from instance storage first | +| Split record (1.3) | Entry size and write cost | Write only the part (`Core`, `Ext`, `Ext2`) that changed | +| Event-fed observability (1.4) | Instructions when unused | `on_usage` exits after one read when no rules exist | +| Bounded collections (1.6) | Worst-case instructions | Cap checked on insert, never on read | +| Pure first slice (1.2) | WASM size | No entry point until the feature is wired | +| Non-reverting side effects (1.5) | Failed transactions | `try_invoke_contract`, saturating counters | + +Measure with `estimate_compute` and calibrate with `record_compute_usage` / +`get_compute_cost_report`; the `perf_profiling` helpers turn those profiles into per-operation +insights (`NeedsMoreSamples`, `Volatile`, `LowAccuracy`, `Healthy`). + +--- + +## 4. Reference + +| Concern | Where | Key items | +|---|---|---| +| Entry points | `lib.rs` | `#[contractimpl]` blocks, `require_admin`, `require_admin_role`, `require_role` | +| Errors | `error.rs` | `ContractError` (append-only discriminants) | +| Events | `events.rs` | `(split, action, id?)` topics, `event_seq` | +| Storage tiers | `storage.rs`, `storage_keys.rs` | `bump_instance_ttl`, `bump_persistent_ttl`, `bump_temporary_ttl` | +| Invoice records | `types.rs` | `InvoiceCore`, `InvoiceExt`, `InvoiceExt2`, `InvoiceHot`, `CompactInvoice` | +| Schema | `migrations.rs` | `CURRENT_SCHEMA_VERSION`, `require_schema_current` | +| Observability | `analytics.rs`, `monitoring.rs`, `stats.rs` | `record`, `on_usage`, `check_all`, `get_stats` | +| Cost | `lib.rs`, `perf_profiling.rs` | `estimate_operation_cost`, `record_compute_usage`, `metrics`, `insight` | +| Decisions | [`adr/`](./adr/README.md) | ADR 0001-0005 | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b6b5c00..ef5a704 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -482,6 +482,7 @@ Feature-level design notes are in the `docs/ISSUE_*.md` files. Repository: +- [`ADVANCED_ARCHITECTURE.md`](./ADVANCED_ARCHITECTURE.md): patterns, examples and optimization guide - [`API.md`](./API.md): entry point reference - [`ERROR_CODES.md`](./ERROR_CODES.md): `ContractError` codes - [`FEE_FLOW.md`](./FEE_FLOW.md): fee calculation From f27fa6e58d6bfcc182b2a087f9cda3fe04b07bc4 Mon Sep 17 00:00:00 2001 From: Muhammadcodes112 Date: Mon, 23 Nov 2026 23:08:25 +0100 Subject: [PATCH 3/4] Add contract health monitoring and alert thresholds (#1187) --- contracts/split/src/contract_health.rs | 181 +++++++++++++++++++++++++ contracts/split/src/lib.rs | 2 + 2 files changed, 183 insertions(+) create mode 100644 contracts/split/src/contract_health.rs diff --git a/contracts/split/src/contract_health.rs b/contracts/split/src/contract_health.rs new file mode 100644 index 0000000..9e85b82 --- /dev/null +++ b/contracts/split/src/contract_health.rs @@ -0,0 +1,181 @@ +//! Issue #1187: contract health assessment over monitoring stats (first slice). +//! +//! Builds on the alerting system from issue #1033 (`monitoring`). [`delta`] +//! counts the alerts and failed deliveries raised between two +//! [`MonitoringStats`] snapshots, [`assess`] turns that window plus the current +//! unacknowledged backlog into a [`HealthStatus`] using configurable +//! [`HealthThresholds`], and [`HealthLog`] tracks the outcome of each check. + +#![allow(dead_code)] + +use crate::monitoring::MonitoringStats; + +/// Overall contract health, ordered from best to worst. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum HealthStatus { + /// No threshold exceeded. + Healthy, + /// A warning-level threshold exceeded. + Degraded, + /// A critical-level threshold exceeded. + Critical, +} + +/// Configurable limits for one health check window. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct HealthThresholds { + /// Unacknowledged alerts tolerated before the contract is degraded. + pub max_unacknowledged: u64, + /// New warning alerts tolerated in the window. + pub max_new_warnings: u64, + /// New failed deliveries tolerated in the window. + pub max_failed_deliveries: u64, + /// New critical alerts tolerated in the window. + pub max_new_critical: u64, +} + +impl Default for HealthThresholds { + fn default() -> Self { + HealthThresholds { + max_unacknowledged: 10, + max_new_warnings: 5, + max_failed_deliveries: 0, + max_new_critical: 0, + } + } +} + +/// Alerts and delivery failures raised between two snapshots. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct HealthDelta { + /// New alerts of any severity. + pub new_alerts: u64, + /// New warning alerts. + pub new_warnings: u64, + /// New critical alerts. + pub new_critical: u64, + /// New failed deliveries. + pub new_failed_deliveries: u64, +} + +/// Result of one health check. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct HealthReport { + /// Overall status. + pub status: HealthStatus, + /// Activity in the checked window. + pub delta: HealthDelta, + /// Unacknowledged alerts at the end of the window. + pub unacknowledged: u64, +} + +/// Counts activity between `prev` and `cur` (saturating at zero if counters were reset). +pub fn delta(prev: &MonitoringStats, cur: &MonitoringStats) -> HealthDelta { + HealthDelta { + new_alerts: cur.total_alerts.saturating_sub(prev.total_alerts), + new_warnings: cur.warning_alerts.saturating_sub(prev.warning_alerts), + new_critical: cur.critical_alerts.saturating_sub(prev.critical_alerts), + new_failed_deliveries: cur.failed_deliveries.saturating_sub(prev.failed_deliveries), + } +} + +/// Assesses health for the window from `prev` to `cur`. +pub fn assess( + prev: &MonitoringStats, + cur: &MonitoringStats, + thresholds: &HealthThresholds, +) -> HealthReport { + let d = delta(prev, cur); + let status = if d.new_critical > thresholds.max_new_critical { + HealthStatus::Critical + } else if cur.unacknowledged > thresholds.max_unacknowledged + || d.new_warnings > thresholds.max_new_warnings + || d.new_failed_deliveries > thresholds.max_failed_deliveries + { + HealthStatus::Degraded + } else { + HealthStatus::Healthy + }; + HealthReport { status, delta: d, unacknowledged: cur.unacknowledged } +} + +/// Running record of health checks. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct HealthLog { + /// Checks recorded. + pub checks: u64, + /// Checks that ended degraded. + pub degraded: u64, + /// Checks that ended critical. + pub critical: u64, + /// Status of the most recent check. + pub last_status: Option, +} + +impl HealthLog { + /// Records a report; returns true when the status changed from the previous check. + pub fn record(&mut self, report: &HealthReport) -> bool { + self.checks = self.checks.saturating_add(1); + match report.status { + HealthStatus::Degraded => self.degraded = self.degraded.saturating_add(1), + HealthStatus::Critical => self.critical = self.critical.saturating_add(1), + HealthStatus::Healthy => {} + } + let changed = self.last_status != Some(report.status); + self.last_status = Some(report.status); + changed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stats(warn: u64, crit: u64, failed: u64, unacked: u64) -> MonitoringStats { + MonitoringStats { + total_alerts: warn + crit, + warning_alerts: warn, + critical_alerts: crit, + failed_deliveries: failed, + unacknowledged: unacked, + ..Default::default() + } + } + + #[test] + fn assess_uses_thresholds() { + let t = HealthThresholds::default(); + let base = stats(2, 1, 0, 3); + + let quiet = assess(&base, &stats(3, 1, 0, 4), &t); + assert_eq!(quiet.status, HealthStatus::Healthy); + assert_eq!(quiet.delta.new_alerts, 1); + + assert_eq!(assess(&base, &stats(2, 2, 0, 4), &t).status, HealthStatus::Critical); + assert_eq!(assess(&base, &stats(2, 1, 1, 3), &t).status, HealthStatus::Degraded); + assert_eq!(assess(&base, &stats(2, 1, 0, 11), &t).status, HealthStatus::Degraded); + assert_eq!(assess(&base, &stats(8, 1, 0, 3), &t).status, HealthStatus::Degraded); + + let lenient = HealthThresholds { max_new_critical: 1, ..t }; + assert_eq!(assess(&base, &stats(2, 2, 0, 4), &lenient).status, HealthStatus::Healthy); + } + + #[test] + fn delta_saturates_after_reset() { + assert_eq!(delta(&stats(5, 5, 5, 0), &MonitoringStats::default()), HealthDelta::default()); + } + + #[test] + fn log_tracks_checks_and_changes() { + let t = HealthThresholds::default(); + let base = stats(0, 0, 0, 0); + let mut log = HealthLog::default(); + assert!(log.record(&assess(&base, &base, &t))); + assert!(!log.record(&assess(&base, &base, &t))); + assert!(log.record(&assess(&base, &stats(0, 1, 0, 1), &t))); + assert_eq!(log.checks, 3); + assert_eq!(log.critical, 1); + assert_eq!(log.degraded, 0); + assert_eq!(log.last_status, Some(HealthStatus::Critical)); + } +} diff --git a/contracts/split/src/lib.rs b/contracts/split/src/lib.rs index b7d6e24..8025038 100644 --- a/contracts/split/src/lib.rs +++ b/contracts/split/src/lib.rs @@ -159,6 +159,8 @@ pub mod audit_logging; pub mod rate_limiting; // Issue #1190: Performance profiling report helpers. mod perf_profiling; +// Issue #1187: Contract health assessment over monitoring stats. +mod contract_health; use error::ContractError; use validation::assert_valid_bps; From ce014f2ba8bd9f9a65799d2484a529a33816cea7 Mon Sep 17 00:00:00 2001 From: Muhammadcodes112 Date: Mon, 23 Nov 2026 23:09:15 +0100 Subject: [PATCH 4/4] Add invoice delegation with permission levels (#1185) --- contracts/split/src/invoice_delegation.rs | 258 ++++++++++++++++++++++ contracts/split/src/lib.rs | 2 + 2 files changed, 260 insertions(+) create mode 100644 contracts/split/src/invoice_delegation.rs diff --git a/contracts/split/src/invoice_delegation.rs b/contracts/split/src/invoice_delegation.rs new file mode 100644 index 0000000..40321f1 --- /dev/null +++ b/contracts/split/src/invoice_delegation.rs @@ -0,0 +1,258 @@ +//! Issue #1185: invoice delegation with permission levels (first slice). +//! +//! Extends the single all-rights invoice delegate from issue #43 with +//! per-delegate [`DelegationLevel`]s, optional expiry, revocation and +//! tracking. [`DelegationRegistry`] is a fixed-size table keyed by invoice id +//! and delegate id; [`DelegationRegistry::authorize`] checks a +//! [`DelegatedAction`] against the delegate's active level. + +#![allow(dead_code)] + +/// Maximum delegations held by a [`DelegationRegistry`]. +pub const MAX_DELEGATIONS: usize = 16; + +/// Permission levels, ordered lowest to highest. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub enum DelegationLevel { + /// Read invoice details. + View = 0, + /// Day-to-day management (deadline, metadata). + Manage = 1, + /// Everything the creator can do except delegating further. + Full = 2, +} + +/// Actions a delegate may perform on an invoice. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DelegatedAction { + /// Read invoice details. + ViewInvoice, + /// Extend the invoice deadline. + ExtendDeadline, + /// Update invoice metadata. + UpdateMetadata, + /// Cancel the invoice. + CancelInvoice, +} + +/// Errors returned by delegation operations. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DelegationError { + /// The delegate's level does not allow the action, or it has no active delegation. + Unauthorized, + /// An active delegation already exists for this invoice and delegate. + AlreadyDelegated, + /// No active delegation for this invoice and delegate. + NotFound, + /// The expiry is not after the grant time. + InvalidExpiry, + /// Registry is full. + RegistryFull, +} + +/// One delegation of an invoice to a delegate. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Delegation { + /// Invoice identifier. + pub invoice_id: u64, + /// Delegate identifier. + pub delegate: u64, + /// Granted level. + pub level: DelegationLevel, + /// Grant time. + pub granted_at: u64, + /// Expiry time; 0 means no expiry. + pub expires_at: u64, +} + +impl Delegation { + /// True when the delegation has not expired at `now`. + pub fn is_active(&self, now: u64) -> bool { + self.expires_at == 0 || now < self.expires_at + } +} + +/// Minimum level required for an action. +pub fn required_level(action: DelegatedAction) -> DelegationLevel { + match action { + DelegatedAction::ViewInvoice => DelegationLevel::View, + DelegatedAction::ExtendDeadline | DelegatedAction::UpdateMetadata => { + DelegationLevel::Manage + } + DelegatedAction::CancelInvoice => DelegationLevel::Full, + } +} + +/// Fixed-size delegation table with grant/revoke counters. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct DelegationRegistry { + entries: [Option; MAX_DELEGATIONS], + /// Delegations granted (saturating). + pub granted: u32, + /// Delegations revoked (saturating). + pub revoked: u32, +} + +impl DelegationRegistry { + fn position(&self, invoice_id: u64, delegate: u64) -> Option { + self.entries.iter().position(|e| { + matches!(e, Some(d) if d.invoice_id == invoice_id && d.delegate == delegate) + }) + } + + /// Grants `level` on `invoice_id` to `delegate`. An expired entry for the + /// same pair is replaced. + pub fn grant( + &mut self, + invoice_id: u64, + delegate: u64, + level: DelegationLevel, + now: u64, + expires_at: u64, + ) -> Result<(), DelegationError> { + if expires_at != 0 && expires_at <= now { + return Err(DelegationError::InvalidExpiry); + } + let slot = match self.position(invoice_id, delegate) { + Some(i) if self.entries[i].map(|d| d.is_active(now)).unwrap_or(false) => { + return Err(DelegationError::AlreadyDelegated); + } + Some(i) => i, + None => self + .entries + .iter() + .position(|e| e.is_none()) + .ok_or(DelegationError::RegistryFull)?, + }; + self.entries[slot] = + Some(Delegation { invoice_id, delegate, level, granted_at: now, expires_at }); + self.granted = self.granted.saturating_add(1); + Ok(()) + } + + /// Revokes the delegation for `invoice_id` and `delegate`. + pub fn revoke(&mut self, invoice_id: u64, delegate: u64) -> Result<(), DelegationError> { + let i = self.position(invoice_id, delegate).ok_or(DelegationError::NotFound)?; + self.entries[i] = None; + self.revoked = self.revoked.saturating_add(1); + Ok(()) + } + + /// Revokes every delegation on `invoice_id`; returns how many were removed. + pub fn revoke_all(&mut self, invoice_id: u64) -> u32 { + let mut removed = 0u32; + for e in self.entries.iter_mut() { + if matches!(e, Some(d) if d.invoice_id == invoice_id) { + *e = None; + removed += 1; + } + } + self.revoked = self.revoked.saturating_add(removed); + removed + } + + /// Returns the delegation for the pair, if any (active or expired). + pub fn get(&self, invoice_id: u64, delegate: u64) -> Option { + self.position(invoice_id, delegate).and_then(|i| self.entries[i]) + } + + /// Active level of `delegate` on `invoice_id` at `now`. + pub fn level_of(&self, invoice_id: u64, delegate: u64, now: u64) -> Option { + self.get(invoice_id, delegate).filter(|d| d.is_active(now)).map(|d| d.level) + } + + /// Returns an error unless `delegate` may perform `action` on `invoice_id` at `now`. + pub fn authorize( + &self, + invoice_id: u64, + delegate: u64, + action: DelegatedAction, + now: u64, + ) -> Result<(), DelegationError> { + match self.level_of(invoice_id, delegate, now) { + Some(level) if level >= required_level(action) => Ok(()), + _ => Err(DelegationError::Unauthorized), + } + } + + /// Number of active delegations on `invoice_id` at `now`. + pub fn active_count(&self, invoice_id: u64, now: u64) -> u32 { + self.entries + .iter() + .flatten() + .filter(|d| d.invoice_id == invoice_id && d.is_active(now)) + .count() as u32 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn levels_enforce_actions() { + let mut r = DelegationRegistry::default(); + r.grant(1, 10, DelegationLevel::Manage, 100, 0).unwrap(); + assert!(r.authorize(1, 10, DelegatedAction::ViewInvoice, 100).is_ok()); + assert!(r.authorize(1, 10, DelegatedAction::ExtendDeadline, 100).is_ok()); + assert_eq!( + r.authorize(1, 10, DelegatedAction::CancelInvoice, 100), + Err(DelegationError::Unauthorized) + ); + assert_eq!( + r.authorize(2, 10, DelegatedAction::ViewInvoice, 100), + Err(DelegationError::Unauthorized) + ); + assert_eq!( + r.grant(1, 10, DelegationLevel::Full, 100, 0), + Err(DelegationError::AlreadyDelegated) + ); + } + + #[test] + fn expiry_and_regrant() { + let mut r = DelegationRegistry::default(); + assert_eq!( + r.grant(1, 10, DelegationLevel::View, 100, 100), + Err(DelegationError::InvalidExpiry) + ); + r.grant(1, 10, DelegationLevel::Full, 100, 200).unwrap(); + assert_eq!(r.level_of(1, 10, 199), Some(DelegationLevel::Full)); + assert_eq!(r.level_of(1, 10, 200), None); + r.grant(1, 10, DelegationLevel::View, 200, 0).unwrap(); + assert_eq!(r.level_of(1, 10, 500), Some(DelegationLevel::View)); + assert_eq!(r.granted, 2); + } + + #[test] + fn revocation_and_tracking() { + let mut r = DelegationRegistry::default(); + r.grant(1, 10, DelegationLevel::View, 0, 0).unwrap(); + r.grant(1, 11, DelegationLevel::Manage, 0, 0).unwrap(); + r.grant(2, 10, DelegationLevel::Full, 0, 0).unwrap(); + assert_eq!(r.active_count(1, 0), 2); + + r.revoke(1, 10).unwrap(); + assert_eq!(r.revoke(1, 10), Err(DelegationError::NotFound)); + assert_eq!( + r.authorize(1, 10, DelegatedAction::ViewInvoice, 0), + Err(DelegationError::Unauthorized) + ); + assert_eq!(r.revoke_all(1), 1); + assert_eq!(r.active_count(1, 0), 0); + assert_eq!(r.active_count(2, 0), 1); + assert_eq!((r.granted, r.revoked), (3, 2)); + } + + #[test] + fn registry_full() { + let mut r = DelegationRegistry::default(); + for i in 0..MAX_DELEGATIONS as u64 { + r.grant(1, i, DelegationLevel::View, 0, 0).unwrap(); + } + assert_eq!( + r.grant(1, 99, DelegationLevel::View, 0, 0), + Err(DelegationError::RegistryFull) + ); + } +} diff --git a/contracts/split/src/lib.rs b/contracts/split/src/lib.rs index 8025038..334d57b 100644 --- a/contracts/split/src/lib.rs +++ b/contracts/split/src/lib.rs @@ -161,6 +161,8 @@ pub mod rate_limiting; mod perf_profiling; // Issue #1187: Contract health assessment over monitoring stats. mod contract_health; +// Issue #1185: Invoice delegation with permission levels. +mod invoice_delegation; use error::ContractError; use validation::assert_valid_bps;