bitcoinlib.keys module

class bitcoinlib.keys.Address(data='', hashed_data='', prefix=None, script_type=None, compressed=None, encoding=None, witness_type=None, witver=0, depth=None, change=None, address_index=None, network='bitcoin', 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.

>>> addr = Address('03715219f51a2681b7642d1e0e35f61e5288ff59b87d275be9eaf1a5f481dcdeb6', encoding='bech32', script_type='p2wsh')
>>> addr.address
'bc1qaehsuffn0stxmugx3z69z9hm6gnjd9qzeqlfv92cpf5adw63x4tsfl7vwl'
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

  • 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.

  • witver (int) – Witness version. Used for p2tr addresses

  • 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 (str, Network) – 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

as_dict()[source]

Get current Address class as dictionary. Byte values are represented by hexadecimal strings

Return dict:

as_json()[source]

Get current key as json formatted string

Return str:

property data
property hashed_data
classmethod parse(address, compressed=None, encoding=None, depth=None, change=None, address_index=None, network=None, network_overrides=None)[source]

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

>>> addr = Address.parse('bc1qyftqrh3hm2yapnhh0ukaht83d02a7pda8l5uhkxk9ftzqsmyu7pst6rke3')
>>> addr.as_dict()
{'network': 'bitcoin', '_data': None, 'script_type': 'p2wsh', 'encoding': 'bech32', 'compressed': None, 'witver': 0, 'witness_type': 'segwit', 'depth': None, 'change': None, 'address_index': None, 'prefix': 'bc', 'redeemscript': '', '_hashed_data': None, 'address': 'bc1qyftqrh3hm2yapnhh0ukaht83d02a7pda8l5uhkxk9ftzqsmyu7pst6rke3', 'address_orig': 'bc1qyftqrh3hm2yapnhh0ukaht83d02a7pda8l5uhkxk9ftzqsmyu7pst6rke3'}
Parameters:
  • address (str) – Address to import

  • compressed (bool) – Is key compressed or not, default is None

  • encoding (str) – Address encoding. Default is base58 encoding, for native segwit addresses specify bech32 encoding. Leave empty to derive from address

  • depth (int) – Level of depth in BIP32 key path

  • change (int) – Use 0 for normal address/key, and 1 for change address (for returned/change payments)

  • address_index (int) – Index of address. Used in BIP32 key paths

  • network (str) – Specify network filter, i.e.: bitcoin, testnet, litecoin, etc. Wil trigger check if address is valid for this 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'\x00\x00\x00\x00', child_index=0, is_private=None, network=None, key_type='bip32', password='', compressed=True, encoding=None, witness_type=None, multisig=False)[source]

Bases: Key

Class for Hierarchical Deterministic keys as defined in BIP0032

Besides a private or public key a HDKey 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, a chain with only 32 0-bytes will be used.

>>> private_hex = '221ff330268a9bb5549a02c801764cffbc79d5c26f4041b26293a425fd5b557c'
>>> k = HDKey(private_hex)
>>> k
<HDKey(public_hex=0363c152144dcd5253c1216b733fdc6eb8a94ab2cd5caa8ead5e59ab456ff99927, wif_public=zpub6jftahH18ngZw8pNbq6arfqFD7przPySpW3jhhzQiBKYpzJxqwhBEpCk8rh9p7JQ5JrAMu1Pfq1wCXfDfZL8i9zJvxeehCTAAVTev5oZKCn, network=bitcoin)>
Parameters:
  • import_key (str, bytes, int, tuple) – 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

  • is_private (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’

  • password (str) – Optional password if imported key is password protected

  • compressed (bool) – Is key compressed or not, default is True

  • encoding (str) – Encoding used for address, i.e.: base58 or bech32. Default is base58 or derive from witness type

  • witness_type (str) – Witness type used when creating scripts: legacy, p2sh-segwit or segwit.

  • multisig (bool) – Specify if key is part of multisig wallet, used when creating key representations such as WIF and addreses

Return HDKey:

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

Get address derived from public key

>>> wif = 'xpub661MyMwAqRbcFcXi3aM3fVdd42FGDSdufhrr5tdobiPjMrPUykFMTdaFEr7yoy1xxeifDY8kh2k4h9N77MY6rk18nfgg5rPtbFDF2YHzLfA'
>>> k = HDKey.from_wif(wif)
>>> k.address()
'15CacK61qnzJKpSpx9PFiC8X1ajeQxhq8a'
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 or Bech32 encoded address

as_dict(include_private=False)[source]

Get the current HDKey class as a dictionary. Byte values are represented by hexadecimal strings.

Parameters:

include_private (bool) – Include private key information in dictionary

Return collections.OrderedDict:

as_json(include_private=False)[source]

Get the current key as a JSON formatted string

Parameters:

include_private (bool) – Include private key information in dictionary

Return str:

child_private(index=0, hardened=False, network=None)[source]

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

Used by key_for_path() to create key paths, for instance, to use in HD wallets. You can use this method to create your own key structures.

This method create private child keys, use child_public() to create public child keys.

>>> private_hex = 'd02220828cad5e0e0f25057071f4dae9bf38720913e46a596fd7eb8f83ad045d'
>>> k = HDKey(private_hex)
>>> ck = k.child_private(10)
>>> ck.address()
'bc1q5rlenzyn95pt4rur6jcnrgx5s3u6kw0nnwjrtt'
>>> ck.depth
1
>>> ck.child_index
10
Parameters:
  • index (int) – Key index number

  • hardened (bool) – Specify if a 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 a child public key of the current HD Key object.

Used by key_for_path() to create key paths, for instance, to use in HD wallets. You can use this method to create your own key structures.

This method creates public child keys, use child_private() to create private child keys.

>>> private_hex = 'd02220828cad5e0e0f25057071f4dae9bf38720913e46a596fd7eb8f83ad045d'
>>> k = HDKey(private_hex)
>>> ck = k.child_public(15)
>>> ck.address()
'bc1qlzf2a6tskk8g6g55nsda7akmwsevasv5p4muuf'
>>> ck.depth
1
>>> ck.child_index
15
Parameters:
  • index (int) – Key index number

  • network (str) – Network name.

Return HDKey:

HD Key class object

property fingerprint

Get key fingerprint: the last for bytes of the hash160 of this key.

Return bytes:

static from_passphrase(passphrase, password='', network='bitcoin', key_type='bip32', compressed=True, encoding=None, witness_type='segwit', multisig=False)[source]

Create a key from the provided Mnemonic passphrase

Parameters:
  • passphrase (str) – Mnemonic passphrase, list of words as string separated with a space character

  • password (str) – Password to protect passphrase

  • network (str, Network) – Network to use

  • key_type (str) – HD BIP32 or normal Private Key. Default is ‘bip32’

  • compressed (bool) – Is key compressed or not, default is True

  • encoding (str) – Encoding used for address, i.e.: base58 or bech32. Default is base58 or derive from witness type

  • witness_type (str) – Witness type used when creating scripts: legacy, p2sh-segwit or segwit.

  • multisig (bool) – Specify if key is part of multisig wallet, used when creating key representations such as WIF and addreses

Return HDKey:

static from_seed(import_seed, key_type='bip32', network='bitcoin', compressed=True, encoding=None, witness_type='segwit', multisig=False)[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

  • compressed (bool) – Is key compressed or not, default is True

  • encoding (str) – Encoding used for address, i.e.: base58 or bech32. Default is base58 or derive from witness type

  • witness_type (str) – Witness type used when creating scripts: legacy, p2sh-segwit or segwit.

  • multisig (bool) – Specify if this key is part of a multisig wallet, used when creating key representations such as WIF and addresses

Return HDKey:

static from_wif(wif, network=None, compressed=True, multisig=None)[source]

Create HDKey from BIP32 WIF

Parameters:
  • wif (str) – HDKey WIF

  • network (str) – Network to use as string

  • compressed (bool) – Is key compressed or not, default is True

  • multisig (bool) – Specify if key is part of multisig wallet, used when creating key representations such as WIF and addresses

Return HDKey:

info()[source]

Prints key information to standard output

inverse()[source]

Return inverse of this private or public key

Return Key:

key_for_path(path, network=None)[source]

Determine subkey for HD Key for given path. Path format: m / purpose’ / coin_type’ / account’ / change / address_index

See BIP0044 bitcoin proposal for more explanation.

>>> wif = 'xprv9s21ZrQH143K4LvcS93AHEZh7gBiYND6zMoRiZQGL5wqbpCU2KJDY87Txuv9dduk9hAcsL76F8b5JKzDREf8EmXjbUwN1c4nR9GEx56QGg2'
>>> k = HDKey.from_wif(wif)
>>> k.key_for_path("m/44'/0'/0'/0/2")
<HDKey(public_hex=03004331ca7f0dcdd925abc4d0800a0d4a0562a02c257fa39185c55abdfc4f0c0c, wif_public=xpub6GyQoEbMUNwu1LnbiCSaD8wLrcjyRCEQA8tNsFCH4pnvCbuWSZkSB6LUNe89YsCBTg1Ncs7vHJBjMvw2Q7siy3A4g1srAq7Lv3CtEXghv44, network=bitcoin)>
Parameters:
  • path (str, list) – BIP0044 key path

  • network (str) – Network name.

Return HDKey:

HD Key class object of subkey

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 the current private key. Strips all private information from HDKey object, returns deepcopy version of the current object

Return HDKey:

public_master(account_id=0, purpose=None, multisig=None, witness_type=None, as_private=False)[source]

Derives a public master key for the current HDKey. A public master key can be shared with other software administration tools to create readonly wallets or can be used to create multisignature wallets.

>>> private_hex = 'b66ed9778029d32ebede042c79f448da8f7ab9efba19c63b7d3cdf6925203b71'
>>> k = HDKey(private_hex)
>>> pm = k.public_master()
>>> pm.wif()
'zpub6qN4WhSaerCBXv28QdRXwY4EvnAUbCSLCWUF5ZNSsyrupWwBRv4irjjQ6vpz5WFM7Z7zyy3eQBzijfszpvqdoiyAVLc44MsL4mVQDTwSHpT'
Parameters:
  • account_id (int) – Account ID. Leave empty for account 0

  • purpose (int) – BIP standard used, i.e. 44 for default, 45 for multisig, 84 for segwit. Derived from witness_type and multisig arguments if not provided

  • multisig (bool) – Key is part of a multisignature wallet?

  • witness_type (str) – Specify witness type, default is legacy. Use ‘segwit’ or ‘p2sh-segwit’ for segregated witness.

  • as_private – Return private key if available. Default is to return public key

Return HDKey:

public_master_multisig(account_id=0, purpose=None, witness_type=None, as_private=False)[source]

Derives a public master key for current HDKey for use with multi signature wallets. Wrapper for the public_master() method.

Parameters:
  • account_id (int) – Account ID. Leave empty for account 0

  • purpose (int) – BIP standard used, i.e. 44 for default, 45 for multisig, 84 for segwit.

  • witness_type (str) – Specify a witness type, default is legacy. Use ‘segwit’ or ‘p2sh-segwit’ for segregated witness.

  • as_private – Return a private key if available. The default is to return the public key

Return HDKey:

sign_message(message, use_rfc6979=True, k=None, hash_type=1, force_canonical=False)[source]

Create a Signature for the provided message. Provide the message in bytes format, this method will add network specific data and will hash the message. By default, a deterministic k value will be used according to the RFC6979 standard.

Parameters:
  • message (bytes, hexstring) – Message to be signed. Must be unhashed and in bytes format.

  • use_rfc6979 (bool) – Use deterministic value for k nonce to derive k from txid/message according to RFC6979 standard. Default is True, set to False to use random k

  • k (int) – Provide own k. Only use for testing or if you know what you are doing. Providing wrong value for k can result in leaking your private key!

  • hash_type (int) – Specific hash type, default is SIGHASH_ALL

  • force_canonical (bool) – Some wallets do not require a canonical s value, so you could set this to False

Return Signature:

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

See BIP0044 bitcoin proposal for more explanation.

Deprecated: function renamed to key_for_path()

>>> wif = 'xprv9s21ZrQH143K4LvcS93AHEZh7gBiYND6zMoRiZQGL5wqbpCU2KJDY87Txuv9dduk9hAcsL76F8b5JKzDREf8EmXjbUwN1c4nR9GEx56QGg2'
>>> k = HDKey.from_wif(wif)
>>> k.subkey_for_path("m/44'/0'/0'/0/2")
<HDKey(public_hex=03004331ca7f0dcdd925abc4d0800a0d4a0562a02c257fa39185c55abdfc4f0c0c, wif_public=xpub6GyQoEbMUNwu1LnbiCSaD8wLrcjyRCEQA8tNsFCH4pnvCbuWSZkSB6LUNe89YsCBTg1Ncs7vHJBjMvw2Q7siy3A4g1srAq7Lv3CtEXghv44, network=bitcoin)>
Parameters:
  • path (str, list) – BIP0044 key path

  • network (str) – Network name.

Return HDKey:

HD Key class object of subkey

wif(is_private=None, child_index=None, prefix=None, witness_type=None, multisig=None)[source]

Get Extended WIF of the current key

>>> private_hex = '221ff330268a9bb5549a02c801764cffbc79d5c26f4041b26293a425fd5b557c'
>>> k = HDKey(private_hex)
>>> k.wif()
'zpub6jftahH18ngZw8pNbq6arfqFD7przPySpW3jhhzQiBKYpzJxqwhBEpCk8rh9p7JQ5JrAMu1Pfq1wCXfDfZL8i9zJvxeehCTAAVTev5oZKCn'
Parameters:
  • is_private (bool) – Return public or private 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

  • witness_type (str) – Specify witness type, default is legacy. Use ‘segwit’ for segregated witness.

  • multisig (bool) – Key is part of a multisignature wallet?

Return str:

Base58 encoded WIF key

wif_key(prefix=None)[source]

Get WIF of the Key object. Call to parent object Key.wif()

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

wif_private(prefix=None, witness_type=None, multisig=None)[source]

Get Extended WIF private key. Wrapper for the wif() method

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

  • witness_type (str) – Specify witness type, default is legacy. Use ‘segwit’ for segregated witness.

  • multisig (bool) – Key is part of a multi signature wallet?

Return str:

Base58 encoded WIF key

wif_public(prefix=None, witness_type=None, multisig=None)[source]

Get Extended WIF public key. Wrapper for the wif() method

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

  • witness_type (str) – Specify witness type, default is legacy. Use ‘segwit’ for segregated witness.

  • multisig (bool) – Key is part of a multisignature wallet?

Return str:

Base58 encoded WIF key

class bitcoinlib.keys.Key(import_key=None, network=None, compressed=True, password='', is_private=None, strict=True)[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 import_key is empty a new private key will be generated.

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 compressed boolean attribute tells if the original imported key was compressed or not.

>>> k = Key('cNUpWJbC1hVJtyxyV4bVAnb4uJ7FPhr82geo1vnoA29XWkeiiCQn')
>>> k.secret
12127227708610754620337553985245292396444216111803695028419544944213442390363

Can also be used to import BIP-38 password protected keys

>>> k2 = Key('6PYM8wAnnmAK5mHYoF7zqj88y5HtK7eiPeqPdu4WnYEFkYKEEoMFEVfuDg', password='test', network='testnet')
>>> k2.secret
12127227708610754620337553985245292396444216111803695028419544944213442390363
Parameters:
  • import_key (str, int, bytes, tuple) – 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

  • password (str) – Optional password if imported key is password protected

  • is_private (bool) – Specify if imported key is private or public. Default is None: derive from provided key

  • strict (bool) – Raise BKeyError if key is invalid. Default is True. Set to False if you’re parsing blockchain transactions, as some may contain invalid keys, but the transaction is/was still valid.

Returns:

Key object

address(compressed=None, prefix=None, script_type=None, encoding=None)[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 or Bech32 encoded address

property address_obj

Get address object property. Create standard address object if not defined already.

Return Address:

address_uncompressed(prefix=None, script_type=None, encoding=None)[source]

Get uncompressed address from the 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

  • 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

as_bytes(private=False)[source]

Return bytes representation of private or public key

Parameters:

private – Private or public key

Return bytes:

as_dict(include_private=False)[source]

Get current Key class as dictionary. Byte values are represented by hexadecimal strings.

Parameters:

include_private (bool) – Include private key information in dictionary

Return collections.OrderedDict:

as_hex(private=False)[source]

Return hex representation of private or public key

Parameters:

private – Private or public key

Return str:

as_json(include_private=False)[source]

Get current key as json formatted string

Parameters:

include_private (bool) – Include private key information in dictionary

Return str:

encrypt(password)[source]

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

>>> k = Key('cNUpWJbC1hVJtyxyV4bVAnb4uJ7FPhr82geo1vnoA29XWkeiiCQn')
>>> k.encrypt('test')
'6PYM8wAnnmAK5mHYoF7zqj88y5HtK7eiPeqPdu4WnYEFkYKEEoMFEVfuDg'
Parameters:

password (str) – Required password for encryption

Return str:

BIP38 password encrypted private key

static from_wif(wif, network=None)[source]

Import private key in WIF format.

Parameters:
  • wif (str) – Private key in WIF format

  • network (str, Network) – Bitcoin, testnet, litecoin or other network

Return Key:

property hash160

Get the public key in RIPEMD-160 + SHA256 format

Return bytes:

hex()[source]
info()[source]

Prints key information to standard output

inverse()[source]

Return inverse of private or public key

Return Key:

public()[source]

Get public version of current key. Removes all private information from current key

Return Key:

Public key

public_point()[source]

Get public key point on Elliptic curve

Return tuple:

(x, y) point

property public_uncompressed_byte
property public_uncompressed_hex
sign_message(message, use_rfc6979=True, k=None, hash_type=1, force_canonical=False)[source]

Create a Signature for the provided message. Provide the message in bytes format, this method will add network specific data and will hash the message. By default, a deterministic k value will be used according to the RFC6979 standard.

Parameters:
  • message (bytes, hexstring) – Message to be signed. Must be unhashed and in bytes format.

  • use_rfc6979 (bool) – Use deterministic value for k nonce to derive k from txid/message according to RFC6979 standard. Default is True, set to False to use random k

  • k (int) – Provide own k. Only use for testing or if you know what you are doing. Providing wrong value for k can result in leaking your private key!

  • hash_type (int) – Specific hash type, default is SIGHASH_ALL

  • force_canonical (bool) – Some wallets do not require a canonical s value, so you could set this to False

Return Signature:

verify_message(message, signature)[source]

Verify if provided message is signed by signature.

Parameters:
  • message (bytes, hexstring) – Message to verify. Must be unhashed and in bytes format.

  • signature (Signature) – signature as Signature object

Return bool:

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

property x
property y
class bitcoinlib.keys.Signature(r, s, message=None, secret=None, signature=None, der_signature=None, public_key=None, k=None, hash_type=1, compressed=True, recid=0, witness_type=None, network=None)[source]

Bases: object

Signature class for transactions. Used to create signatures to sign transaction and verification

Sign a transaction hash with a private key and show DER encoded signature:

>>> sk = HDKey('f2620684cef2b677dc2f043be8f0873b61e79b274c7e7feeb434477c082e0dc2')
>>> txid = 'c77545c8084b6178366d4e9a06cf99a28d7b5ff94ba8bd76bbbce66ba8cdef70'
>>> signature = sign(txid, sk)
>>> signature.as_der_encoded().hex()
'3045022100ae1aa67bbb68dcf960d088681fcaebed55abbe63a2e7154899ffd2cbc3c45d0302206f4267d4e67510bb3405940e904446335977a8163d340c8a28bd134866a94e4f01'
>>> signature2 = b'IKF5khz0uiaTwl2LMnFC4ZyLHsqbYTVLMz7o1F5CN4j5Y0RLjLx8fPIYBcs1fulUl2NKnaE92QbP/w/1NGymqFo='
>>> sig = Signature.parse_base64(signature2, sk)
>>> sig.r
73037165552361988254704500960942039375799082706135232334719139810058545105145

Initialize a Signature object with provided r and r value

>>> r = 32979225540043540145671192266052053680452913207619328973512110841045982813493
>>> s = 12990793585889366641563976043319195006380846016310271470330687369836458989268
>>> sig = Signature(r, s)
>>> sig.hex()
'48e994862e2cdb372149bad9d9894cf3a5562b4565035943efe0acc502769d351cb88752b5fe8d70d85f3541046df617f8459e991d06a7c0db13b5d4531cd6d4'
Parameters:
  • r (int) – r value of signature

  • s (int) – s value of signature

  • message (bytes, hexstring) – Transaction hash or message z to sign if known

  • secret (int) – Private key secret number

  • signature (str, bytes) – r and s value of signature as string

  • der_signature (str, bytes) – DER encoded signature

  • public_key (HDKey, Key, str, hexstring, bytes) – Provide public key P if known

  • k (int) – k value used for signature

  • hash_type (int) – Specific hash type, default is SIGHASH_ALL

  • compressed (bool) – Compressed or uncompressed key. Used for message signatures

  • recid (int) – Recovery ID to indicate which of the 4 possible public points x,y combinations will be used. Used for message signatures

  • network (str, Network) – Network to use

as_base64()[source]

Return the current Signature in base64 format following the bip-0137 standard, used for message signing.

Uses this format: [1 byte of header data][32 bytes for r value][32 bytes for s value]

The header byte contains information about the type of address.

as_bytes()[source]
as_der_encoded(as_hex=False, include_hash_type=True)[source]

Get DER encoded signature

Parameters:
  • as_hex (bool) – Output as hexstring

  • include_hash_type (bool) – Include hash_type byte at end of signatures as used in raw scripts. Default is True

Return bytes:

as_hex()[source]
as_signed_message(message)[source]

Return signed message string to exchange with other entities.

Output example: —–BEGIN BITCOIN SIGNED MESSAGE—– Bitcoin Signed Message —–BEGIN SIGNATURE—– bc1qfpv6fhe8vqwrq3ag853u5m6l635jy8dku9ysak H/vw2bYHTyrQrRKo+RgahP8Y3L992q6YDJZipAXYV/s6LNN9XgV7ZOpYUnhAs+W6EpLRSzk4iDA6Xfx5qj6bDM0= —–END BITCOIN SIGNED MESSAGE—–

Parameters:

message (str) – Provide original signed message. Signature object does not store message string

Return str:

bytes()[source]

Signature r and s value as single bytes string

Return bytes:

static create(message, private, use_rfc6979=True, k=None, hash_type=1, prehashed=True, force_canonical=False, network='bitcoin')[source]

Sign a message or transaction hash and create a signature with provided private key.

>>> k = 'b2da575054fb5daba0efde613b0b8e37159b8110e4be50f73cbe6479f6038f5b'
>>> message = '0d12fdc4aac9eaaab9730999e0ce84c3bd5bb38dfd1f4c90c613ee177987429c'
>>> sig = Signature.create(message, k)
>>> sig.hex()
'21934dde1f8b62d73359991c4ebe043cc7758118611455b97e7d8c5fd4ae99805f8cf0507436f94062635ad5ccb883f87cfd9ecb54bcff084e99ee100c21e0c1'
>>> sig.r
15186587944669097449478602251208188095231503054964345209048973685229045586304
>>> sig.s
72573351444679110937806889424191062155363700089799568781362665366696974639232
Parameters:
  • message (bytes, str) – Transaction signature or transaction hash (txid). If unhashed transaction or message is provided the double_sha256 hash of message will be calculated.

  • private (HDKey, Key, str, hexstring, bytes) – Private key as HDKey or Key object, or any other string accepted by HDKey object

  • use_rfc6979 (bool) – Use deterministic value for k nonce to derive k from txid/message according to RFC6979 standard. Default is True, set to False to use random k

  • k (int) – Provide own k. Only use for testing or if you know what you are doing. Providing wrong value for k can result in leaking your private key!

  • hash_type (int) – Specific hash type, default is SIGHASH_ALL

  • prehashed (bool) – Wheter the message / txid provided was already prehashed with the Double SHA 256 for instance. Default is True if message size is 32 else False, if set to False the message will be hashed with double_sha256 by this create method.

  • force_canonical (bool) – Calculate signature with canonical s value. Default is True, needed for valid transacton signatures. Only set to False for signing messages.

Return Signature:

hex()[source]

Signature r and s value as single hexadecimal string

Return hexstring:

property message
classmethod parse(signature, public_key=None)[source]
static parse_base64(signature, public_key=None)[source]

Parse base64 encoded signature and return a Signature object.

Extract compressed and recovery ID info from the first byte.

Parameters:
  • signature (str, bytes) – Base64 encoded signature

  • public_key (HDKey, Key, str, hexstring, bytes) – Public key to pass to signature object

Return Signature:

static parse_bytes(signature, public_key=None)[source]

Create a signature from signature string with r and s part. Signature should be a DER encoded byte string of a 64 bytes string with an r and s value

Parameters:
  • signature (bytes) – Signature string

  • public_key (HDKey, Key, str, hexstring, bytes) – Public key as HDKey or Key object or any other string accepted by HDKey object

Return Signature:

classmethod parse_hex(signature, public_key=None)[source]
property public_key

Return public key as HDKey object

Return HDKey:

verify(message=None, public_key=None)[source]

Verify this signature. Provide a message/txid or public_key if not already known

>>> k = 'b2da575054fb5daba0efde613b0b8e37159b8110e4be50f73cbe6479f6038f5b'
>>> pub_key = HDKey(k).public()
>>> txid = '0d12fdc4aac9eaaab9730999e0ce84c3bd5bb38dfd1f4c90c613ee177987429c'
>>> sig = '48e994862e2cdb372149bad9d9894cf3a5562b4565035943efe0acc502769d351cb88752b5fe8d70d85f3541046df617f8459e991d06a7c0db13b5d4531cd6d4'
>>> sig = Signature.parse_hex(sig)
>>> sig.verify(txid, pub_key)
True
Parameters:
  • message (bytes, hexstring) – Message to verify, for instance a Transaction hash

  • public_key (HDKey, Key, str, hexstring, bytes) – Public key P

Return bool:

verify_message(message, address=None, network=None)[source]

Verify if the provided message is signed with this signature. Provide address to check if address matches the signature.

Parameters:
  • message (bytes, hexstring) – Message to verify. Must be unhashed and in bytes format.

  • address (Address, str) – Address used to sign message

  • network (Network, str) – Network used to sign message

Return bool:

bitcoinlib.keys.addr_convert(addr, prefix, encoding=None, to_encoding=None)[source]

Convert address to another encoding and/or address with another prefix.

>>> addr_convert('1GMDUKLom6bJuY37RuFNc6PHv1rv2Hziuo', prefix='bc', to_encoding='bech32')
'bc1q4pwfmstmw8q80nxtxud2h42lev9xzcjqwqyq7t'
Parameters:
  • addr (str) – Base58 address

  • prefix (str, bytes) – New address prefix

  • encoding (str) – Encoding of original address: base58 or bech32. Leave empty to extract from address

  • to_encoding (str) – Encoding of converted address: base58 or bech32. Leave empty use same encoding as original address

Return str:

New converted address

bitcoinlib.keys.bip38_create_new_encrypted_wif(intermediate_passphrase, compressed=True, seed=b'\x10\xa5D\xbax\x99\xb3e\x7f\xc7\xa8`\x10\x92#aQo7A\x15H\x8d\x82', network='bitcoin')[source]

Create new encrypted WIF BIP38 EC multiplied key. Use bip38_intermediate_password() to create an intermediate passphrase first.

Parameters:
  • intermediate_passphrase (str) – Intermediate passphrase text

  • compressed (boolean) – Compressed or uncompressed key

  • seed (str, bytes) – Seed, default to os.urandom(24)

  • network (str) – Network name

Returns dict:

Dictionary with encrypted WIF key and confirmation code

bitcoinlib.keys.bip38_decrypt(encrypted_privkey, password)[source]

BIP0038 non-ec-multiply decryption. Returns WIF private key. Based on code from https://github.com/nomorecoin/python-bip38-testing This method is called by Key class init function when importing BIP0038 key.

Parameters:
  • encrypted_privkey (str) – Encrypted private key using WIF protected key format

  • password (str) – Required password for decryption

Return tuple (bytes, bytes, boolean, dict):

(Private Key bytes, 4 byte address hash for verification, compressed?, dictionary with additional info)

bitcoinlib.keys.bip38_encrypt(private_hex, address, password, flagbyte=b'\xe0')[source]

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

Parameters:
  • private_hex (str) – Private key in hex format

  • address (str) – Address string

  • password (str) – Required password for encryption

  • flagbyte (bytes) – Flagbyte prefix for WIF

Return str:

BIP38 password encrypted private key

bitcoinlib.keys.bip38_intermediate_password(passphrase, lot=None, sequence=None, owner_salt=b'\xba"\x00\xa6,\x8b\x87\x87')[source]

Intermediate passphrase generator for EC multiplied BIP38 encrypted private keys. Source: https://github.com/meherett/python-bip38/blob/master/bip38/bip38.py

Use intermediate password to create an encrypted WIF key with the bip38_create_new_encrypted_wif() method.

Parameters:
  • passphrase (str) – Passphrase or password text

  • lot (int) – Lot number between 100000 <= lot <= 999999 range, default to None

  • sequence (int) – Sequence number between 0 <= sequence <= 4095 range, default to None

  • owner_salt (str, bytes) – Owner salt, default to os.urandom(8)

Returns str:

Intermediate passphrase

>>> bip38_intermediate_password(passphrase="TestingOneTwoThree", lot=199999, sequence=1, owner_salt="75ed1cdeb254cb38")
'passphraseb7ruSN4At4Rb8hPTNcAVezfsjonvUs4Qo3xSp1fBFsFPvVGSbpP2WTJMhw3mVZ'
bitcoinlib.keys.check_network_and_key(key, network=None, kf_networks=None, default_network='bitcoin')[source]

Check if a given key corresponds with the 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.

>>> check_network_and_key('L4dTuJf2ceEdWDvCPsLhYf8GiiuYqXtqfbcKdC21BPDvEM1ykJRC')
'bitcoin'

A BKeyError will be raised if the key does not correspond with the network or if multiple networks are found.

Parameters:
  • key (str, int, bytes) – Key in any format recognized by get_key_format function

  • network (str, None) – Optional network. Method raises BKeyError if keys belong to another network

  • kf_networks (list, None) – 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, None) – 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 contains the network with the highest priority if multiple networks are found. Same applies for the script type.

Specify the network argument if the network is known to avoid unexpected results.

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

>>> deserialize_address('1Khyc5eUddbhYZ8bEZi9wiN8TrmQ8uND4j')
{'address': '1Khyc5eUddbhYZ8bEZi9wiN8TrmQ8uND4j', 'encoding': 'base58', 'public_key_hash': 'cd322766c02e7c37c3e3f9b825cd41ffbdcd17d7', 'public_key_hash_bytes': b"\xcd2'f\xc0.|7\xc3\xe3\xf9\xb8%\xcdA\xff\xbd\xcd\x17\xd7", 'prefix': b'\x00', 'network': 'bitcoin', 'script_type': 'p2pkh', 'witness_type': 'legacy', 'networks': ['bitcoin', 'regtest'], 'checksum': b'\xcf\xa4I0', 'witver': None, 'raw': b"\x00\xcd2'f\xc0.|7\xc3\xe3\xf9\xb8%\xcdA\xff\xbd\xcd\x17\xd7\xcf\xa4I0"}
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) – Specify network filter, i.e.: bitcoin, testnet, litecoin, etc. Wil trigger check if address is valid for this network

Return dict:

with information about this address

bitcoinlib.keys.ec_point(m)[source]

Method for elliptic curve multiplication on the secp256k1 curve. Multiply Generator point G by m

Parameters:

m (int) – A scalar multiplier

Return Point:

Generator point G multiplied by m

bitcoinlib.keys.ec_point_multiplication(p, m, return_point=False)[source]

Method for elliptic curve multiplication on the secp256k1 curve. Multiply Generator point G by m

Parameters:
  • p (tuple) – Point on SECP256k1 curve

  • m (int) – A scalar multiplier

Return tuple:

Generator point G multiplied by m as tuple in (x, y) format

bitcoinlib.keys.get_key_format(key, is_private=None)[source]

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

This method does not validate if a key is valid.

>>> get_key_format('L4dTuJf2ceEdWDvCPsLhYf8GiiuYqXtqfbcKdC21BPDvEM1ykJRC')
{'format': 'wif_compressed', 'networks': ['bitcoin', 'regtest'], 'is_private': True, 'script_types': [], 'witness_types': ['segwit'], 'multisig': [False]}
>>> get_key_format('becc7ac3b383cd609bd644aa5f102a811bac49b6a34bbd8afe706e32a9ac5c5e')
{'format': 'hex', 'networks': None, 'is_private': True, 'script_types': [], 'witness_types': ['segwit'], 'multisig': [False]}
>>> get_key_format('Zpub6vZyhw1ShkEwNxtqfjk7jiwoEbZYMJdbWLHvEwo6Ns2fFc9rdQn3SerYFQXYxtZYbA8a1d83shW3g4WbsnVsymy2L8m7wpeApiuPxug3ARu')
{'format': 'hdkey_public', 'networks': ['bitcoin', 'regtest'], 'is_private': False, 'script_types': ['p2wsh'], 'witness_types': ['segwit'], 'multisig': [True]}
Parameters:
  • key (str, int, bytes) – Any private or public key

  • is_private (bool) – Is key private or not?

Return dict:

Dictionary with format, network and is_private

bitcoinlib.keys.message_magic(message, network=None)[source]

Add network magic to a message string, so “Hello world!” results in “BITCOIN Signed Message: Hello world!

Parameters:
  • message (str) – Message text

  • network (Network, str) – Network to use, default is Bitcoin

Return str:

bitcoinlib.keys.mod_sqrt(a)[source]

Compute the square root of ‘a’ using the secp256k1 ‘bitcoin’ curve

Used to calculate y-coordinate if only x-coordinate from a public key point is known. Formula: y ** 2 == x ** 3 + 7

Parameters:

a (int) – Number to calculate square root

Return int:

bitcoinlib.keys.path_expand(path, path_template=None, level_offset=None, account_id=0, cosigner_id=0, purpose=84, address_index=0, change=0, witness_type='segwit', multisig=False, network='bitcoin')[source]

Create key path. Specify part of key path and path settings

>>> path_expand([10, 20], witness_type='segwit')
['m', "84'", "0'", "0'", '10', '20']
Parameters:
  • path (list, str) – Part of path, for example [0, 2] for change=0 and address_index=2

  • path_template (list) – Template for path to create, default is BIP 44: [“m”, “purpose’”, “coin_type’”, “account’”, “change”, “address_index”]

  • level_offset (int) – Just create part of path. For example -2 means create path with the last 2 items (change, address_index) or 1 will return the master key ‘m’

  • account_id (int) – Account ID

  • cosigner_id (int) – ID of cosigner

  • purpose (int) – Purpose value

  • address_index (int) – Index of key, normally provided to ‘path’ argument

  • change (int) – Change key = 1 or normal = 0, normally provided to ‘path’ argument

  • witness_type (str) – Witness type for paths with a script ID, specify ‘p2sh-segwit’ or ‘segwit’

  • multisig (bool) – Is path for multisig keys?

  • network (str) – Network name. Leave empty for default network

Return list:

bitcoinlib.keys.sign(message, private, use_rfc6979=True, k=None, hash_type=1, prehashed=True, force_canonical=True, network='bitcoin')[source]

Sign the transaction hash or message with the secret private key. Creates a signature object.

Sign a transaction hash with a private key and show DER encoded signature

>>> sk = HDKey('728afb86a98a0b60cc81faadaa2c12bc17d5da61b8deaf1c08fc07caf424d493')
>>> txid = 'c77545c8084b6178366d4e9a06cf99a28d7b5ff94ba8bd76bbbce66ba8cdef70'
>>> signature = sign(txid, sk)
>>> signature.as_der_encoded().hex()
'3044022039df9d8a0b4df185605c5a46eb087d499ddf98cb5ebcae6e0fd99c56152d2d730220726a3c03ac0b04e1489a1f465cb615be87dde7c4c7806195ca6b1acc2910e06901'
Parameters:
  • message (bytes, str) – Transaction signature or transaction hash. If unhashed transaction or message is provided the double_sha256 hash of message will be calculated.

  • private (HDKey, Key, str, hexstring, bytes) – Private key as HDKey or Key object, or any other string accepted by HDKey object

  • use_rfc6979 (bool) – Use deterministic value for k nonce to derive k from txid/message according to RFC6979 standard. Default is True, set to False to use random k

  • k (int) – Provide own k. Only use for testing or if you know what you are doing. Providing wrong value for k can result in leaking your private key!

  • hash_type (int) – Specific hash type, default is SIGHASH_ALL

  • prehashed (bool) – Whether the message / txid provided was already prehashed with the Double SHA 256 for instance. Default is True, if set to False the message will be hashed with double_sha256 by this create method.

  • force_canonical (bool) – Force canonicalization of signature s value. Default is True

  • network (str, Network) – Specific network, default is DEFAULT_NETWORK

Return Signature:

bitcoinlib.keys.signed_message_parse(message_signature)[source]

Parse Bitcoin Signed Message and split into message, address and signature part.

Example: python> signed_message_parse(’ —–BEGIN BITCOIN SIGNED MESSAGE—–

Bitcoinlib is cool! —–BEGIN SIGNATURE—– bc1qed0dq6a7gshfvap4j946u44kk73gs3a0d5p3sw ILtL9qkUb+2nfxY3bUqfoWsVSwhMSos+DVY7p3EqmzQ6qF2gHNPvILwrsZ2AKlIqPmJjln4OKpW+d86wBn27yJw= —–END BITCOIN SIGNED MESSAGE—–“)

Result: (‘Bitcoinlib is cool!’, ‘bc1qed0dq6a7gshfvap4j946u44kk73gs3a0d5p3sw’, ‘ILtL9qkUb+2nfxY3bUqfoWsVSwhMSos+DVY7p3EqmzQ6qF2gHNPvILwrsZ2AKlIqPmJjln4OKpW+d86wBn27yJw=’, ‘bitcoin’)

Parameters:

message_signature (str) – Signed Message text

Return tuple (str, str, str, str):

message, base64 encoded signature, address

bitcoinlib.keys.verify(message, signature, public_key=None)[source]

Verify the provided signature with the message / txid. If provided signature is no Signature object a new object will be created for verification.

>>> k = 'b2da575054fb5daba0efde613b0b8e37159b8110e4be50f73cbe6479f6038f5b'
>>> pub_key = HDKey(k).public()
>>> txid = '0d12fdc4aac9eaaab9730999e0ce84c3bd5bb38dfd1f4c90c613ee177987429c'
>>> sig = '48e994862e2cdb372149bad9d9894cf3a5562b4565035943efe0acc502769d351cb88752b5fe8d70d85f3541046df617f8459e991d06a7c0db13b5d4531cd6d4'
>>> verify(txid, sig, pub_key)
True
Parameters:
  • message (bytes, hexstring) – Message / Transaction hash

  • signature (Signature, str, bytes) – signature as Signature, hexstring or bytes

  • public_key (HDKey, Key, str, hexstring, bytes) – Public key P. If not provided it will be derived from provided Signature object or raise an error if not available

Return bool:

bitcoinlib.keys.verify_message(message, sig, address, network=None)[source]

Verify a signed message. Prove if the owner of the provided address did sign this exact message.

>>> message = 'this is a unittest'
>>> sig = 'IBqszVUdhXkJnZpcoQh+EyEZicOQP0fZ2z/Rzw4Xa+YgCXtsOYSR1RvAYAeejCkEW6iQZ9e5j8AqSH2zxvshZPM='
>>> addr = 'bc1q7wdttvkuypq3p2ww7cfzgzzs659jehhgvsfnnn'
>>> verify_message(message, sig, addr)
True
Parameters:
  • message (str) – Message text

  • sig (str, Signature) – Signature

  • address (str, Address) – Address to verify message

  • network (Network, str) – Network to use, default is Bitcoin

Return bool: