INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Uses an executor to send an asynchronous ZMQ request to the validator with the handler s Connection | async def _send_request(self, request_type, payload):
"""Uses an executor to send an asynchronous ZMQ request to the
validator with the handler's Connection
"""
try:
return await self._connection.send(
message_type=request_type,
message_content... |
Parses the content from a validator response Message. | def _parse_response(proto, response):
"""Parses the content from a validator response Message.
"""
try:
content = proto()
content.ParseFromString(response.content)
return content
except (DecodeError, AttributeError):
LOGGER.error('Validator... |
Raises HTTPErrors based on error statuses sent from validator. Checks for common statuses and runs route specific error traps. | def _check_status_errors(proto, content, error_traps=None):
"""Raises HTTPErrors based on error statuses sent from validator.
Checks for common statuses and runs route specific error traps.
"""
if content.status == proto.OK:
return
try:
if content.status ... |
Creates the JSON response envelope to be sent back to the client. | def _wrap_response(request, data=None, metadata=None, status=200):
"""Creates the JSON response envelope to be sent back to the client.
"""
envelope = metadata or {}
if data is not None:
envelope['data'] = data
return web.Response(
status=status,
... |
Builds the metadata for a pagingated response and wraps everying in a JSON encoded web. Response | def _wrap_paginated_response(cls, request, response, controls, data,
head=None):
"""Builds the metadata for a pagingated response and wraps everying in
a JSON encoded web.Response
"""
paging_response = response['paging']
if head is None:
... |
Parses out the head and link properties based on the HTTP Request from the client and the Protobuf response from the validator. | def _get_metadata(cls, request, response, head=None):
"""Parses out the head and link properties based on the HTTP Request
from the client, and the Protobuf response from the validator.
"""
head = response.get('head_id', head)
metadata = {'link': cls._build_url(request, head=head... |
Builds a response URL by overriding the original queries with specified change queries. Change queries set to None will not be used. Setting a change query to False will remove it even if there is an original query with a value. | def _build_url(cls, request, path=None, **changes):
"""Builds a response URL by overriding the original queries with
specified change queries. Change queries set to None will not be used.
Setting a change query to False will remove it even if there is an
original query with a value.
... |
Gets a forwarded value from the Forwarded header if present or the equivalent X - Forwarded - header if not. If neither is present returns an empty string. | def _get_forwarded(request, key):
"""Gets a forwarded value from the `Forwarded` header if present, or
the equivalent `X-Forwarded-` header if not. If neither is present,
returns an empty string.
"""
forwarded = request.headers.get('Forwarded', '')
match = re.search(
... |
Deserializes a Block s header and the header of its Batches. | def _expand_block(cls, block):
"""Deserializes a Block's header, and the header of its Batches.
"""
cls._parse_header(BlockHeader, block)
if 'batches' in block:
block['batches'] = [cls._expand_batch(b) for b in block['batches']]
return block |
Deserializes a Batch s header and the header of its Transactions. | def _expand_batch(cls, batch):
"""Deserializes a Batch's header, and the header of its Transactions.
"""
cls._parse_header(BatchHeader, batch)
if 'transactions' in batch:
batch['transactions'] = [
cls._expand_transaction(t) for t in batch['transactions']]
... |
Deserializes a resource s base64 encoded Protobuf header. | def _parse_header(cls, header_proto, resource):
"""Deserializes a resource's base64 encoded Protobuf header.
"""
header = header_proto()
try:
header_bytes = base64.b64decode(resource['header'])
header.ParseFromString(header_bytes)
except (KeyError, TypeErr... |
Parses start and/ or limit queries into a paging controls dict. | def _get_paging_controls(request):
"""Parses start and/or limit queries into a paging controls dict.
"""
start = request.url.query.get('start', None)
limit = request.url.query.get('limit', None)
controls = {}
if limit is not None:
try:
control... |
Turns a raw paging controls dict into Protobuf ClientPagingControls. | def _make_paging_message(controls):
"""Turns a raw paging controls dict into Protobuf ClientPagingControls.
"""
return client_list_control_pb2.ClientPagingControls(
start=controls.get('start', None),
limit=controls.get('limit', None)) |
Parses the reverse query into a list of ClientSortControls protobuf messages. | def _get_sorting_message(request, key):
"""Parses the reverse query into a list of ClientSortControls protobuf
messages.
"""
control_list = []
reverse = request.url.query.get('reverse', None)
if reverse is None:
return control_list
if reverse.lower() ... |
Parses the wait query parameter and sets the corresponding wait and timeout properties in the validator query. | def _set_wait(self, request, validator_query):
"""Parses the `wait` query parameter, and sets the corresponding
`wait` and `timeout` properties in the validator query.
"""
wait = request.url.query.get('wait', 'false')
if wait.lower() != 'false':
validator_query.wait =... |
Remove properties with empty strings from nested dicts. | def _drop_empty_props(self, item):
"""Remove properties with empty strings from nested dicts.
"""
if isinstance(item, list):
return [self._drop_empty_props(i) for i in item]
if isinstance(item, dict):
return {
k: self._drop_empty_props(v)
... |
Rename keys ending in id to just be id for nested dicts. | def _drop_id_prefixes(self, item):
"""Rename keys ending in 'id', to just be 'id' for nested dicts.
"""
if isinstance(item, list):
return [self._drop_id_prefixes(i) for i in item]
if isinstance(item, dict):
return {
'id' if k.endswith('id') else k:... |
Fetches the request s head query and validates if present. | def _get_head_id(cls, request):
"""Fetches the request's head query, and validates if present.
"""
head_id = request.url.query.get('head', None)
if head_id is not None:
cls._validate_id(head_id)
return head_id |
Parses the id filter paramter from the url query. | def _get_filter_ids(cls, request):
"""Parses the `id` filter paramter from the url query.
"""
id_query = request.url.query.get('id', None)
if id_query is None:
return None
filter_ids = id_query.split(',')
for filter_id in filter_ids:
cls._validat... |
Creates a StateView for the given state root hash. | def create_view(self, state_root_hash=None):
"""Creates a StateView for the given state root hash.
Args:
state_root_hash (str): The state root hash of the state view
to return. If None, returns the state view for the
Returns:
StateView: state view locked... |
Register the subscriber for the given event subscriptions. | def add_subscriber(self, connection_id, subscriptions,
last_known_block_id):
"""Register the subscriber for the given event subscriptions.
Raises:
InvalidFilterError
One of the filters in the subscriptions is invalid.
"""
with self._sub... |
Send an event list with all events that are in the given subscriptions from all blocks since that latest block in the current chain that is in the given last known block ids. | def catchup_subscriber(self, connection_id):
"""Send an event list with all events that are in the given
subscriptions from all blocks since that latest block in the current
chain that is in the given last known block ids.
Raises:
PossibleForkDetectedError
A ... |
Raises: PossibleForkDetectedError | def get_catchup_block_ids(self, last_known_block_id):
'''
Raises:
PossibleForkDetectedError
'''
# If latest known block is not the current chain head, catch up
catchup_up_blocks = []
chain_head = self._block_store.chain_head
if chain_head and last_know... |
Get a list of events associated with all the block ids. | def get_events_for_block_ids(self, block_ids, subscriptions):
"""Get a list of events associated with all the block ids.
Args:
block_ids (list of str): The block ids to search for events that
match each subscription.
subscriptions (list of EventSubscriptions): Ev... |
Get a list of events associated with all the blocks. | def get_events_for_blocks(self, blocks, subscriptions):
"""Get a list of events associated with all the blocks.
Args:
blocks (list of BlockWrapper): The blocks to search for events that
match each subscription.
subscriptions (list of EventSubscriptions): EventFil... |
Returns a consensus module by name. | def get_consensus_module(module_name):
"""Returns a consensus module by name.
Args:
module_name (str): The name of the module to load.
Returns:
module: The consensus module.
Raises:
UnknownConsensusModuleError: Raised if the given module_name does
... |
Returns the consensus_module based on the consensus module set by the sawtooth_settings transaction family. | def get_configured_consensus_module(block_id, state_view):
"""Returns the consensus_module based on the consensus module set by
the "sawtooth_settings" transaction family.
Args:
block_id (str): the block id associated with the current state_view
state_view (:obj:`StateVi... |
Parse command line flags added to rest_api command. | def parse_args(args):
"""Parse command line flags added to `rest_api` command.
"""
parser = argparse.ArgumentParser(
description='Starts the REST API application and connects to a '
'specified validator.')
parser.add_argument('-B', '--bind',
help='identify host a... |
Builds the web app adds route handlers and finally starts the app. | def start_rest_api(host, port, connection, timeout, registry,
client_max_size=None):
"""Builds the web app, adds route handlers, and finally starts the app.
"""
loop = asyncio.get_event_loop()
connection.open()
app = web.Application(loop=loop, client_max_size=client_max_size)
... |
Creates the arg parsers needed for the genesis command. | def add_genesis_parser(subparsers, parent_parser):
"""Creates the arg parsers needed for the genesis command.
"""
parser = subparsers.add_parser(
'genesis',
help='Creates the genesis.batch file for initializing the validator',
description='Generates the genesis.batch file for '
... |
Given the command args take an series of input files containing GenesisData combine all the batches into one GenesisData and output the result into a new file. | def do_genesis(args, data_dir=None):
"""Given the command args, take an series of input files containing
GenesisData, combine all the batches into one GenesisData, and output the
result into a new file.
"""
if data_dir is None:
data_dir = get_data_dir()
if not os.path.exists(data_dir):... |
Validates the transaction dependencies for the transactions contained within the sequence of batches. Given that all the batches are expected to to be executed for the genesis blocks it is assumed that any dependent transaction will proceed the depending transaction. | def _validate_depedencies(batches):
"""Validates the transaction dependencies for the transactions contained
within the sequence of batches. Given that all the batches are expected to
to be executed for the genesis blocks, it is assumed that any dependent
transaction will proceed the depending transacti... |
Ensure that all settings required at genesis are set. | def _check_required_settings(batches):
"""Ensure that all settings required at genesis are set."""
required_settings = [
'sawtooth.consensus.algorithm.name',
'sawtooth.consensus.algorithm.version']
for batch in batches:
for txn in batch.transactions:
txn_header = Transac... |
Retrieves a value associated with a key from the database | def get(self, key, index=None):
"""Retrieves a value associated with a key from the database
Args:
key (str): The key to retrieve
"""
records = self.get_multi([key], index=index)
try:
return records[0][1] # return the value from the key/value tuple
... |
Cleans up any outstanding subscriptions. | async def on_shutdown(self):
"""
Cleans up any outstanding subscriptions.
"""
await self._unregister_subscriptions()
self._accepting = False
for (ws, _) in self._subscribers:
await ws.close(code=aiohttp.WSCloseCode.GOING_AWAY,
mess... |
Handles requests for new subscription websockets. | 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 | 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 | 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 | 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. batch_ids are not the same length the batch_id l... | 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 | 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. | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 in the blockstore and ... | 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 of any authorization - type mess... | 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 access to the role ALL and the val... | 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 not sent a ConnectionRequest or th... | 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 is accepted the node’s public key... | 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 | 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 | 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. | 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. | 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 | 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(
'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.