Skip to content

Latest commit

 

History

History

python

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

README.md

AetherGuard Python SDK (aetherguard-py)

Deterministic Mathematical Invariant Firewall and Financial OS for Autonomous AI Agents
Native bindings and safety guards for Python AI Agents (LangChain, CrewAI, AutoGPT, LlamaIndex).

License: MIT Python: 3.9+ Security: STRIDE Verified


🎯 Overview

Autonomous AI agents powered by Large Language Models (LLMs) are prone to prompt injections, goal-hijacking, and logical hallucinations. When AI agents are granted access to crypto wallets or smart contract execution keys, a single prompt injection can drain treasury reserves in seconds.

AetherGuard solves this by establishing a non-bypassable, mathematically enforced policy layer between autonomous agents and their private keys. Every transaction proposal is audited against formal mathematical invariants:

  1. Single Spend Caps ($S \le C_{max}$)
  2. Rolling Window Budgets ($\sum S \le B_{window}$)
  3. Mandatory Balance Floors ($B - S \ge F_{min}$)
  4. Strict Whitelisting (Approved Recipients, Target Contracts, Function Selectors)
  5. Emergency Circuit Breaker (Instant Kill-Switch Freeze)
  6. Human Autonomy Thresholds (Automatic escalation to human multisig if spend exceeds threshold)

🚀 Installation

pip install aetherguard

Or for local development:

git clone https://github.com/Ranjeet2063/aetherguard.git
cd aetherguard/packages/python
pip install -e .

⚡ Quickstart

1. Basic Invariant Verification

from aetherguard import AetherGuardClient, conservative_policy, InvariantViolationError

# Configure conservative safety boundaries
policy = conservative_policy(
    min_balance_floor=100_000_000,       # 10 XLM floor
    max_single_spend=50_000_000,         # 5 XLM cap
    max_rolling_window_spend=150_000_000,# 15 XLM per 24 hours
    rolling_window_seconds=86400,
    allowed_recipients=["GBXY...TREASURY_RESERVE"]
)

client = AetherGuardClient(policy)

# AI agent proposes a spend
proposal = client.create_proposal(
    agent_id="agent-01",
    intent_prompt="Pay for compute resources",
    target_contract="C_PAYMENT_CONTRACT",
    function_name="transfer",
    recipient="GBXY...TREASURY_RESERVE",
    amount=30_000_000,
    asset_symbol="XLM"
)

# Intercept and verify against invariants
current_balance = 500_000_000 # 50 XLM
proof = client.evaluate_and_prove(proposal, current_balance)

print(f"Transaction Approved! Cryptographic Proof: {proof.invariant_digest_hex}")

2. Universal Local HTTP Invariant Gateway (Zero Code / Zero SDK)

Run the local Invariant Gateway daemon:

python -m aetherguard.gateway --port 8787

Any autonomous AI agent (Python, JS/Node, Go, or cURL) can audit operations over local HTTP:

curl -X POST http://127.0.0.1:8787/evaluate \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "claude-analyst",
    "recipient": "GBBQSMW3W6H557ZTRG36X2WCKW3ZTXQ33TIX4X4C642N5Y5S2G2T75S4",
    "amount": 30000000
  }'
  • Approved (200 OK): Returns cryptographic proof digest and projected reserve balance.
  • Violation (403 Forbidden): Immediately blocks adversarial prompt injection before touching the network.

3. Live Terminal TUI Activity Monitor & Radar

Launch the live ANSI visual radar dashboard connected to a running gateway:

python -m aetherguard.monitor --url http://127.0.0.1:8787

Or run an interactive cinematic simulation of autonomous trading agents and prompt injection attacks intercepted in real time:

python -m aetherguard.monitor --simulate

4. Mobile Alerts (Telegram & Discord Webhooks)

Receive instant mobile notifications whenever transactions are approved or adversarial prompt attacks are neutralized:

python -m aetherguard.gateway \
  --port 8787 \
  --discord-webhook "https://discord.com/api/webhooks/..." \
  --telegram-token "BOT_TOKEN" \
  --telegram-chat "CHAT_ID" \
  --alert-level VIOLATIONS

Alert dispatch runs in detached background threads with zero latency overhead on the mathematical invariant engine.

5. DeFi Slippage & AMM Flash Guard (Soroswap / Phoenix DEX)

Protect autonomous trading agents against MEV sandwich attacks and flash-loan oracle price distortion:

from aetherguard import AetherGuardClient, defi_arbitrage_policy

# Configure 50 bps (0.5%) maximum slippage & 150 bps (1.5%) oracle divergence
policy = defi_arbitrage_policy(
    max_slippage_bps=50,
    max_oracle_deviation_bps=150,
)
client = AetherGuardClient(policy)

# Create swap proposal with mathematical verification
proposal = client.create_swap_proposal(
    agent_id="soroswap_arbitrage_bot",
    intent_prompt="Execute USDC -> XLM DEX swap",
    target_contract="CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC",
    function_name="swap_exact_tokens",
    recipient="GDQP2KPQGKIHYJGXNUIYOMHARUARCA7DJT5FO2FFOOKY3IF53Q7L5G6Z",
    asset_in="USDC",
    asset_out="XLM",
    amount_in=100_000_000,
    expected_amount_out=1_000_000_000,
    min_amount_out=996_000_000,  # 40 bps slippage (<= 50 bps limit)
    oracle_reference_price_bps=100_000, # 10.0 XLM/USDC reference oracle
)

### 6. Zero-Knowledge Invariant Attestation & Local Enclave (TEE) Verification

Generate non-forgeable, hardware-signed Ed25519 attestation certificates for every approved action, while proving policy compliance in Zero-Knowledge:

```python
from aetherguard import AetherGuardClient, conservative_policy, verify_enclave_certificate

client = AetherGuardClient(conservative_policy())

# 1. Zero-Knowledge Policy Commitment (Hides whitelist addresses & caps from public surveillance)
zk_policy_commitment = client.policy_commitment
print("ZK Policy Commitment:", zk_policy_commitment)

# 2. Agent submits proposal
proposal = client.create_proposal(
    agent_id="phoenix_agent",
    intent_prompt="Routine treasury rebalance",
    target_contract="C_CORE_ESCROW",
    function_name="transfer",
    recipient="G_AUDITED_VENDOR_VAULT_01",
    amount=10_000_000,
    asset_symbol="XLM",
)

# 3. Enclave evaluates invariants and issues signed hardware certificate
proof, certificate = client.evaluate_and_attest(proposal, current_account_balance=500_000_000)

print("Enclave Public Key:", certificate.enclave_public_key_hex)
print("Anti-Replay Nonce:", certificate.nonce)
print("Ed25519 Signature:", certificate.enclave_signature_hex)

# 4. Independent 3rd-Party Verification (Prover vs Verifier)
is_valid = verify_enclave_certificate(
    certificate,
    expected_pubkey_hex=client.enclave_public_key_hex,
    expected_policy_commitment_hex=zk_policy_commitment,
)
assert is_valid is True

Verify certificates via the Universal Gateway:

curl -X POST http://127.0.0.1:8787/verify \
  -H "Content-Type: application/json" \
  -d '{"certificate": { ... }}'

🤖 Framework Integrations

LangChain Tools

Protect any LangChain tool from rogue execution using @guard_tool:

from aetherguard import AetherGuardClient, conservative_policy
from aetherguard.integrations import guard_tool

client = AetherGuardClient(conservative_policy())

@guard_tool(
    client=client,
    balance_provider=lambda: 500_000_000,
    target_contract="stellar-payment",
    function_name="transfer",
    catch_and_return_message=True # Feeds back safely to LLM on rejection
)
def pay_vendor(recipient: str, amount: int) -> str:
    # Actual on-chain wallet signing logic here
    return f"Paid {amount} to {recipient}"

CrewAI Multi-Agent Pipelines

from aetherguard.integrations import CrewAIGuard

guard = CrewAIGuard(client, balance_provider=lambda: 500_000_000)

# Verify multi-agent actions before execution
is_safe = guard.verify_action(
    action_name="Staking Rewards Distribution",
    recipient="G_STAKING_REWARDS_POOL",
    amount=20_000_000
)

LlamaIndex Tools

from aetherguard.integrations import guard_llamaindex_tool

@guard_llamaindex_tool(client=client, balance_provider=get_wallet_balance)
def retrieve_and_pay(chunk_id: str, recipient: str, amount: int):
    return pay_oracle_for_chunk(chunk_id, recipient, amount)

To receive the signed proof and certificate alongside a tool result, wrap a callable with LlamaIndexActionGuard. Both calls verify the action before executing the tool. execute_with_attestation returns (tool_result, proof, certificate); normal guard(...) calls return only the tool result. A rejected action raises InvariantViolationError without calling the tool.

from aetherguard import verify_enclave_certificate
from aetherguard.integrations import LlamaIndexActionGuard

def pay_for_chunk(chunk_id: str, recipient: str, amount: int):
    return pay_oracle_for_chunk(chunk_id, recipient, amount)

guard = LlamaIndexActionGuard(
    pay_for_chunk, client=client, balance_provider=get_wallet_balance
)
result, proof, certificate = guard.execute_with_attestation(
    chunk_id="doc-1", recipient="GBXY...", amount=1000
)
assert verify_enclave_certificate(
    certificate,
    expected_pubkey_hex=client.enclave_public_key_hex,
    expected_policy_commitment_hex=client.policy_commitment,
)
# The explicit method exposes the signed evidence to the caller.

AutoGPT Command Interceptor

from aetherguard.integrations import AutoGPTGuard

guard = AutoGPTGuard(client, balance_provider=get_wallet_balance)
is_allowed = guard.intercept_command("pay_vendor", {"recipient": "GBXY...", "amount": 1000})

🧪 Testing

Run the full local unit test suite:

python3 -m unittest discover tests

🛡️ Formal Security Architecture

AetherGuard implements formal proofs based on Ramanujan invariant symmetries and Microsoft STRIDE threat modeling. Read the full formal specification in STRIDE_THREAT_MODEL.md.


📄 License

MIT © Ranjeet2063