INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Runs the block list or block show command printing output to the console
def do_block(args): """Runs the block list or block show command, printing output to the console Args: args: The parsed arguments sent to the command at runtime """ rest_client = RestClient(args.url, args.user) if args.subcommand == 'list': block_generator = rest_client...
Returns the next incoming message.
async def incoming(self): """Returns the next incoming message. """ msg = await self._queue.get() self._queue.task_done() return msg
Wait for a reply to a given correlation id. If a timeout is provided it will raise a asyncio. TimeoutError.
async def await_reply(self, correlation_id, timeout=None): """Wait for a reply to a given correlation id. If a timeout is provided, it will raise a asyncio.TimeoutError. """ try: result = await asyncio.wait_for( self._futures[correlation_id], timeout=timeout)...
Fail all the expected replies with a given error.
def fail_all(self, err): """Fail all the expected replies with a given error. """ for c_id in self._futures: self._fail_reply(c_id, err)
Given a message route it either to the incoming queue or to the future associated with its correlation_id.
async def route_msg(self, msg): """Given a message, route it either to the incoming queue, or to the future associated with its correlation_id. """ if msg.correlation_id in self._futures: self._set_reply(msg.correlation_id, msg) else: await self._push_inco...
Starts receiving messages on the underlying socket and passes them to the message router.
async def start(self): """Starts receiving messages on the underlying socket and passes them to the message router. """ self._is_running = True while self._is_running: try: zmq_msg = await self._socket.recv_multipart() message = Messa...
Opens the connection.
def open(self): """Opens the connection. An open connection will monitor for disconnects from the remote end. Messages are either received as replies to outgoing messages, or received from an incoming queue. """ LOGGER.info('Connecting to %s', self._url) asyncio....
Register a callback for a specific connection state change.
def on_connection_state_change(self, event_type, callback): """Register a callback for a specific connection state change. Register a callback to be triggered when the connection changes to the specified state, signified by a ConnectionEvent. The callback must be a coroutine. ...
Sends a message and returns a future for the response.
async def send(self, message_type, message_content, timeout=None): """Sends a message and returns a future for the response. """ return await self._sender.send( message_type, message_content, timeout=timeout)
Closes the connection.
def close(self): """Closes the connection. All outstanding futures for replies will be sent a DisconnectError. """ if self._recv_task: self._recv_task.cancel() self._disable_monitoring() if self._monitor_task and not self._monitor_task.done(): s...
Removes a key: value from the database
def delete(self, key): """Removes a key:value from the database Args: key (str): The key to remove. """ with self._lmdb.begin(write=True, buffers=True) as txn: txn.delete(key.encode())
Returns a list of keys in the database
def keys(self, index=None): """Returns a list of keys in the database """ with self._lmdb.begin() as txn: return [key.decode() for key, _ in txn.cursor()]
Assembles the candidate block into it s finalized form for broadcast.
def build_block(self): """ Assembles the candidate block into it's finalized form for broadcast. """ header_bytes = self.block_header.SerializeToString() block = Block(header=header_bytes, header_signature=self._header_signature) block.batches.extend...
Set the status of an executed transaction.
def set_transaction_execution_result( self, txn_signature, is_valid, context_id, state_changes, events, data, error_message, error_data): """Set the status of an executed transaction. Called by the executor after a transaction has been processed. The scheduler must know...
Add block in a chain in the correct order. Also add all of the blocks to the cache before doing a purge.
def add_chain(self, chain): """ Add block in a chain in the correct order. Also add all of the blocks to the cache before doing a purge. """ with self._lock: chain.sort(key=lambda x: x.block_num) for block in chain: block_id = block.header_...
Remove all expired entries from the cache that do not have a reference count.
def _purge_expired(self): """ Remove all expired entries from the cache that do not have a reference count. """ time_horizon = time.time() - self._keep_time new_cache = {} dec_count_for = [] for (k, v) in self._cache.items(): if v.count > 0: ...
Checks if a status enum matches the trigger originally set and if so raises the appropriate error.
def check(cls, status): """Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. ...
Returns a copy of the block without the non - injected batches which other validators are likely to already have. This reduces the size of the broadcasted block.
def _remove_batches(self, block, keep_batches): """Returns a copy of the block without the non-injected batches, which other validators are likely to already have. This reduces the size of the broadcasted block. """ clone = Block() clone.header = block.header clon...
Do initialization necessary for the consensus to claim a block this may include initiating voting activates starting proof of work hash generation or create a PoET wait timer.
def initialize_block(self, block_header): """Do initialization necessary for the consensus to claim a block, this may include initiating voting activates, starting proof of work hash generation, or create a PoET wait timer. Args: block_header (BlockHeader): the BlockHeader t...
Check if a candidate block is ready to be claimed.
def check_publish_block(self, block_header): """Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed. """ ...
The longest chain is selected. If they are equal then the hash value of the previous block id and publisher signature is computed. The lowest result value is the winning block. Args: cur_fork_head: The current head of the block chain. new_fork_head: The head of the fork that is being evaluated. Returns: bool: True if c...
def compare_forks(self, cur_fork_head, new_fork_head): """The longest chain is selected. If they are equal, then the hash value of the previous block id and publisher signature is computed. The lowest result value is the winning block. Args: cur_fork_head: The current head of...
Check the batch signing key against the allowed transactor permissions. The roles being checked are the following from first to last: transactor. batch_signer transactor default
def is_batch_signer_authorized(self, batch, state_root=None, from_state=False): """ Check the batch signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "transactor.batch_...
Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following from first to last: transactor. transaction_signer. <TP_Name > transactor. transaction_signer transactor default
def is_transaction_signer_authorized(self, transactions, state_root, from_state): """ Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "tra...
Check the batch signing key against the allowed off - chain transactor permissions. The roles being checked are the following from first to last: transactor. batch_signer transactor
def check_off_chain_batch_roles(self, batch): """ Check the batch signing key against the allowed off-chain transactor permissions. The roles being checked are the following, from first to last: "transactor.batch_signer" "transactor" The first...
Check the transaction signing key against the allowed off - chain transactor permissions. The roles being checked are the following from first to last: transactor. transaction_signer. <TP_Name > transactor. transaction_signer transactor
def check_off_chain_transaction_roles(self, transactions): """ Check the transaction signing key against the allowed off-chain transactor permissions. The roles being checked are the following, from first to last: "transactor.transaction_signer.<TP_Name>" ...
Check the public key of a node on the network to see if they are permitted to participate. The roles being checked are the following from first to last: network default
def check_network_role(self, public_key): """ Check the public key of a node on the network to see if they are permitted to participate. The roles being checked are the following, from first to last: "network" "default" The first role that is ...
Used to retrieve an identity role. Args: item ( string ): the name of the role to be fetched state_root ( string ): The state root of the previous block. from_state ( bool ): Whether the identity value should be read directly from state instead of using the cached values. This should be used when the state_root passed ...
def get_role(self, item, state_root, from_state=False): """ Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value shoul...
Takes a statuses dict and formats it for transmission with Protobuf and ZMQ.
def _format_batch_statuses(statuses, batch_ids, tracker): """Takes a statuses dict and formats it for transmission with Protobuf and ZMQ. Args: statuses (dict of int): Dict with batch ids as the key, status as value batch_ids (list of str): The batch ids in their original order trac...
Handles parsing incoming requests and wrapping the final response.
def handle(self, connection_id, message_content): """Handles parsing incoming requests, and wrapping the final response. Args: connection_id (str): ZMQ identity sent over ZMQ socket message_content (bytes): Byte encoded request protobuf to be parsed Returns: ...
Wraps child s response in a HandlerResult to be sent back to client.
def _wrap_result(self, response): """Wraps child's response in a HandlerResult to be sent back to client. Args: response (enum or dict): Either an integer status enum, or a dict of attributes to be added to the protobuf response. """ if isinstance(response, i...
Convenience method to wrap a status with any key word args.
def _wrap_response(self, status=None, **kwargs): """Convenience method to wrap a status with any key word args. Args: status (enum): enum response status, defaults to OK Returns: dict: inlcudes a 'status' attribute and any key word arguments """ kwargs['...
Fetches the request specified head block or the chain head.
def _get_head_block(self, request): """Fetches the request specified head block, or the chain head. Note: This method will fail if `_block_store` has not been set Args: request (object): The parsed protobuf request object Returns: Block: the block o...
Sets the root of the merkle tree returning any head id used.
def _set_root(self, request): """Sets the root of the merkle tree, returning any head id used. Note: This method will fail if `_tree` has not been set Args: request (object): The parsed protobuf request object Returns: str: the state root of the hea...
Builds a list of blocks or resources derived from blocks handling multiple possible filter requests: - filtered by a set of ids - filtered by head block - filtered by both id and head block - not filtered ( all current resources )
def _list_store_resources(self, request, head_id, filter_ids, resource_fetcher, block_xform): """Builds a list of blocks or resources derived from blocks, handling multiple possible filter requests: - filtered by a set of ids - filtered by head block...
Validates a list of ids raising a ResponseFailed error if invalid.
def _validate_ids(self, resource_ids): """Validates a list of ids, raising a ResponseFailed error if invalid. Args: resource_id (list of str): The ids to validate Raises: ResponseFailed: The id was invalid, and a status of INVALID_ID will be sent with th...
Validates a state root raising a ResponseFailed error if invalid.
def _validate_state_root(self, state_root): """Validates a state root, raising a ResponseFailed error if invalid. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be ...
Validates a namespace raising a ResponseFailed error if invalid.
def _validate_namespace(self, namespace): """Validates a namespace, raising a ResponseFailed error if invalid. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be sen...
Truncates a list of resources based on ClientPagingControls
def paginate_resources(cls, request, resources, on_fail_status): """Truncates a list of resources based on ClientPagingControls Args: request (object): The parsed protobuf request object resources (list of objects): The resources to be paginated Returns: lis...
Helper method to fetch the index of a resource by its id or address
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 shifts for new forks.
def print_splits(cliques, next_cliques): """Print shifts for new forks.""" splits = 0 for i, clique in enumerate(cliques): parent, _ = clique # If this fork continues if parent in next_cliques: # If there is a new fork, print a split if len(next_cliques[paren...
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.
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 ).
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.
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 ).
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...