text
stringlengths
81
112k
API endpoint to perform a text search on the assets. Args: search (str): Text search string to query the text index limit (int, optional): Limit the number of returned documents. Return: A list of assets that match the query. def get(self): """API endpoint ...
Initialize chain upon genesis or a migration def init_chain(self, genesis): """Initialize chain upon genesis or a migration""" app_hash = '' height = 0 known_chain = self.bigchaindb.get_latest_abci_chain() if known_chain is not None: chain_id = known_chain['chain_i...
Return height of the latest committed block. def info(self, request): """Return height of the latest committed block.""" self.abort_if_abci_chain_is_not_synced() # Check if BigchainDB supports the Tendermint version if not (hasattr(request, 'version') and tendermint_version_is_compati...
Validate the transaction before entry into the mempool. Args: raw_tx: a raw string (in bytes) transaction. def check_tx(self, raw_transaction): """Validate the transaction before entry into the mempool. Args: raw_tx: a raw string (in bytes) transaction....
Initialize list of transaction. Args: req_begin_block: block object which contains block header and block hash. def begin_block(self, req_begin_block): """Initialize list of transaction. Args: req_begin_block: block object which contains block header ...
Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction. def deliver_tx(self, raw_transaction): """Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction. """ ...
Calculate block hash using transaction ids and previous block hash to be stored in the next block. Args: height (int): new height of the chain. def end_block(self, request_end_block): """Calculate block hash using transaction ids and previous block hash to be stored in the ...
Store the new height and along with block hash. def commit(self): """Store the new height and along with block hash.""" self.abort_if_abci_chain_is_not_synced() data = self.block_txn_hash.encode('utf-8') # register a new block only when new transactions are received if self.b...
For more details refer BEP-21: https://github.com/bigchaindb/BEPs/tree/master/21 def validate(self, bigchain, current_transactions=[]): """For more details refer BEP-21: https://github.com/bigchaindb/BEPs/tree/master/21 """ current_validators = self.get_validators(bigchain) super(Vali...
Create a new queue for a specific combination of event types and return it. Returns: a :class:`multiprocessing.Queue`. Raises: RuntimeError if called after `run` def get_subscriber_queue(self, event_types=None): """Create a new queue for a specific combination o...
Given an event, send it to all the subscribers. Args event (:class:`~bigchaindb.events.EventTypes`): the event to dispatch to all the subscribers. def dispatch(self, event): """Given an event, send it to all the subscribers. Args event (:class:`~bigchai...
Start the exchange def run(self): """Start the exchange""" self.started_queue.put('STARTED') while True: event = self.publisher_queue.get() if event == POISON_PILL: return else: self.dispatch(event)
Initialize the configured backend for use with BigchainDB. Creates a database with :attr:`dbname` with any required tables and supporting indexes. Args: connection (:class:`~bigchaindb.backend.connection.Connection`): an existing connection to use to initialize the database. ...
Validate all nested "language" key in `obj`. Args: obj (dict): dictionary whose "language" key is to be validated. Returns: None: validation successful Raises: ValidationError: will raise exception in case language is not valid. def validate_language_key(obj, ...
API endpoint to get details about a block. Args: block_id (str): the id of the block. Return: A JSON string containing the data about the block. def get(self, block_id): """API endpoint to get details about a block. Args: block_id (str): the id of ...
API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided". def get(self): """API endpoint to get ...
Generate base58 encode public-private key pair from a hex encoded private key def key_pair_from_ed25519_key(hex_private_key): """Generate base58 encode public-private key pair from a hex encoded private key""" priv_key = crypto.Ed25519SigningKey(bytes.fromhex(hex_private_key)[:32], encoding='bytes') public...
Generate base58 public key from hex encoded public key def public_key_from_ed25519_key(hex_public_key): """Generate base58 public key from hex encoded public key""" public_key = crypto.Ed25519VerifyingKey(bytes.fromhex(hex_public_key), encoding='bytes') return public_key.encode(encoding='base58').decode('u...
Encode a fulfillment as a details dictionary Args: fulfillment: Crypto-conditions Fulfillment object def _fulfillment_to_details(fulfillment): """Encode a fulfillment as a details dictionary Args: fulfillment: Crypto-conditions Fulfillment object """ if fulfillment.type_name == '...
Load a fulfillment for a signing spec dictionary Args: data: tx.output[].condition.details dictionary def _fulfillment_from_details(data, _depth=0): """Load a fulfillment for a signing spec dictionary Args: data: tx.output[].condition.details dictionary """ if _depth == 100: ...
Transforms the object to a Python dictionary. Note: If an Input hasn't been signed yet, this method returns a dictionary representation. Returns: dict: The Input as an alternative serialization format. def to_dict(self): """Transforms th...
Transforms a Python dictionary to an Input object. Note: Optionally, this method can also serialize a Cryptoconditions- Fulfillment that is not yet signed. Args: data (dict): The Input to be transformed. Returns: :cla...
Transforms the object to a Python dictionary. Returns: (dict|None): The link as an alternative serialization format. def to_dict(self): """Transforms the object to a Python dictionary. Returns: (dict|None): The link as an alternative serialization forma...
Transforms the object to a Python dictionary. Note: A dictionary serialization of the Input the Output was derived from is always provided. Returns: dict: The Output as an alternative serialization format. def to_dict(self): """Transform...
Generates a Output from a specifically formed tuple or list. Note: If a ThresholdCondition has to be generated where the threshold is always the number of subconditions it is split between, a list of the following structure is sufficient: [(a...
Generates ThresholdSha256 conditions from a list of new owners. Note: This method is intended only to be used with a reduce function. For a description on how to use this method, see :meth:`~.Output.generate`. Args: initial (:clas...
Transforms a Python dictionary to an Output object. Note: To pass a serialization cycle multiple times, a Cryptoconditions Fulfillment needs to be present in the passed-in dictionary, as Condition URIs are not serializable anymore. ...
Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index. def spent_outputs(self): """Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id a...
A simple way to generate a `CREATE` transaction. Note: This method currently supports the following Cryptoconditions use cases: - Ed25519 - ThresholdSha256 Additionally, it provides support for the following BigchainDB...
A simple way to generate a `TRANSFER` transaction. Note: Different cases for threshold conditions: Combining multiple `inputs` with an arbitrary number of `recipients` can yield interesting cases for the creation of threshold conditions we'd ...
Converts a Transaction's outputs to spendable inputs. Note: Takes the Transaction's outputs and derives inputs from that can then be passed into `Transaction.transfer` as `inputs`. A list of integers can be passed to `indices` that ...
Adds an input to a Transaction's list of inputs. Args: input_ (:class:`~bigchaindb.common.transaction. Input`): An Input to be added to the Transaction. def add_input(self, input_): """Adds an input to a Transaction's list of inputs. Args: ...
Adds an output to a Transaction's list of outputs. Args: output (:class:`~bigchaindb.common.transaction. Output`): An Output to be added to the Transaction. def add_output(self, output): """Adds an output to a Transaction's list of outputs. ...
Fulfills a previous Transaction's Output by signing Inputs. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256 Furthermore, note that all keys required to f...
Signs a single Input. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256. Args: input_ (:class:`~bigchaindb.common.transaction. ...
Signs a Ed25519Fulfillment. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The input to be signed. message (str): The message to be signed key_pairs (dict): The keys to sign the Transaction with. def _sign_simple_signature_...
Signs a ThresholdSha256. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The Input to be signed. message (str): The message to be signed key_pairs (dict): The keys to sign the Transaction with. def _sign_threshold_signature_...
Validates an Input against a given set of Outputs. Note: The number of `output_condition_uris` must be equal to the number of Inputs a Transaction has. Args: output_condition_uris (:obj:`list` of :obj:`str`): A list of Outputs...
Transforms the object to a Python dictionary. Returns: dict: The Transaction as an alternative serialization format. def to_dict(self): """Transforms the object to a Python dictionary. Returns: dict: The Transaction as an alternative serialization forma...
Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~bigchaindb.common. transaction.Transaction`): A list o...
Validate the transaction ID of a transaction Args: tx_body (dict): The Transaction to be transformed. def validate_id(tx_body): """Validate the transaction ID of a transaction Args: tx_body (dict): The Transaction to be transformed. """ ...
Transforms a Python dictionary to a Transaction object. Args: tx_body (dict): The Transaction to be transformed. Returns: :class:`~bigchaindb.common.transaction.Transaction` def from_dict(cls, tx, skip_schema_validation=True): """Transforms a Python dic...
Helper method that reconstructs a transaction dict that was returned from the database. It checks what asset_id to retrieve, retrieves the asset from the asset table and reconstructs the transaction. Args: bigchain (:class:`~bigchaindb.tendermint.BigchainDB`): An instance ...
For the given `tx` based on the `operation` key return its implementation class def resolve_class(operation): """For the given `tx` based on the `operation` key return its implementation class""" create_txn_class = Transaction.type_registry.get(Transaction.CREATE) return Transaction.type_regis...
Create a new connection to the database backend. All arguments default to the current configuration's values if not given. Args: backend (str): the name of the backend to use. host (str): the host to connect to. port (int): the port to connect to. name (str): the name of th...
Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. def connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. ...
API endpoint to get validators set. Return: A JSON string containing the validator set of the current node. def get(self): """API endpoint to get validators set. Return: A JSON string containing the validator set of the current node. """ pool = current...
Return the validator set from the most recent approved block :return: { 'height': <block_height>, 'validators': <validator_set> } def get_validator_change(cls, bigchain): """Return the validator set from the most recent approved block :return: { 'he...
Return a dictionary of validators with key as `public_key` and value as the `voting_power` def get_validators(cls, bigchain, height=None): """Return a dictionary of validators with key as `public_key` and value as the `voting_power` """ validators = {} for validato...
Convert validator dictionary to a recipient list for `Transaction` def recipients(cls, bigchain): """Convert validator dictionary to a recipient list for `Transaction`""" recipients = [] for public_key, voting_power in cls.get_validators(bigchain).items(): recipients.append(([publi...
Validate election transaction NOTE: * A valid election is initiated by an existing validator. * A valid election is one where voters are validators and votes are allocated according to the voting power of each validator node. Args: :param bigchain: (BigchainDB) a...
Validate the election transaction. Since `ELECTION` extends `CREATE` transaction, all the validations for `CREATE` transaction should be inherited def validate_schema(cls, tx): """Validate the election transaction. Since `ELECTION` extends `CREATE` transaction, all the validations for `CREATE` ...
Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. Custom elections may override this function and introdu...
Looks for election and vote transactions inside the block, records and processes elections. Every election is recorded in the database. Every vote has a chance to conclude the corresponding election. When an election is concluded, the corresponding database record is ...
Looks for election and vote transactions inside the block and cleans up the database artifacts possibly created in `process_blocks`. Part of the `end_block`/`commit` crash recovery. def rollback(cls, bigchain, new_height, txn_ids): """Looks for election and vote transactions inside the b...
Validate the validator election vote transaction. Since `VOTE` extends `TRANSFER` transaction, all the validations for `CREATE` transaction should be inherited def validate_schema(cls, tx): """Validate the validator election vote transaction. Since `VOTE` extends `TRANSFER` transaction, a...
Map a function to the leafs of a mapping. def map_leafs(func, mapping): """Map a function to the leafs of a mapping.""" def _inner(mapping, path=None): if path is None: path = [] for key, val in mapping.items(): if isinstance(val, collections.Mapping): ...
Returns the config values found in a configuration file. Args: filename (str): the JSON file with the configuration values. If ``None``, CONFIG_DEFAULT_PATH will be used. Returns: dict: The config values in the specified config file (or the file at CONFIG_DEFAULT_PATH...
Return a new configuration with the values found in the environment. The function recursively iterates over the config, checking if there is a matching env variable. If an env variable is found, the func updates the configuration with that value. The name of the env variable is built combining a prefi...
Return a new configuration where all the values types are aligned with the ones in the default configuration def update_types(config, reference, list_sep=':'): """Return a new configuration where all the values types are aligned with the ones in the default configuration """ def _coerce(current, v...
Set bigchaindb.config equal to the default config dict, then update that with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default config Note: Any pre...
Update bigchaindb.config with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default config def update_config(config): """Update bigchaindb.config with whatever is i...
Write the provided configuration to a specific location. Args: config (dict): a dictionary with the configuration to load. filename (str): the name of the file that will store the new configuration. Defaults to ``None``. If ``None``, the HOME of the current user and the string ``.bigcha...
Run ``file_config`` and ``env_config`` if the module has not been initialized. def autoconfigure(filename=None, config=None, force=False): """Run ``file_config`` and ``env_config`` if the module has not been initialized. """ if not force and is_configured(): logger.debug('System already con...
Find and load the chosen validation plugin. Args: name (string): the name of the entry_point, as advertised in the setup.py of the providing package. Returns: an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules`` def load_validation_plugin(name=None): ...
Create a pool that imposes a limit on the number of stored instances. Args: builder: a function to build an instance. size: the size of the pool. timeout(Optional[float]): the seconds to wait before raising a ``queue.Empty`` exception if no instances are available ...
Check if the public_key of owner is in the condition details as an Ed25519Fulfillment.public_key Args: condition_details (dict): dict with condition details owner (str): base58 public key of owner Returns: bool: True if the public key is found in the condition details, False otherw...
Check Tendermint compatability with BigchainDB server :param running_tm_ver: Version number of the connected Tendermint instance :type running_tm_ver: str :return: True/False depending on the compatability with BigchainDB server :rtype: bool def tendermint_version_is_compatible(running_tm_ver): ""...
Run the recorded chain of methods on `instance`. Args: instance: an object. def run(self, instance): """Run the recorded chain of methods on `instance`. Args: instance: an object. """ last = instance for item in self.stack: if isin...
Base websocket URL that is advertised to external clients. Useful when the websocket URL advertised to the clients needs to be customized (typically when running behind NAT, firewall, etc.) def base_ws_uri(): """Base websocket URL that is advertised to external clients. Useful when the websocket URL ...
API endpoint to get details about a transaction. Args: tx_id (str): the id of the transaction. Return: A JSON string containing the data about the transaction. def get(self, tx_id): """API endpoint to get details about a transaction. Args: tx_id (s...
API endpoint to push transactions to the Federation. Return: A ``dict`` containing the data about the transaction. def post(self): """API endpoint to push transactions to the Federation. Return: A ``dict`` containing the data about the transaction. """ ...
Get outputs for a public key def get_outputs_by_public_key(self, public_key): """Get outputs for a public key""" txs = list(query.get_owned_ids(self.connection, public_key)) return [TransactionLink(tx['id'], index) for tx in txs for index, output in enumerate(tx[...
Remove outputs that have been spent Args: outputs: list of TransactionLink def filter_spent_outputs(self, outputs): """Remove outputs that have been spent Args: outputs: list of TransactionLink """ links = [o.to_dict() for o in outputs] txs = li...
Load a schema from disk def _load_schema(name, path=__file__): """Load a schema from disk""" path = os.path.join(os.path.dirname(path), name + '.yaml') with open(path) as handle: schema = yaml.safe_load(handle) fast_schema = rapidjson.Validator(rapidjson.dumps(schema)) return path, (schema,...
Validate data against a schema def _validate_schema(schema, body): """Validate data against a schema""" # Note # # Schema validation is currently the major CPU bottleneck of # BigchainDB. the `jsonschema` library validates python data structures # directly and produces nice error messages, but...
Validate a transaction dict. TX_SCHEMA_COMMON contains properties that are common to all types of transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top. def validate_transaction_schema(tx): """Validate a transaction dict. TX_SCHEMA_COMMON contains properties that are common to al...
Submit a valid transaction to the mempool. def post_transaction(self, transaction, mode): """Submit a valid transaction to the mempool.""" if not mode or mode not in self.mode_list: raise ValidationError('Mode must be one of the following {}.' .format(', '....
Submit a valid transaction to the mempool. def write_transaction(self, transaction, mode): # This method offers backward compatibility with the Web API. """Submit a valid transaction to the mempool.""" response = self.post_transaction(transaction, mode) return self._process_post_respons...
Update the UTXO set given ``transaction``. That is, remove the outputs that the given ``transaction`` spends, and add the outputs that the given ``transaction`` creates. Args: transaction (:obj:`~bigchaindb.models.Transaction`): A new transaction incoming into the sy...
Store the given ``unspent_outputs`` (utxos). Args: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs. def store_unspent_outputs(self, *unspent_outputs): """Store the given ``unspent_outputs`` (utxos). Args: ...
Returns the merkle root of the utxoset. This implies that the utxoset is first put into a merkle tree. For now, the merkle tree and its root will be computed each time. This obviously is not efficient and a better approach that limits the repetition of the same computation when ...
Get the utxoset. Returns: generator of unspent_outputs. def get_unspent_outputs(self): """Get the utxoset. Returns: generator of unspent_outputs. """ cursor = backend.query.get_unspent_outputs(self.connection) return (record for record in cursor...
Deletes the given ``unspent_outputs`` (utxos). Args: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs. def delete_unspent_outputs(self, *unspent_outputs): """Deletes the given ``unspent_outputs`` (utxos). Args: ...
Get a list of transactions filtered on some criteria def get_transactions_filtered(self, asset_id, operation=None): """Get a list of transactions filtered on some criteria """ txids = backend.query.get_txids_filtered(self.connection, asset_id, op...
Get a list of output links filtered on some criteria Args: owner (str): base58 encoded public_key. spent (bool): If ``True`` return only the spent outputs. If ``False`` return only unspent outputs. If spent is not specified (``None``) ...
Get the block with the specified `block_id`. Returns the block corresponding to `block_id` or None if no match is found. Args: block_id (int): block id of the block to get. def get_block(self, block_id): """Get the block with the specified `block_id`. Returns the ...
Retrieve the list of blocks (block ids) containing a transaction with transaction id `txid` Args: txid (str): transaction id of the transaction to query Returns: Block id list (list(int)) def get_block_containing_tx(self, txid): """Retrieve the list of block...
Validate a transaction against the current status of the database. def validate_transaction(self, tx, current_transactions=[]): """Validate a transaction against the current status of the database.""" transaction = tx # CLEANUP: The conditional below checks for transaction in dict format. ...
Return an iterator of assets that match the text search Args: search (str): Text search string to query the text index limit (int, optional): Limit the number of returned documents. Returns: iter: An iterator of assets that match the text search. def text_search(se...
Store validator set at a given `height`. NOTE: If the validator set already exists at that `height` then an exception will be raised. def store_validator_set(self, height, validators): """Store validator set at a given `height`. NOTE: If the validator set already exists at that...
Generate and record a new ABCI chain ID. New blocks are not accepted until we receive an InitChain ABCI request with the matching chain ID and validator set. Chain ID is generated based on the current chain and height. `chain-X` => `chain-X-migrated-at-height-5`. `chain-X-migrat...
Bridge between a synchronous multiprocessing queue and an asynchronous asyncio queue. Args: in_queue (multiprocessing.Queue): input queue out_queue (asyncio.Queue): output queue def _multiprocessing_to_asyncio(in_queue, out_queue, loop): """Bridge between a synchronous multiprocessing queu...
Handle a new socket connection. def websocket_handler(request): """Handle a new socket connection.""" logger.debug('New websocket connection.') websocket = web.WebSocketResponse() yield from websocket.prepare(request) uuid = uuid4() request.app['dispatcher'].subscribe(uuid, websocket) whi...
Init the application server. Return: An aiohttp application. def init_app(event_source, *, loop=None): """Init the application server. Return: An aiohttp application. """ dispatcher = Dispatcher(event_source) # Schedule the dispatcher loop.create_task(dispatcher.publish(...
Create and start the WebSocket server. def start(sync_event_source, loop=None): """Create and start the WebSocket server.""" if not loop: loop = asyncio.get_event_loop() event_source = asyncio.Queue(loop=loop) bridge = threading.Thread(target=_multiprocessing_to_asyncio, ...
Publish new events to the subscribers. def publish(self): """Publish new events to the subscribers.""" while True: event = yield from self.event_source.get() str_buffer = [] if event == POISON_PILL: return if isinstance(event, str): ...
Computes the merkle root for a given list. Args: hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree. Returns: str: Merkle root in hexadecimal form. def merkleroot(hashes): """Computes the merkle root for a given list. Args: hashes (:obj:`list` of :obj:`bytes`): The ...
Note this only compatible with Tendermint 0.19.x def public_key64_to_address(base64_public_key): """Note this only compatible with Tendermint 0.19.x""" ed25519_public_key = public_key_from_base64(base64_public_key) encoded_public_key = amino_encoded_public_key(ed25519_public_key) return hashlib.new('ri...
Validate transaction spend Args: bigchain (BigchainDB): an instantiated bigchaindb.BigchainDB object. Returns: The transaction (Transaction) if the transaction is valid else it raises an exception describing the reason why the transaction is invalid. ...