Skip to main content

Implementation of BIP39, BIP32, BIP44, BIP49 and BIP84 for Bitcoin wallet seed, keys and address generation

Project description

BIP utility library

Introduction

This package contains an implementation of some BIP (Bitcoin Improvement Proposal) specifications, allowing to:

  • Generate a mnemonic string from a random entropy
  • Generate a secure seed from the mnemonic string
  • Use the seed to generate the master key of the wallet and derive the children keys, including address encoding

The implemented BIP specifications are the following:

  • BIP-0039 for mnemonic and seed generation
  • BIP-0032 for master key generation (from the secure seed) and children keys derivation
  • BIP-0044, BIP-0049 and BIP-0084 for the hierarchy of deterministic wallets, based on BIP-0032 algorithms

In addition to this, the package allows to:

  • Generate P2PKH addresses (included in BIP-0044)
  • Generate P2SH addresses (included in BIP-0049)
  • Generate P2WPKH addresses (included in BIP-0084)
  • Encode/Decode WIF
  • Encode/Decode base58
  • Encode/Decode bech32

Install the package

The package requires Python 3, it is not compatible with Python 2. To install it:

  • Using setuptools:

      python setup.py install
    
  • Using pip:

      pip install bip_utils
    

To run the unit tests:

python setup.py test

BIP-0039 library

Mnemonic generation

A mnemonic string can be generated by specifying the words number (in this case a random entropy will be used) or directly the entropy bytes. Supported words number: 12, 15, 18, 21, 24 Supported entropy bits: 128, 160, 192, 224, 256

NOTE: only the English words list is supported.

Code example

from bip_utils import Bip39MnemonicGenerator

# Generate a random mnemonic string of 15 words
mnemonic = Bip39MnemonicGenerator.FromWordsNumber(15)

# Generate the mnemonic string from entropy bytes:
entropy_bytes_hex = b"00000000000000000000000000000000"
mnemonic = Bip39MnemonicGenerator.FromEntropy(binascii.unhexlify(entropy_bytes_hex))

Mnemonic validation

A mnemonic string can be validated by verifying its checksum. It is also possible to get back the entropy bytes from a mnemonic.

Code example

 from bip_utils import Bip39MnemonicValidator

 # Get back the original entropy from a mnemonic string
 entropy_bytes = Bip39MnemonicValidator(mnemonic).GetEntropy()
 # Validate a mnemonic string by verifying its checksum
 is_valid = Bip39MnemonicValidator(mnemonic).Validate()

Seed generation

A secure 64-byte seed is generated from a mnemonic and can be protected by a passphrase. This seed can be used to contruct a Bip class.

Code example

from bip_utils import Bip39SeedGenerator

# If not specified, the passphrase will be empty
passphrase = "my_passphrase"
seed_bytes = Bip39SeedGenerator(mnemonic).Generate(passphrase)

BIP-0032 library

The BIP-0032 library is wrapped inside the BIP-0044, BIP-0049 and BIP-0084 libraries, so there is no need to use it alone unless you need to derive some non-standard paths.

Construction from a seed

The class is constructed from a seed. The seed can be specified manually or generated by Bip39SeedGenerator. The constructed class is the master path, i.e. m, so printing the private key will result in printing the master key.

NOTE: construction from a key is not currently supported

Code example

from bip_utils import Bip32

# Seed bytes
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4")
# Path returned: m
bip32_ctx = Bip32.FromSeed(seed_bytes)
# Print master key in extended format
print(bip32_ctx.ExtendedPrivateKey())

Keys derivation

Each time a key is derived, a new instance of the Bip32 class is returned. This allows to chain the methods call or save a specific key pair for future derivation. The Bip32.HardenIndex method can be used to make an index hardened.

Code example

from bip_utils import Bip32

# Path: m
bip32_ctx = Bip32.FromSeed(seed_bytes)
# Derive path: m/0'/1'/2
bip32_ctx = bip32_ctx.ChildKey(Bip32.HardenIndex(0)) \
                     .ChildKey(Bip32.HardenIndex(1)) \
                     .ChildKey(2)
# Print keys in extended format
print(bip32_ctx.ExtendedPrivateKey())
print(bip32_ctx.ExtendedPublicKey())

# Alternative: derive from path
bip32_ctx = Bip32.FromSeed(seed_bytes)
bip32_ctx = bip32_ctx.DerivePath("0'/1'/2")

# Alternative: create directly from seed and path
bip32_ctx = Bip32.FromSeed(seed_bytes, "m/0'/1'/2")

Parse path

The Bip32 module allows also to parse paths by returning the list of indexes in the path.
In case of error, an empty list is returned.

Code example

from bip_utils import PathParser

# Print: [0, 2147483648, 2147483649, 2]
print(PathParser.Parse("m/0'/1'/2"))
# Same but skipping the master. Print: [2147483648, 2147483649, 2]
print(PathParser.Parse("0'/1'/2", True))
# Error path: empty list returned. Print: []
print(PathParser.Parse("m/0'/abc/2"))

Bip-0044, BIP-0049, BIP-0084 libraries

These libraries derives all from the same base class, so they are used exactly in the same way. Therefore, the following code examples can be used with the Bip44, Bip49 or Bip84 class.

Construction from a seed

A Bip class is constructed from a seed, like Bip32. The seed can be specified manually or generated by Bip39SeedGenerator.

NOTE: construction from a key is not currently supported

Code example

from bip_utils import Bip44

# Seed bytes
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4")
# Path returned: m
# In case it's a test net, pass True as second parameter
bip44_ctx = Bip44.FromSeed(seed_bytes)

Keys derivation

Like Bip32, each time a key is derived a new instance of the Bip class is returned. The keys must be derived in the order specified by BIP-0044:

m / purpose' / coin_type' / account' / change / address_index

using the correspondent methods. If keys are derived in the wrong order, a RuntimeError will be raised. The private and public extended keys can be printed at any derivation level.

NOTE: only Bitcoin and Bitcoin testnet are supported, but it can be extended with other coins.

Code example

from bip_utils import Bip44, Bip44Coins, Bip44Chains

# Create from seed
bip44_mst = Bip44.FromSeed(seed_bytes)
# Print master key in extended format (pass False as parameter to get the key bytes instead)
print(bip44_mst.PrivateKey())
# Print the master key in WIF
print(bip44_mst.WalletImportFormat())


# Derive account 0 for Bitcoin: m/44'/0'/0'
bip44_acc = bip44_mst.Purpose()                \
                     .Coin(Bip44Coins.BITCOIN) \
                     .Account(0)
# Print keys in extended format
print(bip44_acc.PrivateKey())
print(bip44_acc.PublicKey())

# Derive the external chain: m/44'/0'/0'/0
bip44_chain = bip44_acc.Chain(Bip44Chains.CHAIN_EXT)
# Print again keys in extended format
print(bip44_chain.PrivateKey())
print(bip44_chain.PublicKey())

# Derive the first 20 address of the external chain: m/44'/0'/0'/0/i
for i in range(20):
    bip44_addr = bip44_chain.AddressIndex(i)
    # Print extended keys and address
    print(bip44_addr.PrivateKey())
    print(bip44_addr.PublicKey())
    print(bip44_addr.Address())

In the example above, Bip44 can be substitued with Bip49 or Bip84 without changing the code.

WIF

This library is used internally by the other libraries, but it's available also for external use.

Code example

from bip_utils import WifDecoder, WifEncoder

key_bytes = binascii.unhexlify(b'1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67')

# Encode
enc = WifEncoder.Encode(key_bytes)
# Decode
dec = WifDecoder.Decode(enc)

Base58

This library is used internally by the other libraries, but it's available also for external use. It supports both normal encode/decode and check_encode/check_decode.

Code example

from bip_utils import Base58Decoder, Base58Encoder

data_bytes = binascii.unhexlify(b"636363")

# Normal encode
enc     = Base58Encoder.Encode(data_bytes)
# Check encode
chk_enc = Base58Encoder.CheckEncode(data_bytes)

# Normal decode
dec     = Base58Decoder.Decode(enc)
# Check decode, RuntimeError is raised if checksum verification fails
chk_dec = Base58Decoder.CheckDecode(chk_enc)

Bech32

This library is used internally by the other libraries, but it's available also for external use.

Code example

from bip_utils import Bech32Decoder, Bech32Encoder

data_bytes = binascii.unhexlify(b'9c90f934ea51fa0f6504177043e0908da6929983')

# Encode
enc = Bech32Encoder.EncodeAddr("bc", 0, data_bytes)
# Decode
dec = Bech32Decoder.DecodeAddr("bc", enc)

Complete code example

Example from mnemonic generation to wallet addresses.

from bip_utils import Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44, Bip44Coins, Bip44Chains

# Generate random mnemonic
mnemonic = Bip39MnemonicGenerator.FromWordsNumber(12)
print("Mnemonic string: %s" % mnemonic)
# Generate seed from mnemonic
seed_bytes = Bip39SeedGenerator(mnemonic).Generate()

# Generate BIP44 master keys
bip_obj_mst = Bip44.FromSeed(seed_bytes)
# Print master key
print("Master key (bytes): %s" % binascii.hexlify(bip_obj_mst.PrivateKey(False)))
print("Master key (extended): %s" % bip_obj_mst.PrivateKey())
print("Master key (WIF): %s" % bip_obj_mst.WalletImportFormat())

# Generate BIP44 account keys: m/44'/0'/0'
bip_obj_acc = bip_obj_mst.Purpose().Coin(Bip44Coins.BITCOIN).Account(0)
# Generate BIP44 chain keys: m/44'/0'/0'/0
bip_obj_chain = bip_obj_acc.Chain(Bip44Chains.CHAIN_EXT)

# Generate the address pool (first 20 addresses): m/44'/0'/0'/0/i
for i in range(20):
    print("%d. Address public key (extended): %s" % (i, bip_obj_mst.PrivateKey()))
    print("%d. Address private key (extended): %s" % (i, bip_obj_mst.PublicKey()))
    print("%d. Address: %s" % (i, bip_obj_chain.AddressIndex(i).Address()))

License

This software is available under the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for bip-utils, version 0.1.0
Filename, size File type Python version Upload date Hashes
Filename, size bip_utils-0.1.0.tar.gz (30.3 kB) File type Source Python version None Upload date Hashes View
Filename, size bip_utils-0.1.0-py3.8.egg (65.8 kB) File type Egg Python version 3.8 Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page