INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return chunk no and 1-based offset of key
:param key:
:return: | def _get_key_location(self, key) -> (int, int):
"""
Return chunk no and 1-based offset of key
:param key:
:return:
"""
key = int(key)
if key == 0:
return 1, 0
remainder = key % self.chunkSize
addend = ChunkedFileStore.firstChunkIndex
... |
Determines the file to retrieve the data from and retrieves the data.
:return: value corresponding to specified key | def get(self, key) -> str:
"""
Determines the file to retrieve the data from and retrieves the data.
:return: value corresponding to specified key
"""
# TODO: get is creating files when a key is given which is more than
# the store size
chunk_no, offset = self._g... |
Clear all data in file storage. | def reset(self) -> None:
"""
Clear all data in file storage.
"""
self.close()
for f in os.listdir(self.dataDir):
os.remove(os.path.join(self.dataDir, f))
self._useLatestChunk() |
Lines in a store (all chunks)
:return: lines | def _lines(self):
"""
Lines in a store (all chunks)
:return: lines
"""
chunkIndices = self._listChunks()
for chunkIndex in chunkIndices:
with self._openChunk(chunkIndex) as chunk:
yield from chunk._lines() |
Lists stored chunks
:return: sorted list of available chunk indices | def _listChunks(self):
"""
Lists stored chunks
:return: sorted list of available chunk indices
"""
chunks = []
for fileName in os.listdir(self.dataDir):
index = ChunkedFileStore._fileNameToChunkIndex(fileName)
if index is not None:
... |
Filters messages by view number so that only the messages that have the
current view number are retained.
:param wrappedMsgs: the messages to filter | def filterMsgs(self, wrappedMsgs: deque) -> deque:
"""
Filters messages by view number so that only the messages that have the
current view number are retained.
:param wrappedMsgs: the messages to filter
"""
filtered = deque()
while wrappedMsgs:
wrapp... |
Service at most `limit` messages from the inBox.
:param limit: the maximum number of messages to service
:return: the number of messages successfully processed | async def serviceQueues(self, limit=None) -> int:
"""
Service at most `limit` messages from the inBox.
:param limit: the maximum number of messages to service
:return: the number of messages successfully processed
"""
return await self.inBoxRouter.handleAll(self.filterM... |
Notifies primary decider about the fact that view changed to let it
prepare for election, which then will be started from outside by
calling decidePrimaries() | def view_change_started(self, viewNo: int):
"""
Notifies primary decider about the fact that view changed to let it
prepare for election, which then will be started from outside by
calling decidePrimaries()
"""
if viewNo <= self.viewNo:
logger.warning("{}Provi... |
Send a message to the node on which this replica resides.
:param msg: the message to send | def send(self, msg):
"""
Send a message to the node on which this replica resides.
:param msg: the message to send
"""
logger.debug("{}'s elector sending {}".format(self.name, msg))
self.outBox.append(msg) |
Authenticates a given request data by verifying signatures from
any registered authenticators. If the request is a query returns
immediately, if no registered authenticator can authenticate then an
exception is raised.
:param req_data:
:return: | def authenticate(self, req_data, key=None):
"""
Authenticates a given request data by verifying signatures from
any registered authenticators. If the request is a query returns
immediately, if no registered authenticator can authenticate then an
exception is raised.
:para... |
Retrieve a plugin by name. | def get(self, name):
"""Retrieve a plugin by name."""
try:
return self.plugins[name]
except KeyError:
raise RuntimeError("plugin {} does not exist".format(name)) |
Authenticate the client's message with the signature provided.
:param identifier: some unique identifier; if None, then try to use
msg['identifier'] as identifier
:param signature: a utf-8 and base58 encoded signature
:param msg: the message to authenticate
:param threshold: The... | def authenticate(self,
msg: Dict,
identifier: Optional[str] = None,
signature: Optional[str] = None,
threshold: Optional[int] = None,
key: Optional[str] = None) -> str:
"""
Authenticate the client's ... |
:param msg:
:param signatures: A mapping from identifiers to signatures.
:param threshold: The number of successful signature verification
required. By default all signatures are required to be verified.
:return: returns the identifiers whose signature was matched and
correct; a ... | def authenticate_multi(self, msg: Dict, signatures: Dict[str, str],
threshold: Optional[int] = None):
"""
:param msg:
:param signatures: A mapping from identifiers to signatures.
:param threshold: The number of successful signature verification
required... |
Prepares the data to be serialised for signing and then verifies the
signature
:param req_data:
:param identifier:
:param signature:
:param verifier:
:return: | def authenticate(self, req_data, identifier: Optional[str]=None,
signature: Optional[str]=None, threshold: Optional[int] = None,
verifier: Verifier=DidVerifier):
"""
Prepares the data to be serialised for signing and then verifies the
signature
:... |
Compares two instances. | def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:
""" Compares two instances. """
# TODO types checking
if v1._version > v2._version:
return 1
elif v1._version == v2._version:
return 0
else:
return -1 |
Ensure appropriate connections. | def maintainConnections(self, force=False):
"""
Ensure appropriate connections.
"""
now = time.perf_counter()
if now < self.nextCheck and not force:
return False
self.nextCheck = now + (self.config.RETRY_TIMEOUT_NOT_RESTRICTED
... |
Check whether registry contains some addresses
that were never connected to
:return: | def reconcileNodeReg(self) -> set:
"""
Check whether registry contains some addresses
that were never connected to
:return:
"""
matches = set()
for name, remote in self.remotes.items():
if name not in self.registry:
continue
... |
Try to connect to the missing nodes | def connectToMissing(self) -> set:
"""
Try to connect to the missing nodes
"""
missing = self.reconcileNodeReg()
if not missing:
return missing
logger.info("{}{} found the following missing connections: {}".
format(CONNECTION_PREFIX, self... |
Passes the log record back to the CLI for rendering | def emit(self, record):
"""
Passes the log record back to the CLI for rendering
"""
should_cb = None
attr_val = None
if hasattr(record, self.typestr):
attr_val = getattr(record, self.typestr)
should_cb = bool(attr_val)
if should_cb is None ... |
Choose a schema for client request operation and validate
the operation field. If the schema is not found skips validation.
:param dct: an operation field from client request
:return: raises exception if invalid request | def validate(self, dct):
"""
Choose a schema for client request operation and validate
the operation field. If the schema is not found skips validation.
:param dct: an operation field from client request
:return: raises exception if invalid request
"""
if not isin... |
Updates the connection count of this node if not already done. | def conns(self, value: Set[str]) -> None:
"""
Updates the connection count of this node if not already done.
"""
if not self._conns == value:
old = self._conns
self._conns = value
ins = value - old
outs = old - value
logger.disp... |
A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number of protocol instances.
- Check protocol instances. See `checkProtocolIn... | def _connsChanged(self, ins: Set[str], outs: Set[str]) -> None:
"""
A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the nu... |
Returns the name of the remote by HA if found in the node registry, else
returns None | def findInNodeRegByHA(self, remoteHa):
"""
Returns the name of the remote by HA if found in the node registry, else
returns None
"""
regName = [nm for nm, ha in self.registry.items()
if self.sameAddr(ha, remoteHa)]
if len(regName) > 1:
raise... |
Returns the name of the remote object if found in node registry.
:param remote: the remote object | def getRemoteName(self, remote):
"""
Returns the name of the remote object if found in node registry.
:param remote: the remote object
"""
if remote.name not in self.registry:
find = [name for name, ha in self.registry.items()
if ha == remote.ha]
... |
Returns the names of nodes in the registry this node is NOT connected
to. | def notConnectedNodes(self) -> Set[str]:
"""
Returns the names of nodes in the registry this node is NOT connected
to.
"""
return set(self.registry.keys()) - self.conns |
Create and bind the ZAP socket | def start(self):
"""Create and bind the ZAP socket"""
self.zap_socket = self.context.socket(zmq.REP)
self.zap_socket.linger = 1
zapLoc = 'inproc://zeromq.zap.{}'.format(MultiZapAuthenticator.count)
self.zap_socket.bind(zapLoc)
self.log.debug('Starting ZAP at {}'.format(za... |
Close the ZAP socket | def stop(self):
"""Close the ZAP socket"""
if self.zap_socket:
self.log.debug(
'Stopping ZAP at {}'.format(self.zap_socket.LAST_ENDPOINT))
super().stop() |
Start ZAP authentication | def start(self):
"""Start ZAP authentication"""
super().start()
self.__poller = zmq.asyncio.Poller()
self.__poller.register(self.zap_socket, zmq.POLLIN)
self.__task = asyncio.ensure_future(self.__handle_zap()) |
Stop ZAP authentication | def stop(self):
"""Stop ZAP authentication"""
if self.__task:
self.__task.cancel()
if self.__poller:
self.__poller.unregister(self.zap_socket)
self.__poller = None
super().stop() |
Generate a random string in hex of the specified size
DO NOT use python provided random class its a Pseudo Random Number Generator
and not secure enough for our needs
:param size: size of the random string to generate
:return: the hexadecimal random string | def randomString(size: int = 20) -> str:
"""
Generate a random string in hex of the specified size
DO NOT use python provided random class its a Pseudo Random Number Generator
and not secure enough for our needs
:param size: size of the random string to generate
:return: the hexadecimal random... |
Takes *size* random elements from provided alphabet
:param size:
:param alphabet: | def random_from_alphabet(size, alphabet):
"""
Takes *size* random elements from provided alphabet
:param size:
:param alphabet:
"""
import random
return list(random.choice(alphabet) for _ in range(size)) |
Find the most frequent element of a collection.
:param elements: An iterable of elements
:param to_hashable_f: (optional) if defined will be used to get
hashable presentation for non-hashable elements. Otherwise json.dumps
is used with sort_keys=True
:return: element which is the most frequ... | def mostCommonElement(elements: Iterable[T], to_hashable_f: Callable=None):
"""
Find the most frequent element of a collection.
:param elements: An iterable of elements
:param to_hashable_f: (optional) if defined will be used to get
hashable presentation for non-hashable elements. Otherwise jso... |
Search for an attribute in an object and replace it with another.
:param obj: the object to search for the attribute
:param toFrom: dictionary of the attribute name before and after search and replace i.e. search for the key and replace with the value
:param checked: set of attributes of the object for rec... | def objSearchReplace(obj: Any,
toFrom: Dict[Any, Any],
checked: Set[Any]=None,
logMsg: str=None,
deepLevel: int=None) -> None:
"""
Search for an attribute in an object and replace it with another.
:param obj: the object to ... |
A generator for prime numbers starting from 2. | def prime_gen() -> int:
# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra
"""
A generator for prime numbers starting from 2.
"""
D = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = 2 * q
... |
Run an array of coroutines
:param corogen: a generator that generates coroutines
:return: list or returns of the coroutines | async def runall(corogen):
"""
Run an array of coroutines
:param corogen: a generator that generates coroutines
:return: list or returns of the coroutines
"""
results = []
for c in corogen:
result = await c
results.append(result)
return results |
Keep checking the condition till it is true or a timeout is reached
:param condition: the condition to check (a function that returns bool)
:param args: the arguments to the condition
:return: True if the condition is met in the given timeout, False otherwise | async def untilTrue(condition, *args, timeout=5) -> bool:
"""
Keep checking the condition till it is true or a timeout is reached
:param condition: the condition to check (a function that returns bool)
:param args: the arguments to the condition
:return: True if the condition is met in the given ti... |
Compare provided fields of 2 named tuples for equality and returns true
:param tuple1:
:param tuple2:
:param fields:
:return: | def compareNamedTuple(tuple1: NamedTuple, tuple2: NamedTuple, *fields):
"""
Compare provided fields of 2 named tuples for equality and returns true
:param tuple1:
:param tuple2:
:param fields:
:return:
"""
tuple1 = tuple1._asdict()
tuple2 = tuple2._asdict()
comp = []
for fiel... |
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc | def prettyDateDifference(startTime, finishTime=None):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
if startTime is None:
return None
if not isin... |
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise | def compare_3PC_keys(key1, key2) -> int:
"""
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
"""
if key1[0] == key2[0]:
return key2[1] - key1[1]
else:
return key2[0] - key1[0] |
Create and return a hashStore implementation based on configuration | def initHashStore(data_dir, name, config=None, read_only=False) -> HashStore:
"""
Create and return a hashStore implementation based on configuration
"""
config = config or getConfig()
hsConfig = config.hashStore['type'].lower()
if hsConfig == HS_FILE:
return FileHashStore(dataDir=data_d... |
:param didMethodName: name of DID Method
:param required: if not found and True, throws an exception, else None
:return: DID Method | def get(self, didMethodName, required=True) -> DidMethod:
"""
:param didMethodName: name of DID Method
:param required: if not found and True, throws an exception, else None
:return: DID Method
"""
dm = self.d.get(didMethodName) if didMethodName else self.default
... |
Transmit the specified message to the remote client specified by `remoteName`.
:param msg: a message
:param remoteName: the name of the remote | def transmitToClient(self, msg: Any, remoteName: str):
"""
Transmit the specified message to the remote client specified by `remoteName`.
:param msg: a message
:param remoteName: the name of the remote
"""
payload = self.prepForSending(msg)
try:
if is... |
:param coroFuncs: iterable of no-arg functions
:param totalTimeout:
:param retryWait:
:param acceptableExceptions:
:param acceptableFails: how many of the passed in coroutines can
ultimately fail and still be ok
:return: | async def eventuallyAll(*coroFuncs: FlexFunc, # (use functools.partials if needed)
totalTimeout: float,
retryWait: float=0.1,
acceptableExceptions=None,
acceptableFails: int=0,
override_timeout_limit... |
Merge any newly received txns during catchup with already received txns
:param existing_txns:
:param new_txns:
:return: | def _merge_catchup_txns(existing_txns, new_txns):
"""
Merge any newly received txns during catchup with already received txns
:param existing_txns:
:param new_txns:
:return:
"""
# TODO: Can we replace this with SortedDict and before merging substract existing tran... |
Transforms transactions for ledger!
Returns:
Whether catchup reply corresponding to seq_no
Name of node from which txns came
Number of transactions ready to be processed | def _has_valid_catchup_replies(self, seq_no: int, txns_to_process: List[Tuple[int, Any]]) -> Tuple[bool, str, int]:
"""
Transforms transactions for ledger!
Returns:
Whether catchup reply corresponding to seq_no
Name of node from which txns came
Number of tran... |
Returns validator ip, ports and keys
:param ledger:
:param returnActive: If returnActive is True, return only those
validators which are not out of service
:return: | def parseLedgerForHaAndKeys(ledger, returnActive=True, ledger_size=None):
"""
Returns validator ip, ports and keys
:param ledger:
:param returnActive: If returnActive is True, return only those
validators which are not out of service
:return:
"""
nodeReg =... |
Makes sure that we have integer as keys after possible deserialization from json
:param txn: txn to be transformed
:return: transformed txn | def transform_txn_for_ledger(txn):
'''
Makes sure that we have integer as keys after possible deserialization from json
:param txn: txn to be transformed
:return: transformed txn
'''
txn_data = get_payload_data(txn)
txn_data[AUDIT_TXN_LEDGERS_SIZE] = {int(k): v fo... |
helper function for parseLedgerForHaAndKeys | def _parse_pool_transaction_file(
ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
ledger_size=None):
"""
helper function for parseLedgerForHaAndKeys
"""
for _, txn in ledger.getAllTxn(to=ledger_size):
if get_type(txn) == NODE:
... |
:param txn_count: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param state_root: The state trie root after the txns are committed
:param txn_root: The txn merkle root after the txns are committed
:return: list of committ... | def commit_batch(self, three_pc_batch, prev_handler_result=None):
"""
:param txn_count: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param state_root: The state trie root after the txns are committed
:param txn_ro... |
Return hash reverting for and calculate count of reverted txns
:return: root_hash, for reverting to (needed in revertToHead method) and count of reverted txns | def reject_batch(self):
"""
Return hash reverting for and calculate count of reverted txns
:return: root_hash, for reverting to (needed in revertToHead method) and count of reverted txns
"""
prev_size = 0
if len(self.un_committed) == 0:
raise LogicError("No it... |
Serializes a dict to bytes preserving the order (in sorted order)
:param data: the data to be serialized
:return: serialized data as bytes | def serialize(self, data: Dict, fields=None, toBytes=True):
"""
Serializes a dict to bytes preserving the order (in sorted order)
:param data: the data to be serialized
:return: serialized data as bytes
"""
if isinstance(data, Dict):
data = self._sort_dict(dat... |
Deserializes msgpack bytes to OrderedDict (in the same sorted order as for serialize)
:param data: the data in bytes
:return: sorted OrderedDict | def deserialize(self, data, fields=None):
"""
Deserializes msgpack bytes to OrderedDict (in the same sorted order as for serialize)
:param data: the data in bytes
:return: sorted OrderedDict
"""
# TODO: it can be that we returned data by `get_lines`, that is already deser... |
:param txnCount: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param stateRoot: The state trie root after the txns are committed
:param txnRoot: The txn merkle root after the txns are committed
:return: list of committed ... | def commit(self, txnCount, stateRoot, txnRoot, ppTime) -> List:
"""
:param txnCount: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param stateRoot: The state trie root after the txns are committed
:param txnRoot: T... |
Get a value (and proof optionally)for the given path in state trie.
Does not return the proof is there is no aggregate signature for it.
:param path: the path generate a state proof for
:param head_hash: the root to create the proof against
:param get_value: whether to return the value
... | def get_value_from_state(self, path, head_hash=None, with_proof=False, multi_sig=None):
'''
Get a value (and proof optionally)for the given path in state trie.
Does not return the proof is there is no aggregate signature for it.
:param path: the path generate a state proof for
:p... |
Verify the consistency between two root hashes.
old_tree_size must be <= new_tree_size.
Args:
old_tree_size: size of the older tree.
new_tree_size: size of the newer_tree.
old_root: the root hash of the older tree.
new_root: the root hash of the newer tr... | def verify_tree_consistency(self, old_tree_size: int, new_tree_size: int,
old_root: bytes, new_root: bytes,
proof: Sequence[bytes]):
"""Verify the consistency between two root hashes.
old_tree_size must be <= new_tree_size.
Args:
... |
Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf_hash: The hash of the leaf for which the proof was provided.
leaf_index: Index of the leaf in the tree.
proof: A list of SHA-256 hashes representing the Merkle audit... | def verify_leaf_hash_inclusion(self, leaf_hash: bytes, leaf_index: int,
proof: List[bytes], sth: STH):
"""Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf_hash: The hash of the leaf for which the ... |
Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf: The leaf for which the proof was provided.
leaf_index: Index of the leaf in the tree.
proof: A list of SHA-256 hashes representing the Merkle audit
path... | def verify_leaf_inclusion(self, leaf: bytes, leaf_index: int,
proof: List[bytes], sth: STH):
"""Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf: The leaf for which the proof was provided.
... |
Schedule an action to be executed after `seconds` seconds.
:param action: a callable to be scheduled
:param seconds: the time in seconds after which the action must be executed | def _schedule(self, action: Callable, seconds: int=0) -> int:
"""
Schedule an action to be executed after `seconds` seconds.
:param action: a callable to be scheduled
:param seconds: the time in seconds after which the action must be executed
"""
self.aid += 1
if... |
Run all pending actions in the action queue.
:return: number of actions executed. | def _serviceActions(self) -> int:
"""
Run all pending actions in the action queue.
:return: number of actions executed.
"""
if self.aqStash:
tm = time.perf_counter()
if tm > self.aqNextCheck:
earliest = float('inf')
for d i... |
Execute a transaction that involves consensus pool management, like
adding a node, client or a steward.
:param ppTime: PrePrepare request time
:param reqs_keys: requests keys to be committed | def execute_pool_txns(self, three_pc_batch) -> List:
"""
Execute a transaction that involves consensus pool management, like
adding a node, client or a steward.
:param ppTime: PrePrepare request time
:param reqs_keys: requests keys to be committed
"""
committed_t... |
If the trie is empty then initialize it by applying
txns from ledger. | def init_state_from_ledger(self, state: State, ledger: Ledger, reqHandler):
"""
If the trie is empty then initialize it by applying
txns from ledger.
"""
if state.isEmpty:
logger.info('{} found state to be empty, recreating from '
'ledger'.form... |
Notifies node about the fact that view changed to let it
prepare for election | def on_view_change_start(self):
"""
Notifies node about the fact that view changed to let it
prepare for election
"""
self.view_changer.start_view_change_ts = self.utc_epoch()
for replica in self.replicas.values():
replica.on_view_change_start()
logge... |
View change completes for a replica when it has been decided which was
the last ppSeqNo and state and txn root for previous view | def on_view_change_complete(self):
"""
View change completes for a replica when it has been decided which was
the last ppSeqNo and state and txn root for previous view
"""
self.future_primaries_handler.set_node_state()
if not self.replicas.all_instances_have_primary:
... |
Create and return a hashStore implementation based on configuration | def getHashStore(self, name) -> HashStore:
"""
Create and return a hashStore implementation based on configuration
"""
return initHashStore(self.dataLocation, name, self.config) |
Actions to be performed on stopping the node.
- Close the UDP socket of the nodestack | def onStopping(self):
"""
Actions to be performed on stopping the node.
- Close the UDP socket of the nodestack
"""
# Log stats should happen before any kind of reset or clearing
if self.config.STACK_COMPANION == 1:
add_stop_time(self.ledger_dir, self.utc_epo... |
.opened
This function is executed by the node each time it gets its share of
CPU time from the event loop.
:param limit: the number of items to be serviced in this attempt
:return: total number of messages serviced by this node | async def prod(self, limit: int = None) -> int:
""".opened
This function is executed by the node each time it gets its share of
CPU time from the event loop.
:param limit: the number of items to be serviced in this attempt
:return: total number of messages serviced by this node
... |
Process `limit` number of messages from the nodeInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed | async def serviceNodeMsgs(self, limit: int) -> int:
"""
Process `limit` number of messages from the nodeInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
with self.metrics.measure_time(MetricsName.SE... |
Process `limit` number of messages from the clientInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed | async def serviceClientMsgs(self, limit: int) -> int:
"""
Process `limit` number of messages from the clientInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
c = await self.clientstack.service(limit,... |
Service the view_changer's inBox, outBox and action queues.
:return: the number of messages successfully serviced | async def serviceViewChanger(self, limit) -> int:
"""
Service the view_changer's inBox, outBox and action queues.
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
o = self.serviceViewChangerOutBox(limit)
i = aw... |
Service the observable's inBox and outBox
:return: the number of messages successfully serviced | async def service_observable(self, limit) -> int:
"""
Service the observable's inBox and outBox
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
o = self._service_observable_out_box(limit)
i = await self._obser... |
Service at most `limit` number of messages from the observable's outBox.
:return: the number of messages successfully serviced. | def _service_observable_out_box(self, limit: int = None) -> int:
"""
Service at most `limit` number of messages from the observable's outBox.
:return: the number of messages successfully serviced.
"""
msg_count = 0
while True:
if limit and msg_count >= limit:... |
Service the observer's inBox and outBox
:return: the number of messages successfully serviced | async def service_observer(self, limit) -> int:
"""
Service the observer's inBox and outBox
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
return await self._observer.serviceQueues(limit) |
A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number of protocol instances.
- Check protocol instances. See `checkInstances(... | def onConnsChanged(self, joined: Set[str], left: Set[str]):
"""
A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number... |
Ask other node for LedgerStatus | def _ask_for_ledger_status(self, node_name: str, ledger_id):
"""
Ask other node for LedgerStatus
"""
self.request_msg(LEDGER_STATUS, {f.LEDGER_ID.nm: ledger_id},
[node_name, ])
logger.info("{} asking {} for ledger status of ledger {}".format(self, node_na... |
Check if this node has the minimum required number of protocol
instances, i.e. f+1. If not, add a replica. If no election is in
progress, this node will try to nominate one of its replicas as primary.
This method is called whenever a connection with a new node is
established. | def checkInstances(self) -> None:
# TODO: Is this method really needed?
"""
Check if this node has the minimum required number of protocol
instances, i.e. f+1. If not, add a replica. If no election is in
progress, this node will try to nominate one of its replicas as primary.
... |
Add or remove replicas depending on `f` | def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
"""
Add or remove replicas depending on `f`
"""
# TODO: refactor this
replica_num = old_required_number_of_instances
while... |
This thing checks whether new primary was elected.
If it was not - starts view change again | def _check_view_change_completed(self):
"""
This thing checks whether new primary was elected.
If it was not - starts view change again
"""
logger.info('{} running the scheduled check for view change completion'.format(self))
if not self.view_changer.view_change_in_progre... |
Process `limit` number of replica messages | def service_replicas_outbox(self, limit: int = None) -> int:
"""
Process `limit` number of replica messages
"""
# TODO: rewrite this using Router
num_processed = 0
for message in self.replicas.get_output(limit):
num_processed += 1
if isinstance(me... |
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced. | def serviceViewChangerOutBox(self, limit: int = None) -> int:
"""
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced.
"""
msgCount = 0
while self.view_changer.outBox and (not limit or msgCount ... |
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced. | async def serviceViewChangerInbox(self, limit: int = None) -> int:
"""
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced.
"""
msgCount = 0
while self.msgsToViewChanger and (not limit or msgCou... |
Return the name of the primary node of the master instance | def master_primary_name(self) -> Optional[str]:
"""
Return the name of the primary node of the master instance
"""
master_primary_name = self.master_replica.primaryName
if master_primary_name:
return self.master_replica.getNodeName(master_primary_name)
return... |
Return true if the instance id of message corresponds to a correct
replica.
:param msg: the node message to validate
:return: | def msgHasAcceptableInstId(self, msg, frm) -> bool:
"""
Return true if the instance id of message corresponds to a correct
replica.
:param msg: the node message to validate
:return:
"""
# TODO: refactor this! this should not do anything except checking!
i... |
Return true if the view no of message corresponds to the current view
no or a view no in the future
:param msg: the node message to validate
:return: | def msgHasAcceptableViewNo(self, msg, frm) -> bool:
"""
Return true if the view no of message corresponds to the current view
no or a view no in the future
:param msg: the node message to validate
:return:
"""
# TODO: refactor this! this should not do anything exc... |
Send the message to the intended replica.
:param msg: the message to send
:param frm: the name of the node which sent this `msg` | def sendToReplica(self, msg, frm):
"""
Send the message to the intended replica.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
# TODO: discard or stash messages here instead of doing
# this in msgHas* methods!!!
... |
Send the message to the intended view changer.
:param msg: the message to send
:param frm: the name of the node which sent this `msg` | def sendToViewChanger(self, msg, frm):
"""
Send the message to the intended view changer.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
if (isinstance(msg, InstanceChange) or
self.msgHasAcceptableViewNo(msg, fr... |
Send the message to the observer.
:param msg: the message to send
:param frm: the name of the node which sent this `msg` | def send_to_observer(self, msg, frm):
"""
Send the message to the observer.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
logger.debug("{} sending message to observer: {}".
format(self, (msg, frm)))
... |
Validate and process one message from a node.
:param wrappedMsg: Tuple of message and the name of the node that sent
the message | def handleOneNodeMsg(self, wrappedMsg):
"""
Validate and process one message from a node.
:param wrappedMsg: Tuple of message and the name of the node that sent
the message
"""
try:
vmsg = self.validateNodeMsg(wrappedMsg)
if vmsg:
... |
Validate another node's message sent to this node.
:param wrappedMsg: Tuple of message and the name of the node that sent
the message
:return: Tuple of message from node and name of the node | def validateNodeMsg(self, wrappedMsg):
"""
Validate another node's message sent to this node.
:param wrappedMsg: Tuple of message and the name of the node that sent
the message
:return: Tuple of message from node and name of the node
"""
msg, frm = wrappedMsg
... |
If the message is a batch message validate each message in the batch,
otherwise add the message to the node's inbox.
:param msg: a node message
:param frm: the name of the node that sent this `msg` | def unpackNodeMsg(self, msg, frm) -> None:
"""
If the message is a batch message validate each message in the batch,
otherwise add the message to the node's inbox.
:param msg: a node message
:param frm: the name of the node that sent this `msg`
"""
# TODO: why do... |
Append the message to the node inbox
:param msg: a node message
:param frm: the name of the node that sent this `msg` | def postToNodeInBox(self, msg, frm):
"""
Append the message to the node inbox
:param msg: a node message
:param frm: the name of the node that sent this `msg`
"""
logger.trace("{} appending to nodeInbox {}".format(self, msg))
self.nodeInBox.append((msg, frm)) |
Process the messages in the node inbox asynchronously. | async def processNodeInBox(self):
"""
Process the messages in the node inbox asynchronously.
"""
while self.nodeInBox:
m = self.nodeInBox.popleft()
await self.process_one_node_message(m) |
Validate and process a client message
:param wrappedMsg: a message from a client | def handleOneClientMsg(self, wrappedMsg):
"""
Validate and process a client message
:param wrappedMsg: a message from a client
"""
try:
vmsg = self.validateClientMsg(wrappedMsg)
if vmsg:
self.unpackClientMsg(*vmsg)
except BlowUp:
... |
Validate a message sent by a client.
:param wrappedMsg: a message from a client
:return: Tuple of clientMessage and client address | def validateClientMsg(self, wrappedMsg):
"""
Validate a message sent by a client.
:param wrappedMsg: a message from a client
:return: Tuple of clientMessage and client address
"""
msg, frm = wrappedMsg
if self.isClientBlacklisted(frm):
self.discard(str... |
If the message is a batch message validate each message in the batch,
otherwise add the message to the node's clientInBox.
But node return a Nack message if View Change in progress
:param msg: a client message
:param frm: the name of the client that sent this `msg` | def unpackClientMsg(self, msg, frm):
"""
If the message is a batch message validate each message in the batch,
otherwise add the message to the node's clientInBox.
But node return a Nack message if View Change in progress
:param msg: a client message
:param frm: the name ... |
Process the messages in the node's clientInBox asynchronously.
All messages in the inBox have already been validated, including
signature check. | async def processClientInBox(self):
"""
Process the messages in the node's clientInBox asynchronously.
All messages in the inBox have already been validated, including
signature check.
"""
while self.clientInBox:
m = self.clientInBox.popleft()
req,... |
Check if received a quorum of view change done messages and if yes
check if caught up till the
Check if all requests ordered till last prepared certificate
Check if last catchup resulted in no txns | def is_catchup_needed_during_view_change(self) -> bool:
"""
Check if received a quorum of view change done messages and if yes
check if caught up till the
Check if all requests ordered till last prepared certificate
Check if last catchup resulted in no txns
"""
if... |
State based validation | def doDynamicValidation(self, request: Request):
"""
State based validation
"""
self.execute_hook(NodeHooks.PRE_DYNAMIC_VALIDATION, request=request)
# Digest validation
ledger_id, seq_no = self.seqNoDB.get_by_payload_digest(request.payload_digest)
if ledger_id is... |
Apply request to appropriate ledger and state. `cons_time` is the
UTC epoch at which consensus was reached. | def applyReq(self, request: Request, cons_time: int):
"""
Apply request to appropriate ledger and state. `cons_time` is the
UTC epoch at which consensus was reached.
"""
self.execute_hook(NodeHooks.PRE_REQUEST_APPLICATION, request=request,
cons_time=cons... |
Handle a REQUEST from the client.
If the request has already been executed, the node re-sends the reply to
the client. Otherwise, the node acknowledges the client request, adds it
to its list of client requests, and sends a PROPAGATE to the
remaining nodes.
:param request: the R... | def processRequest(self, request: Request, frm: str):
"""
Handle a REQUEST from the client.
If the request has already been executed, the node re-sends the reply to
the client. Otherwise, the node acknowledges the client request, adds it
to its list of client requests, and sends ... |
Process one propagateRequest sent to this node asynchronously
- If this propagateRequest hasn't been seen by this node, then broadcast
it to all nodes after verifying the the signature.
- Add the client to blacklist if its signature is invalid
:param msg: the propagateRequest
:... | def processPropagate(self, msg: Propagate, frm):
"""
Process one propagateRequest sent to this node asynchronously
- If this propagateRequest hasn't been seen by this node, then broadcast
it to all nodes after verifying the the signature.
- Add the client to blacklist if its sig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.