Mempool ids

From XSpoonAi/spoon-awesome-skill · View interactive version

Mempool ids is an AI agent skill from the GitHub repository XSpoonAi/spoon-awesome-skill. Real-time blockchain intrusion detection system that monitors mempool for exploit attempts and automatically executes defensive responses using ML classification and gas-optimized front-running

How to use this skill

Skill file

Mempool Intrusion Detection System

##Overview

Real-time blockchain intrusion detection system that monitors the Ethereum mempool for exploit attempts, analyzes transaction payloads using machine learning, and automatically executes defensive responses by front-running attackers with gas-optimized pause transactions.

Analysis Type: Real-Time Intrusion Detection + Automated Response

Approach: Signature-Based + ML Classification + Active Defense

Target: Ethereum & EVM-Compatible Chains

Status: Production Ready

Key Capabilities

1. **Mempool Monitoring** (mempool_monitor.py)

2. **Payload Analysis** (payload_analyzer.py)

3. **ML Classification** (exploit_classifier.py)

4. **Automated Defense** (defense_executor.py)

5. **IDS Engine** (ids_engine.py)

Components

mempool_monitor.py (550 lines)

Purpose: Real-time WebSocket monitoring of pending transactions

Key Classes:

Methods:

async def connect()                      # Establish WebSocket connection
async def subscribe_pending_transactions()  # Subscribe to mempool
async def process_transaction(tx_hash)   # Fetch and process transaction
_parse_transaction(tx)                   # Parse into PendingTransaction
_decode_function_call(tx)                # Decode function with ABI
async def reconnect()                    # Auto-reconnect on failure

payload_analyzer.py (650 lines)

Purpose: Transaction payload analysis and feature extraction

Key Classes:

Methods:

analyze(tx_hash, from_addr, to_addr, value, gas_price, input_data, nonce, timestamp)
_calculate_entropy(hex_string)           # Shannon entropy
_analyze_parameters(input_data)          # Parameter patterns
_calculate_gas_percentile(gas_price)     # Gas anomaly detection
_match_reentrancy_pattern()              # Reentrancy detection
_match_flash_loan_pattern()              # Flash loan detection
_match_price_manipulation_pattern()      # Price manipulation
to_feature_vector()                      # Convert to ML input

exploit_classifier.py (600 lines)

Purpose: ML-based exploit classification

Key Classes:

Methods:

train(X, y, validation_split)            # Train model
predict(features)                        # Classify transaction
_calculate_metrics(y_true, y_pred)      # Performance metrics
_determine_threat_level(probability)     # Map probability to level
_get_decision_factors(features)          # Explainable AI
tune_threshold(X_val, y_val, target_fpr) # Optimize threshold
generate_synthetic_training_data()       # Bootstrap training
save_model(filepath)                     # Persist model
load_model(filepath)                     # Load trained model

defense_executor.py (550 lines)

Purpose: Automated defense response execution

Key Classes:

Methods:

execute_defense(strategy, target_contract, threat_tx_hash, threat_gas_price, urgency)
_calculate_gas_strategy(threat_gas_price, urgency)  # Gas optimization
_execute_pause_contract(action, contract, gas)  # Pause transaction
_wait_for_confirmation(action)           # Monitor confirmation
retry_failed_action(action)              # Retry with higher gas
get_statistics()                         # Defense metrics

ids_engine.py (550 lines)

Purpose: Main orchestration and management

Key Classes:

Methods:

async def start()                        # Start IDS
async def stop()                         # Stop IDS
_on_transaction_detected(tx)            # Transaction callback
async _analyze_transaction(tx)           # Feature extraction + classification
_is_actionable_threat(classification)    # Threshold checking
async _handle_threat(tx, features, classification)  # Threat handler
async _execute_defense(detection)        # Defense trigger
get_statistics()                         # Get metrics
export_detections(filepath)              # Export to JSON

Detection Algorithms

Feature Extraction (22 Dimensions)

  1. Function Characteristics
  1. Parameter Patterns
  1. Value & Gas Patterns
  1. Call Patterns
  1. Exploit Signatures
  1. Behavioral Indicators

ML Classification Pipeline

# 1. Feature Extraction
features = analyzer.analyze(tx)  # → 22D vector

# 2. Normalization
X_scaled = scaler.transform(features)

# 3. Ensemble Prediction
probabilities = model.predict_proba(X_scaled)
prob_malicious = probabilities[1]

# 4. Threshold Classification
is_malicious = prob_malicious >= threshold

# 5. Threat Level Mapping
if prob < 0.3: level = BENIGN
elif prob < 0.5: level = LOW
elif prob < 0.7: level = MEDIUM
elif prob < 0.9: level = HIGH
else: level = CRITICAL

Defense Execution Strategy

# 1. Gas Price Calculation
base_fee = latest_block.baseFeePerGas
threat_priority = threat_gas_price - base_fee
defense_priority = threat_priority * buffer_multiplier  # 1.5-2.0x
max_fee = (base_fee * 1.2) + (defense_priority * 1.5)

# 2. Transaction Building
pause_tx = {
    'from': defender_address,
    'to': target_contract,
    'data': pause_function_selector,
    'maxFeePerGas': max_fee,
    'maxPriorityFeePerGas': defense_priority,
    'gas': gas_estimate * 1.2
}

# 3. Sign & Broadcast
signed_tx = defender_account.sign_transaction(pause_tx)
tx_hash = w3.eth.send_raw_transaction(signed_tx)

# 4. Monitor Confirmation
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)

Usage Examples

See README.md for comprehensive usage examples including:

Configuration

Threshold Tuning

Classification Threshold (0.0-1.0):

Threat Level Threshold:

Gas Buffer Multiplier

Performance Metrics

Latency:

Throughput:

Accuracy (synthetic data):

Production Considerations

Security

Scalability

Monitoring

Cost Management

Limitations

  1. WebSocket Dependency: Requires stable WebSocket connection
  2. Gas Price Competition: Very sophisticated attackers may outbid
  3. Network Latency: Response time depends on network conditions
  4. False Positives: ML models can misclassify legitimate transactions
  5. Training Data: Synthetic training data may not cover all exploit types

Future Enhancements

  1. Advanced ML Models: Neural networks, LSTM for temporal patterns
  2. Multi-Chain Support: Polygon, BSC, Arbitrum
  3. Collaborative Detection: Share threat intelligence across instances
  4. Historical Analysis: Learn from past attacks
  5. Simulation Mode: Test defenses without real transactions
  6. DAO Integration: Community-based defense decisions

References

License

MIT License - See LICENSE file for details

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.