{
  "name": "Cryptocurrency & Web3 Security",
  "description": "Security patterns for blockchain, cryptocurrency, and Web3 applications",
  "domainKeywords": [
    "crypto",
    "blockchain",
    "web3",
    "defi",
    "nft",
    "wallet",
    "smart contract",
    "ethereum"
  ],
  "compliance": {
    "regulations": ["AML", "KYC", "FATF", "BSA", "Regional crypto regulations"],
    "scope": "Applications handling cryptocurrencies and digital assets",
    "requirements": [
      "Secure private key management",
      "Anti-money laundering (AML) compliance",
      "Know Your Customer (KYC) verification",
      "Transaction monitoring and reporting",
      "Wallet security and multi-signature",
      "Smart contract security audits"
    ]
  },
  "securityPatterns": {
    "walletSecurity": {
      "privateKeys": "Never store private keys in plaintext",
      "keyDerivation": "Use BIP32/BIP44 for key derivation",
      "storage": "Hardware Security Modules (HSMs) for production",
      "backup": "Secure backup and recovery procedures",
      "multiSig": "Multi-signature wallets for high-value transactions"
    },
    "smartContracts": {
      "auditing": "Professional security audits required",
      "testing": "Comprehensive test coverage including edge cases",
      "upgradeability": "Consider proxy patterns for upgradeable contracts",
      "accessControl": "Role-based access control in contracts",
      "gasOptimization": "Optimize for gas efficiency and DoS protection"
    },
    "transactionSecurity": {
      "validation": "Multi-layer transaction validation",
      "monitoring": "Real-time transaction monitoring",
      "limits": "Configurable transaction limits",
      "timelock": "Time-delayed execution for large transactions",
      "approval": "Multi-party approval workflows"
    },
    "apiSecurity": {
      "authentication": "Strong API authentication (JWT + API keys)",
      "rateLimit": "Aggressive rate limiting for trading APIs",
      "signing": "Request signing for sensitive operations",
      "websockets": "Secure WebSocket connections for real-time data"
    }
  },
  "implementationPatterns": {
    "backend": {
      "walletIntegration": {
        "abstraction": "Abstract wallet operations behind service layer",
        "keyManagement": "Separate key management from application logic",
        "transactions": "Queue and batch transactions for efficiency",
        "monitoring": "Monitor blockchain for transaction confirmations"
      },
      "tradingEngine": {
        "orderMatching": "Secure order matching algorithms",
        "balanceTracking": "Accurate balance tracking with locks",
        "riskManagement": "Position limits and risk controls",
        "latency": "Low-latency execution for competitive trading"
      },
      "compliance": {
        "kyc": "Identity verification workflows",
        "aml": "Automated AML screening and monitoring",
        "reporting": "Suspicious activity reporting (SAR)",
        "sanctions": "OFAC and sanctions list screening"
      }
    },
    "frontend": {
      "walletConnection": {
        "webWallets": "Support for MetaMask, WalletConnect, etc.",
        "security": "Validate wallet signatures and addresses",
        "persistence": "Secure session management",
        "switching": "Handle network and account switching"
      },
      "trading": {
        "realTime": "Real-time price and order book updates",
        "charting": "Advanced charting capabilities",
        "orderTypes": "Support for various order types",
        "riskWarnings": "Clear risk disclosures and warnings"
      }
    }
  },
  "blockchainIntegration": {
    "ethereum": {
      "web3": "Use ethers.js or web3.js for blockchain interaction",
      "infura": "Reliable node access via Infura/Alchemy",
      "events": "Event listening and log parsing",
      "gasManagement": "Dynamic gas price management"
    },
    "bitcoin": {
      "addresses": "Support for multiple address types",
      "utxo": "UTXO management and coin selection",
      "fees": "Dynamic fee estimation",
      "scripting": "Advanced scripting for complex transactions"
    },
    "multiChain": {
      "abstraction": "Chain-agnostic service interfaces",
      "bridging": "Cross-chain bridge integrations",
      "networks": "Support for testnets and multiple networks",
      "consensus": "Handle different consensus mechanisms"
    }
  },
  "testingRequirements": {
    "coverage": {
      "minimum": "95% for financial logic modules",
      "focus": "Security-critical components and edge cases"
    },
    "security": [
      "Smart contract security audits",
      "Penetration testing for web interfaces",
      "Key management security testing",
      "Transaction flow security validation",
      "API security testing"
    ],
    "blockchain": [
      "Test on multiple networks (mainnet, testnet)",
      "Handle network congestion scenarios",
      "Test transaction failure and retry logic",
      "Validate gas estimation accuracy",
      "Test blockchain reorganization handling"
    ]
  },
  "context7Libraries": [
    "ethers",
    "web3",
    "@metamask/providers",
    "bitcoinjs-lib",
    "@walletconnect/client",
    "bip32",
    "bip39"
  ],
  "codeTemplates": {
    "walletService": {
      "description": "Secure wallet service interface",
      "template": "@Injectable()\nexport class WalletService {\n  async signTransaction(transaction: Transaction, keyId: string): Promise<string> {\n    const privateKey = await this.keyManager.getKey(keyId);\n    return this.signer.sign(transaction, privateKey);\n  }\n\n  async validateAddress(address: string, network: Network): Promise<boolean> {\n    return this.validator.isValid(address, network);\n  }\n}"
    },
    "transactionMonitor": {
      "description": "Blockchain transaction monitoring",
      "template": "this.web3.eth.subscribe('pendingTransactions', (txHash) => {\n  this.web3.eth.getTransaction(txHash).then(tx => {\n    if (this.isWatchedAddress(tx.to)) {\n      this.processIncomingTransaction(tx);\n    }\n  });\n});"
    },
    "smartContractInteraction": {
      "description": "Safe smart contract interaction",
      "template": "const contract = new ethers.Contract(address, abi, signer);\nconst gasEstimate = await contract.estimateGas.transfer(to, amount);\nconst tx = await contract.transfer(to, amount, {\n  gasLimit: gasEstimate.mul(110).div(100), // 10% buffer\n  gasPrice: await this.getOptimalGasPrice()\n});"
    }
  },
  "complianceChecklist": [
    "Know Your Customer (KYC) procedures implemented",
    "Anti-Money Laundering (AML) monitoring in place",
    "Suspicious activity reporting (SAR) procedures",
    "OFAC and sanctions screening implemented",
    "Transaction monitoring and analysis tools",
    "Customer due diligence (CDD) procedures",
    "Enhanced due diligence (EDD) for high-risk customers",
    "Record keeping and data retention policies",
    "Compliance training for staff",
    "Regular compliance audits and reviews"
  ],
  "securityBestPractices": [
    "Never store private keys in application code",
    "Use hardware security modules (HSMs) for key storage",
    "Implement multi-signature wallets for treasury management",
    "Conduct regular security audits of smart contracts",
    "Use time-locked transactions for large amounts",
    "Implement comprehensive transaction monitoring",
    "Use secure random number generation",
    "Validate all blockchain data independently",
    "Implement proper access controls and authentication",
    "Maintain detailed audit logs of all operations"
  ],
  "riskAssessment": [
    "Private key compromise and theft",
    "Smart contract vulnerabilities and exploits",
    "Exchange hacks and loss of user funds",
    "Regulatory compliance failures",
    "Market manipulation and fraud",
    "Technical failures and system outages",
    "Insider threats and malicious employees",
    "Third-party service provider risks",
    "Quantum computing threats to cryptography",
    "Cross-chain bridge vulnerabilities"
  ]
}
