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.
- *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(
-
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.
-
outputs
¶ OutputsEndpoint
– Exposes functionalities of the'/outputs'
endpoint.
-
transactions
¶ TransactionsEndpoint
– Exposes functionalities of the'/transactions'
endpoint.
-
transport
¶ Transport
– Object responsible for forwarding requests to aConnection
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: Returns: The fulfilled transaction payload, ready to be sent to a BigchainDB federation.
Return type: 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: 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 toretrieve()
andget()
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 useretrieve()
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 toNone
. - recipients (
list
|tuple
|str
, optional) – One or more public keys representing the new recipients(s) of the asset being created or transferred. Defaults toNone
. - asset (
dict
, optional) – The asset to be created or transferred. MUST be supplied for'TRANSFER'
operations. Defaults toNone
. - metadata (
dict
, optional) – Metadata associated with the transaction. Defaults toNone
. - 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 adict
. Only applies to, and MUST be supplied for,'TRANSFER'
operations.
Returns: The prepared transaction.
Return type: Raises: BigchaindbException
– Ifoperation
is not'CREATE'
or'TRANSFER'
.Important
CREATE operations
signers
MUST be set.recipients
,asset
, andmetadata
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 toFalse
, it will be set equal tosigners
:if not recipients: recipients = signers
TRANSFER operations
recipients
,asset
, andinputs
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.
- operation (str) – The operation to perform. Must be
-
retrieve
(txid, headers=None)[source]¶ Retrieves the transaction with the given id.
Parameters: Returns: The transaction with the given id.
Return type:
-
send_async
(transaction, headers=None)[source]¶ Submit a transaction to the Federation with the mode async.
Parameters: Returns: The transaction sent to the Federation node(s).
Return type:
-
send_commit
(transaction, headers=None)[source]¶ Submit a transaction to the Federation with the mode commit.
Parameters: Returns: The transaction sent to the Federation node(s).
Return type:
-
-
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: Example
Given a transaction with id
da1b64a907ba54
having an ed25519 condition (at index0
) 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.
-
-
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 eitherprepare_create_transaction()
orprepare_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 toNone
. - recipients (
list
|tuple
|str
, optional) – One or more public keys representing the new recipients(s) of the asset being created or transferred. Defaults toNone
. - asset (
dict
, optional) – The asset to be created or transferred. MUST be supplied for'TRANSFER'
operations. Defaults toNone
. - metadata (
dict
, optional) – Metadata associated with the transaction. Defaults toNone
. - 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 adict
. Only applies to, and MUST be supplied for,'TRANSFER'
operations.
Returns: The prepared transaction.
Return type: Raises: BigchaindbException
– Ifoperation
is not'CREATE'
or'TRANSFER'
.Important
CREATE operations
signers
MUST be set.recipients
,asset
, andmetadata
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 toFalse
, it will be set equal tosigners
:if not recipients: recipients = signers
TRANSFER operations
recipients
,asset
, andinputs
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.
- operation (str) – The operation to perform. Must be
-
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 toNone
. - asset (
dict
, optional) – The asset to be created. Defaults toNone
. - metadata (
dict
, optional) – Metadata associated with the transaction. Defaults toNone
.
Returns: The prepared
"CREATE"
transaction.Return type: Important
If
asset
is set, it MUST be in the form of:{ 'data': { ... } }
If
recipients
is not given, or evaluates toFalse
, it will be set equal tosigners
:if not recipients: recipients = signers
- 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 adict
. - 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 theid
of the asset being transferred with this transaction. - metadata (
dict
) – Metadata associated with the transaction. Defaults toNone
.
Returns: The prepared
"TRANSFER"
transaction.Return type: 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 bytx
:# 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'], ... )
- inputs (
-
bigchaindb_driver.offchain.
fulfill_transaction
(transaction, *, private_keys)[source]¶ Fulfills the given transaction.
Parameters: Returns: The fulfilled transaction payload, ready to be sent to a BigchainDB federation.
Return type: 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: Returns: Result of
requests.models.Response.json()
Return type:
-
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 ofConnection
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:
-
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.
- method (str) – HTTP method (e.g.:
-
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 fieldsprivate_key
andpublic_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.
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
.
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 toCreateOperation
.
-
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
orTransferOperation
.Important
If the
str.upper()
step, or theops_map
lookup fails, the givenoperation
argument is returned.
-
bigchaindb_driver.utils.
normalize_node
(node, headers=None)[source]¶ Normalizes given node as str or dict with headers