Derive bitcoin addresses from HD xpub keys

Objectives

we want to

  • generate Bitcoin receiving addresses from an xpub key (so that no secret information needs to be shared)
  • do this independently from a service / API, in python
  • be compatible with https://iancoleman.io/bip39/
  • be compatible with wallet software such as Electrum or blockchain.info so that the received funds can be easily managed

A note in regards to blockchain.info:

  • blockchain.info allows to export the mnemonic and also the xpub key for each wallet account created
  • the xprv key for each account can be derived via https://iancoleman.io/bip39/ by setting the account to {n}, where 0 corresponds to the first blockchain.info account, 1 to the second, and so on.
  • this xprv can then be imported into Electrum

Solution

https://github.com/primal100/pybitcointools/ appears to be the continuation of Vitalik Buterin’s abandoned https://github.com/vbuterin/pybitcointools.

Then:

from cryptos import *

words = 'word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12'
coin = Bitcoin()
private_wallet = coin.wallet(words)

xpub = private_wallet.keystore.xpub

# this is where you would start with an address calculation feature in an insecure environment like a web server
pub_keystore = keystore.from_xpub(xpub, coin, "p2pkh")
pub_wallet = wallet.HDWallet(pub_keystore)
print(pub_wallet.new_receiving_addresses(num=3))