DILSHAD737 commited on
Commit
b1ea2ad
·
1 Parent(s): 551ac1f

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -278
app.py DELETED
@@ -1,278 +0,0 @@
1
- import asyncio
2
- import warnings
3
- warnings.filterwarnings("ignore", category=UserWarning)
4
- warnings.filterwarnings("ignore", category=RuntimeWarning)
5
-
6
- try:
7
- asyncio.set_event_loop(asyncio.new_event_loop())
8
- except Exception:
9
- pass
10
-
11
- import gradio as gr
12
- import hashlib, hmac, os, time, math, random, gc
13
- from itertools import permutations, combinations
14
- from mnemonic import Mnemonic
15
- import coincurve
16
- from eth_utils import keccak, to_checksum_address
17
- import spaces
18
-
19
- @spaces.GPU
20
- def _noop():
21
- return "ok"
22
-
23
- # ============================================================
24
- _MNEMONIC = None
25
- def _get_mnemonic():
26
- global _MNEMONIC
27
- if _MNEMONIC is None:
28
- _MNEMONIC = Mnemonic("english")
29
- return _MNEMONIC
30
-
31
- # ---------- BIP32 manual ----------
32
- _SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
33
- _HARDENED = 0x80000000
34
-
35
- def _bip32_derive_child_priv(parent_priv, parent_chain, index):
36
- if index >= _HARDENED:
37
- data = b'\x00' + parent_priv + index.to_bytes(4, 'big')
38
- else:
39
- pub = coincurve.PrivateKey(parent_priv).public_key.format(compressed=True)
40
- data = pub + index.to_bytes(4, 'big')
41
- I = hmac.new(parent_chain, data, hashlib.sha512).digest()
42
- child_int = (int.from_bytes(I[:32], 'big') + int.from_bytes(parent_priv, 'big')) % _SECP256K1_N
43
- if child_int == 0:
44
- raise ValueError("Invalid child key")
45
- return child_int.to_bytes(32, 'big'), I[32:]
46
-
47
- def seed_to_privkey_hd(seed, address_index=0):
48
- I = hmac.new(b"Bitcoin seed", seed, hashlib.sha512).digest()
49
- key, chain = I[:32], I[32:]
50
- for idx in [44 + _HARDENED, 60 + _HARDENED, _HARDENED, 0, address_index]:
51
- key, chain = _bip32_derive_child_priv(key, chain, idx)
52
- return key
53
-
54
- # ---------- BIP39 ----------
55
- try:
56
- import bip39 as _bip39_rust
57
- _USE_RUST_BIP39 = True
58
- if hasattr(_bip39_rust, 'phrase_to_seed'):
59
- _seed_fn = _bip39_rust.phrase_to_seed
60
- _check_fn = getattr(_bip39_rust, 'check_phrase', None)
61
- elif hasattr(_bip39_rust, 'bip39_to_seed'):
62
- _seed_fn = _bip39_rust.bip39_to_seed
63
- _check_fn = getattr(_bip39_rust, 'bip39_validate', None)
64
- else:
65
- _seed_fn = None; _check_fn = None; _USE_RUST_BIP39 = False
66
- except ImportError:
67
- _bip39_rust = None; _USE_RUST_BIP39 = False; _seed_fn = None; _check_fn = None
68
-
69
- def is_valid_bip39(phrase):
70
- if _USE_RUST_BIP39 and _check_fn:
71
- return _check_fn(phrase)
72
- return _get_mnemonic().check(phrase)
73
-
74
- def phrase_to_seed(phrase, passphrase=""):
75
- if _USE_RUST_BIP39 and _seed_fn:
76
- return _seed_fn(phrase, passphrase)
77
- return _get_mnemonic().to_seed(phrase, passphrase=passphrase)
78
-
79
- # ---------- Address file ----------
80
- def load_addresses(path):
81
- s = set()
82
- with open(path, "r", encoding="utf-8") as f:
83
- for line in f:
84
- a = line.strip().strip('"').strip("'").lstrip("\ufeff").lower()
85
- if a.startswith("0x"):
86
- a = a[2:]
87
- if a and len(a) == 40:
88
- s.add(a)
89
- return s
90
-
91
- def normalize(addr):
92
- a = addr.strip().lower()
93
- if a.startswith("0x"):
94
- a = a[2:]
95
- return a
96
-
97
- # ---------- Generator ----------
98
- def generate_phrases_for_words(wordlist, mode):
99
- n = len(wordlist)
100
- if mode == "order":
101
- for perm in permutations(wordlist):
102
- yield " ".join(perm)
103
- elif mode == "replace":
104
- for i in range(n):
105
- for w in wordlist:
106
- new = wordlist.copy()
107
- new[i] = w
108
- yield " ".join(new)
109
- elif mode == "subset":
110
- for r in range(1, n + 1):
111
- for combo in combinations(wordlist, r):
112
- yield " ".join(combo)
113
-
114
- # ============================================================
115
- # Gradio functions
116
- # ============================================================
117
-
118
- def generate_random_phrase():
119
- """BIP39 valid phrase generate karta hai — checksum ke saath."""
120
- mnemo = _get_mnemonic()
121
- return mnemo.generate(strength=128) # 128 bits = 12 words
122
-
123
-
124
- def run_scan_range(phrase, addresses_file, phrase_mode,
125
- start_index, end_index, passphrase):
126
- """0–20 index range scan — single process, fast."""
127
- if not os.path.exists(addresses_file):
128
- return f"❌ File nahi mili: {addresses_file}", ""
129
-
130
- words = phrase.strip().split()
131
- if len(words) != 12:
132
- return f"❌ Phrase 12 words ki nahi hai ({len(words)} words)", ""
133
-
134
- start_index = int(start_index)
135
- end_index = int(end_index)
136
- if start_index > end_index:
137
- return "❌ Start index end index se bada nahi ho sakta", ""
138
-
139
- try:
140
- known = load_addresses(addresses_file)
141
- except Exception as e:
142
- return f"❌ Addresses load fail: {e}", ""
143
-
144
- if not known:
145
- return "❌ Koi valid address file mein nahi mila", ""
146
-
147
- total_combos = len(words) * len(words) if phrase_mode == "replace" else math.factorial(len(words)) if phrase_mode == "order" else 2**len(words) - 1
148
- index_count = end_index - start_index + 1
149
- total_scans = total_combos * index_count
150
-
151
- log_lines = [
152
- f"✅ Loaded {len(known):,} addresses",
153
- f"🔧 Mode: {phrase_mode}",
154
- f"🔑 Index range: {start_index}–{end_index} ({index_count} indices)",
155
- f"📝 Phrase: {phrase}",
156
- f"🔢 Combinations per index: {total_combos:,}",
157
- f"🔢 Total scans: {total_scans:,}",
158
- "",
159
- ]
160
-
161
- matches = []
162
- start = time.time()
163
-
164
- for idx in range(start_index, end_index + 1):
165
- log_lines.append(f"🔍 Checking index {idx}...")
166
- for phrase_str in generate_phrases_for_words(words, phrase_mode):
167
- if not is_valid_bip39(phrase_str):
168
- continue
169
- try:
170
- seed = phrase_to_seed(phrase_str, passphrase)
171
- priv = seed_to_privkey_hd(seed, idx)
172
- pub = coincurve.PrivateKey(priv).public_key.format(compressed=False)[1:]
173
- addr = to_checksum_address(keccak(pub)[-20:])
174
- except Exception:
175
- continue
176
- if normalize(addr) in known:
177
- match_line = (
178
- f"🎉 MATCH!\n"
179
- f"Phrase: {phrase_str}\n"
180
- f"Index: {idx}\n"
181
- f"Key: {priv.hex()}\n"
182
- f"Addr: {addr}\n"
183
- )
184
- log_lines.append(match_line)
185
- matches.append((phrase_str, idx, priv.hex(), addr))
186
-
187
- elapsed = time.time() - start
188
- log_lines.append(f"=== DONE ===")
189
- log_lines.append(f"Total time: {elapsed:.1f}s")
190
- log_lines.append(f"Total matches: {len(matches)}")
191
-
192
- matches_text = "\n".join(
193
- f"Phrase: {p}\nIndex: {i}\nKey: {k}\nAddr: {a}\n" for p, i, k, a in matches
194
- ) if matches else "Koi match nahi mila"
195
-
196
- return "\n".join(log_lines), matches_text
197
-
198
-
199
- # ============================================================
200
- # Build UI
201
- # ============================================================
202
- with gr.Blocks(title="Phrase Scanner") as demo:
203
- gr.Markdown("# 🔍 Phrase Scanner")
204
- gr.Markdown("Phrase daalein aur index range (0–20) ke saath address file se match karein.")
205
-
206
- with gr.Row():
207
- with gr.Column(scale=1):
208
- gr.Markdown("### Settings")
209
- phrase = gr.Textbox(
210
- label="🔑 12-Word Phrase",
211
- value="lesson cushion crane affair federal decline limb spend reunion chief cart zebra",
212
- lines=2,
213
- placeholder="lesson cushion crane ...",
214
- )
215
- generate_btn = gr.Button("🎲 Random Phrase Generate Karein", variant="secondary")
216
- addresses_file = gr.Textbox(
217
- label="Addresses File",
218
- value="12730802_addresses.csv",
219
- )
220
- phrase_mode = gr.Radio(
221
- choices=["replace", "order", "subset"],
222
- value="replace",
223
- label="Phrase Mode",
224
- )
225
- with gr.Row():
226
- start_index = gr.Number(
227
- label="Start Index",
228
- value=0, precision=0, minimum=0,
229
- )
230
- end_index = gr.Number(
231
- label="End Index",
232
- value=20, precision=0, minimum=0,
233
- )
234
- passphrase = gr.Textbox(
235
- label="BIP39 Passphrase (khali chhod dein)",
236
- value="",
237
- type="password",
238
- )
239
- run_btn = gr.Button("🚀 Scan Shuru Karein", variant="primary")
240
-
241
- with gr.Column(scale=2):
242
- gr.Markdown("### Output")
243
- log_output = gr.Textbox(
244
- label="Scan Log",
245
- lines=20,
246
- max_lines=30,
247
- interactive=False,
248
- autoscroll=True,
249
- )
250
- matches_output = gr.Textbox(
251
- label="Matches",
252
- lines=10,
253
- interactive=False,
254
- autoscroll=True,
255
- )
256
-
257
- generate_btn.click(fn=generate_random_phrase, outputs=[phrase])
258
- run_btn.click(
259
- fn=run_scan_range,
260
- inputs=[phrase, addresses_file, phrase_mode,
261
- start_index, end_index, passphrase],
262
- outputs=[log_output, matches_output],
263
- )
264
-
265
- # ZeroGPU requirement
266
- _noop()
267
-
268
- _original_launch = demo.launch
269
- def _patched_launch(**kwargs):
270
- kwargs.setdefault("ssr_mode", False)
271
- kwargs.setdefault("share", True)
272
- kwargs.setdefault("server_name", "0.0.0.0")
273
- kwargs.setdefault("server_port", 7860)
274
- return _original_launch(**kwargs)
275
- demo.launch = _patched_launch
276
-
277
- if __name__ == "__main__":
278
- demo.launch(theme=gr.themes.Soft())