How can I import a Bitcoin paper wallet key into a bitcoinlib wallet?

1.6k Views Asked by At

I tried the following, which gives me the correct address for the private key, but I can't seem to import this and use it from a wallet.

>>> from bitcoinlib.wallets import HDWallet
>>> from bitcoinlib.keys import Key
>>> k = Key(import_key=pkstring, is_private=True)
>>> print(k.address())
1BZAHUFU5vgmtiwPnD1HLPiWNoD9tejndt
>>> w = HDWallet.create('Wallet')
>>> w.import_key(k)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/bitcoinlib/wallets.py", line 1381, in import_key
    network = check_network_and_key(key, default_network=self.network.name)
  File "/usr/local/lib/python3.7/site-packages/bitcoinlib/keys.py", line 89, in check_network_and_key
    kf = get_key_format(key)
  File "/usr/local/lib/python3.7/site-packages/bitcoinlib/keys.py", line 148, in get_key_format
    elif len(key) == 130 and key[:2] == '04' and not isprivate:
TypeError: object of type 'Key' has no len()

I think it may have something to do with the difference between a Key object and a HDKey object. I need to import an ordinary key.

1

There are 1 best solutions below

0
On

Your code should work in the latest version of bitcoinlib.

You could also import the key directly in the wallet without creating a Key object first:

 w = HDWallet.create('Wallet')
 w.import_key(pkstring)

Or just create a wallet with a single key from your key string:

 w = HDWallet.create('Wallet2', keys=pkstring, scheme='single')