python-bitcoinlib¶
This Python2/3 library provides an easy interface to the bitcoin data structures and protocol. The approach is low-level and “ground up”, with a focus on providing tools to manipulate the internals of how Bitcoin works.
Getting Started¶
Requirements¶
To install python-bitcoinlib:
sudo apt-get install libssl-dev
pip install python-bitcoinlib
# Or for the latest git version
pip install git+https://github.com/petertodd/python-bitcoinlib
The RPC interface, bitcoin.rpc
, is designed to work with Bitcoin Core v0.9.
Older versions mostly work but there do exist some incompatibilities.
Example Code¶
See examples/ directory. For instance this example creates a transaction spending a pay-to-script-hash transaction output:
$ PYTHONPATH=. examples/spend-pay-to-script-hash-txout.py
<hex-encoded transaction>
Also see dust-b-gone for a simple example of Bitcoin Core wallet interaction through the RPC interface: https://github.com/petertodd/dust-b-gone
Selecting the chain to use¶
Do the following:
import bitcoin
bitcoin.SelectParams(NAME)
Where NAME is one of ‘testnet’, ‘mainnet’, or ‘regtest’. The chain currently selected is a global variable that changes behavior everywhere, just like in the Satoshi codebase.
Advisories¶
Mutable vs. Immutable objects¶
Like the Bitcoin Core codebase CTransaction is immutable and CMutableTransaction is mutable; unlike the Bitcoin Core codebase this distinction also applies to COutPoint, CTxIn, CTxOut, and CBlock.
Endianness Gotchas¶
Rather confusingly Bitcoin Core shows transaction and block hashes as little-endian hex rather than the big-endian the rest of the world uses for SHA256. python-bitcoinlib provides the convenience functions x() and lx() in bitcoin.core to convert from big-endian and little-endian hex to raw bytes to accomodate this. In addition see b2x() and b2lx() for conversion from bytes to big/little-endian hex.
Consensus-critical API¶
Core¶
Basic core definitions, datastructures, and (context-independent) validation
-
class
bitcoin.core.
CBlock
(nVersion=2, hashPrevBlock='x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00', hashMerkleRoot='x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00', nTime=0, nBits=0, nNonce=0, vtx=())[source]¶ A block including all transactions in it
-
GetHash
()[source]¶ Return the block hash
Note that this is the hash of the header, not the entire serialized block.
-
static
build_merkle_tree_from_txids
(txids)[source]¶ Build a full CBlock merkle tree from txids
txids - iterable of txids
Returns a new merkle tree in deepest first order. The last element is the merkle root.
WARNING! If you’re reading this because you’re learning about crypto and/or designing a new system that will use merkle trees, keep in mind that the following merkle tree algorithm has a serious flaw related to duplicate txids, resulting in a vulnerability. (CVE-2012-2459) Bitcoin has since worked around the flaw, but for new applications you should use something different; don’t just copy-and-paste this code without understanding the problem first.
-
calc_merkle_root
()[source]¶ Calculate the merkle root
The calculated merkle root is not cached; every invocation re-calculates it from scratch.
-
vMerkleTree
¶
-
vtx
¶
-
-
class
bitcoin.core.
CBlockHeader
(nVersion=2, hashPrevBlock='x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00', hashMerkleRoot='x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00', nTime=0, nBits=0, nNonce=0)[source]¶ A block header
-
difficulty
¶
-
hashMerkleRoot
¶
-
hashPrevBlock
¶
-
nBits
¶
-
nNonce
¶
-
nTime
¶
-
nVersion
¶
-
-
class
bitcoin.core.
CMutableOutPoint
(hash='x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00', n=4294967295)[source]¶ A mutable COutPoint
-
GetHash
()¶ Return the hash of the serialized object
-
-
class
bitcoin.core.
CMutableTransaction
(vin=None, vout=None, nLockTime=0, nVersion=1)[source]¶ A mutable transaction
-
GetHash
()¶ Return the hash of the serialized object
-
-
class
bitcoin.core.
CMutableTxIn
(prevout=None, scriptSig=CScript([]), nSequence=4294967295)[source]¶ A mutable CTxIn
-
GetHash
()¶ Return the hash of the serialized object
-
-
class
bitcoin.core.
CMutableTxOut
(nValue=-1, scriptPubKey=CScript([]))[source]¶ A mutable CTxOut
-
GetHash
()¶ Return the hash of the serialized object
-
-
class
bitcoin.core.
COutPoint
(hash='x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00', n=4294967295)[source]¶ The combination of a transaction hash and an index n into its vout
-
classmethod
from_outpoint
(outpoint)[source]¶ Create an immutable copy of an existing OutPoint
If output is already immutable (outpoint.__class__ is COutPoint) it is returned directly.
-
hash
¶
-
n
¶
-
classmethod
-
class
bitcoin.core.
CTransaction
(vin=(), vout=(), nLockTime=0, nVersion=1)[source]¶ A transaction
-
classmethod
from_tx
(tx)[source]¶ Create an immutable copy of a pre-existing transaction
If tx is already immutable (tx.__class__ is CTransaction) then it will be returned directly.
-
nLockTime
¶
-
nVersion
¶
-
vin
¶
-
vout
¶
-
classmethod
-
class
bitcoin.core.
CTxIn
(prevout=COutPoint(), scriptSig=CScript([]), nSequence=4294967295)[source]¶ An input of a transaction
Contains the location of the previous transaction’s output that it claims, and a signature that matches the output’s public key.
-
classmethod
from_txin
(txin)[source]¶ Create an immutable copy of an existing TxIn
If txin is already immutable (txin.__class__ is CTxIn) it is returned directly.
-
nSequence
¶
-
prevout
¶
-
scriptSig
¶
-
classmethod
-
class
bitcoin.core.
CTxOut
(nValue=-1, scriptPubKey=CScript([]))[source]¶ An output of a transaction
Contains the public key that the next input must be able to sign with to claim it.
-
classmethod
from_txout
(txout)[source]¶ Create an immutable copy of an existing TxOut
If txout is already immutable (txout.__class__ is CTxOut) then it will be returned directly.
-
nValue
¶
-
scriptPubKey
¶
-
classmethod
-
bitcoin.core.
CheckBlock
(block, fCheckPoW=True, fCheckMerkleRoot=True, cur_time=None)[source]¶ Context independent CBlock checks.
CheckBlockHeader() is called first, which may raise a CheckBlockHeader exception, followed the block tests. CheckTransaction() is called for every transaction.
fCheckPoW - Check proof-of-work. fCheckMerkleRoot - Check merkle root matches transactions. cur_time - Current time. Defaults to time.time()
-
bitcoin.core.
CheckBlockHeader
(block_header, fCheckPoW=True, cur_time=None)[source]¶ Context independent CBlockHeader checks.
fCheckPoW - Check proof-of-work. cur_time - Current time. Defaults to time.time()
Raises CBlockHeaderError if block header is invalid.
-
bitcoin.core.
CheckProofOfWork
(hash, nBits)[source]¶ Check a proof-of-work
Raises CheckProofOfWorkError
-
bitcoin.core.
CheckTransaction
(tx)[source]¶ Basic transaction checks that don’t depend on any context.
Raises CheckTransactionError
-
class
bitcoin.core.
CoreChainParams
[source]¶ Define consensus-critical parameters of a given instance of the Bitcoin system
-
GENESIS_BLOCK
= None¶
-
NAME
= None¶
-
PROOF_OF_WORK_LIMIT
= None¶
-
SUBSIDY_HALVING_INTERVAL
= None¶
-
-
class
bitcoin.core.
CoreMainParams
[source]¶ -
GENESIS_BLOCK
= CBlock(1, lx(0000000000000000000000000000000000000000000000000000000000000000), lx(4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b), 1231006505, 0x1d00ffff, 0x7c2bac1d)¶
-
NAME
= u'mainnet'¶
-
PROOF_OF_WORK_LIMIT
= 26959946667150639794667015087019630673637144422540572481103610249215L¶
-
SUBSIDY_HALVING_INTERVAL
= 210000¶
-
-
class
bitcoin.core.
CoreRegTestParams
[source]¶ -
GENESIS_BLOCK
= CBlock(1, lx(0000000000000000000000000000000000000000000000000000000000000000), lx(4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b), 1296688602, 0x207fffff, 0x00000002)¶
-
NAME
= u'regtest'¶
-
PROOF_OF_WORK_LIMIT
= 57896044618658097711785492504343953926634992332820282019728792003956564819967L¶
-
SUBSIDY_HALVING_INTERVAL
= 150¶
-
-
class
bitcoin.core.
CoreTestNetParams
[source]¶ -
GENESIS_BLOCK
= CBlock(1, lx(0000000000000000000000000000000000000000000000000000000000000000), lx(4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b), 1296688602, 0x1d00ffff, 0x18aea41a)¶
-
NAME
= u'testnet'¶
-
-
exception
bitcoin.core.
ValidationError
[source]¶ Base class for all blockchain validation errors
Everything that is related to validating the blockchain, blocks, transactions, scripts, etc. is derived from this class.
-
bitcoin.core.
b2lx
(b)[source]¶ Convert bytes to a little-endian hex string
Lets you show uint256’s and uint160’s the way the Satoshi codebase shows them.
Bignum handling¶
Bignum routines
ECC Public Keys¶
ECC secp256k1 crypto routines
WARNING: This module does not mlock() secrets; your private keys may end up on disk in swap! Use with caution!
Scripts and Opcodes¶
Scripts
Functionality to build scripts, as well as SignatureHash(). Script evaluation is in bitcoin.core.scripteval
-
class
bitcoin.core.script.
CScript
[source]¶ Serialized script
A bytes subclass, so you can use this directly whenever bytes are accepted. Note that this means that indexing does not work - you’ll get an index by byte rather than opcode. This format was chosen for efficiency so that the general case would not require creating a lot of little CScriptOP objects.
iter(script) however does iterate by opcode.
-
GetSigOpCount
(fAccurate)[source]¶ Get the SigOp count.
fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details.
Note that this is consensus-critical.
-
has_canonical_pushes
()[source]¶ Test if script only uses canonical pushes
Not yet consensus critical; may be in the future.
-
is_p2sh
()[source]¶ Test if the script is a p2sh scriptPubKey
Note that this test is consensus-critical.
-
is_push_only
()[source]¶ Test if the script only contains pushdata ops
Note that this test is consensus-critical.
Scripts that contain invalid pushdata ops return False, matching the behavior in Bitcoin Core.
-
is_valid
()[source]¶ Return True if the script is valid, False otherwise
The script is valid if all PUSHDATA’s are valid; invalid opcodes do not make is_valid() return False.
-
raw_iter
()[source]¶ Raw iteration
Yields tuples of (opcode, data, sop_idx) so that the different possible PUSHDATA encodings can be accurately distinguished, as well as determining the exact opcode byte indexes. (sop_idx)
-
to_p2sh_scriptPubKey
(checksize=True)[source]¶ Create P2SH scriptPubKey from this redeemScript
That is, create the P2SH scriptPubKey that requires this script as a redeemScript to spend.
- checksize - Check if the redeemScript is larger than the 520-byte max
- pushdata limit; raise ValueError if limit exceeded.
Since a >520-byte PUSHDATA makes EvalScript() fail, it’s not actually possible to redeem P2SH outputs with redeem scripts >520 bytes.
-
-
exception
bitcoin.core.script.
CScriptTruncatedPushDataError
(msg, data)[source]¶ Invalid pushdata due to truncation
-
bitcoin.core.script.
FindAndDelete
(script, sig)[source]¶ Consensus critical, see FindAndDelete() in Satoshi codebase
-
bitcoin.core.script.
RawSignatureHash
(script, txTo, inIdx, hashtype)[source]¶ Consensus-correct SignatureHash
Returns (hash, err) to precisely match the consensus-critical behavior of the SIGHASH_SINGLE bug. (inIdx is not checked for validity)
If you’re just writing wallet software you probably want SignatureHash() instead.
Script evaluation/verification¶
Script evaluation
Be warned that there are highly likely to be consensus bugs in this code; it is unlikely to match Satoshi Bitcoin exactly. Think carefully before using this module.
-
exception
bitcoin.core.scripteval.
ArgumentsInvalidError
(opcode, msg, **kwargs)[source]¶ Arguments are invalid
-
bitcoin.core.scripteval.
EvalScript
(stack, scriptIn, txTo, inIdx, flags=())[source]¶ Evaluate a script
stack - Initial stack scriptIn - Script txTo - Transaction the script is a part of inIdx - txin index of the scriptSig flags - SCRIPT_VERIFY_* flags to apply
-
exception
bitcoin.core.scripteval.
EvalScriptError
(msg, sop=None, sop_data=None, sop_pc=None, stack=None, scriptIn=None, txTo=None, inIdx=None, flags=None, altstack=None, vfExec=None, pbegincodehash=None, nOpCount=None)[source]¶ Base class for exceptions raised when a script fails during EvalScript()
The execution state just prior the opcode raising the is saved. (if available)
-
exception
bitcoin.core.scripteval.
MissingOpArgumentsError
(opcode, s, n, **kwargs)[source]¶ Missing arguments
-
exception
bitcoin.core.scripteval.
VerifyOpFailedError
(opcode, **kwargs)[source]¶ A VERIFY opcode failed
-
bitcoin.core.scripteval.
VerifyScript
(scriptSig, scriptPubKey, txTo, inIdx, flags=())[source]¶ Verify a scriptSig satisfies a scriptPubKey
scriptSig - Signature scriptPubKey - PubKey txTo - Spending transaction inIdx - Index of the transaction input containing scriptSig
Raises a ValidationError subclass if the validation fails.
Serialization¶
Serialization routines
You probabably don’t need to use these directly.
-
exception
bitcoin.core.serialize.
DeserializationExtraDataError
(msg, obj, padding)[source]¶ Deserialized data had extra data at the end
Thrown by deserialize() when not all data is consumed during deserialization. The deserialized object and extra padding not consumed are saved.
-
class
bitcoin.core.serialize.
Serializable
[source]¶ Base class for serializable objects
-
exception
bitcoin.core.serialize.
SerializationTruncationError
[source]¶ Serialized data was truncated
Thrown by deserialize() and stream_deserialize()
-
bitcoin.core.serialize.
ser_read
(f, n)[source]¶ Read from a stream safely
Raises SerializationError and SerializationTruncationError appropriately. Use this instead of f.read() in your classes stream_(de)serialization() functions.
Non-consensus-critical API¶
Chain selection¶
-
class
bitcoin.
MainParams
[source]¶ -
BASE58_PREFIXES
= {u'SECRET_KEY': 128, u'SCRIPT_ADDR': 5, u'PUBKEY_ADDR': 0}¶
-
DEFAULT_PORT
= 8333¶
-
DNS_SEEDS
= ((u'bitcoin.sipa.be', u'seed.bitcoin.sipa.be'), (u'bluematt.me', u'dnsseed.bluematt.me'), (u'dashjr.org', u'dnsseed.bitcoin.dashjr.org'), (u'bitcoinstats.com', u'seed.bitcoinstats.com'), (u'xf2.org', u'bitseed.xf2.org'))¶
-
MESSAGE_START
= '\xf9\xbe\xb4\xd9'¶
-
RPC_PORT
= 8332¶
-
-
class
bitcoin.
RegTestParams
[source]¶ -
BASE58_PREFIXES
= {u'SECRET_KEY': 239, u'SCRIPT_ADDR': 196, u'PUBKEY_ADDR': 111}¶
-
DEFAULT_PORT
= 18444¶
-
DNS_SEEDS
= ()¶
-
MESSAGE_START
= '\xfa\xbf\xb5\xda'¶
-
RPC_PORT
= 18332¶
-
-
bitcoin.
SelectParams
(name)[source]¶ Select the chain parameters to use
name is one of ‘mainnet’, ‘testnet’, or ‘regtest’
Default chain is ‘mainnet’
-
class
bitcoin.
TestNetParams
[source]¶ -
BASE58_PREFIXES
= {u'SECRET_KEY': 239, u'SCRIPT_ADDR': 196, u'PUBKEY_ADDR': 111}¶
-
DEFAULT_PORT
= 18333¶
-
DNS_SEEDS
= ((u'bitcoin.petertodd.org', u'testnet-seed.bitcoin.petertodd.org'), (u'bluematt.me', u'testnet-seed.bluematt.me'))¶
-
MESSAGE_START
= '\x0b\x11\t\x07'¶
-
RPC_PORT
= 18332¶
-
Base58 encoding¶
Base58 encoding and decoding
Bloom filters¶
Bloom filter support
-
class
bitcoin.bloom.
CBloomFilter
(nElements, nFPRate, nTweak, nFlags)[source]¶ -
-
MAX_BLOOM_FILTER_SIZE
= 36000¶
-
MAX_HASH_FUNCS
= 50¶
-
UPDATE_ALL
= 1¶
-
UPDATE_MASK
= 3¶
-
UPDATE_NONE
= 0¶
-
UPDATE_P2PUBKEY_ONLY
= 2¶
-
-
bitcoin.bloom.
MurmurHash3
(x86_32)[source]¶ Used for bloom filters. See http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
Network communication¶
Network messages¶
members: | |
---|---|
undoc-members: |
Wallet-related code¶
Wallet-related functionality
Includes things like representing addresses and converting them to/from scriptPubKeys; currently there is no actual wallet support implemented.
members: | |
---|---|
undoc-members: |