Library Reference

driver

class bigchaindb_driver.BigchainDB(*nodes, transport_class=<class 'bigchaindb_driver.transport.Transport'>, headers=None, timeout=20)[source]

A BigchainDB driver is able to create, sign, and submit transactions to one or more nodes in a Federation.

If initialized with >1 nodes, the driver will send successive requests to different nodes in a round-robin fashion (this will be customizable in the future).

__init__(*nodes, transport_class=<class 'bigchaindb_driver.transport.Transport'>, headers=None, timeout=20)[source]

Initialize a BigchainDB driver instance.

Parameters:
  • *nodes (list of (str or dict)) – BigchainDB nodes to connect to. Currently, the full URL must be given. In the absence of any node, the default('http://localhost:9984') will be used. If node is passed as a dict, endpoint is a required key; headers is an optional dict of headers.
  • transport_class – Optional transport class to use. Defaults to Transport.
  • headers (dict) – Optional headers that will be passed with each request. To pass headers only on a per-request basis, you can pass the headers to the method of choice (e.g. BigchainDB().transactions.send_commit()).
  • timeout (int) – Optional timeout in seconds that will be passed to each request.
api_info(headers=None)[source]

Retrieves information provided by the API root endpoint '/api/v1'.

Parameters:headers (dict) – Optional headers to pass to the request.
Returns:Details of the HTTP API provided by the BigchainDB server.
Return type:dict
assets

AssetsEndpoint – Exposes functionalities of the '/assets' endpoint.

blocks

BlocksEndpoint – Exposes functionalities of the '/blocks' endpoint.

info(headers=None)[source]

Retrieves information of the node being connected to via the root endpoint '/'.

Parameters:headers (dict) – Optional headers to pass to the request.
Returns:Details of the node that this instance is connected to. Some information that may be interesting:
  • the server version and
  • an overview of all the endpoints
Return type:dict

Note

Currently limited to one node, and will be expanded to return information for each node that this instance is connected to.

metadata

MetadataEndpoint – Exposes functionalities of the '/metadata' endpoint.

nodes

tuple of str – URLs of connected nodes.

outputs

OutputsEndpoint – Exposes functionalities of the '/outputs' endpoint.

transactions

TransactionsEndpoint – Exposes functionalities of the '/transactions' endpoint.

transport

Transport – Object responsible for forwarding requests to a Connection instance (node).

class bigchaindb_driver.driver.TransactionsEndpoint(driver)[source]

Exposes functionality of the '/transactions/' endpoint.

path

str – The path of the endpoint.

static fulfill(transaction, private_keys)[source]

Fulfills the given transaction.

Parameters:
  • transaction (dict) – The transaction to be fulfilled.
  • private_keys (str | list | tuple) – One or more private keys to be used for fulfilling the transaction.
Returns:

The fulfilled transaction payload, ready to be sent to a BigchainDB federation.

Return type:

dict

Raises:

MissingPrivateKeyError – If a private key is missing.

get(*, asset_id, operation=None, headers=None)[source]

Given an asset id, get its list of transactions (and optionally filter for only 'CREATE' or 'TRANSFER' transactions).

Parameters:
  • asset_id (str) – Id of the asset.
  • operation (str) – The type of operation the transaction should be. Either 'CREATE' or 'TRANSFER'. Defaults to None.
  • headers (dict) – Optional headers to pass to the request.

Note

Please note that the id of an asset in BigchainDB is actually the id of the transaction which created the asset. In other words, when querying for an asset id with the operation set to 'CREATE', only one transaction should be expected. This transaction will be the transaction in which the asset was created, and the transaction id will be equal to the given asset id. Hence, the following calls to retrieve() and get() should return the same transaction.

>>> bdb = BigchainDB()
>>> bdb.transactions.retrieve('foo')
>>> bdb.transactions.get(asset_id='foo', operation='CREATE')

Since get() returns a list of transactions, it may be more efficient to use retrieve() instead, if one is only interested in the 'CREATE' operation.

Returns:List of transactions.
Return type:list
static prepare(*, operation='CREATE', signers=None, recipients=None, asset=None, metadata=None, inputs=None)[source]

Prepares a transaction payload, ready to be fulfilled.

Parameters:
  • operation (str) – The operation to perform. Must be 'CREATE' or 'TRANSFER'. Case insensitive. Defaults to 'CREATE'.
  • signers (list | tuple | str, optional) – One or more public keys representing the issuer(s) of the asset being created. Only applies for 'CREATE' operations. Defaults to None.
  • recipients (list | tuple | str, optional) – One or more public keys representing the new recipients(s) of the asset being created or transferred. Defaults to None.
  • asset (dict, optional) – The asset to be created or transferred. MUST be supplied for 'TRANSFER' operations. Defaults to None.
  • metadata (dict, optional) – Metadata associated with the transaction. Defaults to None.
  • inputs (dict | list | tuple, optional) – One or more inputs holding the condition(s) that this transaction intends to fulfill. Each input is expected to be a dict. Only applies to, and MUST be supplied for, 'TRANSFER' operations.
Returns:

The prepared transaction.

Return type:

dict

Raises:

BigchaindbException – If operation is not 'CREATE' or 'TRANSFER'.

Important

CREATE operations

  • signers MUST be set.

  • recipients, asset, and metadata MAY be set.

  • If asset is set, it MUST be in the form of:

    {
        'data': {
            ...
        }
    }
    
  • The argument inputs is ignored.

  • If recipients is not given, or evaluates to False, it will be set equal to signers:

    if not recipients:
        recipients = signers
    

TRANSFER operations

  • recipients, asset, and inputs MUST be set.

  • asset MUST be in the form of:

    {
        'id': '<Asset ID (i.e. TX ID of its CREATE transaction)>'
    }
    
  • metadata MAY be set.

  • The argument signers is ignored.

retrieve(txid, headers=None)[source]

Retrieves the transaction with the given id.

Parameters:
  • txid (str) – Id of the transaction to retrieve.
  • headers (dict) – Optional headers to pass to the request.
Returns:

The transaction with the given id.

Return type:

dict

send_async(transaction, headers=None)[source]

Submit a transaction to the Federation with the mode async.

Parameters:
  • transaction (dict) – the transaction to be sent to the Federation node(s).
  • headers (dict) – Optional headers to pass to the request.
Returns:

The transaction sent to the Federation node(s).

Return type:

dict

send_commit(transaction, headers=None)[source]

Submit a transaction to the Federation with the mode commit.

Parameters:
  • transaction (dict) – the transaction to be sent to the Federation node(s).
  • headers (dict) – Optional headers to pass to the request.
Returns:

The transaction sent to the Federation node(s).

Return type:

dict

send_sync(transaction, headers=None)[source]

Submit a transaction to the Federation with the mode sync.

Parameters:
  • transaction (dict) – the transaction to be sent to the Federation node(s).
  • headers (dict) – Optional headers to pass to the request.
Returns:

The transaction sent to the Federation node(s).

Return type:

dict

class bigchaindb_driver.driver.OutputsEndpoint(driver)[source]

Exposes functionality of the '/outputs' endpoint.

path

str – The path of the endpoint.

get(public_key, spent=None, headers=None)[source]

Get transaction outputs by public key. The public_key parameter must be a base58 encoded ed25519 public key associated with transaction output ownership.

Parameters:
  • public_key (str) – Public key for which unfulfilled conditions are sought.
  • spent (bool) – Indicate if the result set should include only spent or only unspent outputs. If not specified (None) the result includes all the outputs (both spent and unspent) associated with the public key.
  • headers (dict) – Optional headers to pass to the request.
Returns:

List of unfulfilled conditions.

Return type:

list of str

Example

Given a transaction with id da1b64a907ba54 having an ed25519 condition (at index 0) with alice’s public key:

>>> bdb = BigchainDB()
>>> bdb.outputs.get(alice_pubkey)
... ['../transactions/da1b64a907ba54/conditions/0']
class bigchaindb_driver.driver.AssetsEndpoint(driver)[source]

Exposes functionality of the '/assets' endpoint.

path

str – The path of the endpoint.

get(*, search, limit=0, headers=None)[source]

Retrieves the assets that match a given text search string.

Parameters:
  • search (str) – Text search string.
  • limit (int) – Limit the number of returned documents. Defaults to zero meaning that it returns all the matching assets.
  • headers (dict) – Optional headers to pass to the request.
Returns:

List of assets that match the query.

Return type:

list of dict

class bigchaindb_driver.driver.NamespacedDriver(driver)[source]

Base class for creating endpoints (namespaced objects) that can be added under the BigchainDB driver.

__init__(driver)[source]

Initializes an instance of NamespacedDriver with the given driver instance.

Parameters:driver (BigchainDB) – Instance of BigchainDB.

offchain

Module for operations that can be performed “offchain”, meaning without a connection to one or more BigchainDB federation nodes.

bigchaindb_driver.offchain.prepare_transaction(*, operation='CREATE', signers=None, recipients=None, asset=None, metadata=None, inputs=None)[source]

Prepares a transaction payload, ready to be fulfilled. Depending on the value of operation, simply dispatches to either prepare_create_transaction() or prepare_transfer_transaction().

Parameters:
  • operation (str) – The operation to perform. Must be 'CREATE' or 'TRANSFER'. Case insensitive. Defaults to 'CREATE'.
  • signers (list | tuple | str, optional) – One or more public keys representing the issuer(s) of the asset being created. Only applies for 'CREATE' operations. Defaults to None.
  • recipients (list | tuple | str, optional) – One or more public keys representing the new recipients(s) of the asset being created or transferred. Defaults to None.
  • asset (dict, optional) – The asset to be created or transferred. MUST be supplied for 'TRANSFER' operations. Defaults to None.
  • metadata (dict, optional) – Metadata associated with the transaction. Defaults to None.
  • inputs (dict | list | tuple, optional) – One or more inputs holding the condition(s) that this transaction intends to fulfill. Each input is expected to be a dict. Only applies to, and MUST be supplied for, 'TRANSFER' operations.
Returns:

The prepared transaction.

Return type:

dict

Raises:

BigchaindbException – If operation is not 'CREATE' or 'TRANSFER'.

Important

CREATE operations

  • signers MUST be set.

  • recipients, asset, and metadata MAY be set.

  • If asset is set, it MUST be in the form of:

    {
        'data': {
            ...
        }
    }
    
  • The argument inputs is ignored.

  • If recipients is not given, or evaluates to False, it will be set equal to signers:

    if not recipients:
        recipients = signers
    

TRANSFER operations

  • recipients, asset, and inputs MUST be set.

  • asset MUST be in the form of:

    {
        'id': '<Asset ID (i.e. TX ID of its CREATE transaction)>'
    }
    
  • metadata MAY be set.

  • The argument signers is ignored.

bigchaindb_driver.offchain.prepare_create_transaction(*, signers, recipients=None, asset=None, metadata=None)[source]

Prepares a "CREATE" transaction payload, ready to be fulfilled.

Parameters:
  • signers (list | tuple | str) – One or more public keys representing the issuer(s) of the asset being created.
  • recipients (list | tuple | str, optional) – One or more public keys representing the new recipients(s) of the asset being created. Defaults to None.
  • asset (dict, optional) – The asset to be created. Defaults to None.
  • metadata (dict, optional) – Metadata associated with the transaction. Defaults to None.
Returns:

The prepared "CREATE" transaction.

Return type:

dict

Important

  • If asset is set, it MUST be in the form of:

    {
        'data': {
            ...
        }
    }
    
  • If recipients is not given, or evaluates to False, it will be set equal to signers:

    if not recipients:
        recipients = signers
    
bigchaindb_driver.offchain.prepare_transfer_transaction(*, inputs, recipients, asset, metadata=None)[source]

Prepares a "TRANSFER" transaction payload, ready to be fulfilled.

Parameters:
  • inputs (dict | list | tuple) – One or more inputs holding the condition(s) that this transaction intends to fulfill. Each input is expected to be a dict.
  • recipients (str | list | tuple) – One or more public keys representing the new recipients(s) of the asset being transferred.
  • asset (dict) – A single-key dictionary holding the id of the asset being transferred with this transaction.
  • metadata (dict) – Metadata associated with the transaction. Defaults to None.
Returns:

The prepared "TRANSFER" transaction.

Return type:

dict

Important

  • asset MUST be in the form of:

    {
        'id': '<Asset ID (i.e. TX ID of its CREATE transaction)>'
    }
    

Example

Todo

Replace this section with docs.

In case it may not be clear what an input should look like, say Alice (public key: '3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf') wishes to transfer an asset over to Bob (public key: 'EcRawy3Y22eAUSS94vLF8BVJi62wbqbD9iSUSUNU9wAA'). Let the asset creation transaction payload be denoted by tx:

# noqa E501
>>> tx
    {'asset': {'data': {'msg': 'Hello BigchainDB!'}},
     'id': '9650055df2539223586d33d273cb8fd05bd6d485b1fef1caf7c8901a49464c87',
     'inputs': [{'fulfillment': {'public_key': '3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf',
                                 'type': 'ed25519-sha-256'},
                 'fulfills': None,
                 'owners_before': ['3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf']}],
     'metadata': None,
     'operation': 'CREATE',
     'outputs': [{'amount': '1',
                  'condition': {'details': {'public_key': '3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf',
                                            'type': 'ed25519-sha-256'},
                                'uri': 'ni:///sha-256;7ApQLsLLQgj5WOUipJg1txojmge68pctwFxvc3iOl54?fpt=ed25519-sha-256&cost=131072'},
                  'public_keys': ['3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf']}],
     'version': '2.0'}

Then, the input may be constructed in this way:

output_index
output = tx['transaction']['outputs'][output_index]
input_ = {
    'fulfillment': output['condition']['details'],
    'input': {
        'output_index': output_index,
        'transaction_id': tx['id'],
    },
    'owners_before': output['owners_after'],
}

Displaying the input on the prompt would look like:

>>> input_
{'fulfillment': {
  'public_key': '3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf',
  'type': 'ed25519-sha-256'},
 'input': {'output_index': 0,
  'transaction_id': '9650055df2539223586d33d273cb8fd05bd6d485b1fef1caf7c8901a49464c87'},
 'owners_before': ['3Cxh1eKZk3Wp9KGBWFS7iVde465UvqUKnEqTg2MW4wNf']}

To prepare the transfer:

>>> prepare_transfer_transaction(
...     inputs=input_,
...     recipients='EcRawy3Y22eAUSS94vLF8BVJi62wbqbD9iSUSUNU9wAA',
...     asset=tx['transaction']['asset'],
... )
bigchaindb_driver.offchain.fulfill_transaction(transaction, *, private_keys)[source]

Fulfills the given transaction.

Parameters:
  • transaction (dict) – The transaction to be fulfilled.
  • private_keys (str | list | tuple) – One or more private keys to be used for fulfilling the transaction.
Returns:

The fulfilled transaction payload, ready to be sent to a BigchainDB federation.

Return type:

dict

Raises:

MissingPrivateKeyError – If a private key is missing.

transport

class bigchaindb_driver.transport.Transport(*nodes, timeout=None)[source]

Transport class.

__init__(*nodes, timeout=None)[source]

Initializes an instance of Transport.

Parameters:
  • nodes – each node is a dictionary with the keys endpoint and headers
  • timeout (int) – Optional timeout in seconds.
forward_request(method, path=None, json=None, params=None, headers=None)[source]

Makes HTTP requests to the configured nodes.

Retries connection errors (e.g. DNS failures, refused connection, etc). A user may choose to retry other errors by catching the corresponding exceptions and retrying forward_request.

Exponential backoff is implemented individually for each node. Backoff delays are expressed as timestamps stored on the object and they are not reset in between multiple function calls.

Times out when self.timeout is expired, if not None.

Parameters:
  • method (str) – HTTP method name (e.g.: 'GET').
  • path (str) – Path to be appended to the base url of a node. E.g.: '/transactions').
  • json (dict) – Payload to be sent with the HTTP request.
  • params (dict)) – Dictionary of URL (query) parameters.
  • headers (dict) – Optional headers to pass to the request.
Returns:

Result of requests.models.Response.json()

Return type:

dict

pool

class bigchaindb_driver.pool.Pool(connections, picker_class=<class 'bigchaindb_driver.pool.RoundRobinPicker'>)[source]

Pool of connections.

__init__(connections, picker_class=<class 'bigchaindb_driver.pool.RoundRobinPicker'>)[source]

Initializes a Pool instance.

Parameters:connections (list) – List of Connection instances.
get_connection()[source]

Gets a Connection instance from the pool.

Returns:A Connection instance.
class bigchaindb_driver.pool.RoundRobinPicker[source]

Picks a Connection instance from a list of connections.

__init__()

Initialize self. See help(type(self)) for accurate signature.

pick(connections)[source]

Picks a connection with the earliest backoff time.

As a result, the first connection is picked for as long as it has no backoff time. Otherwise, the connections are tried in a round robin fashion.
Parameters:( (connections) – obj:list): List of Connection instances.
class bigchaindb_driver.pool.AbstractPicker[source]

Abstract class for picker classes that pick connections from a pool.

pick(connections)[source]

Picks a Connection instance from the given list of Connection instances.

Parameters:connections (List) – List of Connection instances.

connection

class bigchaindb_driver.connection.Connection(*, node_url, headers=None)[source]

A Connection object to make HTTP requests to a particular node.

__init__(*, node_url, headers=None)[source]

Initializes a Connection instance.

Parameters:
  • node_url (str) – Url of the node to connect to.
  • headers (dict) – Optional headers to send with each request.
request(method, *, path=None, json=None, params=None, headers=None, timeout=None, backoff_cap=None, **kwargs)[source]

Performs an HTTP request with the given parameters.

Implements exponential backoff.

If ConnectionError occurs, a timestamp equal to now + the default delay (BACKOFF_DELAY) is assigned to the object. The timestamp is in UTC. Next time the function is called, it either waits till the timestamp is passed or raises TimeoutError.

If ConnectionError occurs two or more times in a row, the retry count is incremented and the new timestamp is calculated as now + the default delay multiplied by two to the power of the number of retries.

If a request is successful, the backoff timestamp is removed, the retry count is back to zero.

Parameters:
  • method (str) – HTTP method (e.g.: 'GET').
  • path (str) – API endpoint path (e.g.: '/transactions').
  • json (dict) – JSON data to send along with the request.
  • params (dict) – Dictionary of URL (query) parameters.
  • headers (dict) – Optional headers to pass to the request.
  • timeout (int) – Optional timeout in seconds.
  • backoff_cap (int) – The maximal allowed backoff delay in seconds to be assigned to a node.
  • kwargs – Optional keyword arguments.

crypto

class bigchaindb_driver.crypto.CryptoKeypair(private_key, public_key)
private_key

Alias for field number 0

public_key

Alias for field number 1

bigchaindb_driver.crypto.generate_keypair(seed=None)[source]

Generates a cryptographic key pair.

Parameters:seed (bytes) – 32-byte seed for deterministic generation. Defaults to None.
Returns:A collections.namedtuple with named fields private_key and public_key.
Return type:CryptoKeypair

exceptions

Exceptions used by bigchaindb_driver.

exception bigchaindb_driver.exceptions.BigchaindbException[source]

Base exception for all Bigchaindb exceptions.

exception bigchaindb_driver.exceptions.TransportError[source]

Base exception for transport related errors.

This is mainly for cases where the status code denotes an HTTP error, and for cases in which there was a connection error.

exception bigchaindb_driver.exceptions.ConnectionError[source]

Exception for errors occurring when connecting, and/or making a request to Bigchaindb.

exception bigchaindb_driver.exceptions.NotFoundError[source]

Exception for HTTP 404 errors.

exception bigchaindb_driver.exceptions.KeypairNotFoundException[source]

Raised if an operation cannot proceed because the keypair was not given.

exception bigchaindb_driver.exceptions.InvalidPrivateKey[source]

Raised if a private key is invalid. E.g.: None.

exception bigchaindb_driver.exceptions.InvalidPublicKey[source]

Raised if a public key is invalid. E.g.: None.

exception bigchaindb_driver.exceptions.MissingPrivateKeyError[source]

Raised if a private key is missing.

utils

Set of utilities to support various functionalities of the driver.

bigchaindb_driver.utils.ops_map

dict – Mapping between operation strings and classes. E.g.: The string 'CREATE' is mapped to CreateOperation.

class bigchaindb_driver.utils.CreateOperation[source]

Class representing the 'CREATE' transaction operation.

class bigchaindb_driver.utils.TransferOperation[source]

Class representing the 'TRANSFER' transaction operation.

bigchaindb_driver.utils._normalize_operation(operation)[source]

Normalizes the given operation string. For now, this simply means converting the given string to uppercase, looking it up in ops_map, and returning the corresponding class if present.

Parameters:operation (str) – The operation string to convert.
Returns:The class corresponding to the given string, CreateOperation or TransferOperation.

Important

If the str.upper() step, or the ops_map lookup fails, the given operation argument is returned.

bigchaindb_driver.utils.normalize_node(node, headers=None)[source]

Normalizes given node as str or dict with headers

bigchaindb_driver.utils.normalize_nodes(*nodes, headers=None)[source]

Normalizes given dict or array of driver nodes

bigchaindb_driver.utils.normalize_url(node)[source]

Normalizes the given node url