ebellocchia / bip_utils

Generation of mnemonics, seeds, private/public keys and addresses for different types of cryptocurrencies
MIT License
297 stars 83 forks source link

Need help #4

Closed stdusr closed 3 years ago

stdusr commented 3 years ago

Good day, would you mind providing me a small example how to derive the first 20 BTC and ETH addresses(used to receive actual funds) from a "normal" private key? I see, you provided many examples how to do it using mnemonic, seed or private extended key. But I can't wrap my head around, how to do it using private key, generated by various software wallets(Electrum, Exodus, etc.) For example, I have a private key: KzBfG4pV3xjD4aNsxggFmtY6dLqae55CKEFiU2dDztpxtyotdjib How do I derive the first BTC address from it, which should be: 129hrvLEK84djejoW4hMEC48gEuYSHMLiD (Ideally, it should support all BTC address formats, P2PKH, P2SH, Bech32) :)

I'm not lazy, just all the crypto and math stuff is beyond my limits of comprehension. Willing to make a donation :)

ebellocchia commented 3 years ago

Hello, don't worry, what you want to do is actually not so easy because you are importing a private key related to an address, so it requires a little bit of playing around with the classes. Anyway, you can get the address as follows:

from bip_utils import Bip32, Bip44, Bip44Coins, WifDecoder
from bip_utils.bip.bip44_base import Bip44Levels

wif = "KzBfG4pV3xjD4aNsxggFmtY6dLqae55CKEFiU2dDztpxtyotdjib"

# Decode private key
priv_key_bytes = WifDecoder.Decode(wif)
# Create Bip44 object (substitute with Bip49 or Bip84 for other address types)
bip44_addr = Bip44(Bip32(priv_key_bytes, b"", Bip44Levels.ADDRESS_INDEX), Bip44Coins.BITCOIN)
# Print address and keys
print("Address:", bip44_addr.PublicKey().ToAddress())
print("Priv key:", bip44_addr.PrivateKey().Raw().ToHex())
print("Pub key:", bip44_addr.PublicKey().RawCompressed().ToHex())

That will correctly print 129hrvLEK84djejoW4hMEC48gEuYSHMLiD as address. Please note that you cannot generate 20 addresses from this private key, because the key is only related to 1 address (you need the parent private key for generating all addresses).