I am trying to derive addresses from a master public key (aka extended public key) in python. I don't fully understand the math behind the key derivation, but have been able to decode the master public key from base58 to bin and encode the bin to hex. This is now where I am stuck at, I have all the info from the hex including the chain code, but am not sure what to do with the chain code hex. I have tried many different versions of encoded/decoded master public keys and some of them generated addresses, but the addresses were not properly derived from the original master public key.

Master Public Key (base58): ypub6WpT17zUsUE5oPuekrZEHkzk4bF4j9S3CM8VMx3BpiQwxxWMS914zVWEyMRBAJHQiQZRbtX4VLDYo4Y8WQZXCgSkzwEAJ73ToepntwymZ8g

Master Public Key (hex): 049d7cb2032d8b913e8000000059ddf15a4f066a86e3f9035060be5d13fba7fc94ae6ad525b626cb53175deef602e555ecef37d396bf7d641f2d42feb015c90d3d8a690832dc6e118fedecb8789cf58fc09d

I have been using bitaps.com/bip32 to compare if I was ever able to successfully derive the first address in index 0 with BIP49 selected. All of the values on bitaps.com/bip32 correlates with characters in the master public key hex above.

This is the correct public key which is generated for the address in index 0: 02b1fb3ab28ba345fa21521dcf0c09e6f2e8edae0113d562da61ae6dadd6dc5187

How would I be able to use the chain code hex from the master public key hex to generate the public key above for the derivation path m/49'/0'/0'/0/0 and then use that public key to generate the corresponding address in python?

  • @MikeD That looks promising, but needs to be modified to work with BIP49. The script which is used in that code sample is P2PKH, I am trying to use P2WPKH-P2SH script.
    – amint
    Aug 14 '21 at 16:14
  • No modification is needed, I can reproduce the test vector from bip49 with this command (Xprv.from_mnemonic('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about')/49./1./0./0/0).key.to_public().to_address('P2WPKH-P2SH') prints '2Mww8dCYPUpKHofjgcXcBCEGmniw9CoaiD2'
    – Mike D
    Aug 14 '21 at 17:02
  • @MikeD Is it possible to get from master public key instead of mnemonic? Using Electrum and want to derive the keys from the master public key in python.
    – amint
    Aug 14 '21 at 17:26
  • You can’t derive a hardened path from an extended public key so m/49’/0’/0’/0 is not possible
    – Mike D
    Aug 14 '21 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.