# Security Package Documentation ## Overview The security package provides secure private key management and transaction signing for the MEV Bot application. It implements comprehensive security measures including encryption, rate limiting, key rotation, audit logging, and permission controls to protect sensitive cryptographic assets. ## Core Components ### `KeyManager` Structure The main key manager structure provides secure key management: 1. **Logger** - Structured logging for security events 2. **Keystore** - Ethereum keystore for key storage 3. **Encryption Key** - Master encryption key for key protection 4. **Keys** - In-memory map of secure keys 5. **Configuration** - Security configuration parameters 6. **Rate Limiting** - Transaction signing rate limiting 7. **Audit Logging** - Security audit trail ### `KeyManagerConfig` Structure Configuration for the key manager: - **KeystorePath** - Path to keystore directory - **EncryptionKey** - Master encryption key - **KeyRotationDays** - Days before key rotation warning - **MaxSigningRate** - Maximum signings per minute - **RequireHardware** - Whether to require hardware security module - **BackupPath** - Path for encrypted key backups - **AuditLogPath** - Path for audit logging - **SessionTimeout** - How long before re-authentication required ### `SecureKey` Structure Represents a securely stored private key: - **Address** - Ethereum address - **EncryptedKey** - AES-GCM encrypted private key - **CreatedAt** - Key creation timestamp - **LastUsed** - Last usage timestamp - **UsageCount** - Number of times used - **MaxUsage** - Maximum usage limit (optional) - **ExpiresAt** - Expiration time (optional) - **BackupLocations** - Backup file locations - **KeyType** - Key type ("trading", "emergency", "backup") - **Permissions** - Key permissions - **IsActive** - Whether key is active ### `KeyPermissions` Structure Defines what operations a key can perform: - **CanSign** - Whether key can sign transactions - **CanTransfer** - Whether key can transfer value - **MaxTransferWei** - Maximum transfer amount (optional) - **AllowedContracts** - Allowed contract addresses (optional) - **RequireConfirm** - Whether confirmation is required ## Key Management Functions ### `NewKeyManager(config *KeyManagerConfig, logger *logger.Logger) (*KeyManager, error)` Creates a new secure key manager: 1. Validates configuration 2. Creates keystore directory 3. Initializes encryption 4. Loads existing keys 5. Starts background maintenance tasks ### `GenerateKey(keyType string, permissions KeyPermissions) (common.Address, error)` Generates a new private key with specified permissions: 1. Creates new ECDSA private key 2. Encrypts with AES-GCM 3. Stores securely with metadata 4. Creates backup 5. Logs audit entry ### `ImportKey(privateKeyHex string, keyType string, permissions KeyPermissions) (common.Address, error)` Imports an existing private key: 1. Parses hex private key 2. Checks for duplicates 3. Encrypts with AES-GCM 4. Stores securely with metadata 5. Creates backup 6. Logs audit entry ### `GetKeyInfo(address common.Address) (*SecureKey, error)` Returns information about a key without sensitive data: 1. Retrieves key information 2. Removes encrypted key data 3. Returns safe copy ### `ListKeys() []common.Address` Returns addresses of all managed keys: 1. Iterates through key map 2. Returns address list ### `RotateKey(oldAddress common.Address) (common.Address, error)` Creates a new key to replace an existing one: 1. Generates new key with same permissions 2. Marks old key as inactive 3. Logs audit entry ## Transaction Signing ### `SignTransaction(request *SigningRequest) (*SigningResult, error)` Signs a transaction with comprehensive security checks: 1. Validates key exists and is active 2. Checks permissions and limits 3. Applies rate limiting 4. Performs security warnings 5. Decrypts private key 6. Signs transaction 7. Updates key usage 8. Logs audit entry ### Security Checks Performed: - Key existence and activity - Signing permissions - Key expiration - Usage limits - Transfer permissions and limits - Contract interaction permissions - Rate limiting - Security warnings ### `SigningRequest` Structure - **Transaction** - Transaction to sign - **ChainID** - Chain identifier - **From** - Sender address - **Purpose** - Description of transaction - **UrgencyLevel** - Urgency level (1-5) ### `SigningResult` Structure - **SignedTx** - Signed transaction - **Signature** - Raw signature bytes - **SignedAt** - Signing timestamp - **KeyUsed** - Key used for signing - **AuditID** - Audit identifier - **Warnings** - Security warnings ## Encryption and Security ### Key Encryption The key manager uses AES-GCM encryption: 1. **AES-256** - Strong symmetric encryption 2. **GCM Mode** - Authenticated encryption 3. **Random Nonces** - Unique per encryption 4. **Scrypt KDF** - Secure key derivation ### `encryptPrivateKey(privateKey *ecdsa.PrivateKey) ([]byte, error)` Encrypts a private key using AES-GCM: 1. Converts private key to bytes 2. Creates AES cipher 3. Generates random nonce 4. Encrypts with authentication 5. Clears original key bytes ### `decryptPrivateKey(encryptedKey []byte) (*ecdsa.PrivateKey, error)` Decrypts an encrypted private key: 1. Creates AES cipher 2. Extracts nonce 3. Decrypts with authentication 4. Converts to ECDSA private key 5. Clears decrypted bytes ### Memory Security The key manager implements memory security measures: - Clears private key bytes after use - Uses secure key derivation - Implements secure random generation - Clears sensitive data from memory ## Rate Limiting ### `checkRateLimit(address common.Address) error` Checks if signing rate limit is exceeded: 1. Tracks signings per key 2. Resets counter every minute 3. Enforces maximum rate 4. Returns error if exceeded ### Configuration - **MaxSigningRate** - Maximum signings per minute per key - **Rate Limiting Disabled** - When MaxSigningRate <= 0 ## Audit Logging ### `auditLog(operation string, keyAddress common.Address, success bool, details string)` Writes an entry to the audit log: 1. Creates audit entry with timestamp 2. Calculates risk score 3. Writes to audit log file 4. Logs to main logger ### `AuditEntry` Structure - **Timestamp** - Event timestamp - **Operation** - Operation performed - **KeyAddress** - Key address involved - **Success** - Whether operation succeeded - **Details** - Detailed information - **IPAddress** - IP address (optional) - **UserAgent** - User agent (optional) - **RiskScore** - Risk score (1-10) ### Risk Scoring - **Failed Operations** - High risk (8) - **Transaction Signing** - Medium risk (3) - **Key Generation** - Medium-high risk (5) - **Key Rotation** - Medium risk (4) - **Other Operations** - Low risk (2) ## Backup and Recovery ### `createKeyBackup(secureKey *SecureKey) error` Creates an encrypted backup of a key: 1. Creates backup file path 2. Prepares backup data 3. Encrypts with additional encryption 4. Writes to backup file 5. Updates backup locations ### Backup Security - **Separate Encryption** - Additional encryption for backups - **Secure Storage** - Configurable backup path - **Multiple Backups** - Tracks backup locations - **Encrypted Data** - Backup data encryption ## Maintenance and Monitoring ### `backgroundTasks()` Runs periodic maintenance tasks: 1. Hourly maintenance checks 2. Key expiration monitoring 3. Key rotation reminders ### `performMaintenance()` Performs periodic security maintenance: 1. Checks for expired keys 2. Checks for keys needing rotation 3. Logs warnings for security issues ### Key Lifecycle Management - **Automatic Key Generation** - Generates default key if none exist - **Key Expiration** - Automatic expiration checking - **Rotation Reminders** - Periodic rotation warnings - **Usage Tracking** - Key usage monitoring ## Security Features ### Encryption Security - **AES-256-GCM** - Industry standard encryption - **Scrypt KDF** - Secure key derivation - **Random Nonces** - Unique per encryption - **Authenticated Encryption** - Tamper detection ### Access Control - **Permission-Based** - Fine-grained permissions - **Usage Limits** - Maximum usage tracking - **Contract Restrictions** - Allowed contract lists - **Transfer Limits** - Maximum transfer amounts ### Rate Limiting - **Per-Key Limits** - Individual key rate limits - **Time-Based** - Minute-based rate limiting - **Configurable** - Adjustable rate limits ### Audit Trail - **Comprehensive Logging** - All security events logged - **Risk Scoring** - Automated risk assessment - **Detailed Information** - Rich audit data - **Persistent Storage** - File-based audit logs ### Key Management - **Automatic Generation** - Default key generation - **Rotation Support** - Secure key rotation - **Expiration Tracking** - Automatic expiration - **Backup Creation** - Encrypted key backups ## Best Practices ### Key Security 1. Use strong encryption keys 2. Regularly rotate keys 3. Monitor key usage 4. Implement usage limits 5. Use separate keys for different purposes ### Transaction Security 1. Validate all transactions 2. Apply rate limiting 3. Check permissions 4. Log all signings 5. Monitor for anomalies ### Audit Security 1. Log all security events 2. Calculate risk scores 3. Monitor audit logs 4. Retain logs appropriately 5. Protect audit file access ### Backup Security 1. Create regular backups 2. Store backups securely 3. Encrypt backup data 4. Test backup recovery 5. Monitor backup integrity ## Error Handling ### Security Errors - **Invalid Keys** - Key parsing failures - **Encryption Failures** - Encryption/decryption errors - **Rate Limiting** - Signing rate exceeded - **Permission Denied** - Insufficient permissions - **Key Expired** - Expired key usage ### Recovery - **Automatic Key Generation** - Recovers from no keys - **Backup Restoration** - Key recovery from backups - **Graceful Degradation** - Continues operation when possible - **Detailed Logging** - Clear error information ## Testing ### Unit Tests - Key generation and import - Encryption and decryption - Transaction signing - Rate limiting - Audit logging - Backup creation ### Integration Tests - End-to-end key management - Security workflow testing - Performance under load - Failure scenario handling ## Future Improvements ### Enhanced Security 1. Hardware security module (HSM) integration 2. Multi-signature support 3. Threshold signatures 4. Key sharding 5. Biometric authentication ### Advanced Features 1. Key recovery mechanisms 2. Advanced audit analytics 3. Machine learning anomaly detection 4. Blockchain-based audit trails 5. Zero-knowledge proof integration