Menu
Security Intermediate 6 min read

Security for Agents

Comprehensive security guide for AI agents operating with Bitcoin, Lightning, and Nostr. OPSEC, key management, threat modeling, and defensive practices.

security opsec overview

Security for Agents

Security is not optional for AI agents operating in freedom technology. Unlike traditional systems where errors can be reversed, Bitcoin transactions are irreversible, Lightning channels require constant monitoring, and Nostr keys cannot be rotated without losing identity.

Why Security is Critical

ProtocolIrreversible ActionRecovery Possible?
BitcoinTransaction broadcastNo
LightningForce-closePartial (minus fees)
NostrEvent signatureNo (events are immutable)

Agents face unique security challenges:

  1. Always-on operation: Continuous exposure to attacks
  2. Automated decisions: No human review before action
  3. Key accessibility: Keys must be accessible for signing
  4. Network exposure: Constant internet connectivity

Security Principles

1. Defense in Depth

Never rely on a single security control:

┌────────────────────────────────────────────┐
│           Network Security                  │
│  ┌────────────────────────────────────┐    │
│  │        Access Control              │    │
│  │  ┌────────────────────────────┐    │    │
│  │  │     Key Management         │    │    │
│  │  │  ┌────────────────────┐    │    │    │
│  │  │  │   Application      │    │    │    │
│  │  │  │      Logic         │    │    │    │
│  │  │  └────────────────────┘    │    │    │
│  │  └────────────────────────────┘    │    │
│  └────────────────────────────────────┘    │
└────────────────────────────────────────────┘

2. Principle of Least Privilege

  • Use separate keys for different operations
  • Limit hot wallet balances
  • Grant minimum necessary permissions
  • Separate read-only and signing capabilities

3. Fail Secure

When in doubt, refuse to act:

def sign_transaction(tx: Transaction) -> Signature | None:
    """Only sign if all safety checks pass."""
    try:
        validate_destination(tx.outputs)
        validate_amount(tx.total_output)
        validate_fee(tx.fee)
        return sign(tx)
    except ValidationError:
        # Fail secure: refuse to sign
        return None

4. Assume Breach

Design systems assuming attackers will get in:

  • Limit blast radius of any single compromise
  • Monitor for anomalous behavior
  • Maintain audit logs
  • Have incident response plans

Security Domains

Key Management

How you generate, store, and use cryptographic keys.

Key TypeRisk LevelBest Practice
Seed phraseCriticalHardware wallet, offline
Bitcoin private keyCriticalDerived, never raw
Lightning node keyHighHot, but isolated
Nostr private keyHighSeparate from funds

Deep dive: Key Management

Operational Security (OPSEC)

Preventing information leakage about your operations.

InformationRisk if LeakedProtection
IP addressDeanonymizationTor, VPN
Transaction patternsLink analysisTiming randomization
Key relationshipsWallet clusteringSeparate identities
Balance amountsTargetingMultiple wallets

Deep dive: Operational Security

Threat Modeling

Understanding who might attack you and how.

AttackerCapabilityMotivation
OpportunisticLowEasy profit
TargetedMediumSpecific goal
State-levelHighSurveillance
InsiderMediumAccess abuse

Deep dive: Threat Modeling

Network Security

Protecting network-level communications.

VectorAttackDefense
DNSHijackingUse IP directly, DNSSEC
TLSMITMCertificate pinning
WebSocketInjectionMessage signing
TorCorrelationSeparate circuits

Deep dive: Network Security

Learning Path

Core Security

  1. Key Management - Generating and protecting keys
  2. OPSEC - Operational security practices
  3. Threat Modeling - Understanding adversaries
  4. Backup and Recovery - Disaster recovery

Protocol-Specific

  1. Network Security - Network-level defenses
  2. Common Attacks - Attack patterns and defenses
  3. Auditing - Logging and verification

Reference

  • Glossary - Security terminology
  • FAQ - Common questions

Security Checklist

Before Deployment

  • Seed phrases stored offline
  • Hot wallet balance minimized
  • Rate limits configured
  • Destination allowlist (if applicable)
  • Monitoring and alerting active
  • Backup tested and verified
  • Incident response plan documented

Ongoing

  • Regular balance audits
  • Log review for anomalies
  • Key rotation (where possible)
  • Software updates applied
  • Threat model reviewed

Quick Start Security

class SecureAgent:
    """Security-aware agent base class."""

    def __init__(self):
        # Limit hot wallet exposure
        self.max_hot_balance_sats = 1_000_000  # 0.01 BTC

        # Rate limiting
        self.max_daily_spend_sats = 10_000_000  # 0.1 BTC
        self.daily_spent = 0

        # Transaction limits
        self.max_single_tx_sats = 5_000_000  # 0.05 BTC

        # Audit logging
        self.audit_log = []

    async def send_payment(
        self,
        destination: str,
        amount_sats: int
    ) -> dict:
        """Secure payment with multiple checks."""

        # Check single transaction limit
        if amount_sats > self.max_single_tx_sats:
            return {"error": "exceeds_single_tx_limit"}

        # Check daily limit
        if self.daily_spent + amount_sats > self.max_daily_spend_sats:
            return {"error": "exceeds_daily_limit"}

        # Validate destination format
        if not self.validate_destination(destination):
            return {"error": "invalid_destination"}

        # Log before execution
        self.audit_log.append({
            "action": "payment",
            "destination": destination,
            "amount": amount_sats,
            "timestamp": datetime.utcnow().isoformat()
        })

        # Execute payment
        result = await self._execute_payment(destination, amount_sats)

        # Update limits
        if result.get("success"):
            self.daily_spent += amount_sats

        return result

Machine-Readable Summary

{
  "topic": "security",
  "audience": "ai-agents",
  "security_domains": [
    "key-management",
    "opsec",
    "threat-modeling",
    "network-security",
    "backup-recovery"
  ],
  "principles": [
    "defense-in-depth",
    "least-privilege",
    "fail-secure",
    "assume-breach"
  ],
  "key_risks": [
    "key-compromise",
    "transaction-manipulation",
    "deanonymization",
    "denial-of-service"
  ]
}