INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Handles requests for new subscription websockets. Args: request (aiohttp.Request): the incoming request Returns: aiohttp.web.WebSocketResponse: the websocket response, when the resulting websocket is closed
async def subscriptions(self, request): """ Handles requests for new subscription websockets. Args: request (aiohttp.Request): the incoming request Returns: aiohttp.web.WebSocketResponse: the websocket response, when the resulting websocket is cl...
:param request (bytes):the serialized request :param result (FutureResult):
def _future_done_callback(self, request, result): """ :param request (bytes):the serialized request :param result (FutureResult): """ self._in_process_transactions_count.dec() req = processor_pb2.TpProcessRequest() req.ParseFromString(request) response = p...
Adds arguments parsers for the batch list, batch show and batch status commands Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object
def add_batch_parser(subparsers, parent_parser): """Adds arguments parsers for the batch list, batch show and batch status commands Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object """ parser = subparsers.add...
Runs the batch list, batch show or batch status command, printing output to the console Args: args: The parsed arguments sent to the command at runtime
def do_batch(args): """Runs the batch list, batch show or batch status command, printing output to the console Args: args: The parsed arguments sent to the command at runtime """ if args.subcommand == 'list': do_batch_list(args) if args.subcommand == 'show': do_...
Runs the batch-status command, printing output to the console Args: args: The parsed arguments sent to the command at runtime
def do_batch_status(args): """Runs the batch-status command, printing output to the console Args: args: The parsed arguments sent to the command at runtime """ rest_client = RestClient(args.url, args.user) batch_ids = args.batch_ids.split(',') if args.wait and args.wait > 0: ...
Check the block to see if it is complete and if it can be passed to the journal. If the block's predecessor is not in the block_manager the predecessor is requested and the current block is added to the the incomplete_block cache. If the block.batches and block.header.bat...
def _complete_block(self, block): """ Check the block to see if it is complete and if it can be passed to the journal. If the block's predecessor is not in the block_manager the predecessor is requested and the current block is added to the the incomplete_block cache. If the ...
Runs the batch list or batch show command, printing output to the console Args: args: The parsed arguments sent to the command at runtime
def do_state(args): """Runs the batch list or batch 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': response = rest_client.list_s...
Computes the merkle root of the state changes in the context corresponding with _last_valid_batch_c_id as applied to _previous_state_hash. Args: required_state_root (str): The merkle root that these txns should equal. Returns: state_hash (str): T...
def _compute_merkle_root(self, required_state_root): """Computes the merkle root of the state changes in the context corresponding with _last_valid_batch_c_id as applied to _previous_state_hash. Args: required_state_root (str): The merkle root that these txns ...
Deserialize a byte string into a BlockWrapper Args: value (bytes): the byte string to deserialze Returns: BlockWrapper: a block wrapper instance
def deserialize_block(value): """ Deserialize a byte string into a BlockWrapper Args: value (bytes): the byte string to deserialze Returns: BlockWrapper: a block wrapper instance """ # Block id strings are stored under batch/txn ids for reference...
Return the head block of the current chain.
def chain_head(self): """ Return the head block of the current chain. """ (vec_ptr, vec_len, vec_cap) = ffi.prepare_vec_result() try: _libexec( 'commit_store_get_chain_head', self.pointer, ctypes.byref(vec_ptr), ...
Returns an iterator that traverses blocks in block number order. Args: start_block (:obj:`BlockWrapper`): the block from which traversal begins start_block_num (str): a starting block number, in hex, from where traversal begins; only used if no starting_b...
def get_block_iter(self, start_block=None, start_block_num=None, reverse=True): """Returns an iterator that traverses blocks in block number order. Args: start_block (:obj:`BlockWrapper`): the block from which traversal begins start_block_n...
Returns all blocks with the given set of block_ids. If a block id in the provided iterable does not exist in the block store, it is ignored. Args: block_ids (:iterable:str): an iterable of block ids Returns list of block wrappers found for the given block ids
def get_blocks(self, block_ids): """Returns all blocks with the given set of block_ids. If a block id in the provided iterable does not exist in the block store, it is ignored. Args: block_ids (:iterable:str): an iterable of block ids Returns list of blo...
Check to see if the requested transaction_id is in the current chain. If so, find the batch that has the transaction referenced by the transaction_id and return the batch. This is done by finding the block and searching for the batch. :param transaction_id (string): The id of the transa...
def get_batch_by_transaction(self, transaction_id): """ Check to see if the requested transaction_id is in the current chain. If so, find the batch that has the transaction referenced by the transaction_id and return the batch. This is done by finding the block and searching for ...
Check to see if the requested batch_id is in the current chain. If so, find the batch with the batch_id and return it. This is done by finding the block and searching for the batch. :param batch_id (string): The id of the batch requested. :return: The batch with the batch_id.
def get_batch(self, batch_id): """ Check to see if the requested batch_id is in the current chain. If so, find the batch with the batch_id and return it. This is done by finding the block and searching for the batch. :param batch_id (string): The id of the batch requested. ...
Returns a Transaction object from the block store by its id. Params: transaction_id (str): The header_signature of the desired txn Returns: Transaction: The specified transaction Raises: ValueError: The transaction is not in the block store
def get_transaction(self, transaction_id): """Returns a Transaction object from the block store by its id. Params: transaction_id (str): The header_signature of the desired txn Returns: Transaction: The specified transaction Raises: ValueError: The ...
Uses headers and a row of example data to generate a format string for printing a single row of data. Args: headers (tuple of strings): The headers for each column of data example_row (tuple): A representative tuple of strings or ints Returns string: A format string with a size for...
def format_terminal_row(headers, example_row): """Uses headers and a row of example data to generate a format string for printing a single row of data. Args: headers (tuple of strings): The headers for each column of data example_row (tuple): A representative tuple of strings or ints R...
Uses a set of headers, raw data, and a row parsing function, to print data to the terminal in a table of rows and columns. Args: headers (tuple of strings): The headers for each column of data data_list (list of dicts): Raw response data from the validator parse_row_fn (function): Parse...
def print_terminal_table(headers, data_list, parse_row_fn): """Uses a set of headers, raw data, and a row parsing function, to print data to the terminal in a table of rows and columns. Args: headers (tuple of strings): The headers for each column of data data_list (list of dicts): Raw resp...
Takes headers, data, and a row parsing function, and prints data to the console in a csv format.
def print_csv(headers, data_list, parse_row_fn): """Takes headers, data, and a row parsing function, and prints data to the console in a csv format. """ try: writer = csv.writer(sys.stdout) writer.writerow(headers) for data in data_list: writer.writerow(parse_row_fn(d...
Append item to the list at key. Creates the list at key if it doesn't exist.
def append(self, key, item): """Append item to the list at key. Creates the list at key if it doesn't exist. """ with self._lock: if key in self._dict: self._dict[key].append(item) else: self._dict[key] = [item]
Set key to a copy of items
def set(self, key, items): """Set key to a copy of items""" if not isinstance(items, list): raise ValueError("items must be a list") with self._lock: self._dict[key] = items.copy()
Set key to a copy of items and return the list that was previously stored if the key was set. If not key was set, returns an empty list.
def swap(self, key, items): """Set key to a copy of items and return the list that was previously stored if the key was set. If not key was set, returns an empty list. """ if not isinstance(items, list): raise ValueError("items must be a list") return_value = [] ...
If the key is set, remove and return the list stored at key. Otherwise return default.
def pop(self, key, default): """If the key is set, remove and return the list stored at key. Otherwise return default.""" with self._lock: return self._dict.pop(key, default)
If the key is set, return a copy of the list stored at key. Otherwise return default.
def get(self, key, default): """If the key is set, return a copy of the list stored at key. Otherwise return default.""" with self._lock: try: return self._dict[key].copy() except KeyError: return default
Removes batches from the pending cache if found in the block store, and notifies any observers.
def chain_update(self, block, receipts): """Removes batches from the pending cache if found in the block store, and notifies any observers. """ with self._lock: for batch_id in self._pending.copy(): if self._batch_committed(batch_id): self....
Adds a batch id to the invalid cache along with the id of the transaction that was rejected and any error message or extended data. Removes that batch id from the pending set. The cache is only temporary, and the batch info will be purged after one hour. Args: txn_id (str): ...
def notify_txn_invalid(self, txn_id, message=None, extended_data=None): """Adds a batch id to the invalid cache along with the id of the transaction that was rejected and any error message or extended data. Removes that batch id from the pending set. The cache is only temporary, and the ...
Adds a Batch id to the pending cache, with its transaction ids. Args: batch (str): The id of the pending batch
def notify_batch_pending(self, batch): """Adds a Batch id to the pending cache, with its transaction ids. Args: batch (str): The id of the pending batch """ txn_ids = {t.header_signature for t in batch.transactions} with self._lock: self._pending.add(batc...
Returns the status enum for a batch. Args: batch_id (str): The id of the batch to get the status for Returns: int: The status enum
def get_status(self, batch_id): """Returns the status enum for a batch. Args: batch_id (str): The id of the batch to get the status for Returns: int: The status enum """ with self._lock: if self._batch_committed(batch_id): ret...
Returns a statuses dict for the requested batches. Args: batch_ids (list of str): The ids of the batches to get statuses for Returns: dict: A dict with keys of batch ids, and values of status enums
def get_statuses(self, batch_ids): """Returns a statuses dict for the requested batches. Args: batch_ids (list of str): The ids of the batches to get statuses for Returns: dict: A dict with keys of batch ids, and values of status enums """ with self._loc...
Fetches the id of the Transaction that failed within a particular Batch, as well as any error message or other data about the failure. Args: batch_id (str): The id of the Batch containing an invalid txn Returns: list of dict: A list of dicts with three possible keys: ...
def get_invalid_txn_info(self, batch_id): """Fetches the id of the Transaction that failed within a particular Batch, as well as any error message or other data about the failure. Args: batch_id (str): The id of the Batch containing an invalid txn Returns: list ...
Allows a component to register to be notified when a set of batches is no longer PENDING. Expects to be able to call the "notify_batches_finished" method on the registered component, sending the statuses of the batches. Args: observer (object): Must implement "notify_batches...
def watch_statuses(self, observer, batch_ids): """Allows a component to register to be notified when a set of batches is no longer PENDING. Expects to be able to call the "notify_batches_finished" method on the registered component, sending the statuses of the batches. Args: ...
Updates each observer tracking a particular batch with its new status. If all statuses are no longer pending, notifies the observer and removes it from the list.
def _update_observers(self, batch_id, status): """Updates each observer tracking a particular batch with its new status. If all statuses are no longer pending, notifies the observer and removes it from the list. """ for observer, statuses in self._observers.copy().items(): ...
Returns True if a statuses dict has no PENDING statuses.
def _has_no_pendings(self, statuses): """Returns True if a statuses dict has no PENDING statuses. """ return all(s != ClientBatchStatus.PENDING for s in statuses.values())
Returns the value in this context, or None, for each address in addresses. Useful for gets on the context manager. Args: addresses (list of str): The addresses to return values for, if within this context. Returns: results (list of bytes): The values in ...
def get(self, addresses): """Returns the value in this context, or None, for each address in addresses. Useful for gets on the context manager. Args: addresses (list of str): The addresses to return values for, if within this context. Returns: re...
Returns the value set in this context, or None, for each address in addresses. Args: addresses (list of str): The addresses to return values for, if set within this context. Returns: (list): bytes set at the address or None
def get_if_set(self, addresses): """Returns the value set in this context, or None, for each address in addresses. Args: addresses (list of str): The addresses to return values for, if set within this context. Returns: (list): bytes set at the ad...
Returns a list of addresses that have been deleted, or None if it hasn't been deleted. Args: addresses (list of str): The addresses to check if deleted. Returns: (list of str): The addresses, if deleted, or None.
def get_if_deleted(self, addresses): """Returns a list of addresses that have been deleted, or None if it hasn't been deleted. Args: addresses (list of str): The addresses to check if deleted. Returns: (list of str): The addresses, if deleted, or None. "...
Returns the value at an address if it was an input to the txn but never set. It returns None if that address was never set in the merkle database, or if the address is not within the context. Args: addresses (list of str): The full 70 character addresses. Returns: ...
def get_if_not_set(self, addresses): """Returns the value at an address if it was an input to the txn but never set. It returns None if that address was never set in the merkle database, or if the address is not within the context. Args: addresses (list of str): The full 70 ...
Return all the addresses and opaque values set in the context. Useful in the squash method. Returns: (dict of str to bytes): The addresses and bytes that have been set in the context.
def get_all_if_set(self): """Return all the addresses and opaque values set in the context. Useful in the squash method. Returns: (dict of str to bytes): The addresses and bytes that have been set in the context. """ with self._lock: resu...
Return all the addresses deleted in the context. Useful in the squash method. Returns: (dict of str to bytes): The addresses and bytes that have been deleted in the context.
def get_all_if_deleted(self): """Return all the addresses deleted in the context. Useful in the squash method. Returns: (dict of str to bytes): The addresses and bytes that have been deleted in the context. """ with self._lock: results = ...
Create futures needed before starting the process of reading the address's value from the merkle tree. Args: addresses (list of str): addresses in the txn's inputs that aren't in any base context (or any in the chain).
def create_prefetch(self, addresses): """Create futures needed before starting the process of reading the address's value from the merkle tree. Args: addresses (list of str): addresses in the txn's inputs that aren't in any base context (or any in the chain). ...
Create futures from inputs with the current value for that address at the start of that context. Args: address_values (list of tuple): The tuple is string, bytes of the address and value.
def create_initial(self, address_values): """Create futures from inputs with the current value for that address at the start of that context. Args: address_values (list of tuple): The tuple is string, bytes of the address and value. """ with self._lo...
Set the result for each future at the given addresses with the value stored in the merkle database. Args: address_value_dict (dict of str: bytes): The unique full addresses that the bytes values should be set with.
def set_from_tree(self, address_value_dict): """Set the result for each future at the given addresses with the value stored in the merkle database. Args: address_value_dict (dict of str: bytes): The unique full addresses that the bytes values should be set with. ...
Called in the context manager's delete method to either mark an entry for deletion , or create a new future and immediately set it for deletion in the future. Args: address_list (list of str): The unique full addresses. Raises: AuthorizationException
def delete_direct(self, addresses): """Called in the context manager's delete method to either mark an entry for deletion , or create a new future and immediately set it for deletion in the future. Args: address_list (list of str): The unique full addresses. Raises:...
Called in the context manager's set method to either overwrite the value for an address, or create a new future and immediately set a value in the future. Args: address_value_dict (dict of str:bytes): The unique full addresses with bytes to set at that address. ...
def set_direct(self, address_value_dict): """Called in the context manager's set method to either overwrite the value for an address, or create a new future and immediately set a value in the future. Args: address_value_dict (dict of str:bytes): The unique full addresses ...
Raises an exception if the address is not allowed to be set in this context, based on txn outputs. Notes: Checks that the address is either listed fully as one of the outputs, or some portion of the address is listed as a namespace in the outputs of the txn. ...
def _validate_write(self, address): """Raises an exception if the address is not allowed to be set in this context, based on txn outputs. Notes: Checks that the address is either listed fully as one of the outputs, or some portion of the address is listed as a namespace ...
Raises an exception if the address is not allowed to be read in this context, based on txn inputs. Args: address (str): An address to be validated. Returns: None Raises: AuthorizationException
def validate_read(self, address): """Raises an exception if the address is not allowed to be read in this context, based on txn inputs. Args: address (str): An address to be validated. Returns: None Raises: AuthorizationException """...
Return the value at an address, optionally waiting until it is set from the context_manager, or set based on the pre-fetch mechanism. Returns: (bytes): The opaque value for an address.
def result(self): """Return the value at an address, optionally waiting until it is set from the context_manager, or set based on the pre-fetch mechanism. Returns: (bytes): The opaque value for an address. """ if self._read_only: return self._result ...
Set the addresses's value unless the future has been declared read only. Args: result (bytes): The value at an address. from_tree (bool): Whether the value is being set by a read from the merkle tree. Returns: None
def set_result(self, result, from_tree=False): """Set the addresses's value unless the future has been declared read only. Args: result (bytes): The value at an address. from_tree (bool): Whether the value is being set by a read from the merkle tree. ...
Verify the state root hash of all blocks is in state and if not, reconstruct the missing state. Assumes that there are no "holes" in state, ie starting from genesis, state is present for all blocks up to some point and then not at all. If persist is False, this recomputes state in memory for all blocks ...
def verify_state(global_state_db, blockstore, bind_component, scheduler_type): """ Verify the state root hash of all blocks is in state and if not, reconstruct the missing state. Assumes that there are no "holes" in state, ie starting from genesis, state is present for all blocks up to some point an...
Search through the blockstore and return a tuple containing: - the first block with a missing state root - the state root of that blocks predecessor
def search_for_present_state_root(blockstore, state_view_factory): """ Search through the blockstore and return a tuple containing: - the first block with a missing state root - the state root of that blocks predecessor """ # If there is no chain to process, then we are done. block =...
An endpoint host name is valid if it is a URL and if the host is not the name of a network interface.
def is_valid_endpoint_host(interfaces, endpoint): """ An endpoint host name is valid if it is a URL and if the host is not the name of a network interface. """ result = urlparse(endpoint) hostname = result.hostname if hostname is None: return False ...
A connection must use one of the supported authorization types to prove their identity. If a requester deviates from the procedure in any way, the requester will be rejected and the connection will be closed. The same is true if the requester sends multiple ConnectionRequests or multiple...
def handle(self, connection_id, message_content): """ A connection must use one of the supported authorization types to prove their identity. If a requester deviates from the procedure in any way, the requester will be rejected and the connection will be closed. The same is true ...
The simplest authorization type will be Trust. If Trust authorization is enabled, the validator will trust the connection and approve any roles requested that are available on that endpoint. If the requester wishes to gain access to every role it has permission to access, it can request ...
def handle(self, connection_id, message_content): """ The simplest authorization type will be Trust. If Trust authorization is enabled, the validator will trust the connection and approve any roles requested that are available on that endpoint. If the requester wishes to gain acc...
If the connection wants to take on a role that requires a challenge to be signed, it will request the challenge by sending an AuthorizationChallengeRequest to the validator it wishes to connect to. The validator will send back a random payload that must be signed. If the connection has n...
def handle(self, connection_id, message_content): """ If the connection wants to take on a role that requires a challenge to be signed, it will request the challenge by sending an AuthorizationChallengeRequest to the validator it wishes to connect to. The validator will send back...
When the validator receives an AuthorizationChallengeSubmit message, it will verify the public key against the signature. If the public key is verified, the requested roles will be checked against the stored roles to see if the public key is included in the policy. If the node’s response...
def handle(self, connection_id, message_content): """ When the validator receives an AuthorizationChallengeSubmit message, it will verify the public key against the signature. If the public key is verified, the requested roles will be checked against the stored roles to see if th...
If an AuthorizationViolation is recieved, the connection has decided that this validator is no longer permitted to be connected. Remove the connection preemptively.
def handle(self, connection_id, message_content): """ If an AuthorizationViolation is recieved, the connection has decided that this validator is no longer permitted to be connected. Remove the connection preemptively. """ LOGGER.warning("Received AuthorizationViolation f...
Runs the transaction list or show command, printing to the console Args: args: The parsed arguments sent to the command at runtime
def do_transaction(args): """Runs the transaction list or show command, printing 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': transactions = rest_client.list_tr...
Modifies ARGS in-place to have the attributes defined in the CLI config file if it doesn't already have them. Certain default values are given if they are not in ARGS or the config file.
def load_cli_config(args): """Modifies ARGS in-place to have the attributes defined in the CLI config file if it doesn't already have them. Certain default values are given if they are not in ARGS or the config file. """ default_cli_config = _load_default_cli_config() toml_config = _load_toml_cl...
Returns the TransactionReceipt Args: txn_id (str): the id of the transaction for which the receipt should be retrieved. Returns: TransactionReceipt: The receipt for the given transaction id. Raises: KeyError: if the transaction id is unknown...
def get(self, txn_id): """Returns the TransactionReceipt Args: txn_id (str): the id of the transaction for which the receipt should be retrieved. Returns: TransactionReceipt: The receipt for the given transaction id. Raises: KeyError...
Sends a list of batches to the validator. Args: batch_list (:obj:`BatchList`): the list of batches Returns: dict: the json result data, as a dict
def send_batches(self, batch_list): """Sends a list of batches to the validator. Args: batch_list (:obj:`BatchList`): the list of batches Returns: dict: the json result data, as a dict """ if isinstance(batch_list, BaseMessage): batch_list = ...
Submits the given request, and handles the errors appropriately. Args: url (str): the request to send. params (dict): params to be passed along to get/post data (bytes): the data to include in the request. headers (dict): the headers to include in the request. ...
def _submit_request(self, url, params=None, data=None, headers=None, method="GET"): """Submits the given request, and handles the errors appropriately. Args: url (str): the request to send. params (dict): params to be passed along to get/post ...
Creates the arg parsers needed for the compare command.
def add_list_blocks_parser(subparsers, parent_parser): """Creates the arg parsers needed for the compare command. """ parser = subparsers.add_parser( 'list-blocks', help='List blocks from different nodes.', formatter_class=argparse.RawDescriptionHelpFormatter, epilog='', ...
Handles both "sawtooth/block-commit" Events and "identity/update" Events. For "sawtooth/block-commit", the last_block_num is updated or a fork is detected. For "identity/update", the corresponding cache entry will be updated.
def chain_update(self, block, receipts): """ Handles both "sawtooth/block-commit" Events and "identity/update" Events. For "sawtooth/block-commit", the last_block_num is updated or a fork is detected. For "identity/update", the corresponding cache entry will be updated. "...
Returns a RestApiConfig created by loading a TOML file from the filesystem.
def load_toml_rest_api_config(filename): """Returns a RestApiConfig created by loading a TOML file from the filesystem. """ if not os.path.exists(filename): LOGGER.info( "Skipping rest api loading from non-existent config file: %s", filename) return RestApiConfig(...
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_rest_api_config(configs): """ Given a list of PathConfig objects, merges them into a single PathConfig, giving priority in the order of the configs (first has highest priority). """ bind = None connect = None timeout = None opentsdb_url = None opentsdb_db = None opentsd...
Adds arguments parsers for the block list and block show commands Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object
def add_block_parser(subparsers, parent_parser): """Adds arguments parsers for the block list and block show commands Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object """ parser = subparsers.add_parser( '...
Runs the block list or block show command, printing output to the console Args: args: The parsed arguments sent to the command at runtime
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. 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.
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. Register a callback to be triggered when the connection changes to the specified state, signified by a ConnectionEvent. The callback must be a coroutine. Args: event_type (ConnectionEvent): the connection event to...
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. All outstanding futures for replies will be sent a DisconnectError.
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 Args: key (str): The key to remove.
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. Called by the executor after a transaction has been processed. The scheduler must know when transactions have finished being applied so that it can determine which transactions will become eligible for processing. Args: tx...
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. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. _ApiError: If the statuses don'...
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. Args: block_header (BlockHeader): the BlockHeader to initialize. Returns: True
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. 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.
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 ...
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" The first role that is set will be the one used to ...
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" "def...
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" The first role that is set will be the one used to enforce if the ...
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...
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 v...
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...
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 set will be the one used to enforce if the ...
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 ...
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.
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. Args: status (enum): enum response status, defaults to OK Returns: dict: inlcudes a 'status' attribute and any key word arguments
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. Note: This method will fail if `_block_store` has not been set Args: request (object): The parsed protobuf request object Returns: Block: the block object at the head of the requested chain ...
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. 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 head block used to specify the root ...
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) Note: This me...
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. 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 the response.
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. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be sent with the response.
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. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be sent with the response.
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 Args: request (object): The parsed protobuf request object resources (list of objects): The resources to be paginated Returns: list: The paginated list of resources object: The ClientPagingRespo...
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...