Skip to content

Latest commit

 

History

History
447 lines (317 loc) · 13.5 KB

File metadata and controls

447 lines (317 loc) · 13.5 KB

SoroShield-Matrix

Composable Zero-Trust Execution Firewall for Stellar/Soroban

A production-grade security infrastructure contract designed as a composable dependency for DeFi protocols on the Stellar blockchain. SoroShield-Matrix enables real-time threat detection and validation through cross-contract calls, utilizing Soroban's Storage Rent Architecture for cost-optimal operations.


🎯 Vision

SoroShield-Matrix represents a paradigm shift in DeFi security: from standalone security tooling to integrated network infrastructure. By serving as a composable contract, it allows any DeFi protocol to delegate threat assessment to a decentralized, community-verified registry without reimplementing security logic.

Key Innovation: Temporary storage for unverified community reports auto-expires (saving rent), while confirmed malicious addresses persist permanently for DeFi protocol integration.


🏗️ Architecture

Smart Contract Design

The contract implements a zero-trust execution model:

  1. Community Reporting → Unverified tips stored in Temporary storage (TTL: 5-10k ledgers, ~25-50 minutes)
  2. Analyst Verification → Whitelisted analysts confirm threats, moving them to Persistent storage
  3. Cross-Contract Firewall → External protocols query verify_safe() before processing transactions
  4. Efficient Storage → No wasted rent on outdated unverified reports

Architecture Diagram

┌─────────────────────────────────────────────────────────────────────┐
│                        DeFi ECOSYSTEM                               │
└─────────────────────────────────────────────────────────────────────┘

                              ↓ Cross-Contract Call
                         verify_safe(address)
                              ↓
                         ┌─────────────────────┐
                         │  SoroShield-Matrix  │
                         │   Firewall Oracle   │
                         └──────────┬──────────┘
                                    │
                    ┌───────────────┼───────────────┐
                    ↓               ↓               ↓
        ┌──────────────────┐ ┌───────────────┐ ┌──────────────┐
        │ TEMPORARY        │ │ PERSISTENT    │ │ PERSISTENT   │
        │ STORAGE          │ │ STORAGE       │ │ STORAGE      │
        │                  │ │               │ │              │
        │ Unverified Tips  │ │ Admin Address │ │ Confirmed    │
        │ (auto-expire)    │ │ Analyst Roles │ │ Threats      │
        │ TTL: 5-10k       │ │ TTL: 100-500k │ │ TTL: 100-500k│
        │                  │ │               │ │              │
        └────────┬─────────┘ └───────────────┘ └──────┬───────┘
                 │                                     │
                 ├─ Community ← Temporary (cheap)     │
                 │   Reports    (saves rent)         │
                 │                                   │
                 └─ Analyst     ← Persistent        │
                    Verifies      (expensive)        │
                    │                               │
                    └───────────────────────────────┘
                         ↓
                    Confirmed Threats
                    (blocked for 1 year)

RESULT: True (safe) or False (blocked)

Data Flow

1. Community Member                2. Analyst                 3. DeFi Protocol
   └─ report_suspicious()            ├─ add_analyst()         ├─ verify_safe(user)
      └─ Target Address              ├─ confirm_threat()      └─ Block if false
         └─ Temp Storage             └─ Severity (1-100)         ↓
            (TTL 50 min)                └─ Persist Storage    Continue Tx
                                            (TTL 1 year)      or Reject

Directory Structure

soroshield-matrix/
├── contracts/
│   └── firewall_oracle/
│       ├── src/
│       │   ├── lib.rs              # Core firewall logic & cross-contract API
│       │   └── types.rs            # Storage keys and error definitions
│       ├── tests/
│       │   └── integration.rs      # Integration tests with rent validation
│       └── Cargo.toml              # Rust dependencies & build config
├── frontend/
│   ├── src/
│   │   ├── app/
│   │   │   ├── layout.tsx          # Next.js root layout
│   │   │   ├── page.tsx            # Threat dashboard
│   │   │   └── globals.css         # Tailwind global styles
│   │   ├── components/
│   │   │   └── WalletConnect.tsx   # Freighter integration
│   │   └── utils/
│   │       └── stellar.ts          # Soroban RPC & contract utilities
│   ├── package.json
│   ├── tsconfig.json
│   ├── next.config.js
│   ├── tailwind.config.ts
│   └── .env.example
├── Makefile                         # Build automation
├── CONTRIBUTING.md                  # Contribution guidelines
└── README.md                        # This file

🚀 Quick Start

Prerequisites

  • Rust 1.70+ with wasm32-unknown-unknown target
  • Node.js 18+ and npm/yarn
  • Stellar CLI (optional, for deployment)
  • Freighter Wallet browser extension (for frontend testing)

Build Smart Contract

# Install dependencies and build WASM binary
make build

# Run all tests
make test

# Optimize for deployment (required before deploying to mainnet)
make optimize

# Check binary sizes
make size

Run Frontend

# Install dependencies
make frontend-install

# Development server (http://localhost:3000)
make frontend-dev

# Production build
make frontend-build

📡 Contract API

Core Functions

init(env, admin) -> Result<(), Error>

Initializes the firewall oracle with an admin address. Must be called once.

Auth: No signature required (first caller becomes admin)

client.init(&admin_address)?;

add_analyst(env, admin, analyst) -> Result<(), Error>

Adds an analyst to the whitelisted verification roles.

Auth: Requires admin signature

client.add_analyst(&admin, &analyst_address)?;

report_suspicious(env, reporter, target) -> Result<(), Error>

Community member submits an unverified threat report. Stored in Temporary storage.

Auth: Requires reporter signature

client.report_suspicious(&reporter, &suspicious_address)?;

confirm_threat(env, analyst, target, severity) -> Result<(), Error>

Analyst confirms a threat, moving it to Persistent storage with a severity level (1-100).

Auth: Requires analyst signature + whitelisted analyst role

client.confirm_threat(&analyst, &malicious_address, 85)?;

verify_safe(env, target) -> bool

Cross-Contract Firewall: External DeFi protocols query this to validate an address.

Returns true if safe, false if confirmed threat.

// Example DeFi protocol integration
if !firewall_contract.verify_safe(&user_address) {
    return Err(ContractError::UserBlocked);
}

remove_threat(env, caller, target) -> Result<(), Error>

Removes a confirmed threat from the registry. Only admin or analysts can call.

Auth: Requires caller signature + admin/analyst role

client.remove_threat(&admin, &address_to_remove)?;

Query Functions (Read-Only)

  • get_threat_severity(env, target) -> u32 — Retrieves severity level (0 if not a threat)
  • is_analyst(env, address) -> bool — Checks if address is whitelisted analyst
  • get_admin(env) -> Result<Address, Error> — Returns current admin address

💾 Storage Architecture

Temporary Storage (Community Reports)

Key TTL Use Case
SuspiciousTip(address) 5-10k ledgers (~25-50 min) Unverified community reports auto-expire

Cost Benefit: Network automatically deletes expired entries, saving storage rent.

Persistent Storage (Confirmed Threats)

Key TTL Use Case
Admin 100-500k ledgers (~115 days–1 year) Admin address control
Analyst(address) 100-500k ledgers Whitelisted analyst roles
ConfirmedThreat(address) 100-500k ledgers Malicious addresses blocking transactions

Cost Model: Only confirmed, vetted threats consume permanent network storage.


🔧 Deployment

Testnet Deployment

# 1. Generate a deployment keypair
stellar keys generate admin-key

# 2. Fund it on testnet (go to testnet faucet)
curl https://friendbot.stellar.org?addr=G...

# 3. Build and optimize contract
make optimize

# 4. Deploy
stellar contract deploy \
  --wasm target/wasm32-unknown-unknown/release/firewall_oracle.optimized.wasm \
  --source admin-key \
  --network testnet

# 5. Initialize the contract
stellar contract invoke \
  --id <DEPLOYED_CONTRACT_ID> \
  --source admin-key \
  --network testnet \
  -- init --admin G...

Mainnet Deployment

Before mainnet, ensure:

  • ✅ Comprehensive test coverage passes
  • ✅ Code review by Stellar auditors
  • ✅ Threat model validation
  • ✅ Fee structures and rent calculations verified

🧪 Testing

The project includes comprehensive unit and integration tests:

make test

Test Coverage:

  • Initialization and re-initialization prevention
  • Analyst role enforcement
  • Threat confirmation and severity levels
  • Cross-contract verification logic
  • Threat removal and state management
  • Storage rent and TTL validation
  • Authorization and authentication

🌐 Frontend Integration

Wallet Connection

The frontend uses Freighter API for secure wallet integration:

import { connectFreighter, formatAddress } from '@/utils/stellar'

const { publicKey } = await connectFreighter()
console.log(`Connected: ${formatAddress(publicKey)}`)

Submitting Reports

// Component auto-integrates with contract
client.report_suspicious(walletAddress, targetAddress)

Verifying Threats

const isSafe = client.verify_safe(userAddress)
if (!isSafe) {
  // Block transaction in your DeFi protocol
}

📊 DeFi Protocol Integration Example

// In your DeFi contract
use soroban_sdk::{contract, contractimpl, Address, Env};

#[contract]
pub struct MyDeFiProtocol;

#[contractimpl]
impl MyDeFiProtocol {
    pub fn execute_swap(
        env: Env,
        user: Address,
        input_token: Address,
        output_token: Address,
        amount: i128,
    ) -> Result<i128, String> {
        user.require_auth();

        // Call SoroShield firewall to verify user
        let firewall_id = Address::from_contract_id(&env, &firewall_contract_id);
        let is_safe: bool = env.invoke_contract(
            &firewall_id,
            &Symbol::new(&env, "verify_safe"),
            &(user.clone(),),
        );

        if !is_safe {
            return Err("Address blocked by firewall".to_string());
        }

        // Proceed with swap logic
        Ok(amount)
    }
}

🛡️ Security Considerations

Threat Model

  1. Community Reports → Unverified, expire automatically (low cost)
  2. Analyst Verification → Decentralized validation (prevents abuse)
  3. Cross-Contract Calls → Read-only firewall queries (no state change)
  4. Admin Controls → Can remove false positives or update analyst roles

Authentication

  • Community reports require reporter signature
  • Threat confirmation requires analyst signature + role check
  • Admin operations require admin signature
  • Cross-contract calls are read-only (no signature required)

Rent Architecture Compliance

  • Temporary storage entries automatically expire
  • No indefinite storage costs for unverified reports
  • Confirmed threats use long TTL (1 year), amortizing rent over time

📚 Documentation Files


🤝 Contributing

We welcome contributions! See CONTRIBUTING.md for:

  • Issue labeling and complexity tiers
  • Development workflow
  • Testing requirements
  • Code style guidelines
  • Pull request process

📋 License

This project is licensed under the MIT License. See LICENSE file for details.


🚨 Support

For issues or questions:

  1. Check existing GitHub Issues
  2. Read CONTRIBUTING.md for known issues and workarounds
  3. Open a new issue with detailed reproduction steps

🌟 Acknowledgments

  • Stellar Development Foundation — Soroban SDK and infrastructure
  • Freighter Wallet — Secure key management

Built with ❤️ for the Stellar ecosystem

Last Updated: 2026-07-03