DILSHAD737 commited on
Commit
7af2087
·
1 Parent(s): 1741ab8

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -330
app.py DELETED
@@ -1,330 +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 Cache ----------
80
- _ADDRESS_CACHE = {}
81
-
82
- def load_addresses_cached(path):
83
- if path in _ADDRESS_CACHE:
84
- cached_mtime, cached_set = _ADDRESS_CACHE[path]
85
- try:
86
- current_mtime = os.path.getmtime(path)
87
- if current_mtime == cached_mtime:
88
- return cached_set
89
- except OSError:
90
- pass
91
-
92
- s = set()
93
- with open(path, "r", encoding="utf-8") as f:
94
- for line in f:
95
- a = line.strip().strip('"').strip("'").lstrip("\ufeff").lower()
96
- if a.startswith("0x"):
97
- a = a[2:]
98
- if a and len(a) == 40:
99
- s.add(a)
100
-
101
- try:
102
- mtime = os.path.getmtime(path)
103
- except OSError:
104
- mtime = 0
105
- _ADDRESS_CACHE[path] = (mtime, s)
106
- return s
107
-
108
- def normalize(addr):
109
- a = addr.strip().lower()
110
- if a.startswith("0x"):
111
- a = a[2:]
112
- return a
113
-
114
- # ---------- Generator ----------
115
- def generate_phrases_for_words(wordlist, mode):
116
- n = len(wordlist)
117
- if mode == "order":
118
- for perm in permutations(wordlist):
119
- yield " ".join(perm)
120
- elif mode == "replace":
121
- for i in range(n):
122
- for w in wordlist:
123
- new = wordlist.copy()
124
- new[i] = w
125
- yield " ".join(new)
126
- elif mode == "subset":
127
- for r in range(1, n + 1):
128
- for combo in combinations(wordlist, r):
129
- yield " ".join(combo)
130
-
131
- # ============================================================
132
- # Gradio functions — YIELD for live updates
133
- # ============================================================
134
-
135
- def generate_random_phrase():
136
- return _get_mnemonic().generate(strength=128)
137
-
138
-
139
- def run_multi_phrase_scan(my_phrase, num_phrases, addresses_file, phrase_mode,
140
- start_index, end_index, passphrase):
141
- """
142
- Generator — har step pe yield, taake UI live update ho.
143
- """
144
- if not os.path.exists(addresses_file):
145
- yield f"❌ File nahi mili: {addresses_file}", ""
146
- return
147
-
148
- num_phrases = int(num_phrases)
149
- start_index = int(start_index)
150
- end_index = int(end_index)
151
-
152
- yield "Addresses load ho rahe hain...", ""
153
-
154
- try:
155
- known = load_addresses_cached(addresses_file)
156
- except Exception as e:
157
- yield f"❌ Addresses load fail: {e}", ""
158
- return
159
-
160
- if not known:
161
- yield "❌ Koi valid address file mein nahi mila", ""
162
- return
163
-
164
- mnemo = _get_mnemonic()
165
- phrases = []
166
-
167
- # Apni phrase pehle
168
- my_words = my_phrase.strip().split()
169
- if len(my_words) == 12:
170
- phrases.append(" ".join(my_words))
171
-
172
- for _ in range(num_phrases):
173
- phrases.append(mnemo.generate(strength=128))
174
-
175
- log_lines = [
176
- f"✅ Loaded {len(known):,} addresses (cached)",
177
- f"🔧 Mode: {phrase_mode}",
178
- f"🔑 Index range: {start_index}–{end_index}",
179
- f"📝 Total phrases: {len(phrases)}",
180
- "",
181
- "Phrases:",
182
- ]
183
- for i, p in enumerate(phrases, 1):
184
- tag = " (AAPKI)" if i == 1 and len(my_words) == 12 else ""
185
- log_lines.append(f" {i}. {p}{tag}")
186
- log_lines.append("")
187
-
188
- # Initial yield — phrases dikh jayein
189
- yield "\n".join(log_lines), "Scan shuru ho raha hai..."
190
-
191
- matches = []
192
- start = time.time()
193
- total_phrases = len(phrases)
194
-
195
- for p_idx, phrase in enumerate(phrases, 1):
196
- log_lines.append(f"🔍 [{p_idx}/{total_phrases}] Checking: {phrase}")
197
- yield "\n".join(log_lines), "\n".join(
198
- f"Phrase: {p}\nIndex: {i}\nKey: {k}\nAddr: {a}\n" for p, i, k, a in matches
199
- ) if matches else "Abhi tak koi match nahi"
200
-
201
- words = phrase.strip().split()
202
- if len(words) != 12:
203
- log_lines.append(f" ⚠️ Skipped (not 12 words)")
204
- yield "\n".join(log_lines), "Koi match nahi mila"
205
- continue
206
-
207
- for idx in range(start_index, end_index + 1):
208
- log_lines.append(f" Index {idx}...")
209
- yield "\n".join(log_lines), "\n".join(
210
- f"Phrase: {p}\nIndex: {i}\nKey: {k}\nAddr: {a}\n" for p, i, k, a in matches
211
- ) if matches else "Abhi tak koi match nahi"
212
-
213
- for phrase_str in generate_phrases_for_words(words, phrase_mode):
214
- if not is_valid_bip39(phrase_str):
215
- continue
216
- try:
217
- seed = phrase_to_seed(phrase_str, passphrase)
218
- priv = seed_to_privkey_hd(seed, idx)
219
- pub = coincurve.PrivateKey(priv).public_key.format(compressed=False)[1:]
220
- addr = to_checksum_address(keccak(pub)[-20:])
221
- except Exception:
222
- continue
223
- if normalize(addr) in known:
224
- match_line = (
225
- f"🎉 MATCH!\n"
226
- f"Phrase: {phrase_str}\n"
227
- f"Index: {idx}\n"
228
- f"Key: {priv.hex()}\n"
229
- f"Addr: {addr}\n"
230
- )
231
- log_lines.append(match_line)
232
- matches.append((phrase_str, idx, priv.hex(), addr))
233
- # Match mile to turant dikhayein
234
- yield "\n".join(log_lines), "\n".join(
235
- f"Phrase: {p}\nIndex: {i}\nKey: {k}\nAddr: {a}\n" for p, i, k, a in matches
236
- )
237
-
238
- elapsed = time.time() - start
239
- log_lines.append(f"=== DONE ===")
240
- log_lines.append(f"Total time: {elapsed:.1f}s")
241
- log_lines.append(f"Total matches: {len(matches)}")
242
-
243
- matches_text = "\n".join(
244
- f"Phrase: {p}\nIndex: {i}\nKey: {k}\nAddr: {a}\n" for p, i, k, a in matches
245
- ) if matches else "Koi match nahi mila"
246
-
247
- yield "\n".join(log_lines), matches_text
248
-
249
-
250
- # ============================================================
251
- # Build UI
252
- # ============================================================
253
- with gr.Blocks(title="Phrase Scanner") as demo:
254
- gr.Markdown("# 🔍 Phrase Scanner")
255
- gr.Markdown("Apni phrase ya random phrases check karein, index range ke saath.")
256
-
257
- with gr.Row():
258
- with gr.Column(scale=1):
259
- gr.Markdown("### Settings")
260
- my_phrase = gr.Textbox(
261
- label="🔑 Apni Phrase (optional)",
262
- value="lesson cushion crane affair federal decline limb spend reunion chief cart zebra",
263
- lines=2,
264
- )
265
- num_phrases = gr.Number(
266
- label="Kitni Random Phrases Check Karein?",
267
- value=10, precision=0, minimum=0,
268
- )
269
- addresses_file = gr.Textbox(
270
- label="Addresses File",
271
- value="12730802_addresses.csv",
272
- )
273
- phrase_mode = gr.Radio(
274
- choices=["replace", "order", "subset"],
275
- value="replace",
276
- label="Phrase Mode",
277
- )
278
- with gr.Row():
279
- start_index = gr.Number(
280
- label="Start Index",
281
- value=0, precision=0, minimum=0,
282
- )
283
- end_index = gr.Number(
284
- label="End Index",
285
- value=20, precision=0, minimum=0,
286
- )
287
- passphrase = gr.Textbox(
288
- label="BIP39 Passphrase (khali chhod dein)",
289
- value="",
290
- type="password",
291
- )
292
- run_btn = gr.Button("🚀 Scan Shuru Karein", variant="primary")
293
-
294
- with gr.Column(scale=2):
295
- gr.Markdown("### Output")
296
- log_output = gr.Textbox(
297
- label="Scan Log",
298
- lines=20,
299
- max_lines=30,
300
- interactive=False,
301
- autoscroll=True,
302
- )
303
- matches_output = gr.Textbox(
304
- label="Matches",
305
- lines=10,
306
- interactive=False,
307
- autoscroll=True,
308
- )
309
-
310
- run_btn.click(
311
- fn=run_multi_phrase_scan,
312
- inputs=[my_phrase, num_phrases, addresses_file, phrase_mode,
313
- start_index, end_index, passphrase],
314
- outputs=[log_output, matches_output],
315
- )
316
-
317
- # ZeroGPU requirement
318
- _noop()
319
-
320
- _original_launch = demo.launch
321
- def _patched_launch(**kwargs):
322
- kwargs.setdefault("ssr_mode", False)
323
- kwargs.setdefault("share", True)
324
- kwargs.setdefault("server_name", "0.0.0.0")
325
- kwargs.setdefault("server_port", 7860)
326
- return _original_launch(**kwargs)
327
- demo.launch = _patched_launch
328
-
329
- if __name__ == "__main__":
330
- demo.launch(theme=gr.themes.Soft())