INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 next block. Args: height (int): new height of the chain. """ self.abort_if_abci_chain_is_not_synced() chain_shift = 0 if self.c...
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.block_txn_ids: self.bigchaindb.store_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(ValidatorElection, self).validate(bigchain, current_transactions=current_transactions)...
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 of event types and return it. Returns: a :class:`multiprocessing.Queue`. Raises: RuntimeError if called after `run` """ try: self.start...
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:`~bigchaindb.events.EventTypes`): the event to dispatch to all the subscribers. """ for event_types, queues in self.queues.items(): if event.type & e...
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. ...
def init_database(connection=None, dbname=None): """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 ...
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, key): """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...
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 the block. Return: A JSON string containing the data about the block. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain:...
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 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". """ p...
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_key = priv_key.get_verifying_key() return CryptoKeypair(private_key=priv_k...
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('utf-8')
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 == 'ed25519-sha-256': return { 'type': 'ed25519-sha-256', 'public_key': base58.b58encod...
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: raise ThresholdTooDeep() if data['type'] == 'ed25519-sha-256': public_key = base58.b58decode(data['p...
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 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. """ ...
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...
def from_dict(cls, data): """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. ...
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 format. """ if self.txid is None and self.output is None: return None else: return { 'tr...
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): """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. ""...
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...
def generate(cls, public_keys, amount): """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 foll...
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...
def _gen_condition(cls, initial, new_public_keys): """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:`~.Outpu...
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. ...
def from_dict(cls, data): """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...
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 and output index. """ return ( input_.fulfills.to_dict() for input_ in self.inputs if input_.fulfills ...
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...
def create(cls, tx_signers, recipients, metadata=None, asset=None): """A simple way to generate a `CREATE` transaction. Note: This method currently supports the following Cryptoconditions use cases: - Ed25519 - ThresholdSha256 ...
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 ...
def to_inputs(self, indices=None): """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 intege...
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: input_ (:class:`~bigchaindb.common.transaction. Input`): An Input to be added to the Transaction. """ if not isinstance(input_, Input): raise TypeEr...
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. Args: output (:class:`~bigchaindb.common.transaction. Output`): An Output to be added to the Transaction. """ if not isinstance(output, Output)...
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...
def sign(self, private_keys): """Fulfills a previous Transaction's Output by signing Inputs. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256 Furt...
Signs a single Input. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256. Args: input_ (:class:`~bigchaindb.common.transaction. ...
def _sign_input(cls, input_, message, key_pairs): """Signs a single Input. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256. Args: in...
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_fulfillment(cls, input_, message, key_pairs): """Signs a Ed25519Fulfillment. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The input to be signed. message (str): The message to be signed k...
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_fulfillment(cls, input_, message, key_pairs): """Signs a ThresholdSha256. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The Input to be signed. message (str): The message to be signed k...
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...
def _inputs_valid(self, output_condition_uris): """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:`...
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 format. """ return { 'inputs': [input_.to_dict() for input_ in self.inputs], 'outputs': [output.to_dict() for ou...
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...
def get_asset_id(cls, transactions): """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. ...
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. """ # NOTE: Remove reference to avoid side effects # tx_body = deepcopy(tx_body) tx_body = rapidjson.loads(rapidjson.dum...
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 dictionary to a Transaction object. Args: tx_body (dict): The Transaction to be transformed. Returns: :class:`~bigchaindb.common.transaction.Transaction` """ oper...
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 ...
def from_db(cls, bigchain, tx_dict_list): """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:`~bigch...
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_registry.get(operation, create_txn_class)
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...
def connect(backend=None, host=None, port=None, name=None, max_tries=None, connection_timeout=None, replicaset=None, ssl=None, login=None, password=None, ca_cert=None, certfile=None, keyfile=None, keyfile_passphrase=None, crlfile=None): """Create a new connection to the database ...
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. """ attempt = 0 for i in self.max_tries_counter: attempt += 1 try: self._conn = se...
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_app.config['bigchain_pool'] with pool() as bigchain: validators = bigchain.get_validators() return ...
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: { 'height': <block_height>, 'validators': <validator_set> } """ latest_block = bigchain.get_latest_block() if latest_block is None: ...
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 validator in bigchain.get_validators(height): # NOTE: we assume that Tendermint encodes public key ...
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(([public_key], voting_power)) return recipients
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...
def validate(self, bigchain, current_transactions=[]): """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 validato...
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` transaction should be inherited """ _validate_schema(TX_SCHEMA_COMMON, tx) _validate_schema(TX_SCHEMA_CREATE, tx) if cls.TX_...
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...
def has_concluded(self, bigchain, current_votes=[]): """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. ...
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 ...
def process_block(cls, bigchain, new_height, txns): """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 ele...
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 block and cleans up the database artifacts possibly created in `process_blocks`. Part of the `end_block`/`commit` crash recovery. """ # delete election records for ele...
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, all the validations for `CREATE` transaction should be inherited """ _validate_schema(TX_SCHEMA_COMMON, tx) _validate_schema(TX_SCHEMA_TRANSFER, tx) ...
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): _inner(val, path + [key]) else:...
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...
def file_config(filename=None): """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 ...
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...
def env_config(config): """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 vari...
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, value): # Coerce a value to the `current` type. try: # First we try to apply current to...
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...
def set_config(config): """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 co...
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 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 """ # Update the default config wit...
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...
def write_config(config, filename=None): """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 H...
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 configured, skipping autoconfiguration') return # start with the current c...
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): """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...
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 ...
def pool(builder, size, timeout=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`` exce...
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...
def condition_details_has_owner(condition_details, owner): """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...
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): """ 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: ...
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 isinstance(item, str): last = getattr(last, item) else: la...
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 advertised to the clients needs to be customized (typically when running behind NAT, firewall, etc.) """ scheme = config['wsserver']['advertised_scheme'] host = config['wsserver']['ad...
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 (str): the id of the transaction. Return: A JSON string containing the data about the transaction. """ pool = current_app.config['bigchain_pool'] with pool() a...
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. """ parser = reqparse.RequestParser() parser.add_argument('mode', type=parameters.valid_mode, default='br...
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['outputs']) if...
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 = list(query.get_spending_transactions(self.connection, links)) spends = {TransactionLink.fro...
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, fast_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 validation takes 4+ ms # pe...
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 all types of transaction. TX_SCHEMA_[TRANSFER|CREATE] add additional constraints on top. """ _validate_schema(TX_SCHEMA_COMMON, tx) if tx['operation'] == 'TRANSFER': ...
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(', '.join(self.mode_list))) tx_dict = tr...
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_response(response.json(), mode)
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...
def update_utxoset(self, transaction): """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 ne...
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: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs. """ if unspent_outputs: return backend.query...
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 ...
def get_utxoset_merkle_root(self): """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 re...
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: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs. """ if unspent_outputs: return backend.qu...
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, operation) for txid in txids: yield ...
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``) ...
def get_outputs_filtered(self, owner, spent=None): """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. I...
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 block corresponding to `block_id` or None if no match is found. Args: block_id (int): block id of the block to get. """ block = backend.query.get_block(self.connectio...
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 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)) """ blocks ...
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. # It would be better to only have a single format for the trans...
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(self, search, *, limit=0, table='assets'): """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:...
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 `height` then an exception will be raised. """ return backend.query.store_validator_set(self.connection, {'height': height, ...
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...
def migrate_abci_chain(self): """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-migra...
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 queue and an asynchronous asyncio queue. Args: in_queue (multiprocessing.Queue): input queue out_queue (asyncio.Queue): output queue """ while True: value = in_queue....
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) while True: # Consume input ...
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()) app = web.Application(loop=loop) app['dispatcher'] = dispatcher...
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, args=(sync_event_source, event...
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): str_buffer.append(event) ...
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 leaves of the tree. Returns: str: Merkle root in hexadecimal form. """ # XXX TEMPORARY -- MUST REVIEW and possibly CHANGE # The idea here is that the UTXO SET ...
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('ripemd160', encoded_public_key).hexdigest().upper()
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. ...
def validate(self, bigchain, current_transactions=[]): """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 descr...
Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the database. :exc:`~Config...
def _connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the data...
Add the routes to an app
def add_routes(app): """Add the routes to an app""" for (prefix, routes) in API_SECTIONS: api = Api(app, prefix=prefix) for ((pattern, resource, *args), kwargs) in routes: kwargs.setdefault('strict_slashes', False) api.add_resource(resource, pattern, *args, **kwargs)
Set the chat as yourself. In this context, "yourself" means the user behind the master channel. Every channel should relate this to the corresponding target. Returns: EFBChat: This object.
def self(self) -> 'EFBChat': """ Set the chat as yourself. In this context, "yourself" means the user behind the master channel. Every channel should relate this to the corresponding target. Returns: EFBChat: This object. """ self.chat_name = "You" ...
Set the chat as a system chat. Only set for channel-level and group-level system chats. Returns: EFBChat: This object.
def system(self) -> 'EFBChat': """ Set the chat as a system chat. Only set for channel-level and group-level system chats. Returns: EFBChat: This object. """ self.chat_name = "System" self.chat_alias = None self.chat_uid = EFBChat.SYSTEM_ID ...
Shortcut property, if alias exists, this will provide the alias with name in parenthesis. Otherwise, this will return the name
def long_name(self) -> str: """ Shortcut property, if alias exists, this will provide the alias with name in parenthesis. Otherwise, this will return the name """ if self.chat_alias: return "{0} ({1})".format(self.chat_alias, self.chat_name) else: ...
Verify the completeness of the data. Raises: ValueError: When this chat is invalid.
def verify(self): """ Verify the completeness of the data. Raises: ValueError: When this chat is invalid. """ if any(not i for i in (self.chat_uid, self.module_id)): raise ValueError("Chat data is incomplete.") if not isinstance(self.chat_type, Ch...
Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``.
def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ methods = {} ...