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:
- property data
- property hashed_data
- classmethod import_address(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 network if available, otherwise it will be derived form the address.
- 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:
- 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 network if available, otherwise it will be derived form 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:
- 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=True, 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 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, a chain with only 32 0-bytes will be used.
>>> private_hex = '221ff330268a9bb5549a02c801764cffbc79d5c26f4041b26293a425fd5b557c' >>> k = HDKey(private_hex) >>> k <HDKey(public_hex=0363c152144dcd5253c1216b733fdc6eb8a94ab2cd5caa8ead5e59ab456ff99927, wif_public=xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6SmypHzZG2cYrwpGkWJqRxS6EAW77gd7CHFoXNpBd3LN8xjAyCW, network=bitcoin)>
- Parameters:
import_key (str, bytes, int) – 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 current HDKey class as 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 current key as 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 child private key of current HD Key object.
Used by
subkey_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() '1FgHK5JUa87ASxz5mz3ypeaUV23z9yW654' >>> ck.depth 1 >>> ck.child_index 10
- 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.
Used by
subkey_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 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() '1PfLJJgKs8nUbMPpaQUucbGmr8qyNSMGeK' >>> 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='legacy', multisig=False)[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
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='legacy', 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 key is part of 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:
- 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. Strips all private information from HDKey object, returns deepcopy version of 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 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() 'xpub6CjFexgdDZEtHdW7V4LT8wS9rtG3m187pM9qhTpoZdViFhSv3tW9sWonQNtFN1TCkRGAQGKj1UC2ViHTqb7vJV3X67xSKuCDzv14tBHR3Y7'
- 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 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:
- 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.
>>> 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 current key
>>> private_hex = '221ff330268a9bb5549a02c801764cffbc79d5c26f4041b26293a425fd5b557c' >>> k = HDKey(private_hex) >>> k.wif() 'xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6SmypHzZG2cYrwpGkWJqRxS6EAW77gd7CHFoXNpBd3LN8xjAyCW'
- 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 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) – 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 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_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_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 public key in RIPEMD-160 + SHA256 format
- Return bytes:
- public()[source]
Get public version of current key. Removes all private information from current key
- Return Key:
Public key
- property public_uncompressed_byte
- property public_uncompressed_hex
- 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, txid=None, secret=None, signature=None, der_signature=None, public_key=None, k=None, hash_type=1)[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() '3044022015f9d39d8b53c68c7549d5dc4cbdafe1c71bae3656b93a02d2209e413d9bbcd00220615cf626da0a81945a707f42814cc51ecde499442eb31913a870b9401af6a4ba01'
Initialize 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
txid (bytes, hexstring) – Transaction hash 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
- 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:
- static create(txid, private, use_rfc6979=True, k=None)[source]
Sign a transaction hash and create a signature with provided private key.
>>> k = 'b2da575054fb5daba0efde613b0b8e37159b8110e4be50f73cbe6479f6038f5b' >>> txid = '0d12fdc4aac9eaaab9730999e0ce84c3bd5bb38dfd1f4c90c613ee177987429c' >>> sig = Signature.create(txid, k) >>> sig.hex() '48e994862e2cdb372149bad9d9894cf3a5562b4565035943efe0acc502769d351cb88752b5fe8d70d85f3541046df617f8459e991d06a7c0db13b5d4531cd6d4' >>> sig.r 32979225540043540145671192266052053680452913207619328973512110841045982813493 >>> sig.s 12990793585889366641563976043319195006380846016310271470330687369836458989268
- Parameters:
txid (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!
- Return Signature:
- static from_str(signature, public_key=None)[source]
Create a signature from signature string with r and s part. Signature length must be 64 bytes or 128 character hexstring
- static parse_bytes(signature, public_key=None)[source]
Create a signature from signature string with r and s part. Signature length must be 64 bytes or 128 character hexstring
- property public_key
Return public key as HDKey object
- Return HDKey:
- property txid
- verify(txid=None, public_key=None)[source]
Verify this signature. Provide 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
- 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.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.
>>> check_network_and_key('L4dTuJf2ceEdWDvCPsLhYf8GiiuYqXtqfbcKdC21BPDvEM1ykJRC') 'bitcoin'
A BKeyError will be raised if key does not correspond with network or if multiple network 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 belongs 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 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'], 'witver': None}
- 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.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': ['legacy'], 'multisig': [False]}
>>> get_key_format('becc7ac3b383cd609bd644aa5f102a811bac49b6a34bbd8afe706e32a9ac5c5e') {'format': 'hex', 'networks': None, 'is_private': True, 'script_types': [], 'witness_types': ['legacy'], '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.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 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=44, address_index=0, change=0, witness_type='legacy', 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(txid, private, use_rfc6979=True, k=None)[source]
Sign transaction hash or message with 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() '30440220792f04c5ba654e27eb636ceb7804c5590051dd77da8b80244f1fa8dfbff369b302204ba03b039c808a0403d067f3d75fbe9c65831444c35d64d4192b408d2a7410a101'
- Parameters:
txid (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!
- Return Signature:
- bitcoinlib.keys.verify(txid, signature, public_key=None)[source]
Verify provided signature with txid message. 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