bitcoinlib.services.services module

class bitcoinlib.services.services.Cache(network, db_uri='')[source]

Bases: object

Store transaction, utxo and address information in database to increase speed and avoid duplicate calls to service providers.

Once confirmed a transaction is immutable so we have to fetch it from a service provider only once. When checking for new transactions or utxo’s for a certain address we only have to check the new blocks.

This class is used by the Service class and normally you won’t need to access it directly.

Open Cache class

Parameters
  • network (str, Network) – Specify network used

  • db_uri (str) – Database to use for caching

blockcount(never_expires=False)[source]

Get number of blocks on the current network from cache if recent data is available.

Parameters

never_expires (bool) – Always return latest blockcount found. Can be used to avoid return to old blocks if service providers are not up-to-date.

Return int

cache_enabled()[source]

Check if caching is enabled. Returns False if SERVICE_CACHING_ENABLED is False or no session is defined.

Return bool

commit()[source]

Commit queries in self.session. Rollback if commit fails.

Returns

estimatefee(blocks)[source]

Get fee estimation from cache for confirmation within specified amount of blocks.

Stored in cache in three groups: low, medium and high fees.

Parameters

blocks (int) – Expection confirmation time in blocks.

Return int

Fee in smallest network denominator (satoshi)

getaddress(address)[source]

Get address information from cache, with links to transactions and utxo’s and latest update information.

Parameters

address (str) – Address string

Return DbCacheAddress

An address cache database object

getblock(blockid)[source]

Get specific block from database cache.

Parameters

blockid (int, str) – Block height or block hash

Return Block

getblocktransactions(height, page, limit)[source]

Get range of transactions from a block

Parameters
  • height (int) – Block height

  • page (int) – Transaction page

  • limit (int) – Number of transactions per page

Returns

getrawtransaction(txid)[source]

Get a raw transaction string from the database cache if available

Parameters

txid (bytes) – Transaction identification hash

Return str

Raw transaction as hexstring

gettransaction(txid)[source]

Get transaction from cache. Returns False if not available

Parameters

txid (bytes) – Transaction identification hash

Return Transaction

A single Transaction object

gettransactions(address, after_txid='', limit=20)[source]

Get transactions from cache. Returns empty list if no transactions are found or caching is disabled.

Parameters
  • address (str) – Address string

  • after_txid (bytes) – Transaction ID of last known transaction. Only check for transactions after given tx id. Default: Leave empty to return all transaction. If used only provide a single address

  • limit (int) – Maximum number of transactions to return

Return list

List of Transaction objects

getutxos(address, after_txid='')[source]

Get list of unspent outputs (UTXO’s) for specified address from database cache.

Sorted from old to new, so highest number of confirmations first.

Parameters
  • address (str) – Address string

  • after_txid (bytes) – Transaction ID of last known transaction. Only check for utxos after given tx id. Default: Leave empty to return all utxos.

Return dict

UTXO’s per address

store_address(address, last_block=None, balance=0, n_utxos=None, txs_complete=False, last_txid=None)[source]

Store address information in cache

param address

Address string

type address

str

param last_block

Number or last block retrieved from service provider. For instance if address contains a large number of transactions and they will be retrieved in more then one request.

type last_block

int

param balance

Total balance of address in sathosis, or smallest network detominator

type balance

int

param n_utxos

Total number of UTXO’s for this address

type n_utxos

int

param txs_complete

True if all transactions for this address are added to cache

type txs_complete

bool

param last_txid

Transaction ID of last transaction downloaded from blockchain

type last_txid

bytes

. :return:

store_block(block)[source]

Store block in cache database

Parameters

block (Block) – Block

Returns

store_blockcount(blockcount)[source]

Store network blockcount in cache for 60 seconds

Parameters

blockcount (int, str) – Number of latest block

Returns

store_estimated_fee(blocks, fee)[source]

Store estimated fee retrieved from service providers in cache.

Parameters
  • blocks (int) – Confirmation within x blocks

  • fee (int) – Estimated fee in Sathosis

Returns

store_transaction(t, order_n=None, commit=True)[source]

Store transaction in cache. Use order number to determine order in a block

Parameters
  • t (Transaction) – Transaction

  • order_n (int) – Order in block

  • commit – Commit transaction to database. Default is True. Can be disabled if a larger number of transactions are added to cache, so you can commit outside this method.

Returns

class bitcoinlib.services.services.Service(network='bitcoin', min_providers=1, max_providers=1, providers=None, timeout=5, cache_uri=None, ignore_priority=False, exclude_providers=None, max_errors=4, strict=True)[source]

Bases: object

Class to connect to various cryptocurrency service providers. Use to receive network and blockchain information, get specific transaction information, current network fees or push a raw transaction.

The Service class connects to 1 or more service providers at random to retrieve or send information. If a service providers fails to correctly respond the Service class will try another available provider.

Create a service object for the specified network. By default, the object connect to 1 service provider, but you can specify a list of providers or a minimum or maximum number of providers.

Parameters
  • network (str, Network) – Specify network used

  • min_providers (int) – Minimum number of providers to connect to. Default is 1. Use for instance to receive fee information from a number of providers and calculate the average fee.

  • max_providers (int) – Maximum number of providers to connect to. Default is 1.

  • providers (list of str) – List of providers to connect to. Default is all providers and select a provider at random.

  • timeout (int) – Timeout for web requests. Leave empty to use default from config settings

  • cache_uri (str) – Database to use for caching

  • ignore_priority (bool) – Ignores provider priority if set to True. Could be used for unit testing, so no providers are missed when testing. Default is False

  • exclude_providers (list of str) – Exclude providers in this list, can be used when problems with certain providers arise.

  • strict (bool) – Strict checks of valid signatures, scripts and transactions. Normally use strict=True for wallets, transaction validations etcetera. For blockchain parsing strict=False should be used, but be sure to check warnings in the log file. Default is True.

blockcount()[source]

Get latest block number: The block number of last block in longest chain on the Blockchain.

Block count is cashed for BLOCK_COUNT_CACHE_TIME seconds to avoid to many calls to service providers.

Return int

estimatefee(blocks=3, priority='')[source]

Estimate fee per kilobyte for a transaction for this network with expected confirmation within a certain amount of blocks

Parameters
  • blocks (int) – Expected confirmation time in blocks. Default is 3.

  • priority (str) – Priority for transaction: can be ‘low’, ‘medium’ or ‘high’. Overwrites value supplied in ‘blocks’ argument

Return int

Fee in the smallest network denominator (satoshi)

getbalance(addresslist, addresses_per_request=5)[source]

Get total balance for address or list of addresses

Parameters
  • addresslist (list, str) – Address or list of addresses

  • addresses_per_request (int) – Maximum number of addresses per request. Default is 5. Use lower setting when you experience timeouts or service request errors, or higher when possible.

Return dict

Balance per address

getblock(blockid, parse_transactions=True, page=1, limit=None)[source]

Get block with specified block height or block hash from service providers.

If parse_transaction is set to True a list of Transaction object will be returned otherwise a list of transaction ID’s.

Some providers require 1 or 2 extra request per transaction, so to avoid timeouts or rate limiting errors you can specify a page and limit for the transaction. For instance with page=2, limit=4 only transaction 5 to 8 are returned in the Blocks’s ‘transaction’ attribute.

If you only use a local bcoin or bitcoind provider, make sure you set the limit to maximum (i.e. 9999) because all transactions are already downloaded when fetching the block.

>>> from bitcoinlib.services.services import Service
>>> srv = Service()
>>> b = srv.getblock(0)
>>> b
<Block(000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f, 0, transactions: 1)>
Parameters
  • blockid (str, int) – Hash or block height of block

  • parse_transactions (bool) – Return Transaction objects or just transaction ID’s. Default is return txids.

  • page (int) – Page number of transaction paging. Default is start from the beginning: 1

  • limit (int) – Maximum amount of transaction to return. Default is 10 is parse transaction is enabled, otherwise returns all txid’s (9999)

Return Block

getcacheaddressinfo(address)[source]

Get address information from cache. I.e. balance, number of transactions, number of utox’s, etc

Cache will only be filled after all transactions for a specific address are retrieved (with gettransactions ie)

Parameters

address (str) – address string

Return dict

getinfo()[source]

Returns info about current network. Such as difficulty, latest block, mempool size and network hashrate.

Return dict

getinputvalues(t)[source]

Retrieve values for transaction inputs for given Transaction.

Raw transactions as stored on the blockchain do not contain the input values but only the previous transaction hash and index number. This method retrieves the previous transaction and reads the value.

Parameters

t (Transaction) – Transaction

Return Transaction

getrawblock(blockid)[source]

Get raw block as hexadecimal string for block with specified hash or block height.

Not many providers offer this option, and it can be slow, so it is advised to use a local client such as bitcoind.

Parameters

blockid (str, int) – Block hash or block height

Return str

getrawtransaction(txid)[source]

Get a raw transaction by its transaction hash

Parameters

txid (str) – Transaction identification hash

Return str

Raw transaction as hexstring

gettransaction(txid)[source]

Get a transaction by its transaction hash. Convert to Bitcoinlib Transaction object.

Parameters

txid (str) – Transaction identification hash

Return Transaction

A single transaction object

gettransactions(address, after_txid='', limit=20)[source]

Get all transactions for specified address.

Sorted from old to new, so transactions with highest number of confirmations first.

Parameters
  • address (str) – Address string

  • after_txid (str) – Transaction ID of last known transaction. Only check for transactions after given tx id. Default: Leave empty to return all transaction. If used only provide a single address

  • limit (int) – Maximum number of transactions to return

Return list

List of Transaction objects

getutxos(address, after_txid='', limit=20)[source]

Get list of unspent outputs (UTXO’s) for specified address.

Sorted from old to new, so highest number of confirmations first.

Parameters
  • address (str) – Address string

  • after_txid (str) – Transaction ID of last known transaction. Only check for utxos after given tx id. Default: Leave empty to return all utxos.

  • limit (int) – Maximum number of utxo’s to return

Return dict

UTXO’s per address

isspent(txid, output_n)[source]

Check if the output with provided transaction ID and output number is spent.

Parameters
  • txid (str) – Transaction ID hex

  • output_n (int) – Output number

Return bool

mempool(txid='')[source]

Get list of all transaction IDs in the current mempool

A full list of transactions ID’s will only be returned if a bcoin or bitcoind client is available. Otherwise specify the txid option to verify if a transaction is added to the mempool.

Parameters

txid (str) – Check if transaction with this hash exists in memory pool

Return list

sendrawtransaction(rawtx)[source]

Push a raw transaction to the network

Parameters

rawtx (str) – Raw transaction as hexstring or bytes

Return dict

Send transaction result

exception bitcoinlib.services.services.ServiceError(msg='')[source]

Bases: Exception