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=True, sigs_required=None, sort=False, index_n=0, value=0, double_spend=False, locktime_cltv=None, locktime_csv=None, witness_type=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)) – 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 (bytes, str) – Specify optional signatures
  • public_hash (bytes, str) – Public key or script hash. Specify if key is not available
  • unlocking_script (bytes, hexstring) – Unlocking script (scriptSig) to prove ownership. Optional
  • script_type (str) – Type of unlocking script used, i.e. p2pkh or p2sh_multisig. Default is p2pkh
  • 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 Sequency Verify value.
  • 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 for default
  • network (str, Network) – Network, leave empty for default
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
sequence_timelock_blocks(blocks)[source]
sequence_timelock_time(seconds)[source]
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='base58', 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) – 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) – 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 for default
  • network (str, Network) – Network, leave empty for default
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.

Return type:

Parameters:
  • inputs (Input, list) – Array of Input objects. Leave empty to add later
  • outputs (Output, list) – 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.

:param size; Transaction size in bytes :type size: int :param date: Confirmation date of transaction :type date: datetime.datetime :param confirmations: Number of confirmations :type confirmations: int :param block_height: Block number which includes transaction :type block_height: int :param block_hash: Hash of block for this transaction :type block_hash: str :param input_total: Total value of inputs :type input_total: int :param output_total: Total value of outputs :type output_total: int :param rawtx: Raw hexstring of complete transaction :type rawtx: str :param status: Transaction status, for example: ‘new’, ‘incomplete’, ‘unconfirmed’, ‘confirmed’ :type status: str :param coinbase: Coinbase transaction or not? :type coinbase: bool :param verified: Is transaction successfully verified? Updated when verified() method is called :type verified: bool :param witness_type: Specify witness/signature position: ‘segwit’ or ‘legacy’. Determine from script, address or encoding if not specified. :type witness_type: str :param flag: Transaction flag to indicate version, for example for SegWit :type flag: bytes, str

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, 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, str) – 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) – Specify address of input if known, default is to derive from key or scripts
  • sequence (int, bytes) – 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 – 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.
  • 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)[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) – 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) – 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
Return int:

Transaction output number (output_n)

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
dict()[source]

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

Return dict:
estimate_size(add_change_output=True)[source]

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

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(network='bitcoin')[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
Return Transaction:
 
info()[source]

Prints transaction information to standard output

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

Serialize raw transaction

Return transaction with signed inputs if signatures are available

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
Return bytes:
raw_hex(sign_id=None, hash_type=1)[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
Return hexstring:
 
sign(keys=None, tid=None, multisig_key_n=None, hash_type=1)[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
Return int:

Return int with number of signatures added

signature(sign_id, hash_type=1, sig_version=0)[source]
signature_hash(sign_id, hash_type=1, sig_version=0)[source]
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.

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_deserialize_sigpk(script)[source]

Deserialize a unlocking script (scriptSig) with a signature and public key. The DER encoded signature is decoded to a normal signature with point x and y in 64 bytes total.

Returns signature and public key.

Parameters:script (bytes) – A unlocking script
Return tuple:Tuple with a signature and public key in bytes
bitcoinlib.transactions.script_to_string(script)[source]

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

Example: “OP_DUP OP_HASH160 af8e14a2cecd715c363b3a72b55b59a31e2acac9 OP_EQUALVERIFY OP_CHECKSIG”

Parameters:script (bytes, str) – A locking or unlocking script
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.verify_signature(transaction_to_sign, signature, public_key)[source]

Verify if signatures signs provided transaction hash and corresponds with public key

Parameters:
  • transaction_to_sign (bytes, str) – Raw transaction to sign
  • signature (bytes, str) – A signature
  • public_key (bytes, str) – The public key
Return bool:

Return True if verified