btclib package

Subpackages

Submodules

btclib.alias module

Aliases

mypy aliases, documenting also coding input conventions.

btclib.amount module

Proper handling of monetary amounts.

A BTC monetary amount can be expressed as number of satoshis (1 BTC is 100_000_000) or as Python Decimal with up to 8 digits, e.g. Decimal(“0.12345678”).

Because of floating-point conversion issues (e.g. with floats 1.1 + 2.2 != 3.3) algebra with bitcoin amounts should never involve floats.

The provided functions handle conversion between satoshi amounts (sats) and Decimal/float values.

Amounts cannot be a negative value: the Bitcoin protocol and this library do not deal with negative amounts. The functions in this module could be easily amended (in a backward compatible way) in the future if such a need arises.

btclib.amount.btc_from_sats(amount: int) Decimal

Return the BTC Decimal equivalent of the provided satoshi amount.

btclib.amount.sats_from_btc(amount: Decimal) int

Return the satoshi equivalent of the provided BTC amount.

btclib.amount.valid_btc_amount(amount: Any, dust: Decimal = Decimal('0')) Decimal

Return the BTC amount as Decimal, if valid and not less than dust.

btclib.amount.valid_sats_amount(amount: Any, dust: int = 0) int

Return the satoshi amount as int, if valid and not less than dust.

btclib.b32 module

SegWit address functions.

Some of these functions were originally from https://github.com/sipa/bech32/tree/master/ref/python, with the following modifications:

  • moved bech32 stuff into bech32.py

  • type annotated python3

  • avoided returning None or (None, None), throwing Exceptions instead

  • detailed error messages and exteded safety checks

  • check that bech32 addresses are not longer than 90 characters (as this is not enforced by bech32.b32decode anymore)

btclib.b32.address_from_witness(wit_ver: int, wit_prg: Union[bytes, str], network: str = 'mainnet') str

Encode a bech32 native SegWit address from the witness.

btclib.b32.check_witness(wit_ver: int, wit_prg: Union[bytes, str]) bytes
btclib.b32.has_segwit_prefix(addr: Union[bytes, str]) bool
btclib.b32.p2tr(internal_key: Optional[Union[int, bytes, str, BIP32KeyData, Tuple[int, int]]] = None, script_path: Optional[Any] = None, network: str = 'mainnet')

Return the p2tr bech32 address corresponding to a taproot output key.

btclib.b32.p2wpkh(key: Union[int, bytes, str, BIP32KeyData, Tuple[int, int]], network: Optional[str] = None) str

Return the p2wpkh bech32 address corresponding to a public key.

btclib.b32.p2wsh(script_pub_key: Union[bytes, str], network: str = 'mainnet') str

Return the p2wsh bech32 address corresponding to a script_pub_key.

btclib.b32.power_of_2_base_conversion(data: Iterable[int], from_bits: int, to_bits: int, pad: bool = True) List[int]

Convert a power-of-two digit sequence to another power-of-two base.

btclib.b32.witness_from_address(b32addr: Union[bytes, str]) Tuple[int, bytes, str]

Return the witness from a bech32 native SegWit address.

The returned data structure is: version, program, network.

btclib.b58 module

Base58 address and WIF functions.

Base58 encoding of public keys and scripts as addresses, private keys as WIFs

btclib.b58.address_from_h160(script_type: str, h160: Union[bytes, str], network: str = 'mainnet') str

Return a base58 address from the payload.

btclib.b58.h160_from_address(b58addr: Union[bytes, str]) Tuple[str, bytes, str]

Return the payload from a base58 address.

btclib.b58.p2pkh(key: Union[int, bytes, str, BIP32KeyData, Tuple[int, int]], network: Optional[str] = None, compressed: Optional[bool] = None) str

Return the p2pkh base58 address corresponding to a public key.

btclib.b58.p2sh(script_pub_key: Union[bytes, str], network: str = 'mainnet') str

Return the p2sh base58 address corresponding to a script_pub_key.

btclib.b58.p2wpkh_p2sh(key: Union[int, bytes, str, BIP32KeyData, Tuple[int, int]], network: Optional[str] = None) str

Return the p2wpkh-p2sh base58 address corresponding to a public key.

btclib.b58.p2wsh_p2sh(redeem_script: Union[bytes, str], network: str = 'mainnet') str

Return the p2wsh-p2sh base58 address corresponding to a reedem script.

btclib.b58.wif_from_prv_key(prv_key: Union[int, bytes, str, BIP32KeyData], network: Optional[str] = None, compressed: Optional[bool] = None) str

Return the WIF encoding of a private key.

btclib.base58 module

Base58 encoding and decoding functions.

Binary-to-text encoding schemes are used to transport binary data across channels designed to deal with textual data. In Bitcoin they are mostly used to represent large integers as alphanumeric text.

Base58 is similar to Base64, which uses 10 digits, 26 lowercase characters, 26 uppercase characters, ‘+’ (plus sign), and ‘/’ (forward slash). Base58 omits the similar-looking letters 0 (zero), O (capital o), I (capital i), and l (lower case L) to avoid ambiguity when printed; moreover, it removes ‘+’ and ‘/’ so that a double-click does select the whole string.

Base58Check is the checksummed version of Base58, using hash256(v)[:4] as checksum suffix before encoding; at the decoding stage the checksum validity ensure data integrity.

This implementation of Base58 and Base58Check is originally from https://github.com/keis/base58, with the following modifications:

  • type annotated python3

  • using native python3 int.from_bytes() and i.to_bytes()

  • added optional check on output size for b58decode()

  • interface mimics the native python3 base64 interface, i.e. it supports encoding bytes-like objects to ASCII bytes, and decoding ASCII bytes-like objects or ASCII strings to bytes.

btclib.base58.b58decode(v: Union[bytes, str], out_size: Optional[int] = None) bytes

Decode a Base58Check encoded bytes-like object or ASCII string.

Optionally, it also ensures required output size.

btclib.base58.b58encode(v: Union[bytes, str], in_size: Optional[int] = None) bytes

Encode a bytes-like object using Base58Check.

btclib.bech32 module

Bech32(m) encoding and decoding functions.

BIP173: https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki

This implementation of bech32 is originally from https://github.com/sipa/bech32/tree/master/ref/python, with the following modifications:

  • splitted the original segwit_addr.py file in bech32.py and segwitaddress.py

  • type annotated python3

  • avoided returning (None, None), throwing Exceptions instead

  • removed the 90-chars limit for bech32 string, enforced by segwitaddr instead

  • detailed error messages

  • interface mimics the native python3 base64 interface, i.e. it supports encoding bytes-like objects to ASCII bytes, and decoding ASCII bytes-like objects or ASCII strings to bytes.

btclib.bech32.decode(bech: Union[bytes, str], m: Optional[int] = None) Tuple[str, List[int]]
btclib.bech32.encode(hrp: str, data: List[int], m: Optional[int] = None) bytes

Compute a bech32 string given HRP and data values.

btclib.exceptions module

Expception classes.

This are only meant to dicriminate between Exceptions being raised by btclib from those raised by other codebase.

Users are usually better off just dealing with the regular ValueError, TypeError, and RuntimeError from which the btclib versions are derived.

exception btclib.exceptions.BTClibRuntimeError

Bases: RuntimeError

exception btclib.exceptions.BTClibTypeError

Bases: TypeError

exception btclib.exceptions.BTClibValueError

Bases: ValueError

btclib.hashes module

Hash based helper functions.

btclib.hashes.challenge_(msg_hash: ~typing.Union[bytes, str], ec: ~btclib.ecc.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1), hf: ~typing.Callable[[], ~typing.Any] = <built-in function openssl_sha256>) int
btclib.hashes.hash160(octets: Union[bytes, str]) bytes

Return the HASH160=RIPEMD160(SHA256) of the input octet sequence.

btclib.hashes.hash256(octets: Union[bytes, str]) bytes

Return the SHA256(SHA256(*)) of the input octet sequence.

btclib.hashes.magic_message(msg: Union[bytes, str]) bytes
btclib.hashes.merkle_root(data: List[bytes], hf: Callable[[Union[bytes, str]], bytes]) bytes

Return the Merkel tree root of a list of binary hashes.

The Merkel tree is a binary tree constructed with the provided list of binary data as bottom level, then recursively going up one level by hashing every hash value pair in the current level, until a single value (root) is obtained.

btclib.hashes.reduce_to_hlen(msg: ~typing.Union[bytes, str], hf: ~typing.Callable[[], ~typing.Any] = <built-in function openssl_sha256>) bytes
btclib.hashes.ripemd160(octets: Union[bytes, str]) bytes

Return the RIPEMD160(*) of the input octet sequence.

btclib.hashes.sha256(octets: Union[bytes, str]) bytes

Return the SHA256(*) of the input octet sequence.

btclib.hashes.tagged_hash(tag: bytes, m: bytes, hf: ~typing.Callable[[], ~typing.Any] = <built-in function openssl_sha256>) bytes

btclib.network module

Network constants and associated functions.

class btclib.network.Network(curve: btclib.ecc.curve.Curve, magic_bytes: Union[bytes, str], genesis_block: Union[bytes, str], wif: Union[bytes, str], p2pkh: Union[bytes, str], p2sh: Union[bytes, str], hrp: str, bip32_prv: Union[bytes, str], bip32_pub: Union[bytes, str], slip132_p2wpkh_prv: Union[bytes, str], slip132_p2wpkh_pub: Union[bytes, str], slip132_p2wpkh_p2sh_prv: Union[bytes, str], slip132_p2wpkh_p2sh_pub: Union[bytes, str], slip132_p2wsh_prv: Union[bytes, str], slip132_p2wsh_pub: Union[bytes, str], slip132_p2wsh_p2sh_prv: Union[bytes, str], slip132_p2wsh_p2sh_pub: Union[bytes, str], check_validity: bool = True)

Bases: object

assert_valid() None
bip32_prv: bytes
bip32_pub: bytes
curve: Curve
classmethod from_dict(dict_: Mapping[str, Any], check_validity: bool = True) Network
genesis_block: bytes
hrp: str
magic_bytes: bytes
p2pkh: bytes
p2sh: bytes
slip132_p2wpkh_p2sh_prv: bytes
slip132_p2wpkh_p2sh_pub: bytes
slip132_p2wpkh_prv: bytes
slip132_p2wpkh_pub: bytes
slip132_p2wsh_p2sh_prv: bytes
slip132_p2wsh_p2sh_pub: bytes
slip132_p2wsh_prv: bytes
slip132_p2wsh_pub: bytes
to_dict(check_validity: bool = True) Dict[str, Optional[str]]
wif: bytes
btclib.network.curve_from_xkeyversion(xkeyversion: bytes) Curve
btclib.network.network_from_key_value(key: str, prefix: Union[str, bytes, Curve]) Optional[str]

Return network string from (key, value) pair.

Warning: when used on ‘regtest’ it mostly returns ‘testnet’, which is not a problem as long as it is used for WIF/Base58Address/BIP32xkey because the two networks share the same prefixes.

btclib.network.network_from_xkeyversion(xkeyversion: bytes) str

Return network string from the xkey version prefix.

Warning: when used on ‘regtest’ it returns ‘testnet’, which is not a problem as long as it is used for WIF/Base58Address/BIP32Key because the two networks share the same prefixes.

btclib.network.xprvversions_from_network(network: str = 'mainnet') List[bytes]
btclib.network.xpubversions_from_network(network: str = 'mainnet') List[bytes]

btclib.to_prv_key module

Functions for conversions between different private key formats.

btclib.to_prv_key.int_from_prv_key(prv_key: Union[int, bytes, str, BIP32KeyData], ec: Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) int

Return a verified-as-valid private key integer.

It supports:

  • WIF (bytes or string)

  • BIP32 extended keys (bytes, string, or BIP32KeyData)

  • SEC Octets (bytes or hex-string, with 02, 03, or 04 prefix)

  • integer (native int or hex-strin)

Network and compressed informations from the input key are not used.

btclib.to_prv_key.prv_keyinfo_from_prv_key(prv_key: Union[int, bytes, str, BIP32KeyData], network: Optional[str] = None, compressed: Optional[bool] = None) Tuple[int, str, bool]

btclib.to_pub_key module

Functions for conversions between different public key formats.

btclib.to_pub_key.fingerprint(key: Union[int, bytes, str, BIP32KeyData, Tuple[int, int]], network: Optional[str] = None) bytes

Return the public key fingerprint from a private/public key.

The fingerprint is the last four bytes of the compressed public key HASH160.

btclib.to_pub_key.point_from_key(key: Union[int, bytes, str, BIP32KeyData, Tuple[int, int]], ec: Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) Tuple[int, int]

Return a point tuple from any possible key representation.

It supports:

  • BIP32 extended keys (bytes, string, or BIP32KeyData)

  • SEC Octets (bytes or hex-string, with 02, 03, or 04 prefix)

  • native tuple

btclib.to_pub_key.point_from_pub_key(pub_key: Union[bytes, str, BIP32KeyData, Tuple[int, int]], ec: Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) Tuple[int, int]

Return an elliptic curve point tuple from a public key.

btclib.to_pub_key.pub_keyinfo_from_key(key: Union[int, bytes, str, BIP32KeyData, Tuple[int, int]], network: Optional[str] = None, compressed: Optional[bool] = None) Tuple[bytes, str]

Return the pub key tuple (SEC-bytes, network) from a pub/prv key.

btclib.to_pub_key.pub_keyinfo_from_prv_key(prv_key: Union[int, bytes, str, BIP32KeyData], network: Optional[str] = None, compressed: Optional[bool] = None) Tuple[bytes, str]

Return the pub key tuple (SEC-bytes, network) from a private key.

btclib.to_pub_key.pub_keyinfo_from_pub_key(pub_key: Union[bytes, str, BIP32KeyData, Tuple[int, int]], network: Optional[str] = None, compressed: Optional[bool] = None) Tuple[bytes, str]

Return the pub key tuple (SEC-bytes, network) from a public key.

btclib.utils module

Assorted conversion utilities.

Most conversions from SEC 1 v.2 2.3 are included.

https://www.secg.org/sec1-v2.pdf

btclib.utils.bytes_from_octets(octets: Union[bytes, str], out_size: Optional[Union[int, Iterable[int]]] = None) bytes

Return bytes from a hex-string, stripping leading/trailing spaces.

If the input is not a string, then it goes untouched. Optionally, it also ensures required output size.

btclib.utils.bytesio_from_binarydata(stream: Union[BytesIO, bytes, str]) BytesIO

Return a BytesIO stream object from BinaryIO or Octets.

If the input is not Octets (i.e. str or bytes), then it goes untouched.

btclib.utils.decode_num(data: bytes) int

Decode a number to the bitcoin-specific little endian format.

A number is encoded as little-endian variable-length byte vector with the most significant bit (MSB) determining the sign.

  • 0x01 is 1

  • 0x81 is -1

Therefore, there are two representations of zero:

  • 0x00 is “positive” zero

  • 0x80 is “negative” zero

Positive zero is also represented by a null-length byte vector, which is considered the canonical one.

btclib.utils.encode_num(i: int) bytes

Encode a number to the bitcoin-specific little endian format.

A number is encoded as little-endian variable-length byte vector with the most significant bit (MSB) determining the sign.

  • 0x01 is 1

  • 0x81 is -1

Therefore, there are two representations of zero:

  • 0x00 is “positive” zero

  • 0x80 is “negative” zero

Positive zero is also represented by a null-length byte vector, which is considered the canonical one.

btclib.utils.hex_string(i: Union[bytes, str, int]) str

Return a hex-string from many positive integer representations.

Negative integers are not allowed.

The resulting hex-string has an even number of hex-digits and includes a space every four bytes (i.e. every eight hex-digits).

btclib.utils.int_from_bits(octets: Union[bytes, str], nlen: int) int

Return the leftmost nlen bits.

Take as input a sequence of blen bits and calculate a non-negative integer i that is less than 2^nlen according to SEC 1 v.2 section 4.1.3 (5). Note that an additional reduction modulo n would be required to ensure that 0 < i < n.

int_from_bits is not the reverse of i.to_bytes, even for input sequences of length nlen: i.to_bytes will add some bits on the left, while int_from_bits will discard some bits on the right. i.to_bytes is the reverse of int_from_bits only when nlen is a multiple of 8 and bit sequences already have length nlen. See https://tools.ietf.org/html/rfc6979#section-2.3.5.

btclib.utils.int_from_integer(i: Union[bytes, str, int]) int

Return an int from many possible integer representations.

Allowed integer representations are:

  • 3735928559

  • -3735928559

  • “0xdeadbeef”

  • “-0xdeadbeef”

  • “deadbeef”

  • b’Þ­¾ï’

The binary representation is not allowed because there is no way to discriminate it from a valid hex-string (e.g. “0b11011110101011011011111011101111”).

btclib.var_bytes module

Varbytes encoding and decoding functions.

btclib.var_bytes.parse(stream: Union[BytesIO, bytes, str], forbid_zero_size: bool = False) bytes

Return the variable-length octets read from a stream.

btclib.var_bytes.serialize(octets: Union[bytes, str]) bytes

Return the var_int(len(octets)) + octets serialization of octets.

btclib.var_int module

Varint encoding and decoding functions.

A var_int (variable integer) is variable-length quantity that uses an arbitrary number of binary octets (eight-bit bytes) to represent an arbitrarily large integer. It is usually a base-128 (7 bits) representation of an unsigned integer with the addition of the eighth bit to mark continuation of bytes; it is used to save additional space for a resource constrained system.

This is the slightly different Bitcoin implementation, used in transaction data to indicate the number of upcoming fields or the length of the upcoming field.

Up to 0xfc, a var_int is just 1 byte; however, if the integer is greater than 0xfc, then it is expanded as [1 byte prefix][number]:

  • prefix 0xfd markes the next two bytes as the number;

  • prefix 0xfe markes the next four bytes as the number;

  • prefix 0xff markes the next eight bytes as the number.

btclib.var_int.parse(stream: Union[BytesIO, bytes, str]) int

Return the variable-length integer read from a stream.

btclib.var_int.serialize(i: int) bytes

Return the var_int bytes encoding of an integer.

Module contents

__init__ module for the btclib package.