bitcoinlib.encoding module
- exception bitcoinlib.encoding.EncodingError(msg='')[source]
Bases:
Exception
Log and raise encoding errors
- class bitcoinlib.encoding.Quantity(value, units='', precision=3)[source]
Bases:
object
Class to convert very large or very small numbers to a readable format.
Provided value is converted to number between 0 and 1000, and a metric prefix will be added.
>>> # Example - the Hashrate on 10th July 2020 >>> str(Quantity(122972532877979100000, 'H/s')) '122.973 EH/s'
Convert given value to number between 0 and 1000 and determine metric prefix
- Parameters
value (int, float) – Value as integer in base 0
units (str) – Base units, so ‘g’ for grams for instance
precision (int) – Number of digits after the comma
- bitcoinlib.encoding.addr_base58_to_pubkeyhash(address, as_hex=False)[source]
Convert Base58 encoded address to public key hash
>>> addr_base58_to_pubkeyhash('142Zp9WZn9Fh4MV8F3H5Dv4Rbg7Ja1sPWZ', as_hex=True) '21342f229392d7c9ed82c932916cee6517fbc9a2'
- Parameters
address (str, bytes) – Crypto currency address in base-58 format
as_hex (bool) – Output as hexstring
- Return bytes, str
Public Key Hash
- bitcoinlib.encoding.addr_bech32_checksum(bech)[source]
Get bech32 checksum. Returns 1 for bech32 addresses and 0x2bc830a3 for bech32m addresses. More info https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki
>>> addr_bech32_checksum('bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y') 734539939
- Parameters
bech (str) – Bech32 address to convert
- Return bool
Bech32 checksum
- bitcoinlib.encoding.addr_bech32_to_pubkeyhash(bech, prefix=None, include_witver=False, as_hex=False)[source]
Decode bech32 / segwit address to public key hash
>>> addr_bech32_to_pubkeyhash('bc1qy8qmc6262m68ny0ftlexs4h9paud8sgce3sf84', as_hex=True) '21c1bc695a56f47991e95ff26856e50f78d3c118'
Validate the bech32 string, and determine HRP and data. Only standard data size of 20 and 32 bytes are excepted
- Parameters
bech (str) – Bech32 address to convert
prefix (str) – Address prefix called Human-readable part. Default is None and tries to derive prefix, for bitcoin specify ‘bc’ and for bitcoin testnet ‘tb’
include_witver (bool) – Include witness version in output? Default is False
as_hex (bool) – Output public key hash as hex or bytes. Default is False
- Return str
Public Key Hash
- bitcoinlib.encoding.addr_to_pubkeyhash(address, as_hex=False, encoding=None)[source]
Convert base58 or bech32 address to public key hash
Wrapper for the
addr_base58_to_pubkeyhash()
andaddr_bech32_to_pubkeyhash()
method- Parameters
address (str) – Crypto currency address in base-58 format
as_hex (bool) – Output as hexstring
encoding (str) – Address encoding used: base58 or bech32. Default is base58. Try to derive from address if encoding=None is provided
- Return bytes, str
public key hash
- bitcoinlib.encoding.base58encode(inp)[source]
Convert bytes to base58 encode string
- Parameters
inp (bytes) – Input string
- Return str
- bitcoinlib.encoding.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 tupple (bytes, bytes)
(Private Key bytes, 4 byte address hash for verification)
- bitcoinlib.encoding.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.encoding.change_base(chars, base_from, base_to, min_length=0, output_even=None, output_as_list=None)[source]
Convert input chars from one numeric base to another. For instance from hexadecimal (base-16) to decimal (base-10)
From and to numeric base can be any base. If base is not found in definitions an array of index numbers will be returned
Examples:
>>> change_base('FF', 16, 10) 255 >>> change_base('101', 2, 10) 5
Convert base-58 public WIF of a key to hexadecimal format
>>> change_base('xpub661MyMwAqRbcFnkbk13gaJba22ibnEdJS7KAMY99C4jBBHMxWaCBSTrTinNTc9G5LTFtUqbLpWnzY5yPTNEF9u8sB1kBSygy4UsvuViAmiR', 58, 16) '0488b21e0000000000000000007d3cc6702f48bf618f3f14cce5ee2cacf3f70933345ee4710af6fa4a330cc7d503c045227451b3454ca8b6022b0f0155271d013b58d57d322fd05b519753a46e876388698a'
Convert base-58 address to public key hash: ‘00’ + length ‘21’ + 20 byte key
>>> change_base('142Zp9WZn9Fh4MV8F3H5Dv4Rbg7Ja1sPWZ', 58, 16) '0021342f229392d7c9ed82c932916cee6517fbc9a2487cd97a'
Convert to 2048-base, for example a Mnemonic word list. Will return a list of integers
>>> change_base(100, 16, 2048) [100]
- Parameters
chars (any) – Input string
base_from (int, str) – Base number or name from input. For example 2 for binary, 10 for decimal and 16 for hexadecimal
base_to (int) – Base number or name for output. For example 2 for binary, 10 for decimal and 16 for hexadecimal
min_length (int) – Minimal output length. Required for decimal, advised for all output to avoid leading zeros conversion problems.
output_even (bool) – Specify if output must contain an even number of characters. Sometimes handy for hex conversions.
output_as_list (bool) – Always output as list instead of string.
- Return str, list
Base converted input as string or list.
- bitcoinlib.encoding.convert_der_sig(signature, as_hex=True)[source]
Extract content from DER encoded string: Convert DER encoded signature to signature string.
- Parameters
signature (bytes) – DER signature
as_hex (bool) – Output as hexstring
- Return bytes, str
Signature
- bitcoinlib.encoding.convertbits(data, frombits, tobits, pad=True)[source]
‘General power-of-2 base conversion’
Source: https://github.com/sipa/bech32/tree/master/ref/python
- Parameters
data (list) – Data values to convert
frombits (int) – Number of bits in source data
tobits (int) – Number of bits in result data
pad (bool) – Use padding zero’s or not. Default is True
- Return list
Converted values
- bitcoinlib.encoding.der_encode_sig(r, s)[source]
Create DER encoded signature string with signature r and s value.
- Parameters
r (int) – r value of signature
s (int) – s value of signature
- Return bytes
- bitcoinlib.encoding.double_sha256(string, as_hex=False)[source]
Get double SHA256 hash of string
- Parameters
string (bytes) – String to be hashed
as_hex (bool) – Return value as hexadecimal string. Default is False
- Return bytes, str
- bitcoinlib.encoding.hash160(string)[source]
Creates a RIPEMD-160 + SHA256 hash of the input string
- Parameters
string (bytes) – Script
- Return bytes
RIPEMD-160 hash of script
- bitcoinlib.encoding.int_to_varbyteint(inp)[source]
Convert integer to CompactSize Variable length integer in byte format.
See https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer for specification
>>> int_to_varbyteint(10000).hex() 'fd1027'
- Parameters
inp (int) – Integer to convert
- Returns
byteint: 1-9 byte representation as integer
- bitcoinlib.encoding.normalize_string(string)[source]
Normalize a string to the default NFKD unicode format See https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization
- Parameters
string (bytes, str) – string value
- Returns
string
- bitcoinlib.encoding.normalize_var(var, base=256)[source]
For Python 2 convert variable to string
For Python 3 convert to bytes
Convert decimals to integer type
- Parameters
var (str, byte) – input variable in any format
base (int) – specify variable format, i.e. 10 for decimal, 16 for hex
- Returns
Normalized var in string for Python 2, bytes for Python 3, decimal for base10
- bitcoinlib.encoding.pubkeyhash_to_addr(pubkeyhash, prefix=None, encoding='base58', witver=0)[source]
Convert public key hash to base58 encoded address
Wrapper for the
pubkeyhash_to_addr_base58()
andpubkeyhash_to_addr_bech32()
method- Parameters
pubkeyhash (bytes, str) – Public key hash
prefix (str, bytes) – Prefix version byte of network, default is bitcoin ‘'
encoding (str) – Encoding of address to calculate: base58 or bech32. Default is base58
witver (int) – Witness version used. Currently used for Taproot addresses with witver=1. Ignored for base58 addresses
- Return str
Base58 or bech32 encoded address
- bitcoinlib.encoding.pubkeyhash_to_addr_base58(pubkeyhash, prefix=b'\x00')[source]
Convert public key hash to base58 encoded address
>>> pubkeyhash_to_addr_base58('21342f229392d7c9ed82c932916cee6517fbc9a2') '142Zp9WZn9Fh4MV8F3H5Dv4Rbg7Ja1sPWZ'
- Parameters
pubkeyhash (bytes, str) – Public key hash
prefix (str, bytes) – Prefix version byte of network, default is bitcoin ‘'
- Return str
Base-58 encoded address
- bitcoinlib.encoding.pubkeyhash_to_addr_bech32(pubkeyhash, prefix='bc', witver=0, separator='1', checksum_xor=1)[source]
Encode public key hash as bech32 encoded (segwit) address
>>> pubkeyhash_to_addr_bech32('21c1bc695a56f47991e95ff26856e50f78d3c118') 'bc1qy8qmc6262m68ny0ftlexs4h9paud8sgce3sf84'
Format of address is prefix/hrp + seperator + bech32 address + checksum
For more information see BIP173 proposal at https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
- Parameters
pubkeyhash (str, bytes) – Public key hash
prefix (str) – Address prefix or Human-readable part. Default is ‘bc’ an abbreviation of Bitcoin. Use ‘tb’ for testnet.
witver (int) – Witness version between 0 and 16
separator (str) – Separator char between hrp and data, should always be left to ‘1’ otherwise it’s not standard.
checksum_xor (int) – checksum 1 for bech32 v0 addresses and 0x2bc830a3 for bech32m v1+ addresses
- Return str
Bech32 encoded address
- bitcoinlib.encoding.read_varbyteint(s)[source]
Read variable length integer from BytesIO stream. Wrapper for the varbyteint_to_int method
- Parameters
s (BytesIO) – A binary stream
- Return int
- bitcoinlib.encoding.read_varbyteint_return(s)[source]
Read variable length integer from BytesIO stream. Return original converted bytes (to reconstruct transaction or script).
- Parameters
s (BytesIO) – A binary stream
- Return (int, bytes)
- bitcoinlib.encoding.to_bytes(string, unhexlify=True)[source]
Convert string, hexadecimal string to bytes
- Parameters
string (str, bytes) – String to convert
unhexlify (bool) – Try to unhexlify hexstring
- Returns
Bytes var
- bitcoinlib.encoding.to_hexstring(string)[source]
Convert bytes, string to a hexadecimal string. Use instead of built-in hex() method if format of input string is not known.
>>> to_hexstring(b'\x12\xaa\xdd') '12aadd'
- Parameters
string (bytes, str) – Variable to convert to hex string
- Returns
hexstring
- bitcoinlib.encoding.varbyteint_to_int(byteint)[source]
Convert CompactSize Variable length integer in byte format to integer.
See https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer for specification
>>> varbyteint_to_int(bytes.fromhex('fd1027')) (10000, 3)
- Parameters
byteint (bytes, list) – 1-9 byte representation
- Return (int, int)
tuple wit converted integer and size
- bitcoinlib.encoding.varstr(string)[source]
Convert string to variably sized string: Bytestring preceded with length byte
>>> varstr(to_bytes('5468697320737472696e67206861732061206c656e677468206f66203330')).hex() '1e5468697320737472696e67206861732061206c656e677468206f66203330'
- Parameters
string (bytes, str) – String input
- Return bytes
varstring