bitcoin

bitcoin

class bitcoin.MainParams[source]

Bases: bitcoin.core.CoreMainParams

BASE58_PREFIXES = {u'PUBKEY_ADDR': 0, u'SCRIPT_ADDR': 5, u'SECRET_KEY': 128}
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'), (u'bitcoin.jonasschnelli.ch', u'seed.bitcoin.jonasschnelli.ch'))
MESSAGE_START = '\xf9\xbe\xb4\xd9'
RPC_PORT = 8332
class bitcoin.RegTestParams[source]

Bases: bitcoin.core.CoreRegTestParams

BASE58_PREFIXES = {u'PUBKEY_ADDR': 111, u'SCRIPT_ADDR': 196, u'SECRET_KEY': 239}
DEFAULT_PORT = 18444
DNS_SEEDS = ()
MESSAGE_START = '\xfa\xbf\xb5\xda'
RPC_PORT = 18443
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]

Bases: bitcoin.core.CoreTestNetParams

BASE58_PREFIXES = {u'PUBKEY_ADDR': 111, u'SCRIPT_ADDR': 196, u'SECRET_KEY': 239}
DEFAULT_PORT = 18333
DNS_SEEDS = ((u'testnetbitcoin.jonasschnelli.ch', u'testnet-seed.bitcoin.jonasschnelli.ch'), (u'petertodd.org', u'seed.tbtc.petertodd.org'), (u'bluematt.me', u'testnet-seed.bluematt.me'), (u'bitcoin.schildbach.de', u'testnet-seed.bitcoin.schildbach.de'))
MESSAGE_START = '\x0b\x11\t\x07'
RPC_PORT = 18332

base58

Base58 encoding and decoding

exception bitcoin.base58.Base58Error[source]

Bases: exceptions.Exception

exception bitcoin.base58.InvalidBase58Error[source]

Bases: bitcoin.base58.Base58Error

Raised on generic invalid base58 data, such as bad characters.

Checksum failures raise Base58ChecksumError specifically.

bitcoin.base58.encode(b)[source]

Encode bytes to a base58-encoded string

bitcoin.base58.decode(s)[source]

Decode a base58-encoding string, returning bytes

exception bitcoin.base58.Base58ChecksumError[source]

Bases: bitcoin.base58.Base58Error

Raised on Base58 checksum errors

class bitcoin.base58.CBase58Data(s)[source]

Bases: str

Base58-encoded data

Includes a version and checksum.

Initialize from base58-encoded string

Note: subclasses put your initialization routines here, but ignore the argument - that’s handled by __new__(), and .from_bytes() will call __init__() with None in place of the string.

classmethod from_bytes(data, nVersion)[source]

Instantiate from data and nVersion

to_bytes()[source]

Convert to bytes instance

Note that it’s the data represented that is converted; the checkum and nVersion is not included.

bloom

Bloom filter support

bitcoin.bloom.MurmurHash3(x86_32)[source]

Used for bloom filters. See http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp

class bitcoin.bloom.CBloomFilter(nElements, nFPRate, nTweak, nFlags)[source]

Bases: bitcoin.core.serialize.Serializable

Create a new bloom filter

The filter will have a given false-positive rate when filled with the given number of elements.

Note that if the given parameters will result in a filter outside the bounds of the protocol limits, the filter created will be as close to the given parameters as possible within the protocol limits. This will apply if nFPRate is very low or nElements is unreasonably high.

nTweak is a constant which is added to the seed value passed to the hash function It should generally always be a random value (and is largely only exposed for unit testing)

nFlags should be one of the UPDATE_* enums (but not _MASK)

IsRelevantAndUpdate(tx_hash)[source]
IsWithinSizeConstraints()[source]
MAX_BLOOM_FILTER_SIZE = 36000
MAX_HASH_FUNCS = 50
UPDATE_ALL = 1
UPDATE_MASK = 3
UPDATE_NONE = 0
UPDATE_P2PUBKEY_ONLY = 2
bloom_hash(nHashNum, vDataToHash)[source]
contains(elem)[source]

Test if the filter contains an element

elem may be a COutPoint or bytes

insert(elem)[source]

Insert an element in the filter.

elem may be a COutPoint or bytes

classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]

messages

class bitcoin.messages.MsgSerializable(protover=60002)[source]

Bases: bitcoin.core.serialize.Serializable

classmethod from_bytes(b, protover=60002)[source]
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
classmethod stream_deserialize(f, protover=60002)[source]
stream_serialize(f)[source]
to_bytes()[source]
class bitcoin.messages.msg_version(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'version'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_verack(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'verack'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_addr(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'addr'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_alert(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'alert'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_inv(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'inv'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_getdata(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'getdata'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_getblocks(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'getblocks'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_getheaders(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'getheaders'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_headers(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'headers'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_tx(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'tx'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_block(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'block'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_getaddr(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'getaddr'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_ping(protover=60002, nonce=0)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'ping'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_pong(protover=60002, nonce=0)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'pong'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]
class bitcoin.messages.msg_mempool(protover=60002)[source]

Bases: bitcoin.messages.MsgSerializable

command = 'mempool'
classmethod msg_deser(f, protover=60002)[source]
msg_ser(f)[source]

net

class bitcoin.net.CAddress(protover=60002)[source]

Bases: bitcoin.core.serialize.Serializable

classmethod stream_deserialize(f, without_time=False)[source]
stream_serialize(f, without_time=False)[source]
class bitcoin.net.CInv[source]

Bases: bitcoin.core.serialize.Serializable

classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]
typemap = {0: u'Error', 1: u'TX', 2: u'Block', 3: u'FilteredBlock', 4: u'CompactBlock'}
class bitcoin.net.CBlockLocator(protover=60002)[source]

Bases: bitcoin.core.serialize.Serializable

classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]
class bitcoin.net.CUnsignedAlert[source]

Bases: bitcoin.core.serialize.Serializable

classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]
class bitcoin.net.CAlert[source]

Bases: bitcoin.core.serialize.Serializable

classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]

rpc

Bitcoin Core RPC support

By default this uses the standard library json module. By monkey patching, a different implementation can be used instead, at your own risk:

>>> import simplejson
>>> import bitcoin.rpc
>>> bitcoin.rpc.json = simplejson

(simplejson is the externally maintained version of the same module and thus better optimized but perhaps less stable.)

exception bitcoin.rpc.JSONRPCError[source]

Bases: exceptions.Exception

JSON-RPC protocol error base class

Subclasses of this class also exist for specific types of errors; the set of all subclasses is by no means complete.

SUBCLS_BY_CODE = {-28: <class 'bitcoin.rpc.InWarmupError'>, -27: <class 'bitcoin.rpc.VerifyAlreadyInChainError'>, -26: <class 'bitcoin.rpc.VerifyRejectedError'>, -25: <class 'bitcoin.rpc.VerifyError'>, -8: <class 'bitcoin.rpc.InvalidParameterError'>, -5: <class 'bitcoin.rpc.InvalidAddressOrKeyError'>, -2: <class 'bitcoin.rpc.ForbiddenBySafeModeError'>}
exception bitcoin.rpc.ForbiddenBySafeModeError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -2
exception bitcoin.rpc.InvalidAddressOrKeyError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -5
exception bitcoin.rpc.InvalidParameterError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -8
exception bitcoin.rpc.VerifyError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -25
exception bitcoin.rpc.VerifyRejectedError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -26
exception bitcoin.rpc.VerifyAlreadyInChainError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -27
exception bitcoin.rpc.InWarmupError[source]

Bases: bitcoin.rpc.JSONRPCError

RPC_ERROR_CODE = -28
class bitcoin.rpc.RawProxy(service_url=None, service_port=None, btc_conf_file=None, timeout=30, **kwargs)[source]

Bases: bitcoin.rpc.BaseProxy

Low-level proxy to a bitcoin JSON-RPC service

Unlike Proxy, no conversion is done besides parsing JSON. As far as Python is concerned, you can call any method; JSONRPCError will be raised if the server does not recognize it.

class bitcoin.rpc.Proxy(service_url=None, service_port=None, btc_conf_file=None, timeout=30, **kwargs)[source]

Bases: bitcoin.rpc.BaseProxy

Proxy to a bitcoin RPC service

Unlike RawProxy, data is passed as bitcoin.core objects or packed bytes, rather than JSON or hex strings. Not all methods are implemented yet; you can use call to access missing ones in a forward-compatible way. Assumes Bitcoin Core version >= v0.16.0; older versions mostly work, but there are a few incompatibilities.

Create a proxy object

If service_url is not specified, the username and password are read out of the file btc_conf_file. If btc_conf_file is not specified, ~/.bitcoin/bitcoin.conf or equivalent is used by default. The default port is set according to the chain parameters in use: mainnet, testnet, or regtest.

Usually no arguments to Proxy() are needed; the local bitcoind will be used.

timeout - timeout in seconds before the HTTP interface times out

addnode(node)[source]
addnodeonetry(node)[source]
call(service_name, *args)[source]

Call an RPC method by name and raw (JSON encodable) arguments

dumpprivkey(addr)[source]

Return the private key matching an address

fundrawtransaction(tx, include_watching=False)[source]

Add inputs to a transaction until it has enough in value to meet its out value.

include_watching - Also select inputs which are watch only

Returns dict:

{‘tx’: Resulting tx,
‘fee’: Fee the resulting transaction pays, ‘changepos’: Position of added change output, or -1,

}

generate(numblocks)[source]

Mine blocks immediately (before the RPC call returns)

numblocks - How many blocks are generated immediately.

Returns iterable of block hashes generated.

getaccountaddress(account=None)[source]

Return the current Bitcoin address for receiving payments to this account.

getbalance(account=u'*', minconf=1, include_watchonly=False)[source]

Get the balance

account - The selected account. Defaults to “*” for entire wallet. It may be the default account using “”.

minconf - Only include transactions confirmed at least this many times. (default=1)

include_watchonly - Also include balance in watch-only addresses (see ‘importaddress’) (default=False)

getbestblockhash()[source]

Return hash of best (tip) block in longest block chain.

getblock(block_hash)[source]

Get block <block_hash>

Raises IndexError if block_hash is not valid.

getblockcount()[source]

Return the number of blocks in the longest block chain

getblockhash(height)[source]

Return hash of block in best-block-chain at height.

Raises IndexError if height is not valid.

getblockheader(block_hash, verbose=False)[source]

Get block header <block_hash>

verbose - If true a dict is returned with the values returned by
getblockheader that are not in the block header itself (height, nextblockhash, etc.)

Raises IndexError if block_hash is not valid.

getinfo()[source]

Return a JSON object containing various state info

getmininginfo()[source]

Return a JSON object containing mining-related information

getnewaddress(account=None)[source]

Return a new Bitcoin address for receiving payments.

If account is not None, it is added to the address book so payments received with the address will be credited to account.

getrawchangeaddress()[source]

Returns a new Bitcoin address, for receiving change.

This is for use with raw transactions, NOT normal use.

getrawmempool(verbose=False)[source]

Return the mempool

getrawtransaction(txid, verbose=False)[source]

Return transaction with hash txid

Raises IndexError if transaction not found.

verbose - If true a dict is returned instead with additional information on the transaction.

Note that if all txouts are spent and the transaction index is not enabled the transaction may not be available.

getreceivedbyaddress(addr, minconf=1)[source]

Return total amount received by given a (wallet) address

Get the amount received by <address> in transactions with at least [minconf] confirmations.

Works only for addresses in the local wallet; other addresses will always show zero.

addr - The address. (CBitcoinAddress instance)

minconf - Only include transactions confirmed at least this many times. (default=1)

gettransaction(txid)[source]

Get detailed information about in-wallet transaction txid

Raises IndexError if transaction not found in the wallet.

FIXME: Returned data types are not yet converted.

gettxout(outpoint, includemempool=True)[source]

Return details about an unspent transaction output.

Raises IndexError if outpoint is not found or was spent.

includemempool - Include mempool txouts

importaddress(addr, label=u'', rescan=True)[source]

Adds an address or pubkey to wallet without the associated privkey.

listunspent(minconf=0, maxconf=9999999, addrs=None)[source]

Return unspent transaction outputs in wallet

Outputs will have between minconf and maxconf (inclusive) confirmations, optionally filtered to only include txouts paid to addresses in addrs.

lockunspent(unlock, outpoints)[source]

Lock or unlock outpoints

removenode(node)[source]
sendmany(fromaccount, payments, minconf=1, comment=u'', subtractfeefromamount=[])[source]

Send amount to given addresses.

payments - dict with {address: amount}

sendrawtransaction(tx, allowhighfees=False)[source]

Submit transaction to local node and network.

allowhighfees - Allow even if fees are unreasonably high.

sendtoaddress(addr, amount, comment=u'', commentto=u'', subtractfeefromamount=False)[source]

Send amount to a given address

signrawtransaction(tx, *args)[source]

Sign inputs for transaction

FIXME: implement options

submitblock(block, params=None)[source]

Submit a new block to the network.

params is optional and is currently ignored by bitcoind. See https://en.bitcoin.it/wiki/BIP_0022 for full specification.

unlockwallet(password, timeout=60)[source]

Stores the wallet decryption key in memory for ‘timeout’ seconds.

password - The wallet passphrase.

timeout - The time to keep the decryption key in seconds. (default=60)

validateaddress(address)[source]

Return information about an address

signature

class bitcoin.signature.DERSignature(r, s, length)[source]

Bases: bitcoin.core.serialize.ImmutableSerializable

length
r
s
classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]

signmessage

class bitcoin.signmessage.BitcoinMessage(message=u'', magic=u'Bitcoin Signed Message:n')[source]

Bases: bitcoin.core.serialize.ImmutableSerializable

magic
message
classmethod stream_deserialize(f)[source]
stream_serialize(f)[source]
bitcoin.signmessage.SignMessage(key, message)[source]
bitcoin.signmessage.VerifyMessage(address, message, sig)[source]

wallet

Wallet-related functionality

Includes things like representing addresses and converting them to/from scriptPubKeys; currently there is no actual wallet support implemented.

exception bitcoin.wallet.CBitcoinAddressError[source]

Bases: bitcoin.base58.Base58Error

Raised when an invalid Bitcoin address is encountered

class bitcoin.wallet.CBitcoinAddress(s)[source]

Bases: bitcoin.base58.CBase58Data

A Bitcoin address

Initialize from base58-encoded string

Note: subclasses put your initialization routines here, but ignore the argument - that’s handled by __new__(), and .from_bytes() will call __init__() with None in place of the string.

classmethod from_bytes(data, nVersion)[source]
classmethod from_scriptPubKey(scriptPubKey)[source]

Convert a scriptPubKey to a CBitcoinAddress

Returns a CBitcoinAddress subclass, either P2SHBitcoinAddress or P2PKHBitcoinAddress. If the scriptPubKey is not recognized CBitcoinAddressError will be raised.

to_scriptPubKey()[source]

Convert an address to a scriptPubKey

class bitcoin.wallet.P2SHBitcoinAddress(s)[source]

Bases: bitcoin.wallet.CBitcoinAddress

Initialize from base58-encoded string

Note: subclasses put your initialization routines here, but ignore the argument - that’s handled by __new__(), and .from_bytes() will call __init__() with None in place of the string.

classmethod from_bytes(data, nVersion=None)[source]
classmethod from_redeemScript(redeemScript)[source]

Convert a redeemScript to a P2SH address

Convenience function: equivalent to P2SHBitcoinAddress.from_scriptPubKey(redeemScript.to_p2sh_scriptPubKey())

classmethod from_scriptPubKey(scriptPubKey)[source]

Convert a scriptPubKey to a P2SH address

Raises CBitcoinAddressError if the scriptPubKey isn’t of the correct form.

to_scriptPubKey()[source]

Convert an address to a scriptPubKey

class bitcoin.wallet.P2PKHBitcoinAddress(s)[source]

Bases: bitcoin.wallet.CBitcoinAddress

Initialize from base58-encoded string

Note: subclasses put your initialization routines here, but ignore the argument - that’s handled by __new__(), and .from_bytes() will call __init__() with None in place of the string.

classmethod from_bytes(data, nVersion=None)[source]
classmethod from_pubkey(pubkey, accept_invalid=False)[source]

Create a P2PKH bitcoin address from a pubkey

Raises CBitcoinAddressError if pubkey is invalid, unless accept_invalid is True.

The pubkey must be a bytes instance; CECKey instances are not accepted.

classmethod from_scriptPubKey(scriptPubKey, accept_non_canonical_pushdata=True, accept_bare_checksig=True)[source]

Convert a scriptPubKey to a P2PKH address

Raises CBitcoinAddressError if the scriptPubKey isn’t of the correct form.

accept_non_canonical_pushdata - Allow non-canonical pushes (default True)

accept_bare_checksig - Treat bare-checksig as P2PKH scriptPubKeys (default True)

to_scriptPubKey(nested=False)[source]

Convert an address to a scriptPubKey

class bitcoin.wallet.CKey(secret, compressed=True)[source]

Bases: object

An encapsulated private key

Attributes:

pub - The corresponding CPubKey for this private key

is_compressed - True if compressed

is_compressed
sign(hash)[source]
sign_compact(hash)[source]
exception bitcoin.wallet.CBitcoinSecretError[source]

Bases: bitcoin.base58.Base58Error

class bitcoin.wallet.CBitcoinSecret(s)[source]

Bases: bitcoin.base58.CBase58Data, bitcoin.wallet.CKey

A base58-encoded secret key

classmethod from_secret_bytes(secret, compressed=True)[source]

Create a secret key from a 32-byte secret