Production-grade implementation for detecting and exploiting weak PRNG vulnerabilities in Bitcoin key generation
This tool reproduces the "Milk Sad" vulnerability that led to $900M+ in compromised Bitcoin addresses. It implements a complete pipeline for:
- Address Collection - Gathering addresses from Bitcoin testnet blockchain
- Entropy Analysis - Statistical detection of weak randomness
- Pattern Detection - Identifying PRNG fingerprints (MT19937, sequential generation)
- Key Recovery - Brute-force PRNG seed reconstruction
- Validation - Cryptographic verification of recovered keys
weak-key-scanner/
├── src/
│ ├── address_collector.py # Blockchain API integration
│ ├── entropy_analyzer.py # Shannon entropy & chi-square tests
│ ├── pattern_detector.py # Weakness pattern identification
│ ├── prng_reconstructor.py # MT19937 seed search (parallel)
│ ├── key_recovery.py # Recovery orchestration
│ ├── validator.py # Key/address validation
│ ├── logger.py # Evidence generation
│ └── main.py # Pipeline orchestrator
├── tests/
│ ├── test_entropy_analyzer.py
│ ├── test_prng_reconstructor.py
│ ├── test_key_recovery.py
│ └── test_integration.py
├── config/
│ └── config.yaml # Configuration (thresholds, modes)
├── logs/ # Execution logs
├── results/ # JSON evidence reports
├── requirements.txt
├── install.sh # Automated installation
└── run_aws.sh # AWS execution script
- Checkpoint/Resume: Automatic state saving every 100 addresses
- Graceful Shutdown: SIGTERM/SIGINT handlers for AWS Spot interruption
- Memory Efficient: Streaming architecture for 10,000+ addresses
- Parallel Processing: Multi-core PRNG search (configurable workers)
- CloudWatch Logging: Structured JSON logs for AWS monitoring
- Shannon Entropy:
H = -Σ p(x) log₂ p(x)calculation - Chi-Square Test: Uniform distribution validation
- Pattern Detection: MT19937 fingerprinting, temporal clustering
- Weakness Thresholds: <7.0 bits/byte = WEAK, <7.5 = SUSPICIOUS
- MT19937 Implementation: Python's
random.Random()for seed search - Two Modes:
- TEST MODE: 2²⁰ (1M seeds) - ~1 minute per address
- PRODUCTION MODE: 2³² (4.3B seeds) - ~1-4 hours per address
- Parallel Search: Distributes seed space across CPU cores
- Multiple testnet validation layers
- Configuration validation at startup
- Address prefix checking (
tb1,m,n,2) - API endpoint verification
- No mainnet code paths possible
- Python 3.8+
- Ubuntu/Debian Linux (recommended for AWS EC2)
- 4-8 GB RAM (depending on address count)
- Multi-core CPU (for parallel seed search)
# Clone repository
cd weak-key-scanner
# Run automated installer
chmod +x install.sh
./install.sh
# Activate virtual environment
source venv/bin/activate# Install system dependencies
sudo apt-get update
sudo apt-get install -y build-essential libssl-dev python3-dev
# Install Python packages
pip3 install -r requirements.txt
# Create directories
mkdir -p logs results data/test_vectorsEdit config/config.yaml:
# Network Configuration
bitcoin_network: "testnet" # MUST be testnet
# Scanning Parameters
scanning:
num_addresses: 10000
checkpoint_interval: 100
resume_from_checkpoint: true
# Analysis Thresholds
analysis:
entropy_threshold: 7.0 # Lower = weaker
suspicious_threshold: 7.5
chi_square_p_threshold: 0.01
# PRNG Attack Configuration
prng_attack:
mode: "test" # "test" or "production"
seed_space_test_mode: 1048576 # 2^20 (~1 min/address)
seed_space_full_mode: 4294967296 # 2^32 (~1-4 hrs/address)
parallel_workers: 8
# Safety
safety:
testnet_only: true
allowed_prefixes: ["m", "n", "2", "tb1"]cd src
python3 main.py --addresses 1000# Run in background with automatic recovery
./run_aws.sh 10000 test 8
# ↑ ↑ ↑
# | | └─ Parallel workers
# | └────── Mode (test/production)
# └─────────── Number of addresses
# Monitor progress
./monitor.sh
# Check logs
tail -f logs/aws_execution_*.log# Automatically resumes if checkpoint exists
python3 main.py --addresses 5000
# Force fresh start (clear checkpoint)
python3 main.py --addresses 5000 --clear-checkpointpython3 main.py [OPTIONS]
Options:
--config PATH Configuration file (default: ../config/config.yaml)
--addresses N Number of addresses to scan (overrides config)
--no-checkpoint Disable checkpoint resume
--clear-checkpoint Clear existing checkpoint before startingRealistic Expectations:
- Weak addresses found: 0-2 (modern wallets use proper entropy)
- Keys recovered: 0-1 (very rare)
- Purpose: Demonstrates methodology, validates tool correctness
Higher probability of finding weak keys from:
- Early mobile wallets
- Development/testing tools
- Academic experiments
Create known weak keys for testing:
# Generate test weak key with known seed
python3 << EOF
from prng_reconstructor import PRNGReconstructor
config = {...} # Load config
prng = PRNGReconstructor(config)
seed = 12345
address, privkey = prng.create_weak_key_for_testing(seed)
print(f"Test Address: {address}")
print(f"Seed: {seed}")
EOF| Addresses | Time | CPU Cores |
|---|---|---|
| 10 | ~10 min | 8 |
| 100 | ~1.5 hrs | 8 |
| 1,000 | ~15 hrs | 8 |
| Addresses | Time | CPU Cores |
|---|---|---|
| 1 | 1-4 hrs | 8 |
| 10 | 10-40 hrs | 8 |
| 100 | Days | 8 |
AWS Instance Recommendations:
- c5.2xlarge: 8 vCPU, good cost/performance
- c5.4xlarge: 16 vCPU, faster but higher cost
- Spot Instances: Use with checkpoint/resume
{
"metadata": {
"report_type": "weak_key_scan_evidence",
"generated_at": "2025-11-03T10:30:00",
"network": "testnet"
},
"summary": {
"total_addresses_analyzed": 10000,
"weak_addresses_found": 15,
"patterns_detected": 8,
"keys_recovered": 3
},
"entropy_analysis": [...],
"pattern_detection": {...},
"recovered_keys": [...]
}Location: results/weak_key_evidence_YYYYMMDD_HHMMSS.json
======================================================================
BITCOIN WEAK KEY SCANNER - SUMMARY REPORT
======================================================================
Generated: 2025-11-03 10:30:00
Network: TESTNET
SCAN STATISTICS
----------------------------------------------------------------------
Addresses Analyzed: 10,000
Weak Addresses Found: 15
Patterns Detected: 8
Keys Recovered: 3
Location: results/scan_summary_YYYYMMDD_HHMMSS.txt
pytest tests/ -vpytest tests/test_entropy_analyzer.py -v
pytest tests/test_prng_reconstructor.py -v
pytest tests/test_integration.py -vpytest tests/ --cov=src --cov-report=html# Recommended: c5.2xlarge (8 vCPU, 16 GB RAM)
# AMI: Ubuntu 22.04 LTS
# Storage: 30 GB EBS
# Security Group: Outbound HTTPS (API calls)# Connect to instance
ssh -i your-key.pem ubuntu@<instance-ip>
# Clone repository
git clone <repository-url>
cd weak-key-scanner
# Install
./install.sh# Background execution
./run_aws.sh 10000 test 8
# Disconnect safely (screen or tmux)
screen -S scanner
./run_aws.sh 10000 test 8
# Ctrl+A, D to detach# SSH with log forwarding
ssh -i your-key.pem ubuntu@<instance-ip> "tail -f weak-key-scanner/logs/*.log"
# Or copy results periodically
scp -i your-key.pem ubuntu@<instance-ip>:weak-key-scanner/results/*.json ./The tool automatically handles AWS Spot interruptions:
- Signal Handler: Catches SIGTERM from AWS
- Checkpoint Save: Writes current state
- Graceful Exit: Cleans up resources
- Auto-Resume: Restart script loads checkpoint
# Shannon Entropy
H = -Σ p(x) log₂ p(x)
# Where:
# p(x) = probability of byte x
# Range: 0-8 bits per byte
# Interpretation:
# < 7.0: WEAK (predictable)
# 7.0-7.5: SUSPICIOUS
# 7.5-8.0: GOOD
# = 8.0: Perfect randomness# MT19937 Seed Search
for seed in range(0, 2^32):
prng = random.Random(seed)
candidate_key = generate_key(prng)
candidate_address = derive_address(candidate_key)
if candidate_address == target_address:
return seed, candidate_keyParallel Optimization:
- Divides seed space across N workers
- Each worker searches independent chunk
- Early termination on first match
- Typical speedup: 6-7x on 8 cores
ERROR: API request failed: 429 Too Many Requests
Solution: Increase rate_limit in config (currently 30 req/min)
MemoryError: Unable to allocate array
Solution:
- Reduce
batch_sizein config - Use streaming collection (already default)
- Increase EC2 instance memory
ERROR: Failed to load checkpoint
Solution:
python3 main.py --clear-checkpointThis is normal for modern testnet. Try:
- Increase address count
- Use synthetic test keys
- Target historical blocks
- Config Validation: Startup checks for
testnet_only: true - Address Validation: Rejects non-testnet prefixes
- API Validation: Verifies testnet API endpoints
- No Mainnet Paths: Code structure prevents mainnet use
- Recovered keys masked in JSON reports (first 8 + last 8 chars)
- Full keys available in checkpoint file (secure appropriately)
- Export function includes security warnings
- Recommendation: Encrypt sensitive outputs
- Cryptographic weakness analysis
- PRNG vulnerability research
- Blockchain security education
- Historical vulnerability reproduction
✅ Acceptable:
- Testnet analysis
- Academic research
- Security tool development
- Historical reproduction
❌ Prohibited:
- Mainnet scanning
- Theft attempts
- Unauthorized access
- Commercial exploitation
- Increase workers:
parallel_workers: 16(if CPU available) - Use test mode:
mode: "test"for quick validation - Reduce addresses: Start with 100-1000 for testing
- AWS instance: c5.4xlarge or higher
- Reduce batch_size:
batch_size: 500 - Enable checkpointing:
checkpoint_interval: 50 - Streaming collection: (already default)
- Lines of Code: ~3,500
- Test Coverage: 28 tests
- Configuration Options: 25+
- Output Formats: 3 (JSON, TXT, logs)
- Safety Layers: 5
- Supported Algorithms: Shannon entropy, Chi-square, MT19937
| Mode | Addresses | Hours | On-Demand | Spot |
|---|---|---|---|---|
| Test | 1,000 | ~15 | ~$2.50 | ~$0.75 |
| Test | 10,000 | ~150 | ~$25 | ~$7.50 |
| Production | 10 | ~30 | ~$5 | ~$1.50 |
Recommendation: Use Spot Instances with checkpoint/resume for 70% cost savings.
# Install dev dependencies
pip3 install -r requirements-dev.txt
# Run linter
pylint src/
# Format code
black src/
# Type checking
mypy src/Educational and Research Use Only
This tool is provided for educational purposes and security research. Users are responsible for compliance with applicable laws and regulations.
- Milk Sad Vulnerability: Research Paper
- MT19937: Mersenne Twister algorithm (Python
randommodule) - Bitcoin Testnet: https://testnet.help/
- Mempool.space API: https://mempool.space/docs/api
For questions, issues, or contributions:
- Issues: GitHub Issues
- Documentation: This README + inline code comments
- Research: See Phase 3C technical architecture document
- Bitcoin Core developers
- Mempool.space API
- Python bitcoinlib maintainers
- Security research community