Skip to content

Latest commit

 

History

History
1149 lines (912 loc) · 35.3 KB

File metadata and controls

1149 lines (912 loc) · 35.3 KB

Phase 3.4: Security Audit Framework

Overview

This document defines the security framework for the agentic tokenomics system, including threat models, attack vector analysis, security invariants, and audit procedures.


Threat Model

System Boundaries

┌─────────────────────────────────────────────────────────────────────────────┐
│                            TRUST BOUNDARY                                    │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                     FULLY TRUSTED ZONE                               │    │
│  │  • Regen Ledger consensus                                           │    │
│  │  • On-chain contract state                                          │    │
│  │  • Validator set (2/3 honest assumption)                            │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                    CONDITIONALLY TRUSTED                             │    │
│  │  • Agent runtime (authenticated, rate-limited)                      │    │
│  │  • MCP servers (authenticated, audited)                             │    │
│  │  • KOI knowledge base (integrity-verified)                          │    │
│  │  • Human operators (with escalation)                                │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
├─────────────────────────────────────────────────────────────────────────────┤
│                            UNTRUSTED ZONE                                    │
│  • External API responses                                                    │
│  • User inputs                                                               │
│  • Third-party data sources                                                  │
│  • Network transport (mitigated by TLS)                                     │
└─────────────────────────────────────────────────────────────────────────────┘

Threat Actors

Actor Capability Motivation Target Assets
Malicious Attester Submit false attestations Economic gain Attestation bonds, reputation
Market Manipulator Large capital, multiple accounts Profit from manipulation Credit prices, liquidity
Rogue Agent Operator Access to agent keys Sabotage, profit Agent authority, trust
External Attacker Network access, exploit knowledge Financial gain, disruption All systems
Insider Threat System access, privileged credentials Various Sensitive data, funds
Compromised Validator Up to 1/3 stake Censorship, manipulation Consensus, governance

Asset Inventory

Asset Value Confidentiality Integrity Availability
Bonded tokens (M008, M009, M011) High Low Critical High
Reputation scores (M010) Medium Low Critical Medium
Agent private keys Critical Critical Critical High
KOI knowledge data Medium Medium High Medium
Governance decisions High Low Critical High
User credentials Medium Critical High Medium

Attack Vector Analysis

AV-001: Attestation Fraud

attack_id: AV-001
name: Attestation Fraud
category: Economic Attack
severity: HIGH

description: |
  Attacker submits false attestation with bond, hoping economic value of
  fraud exceeds bond amount before challenge.

attack_flow:
  1. Attacker creates false attestation with minimum bond
  2. False attestation used to claim benefits (e.g., credit issuance)
  3. Challenge window passes without detection
  4. Attacker recovers bond + fraudulent gains

preconditions:
  - Challenge window too short for verification
  - Bond amount too low relative to potential fraud value
  - Insufficient monitoring/detection mechanisms

mitigations:
  - Dynamic bond sizing based on attestation value
  - Mandatory challenge period scaling with attestation impact
  - Agent-assisted anomaly detection
  - Whistleblower incentives (% of slashed bond)

detection:
  - Anomalous attestation patterns
  - Velocity of attestations from single address
  - Correlation with on-chain benefit claims

residual_risk: MEDIUM (with mitigations)

AV-002: Agent Key Compromise

attack_id: AV-002
name: Agent Key Compromise
category: Infrastructure Attack
severity: CRITICAL

description: |
  Attacker gains access to agent signing keys, enabling unauthorized
  transactions or governance actions.

attack_flow:
  1. Attacker compromises agent infrastructure (phishing, exploit, insider)
  2. Extracts agent private keys from memory/storage
  3. Signs malicious transactions using agent authority
  4. Executes unauthorized actions before detection

preconditions:
  - Keys stored in extractable form
  - Insufficient access controls
  - No transaction signing controls

mitigations:
  - Hardware security modules (HSM) for key storage
  - Multi-signature requirements for high-value actions
  - Transaction value limits with human override
  - Key rotation schedule
  - Anomaly detection on agent behavior

detection:
  - Unusual transaction patterns
  - Geographic anomalies
  - Out-of-hours activity
  - Velocity checks

residual_risk: MEDIUM (with HSM + multi-sig)

AV-003: Oracle/MCP Manipulation

attack_id: AV-003
name: Oracle/MCP Data Manipulation
category: Data Integrity Attack
severity: HIGH

description: |
  Attacker manipulates data provided by MCP servers to influence agent
  decisions or smart contract execution.

attack_flow:
  1. Attacker compromises MCP server or intercepts traffic
  2. Modifies responses to agent queries
  3. Agent makes decisions based on false data
  4. Incorrect recommendations/actions executed

preconditions:
  - Single MCP server trust
  - No response verification
  - Weak authentication

mitigations:
  - Multiple independent data sources
  - Cryptographic response signatures
  - Data freshness verification
  - Anomaly detection on data patterns
  - Consensus across multiple oracles

detection:
  - Data consistency checks
  - Historical deviation alerts
  - Cross-source validation failures

residual_risk: MEDIUM (with multi-source validation)

AV-004: Governance Attack

attack_id: AV-004
name: Agent-Assisted Governance Attack
category: Governance Attack
severity: HIGH

description: |
  Attacker exploits agent's proposal/recommendation authority to push
  malicious governance changes.

attack_flow:
  1. Attacker crafts proposal that appears legitimate
  2. Manipulates inputs to agent (KOI data, community signals)
  3. Agent recommends approval based on false context
  4. Proposal passes with agent endorsement

preconditions:
  - Agent has proposal submission authority
  - Insufficient human review window
  - Community trusts agent recommendations

mitigations:
  - Layer 2+ always requires human review window
  - Confidence threshold for auto-submission
  - Multiple agent consensus for proposals
  - Escalation triggers for unusual proposals
  - Community cooling-off periods

detection:
  - Unusual proposal characteristics
  - Low community engagement
  - Agent confidence anomalies

residual_risk: LOW (with Layer 2+ controls)

AV-005: Escrow Manipulation

attack_id: AV-005
name: Service Escrow Manipulation
category: Economic Attack
severity: HIGH

description: |
  Provider or client manipulates escrow to receive funds without
  fulfilling obligations.

attack_flow:
  Provider attack:
    1. Provider creates agreement with vague milestones
    2. Claims milestone completion with insufficient evidence
    3. Receives funds without delivering
  Client attack:
    1. Client receives service
    2. Disputes milestone with false claims
    3. Recovers escrowed funds while keeping service

preconditions:
  - Vague milestone definitions
  - Insufficient evidence requirements
  - Weak arbitration process

mitigations:
  - Clear milestone criteria in contract
  - Evidence IRI requirements
  - Independent arbitration DAO
  - Reputation system consequences
  - Partial release schedules

detection:
  - Dispute frequency analysis
  - Provider/client reputation patterns
  - Milestone evidence verification

residual_risk: MEDIUM (with arbitration + reputation)

AV-006: Sybil Attack on Reputation

attack_id: AV-006
name: Reputation System Sybil Attack
category: Identity Attack
severity: MEDIUM

description: |
  Attacker creates multiple identities to artificially inflate
  reputation signals.

attack_flow:
  1. Attacker creates multiple addresses
  2. Stakes minimal amounts across addresses
  3. Mutual endorsement between sybil accounts
  4. Inflated reputation used to gain trust

preconditions:
  - Low cost of identity creation
  - No stake-weighted signals
  - Linear reputation aggregation

mitigations:
  - Stake-weighted signal weights
  - Quadratic aggregation
  - On-chain history requirements
  - Social graph analysis
  - Proof of unique identity (optional)

detection:
  - Cluster analysis of endorsement patterns
  - Account age/activity correlation
  - Mutual endorsement detection

residual_risk: LOW (with stake-weighting + graph analysis)

Security Invariants

Smart Contract Invariants

// Attestation Bond Contract Invariants

/// INV-001: Bond conservation
/// Total locked bonds must equal sum of all attestation bonds in locked states.
/// Active is the initial state (bonds lock on creation). Challenged bonds remain locked.
invariant bond_conservation {
    TOTAL_LOCKED == sum(attestation.bond for attestation in ATTESTATIONS where attestation.status in [Active, Challenged])
    // Note: If a pre-activation Bonded state is reintroduced, it must be included
    // in this invariant to account for bonds locked during the activation delay.
}

/// INV-002: State transitions are monotonic
/// Attestations can only progress forward in lifecycle
invariant state_monotonic {
    forall attestation:
        old(attestation.status) == Active => new(attestation.status) in [Active, Challenged, Released, Slashed]
        old(attestation.status) == Challenged => new(attestation.status) in [Challenged, Released, Slashed]
        old(attestation.status) in [Released, Slashed] => new(attestation.status) == old(attestation.status)
}

/// INV-003: Challenge window respected
/// Challenges only accepted within window
invariant challenge_window {
    forall challenge:
        challenge.submitted_at < attestation.challenge_window_closes_at
}

/// INV-004: Only arbiter can resolve disputes
/// Challenged attestations can only be resolved by designated arbiter
invariant arbiter_authority {
    forall resolution:
        resolution.status in [Released, Slashed] AND attestation.status == Challenged
        => resolution.sender == CONFIG.arbiter_dao
}

/// INV-005: Bond minimum enforced
/// All attestations must meet minimum bond requirement
invariant minimum_bond {
    forall attestation:
        attestation.bond >= CONFIG.min_bond
}
// Service Escrow Contract Invariants

/// INV-006: Escrow conservation
/// Escrowed funds must equal sum of milestone values
invariant escrow_conservation {
    agreement.escrow_amount == sum(milestone.amount for milestone in agreement.milestones where milestone.status != Completed)
}

/// INV-007: Milestone progression
/// Milestones must complete in order
invariant milestone_order {
    forall agreement:
        forall i < j:
            milestones[j].status == Completed => milestones[i].status == Completed
}

/// INV-008: Dispute resolution authority
/// Only arbiter can resolve disputes
invariant dispute_authority {
    forall milestone:
        milestone.status == Disputed AND new(milestone.status) in [Completed, Rejected]
        => msg.sender == agreement.arbiter
}
// Reputation Registry Invariants

/// INV-009: Weight bounds
/// Signal weights must be within valid range
invariant weight_bounds {
    forall signal:
        0 <= signal.weight <= 1.0
}

/// INV-010: Self-endorsement prevention
/// Cannot endorse own address
invariant no_self_endorsement {
    forall signal:
        signal.signaler != signal.subject_id (when subject_type == "address")
}

/// INV-011: Stake requirement
/// Signalers must have minimum stake
invariant stake_requirement {
    forall signal:
        get_staked_amount(signal.signaler) >= CONFIG.min_stake_to_signal
}

Agent Behavioral Invariants

# Agent Behavioral Invariants

INV-A001:
  name: Confidence threshold enforcement
  description: Agent must not auto-execute actions when confidence < threshold
  condition: decision.confidence < escalation_threshold => action.type != "execute"
  monitoring: Log all decisions with confidence, alert on violations

INV-A002:
  name: Rate limit compliance
  description: Agent must respect MCP rate limits
  condition: requests_per_minute <= configured_rate_limit
  monitoring: Request counter with sliding window

INV-A003:
  name: Transaction value limits
  description: Agent cannot sign transactions exceeding value limit without multi-sig
  condition: tx.value > agent_tx_limit => requires_human_cosign
  monitoring: Transaction value tracking, alert on limit approach

INV-A004:
  name: Audit trail completeness
  description: All decisions must be logged with full context
  condition: decision => exists(audit_log_entry)
  monitoring: Audit log completeness checks

INV-A005:
  name: Escalation path availability
  description: Human escalation path must always be available
  condition: escalation_requested => human_notified_within_sla
  monitoring: Escalation latency tracking

Security Audit Checklist

Smart Contract Audit

## Pre-Audit Preparation

- [ ] Code freeze complete
- [ ] Full test suite passing
- [ ] Documentation complete
- [ ] Known issues documented

## Static Analysis

### Automated Tools
- [ ] Slither analysis (all critical findings addressed)
- [ ] Mythril symbolic execution
- [ ] Semgrep custom rules
- [ ] Rust clippy (for CosmWasm)
- [ ] cargo-audit for dependencies

### Manual Review
- [ ] Access control review
  - [ ] Admin functions properly protected
  - [ ] Role-based permissions correct
  - [ ] Ownership transfer secure

- [ ] Economic logic review
  - [ ] Bond calculations correct
  - [ ] Fee calculations correct
  - [ ] No integer overflow/underflow
  - [ ] Rounding handled appropriately

- [ ] State management review
  - [ ] State transitions valid
  - [ ] No state corruption paths
  - [ ] Proper initialization

- [ ] External call review
  - [ ] Reentrancy protections
  - [ ] Return value checks
  - [ ] Gas limitations considered

## CosmWasm-Specific Checks

- [ ] No unbounded iteration
- [ ] Proper use of `deps.querier`
- [ ] Reply handling correct
- [ ] Submessage ordering
- [ ] Proper error types

## Test Coverage

- [ ] Unit test coverage > 90%
- [ ] Integration test coverage for critical paths
- [ ] Fuzzing results reviewed
- [ ] Edge cases tested

## Documentation

- [ ] All public functions documented
- [ ] State transitions documented
- [ ] Invariants documented
- [ ] Admin procedures documented

Agent Security Audit

## Infrastructure Security

- [ ] Key management
  - [ ] HSM usage for signing keys
  - [ ] Key rotation procedures
  - [ ] Backup and recovery tested

- [ ] Network security
  - [ ] TLS everywhere
  - [ ] mTLS for MCP connections
  - [ ] No exposed internal endpoints

- [ ] Container security
  - [ ] Minimal base images
  - [ ] No root processes
  - [ ] Read-only filesystems where possible
  - [ ] Resource limits configured

## Application Security

- [ ] Input validation
  - [ ] All external inputs validated
  - [ ] Injection prevention
  - [ ] Size limits enforced

- [ ] Authentication & authorization
  - [ ] API authentication verified
  - [ ] Permission model correct
  - [ ] Session management secure

- [ ] Secrets management
  - [ ] No hardcoded secrets
  - [ ] Secrets properly injected
  - [ ] Secrets rotatable

## Behavioral Security

- [ ] Decision logging
  - [ ] All decisions logged
  - [ ] Context preserved
  - [ ] Logs tamper-evident

- [ ] Rate limiting
  - [ ] MCP rate limits enforced
  - [ ] Transaction rate limits
  - [ ] Resource consumption limits

- [ ] Escalation paths
  - [ ] Human review triggers working
  - [ ] Notification delivery verified
  - [ ] Timeout handling correct

MCP Integration Security

## Authentication

- [ ] API key rotation supported
- [ ] mTLS configuration correct
- [ ] Token expiration handled

## Data Integrity

- [ ] Response signature verification
- [ ] Timestamp freshness checks
- [ ] Cross-source validation

## Availability

- [ ] Failover mechanisms
- [ ] Graceful degradation
- [ ] Circuit breakers configured

## Privacy

- [ ] Minimal data exposure
- [ ] PII handling correct
- [ ] Audit log retention policy

Incident Response Plan

Severity Classification

Severity Definition Response Time Escalation
P0 - Critical Active exploit, fund loss risk Immediate CEO, Security Lead, Legal
P1 - High Vulnerability discovered, no active exploit < 1 hour Security Lead, Engineering Lead
P2 - Medium Security issue, low immediate risk < 4 hours Security Team
P3 - Low Minor issue, hardening opportunity < 24 hours Security Team

Response Procedures

P0_Critical_Response:
  immediate_actions:
    - Activate incident channel
    - Pause affected contracts (if possible)
    - Disable affected agents
    - Preserve evidence

  investigation:
    - Identify attack vector
    - Assess scope and impact
    - Identify affected users/funds

  containment:
    - Implement immediate fix or disable
    - Block attacker addresses (if identified)
    - Secure remaining assets

  communication:
    - Internal notification (< 15 min)
    - Community notification (< 1 hour for fund-affecting)
    - Regulatory notification (if required)

  recovery:
    - Deploy fix after review
    - Gradual service restoration
    - User compensation plan (if applicable)

  post_incident:
    - Root cause analysis
    - Process improvement
    - Public post-mortem

Emergency Contacts

security_team:
  primary: security@regen.network
  pager: +1-XXX-XXX-XXXX

on_call_rotation:
  schedule: 24/7
  escalation_path:
    1. On-call engineer (5 min)
    2. Security lead (15 min)
    3. CTO (30 min)

external_contacts:
  legal: legal@regen.network
  auditor: security-firm@example.com
  bug_bounty: immunefi.com/bounty/regen

Bug Bounty Program

Scope

in_scope:
  smart_contracts:
    - attestation-bond
    - service-escrow
    - reputation-registry
    - marketplace-curation

  infrastructure:
    - Agent runtime (critical functions only)
    - MCP servers (authentication bypass, data manipulation)

  websites:
    - app.regen.network (authentication, authorization)
    - api.regen.network (data exposure)

out_of_scope:
  - Third-party services
  - Social engineering
  - Physical attacks
  - DoS (unless protocol-level)

Rewards

Severity Smart Contract Infrastructure Web
Critical $50,000 - $100,000 $20,000 - $50,000 $10,000 - $25,000
High $10,000 - $50,000 $5,000 - $20,000 $2,500 - $10,000
Medium $2,500 - $10,000 $1,000 - $5,000 $500 - $2,500
Low $500 - $2,500 $250 - $1,000 $100 - $500

Reporting Process

reporting:
  platform: Immunefi
  url: https://immunefi.com/bounty/regen

  required_info:
    - Vulnerability description
    - Steps to reproduce
    - Impact assessment
    - Suggested fix (optional)

  response_sla:
    initial_response: 24 hours
    triage: 72 hours
    resolution_timeline: case-by-case

  disclosure:
    policy: coordinated
    timeline: 90 days after fix

Compliance Requirements

Data Protection

gdpr_compliance:
  personal_data:
    - Agent decision logs (may contain addresses)
    - User preferences
    - Escalation records

  requirements:
    - Data minimization
    - Purpose limitation
    - Storage limitation
    - Right to access
    - Right to erasure (where technically feasible)

  implementation:
    - Pseudonymization of addresses in logs
    - Retention policies (30 days for operational, 7 years for audit)
    - Data export functionality

Financial Regulations

aml_considerations:
  high_value_transactions:
    - Escrow agreements > threshold
    - Bond releases > threshold

  monitoring:
    - Transaction pattern analysis
    - Address screening (if required)
    - Suspicious activity reporting

  note: |
    Specific requirements depend on jurisdiction and regulatory
    classification. Legal review required before mainnet launch.

Economic Reboot Attack Vectors (M012-M015)

AV-007: Fee Manipulation Attack

attack_id: AV-007
name: Fee Manipulation
category: Economic Attack
severity: HIGH
target_mechanism: M013 (Fee Routing)

description: |
  Attacker manipulates credit reference prices to minimize fees on
  high-value transactions, or inflates reference prices to grief other users
  with excessive fees.

attack_flow:
  1. Attacker creates wash trades at artificially low prices to suppress
     the marketplace reference price for a credit class
  2. Issues a large batch of credits; fee is calculated on deflated reference
  3. Attacker pays minimal fee on high-value issuance
  4. Reference price recovers; attacker has extracted value

preconditions:
  - Issuance fee uses marketplace_reference pricing (OQ-M013-2)
  - Insufficient trade volume for robust median calculation
  - No time-weighted average or outlier filtering

mitigations:
  - Time-weighted average price (TWAP) over 7 days instead of spot price
  - Outlier filtering: discard trades > 3 standard deviations from median
  - Minimum fee floor (1 REGEN) limits downside of price manipulation
  - Rate bound safety (max 10%) limits upside of price inflation
  - AGENT-003 price anomaly detection (WF-MM-01) flags wash trades
  - Governance-set reference price fallback when marketplace volume is low

detection:
  - Sudden drops in reference price before large issuance events
  - Address correlation between wash traders and batch issuers
  - Fee revenue anomalies (WF-MM-05)

residual_risk: MEDIUM (with TWAP and outlier filtering)

AV-008: Supply Oracle Manipulation

attack_id: AV-008
name: Supply Oracle Manipulation
category: Economic Attack
severity: MEDIUM
target_mechanism: M012 (Dynamic Supply)

description: |
  If the ecological_multiplier is sourced from an external oracle,
  an attacker who compromises the oracle can manipulate the regrowth rate
  — inflating minting or suppressing it.

attack_flow:
  1. Attacker compromises or bribes the ecological data oracle
  2. Reports favorable ΔCO₂ data to maximize ecological_multiplier
  3. Regrowth rate increases; excess minting dilutes existing holders
  4. Alternatively: reports unfavorable data to suppress minting entirely

preconditions:
  - ecological_multiplier_enabled = true
  - Single oracle source without redundancy
  - No on-chain validation of oracle inputs

mitigations:
  - v0 deployment: ecological_multiplier disabled (hardcoded 1.0)
  - Multi-oracle aggregation with outlier rejection (when enabled)
  - Bounded ecological_multiplier: floor at 0, practical ceiling around 1.5
  - On-chain verification against M008 attestation data where possible
  - Governance can disable ecological_multiplier via parameter change
  - Parameter bound safety: regrowth rate capped at 10% regardless

detection:
  - AGENT-003 supply monitoring (WF-MM-06) tracks multiplier values
  - Anomalous regrowth rate changes without corresponding on-chain activity
  - Discrepancy between oracle data and M008 attestation trends

residual_risk: LOW (v0 disabled; MEDIUM when oracle is activated)

AV-009: PoA Governance Capture

attack_id: AV-009
name: Authority Validator Governance Capture
category: Governance Attack
severity: CRITICAL
target_mechanism: M014 (Authority Validator Governance)

description: |
  A coordinated group gains control of a majority of the authority validator
  set (>10 of 21) through the application process, enabling them to control
  block production and governance votes.

attack_flow:
  1. Attacker creates multiple organizations that qualify across categories
  2. Organizations apply as authority validators, presenting legitimate credentials
  3. Over 2-3 term cycles, attacker accumulates sufficient validators
  4. Coordinated validators control 2/3+ of consensus
  5. Validators can censor transactions, pass favorable governance proposals,
     or redirect fee revenue

preconditions:
  - Composition requirements insufficient to prevent capture
  - Application vetting does not detect coordinated ownership
  - No beneficial ownership disclosure requirements

mitigations:
  - Composition guarantee: min 5 per category prevents single-category capture
  - Term limits (12 months) with re-application requirement
  - AGENT-004 monitors validator set for behavioral correlation
  - Validator governance (Layer 3) requires broad community approval, not
    self-approval by existing validators (Security Invariant 3)
  - Dual-track voting: even with validator capture, token holder track (40%)
    can veto malicious proposals
  - Constitutional changes (Layer 4) require 67% supermajority including
    token holders, making fundamental changes harder to ram through
  - KYC/beneficial ownership requirements for validator applicants

detection:
  - Correlation analysis: voting patterns, commission behavior, geographic co-location
  - AGENT-004 flags validators with correlated downtime or voting patterns
  - Community governance participation monitoring

residual_risk: MEDIUM (with composition requirements + dual-track voting)

AV-010: Reward Gaming / Wash Trading

attack_id: AV-010
name: Activity Reward Gaming
category: Economic Attack
severity: HIGH
target_mechanism: M015 (Contribution-Weighted Rewards)

description: |
  Attacker generates artificial on-chain activity (purchases, retirements)
  to inflate their activity score and claim disproportionate rewards.

attack_flow:
  1. Attacker creates credits through a controlled class/project
  2. Lists credits at market price, buys from self (wash trade)
  3. Retires credits (generating both purchase and retirement activity)
  4. Accumulates high activity score
  5. Claims large share of activity pool rewards

preconditions:
  - Rewards exceed M013 fees paid on wash transactions
  - No effective Sybil detection
  - Circular activity not penalized

mitigations:
  - M013 fees extract real value on every transaction: issuance 2%,
    trade 1%, retirement 0.5% — creating structural friction
  - Minimum activity value threshold filters micro-transactions
  - No double-counting: buyer gets purchase credit, retiree gets retirement
    credit — same address cannot claim both on the same transaction unless
    they are actually performing both roles
  - Activity weights ensure no single activity type dominates
  - AGENT-003 (WF-VM-05) monitors for wash trading patterns
  - Proposal anti-gaming: zero reward weight for proposals not reaching quorum
  - Address correlation analysis: flag addresses with circular flow patterns
  - Revenue constraint: rewards pool is capped by actual fee revenue,
    limiting the total available to game

detection:
  - Circular flow analysis: credits issued → bought → retired by same/related addresses
  - Fee-to-reward ratio monitoring per address
  - Statistical outlier detection on activity scores
  - AGENT-003 wash trading alerts

residual_risk: MEDIUM (M013 fees make profitable wash trading structurally difficult)

AV-011: Validator Fund Drain

attack_id: AV-011
name: Validator Fund Drain
category: Economic Attack
severity: HIGH
target_mechanism: M014 Compensation + M013 Fee Routing

description: |
  A compromised or colluding validator set manipulates performance metrics
  to maximize their bonus pool allocation, or approves additional validators
  to dilute competitors' compensation while directing governance-controlled
  funds to accomplices.

attack_flow:
  1. Colluding validators game AGENT-004 performance metrics
  2. Inflate ecosystem_contribution_score through fake KOI artifacts
  3. Submit governance proposal to increase performance_bonus_share
  4. Colluding set captures majority of performance bonus pool

preconditions:
  - Performance bonus enabled (performance_bonus_share_bps > 0)
  - AGENT-004 ecosystem contribution scoring is gameable
  - Insufficient governance oversight of parameter changes

mitigations:
  - Compensation cap: total payout ≤ validator fund balance (no inflation)
  - Performance bonus is only 10% of total fund (default)
  - Uptime score (40% of composite) uses on-chain signing data, ungameable
  - Governance participation (30%) uses on-chain vote records, ungameable
  - Ecosystem contribution (30%) is the only subjective metric — AGENT-004
    uses KOI search which is auditable
  - Parameter changes to performance_bonus_share_bps require Layer 2
    governance with human oversight window
  - Equal base compensation ensures all validators receive fair share

detection:
  - Abnormal performance score distributions
  - AGENT-004 ecosystem scores that diverge from observable contributions
  - Governance proposals to increase bonus share flagged for review

residual_risk: LOW (2/3 of composite score uses ungameable on-chain data)

Economic Reboot Security Invariants

Fee Router (M013) Invariants

m013_invariants:
  FEE_CONSERVATION:
    description: "fee_collected = burn + validator + community + agent_infra for every transaction"
    verification: "Sum pool distributions after each CollectFee call"
    severity: CRITICAL

  SHARE_SUM_UNITY:
    description: "burn_share + validator_share + community_share + agent_infra_share = 10000"
    verification: "Enforced on write in SetDistributionShares"
    severity: CRITICAL

  RATE_BOUND_SAFETY:
    description: "All fee rates <= max_fee_rate_bps (default 10%)"
    verification: "Checked in CollectFee before calculation"
    severity: HIGH

  POOL_ISOLATION:
    description: "No pool can draw from another without governance proposal"
    verification: "Each pool is a separate module account"
    severity: HIGH

Supply Module (M012) Invariants

m012_invariants:
  CAP_INVIOLABILITY:
    description: "current_supply <= hard_cap at all times"
    verification: "Cosmos SDK invariant checker runs every block"
    severity: CRITICAL

  NON_NEGATIVE_SUPPLY:
    description: "current_supply >= 0"
    verification: "Checked after every mint/burn cycle"
    severity: CRITICAL

  MONOTONIC_CAP:
    description: "hard_cap changeable only via Layer 4 governance (67% supermajority)"
    verification: "MsgUpdateSupplyParams rejects hard_cap changes from non-Layer-4 authority"
    severity: CRITICAL

  MINT_BURN_INDEPENDENCE:
    description: "Minting and burning computed independently"
    verification: "No conditional dependency between mint and burn calculations"
    severity: HIGH

  PARAMETER_BOUND_SAFETY:
    description: "base_regrowth_rate in [0, 1000] (0-10%)"
    verification: "Enforced on write in SetSupplyParams"
    severity: HIGH

Authority Module (M014) Invariants

m014_invariants:
  COMPOSITION_GUARANTEE:
    description: "Active set maintains min per category at all times"
    verification: "RemoveValidator blocked if would violate; EndBlocker checks"
    severity: CRITICAL

  BYZANTINE_TOLERANCE:
    description: "active_validators > 3f + 1"
    verification: "Minimum validator count enforced"
    severity: CRITICAL

  NO_SELF_APPROVAL:
    description: "Existing validators cannot unilaterally approve new validators"
    verification: "ApproveValidator requires governance module authority"
    severity: HIGH

  COMPENSATION_CAP:
    description: "Total compensation <= validator fund balance"
    verification: "DistributeCompensation checks fund balance before distribution"
    severity: HIGH

Rewards Module (M015) Invariants

m015_invariants:
  REVENUE_CONSTRAINT:
    description: "Total distributions per period <= Community Pool inflow"
    verification: "DistributeRewards caps total at inflow amount"
    severity: CRITICAL

  STABILITY_CAP:
    description: "Stability allocation <= max_stability_share_bps of inflow"
    verification: "sdk.MinInt applied in DistributeRewards"
    severity: HIGH

  ACTIVITY_INTEGRITY:
    description: "Scores derived only from on-chain transactions"
    verification: "RecordActivity callable only by module hooks, not user messages"
    severity: HIGH

  NO_DOUBLE_COUNTING:
    description: "Each transaction counted once per participant"
    verification: "Hook-based recording with tx_hash deduplication"
    severity: HIGH

  WEIGHT_SUM_UNITY:
    description: "Activity weights sum to 10000"
    verification: "Enforced on write in SetRewardParams"
    severity: MEDIUM

Updated Bug Bounty Scope

economic_reboot_bounty_scope:
  critical:
    reward: "$75,000 - $150,000"
    examples:
      - Supply cap violation (minting above hard_cap)
      - Fee conservation failure (fees lost or created)
      - Unauthorized validator set manipulation
      - Revenue constraint bypass (distributing more than inflow)

  high:
    reward: "$25,000 - $75,000"
    examples:
      - Fee rate bound bypass (exceeding max_fee_rate_bps)
      - Composition guarantee violation
      - Activity score manipulation via direct MsgRecordActivity
      - Stability tier fund loss on early exit

  medium:
    reward: "$5,000 - $25,000"
    examples:
      - Rounding errors leading to accumulated pool imbalance
      - Denial of service on EndBlocker mint/burn execution
      - Performance score gaming through KOI artifacts
      - Reference price manipulation affecting fee calculation

  low:
    reward: "$1,000 - $5,000"
    examples:
      - Informational discrepancies in event emissions
      - Edge cases in phase transition timing
      - Non-critical parameter validation gaps

Summary

Security Area Status Priority
Threat Model Complete -
Attack Vectors 11 documented (6 core + 5 economic reboot) -
Invariants 27 specified (11 core + 16 economic reboot) -
Audit Checklist Ready Pre-mainnet
Incident Response Defined Pre-mainnet
Bug Bounty Designed (updated scope for M012-M015) Post-audit