4

I'm trying to write a Python script to derive a public key from a Seed Phrase using Python.

My current code is the following.

def generate_solana_address_from_seed(seed_phrase):
    seed_phrase_str = ' '.join(seed_phrase)
    mnemo = Mnemonic("english")
    seed = mnemo.to_seed(seed_phrase_str)

    root = bip32utils.BIP32Key.fromEntropy(seed)
    child = (root.ChildKey(44 + bip32utils.BIP32_HARDEN)
             .ChildKey(501 + bip32utils.BIP32_HARDEN)
             .ChildKey(0 + bip32utils.BIP32_HARDEN)
             .ChildKey(0)
             .ChildKey(0))

    private_key = bytes(child.PrivateKey()) + bytes(child.PublicKey())

    keypair = Keypair.from_bytes(private_key)

    return str(keypair.pubkey())


test_address = generate_solana_address_from_seed(seed_phrase)
if test_address == known_public_address:
    print("\n\tMatch found")
else:
    print("No match")

When I run it, I get the following error:

Traceback (most recent call last):
  File "E:\Solana-Wallet\v3.py", line 40, in <module>
    test_address = generate_solana_address_from_seed(seed_phrase)
  File "E:\Solana-Wallet\v3.py", line 35, in generate_solana_address_from_seed
    keypair = Keypair.from_bytes(private_key)
ValueError: expected a sequence of length 64 (got 65)

1 Answer 1

6

Use Keypair.from_seed_phrase_and_passphrase:

from pybip39 import Mnemonic
from solders.keypair import Keypair
mnemonic = Mnemonic()
passphrase = "42"
keypair = Keypair.from_seed_phrase_and_passphrase(mnemonic.phrase, passphrase)
public_key = keypair.pubkey()

Edit: in your comment you mention bip32 keypairs. This is how you do those:

from solders.keypair import Keypair
from solders.pubkey import Pubkey
seed_bytes = bytes([0] * 64)
account_index = 0
derivation_path = f"m/44'/501'/0'/{account_index}'"
from_seed = Keypair.from_seed_and_derivation_path(seed_bytes, derivation_path)
1
  • what is phrase or passphrase in this context? and what about bip32 having infinite addresses? Jan 13 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.