bitmerchant
bitmerchant copied to clipboard
Function to go from a raw public key to an extended public key?
Hey, I'm looking to deterministically generate an extended public key from a raw hex public key.
My method right now is to serialize the xpub from the public key along with a chain code of all zeros.
I'm using the bip32_serialize
function found here:
https://github.com/vbuterin/pybitcointools/blob/master/bitcoin/deterministic.py
Any other suggestions? Is there a function for this in this library?
Do you know if any issues would arise from using a simple chain code? Is there another way to derive such a chain code?
Thanks!
I'm not quite sure I understand what you're trying to accomplish. Do you have control of the private key for the given public key?
Here's a rough example of how you might do this:
In [1]: from bitmerchant.wallet import keys
In [2]: from bitmerchant.wallet import bip32
In [3]: w = bip32.Wallet.new_random_wallet()
In [4]: pubk = w.public_key
In [5]: pubk.get_key()
Out[5]: '046ab4c5639e7fc7bcf025ebf6b95e8f4a633a3951dd5b51901d8b040483e0c5528de00fb909af3f0845022c68f9c587ad4dd79e06539fe6611f4be4bb8b560fcd'
In [6]: # Assuming you're starting from a public key like the above, you can load it:
In [7]: pubk2 = keys.PublicKey.from_hex_key('046ab4c5639e7fc7bcf025ebf6b95e8f4a633a3951dd5b51901d8b040483e0c5528de00fb909af3f0845022c68f9c587ad4dd79e06539fe6611f4be4bb8b560fcd')
In [8]: pubk2 == pubk
Out[8]: True
In [9]: bw = bip32.Wallet(chain_code=0, public_key=pubk2)
In [10]: bw.get_child(0, is_prime=False)
Out[10]: <bitmerchant.wallet.bip32.Wallet at 0x1047dce10>
In [11]: bw.get_child(0, is_prime=False).get_public_key_hex()
Out[11]: '03a015237cb4beb44cebe8bebcc8f1ecd416fa1b255187251c7ef4a32b6c6afab2'
In [12]: bw.get_public_key_hex()
Out[12]: '036ab4c5639e7fc7bcf025ebf6b95e8f4a633a3951dd5b51901d8b040483e0c552'
So this turns a regular public key into a bip32-compatible extended public key. But I'm not sure why you'd want to do this rather than just generating a new private key for a new wallet.
Keep in mind that if you don't control the private key for the pubkey you import then you'll be at risk of having the coins in all child wallets taken by whoever does control the private key.
Also note that initializing the chain_code
to 0 is probably not a secure choice (and, if any attacker knew that you did this, would make it easier for them). I don't have enough knowledge to judge this, though.