DILSHAD737 commited on
Commit
1741ab8
Β·
1 Parent(s): 9145683

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -140
app.py CHANGED
@@ -9,24 +9,18 @@ except Exception:
9
  pass
10
 
11
  import gradio as gr
12
- import hashlib, hmac, os, time, math, gc, random
13
  from itertools import permutations, combinations
14
- from multiprocessing import Pool
15
  from mnemonic import Mnemonic
16
  import coincurve
17
  from eth_utils import keccak, to_checksum_address
18
  import spaces
19
 
20
- # ============================================================
21
- # πŸ”‘ APNI PHRASE YAHAN DALEIN
22
- MY_PHRASE = "lesson cushion crane affair federal decline limb spend reunion chief cart zebra"
23
- # ============================================================
24
-
25
  @spaces.GPU
26
  def _noop():
27
  return "ok"
28
 
29
- # ---------- Mnemonic ----------
30
  _MNEMONIC = None
31
  def _get_mnemonic():
32
  global _MNEMONIC
@@ -36,7 +30,7 @@ def _get_mnemonic():
36
 
37
  # ---------- BIP32 manual ----------
38
  _SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
39
- _HARDENED = 0x80000000
40
 
41
  def _bip32_derive_child_priv(parent_priv, parent_chain, index):
42
  if index >= _HARDENED:
@@ -82,19 +76,39 @@ def phrase_to_seed(phrase, passphrase=""):
82
  return _seed_fn(phrase, passphrase)
83
  return _get_mnemonic().to_seed(phrase, passphrase=passphrase)
84
 
85
- # ---------- Address file ----------
86
- def load_addresses(path):
 
 
 
 
 
 
 
 
 
 
 
87
  s = set()
88
  with open(path, "r", encoding="utf-8") as f:
89
  for line in f:
90
  a = line.strip().strip('"').strip("'").lstrip("\ufeff").lower()
91
- if a.startswith("0x"): a = a[2:]
92
- if a and len(a) == 40: s.add(a)
93
- return frozenset(s)
 
 
 
 
 
 
 
 
94
 
95
  def normalize(addr):
96
  a = addr.strip().lower()
97
- if a.startswith("0x"): a = a[2:]
 
98
  return a
99
 
100
  # ---------- Generator ----------
@@ -114,139 +128,121 @@ def generate_phrases_for_words(wordlist, mode):
114
  for combo in combinations(wordlist, r):
115
  yield " ".join(combo)
116
 
117
- # ---------- Worker ----------
118
- _KNOWN = None
 
119
 
120
- def init_worker(known):
121
- global _KNOWN
122
- _KNOWN = known
123
- _get_mnemonic()
124
 
125
- def process_batch(args):
126
- batch, passphrase, address_index, hd, checksum = args
127
- hits = []
128
- known = _KNOWN
129
- for phrase in batch:
130
- if checksum and not is_valid_bip39(phrase):
131
- continue
132
- try:
133
- seed = phrase_to_seed(phrase, passphrase)
134
- priv = seed_to_privkey_hd(seed, address_index) if hd else seed[:32]
135
- pub = coincurve.PrivateKey(priv).public_key.format(compressed=False)[1:]
136
- addr = to_checksum_address(keccak(pub)[-20:])
137
- except Exception:
138
- continue
139
- if normalize(addr) in known:
140
- hits.append((phrase, priv.hex(), addr))
141
- return hits
142
-
143
- def batch_generator_for_words(wordlist, mode, batch_size):
144
- batch = []
145
- for phrase in generate_phrases_for_words(wordlist, mode):
146
- batch.append(phrase)
147
- if len(batch) >= batch_size:
148
- yield batch
149
- batch = []
150
- if batch:
151
- yield batch
152
 
153
- # ============================================================
154
- # Gradio Interface
155
- # ============================================================
156
- def run_scan(
157
- my_phrase,
158
- addresses_file,
159
- num_phrases,
160
- phrase_mode,
161
- address_index,
162
- passphrase,
163
- workers,
164
- batch_size,
165
- progress=gr.Progress(),
166
- ):
167
  if not os.path.exists(addresses_file):
168
- return f"❌ File nahi mili: {addresses_file}", ""
 
169
 
170
  num_phrases = int(num_phrases)
171
- workers = int(workers)
172
- batch_size = int(batch_size)
173
- address_index = int(address_index)
174
-
175
- if num_phrases < 0:
176
- return "❌ Phrases ki tadaad negative nahi ho sakti", ""
177
- if workers < 1:
178
- return "❌ Kam az kam 1 worker chahiye", ""
179
 
180
  yield "Addresses load ho rahe hain...", ""
 
181
  try:
182
- known = load_addresses(addresses_file)
183
  except Exception as e:
184
- return f"❌ Addresses load fail: {e}", ""
 
185
 
186
  if not known:
187
- return "❌ Koi valid address file mein nahi mila", ""
 
188
 
189
- wordlist = _get_mnemonic().wordlist
190
- random_phrases = [random.sample(wordlist, 12) for _ in range(num_phrases)]
191
 
192
- # πŸ”‘ Apni phrase sab se pehle
193
  my_words = my_phrase.strip().split()
194
  if len(my_words) == 12:
195
- random_phrases.insert(0, my_words)
196
- phrase_note = "βœ… Aapki phrase sab se pehle check hogi"
197
- else:
198
- phrase_note = f"⚠️ Aapki phrase 12 words ki nahi hai ({len(my_words)} words) β€” skip"
199
 
200
- total_phrases = len(random_phrases)
201
  log_lines = [
202
- phrase_note,
203
- f"βœ… Loaded {len(known):,} addresses",
204
- f"βœ… {num_phrases} random phrases + 1 aapki phrase = {total_phrases} total",
205
- f"πŸ”§ Mode: {phrase_mode} | Workers: {workers} | Batch: {batch_size}",
206
- f"πŸ”‘ Address index: {address_index} | Passphrase: {'(set)' if passphrase else '(empty)'}",
207
  "",
 
208
  ]
 
 
 
 
209
 
210
- output_matches = []
211
- matches_text = ""
212
- all_start = time.time()
213
-
214
- for idx, wordlist_words in enumerate(random_phrases, 1):
215
- progress((idx - 1) / total_phrases, desc=f"Phrase {idx}/{total_phrases}")
216
-
217
- gc.collect()
218
- gc.freeze()
219
-
220
- phrase_matches = []
221
-
222
- with Pool(processes=workers,
223
- initializer=init_worker,
224
- initargs=(known,)) as pool:
225
- for hits in pool.imap_unordered(
226
- process_batch,
227
- (
228
- (batch, passphrase, address_index, True, True)
229
- for batch in batch_generator_for_words(wordlist_words, phrase_mode, batch_size)
230
- ),
231
- chunksize=4
232
- ):
233
- for phrase, key_hex, addr in hits:
234
- match_line = f"πŸŽ‰ MATCH!\nPhrase: {phrase}\nKey: {key_hex}\nAddr: {addr}\n"
235
- matches_text += match_line + "\n"
236
- output_matches.append((phrase, key_hex, addr))
237
- phrase_matches.append((phrase, key_hex, addr))
238
- log_lines.append(match_line)
239
- yield "\n".join(log_lines), matches_text
240
 
241
- log_lines.append(f"Phrase {idx}/{total_phrases} done β€” {len(phrase_matches)} match(es)")
242
- yield "\n".join(log_lines), matches_text
 
243
 
244
- elapsed = time.time() - all_start
245
- progress(1.0, desc="Done")
246
- log_lines.append("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  log_lines.append(f"=== DONE ===")
248
  log_lines.append(f"Total time: {elapsed:.1f}s")
249
- log_lines.append(f"Total matches: {len(output_matches)}")
 
 
 
 
250
 
251
  yield "\n".join(log_lines), matches_text
252
 
@@ -256,42 +252,71 @@ def run_scan(
256
  # ============================================================
257
  with gr.Blocks(title="Phrase Scanner") as demo:
258
  gr.Markdown("# πŸ” Phrase Scanner")
259
- gr.Markdown("Aapki phrase + random 12-word phrases generate karein aur address file se match karein.")
260
 
261
  with gr.Row():
262
  with gr.Column(scale=1):
263
  gr.Markdown("### Settings")
264
  my_phrase = gr.Textbox(
265
- label="πŸ”‘ Aapki Phrase (12 words)",
266
- value=MY_PHRASE,
267
- placeholder="lesson cushion crane ...",
268
  lines=2,
269
  )
270
- addresses_file = gr.Textbox(label="Addresses File", value="12730802_addresses.csv")
271
- num_phrases = gr.Slider(label="Kitni Random Phrases", minimum=0, maximum=1000, value=10, step=1)
272
- phrase_mode = gr.Radio(choices=["replace", "order", "subset"], value="replace", label="Phrase Mode")
273
- address_index = gr.Number(label="Address Index", value=0, precision=0)
274
- passphrase = gr.Textbox(label="BIP39 Passphrase (khali chhod dein)", value="", type="password")
275
- workers = gr.Slider(label="Workers", minimum=1, maximum=192, value=48, step=1)
276
- batch_size = gr.Slider(label="Batch Size", minimum=100, maximum=10000, value=5000, step=100)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  run_btn = gr.Button("πŸš€ Scan Shuru Karein", variant="primary")
278
 
279
  with gr.Column(scale=2):
280
  gr.Markdown("### Output")
281
- log_output = gr.Textbox(label="Scan Log", lines=20, max_lines=30, interactive=False, autoscroll=True)
282
- matches_output = gr.Textbox(label="Matches", lines=10, interactive=False, autoscroll=True)
 
 
 
 
 
 
 
 
 
 
 
283
 
284
  run_btn.click(
285
- fn=run_scan,
286
- inputs=[my_phrase, addresses_file, num_phrases, phrase_mode,
287
- address_index, passphrase, workers, batch_size],
288
  outputs=[log_output, matches_output],
289
  )
290
 
291
  # ZeroGPU requirement
292
  _noop()
293
 
294
- # βœ… SSR off + share for health check
295
  _original_launch = demo.launch
296
  def _patched_launch(**kwargs):
297
  kwargs.setdefault("ssr_mode", False)
 
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
 
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:
 
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 ----------
 
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
 
 
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)