pycoin API

Note

pycoin started out as a loose collection of utilities, and is slowly evolving to be a more cohesive API.

Networks

A “network” is a particular coin, such as Bitcoin Mainnet or Bitcoin Testnet. There are two main ways to fetch a network:

from pycoin.symbols.btc import network

or

from pycoin.networks.registry import network_for_netcode
network = network_for_netcode("BTC")

These are the starting points. Nearly all API for a network can be accessed by drilling down below the network object.

Some useful network attributes include:

network.Tx
the class for a transaction
network.Block
the class for a block
network.message
message api, to pack and parse messages used by bitcoin’s peer-to-peer protocol
network.keychain
an object to aggregate private key information, useful for signing transactions
network.parse
for parsing human-readable items like keys, WIFs, addresses
network.contract
api for creating standard scripts in bitcoin
network.address
includes for_script API for turning a TxOut puzzle script into an address
network.keys
api for creating private keys, public keys, and hierarchical keys, both BIP32 and Electrum
network.generator
api for signing messages and verifying signed messages
network.validator
api for validating whether or not transactions are correctly signed
network.tx_utils
shortcuts for building and signing transactions
network.who_signed
utilities to determine which public keys have signed partially signed multisig transactions

network.Tx

class pycoin.coins.Tx.Tx(*args, **kwargs)[source]
class TxIn(*args, **kwargs)

The input part of a Tx that specifies where funds come from.

class TxOut(*args, **kwargs)

The output part of a Tx that specifies where funds go.

as_bin(*args, **kwargs)[source]

Returns a binary blob containing the streamed transaction.

For information about the parameters, see Tx.stream

Returns:binary blob that would parse to the given transaction
as_hex(*args, **kwargs)[source]

Returns a text string containing the streamed transaction encoded as hex.

For information about the parameters, see Tx.stream

Returns:hex string that would parse to the given transaction
bad_solution_count(*args, **kwargs)[source]

Return a count of how many TxIn objects are not correctly solved.

check()[source]

Basic checks that don’t depend on network or block context.

classmethod from_bin(blob)[source]

Return the Tx for the given binary blob.

Parameters:blob – a binary blob containing a transaction streamed in standard form. The blob may also include the unspents (a nonstandard extension, optionally written by Tx.stream), and they will also be parsed.
Returns:Tx

If parsing fails, an exception is raised.

classmethod from_hex(hex_string)[source]

Return the Tx for the given hex string.

Parameters:hex_string – a hex string containing a transaction streamed in standard form. The blob may also include the unspents (a nonstandard extension, optionally written by Tx.stream), and they will also be parsed.
Returns:Tx

If parsing fails, an exception is raised.

hash(hash_type=None)[source]

Return the hash for this Tx object.

id()[source]

Return the human-readable hash for this Tx object.

classmethod parse(f)[source]

Parse a transaction Tx from the file-like object f.

set_unspents(unspents)[source]

Set the unspent inputs for a transaction.

Parameters:unspents – a list of TxOut (or the subclass Spendable) objects corresponding to the TxIn objects for this transaction (same number of items in each list)
sign(*args, **kwargs)[source]

Sign all transaction inputs. The parameters vary depending upon the way the coins being spent are encumbered.

stream(f, *args, **kwargs)[source]

Stream a transaction Tx to the file-like object f.

class pycoin.coins.Tx.TxIn(*args, **kwargs)[source]

The input part of a Tx that specifies where funds come from.

class pycoin.coins.Tx.TxOut(*args, **kwargs)[source]

The output part of a Tx that specifies where funds go.

network.Block

class pycoin.block.Block(version, previous_block_hash, merkle_root, timestamp, difficulty, nonce)[source]

A Block is an element of the Bitcoin chain.

as_bin()[source]

Return the block (or header) as binary.

as_hex()[source]

Return the block (or header) as hex.

check_merkle_hash()[source]

Raise a BadMerkleRootError if the Merkle hash of the transactions does not match the Merkle hash included in the block.

hash()[source]

Calculate the hash for the block header. Note that this has the bytes in the opposite order from how the header is usually displayed (so the long string of 00 bytes is at the end, not the beginning).

id()[source]

Returns the hash of the block displayed with the bytes in the order they are usually displayed in.

classmethod parse(f, include_transactions=True, include_offsets=None, check_merkle_hash=True)[source]

Parse the Block from the file-like object

classmethod parse_as_header(f)[source]

Parse the Block header from the file-like object

previous_block_id()[source]

Returns the hash of the previous block, with the bytes in the order they are usually displayed in.

stream(f)[source]

Stream the block header in the standard way to the file-like object f. The Block subclass also includes the transactions.

stream_header(f)[source]

Stream the block header in the standard way to the file-like object f.

network.message

message.pack(**kwargs)
message.parse(data)

InvItem Module

class pycoin.message.InvItem.InvItem(item_type, data, dont_check=False)[source]

Bases: object

classmethod parse(f)[source]
stream(f)[source]

PeerAddress Module

class pycoin.message.PeerAddress.PeerAddress(services, ip_bin, port)[source]

Bases: object

host()[source]
classmethod parse(f)[source]
stream(f)[source]
pycoin.message.PeerAddress.ip_bin_to_ip4_addr(ip_bin)[source]
pycoin.message.PeerAddress.ip_bin_to_ip6_addr(ip_bin)[source]

network.keychain

class pycoin.key.Keychain.Keychain(sqlite3_db=None)[source]

network.parse

class pycoin.networks.ParseAPI.ParseAPI(network, bip32_prv_prefix=None, bip32_pub_prefix=None, address_prefix=None, pay_to_script_prefix=None, bech32_hrp=None, wif_prefix=None, sec_prefix=None)[source]
address(s)[source]

Parse an address, any of p2pkh, p2sh, p2pkh_segwit, or p2sh_segwit. Return a Contract, or None.

bip32(s)[source]

Parse a bip32 public key from a text string, either a seed, a prv or a pub. Return a BIP32 or None.

bip32_prv(s)[source]

Parse a bip32 private key from a text string (“xprv” type). Return a BIP32 or None.

bip32_pub(s)[source]

Parse a bip32 public key from a text string (“xpub” type). Return a BIP32 or None.

bip32_seed(s)[source]

Parse a bip32 private key from a seed. Return a BIP32 or None.

electrum_prv(s)[source]

Parse an electrum private key from a text string in seed form (“E:xxx” where xxx is a 64-character hex string). Return a ElectrumWallet or None.

electrum_pub(s)[source]

Parse an electrum public key from a text string in seed form (“E:xxx” where xxx is a 128-character hex string). Return a ElectrumWallet or None.

electrum_seed(s)[source]

Parse an electrum key from a text string in seed form (“E:xxx” where xxx is a 32-character hex string). Return a ElectrumWallet or None.

hierarchical_key(s)[source]

Parse text as some kind of hierarchical key. Return a subclass of Key, or None.

input(s)[source]

NOT YET SUPPORTED

p2pkh(s)[source]

Parse a pay-to-public-key-hash address. Return a Contract or None.

p2pkh_segwit(s)[source]

Parse a pay-to-pubkey-hash segwit address. Return a Contract or None.

p2sh(s)[source]

Parse a pay-to-script-hash address. Return a Contract or None.

p2sh_segwit(s)[source]

Parse a pay-to-script-hash segwit address. Return a Contract or None.

parse_b58_hashed(s)[source]

Override me to change how the b58 hashing check is done.

payable(s)[source]

Parse text as either an address or a script to be compiled. Return a Contract, or None.

private_key(s)[source]

Parse text as some kind of private key. Return a subclass of Key, or None.

public_key(s)[source]

Parse text as either a public pair or an sec. Return a subclass of Key, or None.

public_pair(s)[source]

Parse a public pair X/Y or X,Y where X is a coordinate and Y is a coordinate or the string “even” or “odd”. Return a Key or None.

script(s)[source]

Parse a script by compiling it. Return a Contract or None.

script_preimage(s)[source]

NOT YET SUPPORTED

sec(s)[source]

Parse a public pair as a text SEC. Return a Key or None.

secret(s)[source]

Parse text either a private key or a private hierarchical key. Return a subclass of Key, or None.

secret_exponent(s)[source]

Parse an integer secret exponent. Return a Key or None.

spendable(s)[source]

NOT YET SUPPORTED

tx(s)[source]

NOT YET SUPPORTED

wif(s)[source]

Parse a WIF. Return a Key or None.

network.contract

classmethod contract.for_address(address)
classmethod contract.for_p2pk(sec)
classmethod contract.for_p2pkh(hash160)
classmethod contract.for_p2pkh_wit(hash160)
classmethod contract.for_p2sh(hash160)
classmethod contract.for_p2sh_wit(hash256)
classmethod contract.for_multisig(m, sec_keys)
classmethod contract.for_nulldata(data)
classmethod contract.for_p2s(underlying_script)
classmethod contract.for_p2s_wit(underlying_script)
classmethod contract.for_info(info)
classmethod contract.info_for_script(script)

network.address

pycoin.symbols.btc.network.address

network.keys

keys.public(is_compressed=None)
keys.private(is_compressed=True)
keys.bip32_seed()
keys.bip32_deserialize()
keys.electrum_seed()
keys.electrum_private()
class pycoin.symbols.btc.network.keys.InvalidSecretExponentError
class pycoin.symbols.btc.network.keys.InvalidPublicPairError

network.generator

Most bitcoin-like cryptocurrencies use an ECC group called secp256k1 for digital signatures. The ecdsa.secp256k1 generator for this group provides most of the functionality you will need.

from pycoin.symbols.btc import network
public_key = network.generator * 1
print(public_key)

For bitcoin, network.generator is pycoin.ecdsa.secp256k1.secp256k1_generator, which is an instance of a Generator.

network.msg

classmethod msg.sign(key, message, verbose=False)

Return a signature, encoded in Base64, which can be verified by anyone using the public key.

classmethod msg.verify(key_or_address, signature, message=None, msg_hash=None)

Take a signature, encoded in Base64, and verify it against a key object (which implies the public key), or a specific base58-encoded pubkey hash.

classmethod msg.parse_signed(msg_in)

Take an “armoured” message and split into the message body, signing address and the base64 signature. Should work on all altcoin networks, and should accept both Inputs.IO and Multibit formats but not Armory.

Looks like RFC2550 <https://www.ietf.org/rfc/rfc2440.txt> was an “inspiration” for this, so in case of confusion it’s a reference, but I’ve never found a real spec for this. Should be a BIP really.

classmethod msg.hash_for_signing(msg)

Return a hash of msg, according to odd bitcoin method: double SHA256 over a bitcoin encoded stream of two strings: a fixed magic prefix and the actual message.

classmethod msg.signature_for_message_hash(secret_exponent, msg_hash, is_compressed)

Return a signature, encoded in Base64, of msg_hash.

classmethod msg.pair_for_message_hash(signature, msg_hash)

Take a signature, encoded in Base64, and return the pair it was signed by. May raise EncodingError (from _decode_signature)

network.validator

class pycoin.symbols.btc.network.validator.ScriptError
class pycoin.symbols.btc.network.validator.ValidationFailureError
pycoin.symbols.btc.network.validator.errno

alias of pycoin.satoshi.errno

pycoin.symbols.btc.network.validator.flags

alias of pycoin.satoshi.flags

network.tx_utils

tx_utils.create_tx(**kwargs)
tx_utils.sign_tx(**kwargs)
tx_utils.create_signed_tx(**kwargs)
tx_utils.split_with_remainder(**kwargs)
tx_utils.distribute_from_split_pool(fee)
Parameters:
  • tx – a transaction
  • fee – integer, satoshi value to set aside for transaction fee

This function looks at TxOut items of a transaction tx and and puts TxOut items with a coin value of zero into a “split pool”. Funds not explicitly claimed by the fee or other TxOut items are shared as equally as possible among the split pool. If the amount to be split does not divide evenly, some of the earlier TxOut items will get an extra satoshi. This function modifies tx in place.

network.who_signed

classmethod who_signed.solution_blobs(tx, tx_in_idx)

This iterator yields data blobs that appear in the the last solution_script or the witness.

classmethod who_signed.extract_signatures(tx, tx_in_idx)
classmethod who_signed.extract_secs(tx, tx_in_idx)

For a given script solution, iterate yield its sec blobs

classmethod who_signed.public_pairs_for_script(tx, tx_in_idx, generator)

For a given script, iterate over and pull out public pairs encoded as sec values.

classmethod who_signed.public_pairs_signed(tx, tx_in_idx)
classmethod who_signed.who_signed_tx(tx, tx_in_idx)

Given a transaction (tx) an input index (tx_in_idx), attempt to figure out which addresses where used in signing (so far). This method depends on tx.unspents being properly configured. This should work on partially-signed MULTISIG transactions (it will return as many addresses as there are good signatures). Returns a list of (public_pairs, sig_type) pairs.