I’m writing a Python program to reproduce wallet addresses from mnemonics, which sounds simple, but I can’t get an old Electrum (Pre-V2) address that matches the address I get from the official GUI wallet.
All the information is useful as it seems that you can’t find too much information about Electrum address generation before V2.
Does anyone have insight into what I’m doing wrong?
import hashlib, ecdsa, base58
def load_wordlist(filename):
with open(filename, 'r') as f:
return (word.strip() for word in f.readlines())
# Decoding mnemonic into Electrum v1 seed (entropy)
def mnemonic_to_entropy(mnemonic, wordlist):
words = mnemonic.split()
entropy_bits=""
for word in words:
index = wordlist.index(word)
entropy_bits += bin(index)(2:).zfill(11)
# Pading entropy_bits with zeros to make it byte-aligned
extra_bits = len(entropy_bits) % 8
if extra_bits != 0:
entropy_bits = entropy_bits.ljust(len(entropy_bits) + (8 - extra_bits), '0')
entropy_hex = hex(int(entropy_bits, 2))(2:).zfill(len(entropy_bits) // 4)
return bytes.fromhex(entropy_hex)
# Generating private key from entropy + index
def electrum_v1_privkey(entropy, index):
data = entropy + index.to_bytes(4, 'little')
return hashlib.sha256(data).digest()
# Converting private key to compressed public key
def privkey_to_pubkey(privkey):
sk = ecdsa.SigningKey.from_string(privkey, curve=ecdsa.SECP256k1)
vk = sk.verifying_key
prefix = b'\x02' if vk.to_string()(-1) % 2 == 0 else b'\x03'
return prefix + vk.to_string()(:32)
# Converting public key to address
def pubkey_to_address(pubkey):
sha256_pubkey = hashlib.sha256(pubkey).digest()
ripemd160_pubkey = hashlib.new('ripemd160', sha256_pubkey).digest()
prefixed_pubkey = b'\x00' + ripemd160_pubkey
checksum = hashlib.sha256(hashlib.sha256(prefixed_pubkey).digest()).digest()(:4)
return base58.b58encode(prefixed_pubkey + checksum).decode()
mnemonic = "sample mnemonic"
wordlist = load_wordlist('old_electrum_wordlist')
entropy = mnemonic_to_entropy(mnemonic, wordlist)
# Generating first 5 addresses
for index in range(5):
privkey = electrum_v1_privkey(entropy, index)
pubkey = privkey_to_pubkey(privkey)
address = pubkey_to_address(pubkey)
print(f'Address {index}: {address}')
Discover more from Earlybirds Invest
Subscribe to get the latest posts sent to your email.