bitcoinlib.services.services module
- class bitcoinlib.services.services.Cache(network, db_uri='')[source]
Bases:
objectStore transaction, utxo and address information in the 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 the number of blocks on the current network from the cache if recent data is available.
- Parameters:
never_expires (bool) – Always return the 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:
- estimatefee(blocks)[source]
Get fee estimation from cache for confirmation within the specified number of blocks.
Stored in the cache in three groups: low, medium and high fees.
- Parameters:
blocks (int) – Expected confirmation time in blocks.
- Return int:
Fee in the smallest network denominator (satoshi)
- getaddress(address)[source]
Get address information from the 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 the database cache.
- Parameters:
blockid (int, str) – Block height or block hash
- Return Block:
- getblocktransactions(height, page, limit)[source]
Get a 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 the cache. Returns an empty list if no transactions are found or caching is disabled.
- Parameters:
address (str) – Address string
after_txid (bytes) – Transaction ID of the 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 a list of unspent outputs (UTXO’s) for the specified address from the database cache.
Sorted from old to new, so the highest number of confirmations first.
- Parameters:
address (str) – Address string
after_txid (bytes) – Transaction ID of the 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 the cache
- param address:
Address string
- type address:
str
- param last_block:
Number or last block retrieved from the service provider. For instance, if an address contains a large number of transactions, and they will be retrieved in more than 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 the cache database
- Parameters:
block (Block) – The Block object to store in the cache
- Returns:
- store_blockcount(blockcount)[source]
Store network blockcount in the 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, index=None, commit=True)[source]
Store transaction in the cache. Use order number to determine order in a block
- Parameters:
t (Transaction) – The Transaction object
index (int) – Order in block
commit (bool) – Commit transaction to the database. Default is True. Can be disabled if a larger number of transactions are added to the cache, so you can commit outside this method.
- Returns:
- store_utxo(txid, index_n, commit=True)[source]
Store utxo in cache. Updates only known transaction outputs for transactions which are fully cached
- Parameters:
txid (str) – Transaction ID
index_n (int) – Index number of output
commit (bool) – 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, wallet_name=None, provider_name=None)[source]
Bases:
objectClass 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 provider fails to correctly respond, the Service class will try another available provider.
Create a service object for the specified network. By default, the object connects 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.
wallet_name (str) – Name of wallet if connecting to bitcoin node
provider_name (str) – Name of a specific provider to connect to. Note this is different from the providers list argument: the lists mention a type of provider such as ‘blockbook’ or ‘bcoin’, the provider name is a key in the providers.json dictionary file such as ‘bcoin.testnet.localhost’.
- blockcount()[source]
Get the latest block number: The block number of the last block in the longest chain on the Blockchain.
Block count is cashed for BLOCK_COUNT_CACHE_TIME seconds to avoid too many calls to service providers.
- Return int:
- estimatefee(blocks=5, 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.
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 the block with the specified block height or block hash from service providers.
If parse_transaction is set to True, a list of Transaction objects will be returned otherwise a list of transaction IDs.
Some providers require 1 or 2 extra requests 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 and limit=4 only transaction 5 to 8 are returned to the Block’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 25 if parse transaction is enabled, otherwise returns all txid’s (9999)
- Return Block:
- getcacheaddressinfo(address)[source]
Get address information from the cache. I.e. balance, number of transactions, number of utxo’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 the current network. Such as difficulty, latest block, mempool size and network hashrate.
- Return dict:
- getinputvalues(t)[source]
Retrieve values for transaction inputs for a 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) – A Transaction object
- Return Transaction:
- getrawblock(blockid)[source]
Get a raw block as a hexadecimal string for a block with a 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 a 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 the specified address.
Sorted from old to new, so transactions with the highest number of confirmations first.
- Parameters:
address (str) – Address string
after_txid (str) – Transaction ID of the 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 a list of unspent outputs (UTXO’s) for the specified address.
Sorted from old to new, so the highest number of confirmations first.
- Parameters:
address (str) – Address string
after_txid (str) – Transaction ID of the 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. Sometimes ignored by service providers if more results are returned by default.
- Return dict:
UTXO’s per address
- isspent(txid, output_n)[source]
Check if the output with the provided transaction ID and output number is already 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 a transaction with this hash exists in memory pool
- Return list: