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

  • 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)
  • 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_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)

Validate the bech32 string, and determine HRP and data. Only standard data size of 20 and 32 bytes are excepted

  • 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() and addr_bech32_to_pubkeyhash() method

  • 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.bip38_decrypt(encrypted_privkey, passphrase)[source]

BIP0038 non-ec-multiply decryption. Returns WIF private key. Based on code from This method is called by Key class init function when importing BIP0038 key.

  • encrypted_privkey (str) – Encrypted private key using WIF protected key format
  • passphrase (str) – Required passphrase for decryption
Return tupple (bytes, bytes):

(Private Key bytes, 4 byte address hash for verification)

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

BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted private key Based on code from

  • private_hex (str) – Private key in hex format
  • address (str) – Address string
  • passphrase (str) – Required passphrase for encryption
  • flagbyte (bytes) – Flagbyte prefix for WIF
Return str:

BIP38 passphrase 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


>>> change_base('FF', 16, 10)
>>> change_base('101', 2, 10)

Convert base-58 public WIF of a key to hexadecimal format

>>> change_base('xpub661MyMwAqRbcFnkbk13gaJba22ibnEdJS7KAMY99C4jBBHMxWaCBSTrTinNTc9G5LTFtUqbLpWnzY5yPTNEF9u8sB1kBSygy4UsvuViAmiR', 58, 16)

Convert base-58 address to public key hash: ‘00’ + length ‘21’ + 20 byte key

>>> change_base('142Zp9WZn9Fh4MV8F3H5Dv4Rbg7Ja1sPWZ', 58, 16)

Convert to 2048-base, for example a Mnemonic word list. Will return a list of integers

>>> change_base(100, 16, 2048)
  • chars (any) – Input string
  • base_from (int) – 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 a 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.

  • signature (bytes) – DER signature
  • as_hex (bool) – Output as hexstring
Return bytes, str:


bitcoinlib.encoding.convertbits(data, frombits, tobits, pad=True)[source]

‘General power-of-2 base conversion’


  • data (list, bytearray) – 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.

  • 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

  • string (bytes) – String to be hashed
  • as_hex (bool) – Return value as hexadecimal string. Default is False
Return bytes, str:

Creates a RIPEMD-160 + SHA256 hash of the input string

Parameters:string (bytes) – Script
Return bytes:RIPEMD-160 hash of script

Convert integer to CompactSize Variable length integer in byte format.

See for specification

>>> to_hexstring(int_to_varbyteint(10000))
Parameters:inp (int) – Integer to convert
Returns:byteint: 1-9 byte representation as integer

Normalize a string to the default NFKD unicode format See

Parameters:string (bytes, bytearray, str) – string value
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

  • var (str, byte, bytearray, unicode) – input variable in any format
  • base (int) – specify variable format, i.e. 10 for decimal, 16 for hex

Normalized var in string for Python 2, bytes for Python 3, decimal for base10

bitcoinlib.encoding.pubkeyhash_to_addr(pubkeyhash, prefix=None, encoding='base58')[source]

Convert public key hash to base58 encoded address

Wrapper for the pubkeyhash_to_addr_base58() and pubkeyhash_to_addr_bech32() method

  • 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
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')
  • 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')[source]

Encode public key hash as bech32 encoded (segwit) address

>>> pubkeyhash_to_addr_bech32('21c1bc695a56f47991e95ff26856e50f78d3c118')

Format of address is prefix/hrp + seperator + bech32 address + checksum

For more information see BIP173 proposal at

  • pubkeyhash (str, bytes, bytearray) – 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 its not standard.
Return str:

Bech32 encoded address


Convert String, Unicode or Bytes to Python 2 and 3 compatible ByteArray

Parameters:string (bytes, str, bytearray) – String, Unicode, Bytes or ByteArray
Return bytearray:
bitcoinlib.encoding.to_bytes(string, unhexlify=True)[source]

Convert String, Unicode or ByteArray to Bytes

  • string (str, unicode, bytes, bytearray) – String to convert
  • unhexlify (bool) – Try to unhexlify hexstring

Bytes var


Convert Bytes or ByteArray to hexadecimal string

>>> to_hexstring('ªÝ')
Parameters:string (bytes, bytearray, str) – Variable to convert to hex string

Convert CompactSize Variable length integer in byte format to integer.

See for specification

>>> varbyteint_to_int(to_bytes('fd1027'))
(10000, 3)
Parameters:byteint (bytes, list, bytearray) – 1-9 byte representation
Return (int, int):
 tuple wit converted integer and size

Convert string to variably sized string: Bytestring preceded with length byte

>>> to_hexstring(varstr(to_bytes('5468697320737472696e67206861732061206c656e677468206f66203330')))
Parameters:string (bytes, str) – String input
Return bytes:varstring