bitcoinlib.keys module

class bitcoinlib.keys.Address(data='', hashed_data='', network='bitcoin', prefix=None, script_type=None, encoding=None, witness_type=None, network_overrides=None)[source]

Bases: object

Class to store, convert and analyse various address types as representation of public keys or scripts hashes

Initialize an Address object. Specify a public key, redeemscript or a hash.

Parameters:
  • data (str, bytes) – Public key, redeem script or other type of script.
  • hashed_data (str, bytes) – Hash of a public key or script. Will be generated if ‘data’ parameter is provided
  • network (str, Network) – Bitcoin, testnet, litecoin or other network
  • prefix (str, bytes) – Address prefix. Use default network / script_type prefix if not provided
  • script_type (str) – Type of script, i.e. p2sh or p2pkh.
  • encoding (str) – Address encoding. Default is base58 encoding, for native segwit addresses specify bech32 encoding
  • witness_type (str) – Specify ‘legacy’, ‘segwit’ or ‘p2sh-segwit’. Legacy for old-style bitcoin addresses, segwit for native segwit addresses and p2sh-segwit for segwit embedded in a p2sh script. Leave empty to derive automatically from script type if possible
  • network_overrides (dict) – Override network settings for specific prefixes, i.e.: {“prefix_address_p2sh”: “32”}. Used by settings in providers.json
classmethod import_address(address, network=None, network_overrides=None)[source]

Import an address to the Address class. Specify network if available, otherwise it will be derived form the address.

Parameters:
  • address (str) – Address to import
  • network (str) – Bitcoin, testnet, litecoin or other network
  • network_overrides (dict) – Override network settings for specific prefixes, i.e.: {“prefix_address_p2sh”: “32”}. Used by settings in providers.json
Return Address:
with_prefix(prefix)[source]

Convert address using another prefix

Parameters:prefix (str, bytes) – Address prefix
Return str:Converted address
exception bitcoinlib.keys.BKeyError(msg='')[source]

Bases: Exception

Handle Key class Exceptions

class bitcoinlib.keys.HDKey(import_key=None, key=None, chain=None, depth=0, parent_fingerprint=b'x00x00x00x00', child_index=0, isprivate=True, network=None, key_type='bip32', passphrase='', compressed=True)[source]

Bases: object

Class for Hierarchical Deterministic keys as defined in BIP0032

Besides a private or public key a HD Key has a chain code, allowing to create a structure of related keys.

The structure and key-path are defined in BIP0043 and BIP0044.

Hierarchical Deterministic Key class init function. If no import_key is specified a key will be generated with systems cryptographically random function. Import key can be any format normal or HD key (extended key) accepted by get_key_format. If a normal key with no chain part is provided, an chain with only 32 0-bytes will be used.

Parameters:
  • import_key (str, bytes, int, bytearray) – HD Key to import in WIF format or as byte with key (32 bytes) and chain (32 bytes)
  • key (bytes) – Private or public key (length 32)
  • chain (bytes) – A chain code (length 32)
  • depth (int) – Level of depth in BIP32 key path
  • parent_fingerprint (bytes) – 4-byte fingerprint of parent
  • child_index (int) – Index number of child as integer
  • isprivate (bool) – True for private, False for public key. Default is True
  • network (str, Network) – Network name. Derived from import_key if possible
  • key_type (str) – HD BIP32 or normal Private Key. Default is ‘bip32’
  • passphrase (str) – Optional passphrase if imported key is password protected
  • compressed (bool) – Is key compressed or not, default is True
Return HDKey:
account_key(account_id=0, purpose=44, set_network=None)[source]

Derive account BIP44 key for current master key

Parameters:
  • account_id (int) – Account ID. Leave empty for account 0
  • purpose (int) – BIP standard used, i.e. 44 for default, 45 for multisig
  • set_network (str) – Derive account key for different network. Please note this calls the network_change method and changes the network for current key!
Return HDKey:
account_multisig_key(account_id=0, purpose=45, set_network=None)[source]

Derives a multisig account key according to BIP44/45 definition. Wrapper for the ‘account_key’ method.

Parameters:
  • account_id (int) – Account ID. Leave empty for account 0
  • purpose (int) – BIP standard used, leave empty for 45 which is the default for multisig
  • set_network (str) – Derive account key for different network. Please note this calls the network_change method and changes the network for current key!
Return HDKey:
child_private(index=0, hardened=False, network=None)[source]

Use Child Key Derivation (CDK) to derive child private key of current HD Key object.

Parameters:
  • index (int) – Key index number
  • hardened (bool) – Specify if key must be hardened (True) or normal (False)
  • network (str) – Network name.
Return HDKey:

HD Key class object

child_public(index=0, network=None)[source]

Use Child Key Derivation to derive child public key of current HD Key object.

Parameters:
  • index (int) – Key index number
  • network (str) – Network name.
Return HDKey:

HD Key class object

dict()[source]

Returns key information as dictionary

fingerprint()[source]

Get fingerprint of keys public part

Return bytes:
static from_passphrase(password='', network='bitcoin')[source]

Create key from Mnemonic passphrase

Parameters:
  • passphrase (str) – Mnemonic passphrase, list of words as string seperated with a space character
  • password (str) – Password to protect passphrase
  • network (str, Network) – Network to use
Return HDKey:
static from_seed(key_type='bip32', network='bitcoin')[source]

Used by class init function, import key from seed

Parameters:
  • import_seed (str, bytes) – Private key seed as bytes or hexstring
  • key_type (str) – Specify type of key, default is BIP32
  • network (str, Network) – Network to use
Return HDKey:
info()[source]

Prints key information to standard output

network_change(new_network)[source]

Change network for current key

Parameters:new_network (str) – Name of new network
Return bool:True
public()[source]

Public version of current private key.

Return HDKey:
subkey_for_path(path, network=None)[source]

Determine subkey for HD Key for given path. Path format: m / purpose’ / coin_type’ / account’ / change / address_index Example: m/44’/0’/0’/0/2 See BIP0044 bitcoin proposal for more explanation.

Parameters:
  • path (str) – BIP0044 key path
  • network (str) – Network name.
Return HDKey:

HD Key class object of subkey

wif(public=None, child_index=None, prefix=None)[source]

Get Extended WIF of current key

Parameters:
  • public (bool) – Return public key?
  • child_index (int) – Change child index of output WIF key
  • prefix (str, bytes) – Specify version prefix in hexstring or bytes. Normally doesn’t need to be specified, method uses default prefix from network settings
Return str:

Base58 encoded WIF key

wif_public(prefix=None)[source]

Get Extended WIF public key

Parameters:prefix (str, bytes) – Specify version prefix in hexstring or bytes. Normally doesn’t need to be specified, method uses default prefix from network settings
Return str:Base58 encoded WIF key
class bitcoinlib.keys.Key(import_key=None, network=None, compressed=True, passphrase='', is_private=None)[source]

Bases: object

Class to generate, import and convert public cryptographic key pairs used for bitcoin.

If no key is specified when creating class a cryptographically secure Private Key is generated using the os.urandom() function.

Initialize a Key object. Import key can be in WIF, bytes, hexstring, etc. If a private key is imported a public key will be derived. If a public is imported the private key data will be empty.

Both compressed and uncompressed key version is available, the Key.compressed boolean attribute tells if the original imported key was compressed or not.

Parameters:
  • import_key (str, int, bytes, bytearray) – If specified import given private or public key. If not specified a new private key is generated.
  • network (str, Network) – Bitcoin, testnet, litecoin or other network
  • compressed (bool) – Is key compressed or not, default is True
  • passphrase (str) – Optional passphrase if imported key is password protected
  • is_private (bool) – Specify if imported key is private or public. Default is None: derive from provided key
Returns:

Key object

address(compressed=None, prefix=None, script_type=None, encoding='base58')[source]

Get address derived from public key

Parameters:
  • compressed (bool) – Always return compressed address
  • prefix (str, bytes) – Specify versionbyte prefix in hexstring or bytes. Normally doesn’t need to be specified, method uses default prefix from network settings
  • script_type (str) – Type of script, i.e. p2sh or p2pkh.
  • encoding (str) – Address encoding. Default is base58 encoding, for segwit you can specify bech32 encoding
Return str:

Base58 encoded address

address_uncompressed(prefix=None)[source]

Get uncompressed address from public key

Parameters:prefix (str, bytes) – Specify versionbyte prefix in hexstring or bytes. Normally doesn’t need to be specified, method uses default prefix from network settings
Return str:Base58 encoded address
bip38_encrypt(passphrase)[source]

BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey. Based on code from https://github.com/nomorecoin/python-bip38-testing

Parameters:passphrase (str) – Required passphrase for encryption
Return str:BIP38 passphrase encrypted private key
hash160()[source]

Get public key in Hash160 format

Return bytes:Hash160 of public key
info()[source]

Prints key information to standard output

public(return_compressed=None)[source]

Get public key

Parameters:return_compressed (bool) – If True always return a compressed version and if False always return uncompressed
Return str:Public key hexstring
public_point()[source]

Get public key point on Elliptic curve

Return tuple:(x, y) point
public_uncompressed()[source]

Get public key, uncompressed version

Return str:Uncompressed public key hexstring
wif(prefix=None)[source]

Get Private Key in Wallet Import Format, steps: # Convert to Binary and add 0x80 hex # Calculate Double SHA256 and add as checksum to end of key

Parameters:prefix (str, bytes) – Specify versionbyte prefix in hexstring or bytes. Normally doesn’t need to be specified, method uses default prefix from network settings
Return str:Base58Check encoded Private Key WIF
bitcoinlib.keys.check_network_and_key(key, network=None, kf_networks=None, default_network='bitcoin')[source]

Check if given key corresponds with given network and return network if it does. If no network is specified this method tries to extract the network from the key. If no network can be extracted from the key the default network will be returned.

A KeyError will be raised if key does not corresponds with network or if multiple network are found.

Parameters:
  • key (str, int, bytes, bytearray) – Key in any format recognized by get_key_format function
  • network (str) – Optional network. Method raises KeyError if keys belongs to another network
  • kf_networks (list) – Optional list of networks which is returned by get_key_format. If left empty the get_key_format function will be called.
  • default_network (str) – Specify different default network, leave empty for default (bitcoin)
Return str:

Network name

bitcoinlib.keys.deserialize_address(address, encoding=None, network=None)[source]

Deserialize address. Calculate public key hash and try to determine script type and network.

The ‘network’ dictionary item with contain the network with highest priority if multiple networks are found. Same applies for the script type.

Specify the network argument if known to avoid unexpected results.

If more networks and or script types are found you can find these in the ‘networks’ field.

Parameters:
  • address (str) – A base58 or bech32 encoded address
  • encoding (str) – Encoding scheme used for address encoding. Attempts to guess encoding if not specified.
  • network (str) – Bitcoin, testnet, litecoin or other network
Return dict:

with information about this address

bitcoinlib.keys.ec_point(p)[source]

Method for elliptic curve multiplication

Parameters:p – A point on the elliptic curve
Return Point:Point multiplied by generator G
bitcoinlib.keys.get_key_format(key, isprivate=None)[source]

Determines the type (private or public), format and network key.

This method does not validate if a key is valid.

Parameters:
  • key (str, int, bytes, bytearray) – Any private or public key
  • isprivate (bool) – Is key private or not?
Return dict:

Dictionary with format, network and isprivate