Files
mev-beta/docs/planning/05_HIGH-003_Chain_ID_Validation_Plan.md
Krypto Kajun 850223a953 fix(multicall): resolve critical multicall parsing corruption issues
- Added comprehensive bounds checking to prevent buffer overruns in multicall parsing
- Implemented graduated validation system (Strict/Moderate/Permissive) to reduce false positives
- Added LRU caching system for address validation with 10-minute TTL
- Enhanced ABI decoder with missing Universal Router and Arbitrum-specific DEX signatures
- Fixed duplicate function declarations and import conflicts across multiple files
- Added error recovery mechanisms with multiple fallback strategies
- Updated tests to handle new validation behavior for suspicious addresses
- Fixed parser test expectations for improved validation system
- Applied gofmt formatting fixes to ensure code style compliance
- Fixed mutex copying issues in monitoring package by introducing MetricsSnapshot
- Resolved critical security vulnerabilities in heuristic address extraction
- Progress: Updated TODO audit from 10% to 35% complete

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 00:12:55 -05:00

8.0 KiB

HIGH-003: Chain ID Validation Enhancement - Detailed Fix Plan

Issue ID: HIGH-003
Category: Security
Priority: High
Status: Not Started
Generated: October 9, 2025
Estimate: 2 hours

Overview

This plan enhances chain ID validation in transaction signing to prevent cross-chain replay attacks. The implementation will ensure that transactions are only valid on their intended blockchain by implementing comprehensive chain ID validation and EIP-155 replay protection.

Current Implementation Issues

  • Insufficient chain ID validation during transaction signing
  • Missing EIP-155 replay protection verification
  • No detection mechanism for chain ID mismatches
  • Lack of alerts for potential replay attack attempts

Implementation Tasks

1. Add Comprehensive Chain ID Validation in Transaction Signing

Task ID: HIGH-003.1
Time Estimate: 1 hour
Dependencies: None

Implement robust chain ID validation in transaction signing:

  • Validate chain ID matches expected network before signing
  • Check against known chain IDs for supported networks
  • Prevent signing transactions on mismatched networks
  • Add configurable chain ID validation rules
// Enhanced transaction signing with chain ID validation
type TransactionSigner struct {
    expectedChainID *big.Int
    supportedChains map[string]*big.Int  // name to chain ID mapping
}

func (ts *TransactionSigner) SignTx(tx *types.Transaction, prv *ecdsa.PrivateKey) (*types.Transaction, error) {
    // Get chain ID from transaction
    txChainID := tx.ChainId()
    
    // Validate chain ID if provided in transaction
    if txChainID != nil && txChainID.Cmp(ts.expectedChainID) != 0 {
        return nil, fmt.Errorf("chain ID mismatch: expected %s, got %s", 
            ts.expectedChainID.String(), txChainID.String())
    }
    
    // Perform the signing only after validation
    signedTx, err := types.SignTx(tx, types.LatestSignerForChainID(ts.expectedChainID), prv)
    if err != nil {
        return nil, fmt.Errorf("failed to sign transaction: %w", err)
    }
    
    return signedTx, nil
}

2. Implement EIP-155 Replay Protection Verification

Task ID: HIGH-003.2
Time Estimate: 0.5 hours
Dependencies: HIGH-003.1

Ensure EIP-155 replay protection is properly implemented:

  • Verify that all transactions include proper chain ID data
  • Validate EIP-155 signature format for transactions
  • Check that replay protection is active for all supported chains
  • Prevent transaction replay across different chains
func (ts *TransactionSigner) ValidateEIP155ReplayProtection(tx *types.Transaction) error {
    // Check if the transaction has a chain ID
    chainID := tx.ChainId()
    if chainID == nil {
        return fmt.Errorf("transaction missing chain ID, EIP-155 replay protection not active")
    }
    
    // Verify chain ID is not zero
    if chainID.Sign() == 0 {
        return fmt.Errorf("transaction has invalid chain ID (zero)")
    }
    
    // Verify that this chain ID is supported
    if !ts.isChainIDSupported(chainID) {
        return fmt.Errorf("unsupported chain ID: %s", chainID.String())
    }
    
    return nil
}

func (ts *TransactionSigner) isChainIDSupported(chainID *big.Int) bool {
    for _, supportedID := range ts.supportedChains {
        if supportedID.Cmp(chainID) == 0 {
            return true
        }
    }
    return false
}

3. Add Chain ID Mismatch Detection and Alerts

Task ID: HIGH-003.3
Time Estimate: 0.25 hours
Dependencies: HIGH-003.1

Implement monitoring and alerting for chain ID mismatches:

  • Log chain ID mismatch attempts
  • Generate security alerts for mismatched chain IDs
  • Track statistics on mismatch attempts
  • Implement rate limiting for repeated mismatches
func (ts *TransactionSigner) detectChainIDMismatch(expected, actual *big.Int) {
    if expected.Cmp(actual) != 0 {
        ts.logger.Warn("Chain ID mismatch detected in transaction signing",
            "expected", expected.String(),
            "actual", actual.String(),
            "timestamp", time.Now().Unix(),
        )
        
        // Send alert to security monitoring system
        ts.alertSystem.SendAlert("Chain ID Mismatch", map[string]interface{}{
            "expected_chain_id": expected.String(),
            "actual_chain_id":   actual.String(),
            "timestamp":         time.Now().Unix(),
        })
    }
}

4. Create Tests for Cross-Chain Replay Attack Prevention

Task ID: HIGH-003.4
Time Estimate: 0.25 hours
Dependencies: HIGH-003.1, HIGH-003.2, HIGH-003.3

Develop comprehensive tests to validate replay attack prevention:

  • Test chain ID validation with correct chain IDs
  • Test with mismatched chain IDs (should fail)
  • Test with unsupported chain IDs (should fail)
  • Test EIP-155 replay protection validation
func TestChainIDValidation(t *testing.T) {
    signer := &TransactionSigner{
        expectedChainID: big.NewInt(1), // Mainnet
        supportedChains: map[string]*big.Int{
            "mainnet": big.NewInt(1),
            "sepolia": big.NewInt(11155111),
        },
    }
    
    tests := []struct {
        name          string
        txChainID     *big.Int
        expectError   bool
        description   string
    }{
        {
            name: "valid_mainnet_chain",
            txChainID: big.NewInt(1),
            expectError: false,
            description: "Should accept matching chain ID",
        },
        {
            name: "invalid_chain_mismatch",
            txChainID: big.NewInt(137), // Polygon
            expectError: true,
            description: "Should reject mismatched chain ID",
        },
        {
            name: "unsupported_chain",
            txChainID: big.NewInt(999999),
            expectError: true,
            description: "Should reject unsupported chain ID",
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // Create a test transaction with the specified chain ID
            tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), nil)
            
            // Test signing validation
            _, err := signer.SignTx(tx, testPrivateKey)
            
            if tt.expectError {
                assert.Error(t, err, tt.description)
            } else {
                assert.NoError(t, err, tt.description)
            }
        })
    }
}

Implementation Details

EIP-155 Transaction Structure

EIP-155 transactions include:

  • chainId to sign with, preventing cross-chain replay
  • v, r, s signature components
  • Original transaction fields (nonce, gasPrice, gas, to, value, data)

Validation Flow

  1. Extract chain ID from transaction
  2. Verify chain ID matches expected network
  3. Validate EIP-155 replay protection
  4. Proceed with signing if all validations pass
  5. Log any violations for monitoring

Testing Strategy

  • Unit tests for chain ID validation logic
  • Integration tests with actual transactions
  • Negative tests with mismatched chain IDs
  • Fuzzing tests with various chain ID values

Security Considerations

  • Prevent transaction replay across different chains
  • Ensure chain ID is validated before any irreversible operations
  • Implement proper logging and monitoring for security events
  • Maintain compatibility with existing EIP-155 standards

Code Review Checklist

  • Chain ID validation implemented before signing
  • EIP-155 replay protection properly checked
  • Proper error handling for mismatched chain IDs
  • Security logging implemented for violations
  • Supported chain list is configurable
  • Tests cover all validation scenarios

Rollback Strategy

If issues arise after deployment:

  1. Temporarily disable enhanced chain ID validation
  2. Revert to previous signing implementation
  3. Monitor for any transaction validation issues

Success Metrics

  • Zero chain ID mismatch transactions processed
  • All replay attack attempts detected and blocked
  • All valid transactions on correct chains continue to work
  • Security alerts properly triggered for violations
  • No performance impact on transaction processing