-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy patheth_toolkit.py
More file actions
1497 lines (1252 loc) · 51 KB
/
Copy patheth_toolkit.py
File metadata and controls
1497 lines (1252 loc) · 51 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
"""
Ethereum Wallet Toolkit
================================================================================
DISCLAIMER - EDUCATIONAL PURPOSES ONLY
================================================================================
THIS SOFTWARE IS PROVIDED FOR EDUCATIONAL AND RESEARCH PURPOSES ONLY.
DO NOT USE WITH REAL FUNDS. DO NOT USE IN PRODUCTION.
The author(s) accept NO LIABILITY for any damages, losses, or consequences
arising from the use of this software. By using this software, you acknowledge
that you are solely responsible for your actions and any outcomes.
This software is provided "AS IS" without warranty of any kind. The author(s)
make no guarantees about the security, correctness, or fitness for any purpose.
ALWAYS:
- Audit the code yourself before any use
- Use hardware wallets for real funds
- Never use generated keys for real assets
- Understand that vanity address generation has inherent risks
================================================================================
A comprehensive toolkit for Ethereum wallet operations:
- Generate random wallets
- Generate vanity addresses (prefix/suffix/pattern matching)
- Create/restore from BIP39 mnemonics
- Sign and verify messages
- Validate addresses and keys
Uses official Ethereum Foundation libraries (eth-account).
Author: nich
License: MIT
X (Formerly Twitter): x.com/nichxbt
Github: github.com/nirholas
"""
import argparse
import json
import os
import re
import sys
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from multiprocessing import cpu_count
from typing import Optional
from eth_account import Account
from eth_account.messages import encode_defunct
from eth_account.hdaccount import ETHEREUM_DEFAULT_PATH
from eth_keys import keys
import rlp
# Enable HD wallet features
Account.enable_unaudited_hdwallet_features()
# ============================================================================
# Data Classes
# ============================================================================
@dataclass
class WalletResult:
"""Result of wallet generation."""
address: str
private_key: str
mnemonic: Optional[str] = None
derivation_path: Optional[str] = None
@dataclass
class VanityResult(WalletResult):
"""Result of vanity address generation."""
attempts: int = 0
time_seconds: float = 0.0
# ============================================================================
# Validation Functions
# ============================================================================
def is_valid_hex_pattern(pattern: str) -> bool:
"""Check if pattern contains only valid hex characters."""
return bool(re.match(r'^[0-9a-fA-F]*$', pattern))
def is_valid_address(address: str) -> bool:
"""Validate Ethereum address format."""
if not address.startswith('0x'):
return False
if len(address) != 42:
return False
return is_valid_hex_pattern(address[2:])
def is_valid_private_key(key: str) -> bool:
"""Validate private key format."""
key = key[2:] if key.startswith('0x') else key
if len(key) != 64:
return False
return is_valid_hex_pattern(key)
def validate_public_key(address: str, private_key: str) -> bool:
"""Verify that a private key corresponds to an address."""
try:
account = Account.from_key(private_key)
return account.address.lower() == address.lower()
except Exception:
return False
# ============================================================================
# Wallet Generation
# ============================================================================
def create_wallet() -> WalletResult:
"""Create a new random wallet."""
account = Account.create()
return WalletResult(
address=account.address,
private_key='0x' + account.key.hex()
)
def create_wallet_with_mnemonic(
num_words: int = 12,
language: str = "english",
passphrase: str = "",
derivation_path: str = ETHEREUM_DEFAULT_PATH
) -> WalletResult:
"""Create a new wallet with BIP39 mnemonic."""
account, mnemonic = Account.create_with_mnemonic(
passphrase=passphrase,
num_words=num_words,
language=language,
account_path=derivation_path
)
return WalletResult(
address=account.address,
private_key=account.key.hex(),
mnemonic=mnemonic,
derivation_path=derivation_path
)
def restore_from_mnemonic(
mnemonic: str,
passphrase: str = "",
derivation_path: str = ETHEREUM_DEFAULT_PATH
) -> WalletResult:
"""Restore wallet from BIP39 mnemonic."""
account = Account.from_mnemonic(
mnemonic=mnemonic,
passphrase=passphrase,
account_path=derivation_path
)
return WalletResult(
address=account.address,
private_key=account.key.hex(),
mnemonic=mnemonic,
derivation_path=derivation_path
)
def restore_from_private_key(private_key: str) -> WalletResult:
"""Restore wallet from private key."""
account = Account.from_key(private_key)
return WalletResult(
address=account.address,
private_key=account.key.hex()
)
def derive_multiple_accounts(
mnemonic: str,
count: int = 10,
passphrase: str = "",
base_path: str = "m/44'/60'/0'/0"
) -> list[WalletResult]:
"""Derive multiple accounts from a single mnemonic."""
accounts = []
for i in range(count):
path = f"{base_path}/{i}"
account = Account.from_mnemonic(
mnemonic=mnemonic,
passphrase=passphrase,
account_path=path
)
accounts.append(WalletResult(
address=account.address,
private_key=account.key.hex(),
mnemonic=mnemonic,
derivation_path=path
))
return accounts
# ============================================================================
# Message Signing & Verification
# ============================================================================
def sign_message(message: str, private_key: str) -> dict:
"""Sign a message with a private key."""
signable = encode_defunct(text=message)
signed = Account.sign_message(signable, private_key)
return {
"message": message,
"signature": '0x' + signed.signature.hex(),
"r": hex(signed.r),
"s": hex(signed.s),
"v": signed.v,
"message_hash": '0x' + signed.message_hash.hex()
}
def verify_message(message: str, signature: str, expected_address: str) -> dict:
"""Verify a signed message and recover the signer's address."""
signable = encode_defunct(text=message)
recovered_address = Account.recover_message(signable, signature=signature)
is_valid = recovered_address.lower() == expected_address.lower()
return {
"message": message,
"signature": signature,
"expected_address": expected_address,
"recovered_address": recovered_address,
"is_valid": is_valid
}
# ============================================================================
# Keystore Encryption/Decryption
# ============================================================================
def encrypt_keystore(private_key: str, password: str) -> dict:
"""
Encrypt a private key to a JSON keystore file format.
Creates an industry-standard encrypted keystore compatible with:
- MetaMask
- MyEtherWallet
- Geth
- Most Ethereum wallets
Args:
private_key: Private key (with or without 0x prefix)
password: Password to encrypt the keystore
Returns:
Keystore dictionary (JSON-serializable)
"""
# Normalize private key
if private_key.startswith('0x'):
private_key = private_key[2:]
key_bytes = bytes.fromhex(private_key)
keystore = Account.encrypt(key_bytes, password)
return keystore
def decrypt_keystore(keystore: dict, password: str) -> dict:
"""
Decrypt a JSON keystore file to recover the private key.
Args:
keystore: Keystore dictionary (from JSON file)
password: Password used to encrypt the keystore
Returns:
Dictionary with address and private_key
"""
key_bytes = Account.decrypt(keystore, password)
account = Account.from_key(key_bytes)
return {
"address": account.address,
"private_key": key_bytes.hex()
}
def save_keystore(private_key: str, password: str, filepath: str) -> str:
"""
Encrypt and save a private key to a keystore file.
Args:
private_key: Private key to encrypt
password: Encryption password
filepath: Path to save the keystore file
Returns:
Path to the saved file
"""
keystore = encrypt_keystore(private_key, password)
with open(filepath, 'w') as f:
json.dump(keystore, f, indent=2)
return filepath
def load_keystore(filepath: str, password: str) -> dict:
"""
Load and decrypt a keystore file.
Args:
filepath: Path to the keystore file
password: Decryption password
Returns:
Dictionary with address and private_key
"""
with open(filepath, 'r') as f:
keystore = json.load(f)
return decrypt_keystore(keystore, password)
# ============================================================================
# Transaction Signing
# ============================================================================
def sign_transaction(
private_key: str,
to: str,
value: int,
nonce: int,
gas: int = 21000,
gas_price: Optional[int] = None,
max_fee_per_gas: Optional[int] = None,
max_priority_fee_per_gas: Optional[int] = None,
data: str = "0x",
chain_id: int = 1
) -> dict:
"""
Sign an Ethereum transaction offline.
Supports both legacy (gas_price) and EIP-1559 (max_fee_per_gas) transactions.
Args:
private_key: Signer's private key
to: Recipient address
value: Amount in wei
nonce: Transaction nonce
gas: Gas limit (default: 21000 for simple transfer)
gas_price: Legacy gas price in wei (for pre-EIP-1559)
max_fee_per_gas: EIP-1559 max fee per gas in wei
max_priority_fee_per_gas: EIP-1559 priority fee in wei
data: Transaction data (default: 0x for simple transfer)
chain_id: Network chain ID (1=mainnet, 5=goerli, 11155111=sepolia)
Returns:
Dictionary with signed transaction details
"""
from eth_utils import to_checksum_address
tx = {
"to": to_checksum_address(to),
"value": value,
"gas": gas,
"nonce": nonce,
"chainId": chain_id,
"data": data
}
# EIP-1559 transaction
if max_fee_per_gas is not None:
tx["maxFeePerGas"] = max_fee_per_gas
tx["maxPriorityFeePerGas"] = max_priority_fee_per_gas or 0
tx["type"] = 2
# Legacy transaction
elif gas_price is not None:
tx["gasPrice"] = gas_price
else:
raise ValueError("Must specify either gas_price (legacy) or max_fee_per_gas (EIP-1559)")
signed = Account.sign_transaction(tx, private_key)
return {
"raw_transaction": signed.raw_transaction.hex(),
"hash": signed.hash.hex(),
"r": hex(signed.r),
"s": hex(signed.s),
"v": signed.v,
"transaction": tx
}
def recover_transaction_signer(raw_transaction: str) -> str:
"""
Recover the signer's address from a signed transaction.
Args:
raw_transaction: Raw signed transaction in hex
Returns:
Signer's address
"""
if raw_transaction.startswith('0x'):
raw_transaction = raw_transaction[2:]
tx_bytes = bytes.fromhex(raw_transaction)
return Account.recover_transaction(tx_bytes)
# ============================================================================
# EIP-712 Typed Data Signing
# ============================================================================
def sign_typed_data(private_key: str, domain: dict, types: dict, message: dict, primary_type: str) -> dict:
"""
Sign EIP-712 typed structured data.
Used by DeFi protocols, NFT marketplaces, and dApps for:
- Uniswap Permit2 approvals
- OpenSea listings
- Gnosis Safe transactions
- And many more
Args:
private_key: Signer's private key
domain: EIP-712 domain separator (name, version, chainId, verifyingContract)
types: Type definitions for the structured data
message: The actual message data to sign
primary_type: The primary type name in the types dict
Returns:
Dictionary with signature details
Example:
domain = {
"name": "MyDApp",
"version": "1",
"chainId": 1,
"verifyingContract": "0x..."
}
types = {
"Person": [
{"name": "name", "type": "string"},
{"name": "wallet", "type": "address"}
]
}
message = {"name": "Alice", "wallet": "0x..."}
sign_typed_data(key, domain, types, message, "Person")
"""
from eth_account.messages import encode_typed_data
full_message = {
"types": {
"EIP712Domain": [
{"name": "name", "type": "string"},
{"name": "version", "type": "string"},
{"name": "chainId", "type": "uint256"},
{"name": "verifyingContract", "type": "address"}
],
**types
},
"primaryType": primary_type,
"domain": domain,
"message": message
}
signable = encode_typed_data(full_message=full_message)
signed = Account.sign_message(signable, private_key)
return {
"signature": signed.signature.hex(),
"r": hex(signed.r),
"s": hex(signed.s),
"v": signed.v,
"message_hash": signed.message_hash.hex(),
"domain": domain,
"primary_type": primary_type
}
def verify_typed_data(
domain: dict,
types: dict,
message: dict,
primary_type: str,
signature: str,
expected_address: str
) -> dict:
"""
Verify an EIP-712 typed data signature.
Args:
domain: EIP-712 domain separator
types: Type definitions
message: The message that was signed
primary_type: Primary type name
signature: The signature to verify
expected_address: Expected signer address
Returns:
Dictionary with verification result
"""
from eth_account.messages import encode_typed_data
full_message = {
"types": {
"EIP712Domain": [
{"name": "name", "type": "string"},
{"name": "version", "type": "string"},
{"name": "chainId", "type": "uint256"},
{"name": "verifyingContract", "type": "address"}
],
**types
},
"primaryType": primary_type,
"domain": domain,
"message": message
}
signable = encode_typed_data(full_message=full_message)
recovered = Account.recover_message(signable, signature=signature)
is_valid = recovered.lower() == expected_address.lower()
return {
"expected_address": expected_address,
"recovered_address": recovered,
"is_valid": is_valid
}
# ============================================================================
# Contract Address Calculation
# ============================================================================
def calculate_contract_address(address: str, nonce: int = 0) -> str:
"""
Calculate the contract address that would be created by an account.
Uses RLP encoding: keccak256(rlp([sender, nonce]))
The first contract created by an account has nonce 0.
Args:
address: The account address (with 0x prefix)
nonce: Transaction nonce (0 for first contract)
Returns:
Contract address (with 0x prefix)
"""
# Remove 0x prefix and convert to bytes
addr_bytes = bytes.fromhex(address[2:])
# RLP encode [address, nonce]
encoded = rlp.encode([addr_bytes, nonce])
# Keccak-256 hash and take last 20 bytes
from eth_hash.auto import keccak
contract_hash = keccak(encoded)
contract_address = '0x' + contract_hash[-20:].hex()
# Apply EIP-55 checksum
return Account.from_key(bytes(32)).address[:2] + contract_address[2:] # Placeholder for checksum
def get_checksum_address(address: str) -> str:
"""Convert address to EIP-55 checksum format."""
from eth_hash.auto import keccak
addr = address.lower()[2:] if address.startswith('0x') else address.lower()
hash_hex = keccak(addr.encode()).hex()
result = '0x'
for i, char in enumerate(addr):
if char in '0123456789':
result += char
elif int(hash_hex[i], 16) >= 8:
result += char.upper()
else:
result += char.lower()
return result
# ============================================================================
# Vanity Address Generation
# ============================================================================
def check_vanity_match(
address: str,
prefix: Optional[str] = None,
suffix: Optional[str] = None,
contains: Optional[str] = None,
case_sensitive: bool = False,
letters_only: bool = False,
numbers_only: bool = False,
mirror: bool = False,
leading: Optional[str] = None,
leading_count: int = 0,
doubles: bool = False,
zeros: bool = False,
regex_pattern: Optional[str] = None
) -> bool:
"""Check if an address matches the vanity criteria."""
addr = address[2:] # Remove 0x
if not case_sensitive:
addr_check = addr.lower()
prefix = prefix.lower() if prefix else None
suffix = suffix.lower() if suffix else None
contains = contains.lower() if contains else None
leading = leading.lower() if leading else None
else:
addr_check = addr
# Basic prefix/suffix matching
if prefix and not addr_check.startswith(prefix):
return False
if suffix and not addr_check.endswith(suffix):
return False
if contains and contains not in addr_check:
return False
# Letters only (a-f)
if letters_only:
if not all(c in 'abcdef' for c in addr_check):
return False
# Numbers only (0-9)
if numbers_only:
if not all(c in '0123456789' for c in addr_check):
return False
# Mirror check (first half mirrors second half)
if mirror:
half = len(addr_check) // 2
if addr_check[:half] != addr_check[-half:][::-1]:
return False
# Leading character check (address starts with N repetitions of a character)
if leading and leading_count > 0:
expected = leading * leading_count
if not addr_check.startswith(expected):
return False
# Doubles check (leading pairs like aa, bb, cc)
if doubles:
# Check for at least 2 leading double pairs
count = 0
for i in range(0, len(addr_check) - 1, 2):
if addr_check[i] == addr_check[i + 1]:
count += 1
else:
break
if count < 2:
return False
# Zeros check (address contains many zeros)
if zeros:
zero_count = addr_check.count('0')
if zero_count < 8: # Require at least 8 zeros
return False
# Regex pattern matching
if regex_pattern:
if not re.match(regex_pattern, addr_check, re.IGNORECASE if not case_sensitive else 0):
return False
return True
def mine_vanity_single(
prefix: Optional[str] = None,
suffix: Optional[str] = None,
contains: Optional[str] = None,
case_sensitive: bool = False,
letters_only: bool = False,
numbers_only: bool = False,
mirror: bool = False,
leading: Optional[str] = None,
leading_count: int = 0,
doubles: bool = False,
zeros: bool = False,
regex_pattern: Optional[str] = None,
contract: bool = False,
max_attempts: int = 0
) -> Optional[tuple[str, str, int]]:
"""Mine for a single vanity address."""
attempts = 0
while max_attempts == 0 or attempts < max_attempts:
account = Account.create()
attempts += 1
# Determine which address to check
if contract:
# Check the contract address that would be created
from eth_hash.auto import keccak
addr_bytes = bytes.fromhex(account.address[2:])
encoded = rlp.encode([addr_bytes, 0]) # nonce 0 for first contract
contract_hash = keccak(encoded)
check_address = '0x' + contract_hash[-20:].hex()
check_address = get_checksum_address(check_address)
else:
check_address = account.address
if check_vanity_match(
check_address, prefix, suffix, contains,
case_sensitive, letters_only, numbers_only, mirror,
leading, leading_count, doubles, zeros, regex_pattern
):
if contract:
return check_address, account.key.hex(), attempts, account.address
return check_address, account.key.hex(), attempts
return None
def worker_mine_vanity(
worker_id: int,
prefix: Optional[str],
suffix: Optional[str],
contains: Optional[str],
case_sensitive: bool,
letters_only: bool,
numbers_only: bool,
mirror: bool,
leading: Optional[str] = None,
leading_count: int = 0,
doubles: bool = False,
zeros: bool = False,
regex_pattern: Optional[str] = None,
contract: bool = False,
batch_size: int = 10000
) -> tuple:
"""Worker function for parallel vanity mining."""
total_attempts = 0
while True:
result = mine_vanity_single(
prefix, suffix, contains, case_sensitive,
letters_only, numbers_only, mirror,
leading, leading_count, doubles, zeros, regex_pattern,
contract, batch_size
)
if result:
if contract:
address, key, attempts, deployer = result
return address, key, total_attempts + attempts, deployer
address, key, attempts = result
return address, key, total_attempts + attempts
total_attempts += batch_size
def generate_vanity_address(
prefix: Optional[str] = None,
suffix: Optional[str] = None,
contains: Optional[str] = None,
case_sensitive: bool = False,
letters_only: bool = False,
numbers_only: bool = False,
mirror: bool = False,
leading: Optional[str] = None,
leading_count: int = 0,
doubles: bool = False,
zeros: bool = False,
regex_pattern: Optional[str] = None,
contract: bool = False,
threads: int = 1,
count: int = 1,
callback: Optional[callable] = None
) -> list[VanityResult]:
"""Generate vanity addresses matching the criteria."""
results = []
for i in range(count):
start_time = time.time()
deployer_address = None
if threads == 1:
result_tuple = mine_vanity_single(
prefix, suffix, contains, case_sensitive,
letters_only, numbers_only, mirror,
leading, leading_count, doubles, zeros, regex_pattern,
contract, 0
)
if contract:
address, private_key, attempts, deployer_address = result_tuple
else:
address, private_key, attempts = result_tuple
else:
with ProcessPoolExecutor(max_workers=threads) as executor:
futures = [
executor.submit(
worker_mine_vanity,
j, prefix, suffix, contains, case_sensitive,
letters_only, numbers_only, mirror,
leading, leading_count, doubles, zeros, regex_pattern,
contract
)
for j in range(threads)
]
for future in as_completed(futures):
result_tuple = future.result()
if contract:
address, private_key, attempts, deployer_address = result_tuple
else:
address, private_key, attempts = result_tuple
for f in futures:
f.cancel()
break
elapsed = time.time() - start_time
result = VanityResult(
address=address,
private_key=private_key,
attempts=attempts,
time_seconds=elapsed
)
# Store deployer address in derivation_path field for contract mode
if contract and deployer_address:
result.derivation_path = f"deployer:{deployer_address}"
results.append(result)
if callback:
callback(result, i + 1, count)
return results
# ============================================================================
# Utility Functions
# ============================================================================
def estimate_difficulty(
prefix: Optional[str] = None,
suffix: Optional[str] = None,
contains: Optional[str] = None,
case_sensitive: bool = False
) -> int:
"""Estimate attempts needed to find a vanity address."""
total_chars = len(prefix or '') + len(suffix or '') + len(contains or '')
if case_sensitive:
# Checksum makes it harder (roughly 22 possible chars per position)
return int(22 ** total_chars)
else:
# 16 possible hex characters
return 16 ** total_chars
def format_duration(seconds: float) -> str:
"""Format duration in human-readable form."""
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
return f"{seconds / 60:.1f}m"
elif seconds < 86400:
return f"{seconds / 3600:.1f}h"
else:
return f"{seconds / 86400:.1f}d"
def format_number(n: int) -> str:
"""Format number with commas."""
return f"{n:,}"
# ============================================================================
# CLI Commands
# ============================================================================
def cmd_generate(args):
"""Generate a new wallet."""
if args.mnemonic:
result = create_wallet_with_mnemonic(
num_words=args.words,
language=args.language,
passphrase=args.passphrase or "",
derivation_path=args.path or ETHEREUM_DEFAULT_PATH
)
else:
result = create_wallet()
print(f"Address: {result.address}")
print(f"Private Key: {result.private_key}")
if result.mnemonic:
print(f"Mnemonic: {result.mnemonic}")
print(f"Path: {result.derivation_path}")
if args.output:
with open(args.output, 'w') as f:
json.dump({
"address": result.address,
"private_key": result.private_key,
"mnemonic": result.mnemonic,
"derivation_path": result.derivation_path
}, f, indent=2)
print(f"\nSaved to: {args.output}")
def cmd_restore(args):
"""Restore wallet from mnemonic or private key."""
if args.mnemonic:
mnemonic = ' '.join(args.mnemonic)
result = restore_from_mnemonic(
mnemonic=mnemonic,
passphrase=args.passphrase or "",
derivation_path=args.path or ETHEREUM_DEFAULT_PATH
)
print(f"Address: {result.address}")
print(f"Private Key: {result.private_key}")
print(f"Path: {result.derivation_path}")
elif args.key:
result = restore_from_private_key(args.key)
print(f"Address: {result.address}")
print(f"Private Key: {result.private_key}")
else:
print("Error: Provide --mnemonic or --key")
sys.exit(1)
def cmd_derive(args):
"""Derive multiple accounts from mnemonic."""
mnemonic = ' '.join(args.mnemonic)
accounts = derive_multiple_accounts(
mnemonic=mnemonic,
count=args.count,
passphrase=args.passphrase or "",
base_path=args.base_path or "m/44'/60'/0'/0"
)
print(f"Derived {len(accounts)} accounts:\n")
for i, acc in enumerate(accounts):
print(f"[{i}] {acc.address}")
if args.verbose:
print(f" Key: {acc.private_key}")
print(f" Path: {acc.derivation_path}")
print()
def cmd_vanity(args):
"""Generate vanity address."""
prefix = args.prefix
suffix = args.suffix
contains = args.contains
leading = args.leading
leading_count = args.leading_count if hasattr(args, 'leading_count') else 0
doubles = getattr(args, 'doubles', False)
zeros = getattr(args, 'zeros', False)
regex_pattern = getattr(args, 'regex', None)
contract = getattr(args, 'contract', False)
# Validate inputs
if not any([prefix, suffix, contains, args.letters, args.numbers, args.mirror,
leading, doubles, zeros, regex_pattern]):
print("Error: Specify at least one criteria")
print(" Options: --prefix, --suffix, --contains, --letters, --numbers,")
print(" --mirror, --leading, --doubles, --zeros, --regex")
sys.exit(1)
if prefix and not is_valid_hex_pattern(prefix):
print(f"Error: Invalid prefix '{prefix}'. Use only hex characters (0-9, a-f)")
sys.exit(1)
if suffix and not is_valid_hex_pattern(suffix):
print(f"Error: Invalid suffix '{suffix}'. Use only hex characters (0-9, a-f)")
sys.exit(1)
if contains and not is_valid_hex_pattern(contains):
print(f"Error: Invalid contains pattern '{contains}'. Use only hex characters (0-9, a-f)")
sys.exit(1)
if leading and not is_valid_hex_pattern(leading):
print(f"Error: Invalid leading character '{leading}'. Use only hex characters (0-9, a-f)")
sys.exit(1)
if leading and len(leading) != 1:
print("Error: --leading requires a single hex character")
sys.exit(1)
if regex_pattern:
try:
re.compile(regex_pattern)
except re.error as e:
print(f"Error: Invalid regex pattern: {e}")
sys.exit(1)
# Estimate difficulty
difficulty = estimate_difficulty(prefix, suffix, contains, args.case_sensitive)
if leading and leading_count:
difficulty = max(difficulty, 16 ** leading_count)
if doubles:
difficulty = max(difficulty, 16 ** 4) # At least 2 double pairs
if zeros:
difficulty = max(difficulty, 100000) # Rough estimate for 8+ zeros
if not args.quiet:
print("=" * 60)
print("Ethereum Vanity Address Generator")
print("=" * 60)
print(f"Target: {'Contract' if contract else 'Account'} address")
print(f"Prefix: {prefix or '(none)'}")
print(f"Suffix: {suffix or '(none)'}")
print(f"Contains: {contains or '(none)'}")
if leading: