bitcoinlib.transactions module

class bitcoinlib.transactions.Input(prev_hash, output_n, keys=None, signatures=None, public_hash=b'', unlocking_script=b'', unlocking_script_unsigned=None, script_type=None, address='', sequence=4294967295, compressed=None, sigs_required=None, sort=False, index_n=0, value=0, double_spend=False, locktime_cltv=None, locktime_csv=None, key_path='', witness_type=None, witnesses=None, encoding=None, network='bitcoin')[source]

Bases: object

Transaction Input class, used by Transaction class

An Input contains a reference to an UTXO or Unspent Transaction Output (prev_hash + output_n). To spent the UTXO an unlocking script can be included to prove ownership.

Inputs are verified by the Transaction class.

Create a new transaction input

Parameters:
  • prev_hash (bytes, hexstring) – Transaction hash of the UTXO (previous output) which will be spent.
  • output_n (bytes, int) – Output number in previous transaction.
  • keys (list (bytes, str, Key)) – A list of Key objects or public / private key string in various formats. If no list is provided but a bytes or string variable, a list with one item will be created. Optional
  • signatures (list (bytes, str, Signature)) – Specify optional signatures
  • public_hash (bytes) – Public key hash or script hash. Specify if key is not available
  • unlocking_script (bytes, hexstring) – Unlocking script (scriptSig) to prove ownership. Optional
  • unlocking_script_unsigned (bytes, hexstring) – Unlocking script for signing transaction
  • script_type (str) – Type of unlocking script used, i.e. p2pkh or p2sh_multisig. Default is p2pkh
  • address (str, Address) – Address string or object for input
  • sequence (bytes, int) – Sequence part of input, you normally do not have to touch this
  • compressed (bool) – Use compressed or uncompressed public keys. Default is compressed
  • sigs_required (int) – Number of signatures required for a p2sh_multisig unlocking script
  • sort (boolean) – Sort public keys according to BIP0045 standard. Default is False to avoid unexpected change of key order.
  • index_n (int) – Index of input in transaction. Used by Transaction class.
  • value (int) – Value of input in smallest denominator, i.e. sathosis
  • double_spend (bool) – Is this input also spend in another transaction
  • locktime_cltv (int) – Check Lock Time Verify value. Script level absolute time lock for this input
  • locktime_csv (int) – Check Sequence Verify value.
  • key_path (str, list) – Key path of input key as BIP32 string or list
  • witness_type (str) – Specify witness/signature position: ‘segwit’ or ‘legacy’. Determine from script, address or encoding if not specified.
  • witnesses (list of bytes) – List of witnesses for inputs, used for segwit transactions for instance.
  • encoding (str) – Address encoding used. For example bech32/base32 or base58. Leave empty for default
  • network (str, Network) – Network, leave empty for default
as_dict()[source]

Get transaction input information in json format

Return dict:Json with output_n, prev_hash, output_n, type, address, public_key, public_hash, unlocking_script and sequence
update_scripts(hash_type=1)[source]

Method to update Input scripts.

Creates or updates unlocking script, witness script for segwit inputs, multisig redeemscripts and locktime scripts. This method is called when initializing a Input class or when signing an input.

Parameters:hash_type (int) – Specific hash type, default is SIGHASH_ALL
Return bool:Always returns True when method is completed
class bitcoinlib.transactions.Output(value, address='', public_hash=b'', public_key=b'', lock_script=b'', spent=False, output_n=0, script_type=None, encoding=None, spending_txid='', spending_index_n=None, network='bitcoin')[source]

Bases: object

Transaction Output class, normally part of Transaction class.

Contains the amount and destination of a transaction.

Create a new transaction output

An transaction outputs locks the specified amount to a public key. Anyone with the private key can unlock this output.

The transaction output class contains an amount and the destination which can be provided either as address, public key, public key hash or a locking script. Only one needs to be provided as the they all can be derived from each other, but you can provide as much attributes as you know to improve speed.

Parameters:
  • value (int) – Amount of output in smallest denominator of currency, for example satoshi’s for bitcoins
  • address (str, Address, HDKey) – Destination address of output. Leave empty to derive from other attributes you provide. An instance of an Address or HDKey class is allowed as argument.
  • public_hash (bytes, str) – Hash of public key or script
  • public_key (bytes, str) – Destination public key
  • lock_script (bytes, str) – Locking script of output. If not provided a default unlocking script will be provided with a public key hash.
  • spent (bool) – Is output already spent? Default is False
  • output_n (int) – Output index number, default is 0. Index number has to be unique per transaction and 0 for first output, 1 for second, etc
  • script_type (str) – Script type of output (p2pkh, p2sh, segwit p2wpkh, etc). Extracted from lock_script if provided.
  • encoding (str) – Address encoding used. For example bech32/base32 or base58. Leave empty to derive from address or default base58 encoding
  • spending_txid (str) – Transaction hash of input spending this transaction output
  • spending_index_n (int) – Index number of input spending this transaction output
  • network (str, Network) – Network, leave empty for default
as_dict()[source]

Get transaction output information in json format

Return dict:Json with amount, locking script, public key, public key hash and address
class bitcoinlib.transactions.Transaction(inputs=None, outputs=None, locktime=0, version=1, network='bitcoin', fee=None, fee_per_kb=None, size=None, hash='', date=None, confirmations=None, block_height=None, block_hash=None, input_total=0, output_total=0, rawtx='', status='new', coinbase=False, verified=False, witness_type='legacy', flag=None)[source]

Bases: object

Transaction Class

Contains 1 or more Input class object with UTXO’s to spent and 1 or more Output class objects with destinations. Besides the transaction class contains a locktime and version.

Inputs and outputs can be included when creating the transaction, or can be add later with add_input and add_output respectively.

A verify method is available to check if the transaction Inputs have valid unlocking scripts.

Each input in the transaction can be signed with the sign method provided a valid private key.

Create a new transaction class with provided inputs and outputs.

You can also create a empty transaction and add input and outputs later.

To verify and sign transactions all inputs and outputs need to be included in transaction. Any modification after signing makes the transaction invalid.

Parameters:
  • inputs (list (Input)) – Array of Input objects. Leave empty to add later
  • outputs (list (Output)) – Array of Output object. Leave empty to add later
  • locktime (int) – Transaction level locktime. Locks the transaction until a specified block (value from 1 to 5 million) or until a certain time (Timestamp in seconds after 1-jan-1970). Default value is 0 for transactions without locktime
  • version (bytes, int) – Version rules. Defaults to 1 in bytes
  • network (str, Network) – Network, leave empty for default network
  • fee (int) – Fee in smallest denominator (ie Satoshi) for complete transaction
  • fee_per_kb (int) – Fee in smallest denominator per kilobyte. Specify when exact transaction size is not known.
  • size (int) – Transaction size in bytes
  • hash (bytes) – Transaction hash used as transaction ID
  • date (datetime) – Confirmation date of transaction
  • confirmations (int) – Number of confirmations
  • block_height (int) – Block number which includes transaction
  • block_hash (str) – Hash of block for this transaction
  • input_total (int) – Total value of inputs
  • output_total (int) – Total value of outputs
  • rawtx (bytes) – Bytes representation of complete transaction
  • status (str) – Transaction status, for example: ‘new’, ‘incomplete’, ‘unconfirmed’, ‘confirmed’
  • coinbase (bool) – Coinbase transaction or not?
  • verified (bool) – Is transaction successfully verified? Updated when verified() method is called
  • witness_type (str) – Specify witness/signature position: ‘segwit’ or ‘legacy’. Determine from script, address or encoding if not specified.
  • flag (bytes, str) – Transaction flag to indicate version, for example for SegWit
add_input(prev_hash, output_n, keys=None, signatures=None, public_hash=b'', unlocking_script=b'', unlocking_script_unsigned=None, script_type=None, address='', sequence=4294967295, compressed=True, sigs_required=None, sort=False, index_n=None, value=None, double_spend=False, locktime_cltv=None, locktime_csv=None, key_path='', witness_type=None, encoding=None)[source]

Add input to this transaction

Wrapper for append method of Input class.

Parameters:
  • prev_hash (bytes, hexstring) – Transaction hash of the UTXO (previous output) which will be spent.
  • output_n (bytes, int) – Output number in previous transaction.
  • keys (bytes, str) – Public keys can be provided to construct an Unlocking script. Optional
  • signatures (bytes, str) – Add signatures to input if already known
  • public_hash (bytes) – Specify public hash from key or redeemscript if key is not available
  • unlocking_script (bytes, hexstring) – Unlocking script (scriptSig) to prove ownership. Optional
  • unlocking_script_unsigned (bytes, str) – TODO: find better name…
  • script_type (str) – Type of unlocking script used, i.e. p2pkh or p2sh_multisig. Default is p2pkh
  • address (str, Address) – Specify address of input if known, default is to derive from key or scripts
  • sequence (int, bytes) – Sequence part of input, used for timelocked transactions
  • compressed (bool) – Use compressed or uncompressed public keys. Default is compressed
  • sigs_required – Number of signatures required for a p2sh_multisig unlocking script
  • sigs_required – int
  • sort (boolean) – Sort public keys according to BIP0045 standard. Default is False to avoid unexpected change of key order.
  • index_n (int) – Index number of position in transaction, leave empty to add input to end of inputs list
  • value (int) – Value of input
  • double_spend (bool) – True if double spend is detected, depends on which service provider is selected
  • locktime_cltv (int) – Check Lock Time Verify value. Script level absolute time lock for this input
  • locktime_csv (int) – Check Sequency Verify value.
  • key_path (str, list) – Key path of input key as BIP32 string or list
  • witness_type (str) – Specify witness/signature position: ‘segwit’ or ‘legacy’. Determine from script, address or encoding if not specified.
  • encoding (str) – Address encoding used. For example bech32/base32 or base58. Leave empty to derive from script or script type
Return int:

Transaction index number (index_n)

add_output(value, address='', public_hash=b'', public_key=b'', lock_script=b'', spent=False, output_n=None, encoding=None, spending_txid=None, spending_index_n=None)[source]

Add an output to this transaction

Wrapper for the append method of the Output class.

Parameters:
  • value (int) – Value of output in smallest denominator of currency, for example satoshi’s for bitcoins
  • address (str, Address) – Destination address of output. Leave empty to derive from other attributes you provide.
  • public_hash (bytes, str) – Hash of public key or script
  • public_key (bytes, str) – Destination public key
  • lock_script (bytes, str) – Locking script of output. If not provided a default unlocking script will be provided with a public key hash.
  • spent (bool, None) – Has output been spent in new transaction?
  • output_n (int) – Index number of output in transaction
  • encoding (str) – Address encoding used. For example bech32/base32 or base58. Leave empty for to derive from script or script type
  • spending_txid (str) – Transaction hash of input spending this transaction output
  • spending_index_n (int) – Index number of input spending this transaction output
Return int:

Transaction output number (output_n)

as_dict()[source]

Return Json dictionary with transaction information: Inputs, outputs, version and locktime

Return dict:
as_json()[source]

Get current key as json formatted string

Return str:
calculate_fee()[source]

Get fee for this transaction in smallest denominator (i.e. Satoshi) based on its size and the transaction.fee_per_kb value

Return int:Estimated transaction fee
estimate_size(add_change_output=False)[source]

Get estimated vsize in for current transaction based on transaction type and number of inputs and outputs.

For old-style legacy transaction the vsize is the length of the transaction. In segwit transaction the witness data has less weight. The formula used is: math.ceil(((est_size-witness_size) * 3 + est_size) / 4)

Parameters:add_change_output (bool) – Assume an extra change output will be created but has not been created yet.
Return int:Estimated transaction size
static import_raw(rawtx, network='bitcoin', check_size=True)[source]

Import a raw transaction and create a Transaction object

Uses the transaction_deserialize method to parse the raw transaction and then calls the init method of this transaction class to create the transaction object

Parameters:
  • rawtx (bytes, str) – Raw transaction string
  • network (str, Network) – Network, leave empty for default
  • check_size (bool) – Check if not bytes are left when parsing is finished. Disable when parsing list of transactions, such as the transactions in a raw block. Default is True
Return Transaction:
 
info()[source]

Prints transaction information to standard output

raw(sign_id=None, hash_type=1, witness_type=None)[source]

Serialize raw transaction

Return transaction with signed inputs if signatures are available

Parameters:
  • sign_id (int, None) – Create raw transaction which can be signed by transaction with this input ID
  • hash_type (int) – Specific hash type, default is SIGHASH_ALL
  • witness_type (str) – Serialize transaction with other witness type then default. Use to create legacy raw transaction for segwit transaction to create transaction signature ID’s
Return bytes:
raw_hex(sign_id=None, hash_type=1, witness_type=None)[source]

Wrapper for raw() method. Return current raw transaction hex

Parameters:
  • sign_id (int) – Create raw transaction which can be signed by transaction with this input ID
  • hash_type (int) – Specific hash type, default is SIGHASH_ALL
  • witness_type (str) – Serialize transaction with other witness type then default. Use to create legacy raw transaction for segwit transaction to create transaction signature ID’s
Return hexstring:
 
sign(keys=None, tid=None, multisig_key_n=None, hash_type=1, _fail_on_unknown_key=True)[source]

Sign the transaction input with provided private key

Parameters:
  • keys (HDKey, Key, bytes, list) – A private key or list of private keys
  • tid (int) – Index of transaction input
  • multisig_key_n (int) – Index number of key for multisig input for segwit transactions. Leave empty if not known. If not specified all possibilities will be checked
  • hash_type (int) – Specific hash type, default is SIGHASH_ALL
  • _fail_on_unknown_key (bool) – Method fails if public key from signature is not found in public key list
Return None:
signature(sign_id=None, hash_type=1, witness_type=None)[source]

Serializes transaction and calculates signature for Legacy or Segwit transactions

Parameters:
  • sign_id (int) – Index of input to sign
  • hash_type (int) – Specific hash type, default is SIGHASH_ALL
  • witness_type (str) – Legacy or Segwit witness type? Leave empty to use Transaction witness type
Return bytes:

Transaction signature

signature_hash(sign_id=None, hash_type=1, witness_type=None, as_hex=False)[source]

Double SHA256 Hash of Transaction signature

Parameters:
  • sign_id (int) – Index of input to sign
  • hash_type (int) – Specific hash type, default is SIGHASH_ALL
  • witness_type (str) – Legacy or Segwit witness type? Leave empty to use Transaction witness type
  • as_hex (bool) – Return value as hexadecimal string. Default is False
Return bytes:

Transaction signature hash

signature_segwit(sign_id, hash_type=1)[source]

Serialize transaction signature for segregated witness transaction

Parameters:
  • sign_id (int) – Index of input to sign
  • hash_type (int) – Specific hash type, default is SIGHASH_ALL
Return bytes:

Segwit transaction signature

txid
update_totals()[source]

Update input_total, output_total and fee according to inputs and outputs of this transaction

Return int:
verify()[source]

Verify all inputs of a transaction, check if signatures match public key.

Does not check if UTXO is valid or has already been spent

Return bool:True if enough signatures provided and if all signatures are valid
exception bitcoinlib.transactions.TransactionError(msg='')[source]

Bases: Exception

Handle Transaction class Exceptions

bitcoinlib.transactions.get_unlocking_script_type(locking_script_type, witness_type='legacy', multisig=False)[source]

Specify locking script type and get corresponding script type for unlocking script

>>> get_unlocking_script_type('p2wsh')
'p2sh_multisig'
Parameters:
  • locking_script_type (str) – Locking script type. I.e.: p2pkh, p2sh, p2wpkh, p2wsh
  • witness_type (str) – Type of witness: legacy or segwit. Default is legacy
  • multisig (bool) – Is multisig script or not? Default is False
Return str:

Unlocking script type such as sig_pubkey or p2sh_multisig

bitcoinlib.transactions.script_add_locktime_cltv(locktime_cltv, script)[source]
bitcoinlib.transactions.script_add_locktime_csv(locktime_csv, script)[source]
bitcoinlib.transactions.script_deserialize(script, script_types=None, locking_script=None, size_bytes_check=True)[source]

Deserialize a script: determine type, number of signatures and script data.

Parameters:
  • script (str, bytes, bytearray) – Raw script
  • script_types (list) – Limit script type determination to this list. Leave to default None to search in all script types.
  • locking_script (bool) – Only deserialize locking scripts. Specify False to only deserialize for unlocking scripts. Default is None for both
  • size_bytes_check (bool) – Check if script or signature starts with size bytes and remove size bytes before parsing. Default is True
Return list:

With this items: [script_type, data, number_of_sigs_n, number_of_sigs_m]

bitcoinlib.transactions.script_to_string(script, name_data=False)[source]

Convert script to human readable string format with OP-codes, signatures, keys, etc

>>> script = '76a914c7402ab295a0eb8897ff5b8fbd5276c2d9d2340b88ac'
>>> script_to_string(script)
'OP_DUP OP_HASH160 hash-20 OP_EQUALVERIFY OP_CHECKSIG'
Parameters:
  • script (bytes, str) – A locking or unlocking script
  • name_data (bool) – Replace signatures and keys strings with name
Return str:
bitcoinlib.transactions.serialize_multisig_redeemscript(key_list, n_required=None, compressed=True)[source]

Create a multisig redeemscript used in a p2sh.

Contains the number of signatures, followed by the list of public keys and the OP-code for the number of signatures required.

Parameters:
  • key_list (Key, list) – List of public keys
  • n_required (int) – Number of required signatures
  • compressed (bool) – Use compressed public keys?
Return bytes:

A multisig redeemscript

bitcoinlib.transactions.transaction_deserialize(rawtx, network='bitcoin', check_size=True)[source]

Deserialize a raw transaction

Returns a dictionary with list of input and output objects, locktime and version.

Will raise an error if wrong number of inputs are found or if there are no output found.

Parameters:
  • rawtx (str, bytes, bytearray) – Raw transaction as String, Byte or Bytearray
  • network (str, Network) – Network code, i.e. ‘bitcoin’, ‘testnet’, ‘litecoin’, etc. Leave emtpy for default network
  • check_size (bool) – Check if not bytes are left when parsing is finished. Disable when parsing list of transactions, such as the transactions in a raw block. Default is True
Return Transaction:
 
bitcoinlib.transactions.transaction_update_spents(txs, address)[source]

Update spent information for list of transactions for a specific address. This method assumes the list of transaction complete and up-to-date.

This methods loops through all the transaction and update all transaction outputs for given address, checks if the output is spent and add the spending transaction ID and index number to the outputs.

The same list of transactions with updates outputs will be returned

Parameters:
  • txs (list of Transaction) – Complete list of transactions for given address
  • address (str) – Address string
Return list of Transaction: