code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
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 the value, since it # might be a function return current(value) except TypeError: # Then we check if current is a list AND if the value # is a string. if isinstance(current, list) and isinstance(value, str): # If so, we use the colon as the separator return value.split(list_sep) try: # If we are here, we should try to apply the type # of `current` to the value return type(current)(value) except TypeError: # Worst case scenario we return the value itself. return value def _update_type(value, path): current = reference for elem in path: try: current = current[elem] except KeyError: return value return _coerce(current, value) return map_leafs(_update_type, config)
Return a new configuration where all the values types are aligned with the ones in the default configuration
update_types
python
bigchaindb/bigchaindb
bigchaindb/config_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
Apache-2.0
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 config Note: Any previous changes made to ``bigchaindb.config`` will be lost. """ # Deep copy the default config into bigchaindb.config bigchaindb.config = copy.deepcopy(bigchaindb._config) # Update the default config with whatever is in the passed config update(bigchaindb.config, update_types(config, bigchaindb.config)) bigchaindb.config['CONFIGURED'] = True
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 previous changes made to ``bigchaindb.config`` will be lost.
set_config
python
bigchaindb/bigchaindb
bigchaindb/config_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
Apache-2.0
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 with whatever is in the passed config update(bigchaindb.config, update_types(config, bigchaindb.config)) bigchaindb.config['CONFIGURED'] = True
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_config
python
bigchaindb/bigchaindb
bigchaindb/config_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
Apache-2.0
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 HOME of the current user and the string ``.bigchaindb`` will be used. """ if not filename: filename = CONFIG_DEFAULT_PATH with open(filename, 'w') as f: json.dump(config, f, indent=4)
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 ``.bigchaindb`` will be used.
write_config
python
bigchaindb/bigchaindb
bigchaindb/config_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
Apache-2.0
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 configuration newconfig = bigchaindb.config # update configuration from file try: newconfig = update(newconfig, file_config(filename=filename)) except FileNotFoundError as e: if filename: raise else: logger.info('Cannot find config file `%s`.' % e.filename) # override configuration with env variables newconfig = env_config(newconfig) if config: newconfig = update(newconfig, config) set_config(newconfig) # sets bigchaindb.config
Run ``file_config`` and ``env_config`` if the module has not been initialized.
autoconfigure
python
bigchaindb/bigchaindb
bigchaindb/config_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
Apache-2.0
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`` """ if not name: return BaseValidationRules # TODO: This will return the first plugin with group `bigchaindb.validation` # and name `name` in the active WorkingSet. # We should probably support Requirements specs in the config, e.g. # validation_plugin: 'my-plugin-package==0.0.1;default' plugin = None for entry_point in iter_entry_points('bigchaindb.validation', name): plugin = entry_point.load() # No matching entry_point found if not plugin: raise ResolutionError( 'No plugin found in group `bigchaindb.validation` with name `{}`'. format(name)) # Is this strictness desireable? # It will probably reduce developer headaches in the wild. if not issubclass(plugin, (BaseValidationRules,)): raise TypeError('object of type "{}" does not implement `bigchaindb.' 'validation.BaseValidationRules`'.format(type(plugin))) return plugin
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``
load_validation_plugin
python
bigchaindb/bigchaindb
bigchaindb/config_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
Apache-2.0
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_id'] if known_chain['is_synced']: msg = (f'Got invalid InitChain ABCI request ({genesis}) - ' f'the chain {chain_id} is already synced.') logger.error(msg) sys.exit(1) if chain_id != genesis.chain_id: validators = self.bigchaindb.get_validators() self.log_abci_migration_error(chain_id, validators) sys.exit(1) # set migration values for app hash and height block = self.bigchaindb.get_latest_block() app_hash = '' if block is None else block['app_hash'] height = 0 if block is None else block['height'] + 1 known_validators = self.bigchaindb.get_validators() validator_set = [vutils.decode_validator(v) for v in genesis.validators] if known_validators and known_validators != validator_set: self.log_abci_migration_error(known_chain['chain_id'], known_validators) sys.exit(1) block = Block(app_hash=app_hash, height=height, transactions=[]) self.bigchaindb.store_block(block._asdict()) self.bigchaindb.store_validator_set(height + 1, validator_set) abci_chain_height = 0 if known_chain is None else known_chain['height'] self.bigchaindb.store_abci_chain(abci_chain_height, genesis.chain_id, True) self.chain = {'height': abci_chain_height, 'is_synced': True, 'chain_id': genesis.chain_id} return self.abci.ResponseInitChain()
Initialize chain upon genesis or a migration
init_chain
python
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
Apache-2.0
def check_tx(self, raw_transaction): """Validate the transaction before entry into the mempool. Args: raw_tx: a raw string (in bytes) transaction. """ self.abort_if_abci_chain_is_not_synced() logger.debug('check_tx: %s', raw_transaction) transaction = decode_transaction(raw_transaction) if self.bigchaindb.is_valid_transaction(transaction): logger.debug('check_tx: VALID') return self.abci.ResponseCheckTx(code=CodeTypeOk) else: logger.debug('check_tx: INVALID') return self.abci.ResponseCheckTx(code=CodeTypeError)
Validate the transaction before entry into the mempool. Args: raw_tx: a raw string (in bytes) transaction.
check_tx
python
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
Apache-2.0
def begin_block(self, req_begin_block): """Initialize list of transaction. Args: req_begin_block: block object which contains block header and block hash. """ self.abort_if_abci_chain_is_not_synced() chain_shift = 0 if self.chain is None else self.chain['height'] logger.debug('BEGIN BLOCK, height:%s, num_txs:%s', req_begin_block.header.height + chain_shift, req_begin_block.header.num_txs) self.block_txn_ids = [] self.block_transactions = [] return self.abci.ResponseBeginBlock()
Initialize list of transaction. Args: req_begin_block: block object which contains block header and block hash.
begin_block
python
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
Apache-2.0
def deliver_tx(self, raw_transaction): """Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction. """ self.abort_if_abci_chain_is_not_synced() logger.debug('deliver_tx: %s', raw_transaction) transaction = self.bigchaindb.is_valid_transaction( decode_transaction(raw_transaction), self.block_transactions) if not transaction: logger.debug('deliver_tx: INVALID') return self.abci.ResponseDeliverTx(code=CodeTypeError) else: logger.debug('storing tx') self.block_txn_ids.append(transaction.id) self.block_transactions.append(transaction) return self.abci.ResponseDeliverTx(code=CodeTypeOk)
Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction.
deliver_tx
python
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
Apache-2.0
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.chain is None else self.chain['height'] height = request_end_block.height + chain_shift self.new_height = height # store pre-commit state to recover in case there is a crash during # `end_block` or `commit` logger.debug(f'Updating pre-commit state: {self.new_height}') pre_commit_state = dict(height=self.new_height, transactions=self.block_txn_ids) self.bigchaindb.store_pre_commit_state(pre_commit_state) block_txn_hash = calculate_hash(self.block_txn_ids) block = self.bigchaindb.get_latest_block() if self.block_txn_ids: self.block_txn_hash = calculate_hash([block['app_hash'], block_txn_hash]) else: self.block_txn_hash = block['app_hash'] validator_update = Election.process_block(self.bigchaindb, self.new_height, self.block_transactions) return self.abci.ResponseEndBlock(validator_updates=validator_update)
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.
end_block
python
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
Apache-2.0
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_bulk_transactions(self.block_transactions) block = Block(app_hash=self.block_txn_hash, height=self.new_height, transactions=self.block_txn_ids) # NOTE: storing the block should be the last operation during commit # this effects crash recovery. Refer BEP#8 for details self.bigchaindb.store_block(block._asdict()) logger.debug('Commit-ing new block with hash: apphash=%s ,' 'height=%s, txn ids=%s', data, self.new_height, self.block_txn_ids) if self.events_queue: event = Event(EventTypes.BLOCK_VALID, { 'height': self.new_height, 'transactions': self.block_transactions }) self.events_queue.put(event) return self.abci.ResponseCommit(data=data)
Store the new height and along with block hash.
commit
python
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
Apache-2.0
def __init__(self, event_type, event_data): """Creates a new event. Args: event_type (int): the type of the event, see :class:`~bigchaindb.events.EventTypes` event_data (obj): the data of the event. """ self.type = event_type self.data = event_data
Creates a new event. Args: event_type (int): the type of the event, see :class:`~bigchaindb.events.EventTypes` event_data (obj): the data of the event.
__init__
python
bigchaindb/bigchaindb
bigchaindb/events.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/events.py
Apache-2.0
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.started_queue.get(timeout=1) raise RuntimeError('Cannot create a new subscriber queue while Exchange is running.') except Empty: pass if event_types is None: event_types = EventTypes.ALL queue = Queue() self.queues[event_types].append(queue) return queue
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`
get_subscriber_queue
python
bigchaindb/bigchaindb
bigchaindb/events.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/events.py
Apache-2.0
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 & event_types: for queue in queues: queue.put(event)
Given an event, send it to all the subscribers. Args event (:class:`~bigchaindb.events.EventTypes`): the event to dispatch to all the subscribers.
dispatch
python
bigchaindb/bigchaindb
bigchaindb/events.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/events.py
Apache-2.0
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.from_dict(input_['fulfills']) for tx in txs for input_ in tx['inputs']} return [ff for ff in outputs if ff not in spends]
Remove outputs that have been spent Args: outputs: list of TransactionLink
filter_spent_outputs
python
bigchaindb/bigchaindb
bigchaindb/fastquery.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/fastquery.py
Apache-2.0
def filter_unspent_outputs(self, outputs): """Remove outputs that have not 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.from_dict(input_['fulfills']) for tx in txs for input_ in tx['inputs']} return [ff for ff in outputs if ff in spends]
Remove outputs that have not been spent Args: outputs: list of TransactionLink
filter_unspent_outputs
python
bigchaindb/bigchaindb
bigchaindb/fastquery.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/fastquery.py
Apache-2.0
def __init__(self, connection=None): """Initialize the Bigchain instance A Bigchain instance has several configuration parameters (e.g. host). If a parameter value is passed as an argument to the Bigchain __init__ method, then that is the value it will have. Otherwise, the parameter value will come from an environment variable. If that environment variable isn't set, then the value will come from the local configuration file. And if that variable isn't in the local configuration file, then the parameter will have its default value (defined in bigchaindb.__init__). Args: connection (:class:`~bigchaindb.backend.connection.Connection`): A connection to the database. """ config_utils.autoconfigure() self.mode_commit = BROADCAST_TX_COMMIT self.mode_list = (BROADCAST_TX_ASYNC, BROADCAST_TX_SYNC, self.mode_commit) self.tendermint_host = bigchaindb.config['tendermint']['host'] self.tendermint_port = bigchaindb.config['tendermint']['port'] self.endpoint = 'http://{}:{}/'.format(self.tendermint_host, self.tendermint_port) validationPlugin = bigchaindb.config.get('validation_plugin') if validationPlugin: self.validation = config_utils.load_validation_plugin(validationPlugin) else: self.validation = BaseValidationRules self.connection = connection if connection else backend.connect(**bigchaindb.config['database'])
Initialize the Bigchain instance A Bigchain instance has several configuration parameters (e.g. host). If a parameter value is passed as an argument to the Bigchain __init__ method, then that is the value it will have. Otherwise, the parameter value will come from an environment variable. If that environment variable isn't set, then the value will come from the local configuration file. And if that variable isn't in the local configuration file, then the parameter will have its default value (defined in bigchaindb.__init__). Args: connection (:class:`~bigchaindb.backend.connection.Connection`): A connection to the database.
__init__
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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 new transaction incoming into the system for which the UTXO set needs to be updated. """ spent_outputs = [ spent_output for spent_output in transaction.spent_outputs ] if spent_outputs: self.delete_unspent_outputs(*spent_outputs) self.store_unspent_outputs( *[utxo._asdict() for utxo in transaction.unspent_outputs] )
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 system for which the UTXO set needs to be updated.
update_utxoset
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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.store_unspent_outputs( self.connection, *unspent_outputs)
Store the given ``unspent_outputs`` (utxos). Args: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs.
store_unspent_outputs
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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)
Get the utxoset. Returns: generator of unspent_outputs.
get_unspent_outputs
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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.query.delete_unspent_outputs( self.connection, *unspent_outputs)
Deletes the given ``unspent_outputs`` (utxos). Args: *unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable length tuple or list of unspent outputs.
delete_unspent_outputs
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
def get_transactions_filtered(self, asset_id, operation=None, last_tx=None): """Get a list of transactions filtered on some criteria """ txids = backend.query.get_txids_filtered(self.connection, asset_id, operation, last_tx) for txid in txids: yield self.get_transaction(txid)
Get a list of transactions filtered on some criteria
get_transactions_filtered
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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. If spent is not specified (``None``) return all outputs. Returns: :obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s pointing to another transaction's condition """ outputs = self.fastquery.get_outputs_by_public_key(owner) if spent is None: return outputs elif spent is True: return self.fastquery.filter_unspent_outputs(outputs) elif spent is False: return self.fastquery.filter_spent_outputs(outputs)
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``) return all outputs. Returns: :obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s pointing to another transaction's condition
get_outputs_filtered
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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.connection, block_id) latest_block = self.get_latest_block() latest_block_height = latest_block['height'] if latest_block else 0 if not block and block_id > latest_block_height: return result = {'height': block_id, 'transactions': []} if block: transactions = backend.query.get_transactions(self.connection, block['transactions']) result['transactions'] = [t.to_dict() for t in Transaction.from_db(self, transactions)] return result
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.
get_block
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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 = list(backend.query.get_block_with_transaction(self.connection, txid)) if len(blocks) > 1: logger.critical('Transaction id %s exists in multiple blocks', txid) return [block['height'] for block in blocks]
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))
get_block_containing_tx
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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 transaction # throught the code base. if isinstance(transaction, dict): try: transaction = Transaction.from_dict(tx) except SchemaValidationError as e: logger.warning('Invalid transaction schema: %s', e.__cause__.message) return False except ValidationError as e: logger.warning('Invalid transaction (%s): %s', type(e).__name__, e) return False return transaction.validate(self, current_transactions)
Validate a transaction against the current status of the database.
validate_transaction
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
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-migrated-at-height-5`. `chain-X-migrated-at-height-5` => `chain-X-migrated-at-height-21`. If there is no known chain (we are at genesis), the function returns. """ latest_chain = self.get_latest_abci_chain() if latest_chain is None: return block = self.get_latest_block() suffix = '-migrated-at-height-' chain_id = latest_chain['chain_id'] block_height_str = str(block['height']) new_chain_id = chain_id.split(suffix)[0] + suffix + block_height_str self.store_abci_chain(block['height'] + 1, new_chain_id, False)
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-migrated-at-height-5` => `chain-X-migrated-at-height-21`. If there is no known chain (we are at genesis), the function returns.
migrate_abci_chain
python
bigchaindb/bigchaindb
bigchaindb/lib.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
Apache-2.0
def setup_logging(): """Function to configure log hadlers. .. important:: Configuration, if needed, should be applied before invoking this decorator, as starting the subscriber process for logging will configure the root logger for the child process based on the state of :obj:`bigchaindb.config` at the moment this decorator is invoked. """ logging_configs = DEFAULT_LOGGING_CONFIG new_logging_configs = bigchaindb.config['log'] if 'file' in new_logging_configs: filename = new_logging_configs['file'] logging_configs['handlers']['file']['filename'] = filename if 'error_file' in new_logging_configs: error_filename = new_logging_configs['error_file'] logging_configs['handlers']['errors']['filename'] = error_filename if 'level_console' in new_logging_configs: level = _normalize_log_level(new_logging_configs['level_console']) logging_configs['handlers']['console']['level'] = level if 'level_logfile' in new_logging_configs: level = _normalize_log_level(new_logging_configs['level_logfile']) logging_configs['handlers']['file']['level'] = level if 'fmt_console' in new_logging_configs: fmt = new_logging_configs['fmt_console'] logging_configs['formatters']['console']['format'] = fmt if 'fmt_logfile' in new_logging_configs: fmt = new_logging_configs['fmt_logfile'] logging_configs['formatters']['file']['format'] = fmt if 'datefmt_console' in new_logging_configs: fmt = new_logging_configs['datefmt_console'] logging_configs['formatters']['console']['datefmt'] = fmt if 'datefmt_logfile' in new_logging_configs: fmt = new_logging_configs['datefmt_logfile'] logging_configs['formatters']['file']['datefmt'] = fmt log_levels = new_logging_configs.get('granular_levels', {}) for logger_name, level in log_levels.items(): level = _normalize_log_level(level) try: logging_configs['loggers'][logger_name]['level'] = level except KeyError: logging_configs['loggers'][logger_name] = {'level': level} set_logging_config(logging_configs)
Function to configure log hadlers. .. important:: Configuration, if needed, should be applied before invoking this decorator, as starting the subscriber process for logging will configure the root logger for the child process based on the state of :obj:`bigchaindb.config` at the moment this decorator is invoked.
setup_logging
python
bigchaindb/bigchaindb
bigchaindb/log.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/log.py
Apache-2.0
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 describing the reason why the transaction is invalid. Raises: ValidationError: If the transaction is invalid """ input_conditions = [] if self.operation == Transaction.CREATE: duplicates = any(txn for txn in current_transactions if txn.id == self.id) if bigchain.is_committed(self.id) or duplicates: raise DuplicateTransaction('transaction `{}` already exists' .format(self.id)) if not self.inputs_valid(input_conditions): raise InvalidSignature('Transaction signature is invalid.') elif self.operation == Transaction.TRANSFER: self.validate_transfer_inputs(bigchain, current_transactions) return self
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. Raises: ValidationError: If the transaction is invalid
validate
python
bigchaindb/bigchaindb
bigchaindb/models.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/models.py
Apache-2.0
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 would be empty and this function # would be invoked to compute the merkle root, and since there is nothing, # i.e. an empty list, then the hash of the empty string is returned. # This seems too easy but maybe that is good enough? TO REVIEW! if not hashes: return sha3_256(b'').hexdigest() # XXX END TEMPORARY -- MUST REVIEW ... if len(hashes) == 1: return hexlify(hashes[0]).decode() if len(hashes) % 2 == 1: hashes.append(hashes[-1]) parent_hashes = [ sha3_256(hashes[i] + hashes[i+1]).digest() for i in range(0, len(hashes)-1, 2) ] return merkleroot(parent_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.
merkleroot
python
bigchaindb/bigchaindb
bigchaindb/tendermint_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/tendermint_utils.py
Apache-2.0
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()
Note this only compatible with Tendermint 0.19.x
public_key64_to_address
python
bigchaindb/bigchaindb
bigchaindb/tendermint_utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/tendermint_utils.py
Apache-2.0
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 if the public key is found in the condition details, False otherwise """ if 'subconditions' in condition_details: result = condition_details_has_owner(condition_details['subconditions'], owner) if result: return True elif isinstance(condition_details, list): for subcondition in condition_details: result = condition_details_has_owner(subcondition, owner) if result: return True else: if 'public_key' in condition_details \ and owner == condition_details['public_key']: return True return False
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 otherwise
condition_details_has_owner
python
bigchaindb/bigchaindb
bigchaindb/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/utils.py
Apache-2.0
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: last = last(*item[0], **item[1]) self.stack = [] return last
Run the recorded chain of methods on `instance`. Args: instance: an object.
run
python
bigchaindb/bigchaindb
bigchaindb/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/utils.py
Apache-2.0
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: bool """ # Splitting because version can look like this e.g. 0.22.8-40d6dc2e tm_ver = running_tm_ver.split('-') if not tm_ver: return False for ver in __tm_supported_versions__: if version.parse(ver) == version.parse(tm_ver[0]): return True return False
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
tendermint_version_is_compatible
python
bigchaindb/bigchaindb
bigchaindb/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/utils.py
Apache-2.0
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 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 the database to use. replicaset (str): the name of the replica set (only relevant for MongoDB connections). Returns: An instance of :class:`~bigchaindb.backend.connection.Connection` based on the given (or defaulted) :attr:`backend`. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~ConfigurationError`: If the given (or defaulted) :attr:`backend` is not supported or could not be loaded. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the database. """ backend = backend or get_bigchaindb_config_value_or_key_error('backend') host = host or get_bigchaindb_config_value_or_key_error('host') port = port or get_bigchaindb_config_value_or_key_error('port') dbname = name or get_bigchaindb_config_value_or_key_error('name') # Not sure how to handle this here. This setting is only relevant for # mongodb. # I added **kwargs for both RethinkDBConnection and MongoDBConnection # to handle these these additional args. In case of RethinkDBConnection # it just does not do anything with it. # # UPD: RethinkDBConnection is not here anymore cause we no longer support RethinkDB. # The problem described above might be reconsidered next time we introduce a backend, # if it ever happens. replicaset = replicaset or get_bigchaindb_config_value('replicaset') ssl = ssl if ssl is not None else get_bigchaindb_config_value('ssl', False) login = login or get_bigchaindb_config_value('login') password = password or get_bigchaindb_config_value('password') ca_cert = ca_cert or get_bigchaindb_config_value('ca_cert') certfile = certfile or get_bigchaindb_config_value('certfile') keyfile = keyfile or get_bigchaindb_config_value('keyfile') keyfile_passphrase = keyfile_passphrase or get_bigchaindb_config_value('keyfile_passphrase', None) crlfile = crlfile or get_bigchaindb_config_value('crlfile') try: module_name, _, class_name = BACKENDS[backend].rpartition('.') Class = getattr(import_module(module_name), class_name) except KeyError: raise ConfigurationError('Backend `{}` is not supported. ' 'BigchainDB currently supports {}'.format(backend, BACKENDS.keys())) except (ImportError, AttributeError) as exc: raise ConfigurationError('Error loading backend `{}`'.format(backend)) from exc logger.debug('Connection: {}'.format(Class)) return Class(host=host, port=port, dbname=dbname, max_tries=max_tries, connection_timeout=connection_timeout, replicaset=replicaset, ssl=ssl, login=login, password=password, ca_cert=ca_cert, certfile=certfile, keyfile=keyfile, keyfile_passphrase=keyfile_passphrase, crlfile=crlfile)
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 the database to use. replicaset (str): the name of the replica set (only relevant for MongoDB connections). Returns: An instance of :class:`~bigchaindb.backend.connection.Connection` based on the given (or defaulted) :attr:`backend`. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~ConfigurationError`: If the given (or defaulted) :attr:`backend` is not supported or could not be loaded. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the database.
connect
python
bigchaindb/bigchaindb
bigchaindb/backend/connection.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/connection.py
Apache-2.0
def __init__(self, host=None, port=None, dbname=None, connection_timeout=None, max_tries=None, **kwargs): """Create a new :class:`~.Connection` instance. Args: host (str): the host to connect to. port (int): the port to connect to. dbname (str): the name of the database to use. connection_timeout (int, optional): the milliseconds to wait until timing out the database connection attempt. Defaults to 5000ms. max_tries (int, optional): how many tries before giving up, if 0 then try forever. Defaults to 3. **kwargs: arbitrary keyword arguments provided by the configuration's ``database`` settings """ dbconf = bigchaindb.config['database'] self.host = host or dbconf['host'] self.port = port or dbconf['port'] self.dbname = dbname or dbconf['name'] self.connection_timeout = connection_timeout if connection_timeout is not None \ else dbconf['connection_timeout'] self.max_tries = max_tries if max_tries is not None else dbconf['max_tries'] self.max_tries_counter = range(self.max_tries) if self.max_tries != 0 else repeat(0) self._conn = None
Create a new :class:`~.Connection` instance. Args: host (str): the host to connect to. port (int): the port to connect to. dbname (str): the name of the database to use. connection_timeout (int, optional): the milliseconds to wait until timing out the database connection attempt. Defaults to 5000ms. max_tries (int, optional): how many tries before giving up, if 0 then try forever. Defaults to 3. **kwargs: arbitrary keyword arguments provided by the configuration's ``database`` settings
__init__
python
bigchaindb/bigchaindb
bigchaindb/backend/connection.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/connection.py
Apache-2.0
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 connection to use to initialize the database. Creates one if not given. dbname (str): the name of the database to create. Defaults to the database name given in the BigchainDB configuration. """ connection = connection or connect() dbname = dbname or bigchaindb.config['database']['name'] create_database(connection, dbname) create_tables(connection, dbname)
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. Creates one if not given. dbname (str): the name of the database to create. Defaults to the database name given in the BigchainDB configuration.
init_database
python
bigchaindb/bigchaindb
bigchaindb/backend/schema.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/schema.py
Apache-2.0
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 not valid. """ backend = bigchaindb.config['database']['backend'] if backend == 'localmongodb': data = obj.get(key, {}) if isinstance(data, dict): validate_all_values_for_key_in_obj(data, 'language', validate_language) elif isinstance(data, list): validate_all_values_for_key_in_list(data, 'language', validate_language)
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.
validate_language_key
python
bigchaindb/bigchaindb
bigchaindb/backend/schema.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/schema.py
Apache-2.0
def validate_language(value): """Check if `value` is a valid language. https://docs.mongodb.com/manual/reference/text-search-languages/ Args: value (str): language to validated Returns: None: validation successful Raises: ValidationError: will raise exception in case language is not valid. """ if value not in VALID_LANGUAGES: error_str = ('MongoDB does not support text search for the ' 'language "{}". If you do not understand this error ' 'message then please rename key/field "language" to ' 'something else like "lang".').format(value) raise ValidationError(error_str)
Check if `value` is a valid language. https://docs.mongodb.com/manual/reference/text-search-languages/ Args: value (str): language to validated Returns: None: validation successful Raises: ValidationError: will raise exception in case language is not valid.
validate_language
python
bigchaindb/bigchaindb
bigchaindb/backend/schema.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/schema.py
Apache-2.0
def __init__(self, replicaset=None, ssl=None, login=None, password=None, ca_cert=None, certfile=None, keyfile=None, keyfile_passphrase=None, crlfile=None, **kwargs): """Create a new Connection instance. Args: replicaset (str, optional): the name of the replica set to connect to. **kwargs: arbitrary keyword arguments provided by the configuration's ``database`` settings """ super().__init__(**kwargs) self.replicaset = replicaset or get_bigchaindb_config_value('replicaset') self.ssl = ssl if ssl is not None else get_bigchaindb_config_value('ssl', False) self.login = login or get_bigchaindb_config_value('login') self.password = password or get_bigchaindb_config_value('password') self.ca_cert = ca_cert or get_bigchaindb_config_value('ca_cert') self.certfile = certfile or get_bigchaindb_config_value('certfile') self.keyfile = keyfile or get_bigchaindb_config_value('keyfile') self.keyfile_passphrase = keyfile_passphrase or get_bigchaindb_config_value('keyfile_passphrase') self.crlfile = crlfile or get_bigchaindb_config_value('crlfile')
Create a new Connection instance. Args: replicaset (str, optional): the name of the replica set to connect to. **kwargs: arbitrary keyword arguments provided by the configuration's ``database`` settings
__init__
python
bigchaindb/bigchaindb
bigchaindb/backend/localmongodb/connection.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/localmongodb/connection.py
Apache-2.0
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 database. :exc:`~ConfigurationError`: If there is a ConfigurationError while connecting to the database. """ try: # FYI: the connection process might raise a # `ServerSelectionTimeoutError`, that is a subclass of # `ConnectionFailure`. # The presence of ca_cert, certfile, keyfile, crlfile implies the # use of certificates for TLS connectivity. if self.ca_cert is None or self.certfile is None or \ self.keyfile is None or self.crlfile is None: client = pymongo.MongoClient(self.host, self.port, replicaset=self.replicaset, serverselectiontimeoutms=self.connection_timeout, ssl=self.ssl, **MONGO_OPTS) if self.login is not None and self.password is not None: client[self.dbname].authenticate(self.login, self.password) else: logger.info('Connecting to MongoDB over TLS/SSL...') client = pymongo.MongoClient(self.host, self.port, replicaset=self.replicaset, serverselectiontimeoutms=self.connection_timeout, ssl=self.ssl, ssl_ca_certs=self.ca_cert, ssl_certfile=self.certfile, ssl_keyfile=self.keyfile, ssl_pem_passphrase=self.keyfile_passphrase, ssl_crlfile=self.crlfile, ssl_cert_reqs=CERT_REQUIRED, **MONGO_OPTS) if self.login is not None: client[self.dbname].authenticate(self.login, mechanism='MONGODB-X509') return client except (pymongo.errors.ConnectionFailure, pymongo.errors.OperationFailure) as exc: logger.info('Exception in _connect(): {}'.format(exc)) raise ConnectionError(str(exc)) from exc except pymongo.errors.ConfigurationError as exc: raise ConfigurationError from exc
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:`~ConfigurationError`: If there is a ConfigurationError while connecting to the database.
_connect
python
bigchaindb/bigchaindb
bigchaindb/backend/localmongodb/connection.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/backend/localmongodb/connection.py
Apache-2.0
def run_configure(args): """Run a script to configure the current node.""" config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH config_file_exists = False # if the config path is `-` then it's stdout if config_path != '-': config_file_exists = os.path.exists(config_path) if config_file_exists and not args.yes: want = input_on_stderr('Config file `{}` exists, do you want to ' 'override it? (cannot be undone) [y/N]: '.format(config_path)) if want != 'y': return conf = copy.deepcopy(bigchaindb.config) # select the correct config defaults based on the backend print('Generating default configuration for backend {}' .format(args.backend), file=sys.stderr) database_keys = bigchaindb._database_keys_map[args.backend] conf['database'] = bigchaindb._database_map[args.backend] if not args.yes: for key in ('bind', ): val = conf['server'][key] conf['server'][key] = input_on_stderr('API Server {}? (default `{}`): '.format(key, val), val) for key in ('scheme', 'host', 'port'): val = conf['wsserver'][key] conf['wsserver'][key] = input_on_stderr('WebSocket Server {}? (default `{}`): '.format(key, val), val) for key in database_keys: val = conf['database'][key] conf['database'][key] = input_on_stderr('Database {}? (default `{}`): '.format(key, val), val) for key in ('host', 'port'): val = conf['tendermint'][key] conf['tendermint'][key] = input_on_stderr('Tendermint {}? (default `{}`)'.format(key, val), val) if config_path != '-': bigchaindb.config_utils.write_config(conf, config_path) else: print(json.dumps(conf, indent=4, sort_keys=True)) print('Configuration written to {}'.format(config_path), file=sys.stderr) print('Ready to go!', file=sys.stderr)
Run a script to configure the current node.
run_configure
python
bigchaindb/bigchaindb
bigchaindb/commands/bigchaindb.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/bigchaindb.py
Apache-2.0
def run_election_new_upsert_validator(args, bigchain): """Initiates an election to add/update/remove a validator to an existing BigchainDB network :param args: dict args = { 'public_key': the public key of the proposed peer, (str) 'power': the proposed validator power for the new peer, (str) 'node_id': the node_id of the new peer (str) 'sk': the path to the private key of the node calling the election (str) } :param bigchain: an instance of BigchainDB :return: election_id or `False` in case of failure """ new_validator = { 'public_key': {'value': public_key_from_base64(args.public_key), 'type': 'ed25519-base16'}, 'power': args.power, 'node_id': args.node_id } return create_new_election(args.sk, bigchain, ValidatorElection, new_validator)
Initiates an election to add/update/remove a validator to an existing BigchainDB network :param args: dict args = { 'public_key': the public key of the proposed peer, (str) 'power': the proposed validator power for the new peer, (str) 'node_id': the node_id of the new peer (str) 'sk': the path to the private key of the node calling the election (str) } :param bigchain: an instance of BigchainDB :return: election_id or `False` in case of failure
run_election_new_upsert_validator
python
bigchaindb/bigchaindb
bigchaindb/commands/bigchaindb.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/bigchaindb.py
Apache-2.0
def run_election_approve(args, bigchain): """Approve an election :param args: dict args = { 'election_id': the election_id of the election (str) 'sk': the path to the private key of the signer (str) } :param bigchain: an instance of BigchainDB :return: success log message or `False` in case of error """ key = load_node_key(args.sk) tx = bigchain.get_transaction(args.election_id) voting_powers = [v.amount for v in tx.outputs if key.public_key in v.public_keys] if len(voting_powers) > 0: voting_power = voting_powers[0] else: logger.error('The key you provided does not match any of the eligible voters in this election.') return False inputs = [i for i in tx.to_inputs() if key.public_key in i.owners_before] election_pub_key = ValidatorElection.to_public_key(tx.id) approval = Vote.generate(inputs, [([election_pub_key], voting_power)], tx.id).sign([key.private_key]) approval.validate(bigchain) resp = bigchain.write_transaction(approval, BROADCAST_TX_COMMIT) if resp == (202, ''): logger.info('[SUCCESS] Your vote has been submitted') return approval.id else: logger.error('Failed to commit vote') return False
Approve an election :param args: dict args = { 'election_id': the election_id of the election (str) 'sk': the path to the private key of the signer (str) } :param bigchain: an instance of BigchainDB :return: success log message or `False` in case of error
run_election_approve
python
bigchaindb/bigchaindb
bigchaindb/commands/bigchaindb.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/bigchaindb.py
Apache-2.0
def run_election_show(args, bigchain): """Retrieves information about an election :param args: dict args = { 'election_id': the transaction_id for an election (str) } :param bigchain: an instance of BigchainDB """ election = bigchain.get_transaction(args.election_id) if not election: logger.error(f'No election found with election_id {args.election_id}') return response = election.show_election(bigchain) logger.info(response) return response
Retrieves information about an election :param args: dict args = { 'election_id': the transaction_id for an election (str) } :param bigchain: an instance of BigchainDB
run_election_show
python
bigchaindb/bigchaindb
bigchaindb/commands/bigchaindb.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/bigchaindb.py
Apache-2.0
def run_start(args): """Start the processes to run the node""" # Configure Logging setup_logging() logger.info('BigchainDB Version %s', bigchaindb.__version__) run_recover(bigchaindb.lib.BigchainDB()) if not args.skip_initialize_database: logger.info('Initializing database') _run_init() logger.info('Starting BigchainDB main process.') from bigchaindb.start import start start(args)
Start the processes to run the node
run_start
python
bigchaindb/bigchaindb
bigchaindb/commands/bigchaindb.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/bigchaindb.py
Apache-2.0
def configure_bigchaindb(command): """Decorator to be used by command line functions, such that the configuration of bigchaindb is performed before the execution of the command. Args: command: The command to decorate. Returns: The command wrapper function. """ @functools.wraps(command) def configure(args): config_from_cmdline = None try: if args.log_level is not None: config_from_cmdline = { 'log': { 'level_console': args.log_level, 'level_logfile': args.log_level, }, 'server': {'loglevel': args.log_level}, } except AttributeError: pass bigchaindb.config_utils.autoconfigure( filename=args.config, config=config_from_cmdline, force=True) command(args) return configure
Decorator to be used by command line functions, such that the configuration of bigchaindb is performed before the execution of the command. Args: command: The command to decorate. Returns: The command wrapper function.
configure_bigchaindb
python
bigchaindb/bigchaindb
bigchaindb/commands/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/utils.py
Apache-2.0
def input_on_stderr(prompt='', default=None, convert=None): """Output a string to stderr and wait for input. Args: prompt (str): the message to display. default: the default value to return if the user leaves the field empty convert (callable): a callable to be used to convert the value the user inserted. If None, the type of ``default`` will be used. """ print(prompt, end='', file=sys.stderr) value = builtins.input() return _convert(value, default, convert)
Output a string to stderr and wait for input. Args: prompt (str): the message to display. default: the default value to return if the user leaves the field empty convert (callable): a callable to be used to convert the value the user inserted. If None, the type of ``default`` will be used.
input_on_stderr
python
bigchaindb/bigchaindb
bigchaindb/commands/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/utils.py
Apache-2.0
def start(parser, argv, scope): """Utility function to execute a subcommand. The function will look up in the ``scope`` if there is a function called ``run_<parser.args.command>`` and will run it using ``parser.args`` as first positional argument. Args: parser: an ArgumentParser instance. argv: the list of command line arguments without the script name. scope (dict): map containing (eventually) the functions to be called. Raises: NotImplementedError: if ``scope`` doesn't contain a function called ``run_<parser.args.command>``. """ args = parser.parse_args(argv) if not args.command: parser.print_help() raise SystemExit() # look up in the current scope for a function called 'run_<command>' # replacing all the dashes '-' with the lowercase character '_' func = scope.get('run_' + args.command.replace('-', '_')) # if no command has been found, raise a `NotImplementedError` if not func: raise NotImplementedError('Command `{}` not yet implemented'. format(args.command)) args.multiprocess = getattr(args, 'multiprocess', False) if args.multiprocess is False: args.multiprocess = 1 elif args.multiprocess is None: args.multiprocess = mp.cpu_count() return func(args)
Utility function to execute a subcommand. The function will look up in the ``scope`` if there is a function called ``run_<parser.args.command>`` and will run it using ``parser.args`` as first positional argument. Args: parser: an ArgumentParser instance. argv: the list of command line arguments without the script name. scope (dict): map containing (eventually) the functions to be called. Raises: NotImplementedError: if ``scope`` doesn't contain a function called ``run_<parser.args.command>``.
start
python
bigchaindb/bigchaindb
bigchaindb/commands/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/commands/utils.py
Apache-2.0
def generate_key_pair(): """Generates a cryptographic key pair. Returns: :class:`~bigchaindb.common.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb.common.crypto.CryptoKeypair.private_key` and :attr:`~bigchaindb.common.crypto.CryptoKeypair.public_key`. """ # TODO FOR CC: Adjust interface so that this function becomes unnecessary return CryptoKeypair( *(k.decode() for k in crypto.ed25519_generate_key_pair()))
Generates a cryptographic key pair. Returns: :class:`~bigchaindb.common.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb.common.crypto.CryptoKeypair.private_key` and :attr:`~bigchaindb.common.crypto.CryptoKeypair.public_key`.
generate_key_pair
python
bigchaindb/bigchaindb
bigchaindb/common/crypto.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/crypto.py
Apache-2.0
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_key.encode(encoding='base58').decode('utf-8'), public_key=public_key.encode(encoding='base58').decode('utf-8'))
Generate base58 encode public-private key pair from a hex encoded private key
key_pair_from_ed25519_key
python
bigchaindb/bigchaindb
bigchaindb/common/crypto.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/crypto.py
Apache-2.0
def __init__(self, fulfillment, owners_before, fulfills=None): """Create an instance of an :class:`~.Input`. Args: fulfillment (:class:`cryptoconditions.Fulfillment`): A Fulfillment to be signed with a private key. owners_before (:obj:`list` of :obj:`str`): A list of owners after a Transaction was confirmed. fulfills (:class:`~bigchaindb.common.transaction. TransactionLink`, optional): A link representing the input of a `TRANSFER` Transaction. """ if fulfills is not None and not isinstance(fulfills, TransactionLink): raise TypeError('`fulfills` must be a TransactionLink instance') if not isinstance(owners_before, list): raise TypeError('`owners_before` must be a list instance') self.fulfillment = fulfillment self.fulfills = fulfills self.owners_before = owners_before
Create an instance of an :class:`~.Input`. Args: fulfillment (:class:`cryptoconditions.Fulfillment`): A Fulfillment to be signed with a private key. owners_before (:obj:`list` of :obj:`str`): A list of owners after a Transaction was confirmed. fulfills (:class:`~bigchaindb.common.transaction. TransactionLink`, optional): A link representing the input of a `TRANSFER` Transaction.
__init__
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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. """ try: fulfillment = self.fulfillment.serialize_uri() except (TypeError, AttributeError, ASN1EncodeError, ASN1DecodeError): fulfillment = _fulfillment_to_details(self.fulfillment) try: # NOTE: `self.fulfills` can be `None` and that's fine fulfills = self.fulfills.to_dict() except AttributeError: fulfills = None input_ = { 'owners_before': self.owners_before, 'fulfills': fulfills, 'fulfillment': fulfillment, } return input_
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.
to_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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. Returns: :class:`~bigchaindb.common.transaction.Input` Raises: InvalidSignature: If an Input's URI couldn't be parsed. """ fulfillment = data['fulfillment'] if not isinstance(fulfillment, (Fulfillment, type(None))): try: fulfillment = Fulfillment.from_uri(data['fulfillment']) except ASN1DecodeError: # TODO Remove as it is legacy code, and simply fall back on # ASN1DecodeError raise InvalidSignature("Fulfillment URI couldn't been parsed") except TypeError: # NOTE: See comment about this special case in # `Input.to_dict` fulfillment = _fulfillment_from_details(data['fulfillment']) fulfills = TransactionLink.from_dict(data['fulfills']) return cls(fulfillment, data['owners_before'], fulfills)
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: :class:`~bigchaindb.common.transaction.Input` Raises: InvalidSignature: If an Input's URI couldn't be parsed.
from_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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.b58encode(fulfillment.public_key).decode(), } if fulfillment.type_name == 'threshold-sha-256': subconditions = [ _fulfillment_to_details(cond['body']) for cond in fulfillment.subconditions ] return { 'type': 'threshold-sha-256', 'threshold': fulfillment.threshold, 'subconditions': subconditions, } raise UnsupportedTypeError(fulfillment.type_name)
Encode a fulfillment as a details dictionary Args: fulfillment: Crypto-conditions Fulfillment object
_fulfillment_to_details
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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['public_key']) return Ed25519Sha256(public_key=public_key) if data['type'] == 'threshold-sha-256': threshold = ThresholdSha256(data['threshold']) for cond in data['subconditions']: cond = _fulfillment_from_details(cond, _depth+1) threshold.add_subfulfillment(cond) return threshold raise UnsupportedTypeError(data.get('type'))
Load a fulfillment for a signing spec dictionary Args: data: tx.output[].condition.details dictionary
_fulfillment_from_details
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def __init__(self, txid=None, output=None): """Create an instance of a :class:`~.TransactionLink`. Note: In an IPLD implementation, this class is not necessary anymore, as an IPLD link can simply point to an object, as well as an objects properties. So instead of having a (de)serializable class, we can have a simple IPLD link of the form: `/<tx_id>/transaction/outputs/<output>/`. Args: txid (str, optional): A Transaction to link to. output (int, optional): An Outputs's index in a Transaction with id `txid`. """ self.txid = txid self.output = output
Create an instance of a :class:`~.TransactionLink`. Note: In an IPLD implementation, this class is not necessary anymore, as an IPLD link can simply point to an object, as well as an objects properties. So instead of having a (de)serializable class, we can have a simple IPLD link of the form: `/<tx_id>/transaction/outputs/<output>/`. Args: txid (str, optional): A Transaction to link to. output (int, optional): An Outputs's index in a Transaction with id `txid`.
__init__
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def from_dict(cls, link): """Transforms a Python dictionary to a TransactionLink object. Args: link (dict): The link to be transformed. Returns: :class:`~bigchaindb.common.transaction.TransactionLink` """ try: return cls(link['transaction_id'], link['output_index']) except TypeError: return cls()
Transforms a Python dictionary to a TransactionLink object. Args: link (dict): The link to be transformed. Returns: :class:`~bigchaindb.common.transaction.TransactionLink`
from_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 { 'transaction_id': self.txid, 'output_index': self.output, }
Transforms the object to a Python dictionary. Returns: (dict|None): The link as an alternative serialization format.
to_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def __init__(self, fulfillment, public_keys=None, amount=1): """Create an instance of a :class:`~.Output`. Args: fulfillment (:class:`cryptoconditions.Fulfillment`): A Fulfillment to extract a Condition from. public_keys (:obj:`list` of :obj:`str`, optional): A list of owners before a Transaction was confirmed. amount (int): The amount of Assets to be locked with this Output. Raises: TypeError: if `public_keys` is not instance of `list`. """ if not isinstance(public_keys, list) and public_keys is not None: raise TypeError('`public_keys` must be a list instance or None') if not isinstance(amount, int): raise TypeError('`amount` must be an int') if amount < 1: raise AmountError('`amount` must be greater than 0') if amount > self.MAX_AMOUNT: raise AmountError('`amount` must be <= %s' % self.MAX_AMOUNT) self.fulfillment = fulfillment self.amount = amount self.public_keys = public_keys
Create an instance of a :class:`~.Output`. Args: fulfillment (:class:`cryptoconditions.Fulfillment`): A Fulfillment to extract a Condition from. public_keys (:obj:`list` of :obj:`str`, optional): A list of owners before a Transaction was confirmed. amount (int): The amount of Assets to be locked with this Output. Raises: TypeError: if `public_keys` is not instance of `list`.
__init__
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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. """ # TODO FOR CC: It must be able to recognize a hashlock condition # and fulfillment! condition = {} try: condition['details'] = _fulfillment_to_details(self.fulfillment) except AttributeError: pass try: condition['uri'] = self.fulfillment.condition_uri except AttributeError: condition['uri'] = self.fulfillment output = { 'public_keys': self.public_keys, 'condition': condition, 'amount': str(self.amount), } return output
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.
to_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 following structure is sufficient: [(address|condition)*, [(address|condition)*, ...], ...] Args: public_keys (:obj:`list` of :obj:`str`): The public key of the users that should be able to fulfill the Condition that is being created. amount (:obj:`int`): The amount locked by the Output. Returns: An Output that can be used in a Transaction. Raises: TypeError: If `public_keys` is not an instance of `list`. ValueError: If `public_keys` is an empty list. """ threshold = len(public_keys) if not isinstance(amount, int): raise TypeError('`amount` must be a int') if amount < 1: raise AmountError('`amount` needs to be greater than zero') if not isinstance(public_keys, list): raise TypeError('`public_keys` must be an instance of list') if len(public_keys) == 0: raise ValueError('`public_keys` needs to contain at least one' 'owner') elif len(public_keys) == 1 and not isinstance(public_keys[0], list): if isinstance(public_keys[0], Fulfillment): ffill = public_keys[0] else: ffill = Ed25519Sha256( public_key=base58.b58decode(public_keys[0])) return cls(ffill, public_keys, amount=amount) else: initial_cond = ThresholdSha256(threshold=threshold) threshold_cond = reduce(cls._gen_condition, public_keys, initial_cond) return cls(threshold_cond, public_keys, amount=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 following structure is sufficient: [(address|condition)*, [(address|condition)*, ...], ...] Args: public_keys (:obj:`list` of :obj:`str`): The public key of the users that should be able to fulfill the Condition that is being created. amount (:obj:`int`): The amount locked by the Output. Returns: An Output that can be used in a Transaction. Raises: TypeError: If `public_keys` is not an instance of `list`. ValueError: If `public_keys` is an empty list.
generate
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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:`~.Output.generate`. Args: initial (:class:`cryptoconditions.ThresholdSha256`): A Condition representing the overall root. new_public_keys (:obj:`list` of :obj:`str`|str): A list of new owners or a single new owner. Returns: :class:`cryptoconditions.ThresholdSha256`: """ try: threshold = len(new_public_keys) except TypeError: threshold = None if isinstance(new_public_keys, list) and len(new_public_keys) > 1: ffill = ThresholdSha256(threshold=threshold) reduce(cls._gen_condition, new_public_keys, ffill) elif isinstance(new_public_keys, list) and len(new_public_keys) <= 1: raise ValueError('Sublist cannot contain single owner') else: try: new_public_keys = new_public_keys.pop() except AttributeError: pass # NOTE: Instead of submitting base58 encoded addresses, a user # of this class can also submit fully instantiated # Cryptoconditions. In the case of casting # `new_public_keys` to a Ed25519Fulfillment with the # result of a `TypeError`, we're assuming that # `new_public_keys` is a Cryptocondition then. if isinstance(new_public_keys, Fulfillment): ffill = new_public_keys else: ffill = Ed25519Sha256( public_key=base58.b58decode(new_public_keys)) initial.add_subfulfillment(ffill) return initial
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 (:class:`cryptoconditions.ThresholdSha256`): A Condition representing the overall root. new_public_keys (:obj:`list` of :obj:`str`|str): A list of new owners or a single new owner. Returns: :class:`cryptoconditions.ThresholdSha256`:
_gen_condition
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 anymore. Args: data (dict): The dict to be transformed. Returns: :class:`~bigchaindb.common.transaction.Output` """ try: fulfillment = _fulfillment_from_details(data['condition']['details']) except KeyError: # NOTE: Hashlock condition case fulfillment = data['condition']['uri'] try: amount = int(data['amount']) except ValueError: raise AmountError('Invalid amount: %s' % data['amount']) return cls(fulfillment, data['public_keys'], amount)
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. Args: data (dict): The dict to be transformed. Returns: :class:`~bigchaindb.common.transaction.Output`
from_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def __init__(self, operation, asset, inputs=None, outputs=None, metadata=None, version=None, hash_id=None, tx_dict=None): """The constructor allows to create a customizable Transaction. Note: When no `version` is provided, one is being generated by this method. Args: operation (str): Defines the operation of the Transaction. asset (dict): Asset payload for this Transaction. inputs (:obj:`list` of :class:`~bigchaindb.common. transaction.Input`, optional): Define the assets to outputs (:obj:`list` of :class:`~bigchaindb.common. transaction.Output`, optional): Define the assets to lock. metadata (dict): Metadata to be stored along with the Transaction. version (string): Defines the version number of a Transaction. hash_id (string): Hash id of the transaction. """ if operation not in self.ALLOWED_OPERATIONS: allowed_ops = ', '.join(self.__class__.ALLOWED_OPERATIONS) raise ValueError('`operation` must be one of {}' .format(allowed_ops)) # Asset payloads for 'CREATE' operations must be None or # dicts holding a `data` property. Asset payloads for 'TRANSFER' # operations must be dicts holding an `id` property. if (operation == self.CREATE and asset is not None and not (isinstance(asset, dict) and 'data' in asset)): raise TypeError(('`asset` must be None or a dict holding a `data` ' " property instance for '{}' Transactions".format(operation))) elif (operation == self.TRANSFER and not (isinstance(asset, dict) and 'id' in asset)): raise TypeError(('`asset` must be a dict holding an `id` property ' 'for \'TRANSFER\' Transactions')) if outputs and not isinstance(outputs, list): raise TypeError('`outputs` must be a list instance or None') if inputs and not isinstance(inputs, list): raise TypeError('`inputs` must be a list instance or None') if metadata is not None and not isinstance(metadata, dict): raise TypeError('`metadata` must be a dict or None') self.version = version if version is not None else self.VERSION self.operation = operation self.asset = asset self.inputs = inputs or [] self.outputs = outputs or [] self.metadata = metadata self._id = hash_id self.tx_dict = tx_dict
The constructor allows to create a customizable Transaction. Note: When no `version` is provided, one is being generated by this method. Args: operation (str): Defines the operation of the Transaction. asset (dict): Asset payload for this Transaction. inputs (:obj:`list` of :class:`~bigchaindb.common. transaction.Input`, optional): Define the assets to outputs (:obj:`list` of :class:`~bigchaindb.common. transaction.Output`, optional): Define the assets to lock. metadata (dict): Metadata to be stored along with the Transaction. version (string): Defines the version number of a Transaction. hash_id (string): Hash id of the transaction.
__init__
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def unspent_outputs(self): """UnspentOutput: The outputs of this transaction, in a data structure containing relevant information for storing them in a UTXO set, and performing validation. """ if self.operation == self.CREATE: self._asset_id = self._id elif self.operation == self.TRANSFER: self._asset_id = self.asset['id'] return (UnspentOutput( transaction_id=self._id, output_index=output_index, amount=output.amount, asset_id=self._asset_id, condition_uri=output.fulfillment.condition_uri, ) for output_index, output in enumerate(self.outputs))
UnspentOutput: The outputs of this transaction, in a data structure containing relevant information for storing them in a UTXO set, and performing validation.
unspent_outputs
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 )
Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index.
spent_outputs
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 Additionally, it provides support for the following BigchainDB use cases: - Multiple inputs and outputs. Args: tx_signers (:obj:`list` of :obj:`str`): A list of keys that represent the signers of the CREATE Transaction. recipients (:obj:`list` of :obj:`tuple`): A list of ([keys],amount) that represent the recipients of this Transaction. metadata (dict): The metadata to be stored along with the Transaction. asset (dict): The metadata associated with the asset that will be created in this Transaction. Returns: :class:`~bigchaindb.common.transaction.Transaction` """ (inputs, outputs) = cls.validate_create(tx_signers, recipients, asset, metadata) return cls(cls.CREATE, {'data': asset}, inputs, outputs, metadata)
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 use cases: - Multiple inputs and outputs. Args: tx_signers (:obj:`list` of :obj:`str`): A list of keys that represent the signers of the CREATE Transaction. recipients (:obj:`list` of :obj:`tuple`): A list of ([keys],amount) that represent the recipients of this Transaction. metadata (dict): The metadata to be stored along with the Transaction. asset (dict): The metadata associated with the asset that will be created in this Transaction. Returns: :class:`~bigchaindb.common.transaction.Transaction`
create
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def transfer(cls, inputs, recipients, asset_id, metadata=None): """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 like to support. The following notation is proposed: 1. The index of a `recipient` corresponds to the index of an input: e.g. `transfer([input1], [a])`, means `input1` would now be owned by user `a`. 2. `recipients` can (almost) get arbitrary deeply nested, creating various complex threshold conditions: e.g. `transfer([inp1, inp2], [[a, [b, c]], d])`, means `a`'s signature would have a 50% weight on `inp1` compared to `b` and `c` that share 25% of the leftover weight respectively. `inp2` is owned completely by `d`. Args: inputs (:obj:`list` of :class:`~bigchaindb.common.transaction. Input`): Converted `Output`s, intended to be used as inputs in the transfer to generate. recipients (:obj:`list` of :obj:`tuple`): A list of ([keys],amount) that represent the recipients of this Transaction. asset_id (str): The asset ID of the asset to be transferred in this Transaction. metadata (dict): Python dictionary to be stored along with the Transaction. Returns: :class:`~bigchaindb.common.transaction.Transaction` """ (inputs, outputs) = cls.validate_transfer(inputs, recipients, asset_id, metadata) return cls(cls.TRANSFER, {'id': asset_id}, inputs, outputs, metadata)
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 like to support. The following notation is proposed: 1. The index of a `recipient` corresponds to the index of an input: e.g. `transfer([input1], [a])`, means `input1` would now be owned by user `a`. 2. `recipients` can (almost) get arbitrary deeply nested, creating various complex threshold conditions: e.g. `transfer([inp1, inp2], [[a, [b, c]], d])`, means `a`'s signature would have a 50% weight on `inp1` compared to `b` and `c` that share 25% of the leftover weight respectively. `inp2` is owned completely by `d`. Args: inputs (:obj:`list` of :class:`~bigchaindb.common.transaction. Input`): Converted `Output`s, intended to be used as inputs in the transfer to generate. recipients (:obj:`list` of :obj:`tuple`): A list of ([keys],amount) that represent the recipients of this Transaction. asset_id (str): The asset ID of the asset to be transferred in this Transaction. metadata (dict): Python dictionary to be stored along with the Transaction. Returns: :class:`~bigchaindb.common.transaction.Transaction`
transfer
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 integers can be passed to `indices` that defines which outputs should be returned as inputs. If no `indices` are passed (empty list or None) all outputs of the Transaction are returned. Args: indices (:obj:`list` of int): Defines which outputs should be returned as inputs. Returns: :obj:`list` of :class:`~bigchaindb.common.transaction. Input` """ # NOTE: If no indices are passed, we just assume to take all outputs # as inputs. indices = indices or range(len(self.outputs)) return [ Input(self.outputs[idx].fulfillment, self.outputs[idx].public_keys, TransactionLink(self.id, idx)) for idx in indices ]
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 defines which outputs should be returned as inputs. If no `indices` are passed (empty list or None) all outputs of the Transaction are returned. Args: indices (:obj:`list` of int): Defines which outputs should be returned as inputs. Returns: :obj:`list` of :class:`~bigchaindb.common.transaction. Input`
to_inputs
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 TypeError('`input_` must be a Input instance') self.inputs.append(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.
add_input
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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): raise TypeError('`output` must be an Output instance or None') self.outputs.append(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.
add_output
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 Furthermore, note that all keys required to fully sign the Transaction have to be passed to this method. A subset of all will cause this method to fail. Args: private_keys (:obj:`list` of :obj:`str`): A complete list of all private keys needed to sign all Fulfillments of this Transaction. Returns: :class:`~bigchaindb.common.transaction.Transaction` """ # TODO: Singing should be possible with at least one of all private # keys supplied to this method. if private_keys is None or not isinstance(private_keys, list): raise TypeError('`private_keys` must be a list instance') # NOTE: Generate public keys from private keys and match them in a # dictionary: # key: public_key # value: private_key def gen_public_key(private_key): # TODO FOR CC: Adjust interface so that this function becomes # unnecessary # cc now provides a single method `encode` to return the key # in several different encodings. public_key = private_key.get_verifying_key().encode() # Returned values from cc are always bytestrings so here we need # to decode to convert the bytestring into a python str return public_key.decode() key_pairs = {gen_public_key(PrivateKey(private_key)): PrivateKey(private_key) for private_key in private_keys} tx_dict = self.to_dict() tx_dict = Transaction._remove_signatures(tx_dict) tx_serialized = Transaction._to_str(tx_dict) for i, input_ in enumerate(self.inputs): self.inputs[i] = self._sign_input(input_, tx_serialized, key_pairs) self._hash() return self
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 fully sign the Transaction have to be passed to this method. A subset of all will cause this method to fail. Args: private_keys (:obj:`list` of :obj:`str`): A complete list of all private keys needed to sign all Fulfillments of this Transaction. Returns: :class:`~bigchaindb.common.transaction.Transaction`
sign
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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: 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. """ if isinstance(input_.fulfillment, Ed25519Sha256): return cls._sign_simple_signature_fulfillment(input_, message, key_pairs) elif isinstance(input_.fulfillment, ThresholdSha256): return cls._sign_threshold_signature_fulfillment(input_, message, key_pairs) else: raise ValueError( 'Fulfillment couldn\'t be matched to ' 'Cryptocondition fulfillment type.')
Signs a single Input. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - 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.
_sign_input
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 key_pairs (dict): The keys to sign the Transaction with. """ # NOTE: To eliminate the dangers of accidentally signing a condition by # reference, we remove the reference of input_ here # intentionally. If the user of this class knows how to use it, # this should never happen, but then again, never say never. input_ = deepcopy(input_) public_key = input_.owners_before[0] message = sha3_256(message.encode()) if input_.fulfills: message.update('{}{}'.format( input_.fulfills.txid, input_.fulfills.output).encode()) try: # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings input_.fulfillment.sign( message.digest(), base58.b58decode(key_pairs[public_key].encode())) except KeyError: raise KeypairMismatchException('Public key {} is not a pair to ' 'any of the private keys' .format(public_key)) return input_
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.
_sign_simple_signature_fulfillment
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 key_pairs (dict): The keys to sign the Transaction with. """ input_ = deepcopy(input_) message = sha3_256(message.encode()) if input_.fulfills: message.update('{}{}'.format( input_.fulfills.txid, input_.fulfills.output).encode()) for owner_before in set(input_.owners_before): # TODO: CC should throw a KeypairMismatchException, instead of # our manual mapping here # TODO FOR CC: Naming wise this is not so smart, # `get_subcondition` in fact doesn't return a # condition but a fulfillment # TODO FOR CC: `get_subcondition` is singular. One would not # expect to get a list back. ccffill = input_.fulfillment subffills = ccffill.get_subcondition_from_vk( base58.b58decode(owner_before)) if not subffills: raise KeypairMismatchException('Public key {} cannot be found ' 'in the fulfillment' .format(owner_before)) try: private_key = key_pairs[owner_before] except KeyError: raise KeypairMismatchException('Public key {} is not a pair ' 'to any of the private keys' .format(owner_before)) # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings for subffill in subffills: subffill.sign( message.digest(), base58.b58decode(private_key.encode())) return input_
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.
_sign_threshold_signature_fulfillment
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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:`list` of :obj:`str`): A list of Outputs to check the Inputs against. Returns: bool: If all Outputs are valid. """ if len(self.inputs) != len(output_condition_uris): raise ValueError('Inputs and ' 'output_condition_uris must have the same count') tx_dict = self.tx_dict if self.tx_dict else self.to_dict() tx_dict = Transaction._remove_signatures(tx_dict) tx_dict['id'] = None tx_serialized = Transaction._to_str(tx_dict) def validate(i, output_condition_uri=None): """Validate input against output condition URI""" return self._input_valid(self.inputs[i], self.operation, tx_serialized, output_condition_uri) return all(validate(i, cond) for i, cond in enumerate(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:`list` of :obj:`str`): A list of Outputs to check the Inputs against. Returns: bool: If all Outputs are valid.
_inputs_valid
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def _input_valid(self, input_, operation, message, output_condition_uri=None): """Validates a single Input against a single Output. Note: In case of a `CREATE` Transaction, this method does not validate against `output_condition_uri`. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The Input to be signed. operation (str): The type of Transaction. message (str): The fulfillment message. output_condition_uri (str, optional): An Output to check the Input against. Returns: bool: If the Input is valid. """ ccffill = input_.fulfillment try: parsed_ffill = Fulfillment.from_uri(ccffill.serialize_uri()) except (TypeError, ValueError, ParsingError, ASN1DecodeError, ASN1EncodeError): return False if operation == self.CREATE: # NOTE: In the case of a `CREATE` transaction, the # output is always valid. output_valid = True else: output_valid = output_condition_uri == ccffill.condition_uri message = sha3_256(message.encode()) if input_.fulfills: message.update('{}{}'.format( input_.fulfills.txid, input_.fulfills.output).encode()) # NOTE: We pass a timestamp to `.validate`, as in case of a timeout # condition we'll have to validate against it # cryptoconditions makes no assumptions of the encoding of the # message to sign or verify. It only accepts bytestrings ffill_valid = parsed_ffill.validate(message=message.digest()) return output_valid and ffill_valid
Validates a single Input against a single Output. Note: In case of a `CREATE` Transaction, this method does not validate against `output_condition_uri`. Args: input_ (:class:`~bigchaindb.common.transaction. Input`) The Input to be signed. operation (str): The type of Transaction. message (str): The fulfillment message. output_condition_uri (str, optional): An Output to check the Input against. Returns: bool: If the Input is valid.
_input_valid
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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 output in self.outputs], 'operation': str(self.operation), 'metadata': self.metadata, 'asset': self.asset, 'version': self.version, 'id': self._id, }
Transforms the object to a Python dictionary. Returns: dict: The Transaction as an alternative serialization format.
to_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def _remove_signatures(tx_dict): """Takes a Transaction dictionary and removes all signatures. Args: tx_dict (dict): The Transaction to remove all signatures from. Returns: dict """ # NOTE: We remove the reference since we need `tx_dict` only for the # transaction's hash tx_dict = deepcopy(tx_dict) for input_ in tx_dict['inputs']: # NOTE: Not all Cryptoconditions return a `signature` key (e.g. # ThresholdSha256), so setting it to `None` in any # case could yield incorrect signatures. This is why we only # set it to `None` if it's set in the dict. input_['fulfillment'] = None return tx_dict
Takes a Transaction dictionary and removes all signatures. Args: tx_dict (dict): The Transaction to remove all signatures from. Returns: dict
_remove_signatures
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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. transaction.Transaction`): A list of Transactions. Usually input Transactions that should have a matching asset ID. Returns: str: ID of the asset. Raises: :exc:`AssetIdMismatch`: If the inputs are related to different assets. """ if not isinstance(transactions, list): transactions = [transactions] # create a set of the transactions' asset ids asset_ids = {tx.id if tx.operation == tx.CREATE else tx.asset['id'] for tx in transactions} # check that all the transasctions have the same asset id if len(asset_ids) > 1: raise AssetIdMismatch(('All inputs of all transactions passed' ' need to have the same asset id')) return asset_ids.pop()
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 of Transactions. Usually input Transactions that should have a matching asset ID. Returns: str: ID of the asset. Raises: :exc:`AssetIdMismatch`: If the inputs are related to different assets.
get_asset_id
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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.dumps(tx_body)) try: proposed_tx_id = tx_body['id'] except KeyError: raise InvalidHash('No transaction id found!') tx_body['id'] = None tx_body_serialized = Transaction._to_str(tx_body) valid_tx_id = Transaction._to_hash(tx_body_serialized) if proposed_tx_id != valid_tx_id: err_msg = ("The transaction's id '{}' isn't equal to " "the hash of its body, i.e. it's not valid.") raise InvalidHash(err_msg.format(proposed_tx_id))
Validate the transaction ID of a transaction Args: tx_body (dict): The Transaction to be transformed.
validate_id
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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` """ operation = tx.get('operation', Transaction.CREATE) if isinstance(tx, dict) else Transaction.CREATE cls = Transaction.resolve_class(operation) if not skip_schema_validation: cls.validate_id(tx) cls.validate_schema(tx) inputs = [Input.from_dict(input_) for input_ in tx['inputs']] outputs = [Output.from_dict(output) for output in tx['outputs']] return cls(tx['operation'], tx['asset'], inputs, outputs, tx['metadata'], tx['version'], hash_id=tx['id'], tx_dict=tx)
Transforms a Python dictionary to a Transaction object. Args: tx_body (dict): The Transaction to be transformed. Returns: :class:`~bigchaindb.common.transaction.Transaction`
from_dict
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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:`~bigchaindb.tendermint.BigchainDB`): An instance of BigchainDB used to perform database queries. tx_dict_list (:list:`dict` or :obj:`dict`): The transaction dict or list of transaction dict as returned from the database. Returns: :class:`~Transaction` """ return_list = True if isinstance(tx_dict_list, dict): tx_dict_list = [tx_dict_list] return_list = False tx_map = {} tx_ids = [] for tx in tx_dict_list: tx.update({'metadata': None}) tx_map[tx['id']] = tx tx_ids.append(tx['id']) assets = list(bigchain.get_assets(tx_ids)) for asset in assets: if asset is not None: tx = tx_map[asset['id']] del asset['id'] tx['asset'] = asset tx_ids = list(tx_map.keys()) metadata_list = list(bigchain.get_metadata(tx_ids)) for metadata in metadata_list: tx = tx_map[metadata['id']] tx.update({'metadata': metadata.get('metadata')}) if return_list: tx_list = [] for tx_id, tx in tx_map.items(): tx_list.append(cls.from_dict(tx)) return tx_list else: tx = list(tx_map.values())[0] return cls.from_dict(tx)
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 of BigchainDB used to perform database queries. tx_dict_list (:list:`dict` or :obj:`dict`): The transaction dict or list of transaction dict as returned from the database. Returns: :class:`~Transaction`
from_db
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
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)
For the given `tx` based on the `operation` key return its implementation class
resolve_class
python
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/transaction.py
Apache-2.0
def validate_txn_obj(obj_name, obj, key, validation_fun): """Validate value of `key` in `obj` using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. key (str): key to be validated in `obj`. validation_fun (function): function used to validate the value of `key`. Returns: None: indicates validation successful Raises: ValidationError: `validation_fun` will raise exception on failure """ backend = bigchaindb.config['database']['backend'] if backend == 'localmongodb': data = obj.get(key, {}) if isinstance(data, dict): validate_all_keys_in_obj(obj_name, data, validation_fun) elif isinstance(data, list): validate_all_items_in_list(obj_name, data, validation_fun)
Validate value of `key` in `obj` using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. key (str): key to be validated in `obj`. validation_fun (function): function used to validate the value of `key`. Returns: None: indicates validation successful Raises: ValidationError: `validation_fun` will raise exception on failure
validate_txn_obj
python
bigchaindb/bigchaindb
bigchaindb/common/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/utils.py
Apache-2.0
def validate_all_keys_in_obj(obj_name, obj, validation_fun): """Validate all (nested) keys in `obj` by using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. validation_fun (function): function used to validate the value of `key`. Returns: None: indicates validation successful Raises: ValidationError: `validation_fun` will raise this error on failure """ for key, value in obj.items(): validation_fun(obj_name, key) if isinstance(value, dict): validate_all_keys_in_obj(obj_name, value, validation_fun) elif isinstance(value, list): validate_all_items_in_list(obj_name, value, validation_fun)
Validate all (nested) keys in `obj` by using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. validation_fun (function): function used to validate the value of `key`. Returns: None: indicates validation successful Raises: ValidationError: `validation_fun` will raise this error on failure
validate_all_keys_in_obj
python
bigchaindb/bigchaindb
bigchaindb/common/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/utils.py
Apache-2.0
def validate_all_values_for_key_in_obj(obj, key, validation_fun): """Validate value for all (nested) occurrence of `key` in `obj` using `validation_fun`. Args: obj (dict): dictionary object. key (str): key whose value is to be validated. validation_fun (function): function used to validate the value of `key`. Raises: ValidationError: `validation_fun` will raise this error on failure """ for vkey, value in obj.items(): if vkey == key: validation_fun(value) elif isinstance(value, dict): validate_all_values_for_key_in_obj(value, key, validation_fun) elif isinstance(value, list): validate_all_values_for_key_in_list(value, key, validation_fun)
Validate value for all (nested) occurrence of `key` in `obj` using `validation_fun`. Args: obj (dict): dictionary object. key (str): key whose value is to be validated. validation_fun (function): function used to validate the value of `key`. Raises: ValidationError: `validation_fun` will raise this error on failure
validate_all_values_for_key_in_obj
python
bigchaindb/bigchaindb
bigchaindb/common/utils.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/utils.py
Apache-2.0
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': _validate_schema(TX_SCHEMA_TRANSFER, tx) else: _validate_schema(TX_SCHEMA_CREATE, 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_transaction_schema
python
bigchaindb/bigchaindb
bigchaindb/common/schema/__init__.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/common/schema/__init__.py
Apache-2.0
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 None return bigchain.get_validator_change(latest_block['height'])
Return the validator set from the most recent approved block :return: { 'height': <block_height>, 'validators': <validator_set> }
get_validator_change
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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 in base64 public_key = public_key_from_ed25519_key(key_from_base64(validator['public_key']['value'])) validators[public_key] = validator['voting_power'] return validators
Return a dictionary of validators with key as `public_key` and value as the `voting_power`
get_validators
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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
Convert validator dictionary to a recipient list for `Transaction`
recipients
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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 validator node. Args: :param bigchain: (BigchainDB) an instantiated bigchaindb.lib.BigchainDB object. :param current_transactions: (list) A list of transactions to be validated along with the election Returns: Election: a Election object or an object of the derived Election subclass. Raises: ValidationError: If the election is invalid """ input_conditions = [] duplicates = any(txn for txn in current_transactions if txn.id == self.id) if bigchain.is_committed(self.id) or duplicates: raise DuplicateTransaction('transaction `{}` already exists' .format(self.id)) if not self.inputs_valid(input_conditions): raise InvalidSignature('Transaction signature is invalid.') current_validators = self.get_validators(bigchain) # NOTE: Proposer should be a single node if len(self.inputs) != 1 or len(self.inputs[0].owners_before) != 1: raise MultipleInputsError('`tx_signers` must be a list instance of length one') # NOTE: Check if the proposer is a validator. [election_initiator_node_pub_key] = self.inputs[0].owners_before if election_initiator_node_pub_key not in current_validators.keys(): raise InvalidProposer('Public key is not a part of the validator set') # NOTE: Check if all validators have been assigned votes equal to their voting power if not self.is_same_topology(current_validators, self.outputs): raise UnequalValidatorSet('Validator set much be exactly same to the outputs of election') return self
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) an instantiated bigchaindb.lib.BigchainDB object. :param current_transactions: (list) A list of transactions to be validated along with the election Returns: Election: a Election object or an object of the derived Election subclass. Raises: ValidationError: If the election is invalid
validate
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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_SCHEMA_CUSTOM: _validate_schema(cls.TX_SCHEMA_CUSTOM, tx)
Validate the election transaction. Since `ELECTION` extends `CREATE` transaction, all the validations for `CREATE` transaction should be inherited
validate_schema
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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. Custom elections may override this function and introduce additional checks. """ if self.has_validator_set_changed(bigchain): return False election_pk = self.to_public_key(self.id) votes_committed = self.get_commited_votes(bigchain, election_pk) votes_current = self.count_votes(election_pk, current_votes) total_votes = sum(output.amount for output in self.outputs) if (votes_committed < (2/3) * total_votes) and \ (votes_committed + votes_current >= (2/3)*total_votes): return True return False
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 introduce additional checks.
has_concluded
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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 election is concluded, the corresponding database record is marked as such. Elections and votes are processed in the order in which they appear in the block. Elections are concluded in the order of appearance of their first votes in the block. For every election concluded in the block, calls its `on_approval` method. The returned value of the last `on_approval`, if any, is a validator set update to be applied in one of the following blocks. `on_approval` methods are implemented by elections of particular type. The method may contain side effects but should be idempotent. To account for other concluded elections, if it requires so, the method should rely on the database state. """ # elections initiated in this block initiated_elections = cls._get_initiated_elections(new_height, txns) if initiated_elections: bigchain.store_elections(initiated_elections) # elections voted for in this block and their votes elections = cls._get_votes(txns) validator_update = None for election_id, votes in elections.items(): election = bigchain.get_transaction(election_id) if election is None: continue if not election.has_concluded(bigchain, votes): continue validator_update = election.on_approval(bigchain, new_height) election.store(bigchain, new_height, is_concluded=True) return [validator_update] if validator_update else []
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 marked as such. Elections and votes are processed in the order in which they appear in the block. Elections are concluded in the order of appearance of their first votes in the block. For every election concluded in the block, calls its `on_approval` method. The returned value of the last `on_approval`, if any, is a validator set update to be applied in one of the following blocks. `on_approval` methods are implemented by elections of particular type. The method may contain side effects but should be idempotent. To account for other concluded elections, if it requires so, the method should rely on the database state.
process_block
python
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/election.py
Apache-2.0
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) _validate_schema(cls.TX_SCHEMA_CUSTOM, tx)
Validate the validator election vote transaction. Since `VOTE` extends `TRANSFER` transaction, all the validations for `CREATE` transaction should be inherited
validate_schema
python
bigchaindb/bigchaindb
bigchaindb/elections/vote.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/elections/vote.py
Apache-2.0
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) # NOTE: change more than 1/3 of the current power is not allowed if self.asset['data']['power'] >= (1/3)*sum(current_validators.values()): raise InvalidPowerChange('`power` change must be less than 1/3 of total power') return self
For more details refer BEP-21: https://github.com/bigchaindb/BEPs/tree/master/21
validate
python
bigchaindb/bigchaindb
bigchaindb/upsert_validator/validator_election.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/upsert_validator/validator_election.py
Apache-2.0
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)
Add the routes to an app
add_routes
python
bigchaindb/bigchaindb
bigchaindb/web/routes.py
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/web/routes.py
Apache-2.0