bits package

Subpackages

Submodules

bits.base58

Base58(check) encoding / decoding

bits.base58.base58check(data: bytes) bytes

Encode data as base58check encoding used in Bitcoin addresses # https://en.bitcoin.it/wiki/Base58Check_encoding :param data: bytes, data to encode

Returns:

base58check encoded data

>>> base58check(b"hello world")
b'3vQB7B6MrGQZaxCuFg4oh'
bits.base58.base58check_decode(addr_: bytes) bytes

Decode base58check encoded data :param data: bytes, data to decode

Returns:

decoded data

>>> base58check_decode(b"3vQB7B6MrGQZaxCuFg4oh")
b'hello world'
bits.base58.base58decode(data: bytes) bytes

Decode base58 encoded data :param data: bytes, data to decode

Returns:

decoded data

>>> base58decode(b"StV1DL6CwTryKyV")
b'hello world'
bits.base58.base58encode(data: bytes) bytes

Encode data in base58 format :param data: bytes, data to encode

Returns:

base58 encoded data

>>> base58encode(b"hello world")
b'StV1DL6CwTryKyV'
bits.base58.is_base58check(data: bytes)

Check if data is base58check encoded :param data: bytes, data to check

Returns:

True if base58check encoded, else False

>>> is_base58check(b"DthHcFYf2SzzprfBcpKfTG")
True
>>> is_base58check(b"2yGEbwRFyhPZZckJm")
False

bits.blockchain

blockchain lulz :P

bits.blockchain.block_deser(block: bytes) dict

Deserialize block data :param block: bytes, block data

bits.blockchain.block_header(version: int, prev_blockheaderhash: bytes, merkle_root_hash: bytes, ntime: int, nBits: bytes, nNonce: int) bytes

Create serialized block header from args

# https://developer.bitcoin.org/reference/block_chain.html#block-headers

Parameters:
  • version – int, block version

  • prev_blockheaderhash – bytes, hash of previous block header

  • merkle_root_hash – bytes, merkle root hash

  • ntime – int, Unix epoch time

  • nBits – int, nBits encoding of target threshold

  • nNonce – int, arbitrary number

Returns:

block header

>>> merkle_root_hash = bytes.fromhex("3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a")
>>> nBits = (0x1D00FFFF).to_bytes(4, "little")
>>> bits.crypto.hash256(block_header(1, NULL_32, merkle_root_hash, 1231006505, nBits, 2083236893)).hex()
'6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000'
bits.blockchain.block_header_deser(blk_hdr: bytes) dict
bits.blockchain.block_ser(blk_hdr: bytes, txns: List[bytes]) bytes
bits.blockchain.difficulty(target: int, network: str = 'mainnet') float

difficulty = difficulty_1_target / current_target https://en.bitcoin.it/wiki/Difficulty

bits.blockchain.genesis_block()

Hard coded genesis block - mainnet >>> gb = genesis_block() >>> header = gb[:80] >>> import hashlib >>> hashlib.sha256(hashlib.sha256(header).digest()).digest()[::-1].hex() ‘000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f’

bits.blockchain.genesis_coinbase_tx()
bits.blockchain.merkle_root(txns: List[bytes]) bytes

merkle root from a list of transaction ids https://developer.bitcoin.org/reference/block_chain.html#merkle-trees

Parameters:

txns – list[bytes], list of txids

bits.blockchain.target_threshold(nBits: bytes) int

Calculate target threshold from compact nBits # https://developer.bitcoin.org/reference/block_chain.html#target-nbits :param nBits: bytes, rpc byte order

>>> target = target_threshold(bytes.fromhex("207fffff"))
>>> hex(target)
'0x7fffff0000000000000000000000000000000000000000000000000000000000'

bits.config

class bits.config.Config(**kwargs)

Bases: object

load_config(config_dir: str = '/home/runner/.bits')

Look for configuration file in ~/.bits and load, if present

update(**kwargs)

Update Config with kwargs

Avoid applying keys not defined in __init__ by re-instantiating

bits.constants

Global constants

bits.crypto

bits.crypto.hash160(msg: bytes) bytes
bits.crypto.hash256(msg: bytes) bytes
bits.crypto.ripemd160(msg: bytes) bytes
bits.crypto.sha256(msg: bytes) bytes

bits.ecmath

Elliptic curve math

bits.ecmath.add_mod_p(x: int, y: int, p: int = 115792089237316195423570985008687907853269984665640564039457584007908834671663) int

x + y (mod p)

>>> add_mod_p(SECP256K1_P - 1, 3)
2
bits.ecmath.div_mod_p(x: int, y: int, p: int = 115792089237316195423570985008687907853269984665640564039457584007908834671663) int

x / y (mod p) Using Fermat’s little thereom, mod p x / y = x * (y ** -1) x / y = x * (y ** (p - 2))

bits.ecmath.mul_mod_p(x: int, y: int, p: int = 115792089237316195423570985008687907853269984665640564039457584007908834671663) int

x * y (mod p)

bits.ecmath.point_add(p1: Tuple[int, int], p2: Tuple[int, int], a: int = 0, b: int = 7) Tuple[int, int]
bits.ecmath.point_is_on_curve(x: int, y: int, a: int = 0, b: int = 7) bool

Returns True if (x, y) is on elliptic curve given by y^2 = x^3 + ax + b, else False >>> point_is_on_curve(SECP256K1_Gx, SECP256K1_Gy) True

bits.ecmath.point_negate(p: Tuple[int, int], a: int = 0, b: int = 7) Tuple[int, int]
Returns:

-p

bits.ecmath.point_scalar_mul(k: int, P: Tuple[int, int], a: int = 0, b: int = 7) Tuple[int, int]

Point multiplication using double and add algorithm kP where k has n binary digits O(k)

bits.ecmath.pow_mod_p(x: int, y: int, p: int = 115792089237316195423570985008687907853269984665640564039457584007908834671663) int

x ** y (mod p)

bits.ecmath.sign(key: int, digest: int, N: int = 115792089237316195423570985008687907852837564279074904382605163141518161494337, G: Tuple[int, int] = (55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424)) Tuple[int, int]
bits.ecmath.sqrt_mod_p(x: int, p: int = 115792089237316195423570985008687907853269984665640564039457584007908834671663) int
bits.ecmath.sub_mod_p(x: int, y: int, p: int = 115792089237316195423570985008687907853269984665640564039457584007908834671663) int

x - y (mod p)

>>> hex(sub_mod_p(0, 1))
'0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e'
bits.ecmath.verify(r: int, s: int, point: Tuple[int, int], digest: int, N: int = 115792089237316195423570985008687907852837564279074904382605163141518161494337, G: Tuple[int, int] = (55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424)) bool
bits.ecmath.y_from_x(x: int, a: int = 0, b: int = 7) int

Find y from x y^2 = x^3 + ax + b

bits.integrations

Utils for various integrations with local bitcoind node

bits.integrations.generate_funded_keys(count: int, compressed_pubkey: bool = False, network: str = 'regtest', rpc_url: str = '', rpc_datadir: str = '', rpc_user: str = '', rpc_password: str = '') Iterator[Tuple[bytes, bytes]]

Generate keys which receive coinbase reward sent to p2pkh address :param count: int, number of funded keys to generate :param compressed_pubkey: bool, wether key should correspond to compressed pubkey for recv addr :param network: str, bitcoin network

Returns:

iterator of tuples (key, addr)

bits.integrations.median_time(rpc_url: str = '', rpc_datadir: str = '', rpc_user: str = '', rpc_password: str = '') int

Returns the median time of the last 11 blocks

bits.integrations.mine_block(recv_addr: bytes, rpc_url: str = '', rpc_datadir: str = '', rpc_user: str = '', rpc_password: str = '')

Retrieve all raw mempool transactions and submit in a block. Regtest mode is inferred from getdifficulty rpc. Commits to witness root per BIP 141 via coinbase tx, if necessary :param recv_addr: bytes, addr to receive block reward

bits.keys

bits.keys.key() bytes

Generate a private key

bits.keys.pub(privkey: bytes, compressed: bool = False) bytes

Calculate public point and return pubkey :param privkey: bytes, private key

bits.p2p

P2P and stuff

https://developer.bitcoin.org/devguide/p2p_network.html https://developer.bitcoin.org/reference/p2p_networking.html https://en.bitcoin.it/wiki/Network https://en.bitcoin.it/wiki/Protocol_documentation

class bits.p2p.Node(seeds: List[str] = [], protocol_version: int = 70015, services: int = 1, relay: bool = True, datadir: str = '.bits/blocks', serve_rpc: bool = False, rpc_bind: Tuple[str, int] = (), rpc_username: str | None = None, rpc_password: str | None = None)

Bases: object

connect_peer(host: str | bytes, port: int)

Connect to peer; open socket and send version message

handle_command(peer_no: int, command: bytes, payload: dict)
handle_feefilter_command(peer_no: int, command: bytes, payload: dict)
handle_getheaders_command(peer_no: int, command: bytes, payload: dict)
handle_inv_command(peer_no: int, command: bytes, payload: dict)
handle_ping_command(peer_no: int, command: bytes, payload: dict)

Handle ping command by sending a ‘pong’ message

handle_sendheaders_command(peer_no: int, command: bytes, payload: dict)
handle_verack_command(peer_no: int, command: bytes, payload: dict)
handle_version_command(peer_no: int, command: bytes, payload: dict)
ibd()

Initial Block Download

recv_loop(peer_no: int)

Recv loop; receive msg, add to msg queue

start()
start_rpc_server()
stop()
class bits.p2p.PeerThread(**kwargs)

Bases: Thread

exit()
bits.p2p.addr_payload(count: int, addrs: List[bytes]) bytes
Parameters:
  • count – int, number of ip address (max 1,000)

  • addrs – List[bytes], ip addresses in network ip addr format

bits.p2p.auth_request_handler_factory(username: str, password: str)

Return subclass of SimpleXMLRPCRequestHandler for checking Basic Auth :param username: str, basic auth username :param password: str, basic auth password

Returns:

BasicAuthRequestHandler

bits.p2p.getblocks_payload(block_header_hashes: List[bytes], protocol_version: int = 70015) bytes
bits.p2p.getheaders_payload(protocol_version: int, hash_count: int, block_header_hashes: List[bytes], stop_hash: bytes) bytes
bits.p2p.headers_payload(count: int, headers: List[bytes]) bytes

Serialized headers message payload :param count: int, number of block headers - max of 2000 :param headers: List[bytes], block headers

bits.p2p.inv_payload(count: int, inventories: List[bytes]) bytes
bits.p2p.inventory(type_id: str, hash: bytes) bytes

inventory data structure https://developer.bitcoin.org/glossary.html#term-Inventory

bits.p2p.msg_ser(start_bytes: bytes, command: str | bytes, payload: bytes = b'') bytes

Serialized p2p message

bits.p2p.network_ip_addr(time: int, services: bytes, ip_addr: bytes, port: int) bytes

Network ip address format # https://developer.bitcoin.org/reference/p2p_networking.html#addr

bits.p2p.parse_addr_payload(payload: bytes) dict
bits.p2p.parse_feefilter_payload(payload: bytes) dict
bits.p2p.parse_getheaders_payload(payload: bytes) dict
bits.p2p.parse_inv_payload(payload: bytes) dict
bits.p2p.parse_inventory(inventory_: bytes) dict
bits.p2p.parse_network_ip_addr(payload: bytes) dict
bits.p2p.parse_payload(command, payload)
bits.p2p.parse_ping_payload(payload: bytes) dict
bits.p2p.parse_sendcmpct_payload(payload: bytes) dict
bits.p2p.parse_version_payload(versionpayload_: bytes) dict
bits.p2p.ping_payload(nonce: int) bytes
bits.p2p.recv_msg(sock: socket) Tuple[bytes, bytes, bytes]

Recv and deserialize message ( header + optional payload )

bits.p2p.set_magic_start_bytes(network: str = 'mainnet')
bits.p2p.version_payload(start_height: int, addr_recv_port: int, addr_trans_port: int, protocol_version: int = 70015, services: int = 1, relay: bool = True) bytes
bits.p2p.write_blocks_to_disk(blocks: List[bytes], datadir: str)

Write blocks to disk

observe max_blockfile_size & number files blk00000.dat, blk00001.dat, …

Parameters:
  • blocks – List[bytes]

  • datadir – str, path to blockchain datadir

bits.pem

PEM / DER / ASN.1

bits.pem.decode_base64_pem(pem: bytes) bytes

Decode pem base64 data inspiration from ssl.PEM_cert_to_DER_cert but more general

bits.pem.decode_pem(pem_: bytes)

Decode pem and parse ASN.1

bits.pem.encode_oid(oid: str) bytes

https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier >>> encode_oid(“1.2.840.10045.2.1”).hex() ‘2a8648ce3d0201’ >>> encode_oid(“1.3.6.1.4.1.311.21.20”).hex() ‘2b0601040182371514’ >>> encode_oid(“1.3.132.0.10”).hex() ‘2b8104000a’

bits.pem.encode_parsed_asn1(parsed_data: list) bytes

Inverse of parse_asn1 >>> sig = bytes.fromhex(“3046022100807ebfaf104a08061044a11109873af5c16cfb2e4e4ec69b47bd4dfcf3b630d4022100bbc3387cc3c5fd83d672eee20c40161099f8df44e135ca96a9b8650dbcbfe1bc”) >>> parsed = parse_asn1(sig) >>> encoded = encode_parsed_asn1(parsed[0]) >>> assert sig == encoded

bits.pem.encode_parsed_asn1_val(tag: int, parsed_val: list | bytes) bytes
bits.pem.encode_pem(der_: bytes, header: bytes = b'-----BEGIN CERTIFICATE-----', footer: bytes = b'-----END CERTIFICATE-----') bytes
bits.pem.parse_asn1(data: bytes)

Parse ASN.1 data Recursive for SEQUENCE (OF) tag

bits.pem.parse_asn1_value(tag: int, value: bytes)

Parse ASN.1 tag’s value

bits.pem.parse_oid(data: bytes) str
>>> parse_oid(bytes.fromhex("2a8648ce3d0201"))
'1.2.840.10045.2.1'
>>> parse_oid(bytes.fromhex("2b8104000a"))
'1.3.132.0.10'

bits.rpc

RPC

bits.rpc.rpc_method(method, *params, rpc_url='', rpc_user='', rpc_password='', rpc_datadir='') dict | str

Call a method (w/ params) to bitcoind node

bits.tx

Utilities for transactions

https://developer.bitcoin.org/reference/transactions.html

bits.tx.coinbase_tx(coinbase_script: bytes, script_pubkey: bytes, block_reward: int | None = None, block_height: int | None = None, regtest: bool = False, witness_merkle_root_hash: bytes | None = None) bytes

Create coinbase transaction by supplying arbitrary transaction input coinbase scriptsig and transaction output spending scriptpubkey.

Optional block height (for version 2 blocks per BIP34) and block reward arguments may be provided. If block height is specified, the block reward must be <= max reward, and will be inferred to be == max reward if left unspecified.

Parameters:
  • coinbase_script – bytes, txin scriptsig of arbitrary data not exceeding 100 bytes

  • script_pubkey – bytes, txout scriptpubkey

  • block_reward – Optional[int], txout value in satoshis

  • block_height – Optional[int], block height per BIP34

  • regtest – bool, set True for regtest to calculate blocks per halving correctly

  • witness_merkle_root_hash – Optional[bytes], per BIP141 specify witness merkle root, to be committed in a txout of the coinbase transaction

Returns:

coinbase tx

bits.tx.coinbase_txin(coinbase_script: bytes, sequence: bytes = b'\xff\xff\xff\xff', block_height: int | None = None) bytes

Create coinbase txin

Parameters:
  • coinbase_script – bytes, arbitrary data not exceeding 100 bytes

  • block_height – bytes, block height of this block in script language (now required per BIP34)

bits.tx.outpoint(txid_: bytes, index: int) bytes

# https://developer.bitcoin.org/reference/transactions.html#outpoint-the-specific-part-of-a-specific-output

Parameters:

txid – bytes, txid in internal byte order

bits.tx.send_tx(sender_addr: bytes, recipient_addr: bytes, change_addr: bytes | None = None, sender_keys: List[bytes] = [], sighash_flag: int | None = None, send_fraction: float = 1.0, miner_fee: int = 1000, version: int = 1, locktime: int = 0, rpc_url: str = '', rpc_datadir: str = '', rpc_user: str = '', rpc_password: str = '') bytes

Create raw transaction which sends funds from addr to addr, with optional change address. Depends on configured Bitcoin Core RPC node for UTXO discovery.

Parameters:
  • sender_addr – bytes, send from this address

  • recipient_addr – bytes, send to this address

  • change_addr – Optional[bytes], send change to this address

  • sender_keys – List[bytes], unlocking WIF key(s) corresponding to sender_addr Using this causes signature operations to occur. Omit to return the unsigned transaction

  • sighash_flag – Optional[int], sighash_flag, required if providing sender_keys

  • send_fraction – float, fraction of UTXO value to send to recipient, leftover is sent to change_addr if present, else returned to sender_addr

  • miner_fee – int, amount (in satoshis) to include as miner fee

  • version – int, transaction version

  • locktime – int, transaction locktime

bits.tx.tx(txins: List[bytes], txouts: List[bytes], version: int = 1, locktime: int = 0, script_witnesses: List[bytes] = []) bytes

Transaction serialization, optional SegWit per BIP 141

bits.tx.tx_deser(tx_: bytes, include_raw: bool = False) Tuple[dict, bytes]

Deserialize tx data

Parameters:
  • tx – bytes, tx data

  • include_raw – bool, if True, include raw hex transaction in dict

Returns:

tuple, (deserialized tx, leftove )

bits.tx.txid(internal byte order)
bits.tx.txin(prev_outpoint: bytes, script_sig: bytes, sequence: bytes = b'\xff\xff\xff\xff') bytes
bits.tx.txin_deser(txin_: bytes) Tuple[dict, bytes]
bits.tx.txout(value: int, script_pubkey: bytes) bytes
bits.tx.txout_deser(txout_: bytes) Tuple[dict, bytes]

bits.utils

bits.utils.assert_addr(addr_: bytes) bool
bits.utils.assert_valid_segwit(hrp: bytes, witness_version: int, witness_program: bytes) bool

Assert valid SegWit address per BIP173

bits.utils.compact_size_uint(integer: int) bytes

https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers

bits.utils.compressed_pubkey(pubkey_: bytes) bytes
Returns:

compressed pubkey from (un)compressed pubkey

bits.utils.compute_point(privkey_: bytes) Tuple[int]

Compute (x, y) public key point from private key

>>> compute_point(bytes.fromhex('c3e7b149ad167dc83a5653a9eaae1cc50b36793bfdc050d8efab831d04b876a7'))
(88828742484815144809405969644853584197652586004550817561544596238129398385750, 53299775652378523772666068229018059902560429447534834823349875811815397393717)
bits.utils.decode_segwit_addr(addr: bytes, __support_bip350: bool = True) Tuple[bytes, int, bytes]

Decode SegWit address. See BIP173 and BIP350

bits.utils.der_decode_sig(der: bytes) Tuple[int, int]
bits.utils.der_encode_sig(r: int, s: int) bytes
bits.utils.ensure_sig_low_s(sig_: bytes) bytes

Ensure DER encoded signature has low enough s value https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures

OpenSSL does not ensure this by default https://bitcoin.stackexchange.com/a/59826/135678 Apparently, Bitcoin Core used to do this to get around it https://github.com/bitcoin/bitcoin/blob/v0.9.0/src/key.cpp#L204L224

Essentially just use s = N - s if s > N / 2

bits.utils.is_addr(addr_: bytes) bool
bits.utils.is_point(pubkey_: bytes)
bits.utils.is_segwit_addr(addr_: bytes) bool

Alterative to assert_valid_segwit that catches potential error :returns: bool, True if valid segwit address else False

bits.utils.parse_compact_size_uint(payload: bytes) Tuple[int, bytes]

This function expects a compact size uint at the beginning of payload. Since compact size uints are variable in size, this function will observe the first byte, parse the necessary subsequent bytes, and return, as a tuple, the parsed integer followed by the rest of the payload (i.e. the remaining unparsed payload)

bits.utils.pem_decode_key(pem_: bytes) Tuple[bytes, bytes] | Tuple[bytes]

Decode from pem / der encoded EC private / public key :returns: (privkey, pubkey) or pubkey, respectively

bits.utils.pem_encode_key(key_: bytes) bytes

Encode (pub)key as pem

bits.utils.point(pubkey_: bytes) Tuple[int]

Return (x, y) point from SEC1 public key

>>> point(bytes.fromhex('03c463495bd336bc29636ed6d8c1cf162b45d76adda4df9499370dded242758c56'))
(88828742484815144809405969644853584197652586004550817561544596238129398385750, 53299775652378523772666068229018059902560429447534834823349875811815397393717)
bits.utils.privkey_int(privkey_: bytes) int
bits.utils.pubkey(x: int, y: int, compressed=False) bytes

Returns SEC1 pubkey from point (x, y)

>>> pubkey(*(88828742484815144809405969644853584197652586004550817561544596238129398385750, 53299775652378523772666068229018059902560429447534834823349875811815397393717), compressed=True).hex()
'03c463495bd336bc29636ed6d8c1cf162b45d76adda4df9499370dded242758c56'
bits.utils.pubkey_from_pem(pem_: bytes)
bits.utils.pubkey_hash(pubkey_: bytes) bytes

Returns pubkeyhash as used in P2PKH scriptPubKey e.g. RIPEMD160(SHA256(pubkey))

bits.utils.script_hash(redeem_script: bytes) bytes

HASH160(redeem_script)

bits.utils.segwit_addr(data: bytes, witness_version: int = 0, network: str = 'mainnet') bytes

Defined per BIP173 bech32 https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#segwit-address-format and bech32m per BIP350 https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki

bits.utils.sig(key: bytes, msg: bytes, sighash_flag: int | None = None, msg_preimage: bool = False) bytes

Create DER encoded Bitcoin signature from message, optional sighash_flag

Sighash_flag gets appended to msg, this data is then hashed with HASH256,

signed, and DER-encoded

Parameters:
  • key – bytes, private key

  • msg – bytes,

  • sighash_flag – Optional[int], appended to msg before HASH256

  • msg_preimage – whether msg is pre-image or not pre-image already has 4 byte sighash flag appended if msg_preimage, msg is still hashed, and 1 byte sighash_flag still appended after signing/der-encoding

Returns:

bytes, signature(HASH256(msg + sighash_flag))

bits.utils.sig_verify(sig_: bytes, pubkey_: bytes, msg: bytes, msg_preimage: bool = False) str
bits.utils.to_bitcoin_address(payload: bytes, addr_type: str = 'p2pkh', network: str = 'mainnet', witness_version: int | None = None) bytes

Encode payload as bitcoin address invoice (optional segwit)

Parameters:
  • payload – bytes, pubkey_hash or script_hash

  • addr_type – str, address type, “p2pkh” or “p2sh”. results in p2wpkh or p2wsh, respectively when combined with witness_version

  • network – str, mainnet, testnet, or regtest

  • witness_version – Optional[int], witness version for native segwit addresses usage implies p2wpkh or p2wsh, accordingly

Returns:

base58 (or bech32 segwit) encoded bitcoin address

bits.utils.wif_decode(wif_: bytes, return_dict=False) Tuple[bytes, bytes, bytes] | dict
Returns:

version, key, data

bits.utils.wif_encode(privkey_: bytes, addr_type: str = 'p2pkh', network: str = 'mainnet', data: bytes = b'') bytes

WIF encoding https://en.bitcoin.it/wiki/Wallet_import_format

** Extended WIF spec to include redeemscript or other script data

at suffix

Parameters:
  • privkey – bytes, private key

  • addr_type – str, address type. choices => [“p2pkh”, “p2wpkh”, “p2sh-p2wpkh”, “p2pk”, “multisig”, “p2sh”, “p2wsh”, “p2sh-p2wsh”]

  • network – str, e.g. mainnet, testnet, or regtest

  • data – bytes, appended to key prior to base58check encoding. For p2(w)sh address types, supply redeem script. For p2pk(h) address types, use 0x01 to associate WIF key with a compressed pubkey, omit for uncompressed pubkey. For multsig, supply redeem script For p2wpkh & p2sh-p2wpkh, data shall be omitted since compressed pubkey (and redeem_script) are implied For p2sh-p2wsh, supply witness_script

bits.utils.witness_script_hash(witness_script: bytes) bytes

SHA256(witness_script)

Module contents

bits.init_logging(bitsconfig: dict = {})

Initialize logging

bits.read_bytes(file_: IO | None = None, input_format: str = 'raw') bytes

Read from optional file or stdin and convert to bytes

Any newlines will be stripped from beginning / end for hex and bin, only. Raw is read without any additional processing.

Furthermore, hex and bin will be left-zero-padded to the nearest byte, if they are not provided in 8-bit multiples.

Parameters:
  • file – Optional[IO], optional file object - otherwise stdin is used

  • input_format – str, “raw”, “hex”, or “bin”

Returns:

data as bytes

bits.set_log_level(log_level: str)

Set log level on all handlers

bits.write_bytes(data: bytes, file_: IO | None = None, output_format: str = 'raw')

Write bytes to file or stdout. bin/hex output format will have newline appended

Parameters:
  • data – bytes, bytes to print

  • file – Optional[IO], file object to write to, if None uses stdout

  • output_format – str, ‘raw’, ‘bin’, or ‘hex’