INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Helper method to fetch the index of a resource by its id or address Args: resources (list of objects): The resources to be paginated target_id (string): The address or header_signature of the resource Returns: integer: The index of the target resource Raise...
def index_by_id(cls, target_id, resources): """Helper method to fetch the index of a resource by its id or address Args: resources (list of objects): The resources to be paginated target_id (string): The address or header_signature of the resource Returns: i...
Helper method to fetch the id or address of a resource by its index Args: resources (list of objects): The resources to be paginated index (integer): The index of the target resource Returns: str: The address or header_signature of the resource, retu...
def id_by_index(index, resources): """Helper method to fetch the id or address of a resource by its index Args: resources (list of objects): The resources to be paginated index (integer): The index of the target resource Returns: str: The address or header_s...
Sorts a list of resources based on a list of sort controls Args: request (object): The parsed protobuf request object resources (list of objects): The resources to be sorted fail_enum (int, enum): The enum status to raise with invalid keys header_proto(class): Cl...
def sort_resources(cls, request, resources, fail_enum, header_proto=None): """Sorts a list of resources based on a list of sort controls Args: request (object): The parsed protobuf request object resources (list of objects): The resources to be sorted fail_enum (int,...
Goes through the list of ClientSortControls and returns a list of unique _ValueHandlers. Maintains order, but drops ClientSortControls that have already appeared to help prevent spamming.
def _get_handler_set(cls, request, fail_enum, header_proto=None): """Goes through the list of ClientSortControls and returns a list of unique _ValueHandlers. Maintains order, but drops ClientSortControls that have already appeared to help prevent spamming. """ added = set() ...
Called by the BatchTracker the _BatchWaiter is observing. Should not be called by handlers. Args: statuses (dict of int): A dict with keys of batch ids, and values of status enums
def notify_batches_finished(self, statuses): """Called by the BatchTracker the _BatchWaiter is observing. Should not be called by handlers. Args: statuses (dict of int): A dict with keys of batch ids, and values of status enums """ with self._wait_con...
Locks until a list of batch ids is committed to the block chain or a timeout is exceeded. Returns the statuses of those batches. Args: batch_ids (list of str): The ids of the batches to wait for timeout(int): Maximum time in seconds to wait for Returns: list...
def wait_for_batches(self, batch_ids, timeout=None): """Locks until a list of batch ids is committed to the block chain or a timeout is exceeded. Returns the statuses of those batches. Args: batch_ids (list of str): The ids of the batches to wait for timeout(int): Maximu...
Verify that the directory exists and is readable and writable. Args: path (str): a directory which should exist and be writable human_readable_name (str): a human readable string for the directory which is used in logging statements Returns: bool: False if an error exists, ...
def check_directory(path, human_readable_name): """Verify that the directory exists and is readable and writable. Args: path (str): a directory which should exist and be writable human_readable_name (str): a human readable string for the directory which is used in logging statements...
Creates the arg parsers needed for the identity command and its subcommands.
def add_identity_parser(subparsers, parent_parser): """Creates the arg parsers needed for the identity command and its subcommands. """ # identity parser = subparsers.add_parser( 'identity', help='Works with optional roles, policies, and permissions', description='Provides su...
Executes the config commands subcommands.
def do_identity(args): """Executes the config commands subcommands. """ if args.subcommand == 'policy' and args.policy_cmd == 'create': _do_identity_policy_create(args) elif args.subcommand == 'policy' and args.policy_cmd == 'list': _do_identity_policy_list(args) elif args.subcommand...
Executes the 'policy create' subcommand. Given a key file, and a series of entries, it generates a batch of sawtooth_identity transactions in a BatchList instance. The BatchList is either stored to a file or submitted to a validator, depending on the supplied CLI arguments.
def _do_identity_policy_create(args): """Executes the 'policy create' subcommand. Given a key file, and a series of entries, it generates a batch of sawtooth_identity transactions in a BatchList instance. The BatchList is either stored to a file or submitted to a validator, depending on the supplied CL...
Lists the current on-chain configuration values.
def _do_identity_role_list(args): """Lists the current on-chain configuration values. """ rest_client = RestClient(args.url) state = rest_client.list_state(subtree=IDENTITY_NAMESPACE + _ROLE_PREFIX) head = state['head'] state_values = state['data'] printable_roles = [] for state_value i...
Reads the given file as a hex key. Args: key_filename: The filename where the key is stored. If None, defaults to the default key for the current user. Returns: Signer: the signer Raises: CliException: If unable to read the file.
def _read_signer(key_filename): """Reads the given file as a hex key. Args: key_filename: The filename where the key is stored. If None, defaults to the default key for the current user. Returns: Signer: the signer Raises: CliException: If unable to read the file. ...
Creates a batch from a list of transactions and a public key, and signs the resulting batch with the given signing key. Args: signer (:obj:`Signer`): The cryptographic signer transactions (list of `Transaction`): The transactions to add to the batch. Returns: `Batch`: T...
def _create_batch(signer, transactions): """Creates a batch from a list of transactions and a public key, and signs the resulting batch with the given signing key. Args: signer (:obj:`Signer`): The cryptographic signer transactions (list of `Transaction`): The transactions to add to the ...
Create a ExecutionContext to run a transaction against. Args: state_hash: (str): Merkle root to base state on. base_contexts (list of str): Context ids of contexts that will have their state applied to make this context. inputs (list of str): Addresses that c...
def create_context(self, state_hash, base_contexts, inputs, outputs): """Create a ExecutionContext to run a transaction against. Args: state_hash: (str): Merkle root to base state on. base_contexts (list of str): Context ids of contexts that will have their state...
Breadth first search through the chain of contexts searching for the bytes values at the addresses in addresses_to_find. Args: base_contexts (list of str): The context ids to start with. addresses_to_find (list of str): Addresses to find values in the chain of co...
def _find_address_values_in_chain(self, base_contexts, addresses_to_find): """Breadth first search through the chain of contexts searching for the bytes values at the addresses in addresses_to_find. Args: base_contexts (list of str): The context ids to start with. addres...
Delete contexts from the ContextManager. Args: context_id_list (list): a list of context ids Returns: None
def delete_contexts(self, context_id_list): """Delete contexts from the ContextManager. Args: context_id_list (list): a list of context ids Returns: None """ for c_id in context_id_list: if c_id in self._contexts: del self._c...
Delete the values associated with list of addresses, for a specific context referenced by context_id. Args: context_id (str): the return value of create_context, referencing a particular context. address_list (list): a list of address strs Returns: ...
def delete(self, context_id, address_list): """Delete the values associated with list of addresses, for a specific context referenced by context_id. Args: context_id (str): the return value of create_context, referencing a particular context. address_list...
Get the values associated with list of addresses, for a specific context referenced by context_id. Args: context_id (str): the return value of create_context, referencing a particular context. address_list (list): a list of address strs Returns: ...
def get(self, context_id, address_list): """Get the values associated with list of addresses, for a specific context referenced by context_id. Args: context_id (str): the return value of create_context, referencing a particular context. address_list (list...
Within a context, sets addresses to a value. Args: context_id (str): the context id returned by create_context address_value_list (list): list of {address: value} dicts Returns: (bool): True if the operation is successful, False if the context_id doe...
def set(self, context_id, address_value_list): """Within a context, sets addresses to a value. Args: context_id (str): the context id returned by create_context address_value_list (list): list of {address: value} dicts Returns: (bool): True if the operation ...
Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data (bytes): data to append Returns: (bool): True if the operation is successful, False if the context_id doesn't reference a kn...
def add_execution_data(self, context_id, data): """Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data (bytes): data to append Returns: (bool): True if the operation is successful, Fal...
Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data_type (str): type of data to append data (bytes): data to append Returns: (bool): True if the operation is successful, False if ...
def add_execution_event(self, context_id, event): """Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data_type (str): type of data to append data (bytes): data to append Returns: ...
Applies the given puts and deletes atomically. Args: puts (:iterable:`tuple`): an iterable of key/value pairs to insert deletes (:iterable:str:) an iterable of keys to delete
def update(self, puts, deletes): """Applies the given puts and deletes atomically. Args: puts (:iterable:`tuple`): an iterable of key/value pairs to insert deletes (:iterable:str:) an iterable of keys to delete """ with self._lmdb.begin(write=True, buffers=True) ...
Returns a list of keys in the database
def keys(self, index=None): """Returns a list of keys in the database """ if index is not None and index not in self._indexes: raise ValueError('Index {} does not exist'.format(index)) db = self._indexes[index][0] if index else self._main_db with self._lmdb.begin(db=...
Package up transactions into a batch and send them to the network via the provided batch_sender. :param transactions: list of transactions to package and broadcast. :return: None
def send(self, transactions): """ Package up transactions into a batch and send them to the network via the provided batch_sender. :param transactions: list of transactions to package and broadcast. :return: None """ txn_signatures = [txn.header_signature for txn in trans...
Creates a parser with arguments specific to sending HTTP requests to multiple REST APIs. Returns: {ArgumentParser}: Base parser with default HTTP args
def base_multinode_parser(): """Creates a parser with arguments specific to sending HTTP requests to multiple REST APIs. Returns: {ArgumentParser}: Base parser with default HTTP args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( 'urls', type...
Creates a parser with arguments specific to sending an HTTP request to the REST API. Returns: {ArgumentParser}: Base parser with default HTTP args
def base_http_parser(): """Creates a parser with arguments specific to sending an HTTP request to the REST API. Returns: {ArgumentParser}: Base parser with default HTTP args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( '--url', type=str, ...
Creates a parser with arguments specific to formatting lists of resources. Returns: {ArgumentParser}: Base parser with defaul list args
def base_list_parser(): """Creates a parser with arguments specific to formatting lists of resources. Returns: {ArgumentParser}: Base parser with defaul list args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( '-F', '--format', action='store'...
Creates a parser with arguments specific to formatting a single resource. Returns: {ArgumentParser}: Base parser with default show args
def base_show_parser(): """Creates a parser with arguments specific to formatting a single resource. Returns: {ArgumentParser}: Base parser with default show args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( '-k', '--key', type=str, ...
Returns a list of tuples of (block id, BlockStatus) pairs.
def get_block_statuses(self, block_ids): """Returns a list of tuples of (block id, BlockStatus) pairs. """ try: return [ (block_id.hex(), self._chain_controller.block_validation_result( block_id.hex())) for block_i...
Returns a list of key/value pairs (str, str).
def settings_get(self, block_id, settings): '''Returns a list of key/value pairs (str, str).''' block = self._get_blocks([block_id.hex()])[0] block_header = BlockHeader() block_header.ParseFromString(block.header) try: settings_view = self._settings_view_factory.cr...
Returns a list of address/data pairs (str, bytes)
def state_get(self, block_id, addresses): '''Returns a list of address/data pairs (str, bytes)''' block = self._get_blocks([block_id.hex()])[0] block_header = BlockHeader() block_header.ParseFromString(block.header) try: state_view = self._state_view_factory.create_v...
Creates the args parser needed for the settings command and its subcommands.
def add_settings_parser(subparsers, parent_parser): """Creates the args parser needed for the settings command and its subcommands. """ # The following parser is for the settings subsection of commands. These # commands display information about the currently applied on-chain # settings. s...
Lists the current on-chain configuration values.
def _do_settings_list(args): """Lists the current on-chain configuration values. """ rest_client = RestClient(args.url) state = rest_client.list_state(subtree=SETTINGS_NAMESPACE) prefix = args.filter head = state['head'] state_values = state['data'] printable_settings = [] proposal...
Creates the state address for a given setting key.
def _key_to_address(key): """Creates the state address for a given setting key. """ key_parts = key.split('.', maxsplit=_MAX_KEY_PARTS - 1) key_parts.extend([''] * (_MAX_KEY_PARTS - len(key_parts))) return SETTINGS_NAMESPACE + ''.join(_short_hash(x) for x in key_parts)
Returns a new batch injector
def _create_injector(self, injector): """Returns a new batch injector""" if injector == "block_info": block_info_injector = importlib.import_module( "sawtooth_validator.journal.block_info_injector") return block_info_injector.BlockInfoInjector( se...
This is exposed for unit tests, and should not be called directly.
def on_block_received(self, block_id): """This is exposed for unit tests, and should not be called directly. """ _libexec('chain_controller_on_block_received', self.pointer, ctypes.c_char_p(block_id.encode('utf-8')))
Creates the arg parsers needed for the compare command.
def add_compare_chains_parser(subparsers, parent_parser): """Creates the arg parsers needed for the compare command. """ parser = subparsers.add_parser( 'compare-chains', help='Compare chains from different nodes.', description=( 'Compute and display information about how...
Calculates and outputs comparison between all nodes on the network.
def do_compare_chains(args): """Calculates and outputs comparison between all nodes on the network.""" urls = split_comma_append_args(args.urls) users = split_comma_append_args(args.users) clients = make_rest_apis(urls, users) broken = [] chains, errors = get_chain_generators(clients, args.lim...
Print out summary and per-node comparison data.
def print_summary(graph, tails, node_id_map): """Print out summary and per-node comparison data.""" # Get comparison data heads = get_heads(tails) heights = get_heights(tails) max_height = max(heights) common_height, block_ids_at_common_height = get_common_height(tails) lags = get_lags(heigh...
Print out a table of nodes and the blocks they have at each block height starting with the common ancestor.
def print_table(graph, tails, node_id_map): """Print out a table of nodes and the blocks they have at each block height starting with the common ancestor.""" node_count = len(tails) # Get the width of the table columns num_col_width = max( floor(log(max(get_heights(tails)), 10)) + 1, ...
Print out a tree of blocks starting from the common ancestor.
def print_tree(graph, tails, node_id_map): """Print out a tree of blocks starting from the common ancestor.""" # Example: # | # | 5 # * a {0, 1, 2, 3, 4} # | # | 6 # |\ # * | b {0, 1, 2, 3} # | * n {4} # | | # | | 7 # * | c {0, 1, 2, 3} # | * o {4} # | | ...
Order the new cliques based on the order of their ancestors in the previous iteration.
def build_ordered_cliques(cliques, next_cliques): """Order the new cliques based on the order of their ancestors in the previous iteration.""" def sort_key(clique): return -len(clique[1]) if not cliques: return list(sorted( list(next_cliques.values())[0].items(), ...
Print a row that removes the given column and shifts all the following columns.
def print_fold(column_to_fold, total_columns, skips): """Print a row that removes the given column and shifts all the following columns.""" format_str = '{:<2}' * (total_columns - 1) cols = [] for i in range(column_to_fold): # print(i) if i in skips: cols.append(" ") ...
Print out a row of padding and a row with the block number. Includes the branches prior to this block number.
def print_block_num_row(block_num, cliques, next_cliques): """Print out a row of padding and a row with the block number. Includes the branches prior to this block number.""" n_cliques = len(cliques) if n_cliques == 0: print('| {}'.format(block_num)) return def mapper(clique): ...
Print a '*' on each branch with its block id and the ids of the nodes that have the block.
def print_cliques(cliques, next_cliques, node_id_map): """Print a '*' on each branch with its block id and the ids of the nodes that have the block.""" n_cliques = len(cliques) format_str = '{:<' + str(n_cliques * 2) + '} {} {}' branches = ['|'] * len(cliques) for i, clique in enumerate(cliques...
Print a row that splits the given column into two columns while shifting all the following columns.
def print_split(column_to_split, total_columns): """Print a row that splits the given column into two columns while shifting all the following columns.""" out = "" for _ in range(column_to_split): out += "| " out += "|\\" for _ in range(column_to_split + 1, total_columns): out +=...
Args: An ordered collection of block generators. Returns A dictionary of lists of blocks for all chains where: 1. The first block in all the lists has the same block number 2. Each list has all blocks from the common block to the current block in increasing or...
def get_tails(chains): """ Args: An ordered collection of block generators. Returns A dictionary of lists of blocks for all chains where: 1. The first block in all the lists has the same block number 2. Each list has all blocks from the common block to the current ...
Return whether all the collections return equal values when called with `key`.
def _compare_across(collections, key): """Return whether all the collections return equal values when called with `key`.""" if len(collections) < 2: return True c0 = key(collections[0]) return all(c0 == key(c) for c in collections[1:])
Args: An ordered collection of block generators which have been consumed to the point where they are all at the same block height and the tails of the chains from that block height (in the same order). Returns: A ForkGraph A list of indexes of the chains that had communicati...
def build_fork_graph(chains, tails): """ Args: An ordered collection of block generators which have been consumed to the point where they are all at the same block height and the tails of the chains from that block height (in the same order). Returns: A ForkGraph A l...
Join the identifier tuple with periods ".", combine the arbitrary tags with the base tags and the identifier tag, convert tags to "tag=value" format, and then join everything with ",".
def _join(self, identifier, instance=None, tags=None): """ Join the identifier tuple with periods ".", combine the arbitrary tags with the base tags and the identifier tag, convert tags to "tag=value" format, and then join everything with ",". """ tag_list = [] if...
Creates the arg parsers needed for the config command and its subcommands.
def add_config_parser(subparsers, parent_parser): """Creates the arg parsers needed for the config command and its subcommands. """ parser = subparsers.add_parser( 'config', help='Changes genesis block settings and create, view, and ' 'vote on settings proposals', descrip...
Executes the 'proposal create' subcommand. Given a key file, and a series of key/value pairs, it generates batches of sawtooth_settings transactions in a BatchList instance. The BatchList is either stored to a file or submitted to a validator, depending on the supplied CLI arguments.
def _do_config_proposal_create(args): """Executes the 'proposal create' subcommand. Given a key file, and a series of key/value pairs, it generates batches of sawtooth_settings transactions in a BatchList instance. The BatchList is either stored to a file or submitted to a validator, depending on the ...
Executes the 'proposal list' subcommand. Given a url, optional filters on prefix and public key, this command lists the current pending proposals for settings changes.
def _do_config_proposal_list(args): """Executes the 'proposal list' subcommand. Given a url, optional filters on prefix and public key, this command lists the current pending proposals for settings changes. """ def _accept(candidate, public_key, prefix): # Check to see if the first public ...
Executes the 'proposal vote' subcommand. Given a key file, a proposal id and a vote value, it generates a batch of sawtooth_settings transactions in a BatchList instance. The BatchList is file or submitted to a validator.
def _do_config_proposal_vote(args): """Executes the 'proposal vote' subcommand. Given a key file, a proposal id and a vote value, it generates a batch of sawtooth_settings transactions in a BatchList instance. The BatchList is file or submitted to a validator. """ signer = _read_signer(args.ke...
Creates an individual sawtooth_settings transaction for the given key and value.
def _create_propose_txn(signer, setting_key_value): """Creates an individual sawtooth_settings transaction for the given key and value. """ setting_key, setting_value = setting_key_value nonce = hex(random.randint(0, 2**64)) proposal = SettingProposal( setting=setting_key, value=...
Creates an individual sawtooth_settings transaction for voting on a proposal for a particular setting key.
def _create_vote_txn(signer, proposal_id, setting_key, vote_value): """Creates an individual sawtooth_settings transaction for voting on a proposal for a particular setting key. """ if vote_value == 'accept': vote_id = SettingVote.ACCEPT else: vote_id = SettingVote.REJECT vote =...
Creates and signs a sawtooth_settings transaction with with a payload.
def _make_txn(signer, setting_key, payload): """Creates and signs a sawtooth_settings transaction with with a payload. """ serialized_payload = payload.SerializeToString() header = TransactionHeader( signer_public_key=signer.get_public_key().as_hex(), family_name='sawtooth_settings', ...
A new message was received from a peer
def notify_peer_message(self, message, sender_id): """A new message was received from a peer""" payload = message.SerializeToString() self._notify( "consensus_notifier_notify_peer_message", payload, len(payload), sender_id, len(sender_i...
A new block was received and passed initial consensus validation
def notify_block_new(self, block): """A new block was received and passed initial consensus validation""" payload = block.SerializeToString() self._notify( "consensus_notifier_notify_block_new", payload, len(payload))
The consensus engine has been activated.
def notify_engine_activated(self, chain_head): """The consensus engine has been activated.""" chain_head_bytes = chain_head.SerializeToString() self._notify( "consensus_notifier_notify_engine_activated", chain_head_bytes, len(chain_head_bytes))
Walk to ADDRESS, creating nodes if necessary, and set the data there to UPDATER(data). Arguments: address (str): the address to be updated
def update(self, address, updater, prune=False): ''' Walk to ADDRESS, creating nodes if necessary, and set the data there to UPDATER(data). Arguments: address (str): the address to be updated ''' node = self._get_or_create(address) node.data = updat...
Remove all children (and descendants) below ADDRESS. Arguments: address (str): the address to be pruned
def prune(self, address): ''' Remove all children (and descendants) below ADDRESS. Arguments: address (str): the address to be pruned ''' try: for step in self._walk_to_address(address): node = step except AddressNotInTree: ...
Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded in an unspecified order. Arguments: ...
def walk(self, address): ''' Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded i...
Returns all predecessor transaction ids for a write of the provided address. Arguments: address (str): the radix address Returns: a set of transaction ids
def find_write_predecessors(self, address): """Returns all predecessor transaction ids for a write of the provided address. Arguments: address (str): the radix address Returns: a set of transaction ids """ # A write operation must be preceded by: # ...
Add a predecessor-successor relationship between one txn id and a set of predecessors. Args: txn_id (str): The transaction id of the transaction. predecessors (set): The transaction ids of the transaction's predecessors Returns: None
def add_relationship(self, txn_id, predecessors): """Add a predecessor-successor relationship between one txn id and a set of predecessors. Args: txn_id (str): The transaction id of the transaction. predecessors (set): The transaction ids of the transacti...
Returns whether the predecessor is a predecessor or a predecessor of a predecessor...of any of the others. Args: predecessor (str): The txn id of the predecessor. others (list(str)): The txn id of the successor. Returns: (bool)
def is_predecessor_of_other(self, predecessor, others): """Returns whether the predecessor is a predecessor or a predecessor of a predecessor...of any of the others. Args: predecessor (str): The txn id of the predecessor. others (list(str)): The txn id of the successor. ...
Use the predecessor tree to find dependencies based on inputs. Returns: A list of transaction ids.
def _find_input_dependencies(self, inputs): """Use the predecessor tree to find dependencies based on inputs. Returns: A list of transaction ids. """ dependencies = [] for address in inputs: dependencies.extend( self._predecessor_tree.find_read_predec...
Use the predecessor tree to find dependencies based on outputs. Returns: A list of transaction ids.
def _find_output_dependencies(self, outputs): """Use the predecessor tree to find dependencies based on outputs. Returns: A list of transaction ids. """ dependencies = [] for address in outputs: dependencies.extend( self._predecessor_tree.find_write_p...
Starting with the batch referenced by batch_signature, iterate back through the batches and for each valid batch collect the context_id. At the end remove contexts for txns that are other txn's predecessors. Args: batch_signature (str): The batch to start from, moving back through ...
def _get_contexts_for_squash(self, batch_signature): """Starting with the batch referenced by batch_signature, iterate back through the batches and for each valid batch collect the context_id. At the end remove contexts for txns that are other txn's predecessors. Args: batch...
Decide if possible_successor should be replayed. Args: txn_id (str): Id of txn in failed batch. possible_successor (str): Id of txn to possibly replay. already_seen (list): A list of possible_successors that have been replayed. Returns: (...
def _is_txn_to_replay(self, txn_id, possible_successor, already_seen): """Decide if possible_successor should be replayed. Args: txn_id (str): Id of txn in failed batch. possible_successor (str): Id of txn to possibly replay. already_seen (list): A list of possible_s...
Remove transactions from scheduled and txn_results for successors of txns in a failed batch. These transactions will now, or in the future be rescheduled in next_transaction; giving a replay ability. Args: sig (str): Transaction header signature
def _remove_subsequent_result_because_of_batch_failure(self, sig): """Remove transactions from scheduled and txn_results for successors of txns in a failed batch. These transactions will now, or in the future be rescheduled in next_transaction; giving a replay ability. Args: ...
Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set.
def _set_least_batch_id(self, txn_signature): """Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set. """ batch = self._batches_by_txn_id[txn_signature] least...
Returns whether the transaction is in a valid batch. Args: txn_id (str): The transaction header signature. Returns: (bool): True if the txn's batch is valid, False otherwise.
def _txn_is_in_valid_batch(self, txn_id): """Returns whether the transaction is in a valid batch. Args: txn_id (str): The transaction header signature. Returns: (bool): True if the txn's batch is valid, False otherwise. """ batch = self._batches_by_txn_...
Executes the key generation operation, given the parsed arguments. Args: args (:obj:`Namespace`): The parsed args.
def do_keygen(args): """Executes the key generation operation, given the parsed arguments. Args: args (:obj:`Namespace`): The parsed args. """ if args.key_name is not None: key_name = args.key_name else: key_name = 'validator' key_dir = get_key_dir() if not os.path...
Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
Sends a message containing our peers to the connection identified by connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket.
def send_peers(self, connection_id): """Sends a message containing our peers to the connection identified by connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. """ with self._lock...
Adds candidate endpoints to the list of endpoints to attempt to peer with. Args: peer_endpoints ([str]): A list of public uri's which the validator can attempt to peer with.
def add_candidate_peer_endpoints(self, peer_endpoints): """Adds candidate endpoints to the list of endpoints to attempt to peer with. Args: peer_endpoints ([str]): A list of public uri's which the validator can attempt to peer with. """ if self._topol...
Returns the list of public keys for all peers.
def get_peers_public_keys(self): """Returns the list of public keys for all peers.""" with self._lock: # Use a generator inside the list comprehension to filter out None # values in a single pass return [key for key in (self._network.connection_id_...
Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new peer
def register_peer(self, connection_id, endpoint): """Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new ...
Removes a connection_id from the registry. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket.
def unregister_peer(self, connection_id): """Removes a connection_id from the registry. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. """ public_key = self.peer_to_public_key(connection_id) ...
Sends a message via the network. Args: message_type (str): The type of the message. message (bytes): The message to be sent. connection_id (str): The connection to send it to.
def send(self, message_type, message, connection_id, one_way=False): """Sends a message via the network. Args: message_type (str): The type of the message. message (bytes): The message to be sent. connection_id (str): The connection to send it to. """ ...
Broadcast gossip messages. Broadcast the message to all peers unless they are in the excluded list. Args: gossip_message: The message to be broadcast. message_type: Type of the message. exclude: A list of connection_ids that should be excluded from this ...
def broadcast(self, gossip_message, message_type, exclude=None): """Broadcast gossip messages. Broadcast the message to all peers unless they are in the excluded list. Args: gossip_message: The message to be broadcast. message_type: Type of the message. ...
Adds candidate endpoints to the list of endpoints to attempt to peer with. Args: peer_endpoints ([str]): A list of public uri's which the validator can attempt to peer with.
def add_candidate_peer_endpoints(self, peer_endpoints): """Adds candidate endpoints to the list of endpoints to attempt to peer with. Args: peer_endpoints ([str]): A list of public uri's which the validator can attempt to peer with. """ with self._loc...
Check to see if the successful connection is meant to be peered with. If not, it should be used to get the peers from the endpoint.
def connect_success(self, connection_id): """ Check to see if the successful connection is meant to be peered with. If not, it should be used to get the peers from the endpoint. """ endpoint = self._network.connection_id_to_endpoint(connection_id) endpoint_info = self._te...
Returns pair of byte pointer and size value for use as return parameters in a LIBRARY call
def prepare_vec_result(pointer_type=ctypes.c_uint8): """Returns pair of byte pointer and size value for use as return parameters in a LIBRARY call """ return ( ctypes.POINTER(pointer_type)(), ctypes.c_size_t(0), ctypes.c_size_t(0), )
Explicitly drop this pointer. The memory will be deallocated via the drop_ffi_call_fn passed to the constructor.
def drop(self): """Explicitly drop this pointer. The memory will be deallocated via the drop_ffi_call_fn passed to the constructor. """ if self._ptr: LIBRARY.call(self._drop_ffi_fn, self._ptr) self._ptr = None
Returns the default PathConfig as calculated based on SAWTOOTH_HOME (if set) and operating system.
def get_default_path_config(): """Returns the default PathConfig as calculated based on SAWTOOTH_HOME (if set) and operating system. """ if 'SAWTOOTH_HOME' in os.environ: home_dir = os.environ['SAWTOOTH_HOME'] return PathConfig( config_dir=os.path.join(home_dir, 'etc'), ...
Returns a PathConfig created by loading a TOML file from the filesystem.
def load_toml_path_config(filename): """Returns a PathConfig created by loading a TOML file from the filesystem. """ if not os.path.exists(filename): LOGGER.info( "Skipping path loading from non-existent config file: %s", filename) return PathConfig() LOGGER....
Given a list of PathConfig objects, merges them into a single PathConfig, giving priority in the order of the configs (first has highest priority).
def merge_path_config(configs, config_dir_override): """ Given a list of PathConfig objects, merges them into a single PathConfig, giving priority in the order of the configs (first has highest priority). """ config_dir = None log_dir = None data_dir = None key_dir = None policy_dir ...
Determines if the system should be put in genesis mode Returns: bool: return whether or not a genesis block is required to be generated. Raises: InvalidGenesisStateError: raises this error if there is invalid combination of the following: genesis...
def requires_genesis(self): """ Determines if the system should be put in genesis mode Returns: bool: return whether or not a genesis block is required to be generated. Raises: InvalidGenesisStateError: raises this error if there is invalid ...
Starts the genesis block creation process. Will call the given `on_done` callback on successful completion. Args: on_done (function): a function called on completion Raises: InvalidGenesisStateError: raises this error if a genesis block is unable to be ...
def start(self, on_done): """ Starts the genesis block creation process. Will call the given `on_done` callback on successful completion. Args: on_done (function): a function called on completion Raises: InvalidGenesisStateError: raises this error if a ...
Returns the block publisher based on the consensus module set by the "sawtooth_settings" transaction family. Args: state_hash (str): The current state root hash for reading settings. Raises: InvalidGenesisStateError: if any errors occur getting the Block...
def _get_block_publisher(self, state_hash): """Returns the block publisher based on the consensus module set by the "sawtooth_settings" transaction family. Args: state_hash (str): The current state root hash for reading settings. Raises: InvalidGenesisStateError...
Returns a blocker wrapper with the basics of the block header in place
def _generate_genesis_block(self): """ Returns a blocker wrapper with the basics of the block header in place """ genesis_header = block_pb2.BlockHeader( block_num=0, previous_block_id=NULL_BLOCK_IDENTIFIER, signer_public_key=self._identity_signer.get_...
The block should be complete and the final signature from the publishing validator (this validator) needs to be added.
def _sign_block(self, block): """ The block should be complete and the final signature from the publishing validator (this validator) needs to be added. """ block_header = block.block_header header_bytes = block_header.SerializeToString() signature = self._identit...
Remove all expired entries from the cache.
def _purge_expired(self): """ Remove all expired entries from the cache. """ time_horizon = time.time() - self._keep_time new_cache = {} for (k, v) in self._cache.items(): if v.timestamp > time_horizon: new_cache[k] = v self._cache = ne...
Determines if there is a log config in the config directory and returns it. If it does not exist, return None. Returns: log_config (dict): The dictionary to pass to logging.config.dictConfig
def _get_config(): """Determines if there is a log config in the config directory and returns it. If it does not exist, return None. Returns: log_config (dict): The dictionary to pass to logging.config.dictConfig """ conf_file = os.path.join(_get_config_dir(), 'log_config.toml') if o...
Adds argument parser for the peer command Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object
def add_peer_parser(subparsers, parent_parser): """Adds argument parser for the peer command Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object """ parser = subparsers.add_parser( 'peer', help='Disp...
Returns a tuple of the current size of the pending batch queue and the current queue limit.
def pending_batch_info(self): """Returns a tuple of the current size of the pending batch queue and the current queue limit. """ c_length = ctypes.c_int(0) c_limit = ctypes.c_int(0) self._call( 'pending_batch_info', ctypes.byref(c_length), ...
The existing chain has been updated, the current head block has changed. :param chain_head: the new head of block_chain, can be None if no block publishing is desired. :param committed_batches: the set of batches that were committed as part of the new chain. :param unco...
def on_chain_updated(self, chain_head, committed_batches=None, uncommitted_batches=None): """ The existing chain has been updated, the current head block has changed. :param chain_head: the new head of block_chain, can be None if ...
:param msg: protobuf validator_pb2.Message
def send_message(self, msg, connection_id=None): """ :param msg: protobuf validator_pb2.Message """ zmq_identity = None if connection_id is not None and self._connections is not None: if connection_id in self._connections: connection_info = self._conne...