The 21 Bitcoin Library (two1.bitcoin)

Posted by Nigel Drego

The 21 Bitcoin Library (two1.bitcoin)

The bitcoin module within the 21 Bitcoin Library (two1.bitcoin) provides the following functionality:

  1. Serialization/deserialization of all Bitcoin data structures: blocks and block headers, transactions, scripts, public/private keys, and digital signatures. Serialization is achieved via the bytes() method and deserialization is achieved via the from_bytes() static method of each class.

  2. Creation of standard scripts: Pay-to-Public-Key-Hash (P2PKH) and Pay-to-Script-Hash (P2SH) as well multi-sig script support.

  3. Transaction creation, signing, and verification, including multi-sig transactions.

  4. Standard public/private key generation as well as HD key generation.

In short, you should be able to programmatically manipulate most major Bitcoin data structures after learning the functions in this module.

We will illustrate the use of the two1.bitcoin module by showing how to parse, create, and sign a transaction.

Parsing a transaction

Transactions are the most likely starting place for this module. A transaction can be deserialized from a hex string. For example, this transaction https://blockchain.info/tx/039fc554371f9381376b3ea7a3f22009709f05a993fa90a919ac73c1713bba3b can be deserialized as follows:

import requests

from two1.bitcoin.txn import Transaction

tx_hex = requests.request("GET", "https://blockchain.info/rawtx/039fc554371f9381376b3ea7a3f22009709f05a993fa90a919ac73c1713bba3b?format=hex").text

txn = Transaction.from_hex(tx_hex)

print("txid: %s" % (txn.hash))
print("Num inputs: %d" % (txn.num_inputs))
print("Num outputs: %d" % (txn.num_outputs))

which gives the following:

txid: 039fc554371f9381376b3ea7a3f22009709f05a993fa90a919ac73c1713bba3b
Num inputs: 5
Num outputs: 2

We can iterate over the inputs and outputs and print out the addresses associated with each:

for i, inp in enumerate(txn.inputs):
  print("Input %d: %r" % (i, inp.get_addresses()))

for i, out in enumerate(txn.outputs):
  print("Output %d: %r" % (i, out.get_addresses()))

Results:

Input 0: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 1: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 2: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 3: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 4: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Output 0: ['137KzxStaf6vw5yGujViK3Tkigoix9N3v7']
Output 1: ['1YBnESCmM3irLX9Z8zCaKvCorJwwCrGtv']

For the outputs, we can inspect the value:

for i, inp in enumerate(txn.inputs):
    print("Input %d: %r" % (i, inp.get_addresses()))

for i, out in enumerate(txn.outputs):
    print("Output %d: %r, %d satoshis" % (i, out.get_addresses(), out.value))

which gives:

Input 0: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 1: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 2: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 3: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Input 4: ['18ganSKbBJcHi82mqLmY5UKHG9nxYZWZDU']
Output 0: ['137KzxStaf6vw5yGujViK3Tkigoix9N3v7'], 100000 satoshis
Output 1: ['1YBnESCmM3irLX9Z8zCaKvCorJwwCrGtv'], 23100 satoshis

The transaction can be serialized to either hex or bytes:

print(txn.to_hex())
txn_bytes = bytes(txn)

While this shows how to serialize a transaction, serialization and deserialization is consistent amongst all classes. Serialization is achieved via the bytes() method and deserialization is achieved via the from_bytes() static method of each class.

Creating a transaction

A transaction can be created from scratch by creating and inserting inputs and outputs. As outputs don't require any signing, let's start by creating the first output in the above transacion:

from two1.bitcoin.txn import TransactionOutput
from two1.bitcoin.script import Script
from two1.bitcoin.utils import address_to_key_hash
from two1.bitcoin.utils import bytes_to_str

address = '137KzxStaf6vw5yGujViK3Tkigoix9N3v7'
_, hash160 = address_to_key_hash(address)
out_script = Script.build_p2pkh(hash160)
out1 = TransactionOutput(value=100000, script=out_script)

# Print the script
print("%s" % (out_script))

# Print the address
print("Addresses = %r" % (out1.get_addresses()))

# Print the value
print("Value: %d" % (out1.value))

# Serialize
out1_bytes = bytes(out1)
print(bytes_to_str(out1_bytes))

Results:

OP_DUP OP_HASH160 0x17229b6b4ac45e1a73a6a64fedd9f7d4dab4333e OP_EQUALVERIFY OP_CHECKSIG
Addresses = ['137KzxStaf6vw5yGujViK3Tkigoix9N3v7']
Value: 100000
a0860100000000001976a91417229b6b4ac45e1a73a6a64fedd9f7d4dab4333e88ac

In the above example, we had to extract the HASH160 of the address. The utility function address_to_key_hash allowed us to do that. Using that, we built a Pay-to-Public-Key Hash script using Script.build_p2pkh() which was the first line of the output. We then created the transaction output, inspected the addresses and saw that we got the same address we input, inspected the value and finally serialized the output.

An output by itself is relatively useless without an input as the input provides the funds to fund the transaction. However, to create an input, we need to prove we have ownership of the key that contains the input funds. Since we do not have the private key associated with the inputs in the above transaction, we will create a new key pair and sign a fake input. To do this, we will use the two1.bitcoin.crypto module:

from two1.bitcoin.crypto import PrivateKey

private_key = PrivateKey.from_random()

# Get the public key and address associated with this address
print("Address: %s" % private_key.public_key.address())

Results (this will be different for everyone as we are generating a random key):

Address: 13wBf3z3rshFGWDpMCyBowzCGxWNVnXXyL

A complete example: creating and signing a transaction

Let's put it all together:

from two1.bitcoin.crypto import PrivateKey
from two1.bitcoin.hash import Hash
from two1.bitcoin.txn import TransactionInput
from two1.bitcoin.txn import TransactionOutput
from two1.bitcoin.txn import Transaction
from two1.bitcoin.script import Script
from two1.bitcoin.utils import address_to_key_hash
from two1.bitcoin.utils import bytes_to_str

# We use the private key for the value 1 to make this example
# reproducible.  WARNING: do not use that private key for
# real; you can see here all the other people who have used this
# key: https://blockchain.info/address/1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
#
# If you want to use a real key, you'd import the wallet
# and do wallet.get_private_key(utxo_addr)
private_key = PrivateKey.from_int(1)

# Get the public key and address associated with this address
print("Address: %s" % private_key.public_key.address())

# Create a P2PKH as the UTXO from which we're spending based on
# the private key we just generated. This will not be valid to
# send to the network, but shows how to sign an input.
hash160 = private_key.public_key.hash160()
utxo_pubkey_script = Script.build_p2pkh(hash160)

# Create a transaction input using an empty script
out_txid = Hash("0000000000000000000000000000000000000000000000000000000000000000")
inp = TransactionInput(outpoint=out_txid,
                       outpoint_index=0,
                       script=Script(),
                       sequence_num=0xffffffff)

# Create the output
address = '137KzxStaf6vw5yGujViK3Tkigoix9N3v7'
_, hash160 = address_to_key_hash(address)
out_script = Script.build_p2pkh(hash160)
out = TransactionOutput(value=100000, script=out_script)

# Now let's create a transaction
txn = Transaction(version=Transaction.DEFAULT_TRANSACTION_VERSION,
                  inputs=[inp],
                  outputs=[out],
                  lock_time=0)

# Sign our input
txn.sign_input(input_index=0,
               hash_type=Transaction.SIG_HASH_ALL,
               private_key=private_key,
               sub_script=utxo_pubkey_script)

# Print out signature script
print("\nSignature script: %s" % inp.script)

# And now the serialized transaction
print("\nTransaction:\n%s" % txn.to_hex())
print("\ntxid: %s" % txn.hash)

# verify the transaction input
verified = txn.verify_input_signature(input_index=0,
                                      sub_script=utxo_pubkey_script)
print("\nInput verified? %r" % verified)

And we get something like the following.:

Address: 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH

Signature script: 0x3045022100f1a41e774abc21449663adf9de245057591b5569fce36af99e562acd134a605102203330a12b1d85f3530389c25c7b4b23eee6e4d083eceb5268f5afa680e9bf37f701 0x0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798

Transaction:
01000000010000000000000000000000000000000000000000000000000000000000000000000000006b483045022100f1a41e774abc21449663adf9de245057591b5569fce36af99e562acd134a605102203330a12b1d85f3530389c25c7b4b23eee6e4d083eceb5268f5afa680e9bf37f701210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ffffffff01a0860100000000001976a91417229b6b4ac45e1a73a6a64fedd9f7d4dab4333e88ac00000000

txid: 03800275792ba46a7298089f24df35a14cd0742b501b9dc480e8508e50ee132a

Input verified? True

As above, your exact results will be different since we're generating random private keys.

Note that while this transaction could not be submitted to the Bitcoin network (since the UTXO we referenced doesn't exist), we were able to create a single input/single output transaction, sign the input, verify it, and serialize the entire transaction into a form that could be submitted. To see how to broadcast a raw transaction, see provider.broadcast_transaction in two1.blockchain.

If you want to do this example with a proper UTXO, replace the line referencing the private_key with wallet.get_private_key(utxo_addr). This is an example of using the two1.wallet module programmatically.

two1.bitcoin: module contents

The two1.bitcoin module is organized into the following submodules:

two1.bitcoin.block

This submodule provides the MerkleNode, Block, BlockHeader, and CompactBlock classes. It allows you to work programmatically with the individual blocks in the Bitcoin blockchain.

class two1.bitcoin.block.Block(height, version, prev_block_hash, time, bits, nonce, txns)

Bases: object

A Bitcoin Block object.

The merkle root is automatically computed from the transactions passed in during initialization.

Serialization and deserialization are done according to: https://bitcoin.org/en/developer-reference#serialized-blocks

Parameters:
  • height (uint) – Block height
  • version (uint) – The block version. Endianness: host
  • prev_block_hash (Hash) – a Hash object containing the previous block hash.
  • time (uint) – Block timestamp. Endianness: host
  • bits (uint) – Compact representation of the difficulty. Endianness: host
  • nonce (uint) – Endianness: host
  • txns (list) – List of Transaction objects
coinbase_transaction

Setter/Getter for coinbase_transaction. The setter automatically calls invalidate_coinbase() to ensure the merkle root is recomputed based on the new coinbase transaction.

classmethod from_blockheader(bh, txns)

Creates a Block from an existing BlockHeader object and transactions.

Parameters:
  • bh (BlockHeader) – A BlockHeader object.
  • txns (list) – List of all transactions to be included in the block.
Returns:

block – A Block object.

Return type:

Block

static from_bytes(b)

Creates a Block from a serialized byte stream.

Parameters:b (bytes) – The byte stream, starting with the block version.
Returns:block, b – A tuple. The first item is the deserialized block and the second is the remainder of the byte stream.
Return type:tuple
get_merkle_edge()

This function returns the merkle edge required for mining. Specifically, the edge begins with the first transaction after the coinbase (self.txns[1]) and continues with all nodes in the tree, one-in from the left edge.

Returns:edge – a list of hashes corresponding to the merkle edge
Return type:list
hash

Computes the hash of the block header.

Returns:dhash – The double SHA-256 hash of the block header.
Return type:bytes
invalidate()

Updates the merkle tree and block header if any changes to the underlying txns were made.

invalidate_coinbase()

Optimized update of the merkle tree if only the coinbase has been updated/changed. The whole merkle tree is not computed. Instead, just the left edge is.

class two1.bitcoin.block.BlockHeader(version, prev_block_hash, merkle_root_hash, time, bits, nonce)

Bases: object

A BlockHeader object containing all fields found in a Bitcoin block header.

Serialization & deserialization are done according to: https://bitcoin.org/en/developer-reference#block-headers For definitions of hash byte order, see: https://bitcoin.org/en/developer-reference#hash-byte-order

Parameters:
  • version (uint) – The block version. Endianness: host
  • prev_block_hash (Hash) – a Hash object containing the previous block hash.
  • merkle_root_hash (Hash) – The merkle root hash.
  • time (uint) – Block timestamp. Endianness: host
  • bits (uint) – Compact representation of the difficulty. Endianness: host
  • nonce (uint) – Endianness: host
static from_bytes(b)

Creates a BlockHeader object from a serialized bytestream. This function “eats” the bytestream and returns the remainder of the stream after deserializing the fields of the BlockHeader.

Parameters:b (bytes) – bytes beginning with the (4-byte) version.
Returns:bh, b – A tuple containing two elements - a BlockHeader object and the remainder of the bytestream after deserialization.
Return type:tuple
hash

Computes the double SHA-256 hash of the serialized object.

Returns:object containing the hash
Return type:Hash
valid

Dynamically returns whether hash < target

Returns:valid – True if hash < target, False otherwise.
Return type:bool
class two1.bitcoin.block.CompactBlock(height, version, prev_block_hash, time, bits, merkle_edge, cb_txn=None)

Bases: object

This is a block representation that contains the minimum state required for mining purposes: a BlockHeader and the merkle hashes one-in from the left edge of the merkle tree.

Parameters:
  • height (uint) – Block height. Endianness: host
  • version (uint) – The block version. Endianness: host
  • prev_block_hash (Hash) – a Hash object containing the previous block hash.
  • time (uint) – Block timestamp. Endianness: host
  • bits (uint) – Compact representation of the difficulty. Endianness: host
  • merkle_edge (list(Hash) – a list of merkle hashes one-in from the left edge of the merkle tree. This is the minimum state required to compute the merkle_root if the coinbase txn changes.
  • cb_txn (Transaction) – if provided, must contain a CoinbaseInput. If not provided, use CompactBlock.coinbase_transaction = ... to set the transaction. This will ensure the merkle_root is computed according to the new coinbase transaction.
coinbase_transaction

cb_txn (Transaction) – The coinbase transaction. The setter takes care of recomputing the merkle edge and midstate.

class two1.bitcoin.block.MerkleNode(hash=None, left_child=None, right_child=None)

Bases: object

A MerkleNode object from which you can build a Merkle tree.

Parameters:
  • hash – SHA-256 byte string (internal byte order)
  • left_child – MerkleNode object
  • right_child – MerkleNode object

two1.bitcoin.crypto

This submodule provides the PublicKey, PrivateKey, and Signature classes. It also provides HDPublicKey and HDPrivateKey classes for working with HD wallets.

class two1.bitcoin.crypto.HDKey(key, chain_code, index, depth, parent_fingerprint)

Bases: object

Base class for HDPrivateKey and HDPublicKey.

Parameters:
  • key (PrivateKey or PublicKey) – The underlying simple private or public key that is used to sign/verify.
  • chain_code (bytes) – The chain code associated with the HD key.
  • depth (int) – How many levels below the master node this key is. By definition, depth = 0 for the master node.
  • index (int) – A value between 0 and 0xffffffff indicating the child number. Values >= 0x80000000 are considered hardened children.
  • parent_fingerprint (bytes) – The fingerprint of the parent node. This is 0x00000000 for the master node.
Returns:

An HDKey object.

Return type:

HDKey

fingerprint

Returns the key’s fingerprint, which is the first 4 bytes of its identifier.

A key’s identifier and fingerprint are defined as: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#key-identifiers

Returns:The first 4 bytes of the RIPEMD-160 hash.
Return type:bytes
static from_b58check(key)

Decodes a Base58Check encoded key.

The encoding must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format

Parameters:key (str) – A Base58Check encoded key.
Returns:Either an HD private or public key object, depending on what was serialized.
Return type:HDPrivateKey or HDPublicKey
static from_bytes(b)

Generates either a HDPrivateKey or HDPublicKey from the underlying bytes.

The serialization must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format

Parameters:b (bytes) – A byte stream conforming to the above.
Returns:Either an HD private or public key object, depending on what was serialized.
Return type:HDPrivateKey or HDPublicKey
static from_hex(h)

Generates either a HDPrivateKey or HDPublicKey from the underlying hex-encoded string.

The serialization must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format

Parameters:h (str) – A hex-encoded string conforming to the above.
Returns:Either an HD private or public key object, depending on what was serialized.
Return type:HDPrivateKey or HDPublicKey
static from_path(root_key, path)
hardened

Whether or not this is a hardened node.

Hardened nodes are those with indices >= 0x80000000.

Returns:True if this is hardened, False otherwise.
Return type:bool
identifier

Returns the identifier for the key.

A key’s identifier and fingerprint are defined as: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#key-identifiers

Returns:A 20-byte RIPEMD-160 hash.
Return type:bytes
master

Whether or not this is a master node.

Returns:True if this is a master node, False otherwise.
Return type:bool
static parse_path(path)
static path_from_indices(l)
testnet_bytes

Serialization of the key for testnet.

Returns:A 78-byte serialization of the key, specifically for testnet (i.e. the first 2 bytes will be 0x0435).
Return type:bytes
to_b58check(testnet=False)

Generates a Base58Check encoding of this key.

Parameters:testnet (bool) – True if the key is to be used with testnet, False otherwise.
Returns:A Base58Check encoded string representing the key.
Return type:str
class two1.bitcoin.crypto.HDPrivateKey(key, chain_code, index, depth, parent_fingerprint=b'x00x00x00x00')

Bases: two1.bitcoin.crypto.HDKey, two1.bitcoin.crypto.PrivateKeyBase

Implements an HD Private Key according to BIP-0032: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

For the vast majority of use cases, the 3 static functions (HDPrivateKey.master_key_from_entropy, HDPrivateKey.master_key_from_seed and HDPrivateKey.from_parent) will be used rather than directly constructing an object.

Parameters:
  • key (PrivateKey or PublicKey) – The underlying simple private or public key that is used to sign/verify.
  • chain_code (bytes) – The chain code associated with the HD key.
  • depth (int) – How many levels below the master node this key is. By definition, depth = 0 for the master node.
  • index (int) – A value between 0 and 0xffffffff indicating the child number. Values >= 0x80000000 are considered hardened children.
  • parent_fingerprint (bytes) – The fingerprint of the parent node. This is 0x00000000 for the master node.
Returns:

An HDKey object.

Return type:

HDKey

MAINNET_VERSION = 76066276
TESTNET_VERSION = 70615956
static from_parent(parent_key, i)

Derives a child private key from a parent private key. It is not possible to derive a child private key from a public parent key.

Parameters:parent_private_key (HDPrivateKey) –
identifier

Returns the identifier for the key.

A key’s identifier and fingerprint are defined as: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#key-identifiers

In this case, it will return the RIPEMD-160 hash of the corresponding public key.

Returns:A 20-byte RIPEMD-160 hash.
Return type:bytes
static master_key_from_entropy(passphrase='', strength=128)

Generates a master key from system entropy.

Parameters:
  • strength (int) – Amount of entropy desired. This should be a multiple of 32 between 128 and 256.
  • passphrase (str) – An optional passphrase for the generated mnemonic string.
Returns:

a tuple consisting of the master private key and a mnemonic string from which the seed can be recovered.

Return type:

HDPrivateKey, str

static master_key_from_mnemonic(mnemonic, passphrase='')

Generates a master key from a mnemonic.

Parameters:
  • mnemonic (str) – The mnemonic sentence representing the seed from which to generate the master key.
  • passphrase (str) – Password if one was used.
Returns:

the master private key.

Return type:

HDPrivateKey

static master_key_from_seed(seed)

Generates a master key from a provided seed.

Parameters:seed (bytes or str) – a string of bytes or a hex string
Returns:the master private key.
Return type:HDPrivateKey
public_key

Returns the public key associated with this private key.

Returns:The HDPublicKey object that corresponds to this private key.
Return type:HDPublicKey
raw_sign(message, do_hash=True)

Signs message using the underlying non-extended private key.

Parameters:
  • message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

a raw point (r = pt.x, s = pt.y) which is the signature.

Return type:

ECPointAffine

sign(message, do_hash=True)

Signs message using the underlying non-extended private key.

Note

This differs from raw_sign() since it returns a Signature object.

Parameters:
  • message (bytes or str) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

The signature corresponding to message.

Return type:

Signature

sign_bitcoin(message, compressed=False)

Signs a message using the underlying non-extended private key such that it is compatible with bitcoind, bx, and other Bitcoin clients/nodes/utilities.

Note

0x18 + b”Bitcoin Signed Message:” + newline + len(message) is prepended to the message before signing.

Parameters:
  • message (bytes or str) – Message to be signed.
  • compressed (bool) – True if the corresponding public key will be used in compressed format. False if the uncompressed version is used.
Returns:

A Base64-encoded byte string of the signed message. The first byte of the encoded message contains information about how to recover the public key. In bitcoind parlance, this is the magic number containing the recovery ID and whether or not the key was compressed or not. (This function always processes full, uncompressed public-keys, so the magic number will always be either 27 or 28).

Return type:

bytes

class two1.bitcoin.crypto.HDPublicKey(x, y, chain_code, index, depth, parent_fingerprint=b'x00x00x00x00')

Bases: two1.bitcoin.crypto.HDKey, two1.bitcoin.crypto.PublicKeyBase

Implements an HD Public Key according to BIP-0032: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

For the vast majority of use cases, the static function HDPublicKey.from_parent() will be used rather than directly constructing an object.

Parameters:
  • x (int) – x component of the point representing the public key.
  • y (int) – y component of the point representing the public key.
  • chain_code (bytes) – The chain code associated with the HD key.
  • depth (int) – How many levels below the master node this key is. By definition, depth = 0 for the master node.
  • index (int) – A value between 0 and 0xffffffff indicating the child number. Values >= 0x80000000 are considered hardened children.
  • parent_fingerprint (bytes) – The fingerprint of the parent node. This is 0x00000000 for the master node.
Returns:

An HDPublicKey object.

Return type:

HDPublicKey

MAINNET_VERSION = 76067358
TESTNET_VERSION = 70617039
address(compressed=True, testnet=False)

Address property that returns the Base58Check encoded version of the HASH160.

Parameters:
  • compressed (bool) – Whether or not the compressed key should be used.
  • testnet (bool) – Whether or not the key is intended for testnet usage. False indicates mainnet usage.
Returns:

Base58Check encoded string

Return type:

bytes

compressed_bytes

Byte string corresponding to a compressed representation of this public key.

Returns:b – A 33-byte long byte string.
Return type:bytes
static from_parent(parent_key, i)
hash160(compressed=True)

Return the RIPEMD-160 hash of the SHA-256 hash of the non-extended public key.

Note

This always returns the hash of the compressed version of the public key.

Returns:RIPEMD-160 byte string.
Return type:bytes
identifier

Returns the identifier for the key.

A key’s identifier and fingerprint are defined as: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#key-identifiers

In this case, it will return the RIPEMD-160 hash of the non-extended public key.

Returns:A 20-byte RIPEMD-160 hash.
Return type:bytes
verify(message, signature, do_hash=True)

Verifies that message was appropriately signed.

Parameters:
  • message (bytes) – The message to be verified.
  • signature (Signature) – A signature object.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

verified – True if the signature is verified, False otherwise.

Return type:

bool

class two1.bitcoin.crypto.PrivateKey(k)

Bases: two1.bitcoin.crypto.PrivateKeyBase

Encapsulation of a Bitcoin ECDSA private key.

This class provides capability to generate private keys, obtain the corresponding public key, sign messages and serialize/deserialize into a variety of formats.

Parameters:k (int) – The private key.
Returns:The object representing the private key.
Return type:PrivateKey
MAINNET_VERSION = 128
TESTNET_VERSION = 239
static from_b58check(private_key)

Decodes a Base58Check encoded private-key.

Parameters:private_key (str) – A Base58Check encoded private key.
Returns:A PrivateKey object
Return type:PrivateKey
static from_bytes(b)

Generates PrivateKey from the underlying bytes.

Parameters:b (bytes) – A byte stream containing a 256-bit (32-byte) integer.
Returns:tuple – A PrivateKey object and the remainder of the bytes.
Return type:PrivateKey, bytes
static from_hex(h)

Generates PrivateKey from a hex-encoded string.

Parameters:h (str) – A hex-encoded string containing a 256-bit (32-byte) integer.
Returns:A PrivateKey object.
Return type:PrivateKey
static from_int(i)

Initializes a private key from an integer.

Parameters:i (int) – Integer that is the private key.
Returns:The object representing the private key.
Return type:PrivateKey
static from_random()

Initializes a private key from a random integer.

Returns:The object representing the private key.
Return type:PrivateKey
public_key

Returns the public key associated with this private key.

Returns:The PublicKey object that corresponds to this private key.
Return type:PublicKey
raw_sign(message, do_hash=True)

Signs message using this private key.

Parameters:
  • message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

a raw point (r = pt.x, s = pt.y) which is the signature.

Return type:

ECPointAffine

sign(message, do_hash=True)

Signs message using this private key.

Note

This differs from raw_sign() since it returns a Signature object.

Parameters:
  • message (bytes or str) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

The signature corresponding to message.

Return type:

Signature

sign_bitcoin(message, compressed=False)

Signs a message using this private key such that it is compatible with bitcoind, bx, and other Bitcoin clients/nodes/utilities.

Note

0x18 + b”Bitcoin Signed Message:” + newline + len(message) is prepended to the message before signing.

Parameters:
  • message (bytes or str) – Message to be signed.
  • compressed (bool) – True if the corresponding public key will be used in compressed format. False if the uncompressed version is used.
Returns:

A Base64-encoded byte string of the signed message. The first byte of the encoded message contains information about how to recover the public key. In bitcoind parlance, this is the magic number containing the recovery ID and whether or not the key was compressed or not.

Return type:

bytes

to_b58check(testnet=False)

Generates a Base58Check encoding of this private key.

Returns:A Base58Check encoded string representing the key.
Return type:str
class two1.bitcoin.crypto.PrivateKeyBase(k)

Bases: object

Base class for both PrivateKey and HDPrivateKey.

As this class is a base class it should not be used directly.

Parameters:k (int) – The private key.
Returns:The object representing the private key.
Return type:PrivateKey
static from_b58check(private_key)

Decodes a Base58Check encoded private-key.

Parameters:private_key (str) – A Base58Check encoded private key.
Returns:A PrivateKey object
Return type:PrivateKey
public_key

Returns the public key associated with this private key.

Returns:The PublicKey object that corresponds to this private key.
Return type:PublicKey
raw_sign(message, do_hash=True)

Signs message using this private key.

Parameters:
  • message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

a raw point (r = pt.x, s = pt.y) which is the signature.

Return type:

ECPointAffine

sign(message, do_hash=True)

Signs message using this private key.

Note

This differs from raw_sign() since it returns a Signature object.

Parameters:
  • message (bytes or str) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

The signature corresponding to message.

Return type:

Signature

sign_bitcoin(message, compressed=False)

Signs a message using this private key such that it is compatible with bitcoind, bx, and other Bitcoin clients/nodes/utilities.

Note

0x18 + b”Bitcoin Signed Message:” + newline + len(message) is prepended to the message before signing.

Parameters:
  • message (bytes or str) – Message to be signed.
  • compressed (bool) – True if the corresponding public key will be used in compressed format. False if the uncompressed version is used.
Returns:

A Base64-encoded byte string of the signed message. The first byte of the encoded message contains information about how to recover the public key. In bitcoind parlance, this is the magic number containing the recovery ID and whether or not the key was compressed or not. (This function always processes full, uncompressed public-keys, so the magic number will always be either 27 or 28).

Return type:

bytes

to_b58check(testnet=False)

Generates a Base58Check encoding of this private key.

Returns:A Base58Check encoded string representing the key.
Return type:str
to_hex()

Generates a hex encoding of the serialized key.

Returns:A hex encoded string representing the key.
Return type:str
class two1.bitcoin.crypto.PublicKey(x, y)

Bases: two1.bitcoin.crypto.PublicKeyBase

Encapsulation of a Bitcoin ECDSA public key.

This class provides a high-level API to using an ECDSA public key, specifically for Bitcoin (secp256k1) purposes.

Parameters:
  • x (int) – The x component of the public key point.
  • y (int) – The y component of the public key point.
Returns:

The object representing the public key.

Return type:

PublicKey

MAINNET_VERSION = 0
TESTNET_VERSION = 111
address(compressed=True, testnet=False)

Address property that returns the Base58Check encoded version of the HASH160.

Parameters:
  • compressed (bool) – Whether or not the compressed key should be used.
  • testnet (bool) – Whether or not the key is intended for testnet usage. False indicates mainnet usage.
Returns:

Base58Check encoded string

Return type:

bytes

compressed_bytes

Byte string corresponding to a compressed representation of this public key.

Returns:b – A 33-byte long byte string.
Return type:bytes
static from_base64(b64str, testnet=False)

Generates a public key object from a Base64 encoded string.

Parameters:
  • b64str (str) – A Base64-encoded string.
  • testnet (bool) – If True, changes the version that is prepended to the key.
Returns:

A PublicKey object.

Return type:

PublicKey

static from_bytes(key_bytes)

Generates a public key object from a byte (or hex) string.

The byte stream must be of the SEC variety (http://www.secg.org/): beginning with a single byte telling what key representation follows. A full, uncompressed key is represented by: 0x04 followed by 64 bytes containing the x and y components of the point. For compressed keys with an even y component, 0x02 is followed by 32 bytes containing the x component. For compressed keys with an odd y component, 0x03 is followed by 32 bytes containing the x component.

Parameters:key_bytes (bytes or str) – A byte stream that conforms to the above.
Returns:A PublicKey object.
Return type:PublicKey
static from_hex(h)

Generates a public key object from a hex-encoded string.

See from_bytes() for requirements of the hex string.

Parameters:h (str) – A hex-encoded string.
Returns:A PublicKey object.
Return type:PublicKey
static from_int(i)

Generates a public key object from an integer.

Note

This assumes that the upper 32 bytes of the integer are the x component of the public key point and the lower 32 bytes are the y component.

Parameters:i (Bignum) – A 512-bit integer representing the public key point on the secp256k1 curve.
Returns:A PublicKey object.
Return type:PublicKey
static from_point(p)

Generates a public key object from any object containing x, y coordinates.

Parameters:p (Point) – An object containing a two-dimensional, affine representation of a point on the secp256k1 curve.
Returns:A PublicKey object.
Return type:PublicKey
static from_signature(message, signature)

Attempts to create PublicKey object by deriving it from the message and signature.

Parameters:
  • message (bytes) – The message to be verified.
  • signature (Signature) – The signature for message. The recovery_id must not be None!
Returns:

A PublicKey object derived from the signature, it it exists. None otherwise.

Return type:

PublicKey

hash160(compressed=True)

Return the RIPEMD-160 hash of the SHA-256 hash of the public key.

Parameters:compressed (bool) – Whether or not the compressed key should be used.
Returns:RIPEMD-160 byte string.
Return type:bytes
to_base64()

Hex representation of the serialized byte stream.

Returns:b – A Base64-encoded string.
Return type:str
verify(message, signature, do_hash=True)

Verifies that message was appropriately signed.

Parameters:
  • message (bytes) – The message to be verified.
  • signature (Signature) – A signature object.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

verified – True if the signature is verified, False otherwise.

Return type:

bool

static verify_bitcoin(message, signature, address)

Verifies a message signed using PrivateKey.sign_bitcoin() or any of the bitcoin utils (e.g. bitcoin-cli, bx, etc.)

Parameters:
  • message (bytes) – The message that the signature corresponds to.
  • signature (bytes or str) – A Base64 encoded signature
  • address (str) – Base58Check encoded address.
Returns:

True if the signature verified properly, False otherwise.

Return type:

bool

class two1.bitcoin.crypto.PublicKeyBase

Bases: object

Base class for both PublicKey and HDPublicKey.

As this class is a base class it should not be used directly.

Parameters:
  • x (int) – The x component of the public key point.
  • y (int) – The y component of the public key point.
Returns:

The object representing the public key.

Return type:

PublicKey

address(compressed=True, testnet=False)

Address property that returns the Base58Check encoded version of the HASH160.

Parameters:
  • compressed (bool) – Whether or not the compressed key should be used.
  • testnet (bool) – Whether or not the key is intended for testnet usage. False indicates mainnet usage.
Returns:

Base58Check encoded string

Return type:

bytes

compressed_bytes

Byte string corresponding to a compressed representation of this public key.

Returns:b – A 33-byte long byte string.
Return type:bytes
static from_bytes(key_bytes)

Generates a public key object from a byte (or hex) string.

Parameters:key_bytes (bytes or str) – A byte stream.
Returns:A PublicKey object.
Return type:PublicKey
static from_private_key(private_key)

Generates a public key object from a PrivateKey object.

Parameters:private_key (PrivateKey) – The private key object from which to derive this object.
Returns:A PublicKey object.
Return type:PublicKey
hash160(compressed=True)

Return the RIPEMD-160 hash of the SHA-256 hash of the public key.

Parameters:compressed (bool) – Whether or not the compressed key should be used.
Returns:RIPEMD-160 byte string.
Return type:bytes
to_hex()

Hex representation of the serialized byte stream.

Returns:h – A hex-encoded string.
Return type:str
verify(message, signature, do_hash=True)

Verifies that message was appropriately signed.

Parameters:
  • message (bytes) – The message to be verified.
  • signature (Signature) – A signature object.
  • do_hash (bool) – True if the message should be hashed prior to signing, False if not. This should always be left as True except in special situations which require doing the hash outside (e.g. handling Bitcoin bugs).
Returns:

verified – True if the signature is verified, False otherwise.

Return type:

bool

class two1.bitcoin.crypto.Signature(r, s, recovery_id=None)

Bases: object

Encapsulation of a ECDSA signature for Bitcoin purposes.

Parameters:
  • r (Bignum) – r component of the signature.
  • s (Bignum) – s component of the signature.
  • recovery_id (int) – Must be between 0 and 3 specifying which of the public keys generated by the algorithm specified in http://www.secg.org/sec1-v2.pdf Section 4.1.6 (Public Key Recovery Operation) is the correct one for this signature.
Returns:

sig – A Signature object.

Return type:

Signature

static from_base64(b64str)

Generates a signature object from a Base64 encoded string.

Parameters:b64str (str) – A Base64-encoded string.
Returns:A Signature object.
Return type:Signature
static from_bytes(b)

Extracts the r and s components from a byte string.

Parameters:b (bytes) – A 64-byte long string. The first 32 bytes are extracted as the r component and the second 32 bytes are extracted as the s component.
Returns:A Signature object.
Return type:Signature
Raises:ValueError – If signature is incorrect length
static from_der(der)

Decodes a Signature that was DER-encoded.

Parameters:der (bytes or str) – The DER encoding to be decoded.
Returns:The deserialized signature.
Return type:Signature
static from_hex(h)

Extracts the r and s components from a hex-encoded string.

Parameters:h (str) – A 64-byte (128 character) long string. The first 32 bytes are extracted as the r component and the second 32 bytes are extracted as the s component.
Returns:A Signature object.
Return type:Signature
to_base64()

Hex representation of the serialized byte stream.

Returns:A Base64-encoded string.
Return type:str
to_der()

Encodes this signature using DER

Returns:The DER encoding of (self.r, self.s).
Return type:bytes
to_hex()

Hex representation of the serialized byte stream.

Returns:A hex-encoded string.
Return type:str
x

Convenience property for any method that requires this object to provide a Point interface.

y

Convenience property for any method that requires this object to provide a Point interface.

two1.bitcoin.crypto.get_bytes(s)

Returns the byte representation of a hex- or byte-string.

two1.bitcoin.exceptions

This is a simple submodule that enumerates the different kinds of exceptions that the two1.bitcoin module raises.

exception two1.bitcoin.exceptions.DeserializationError

Bases: Exception

Generic error for exceptions found while deserializing an object.

exception two1.bitcoin.exceptions.InvalidBlockError

Bases: two1.bitcoin.exceptions.DeserializationError

Raised when a Block object cannot be deserialized.

exception two1.bitcoin.exceptions.InvalidBlockHeaderError

Bases: two1.bitcoin.exceptions.DeserializationError

Raised when a BlockHeader object cannot be deserialized.

exception two1.bitcoin.exceptions.InvalidCoinbaseInputError

Bases: two1.bitcoin.exceptions.InvalidTransactionInputError

Raised when a CoinbaseInput object cannot be deserialized.

exception two1.bitcoin.exceptions.InvalidTransactionError

Bases: two1.bitcoin.exceptions.DeserializationError

Raised when a Transaction object cannot be deserialized.

exception two1.bitcoin.exceptions.InvalidTransactionInputError

Bases: two1.bitcoin.exceptions.DeserializationError

Raised when a TransactionInput object cannot be deserialized.

exception two1.bitcoin.exceptions.InvalidTransactionOutputError

Bases: two1.bitcoin.exceptions.DeserializationError

Raised when a TransactionOutput object cannot be deserialized.

exception two1.bitcoin.exceptions.ScriptInterpreterError

Bases: Exception

Raised interpreting an invalid Script.

exception two1.bitcoin.exceptions.ScriptParsingError

Bases: Exception

Raised when parsing an invalid Script.

exception two1.bitcoin.exceptions.ScriptTypeError

Bases: Exception

Raised when a Script is of an invalid type.

two1.bitcoin.script

This submodule provides a single Script class that has knowledge of all Bitcoin opcodes. At the simplest level, it can read in the raw bytes of a Bitcoin script, parse it, and determine what type of script it is (P2PKH, P2SH, multi-sig, etc). It also provides capabilities for building more complex scripts programmatically.

class two1.bitcoin.script.Script(script='')

Bases: object

Handles all Bitcoin script-related needs. Currently this means: parsing text scripts, assembling/disassembling and serialization/deserialization.

If a raw byte stream is passed in, disassembly and parsing are deferred until required. If parsing is immediately required, call Script.parse() after constructing the object.

Parameters:script (bytes or str) – Either a text or byte string containing the script to build.
BTC_OPCODE_REV_TABLE = {0: 'OP_0', 76: 'OP_PUSHDATA1', 77: 'OP_PUSHDATA2', 78: 'OP_PUSHDATA4', 79: 'OP_1NEGATE', 81: 'OP_1', 82: 'OP_2', 83: 'OP_3', 84: 'OP_4', 85: 'OP_5', 86: 'OP_6', 87: 'OP_7', 88: 'OP_8', 89: 'OP_9', 90: 'OP_10', 91: 'OP_11', 92: 'OP_12', 93: 'OP_13', 94: 'OP_14', 95: 'OP_15', 96: 'OP_16', 97: 'OP_NOP', 99: 'OP_IF', 100: 'OP_NOTIF', 103: 'OP_ELSE', 104: 'OP_ENDIF', 105: 'OP_VERIFY', 106: 'OP_RETURN', 107: 'OP_TOALTSTACK', 108: 'OP_FROMALTSTACK', 109: 'OP_2DROP', 110: 'OP_2DUP', 111: 'OP_3DUP', 112: 'OP_2OVER', 113: 'OP_2ROT', 114: 'OP_2SWAP', 115: 'OP_IFDUP', 116: 'OP_DEPTH', 117: 'OP_DROP', 118: 'OP_DUP', 119: 'OP_NIP', 120: 'OP_OVER', 121: 'OP_PICK', 122: 'OP_ROLL', 123: 'OP_ROT', 124: 'OP_SWAP', 125: 'OP_TUCK', 126: 'OP_CAT', 127: 'OP_SUBSTR', 128: 'OP_LEFT', 129: 'OP_RIGHT', 130: 'OP_SIZE', 131: 'OP_INVERT', 132: 'OP_AND', 133: 'OP_OR', 134: 'OP_XOR', 135: 'OP_EQUAL', 136: 'OP_EQUALVERIFY', 139: 'OP_1ADD', 140: 'OP_1SUB', 141: 'OP_2MUL', 142: 'OP_2DIV', 143: 'OP_NEGATE', 144: 'OP_ABS', 145: 'OP_NOT', 146: 'OP_0NOTEQUAL', 147: 'OP_ADD', 148: 'OP_SUB', 149: 'OP_MUL', 150: 'OP_DIV', 151: 'OP_MOD', 152: 'OP_LSHIFT', 153: 'OP_RSHIFT', 154: 'OP_BOOLAND', 155: 'OP_BOOLOR', 156: 'OP_NUMEQUAL', 157: 'OP_NUMEQUALVERIFY', 158: 'OP_NUMNOTEQUAL', 159: 'OP_LESSTHAN', 160: 'OP_GREATERTHAN', 161: 'OP_LESSTHANOREQUAL', 162: 'OP_GREATERTHANOREQUAL', 163: 'OP_MIN', 164: 'OP_MAX', 165: 'OP_WITHIN', 166: 'OP_RIPEMD160', 167: 'OP_SHA1', 168: 'OP_SHA256', 169: 'OP_HASH160', 170: 'OP_HASH256', 171: 'OP_CODESEPARATOR', 172: 'OP_CHECKSIG', 173: 'OP_CHECKSIGVERIFY', 174: 'OP_CHECKMULTISIG', 175: 'OP_CHECKMULTISIGVERIFY', 177: 'OP_CHECKLOCKTIMEVERIFY'}
BTC_OPCODE_TABLE = {'OP_RIPEMD160': 166, 'OP_HASH160': 169, 'OP_ADD': 147, 'OP_NUMNOTEQUAL': 158, 'OP_NOT': 145, 'OP_PUSHDATA2': 77, 'OP_IFDUP': 115, 'OP_NIP': 119, 'OP_IF': 99, 'OP_LEFT': 128, 'OP_VERIFY': 105, 'OP_SHA256': 168, 'OP_CHECKMULTISIGVERIFY': 175, 'OP_DUP': 118, 'OP_11': 91, 'OP_12': 92, 'OP_OR': 133, 'OP_16': 96, 'OP_2DIV': 142, 'OP_PICK': 121, 'OP_HASH256': 170, 'OP_TRUE': 81, 'OP_2ROT': 113, 'OP_10': 90, 'OP_FALSE': 0, 'OP_CHECKSIGVERIFY': 173, 'OP_PUSHDATA1': 76, 'OP_ABS': 144, 'OP_RIGHT': 129, 'OP_LESSTHAN': 159, 'OP_RSHIFT': 153, 'OP_DROP': 117, 'OP_1': 81, 'OP_3DUP': 111, 'OP_0NOTEQUAL': 146, 'OP_1ADD': 139, 'OP_SIZE': 130, 'OP_15': 95, 'OP_CHECKMULTISIG': 174, 'OP_LESSTHANOREQUAL': 161, 'OP_NUMEQUALVERIFY': 157, 'OP_TUCK': 125, 'OP_4': 84, 'OP_INVERT': 131, 'OP_PUSHDATA4': 78, 'OP_FROMALTSTACK': 108, 'OP_1SUB': 140, 'OP_3': 83, 'OP_BOOLOR': 155, 'OP_2OVER': 112, 'OP_14': 94, 'OP_9': 89, 'OP_ROT': 123, 'OP_OVER': 120, 'OP_NUMEQUAL': 156, 'OP_ROLL': 122, 'OP_6': 86, 'OP_SUBSTR': 127, 'OP_MOD': 151, 'OP_CODESEPARATOR': 171, 'OP_2DROP': 109, 'OP_SWAP': 124, 'OP_CHECKSIG': 172, 'OP_DEPTH': 116, 'OP_DIV': 150, 'OP_ELSE': 103, 'OP_EQUALVERIFY': 136, 'OP_RETURN': 106, 'OP_8': 88, 'OP_NEGATE': 143, 'OP_2SWAP': 114, 'OP_BOOLAND': 154, 'OP_WITHIN': 165, 'OP_5': 85, 'OP_SUB': 148, 'OP_AND': 132, 'OP_2MUL': 141, 'OP_2': 82, 'OP_SHA1': 167, 'OP_LSHIFT': 152, 'OP_EQUAL': 135, 'OP_XOR': 134, 'OP_CHECKLOCKTIMEVERIFY': 177, 'OP_13': 93, 'OP_MIN': 163, 'OP_MUL': 149, 'OP_CAT': 126, 'OP_7': 87, 'OP_NOTIF': 100, 'OP_ENDIF': 104, 'OP_TOALTSTACK': 107, 'OP_NOP': 97, 'OP_GREATERTHANOREQUAL': 162, 'OP_GREATERTHAN': 160, 'OP_MAX': 164, 'OP_2DUP': 110, 'OP_0': 0, 'OP_1NEGATE': 79}
P2PKH_MAINNET_VERSION = 0
P2PKH_TESTNET_VERSION = 111
P2SH_MAINNET_VERSION = 5
P2SH_TESTNET_VERSION = 196
address(testnet=False)

Returns the Base58Check encoded version of the HASH160.

Parameters:testnet (bool) – Whether or not the key is intended for testnet usage. False indicates mainnet usage.
Returns:Base58Check encoded string
Return type:bytes
append(value)

Append an OP to the end of the script

Parameters:value (str or bytes) – OP to insert.
ast

Returns the script’s abstract syntax tree.

Returns:a nested list of opcodes which follow the flow of a script’s conditional if/else branching.
Return type:list
static build_multisig_redeem(m, pub_keys)

Builds a multisig redeem script and corresponding Pay-to-Script-Hash script.

Parameters:
  • m (int) – Number of signatures required. Must be <= len(pub_keys).
  • pub_keys (list(bytes) – list of serialized public keys of which the corresponding private keys can be used to sign when redeeming.
Returns:

The redeem script object

Return type:

Script

static build_multisig_sig(sigs, redeem_script)

Builds a multisig signature script.

This script contains the signatures in order given in sigs as well as the redeem script. It is not required to have all required signatures in sigs. However, len(sigs) may not be more than the max number indicated by the redeem script.

Parameters:
  • sigs (list(bytes) – A list of signatures (in DER encoding). The hash_type must already be appended to the byte string for each signature. This function will take care of the relevant data push operations.
  • redeem_script (Script) – The script used to redeem the coins.
Returns:

A multisig signature script. Note: if len(sigs) is less than the minimum number required, the script will not be valid.

Return type:

Script

static build_p2pkh(hash160_key)

Builds a Pay-to-Public-Key-Hash script.

Parameters:hash160_key (bytes) – the RIPEMD-160 hash of the public key in internal byte order.
Returns:scr – a serializable Script object containing the p2pkh script.
Return type:Script
static build_p2sh(hash160_key)

Builds a Pay-to-Script-Hash script.

Parameters:hash160_key (bytes) – the RIPEMD-160 hash of the script in internal byte order.
Returns:scr – a serializable Script object containing the p2sh script.
Return type:Script
static build_push_int(i)

Creates a script to push i onto the stack using the least possible number of bytes.

Parameters:i (int) – integer to be pushed onto the stack.
Returns:b – Serialized bytes containing the appropriate PUSHDATA op for i.
Return type:bytes
extract_multisig_redeem_info()

Returns information about the multisig redeem script

Returns:Contains the following list of keys: ‘m’ (int): Required number of signatures. ‘n’ (int): Maximum number of signatures. ‘public_keys’ (list): List of byte strings corresponding to public keys.
Return type:dict
extract_multisig_sig_info()

Returns information about a multisig signature script.

Returns:With the following key/value pairs: ‘signatures’ (list): List of DER-encoded signatures with hash_type appended at the end of the byte string. ‘redeem_script’ (Script): The associated redeem script.
Return type:dict
extract_sig_info()

Returns the signature and corresponding public key.

Returns:Contains three keys: ‘hash_type’: Integer ‘signature’: The DER-encoded signature ‘public_key’: The bytes corresponding the public key.
Return type:dict
static from_bytes(b)

Deserializes a byte stream containing a script into a Script object. Assumes the first part contains the length of the script in bytes.

Parameters:b (bytes) – A byte-stream containing the script, with the length of the script in bytes prepended.
Returns:(scr, b) – A tuple with the deserialized Script object and the remainder of the byte stream.
Return type:tuple
static from_hex(h, size_prepended=False)

Deserializes a hex-encoded string into a Script.

Parameters:
  • h (str) – hex-encoded string, starting with the length of the script as a compact int.
  • size_prepended (bool) – Should be True if the size of the script has already been prepended.
Returns:

A Script object.

Return type:

Script

get_addresses(testnet=False)

Returns all addresses found in this script

For output scripts, P2PKH scripts will return a single address the funds are being sent to. P2SH scripts will return a single address of the script the funds are being sent to.

For input scripts, only standard signature and multi-signature scripts will return results: the address(es) used to sign. For standard signature scripts, a single address is returned while for multi-sig scripts, all n addresses in the redeem script are returned.

Parameters:testnet (bool) – True if the addresses are being used on testnet, False if used on mainnet.
Returns:A list of Base58Check encoded bitcoin addresses.
Return type:list
get_hash160()

Scans the script for OP_HASH160 and returns the data immediately following it.

Returns:the hash160 or None.
Return type:bytes
hash160()

Return the RIPEMD-160 hash of the SHA-256 hash of the script.

Returns:RIPEMD-160 byte string.
Return type:bytes
insert(index, value)

Inserts an OP before the specified index

Parameters:
  • index (int) – Index of element to insert before
  • value (str or bytes) – OP to insert.
is_multisig_redeem()

Returns whether this script is a multi-sig redeem script.

Returns:True if it is a multi-sig redeem script, False otherwise.
Return type:bool
is_multisig_sig()

Returns whether this script is a multi-sig signature script.

Returns:True if it is a multi-sig signature script, False otherwise.
Return type:bool
is_p2pkh()

Returns whether this script is a common Pay-to-Public-Key-Hash script.

Returns:True if it is a common P2PKH script, False otherwise.
Return type:bool
is_p2pkh_sig()

Returns whether this script a Pay-to-Public-Key-Hash signature script.

Returns:True if it is a P2PKH signature script, False otherwise.
Return type:bool
is_p2sh()

Returns whether this script is a Pay-to-Script-Hash script.

Returns:True if it is a P2SH script, False otherwise.
Return type:bool
remove_op(op)

Returns a new script without any OP_<op>’s in it.

Returns:scr – New script object devoid of any OP_<op>.
Return type:Script
to_hex()

Generates a hex encoding of the serialized script.

Returns:Hex-encoded serialization.
Return type:str
static validate_template(script, template)

Validates a script against a template.

Parameters:
  • script (Script) – A Script object.
  • template (list) – A list of OPs or types against which to validate script.
Returns:

True if the script has the same OPs and types as template, False otherwise.

Return type:

bool

two1.bitcoin.txn

This submodule provides Transaction, Coinbase, TransactionInput, TransactionOutput, and UnspentTransactionOutput classes for building and parsing Bitcoin transactions and their constituent inputs and outputs.

class two1.bitcoin.txn.CoinbaseInput(height, raw_script, sequence=4294967295, block_version=3)

Bases: two1.bitcoin.txn.TransactionInput

See https://bitcoin.org/en/developer-reference#coinbase

Parameters:
  • height (uint) – The height of the block coinbase is part of will go into. Not required for version 1 blocks.
  • raw_script (bytes) – the bytes of the coinbase script. For block_version > 1 the height portion should NOT be included in this script.
  • sequence (int) – Unless you are Satoshi with a version 1 block, the default is fine. If you are Satoshi, send me some of your private keys and set this to 0.
  • block_version (int) – The version of the block this coinbase is a part of or will go into. If raw_script already contains the height of the block, this must be 1.
MAX_INT = 4294967295
NULL_OUTPOINT = <two1.bitcoin.hash.Hash object>
get_addresses(testnet=False)

Returns all addresses associated with the script in this input.

Parameters:testnet (bool) – True if the transaction is a testnet transaction.
Returns:list – A list of all addresses found in the script.
Return type:str
class two1.bitcoin.txn.Transaction(version, inputs, outputs, lock_time)

Bases: object

See https://bitcoin.org/en/developer-reference#raw-transaction-format

Parameters:
  • version (int) – Transaction version (should always be 1). Endianness: host
  • inputs (list(TransactionInput) – all the inputs that spend bitcoin.
  • outputs (list(TransactionOutput) – all the outputs to which bitcoin is sent.
  • lock_time (int) – Time or a block number. Endianness: host
DEFAULT_TRANSACTION_VERSION = 1
SIG_HASH_ALL = 1
SIG_HASH_ANY = 128
SIG_HASH_NONE = 2
SIG_HASH_OLD = 0
SIG_HASH_SINGLE = 3
static from_bytes(b)

Deserializes a byte stream into a Transaction.

Parameters:b (bytes) – byte stream starting with the version.
Returns:First element of the tuple is the Transaction, second is the remainder of the byte stream.
Return type:tuple
static from_hex(h)

Deserializes a hex-encoded string into a Transaction.

Parameters:h (str) – hex-encoded string starting with the version.
Returns:the deserialized Transaction object.
Return type:Transaction
get_addresses(testnet=False)

Returns all addresses associated with this transaction.

Parameters:testnet (bool) – True if the transaction is a testnet transaction.
Returns:A dict containing the following key/value pairs: ‘inputs’: list of lists of addresses, one per input ‘outputs’: list of lists of addresses, one per output
Return type:dict
get_signature_for_input(input_index, hash_type, private_key, sub_script)

Returns the signature for an input.

This function only returns the signature for an input, it does not insert the signature into the script member of the input. It also does not validate that the given private key matches any public keys in the sub_script.

Parameters:
  • input_index (int) – The index of the input to sign.
  • hash_type (int) – What kind of signature hash to do.
  • private_key (crypto.PrivateKey) – private key with which to sign the transaction.
  • sub_script (Script) – the scriptPubKey of the corresponding utxo being spent if the outpoint is P2PKH or the redeem script if the outpoint is P2SH.
Returns:

A tuple containing the signature object and the message that was signed.

Return type:

tuple

hash

Computes the hash of the transaction.

Returns:dhash – Double SHA-256 hash of the serialized transaction.
Return type:bytes
num_inputs

The number of inputs in the transaction.

num_outputs

The number of outputs in the transaction.

output_index_for_address(address_or_hash160)

Returns the index of the output in this transaction that pays to the provided address.

Parameters:address_or_hash160 (str or bytes) – If a string, a Base58Check encoded address. If bytes, the hash160 of the public key.
Returns:The index of the corresponding output or None.
Return type:int
sign_input(input_index, hash_type, private_key, sub_script)

Signs an input.

Parameters:
  • input_index (int) – The index of the input to sign.
  • hash_type (int) – What kind of signature hash to do.
  • private_key (crypto.PrivateKey) – private key with which to sign the transaction.
  • sub_script (Script) – the scriptPubKey of the corresponding utxo being spent if the outpoint is P2PKH or the redeem script if the outpoint is P2SH.
to_hex()

Generates a hex encoding of the serialized transaction.

Returns:Hex-encoded serialization.
Return type:str
verify_input_signature(input_index, sub_script)

Verifies the signature for an input.

This also confirms that the HASH160 in the provided sub_script corresponds with that found in the input sigScript.

Parameters:
  • input_index (int) – The index of the input to verify.
  • sub_script (Script) – The script in the corresponding outpoint.
Returns:

True if the sigScript is verified, False otherwise.

Return type:

bool

verify_partial_multisig(input_index, sub_script)

Verifies a partially signed multi-sig input.

This also confirms that the HASH160 in the provided sub_script corresponds with that found in the input sigScript.

Parameters:
  • input_index (int) – The index of the input to verify.
  • sub_script (Script) – The P2SH script in the corresponding outpoint.
Returns:

True if > 1 and <= m signatures verify the input.

Return type:

bool

class two1.bitcoin.txn.TransactionInput(outpoint, outpoint_index, script, sequence_num)

Bases: object

See https://bitcoin.org/en/developer-reference#txin

Parameters:
  • outpoint (Hash) – A Hash object of the UTXO hash.
  • outpoint_index (uint) – Index of the specific output to spend the transaction from. Endianness: host
  • script (Script) – Script object (or a raw bytes in the case of a Coinbase input)
  • sequence_num (uint) – Sequence number. Endianness: host
static from_bytes(b)

Deserializes a byte stream into a TransactionInput.

Parameters:b (bytes) – byte stream starting with the outpoint.
Returns:First element of the tuple is the TransactionInput object and the second is the remaining byte stream.
Return type:tuple
get_addresses(testnet=False)

Returns all addresses associated with the script in this input.

Parameters:testnet (bool) – True if the transaction is a testnet transaction.
Returns:list – A list of all addresses found in the script.
Return type:str
class two1.bitcoin.txn.TransactionOutput(value, script)

Bases: object

See https://bitcoin.org/en/developer-reference#txout

Parameters:
  • value (int) – Number of satoshis to be spent. Endianness: host
  • script (Script) – A pay-out script.
static from_bytes(b)

Deserializes a byte stream into a TransactionOutput object.

Parameters:b (bytes) – byte-stream beginning with the value.
Returns:First element of the tuple is a TransactionOutput, the second is the remainder of the byte stream.
Return type:tuple
get_addresses(testnet=False)

Returns all addresses associated with the script in this output.

Parameters:testnet (bool) – True if the transaction is a testnet transaction.
Returns:list – A list of all addresses found in the script.
Return type:str
class two1.bitcoin.txn.UnspentTransactionOutput(transaction_hash, outpoint_index, value, scr, confirmations)

Bases: object

Container class for compactly describing unspent transaction outputs.

Parameters:
  • transaction_hash (Hash) – Hash of the transaction containing the unspent output.
  • outpoint_index (int) – Index of the output.
  • value (int) – Number of satoshis in the output.
  • scr (Script) – The scriptPubKey of the output.
  • confirmations (int) – Number of confirmations for the transaction.
confirmed

Returns whether the unspect transaction output is confirmed.

This method uses six (6) blocks as a threshhold to determine whether the transaction is considered ‘confirmed’.

Returns:True if confirmed, False otherwise.
Return type:bool

two1.bitcoin.utils

This submodule provides functions for accomplishing common tasks encountered in creating and parsing Bitcoin objects, like turning difficulties into targets or deserializing and serializing various kinds of packed byte formats.

two1.bitcoin.utils.address_to_key_hash(s)

Given a Bitcoin address decodes the version and RIPEMD-160 hash of the public key.

Parameters:s (bytes) – The Bitcoin address to decode
Returns:(version, h160) – A tuple containing the version and RIPEMD-160 hash of the public key.
Return type:tuple
two1.bitcoin.utils.bits_to_difficulty(bits)

Determines the difficulty corresponding to bits. See: https://en.bitcoin.it/wiki/Difficulty

Parameters:bits (int) – Compact target (32 bits)
Returns:diff – Measure of how hard it is to find a solution below the target represented by bits.
Return type:float
two1.bitcoin.utils.bits_to_target(bits)

Decodes the full target from a compact representation. See: https://bitcoin.org/en/developer-reference#target-nbits

Parameters:bits (int) – Compact target (32 bits)
Returns:target – Full 256-bit target
Return type:Bignum
two1.bitcoin.utils.bytes_to_str(b)

Converts bytes into a hex-encoded string.

Parameters:b (bytes) – bytes to encode
Returns:h – hex-encoded string corresponding to b.
Return type:str
two1.bitcoin.utils.compute_reward(height)

Computes the block reward for a block at the supplied height. See: https://en.bitcoin.it/wiki/Controlled_supply for the reward schedule.

Parameters:height (int) – Block height
Returns:reward – Number of satoshis rewarded for solving a block at the given height.
Return type:int
two1.bitcoin.utils.difficulty_to_bits(difficulty)

Converts a difficulty to a compact target.

Parameters:difficulty (float) – The difficulty to create a target for
Returns:ct – Compact target
Return type:int
two1.bitcoin.utils.difficulty_to_target(difficulty)

Converts a difficulty to a long-form target.

Parameters:difficulty (float) – The difficulty to return the appropriate target for
Returns:target – The corresponding target
Return type:int
two1.bitcoin.utils.hash160(b)

Computes the HASH160 of b.

Parameters:b (bytes) – A byte string to compute the HASH160 of.
Returns:The RIPEMD-160 digest of the SHA256 hash of b.
two1.bitcoin.utils.hex_str_to_bytes(h)

Converts a hex-encoded string to bytes.

Parameters:h (str) – hex-encoded string to convert.
Returns:b – bytes corresponding to h.
Return type:bytes
two1.bitcoin.utils.key_hash_to_address(hash160, version=0)

Convert RIPEMD-160 hash to bitcoin address.

Parameters:
  • hash160 (bytes/str) – bitcoin hash160 to decode
  • version (int) – The version prefix
Returns:

base58 encoded bitcoin address

Return type:

(bitcoin address)

two1.bitcoin.utils.pack_compact_int(i)

See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers

Parameters:i (int) – Integer to be serialized.
Returns:b – Serialized bytes corresponding to i.
Return type:bytes
two1.bitcoin.utils.pack_u32(i)

Serializes a 32-bit integer into little-endian form.

Parameters:i (int) – integer to be serialized.
Returns:b – 4 bytes containing the little-endian serialization of i.
Return type:bytes
two1.bitcoin.utils.pack_u64(i)

Serializes a 64-bit integer into little-endian form.

Parameters:i (int) – integer to be serialized.
Returns:b – 8 bytes containing the little-endian serialization of i.
Return type:bytes
two1.bitcoin.utils.pack_var_str(s)

Serializes a variable length byte stream.

Parameters:s (bytes) – byte stream to serialize
Returns:b – Serialized bytes, prepended with the length of the byte stream.
Return type:bytes
two1.bitcoin.utils.rand_bytes(n, secure=True)

Returns n random bytes.

Parameters:
  • n (int) – number of bytes to return.
  • secure (bool) – If True, uses os.urandom to generate cryptographically secure random bytes. Otherwise, uses random.randint() which generates pseudo-random numbers.
Returns:

b – n random bytes.

Return type:

bytes

two1.bitcoin.utils.render_int(n)

Renders an int in the shortest possible form.

When packing the height into the coinbase script, the integer representing the height must be encoded in the shortest possible manner. See: https://bitcoin.org/en/developer-reference#coinbase.

Parameters:n (int) – number to be encoded.
Returns:b – bytes representing n in the shortest possible form.
Return type:bytes
two1.bitcoin.utils.target_to_bits(target)

Creates a compact target representation for a given target.

Parameters:target (Bignum) – The long-form target to make compact.
Returns:ct – Compact target
Return type:int
two1.bitcoin.utils.unpack_compact_int(bytestr)

See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers

Parameters:bytestr (bytes) – bytes containing an unsigned integer to be deserialized.
Returns:n – deserialized integer.
Return type:int
two1.bitcoin.utils.unpack_u32(b)

Deserializes a 32-bit integer from bytes.

Parameters:b (bytes) – At least 4 bytes containing the serialized integer.
Returns:(i, b) – A tuple containing the deserialized integer and the remainder of the byte stream.
Return type:tuple
two1.bitcoin.utils.unpack_u64(b)

Deserializes a 64-bit integer from bytes.

Parameters:b (bytes) – At least 8 bytes containing the serialized integer.
Returns:(i, b) – A tuple containing the deserialized integer and the remainder of the byte stream.
Return type:tuple
two1.bitcoin.utils.unpack_var_str(b)

Deserializes a variable length byte stream.

Parameters:b (bytes) – variable length byte stream to deserialize
Returns:(s, b) – A tuple containing the variable length byte stream and the remainder of the input byte stream.
Return type:tuple