INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Handle GET_TXN request
def handle_get_txn_req(self, request: Request, frm: str): """ Handle GET_TXN request """ ledger_id = request.operation.get(f.LEDGER_ID.nm, DOMAIN_LEDGER_ID) if ledger_id not in self.ledger_to_req_handler: self.send_nack_to_client((request.identifier, request.reqId), ...
Execute ordered request :param ordered: an ordered request :return: whether executed
def processOrdered(self, ordered: Ordered): """ Execute ordered request :param ordered: an ordered request :return: whether executed """ if ordered.instId not in self.instances.ids: logger.warning('{} got ordered request for instance {} which ' ...
Take any messages from replica that have been ordered and process them, this should be done rarely, like before catchup starts so a more current LedgerStatus can be sent. can be called either 1. when node is participating, this happens just before catchup starts so the node can h...
def force_process_ordered(self): """ Take any messages from replica that have been ordered and process them, this should be done rarely, like before catchup starts so a more current LedgerStatus can be sent. can be called either 1. when node is participating, this happens...
Process an exception escalated from a Replica
def processEscalatedException(self, ex): """ Process an exception escalated from a Replica """ if isinstance(ex, SuspiciousNode): self.reportSuspiciousNodeEx(ex) else: raise RuntimeError("unhandled replica-escalated exception") from ex
Checks if any requests have been ordered since last performance check and updates the performance check data store if needed. :return: True if new ordered requests, False otherwise
def _update_new_ordered_reqs_count(self): """ Checks if any requests have been ordered since last performance check and updates the performance check data store if needed. :return: True if new ordered requests, False otherwise """ last_num_ordered = self._last_performance...
Check if master instance is slow and send an instance change request. :returns True if master performance is OK, False if performance degraded, None if the check was needed
def checkPerformance(self) -> Optional[bool]: """ Check if master instance is slow and send an instance change request. :returns True if master performance is OK, False if performance degraded, None if the check was needed """ logger.trace("{} checking its performance".fo...
Schedule an primary connection check which in turn can send a view change message
def lost_master_primary(self): """ Schedule an primary connection check which in turn can send a view change message """ self.primaries_disconnection_times[self.master_replica.instId] = time.perf_counter() self._schedule_view_change()
Validate the signature of the request Note: Batch is whitelisted because the inner messages are checked :param msg: a message requiring signature verification :return: None; raises an exception if the signature is not valid
def verifySignature(self, msg): """ Validate the signature of the request Note: Batch is whitelisted because the inner messages are checked :param msg: a message requiring signature verification :return: None; raises an exception if the signature is not valid """ ...
Execute the REQUEST sent to this Node :param view_no: the view number (See glossary) :param pp_time: the time at which PRE-PREPARE was sent :param valid_reqs: list of valid client requests keys :param valid_reqs: list of invalid client requests keys
def executeBatch(self, three_pc_batch: ThreePcBatch, valid_reqs_keys: List, invalid_reqs_keys: List, audit_txn_root) -> None: """ Execute the REQUEST sent to this Node :param view_no: the view number (See glossary) :param pp_time: the time at wh...
A batch of requests has been created and has been applied but committed to ledger and state. :param ledger_id: :param state_root: state root after the batch creation :return:
def onBatchCreated(self, three_pc_batch: ThreePcBatch): """ A batch of requests has been created and has been applied but committed to ledger and state. :param ledger_id: :param state_root: state root after the batch creation :return: """ ledger_id = three...
A batch of requests has been rejected, if stateRoot is None, reject the current batch. :param ledger_id: :param stateRoot: state root after the batch was created :return:
def onBatchRejected(self, ledger_id): """ A batch of requests has been rejected, if stateRoot is None, reject the current batch. :param ledger_id: :param stateRoot: state root after the batch was created :return: """ if ledger_id == POOL_LEDGER_ID: ...
Adds a new client or steward to this node based on transaction type.
def addNewRole(self, txn): """ Adds a new client or steward to this node based on transaction type. """ # If the client authenticator is a simple authenticator then add verkey. # For a custom authenticator, handle appropriately. # NOTE: The following code should not be u...
Check whether the keys are setup in the local STP keep. Raises KeysNotFoundException if not found.
def ensureKeysAreSetup(self): """ Check whether the keys are setup in the local STP keep. Raises KeysNotFoundException if not found. """ if not areKeysSetup(self.name, self.keys_dir): raise REx(REx.reason.format(self.name) + self.keygenScript)
Report suspicion on a node on the basis of an exception
def reportSuspiciousNodeEx(self, ex: SuspiciousNode): """ Report suspicion on a node on the basis of an exception """ self.reportSuspiciousNode(ex.node, ex.reason, ex.code, ex.offendingMsg)
Report suspicion on a node and add it to this node's blacklist. :param nodeName: name of the node to report suspicion on :param reason: the reason for suspicion
def reportSuspiciousNode(self, nodeName: str, reason=None, code: int = None, offendingMsg=None): """ Report suspicion on a node and add it to this node's blacklist. :param nodeNam...
Report suspicion on a client and add it to this node's blacklist. :param clientName: name of the client to report suspicion on :param reason: the reason for suspicion
def reportSuspiciousClient(self, clientName: str, reason): """ Report suspicion on a client and add it to this node's blacklist. :param clientName: name of the client to report suspicion on :param reason: the reason for suspicion """ logger.warning("{} raised suspicion o...
Add the client specified by `clientName` to this node's blacklist
def blacklistClient(self, clientName: str, reason: str = None, code: int = None): """ Add the client specified by `clientName` to this node's blacklist """ msg = "{} blacklisting client {}".format(self, clientName) if reason: msg += " for reaso...
Add the node specified by `nodeName` to this node's blacklist
def blacklistNode(self, nodeName: str, reason: str = None, code: int = None): """ Add the node specified by `nodeName` to this node's blacklist """ msg = "{} blacklisting node {}".format(self, nodeName) if reason: msg += " for reason {}".format(reason) if code...
Print the node's current statistics to log.
def logstats(self): """ Print the node's current statistics to log. """ lines = [ "node {} current stats".format(self), "--------------------------------------------------------", "node inbox size : {}".format(len(self.nodeInBox)), ...
Print the node's info to log for the REST backend to read.
def logNodeInfo(self): """ Print the node's info to log for the REST backend to read. """ self.nodeInfo['data'] = self.collectNodeInfo() with closing(open(os.path.join(self.ledger_dir, 'node_info'), 'w')) \ as logNodeInfoFile: logNodeInfoFile.write(js...
Iterates over `collections` of the gives object and gives its byte size and number of items in collection
def get_collection_sizes(obj, collections: Optional[Tuple]=None, get_only_non_empty=False): """ Iterates over `collections` of the gives object and gives its byte size and number of items in collection """ from pympler import asizeof collections = collections or (list, d...
A safety net. Decorator for functions that are only allowed to return True or raise an exception. Args: f: A function whose only expected return value is True. Returns: A wrapped functions whose guaranteed only return value is True.
def returns_true_or_raises(f): """A safety net. Decorator for functions that are only allowed to return True or raise an exception. Args: f: A function whose only expected return value is True. Returns: A wrapped functions whose guaranteed only return value is True. """ @f...
Return the list of replicas that don't belong to the master protocol instance
def backupIds(self) -> Sequence[int]: """ Return the list of replicas that don't belong to the master protocol instance """ return [id for id in self.started.keys() if id != 0]
Checks whether n-f nodes completed view change and whether one of them is the next primary
def _hasViewChangeQuorum(self): # This method should just be present for master instance. """ Checks whether n-f nodes completed view change and whether one of them is the next primary """ num_of_ready_nodes = len(self._view_change_done) diff = self.quorum - num_o...
Validate and process an instance change request. :param instChg: the instance change request :param frm: the name of the node that sent this `msg`
def process_instance_change_msg(self, instChg: InstanceChange, frm: str) -> None: """ Validate and process an instance change request. :param instChg: the instance change request :param frm: the name of the node that sent this `msg` """ if frm not in self.provider.connec...
Processes ViewChangeDone messages. Once n-f messages have been received, decides on a primary for specific replica. :param msg: ViewChangeDone message :param sender: the name of the node from which this message was sent
def process_vchd_msg(self, msg: ViewChangeDone, sender: str) -> bool: """ Processes ViewChangeDone messages. Once n-f messages have been received, decides on a primary for specific replica. :param msg: ViewChangeDone message :param sender: the name of the node from which this me...
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 """ # do not start any view changes until catch-up is fin...
Broadcast an instance change request to all the remaining nodes :param view_no: the view number when the instance change is requested
def sendInstanceChange(self, view_no: int, suspicion=Suspicions.PRIMARY_DEGRADED): """ Broadcast an instance change request to all the remaining nodes :param view_no: the view number when the instance change is requested """ # If not found any sent in...
Return whether there's quorum for view change for the proposed view number and its view is less than or equal to the proposed view
def _canViewChange(self, proposedViewNo: int) -> (bool, str): """ Return whether there's quorum for view change for the proposed view number and its view is less than or equal to the proposed view """ msg = None quorum = self.quorums.view_change.value if not self....
Trigger the view change process. :param proposed_view_no: the new view number after view change.
def start_view_change(self, proposed_view_no: int, continue_vc=False): """ Trigger the view change process. :param proposed_view_no: the new view number after view change. """ # TODO: consider moving this to pool manager # TODO: view change is a special case, which can h...
This method is called when sufficient number of ViewChangeDone received and makes steps to switch to the new primary
def _verify_primary(self, new_primary, ledger_info): """ This method is called when sufficient number of ViewChangeDone received and makes steps to switch to the new primary """ expected_primary = self.provider.next_primary_name() if new_primary != expected_primary: ...
Sends ViewChangeDone message to other protocol participants
def _send_view_change_done_message(self): """ Sends ViewChangeDone message to other protocol participants """ new_primary_name = self.provider.next_primary_name() ledger_summary = self.provider.ledger_summary() message = ViewChangeDone(self.view_no, ...
Returns the last accepted `ViewChangeDone` message. If no view change has happened returns ViewChangeDone with view no 0 to a newly joined node
def get_msgs_for_lagged_nodes(self) -> List[ViewChangeDone]: # Should not return a list, only done for compatibility with interface """ Returns the last accepted `ViewChangeDone` message. If no view change has happened returns ViewChangeDone with view no 0 to a newly joined node ...
Performs basic validation of field value and then passes it for specific validation. :param val: field value to validate :return: error message or None
def validate(self, val): """ Performs basic validation of field value and then passes it for specific validation. :param val: field value to validate :return: error message or None """ if self.nullable and val is None: return type_er = self._...
Return a signature for the given message.
def sign(self, msg: Dict) -> Dict: """ Return a signature for the given message. """ ser = serialize_msg_for_signing(msg, topLevelKeysToIgnore=[f.SIG.nm]) bsig = self.naclSigner.signature(ser) sig = base58.b58encode(bsig).decode("utf-8") return sig
This will _lastPrePrepareSeqNo to values greater than its previous values else it will not. To forcefully override as in case of `revert`, directly set `self._lastPrePrepareSeqNo`
def lastPrePrepareSeqNo(self, n): """ This will _lastPrePrepareSeqNo to values greater than its previous values else it will not. To forcefully override as in case of `revert`, directly set `self._lastPrePrepareSeqNo` """ if n > self._lastPrePrepareSeqNo: self...
Create and return the name for a replica using its nodeName and instanceId. Ex: Alpha:1
def generateName(nodeName: str, instId: int): """ Create and return the name for a replica using its nodeName and instanceId. Ex: Alpha:1 """ if isinstance(nodeName, str): # Because sometimes it is bytes (why?) if ":" in nodeName: ...
Set the value of isPrimary. :param value: the value to set isPrimary to
def primaryName(self, value: Optional[str]) -> None: """ Set the value of isPrimary. :param value: the value to set isPrimary to """ if value is not None: self.warned_no_primary = False self.primaryNames[self.viewNo] = value self.compact_primary_names...
Return lowest pp_seq_no of the view for which can be prepared but choose from unprocessed PRE-PREPAREs and PREPAREs.
def get_lowest_probable_prepared_certificate_in_view( self, view_no) -> Optional[int]: """ Return lowest pp_seq_no of the view for which can be prepared but choose from unprocessed PRE-PREPAREs and PREPAREs. """ # TODO: Naive implementation, dont need to iterate over ...
Since last ordered view_no and pp_seq_no are only communicated for master instance, backup instances use this method for restoring `last_ordered_3pc` :return:
def _setup_last_ordered_for_non_master(self): """ Since last ordered view_no and pp_seq_no are only communicated for master instance, backup instances use this method for restoring `last_ordered_3pc` :return: """ if not self.isMaster and self.first_batch_after_cat...
Return whether this replica was primary in the given view
def is_primary_in_view(self, viewNo: int) -> Optional[bool]: """ Return whether this replica was primary in the given view """ if viewNo not in self.primaryNames: return False return self.primaryNames[viewNo] == self.name
Return whether this replica is primary if the request's view number is equal this replica's view number and primary has been selected for the current view. Return None otherwise. :param msg: message
def isPrimaryForMsg(self, msg) -> Optional[bool]: """ Return whether this replica is primary if the request's view number is equal this replica's view number and primary has been selected for the current view. Return None otherwise. :param msg: message """ ...
Return whether this message was from primary replica :param msg: :param sender: :return:
def isMsgFromPrimary(self, msg, sender: str) -> bool: """ Return whether this message was from primary replica :param msg: :param sender: :return: """ if self.isMsgForCurrentView(msg): return self.primaryName == sender try: return s...
This method will do dynamic validation and apply requests. If there is any errors during validation it would be raised
def processReqDuringBatch( self, req: Request, cons_time: int): """ This method will do dynamic validation and apply requests. If there is any errors during validation it would be raised """ if self.isMaster: self.node.doDynamicVali...
TODO: for now default value for fields sub_seq_no is 0 and for final is True
def create_3pc_batch(self, ledger_id): pp_seq_no = self.lastPrePrepareSeqNo + 1 pool_state_root_hash = self.stateRootHash(POOL_LEDGER_ID) self.logger.debug("{} creating batch {} for ledger {} with state root {}".format( self, pp_seq_no, ledger_id, self.stateRootHash(ledge...
Process `limit` number of messages in the inBox. :param limit: the maximum number of messages to process :return: the number of messages successfully processed
def serviceQueues(self, limit=None): """ Process `limit` number of messages in the inBox. :param limit: the maximum number of messages to process :return: the number of messages successfully processed """ # TODO should handle SuspiciousNode here r = self.dequeue_...
Process a 3-phase (pre-prepare, prepare and commit) request. Dispatch the request only if primary has already been decided, otherwise stash it. :param msg: the Three Phase message, one of PRE-PREPARE, PREPARE, COMMIT :param sender: name of the node that sent this message
def process_three_phase_msg(self, msg: ThreePhaseMsg, sender: str): """ Process a 3-phase (pre-prepare, prepare and commit) request. Dispatch the request only if primary has already been decided, otherwise stash it. :param msg: the Three Phase message, one of PRE-PREPARE, PREPAR...
Validate and process provided PRE-PREPARE, create and broadcast PREPARE for it. :param pre_prepare: message :param sender: name of the node that sent this message
def processPrePrepare(self, pre_prepare: PrePrepare, sender: str): """ Validate and process provided PRE-PREPARE, create and broadcast PREPARE for it. :param pre_prepare: message :param sender: name of the node that sent this message """ key = (pre_prepare.viewNo...
Try to send the Prepare message if the PrePrepare message is ready to be passed into the Prepare phase.
def tryPrepare(self, pp: PrePrepare): """ Try to send the Prepare message if the PrePrepare message is ready to be passed into the Prepare phase. """ rv, msg = self.canPrepare(pp) if rv: self.doPrepare(pp) else: self.logger.debug("{} cannot...
Validate and process the PREPARE specified. If validation is successful, create a COMMIT and broadcast it. :param prepare: a PREPARE msg :param sender: name of the node that sent the PREPARE
def processPrepare(self, prepare: Prepare, sender: str) -> None: """ Validate and process the PREPARE specified. If validation is successful, create a COMMIT and broadcast it. :param prepare: a PREPARE msg :param sender: name of the node that sent the PREPARE """ ...
Validate and process the COMMIT specified. If validation is successful, return the message to the node. :param commit: an incoming COMMIT message :param sender: name of the node that sent the COMMIT
def processCommit(self, commit: Commit, sender: str) -> None: """ Validate and process the COMMIT specified. If validation is successful, return the message to the node. :param commit: an incoming COMMIT message :param sender: name of the node that sent the COMMIT """ ...
Try to commit if the Prepare message is ready to be passed into the commit phase.
def tryCommit(self, prepare: Prepare): """ Try to commit if the Prepare message is ready to be passed into the commit phase. """ rv, reason = self.canCommit(prepare) if rv: self.doCommit(prepare) else: self.logger.debug("{} cannot send COMM...
Try to order if the Commit message is ready to be ordered.
def tryOrder(self, commit: Commit): """ Try to order if the Commit message is ready to be ordered. """ canOrder, reason = self.canOrder(commit) if canOrder: self.logger.trace("{} returning request to node".format(self)) self.doOrder(commit) else: ...
Create a commit message from the given Prepare message and trigger the commit phase :param p: the prepare message
def doCommit(self, p: Prepare): """ Create a commit message from the given Prepare message and trigger the commit phase :param p: the prepare message """ key_3pc = (p.viewNo, p.ppSeqNo) self.logger.debug("{} Sending COMMIT{} at {}".format(self, key_3pc, self.get_c...
Check if there are any requests which are not finalised, i.e for which there are not enough PROPAGATEs
def nonFinalisedReqs(self, reqKeys: List[Tuple[str, int]]): """ Check if there are any requests which are not finalised, i.e for which there are not enough PROPAGATEs """ return {key for key in reqKeys if not self.requests.is_finalised(key)}
Applies (but not commits) requests of the PrePrepare to the ledger and state
def _apply_pre_prepare(self, pre_prepare: PrePrepare): """ Applies (but not commits) requests of the PrePrepare to the ledger and state """ reqs = [] idx = 0 rejects = [] invalid_indices = [] suspicious = False # 1. apply each request ...
Decide whether this replica is eligible to process a PRE-PREPARE. :param pre_prepare: a PRE-PREPARE msg to process :param sender: the name of the node that sent the PRE-PREPARE msg
def _can_process_pre_prepare(self, pre_prepare: PrePrepare, sender: str) -> Optional[int]: """ Decide whether this replica is eligible to process a PRE-PREPARE. :param pre_prepare: a PRE-PREPARE msg to process :param sender: the name of the node that sent the PRE-PREPARE msg """...
Add the specified PRE-PREPARE to this replica's list of received PRE-PREPAREs and try sending PREPARE :param pp: the PRE-PREPARE to add to the list
def addToPrePrepares(self, pp: PrePrepare) -> None: """ Add the specified PRE-PREPARE to this replica's list of received PRE-PREPAREs and try sending PREPARE :param pp: the PRE-PREPARE to add to the list """ key = (pp.viewNo, pp.ppSeqNo) self.prePrepares[key] = p...
Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes
def canPrepare(self, ppReq) -> (bool, str): """ Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes """ if self.has_sent_prepare(ppReq): return False, 'has ...
Return whether the PREPARE specified is valid. :param prepare: the PREPARE to validate :param sender: the name of the node that sent the PREPARE :return: True if PREPARE is valid, False otherwise
def validatePrepare(self, prepare: Prepare, sender: str) -> bool: """ Return whether the PREPARE specified is valid. :param prepare: the PREPARE to validate :param sender: the name of the node that sent the PREPARE :return: True if PREPARE is valid, False otherwise """ ...
Add the specified PREPARE to this replica's list of received PREPAREs and try sending COMMIT :param prepare: the PREPARE to add to the list
def addToPrepares(self, prepare: Prepare, sender: str): """ Add the specified PREPARE to this replica's list of received PREPAREs and try sending COMMIT :param prepare: the PREPARE to add to the list """ # BLS multi-sig: self._bls_bft_replica.process_prepare(prep...
Return whether the specified PREPARE can proceed to the Commit step. Decision criteria: - If this replica has got just n-f-1 PREPARE requests then commit request. - If less than n-f-1 PREPARE requests then probably there's no consensus on the request; don't commit -...
def canCommit(self, prepare: Prepare) -> (bool, str): """ Return whether the specified PREPARE can proceed to the Commit step. Decision criteria: - If this replica has got just n-f-1 PREPARE requests then commit request. - If less than n-f-1 PREPARE requests then probab...
Return whether the COMMIT specified is valid. :param commit: the COMMIT to validate :return: True if `request` is valid, False otherwise
def validateCommit(self, commit: Commit, sender: str) -> bool: """ Return whether the COMMIT specified is valid. :param commit: the COMMIT to validate :return: True if `request` is valid, False otherwise """ key = (commit.viewNo, commit.ppSeqNo) if not self.has_p...
Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT
def addToCommits(self, commit: Commit, sender: str): """ Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT """ # BLS multi-sig: ...
Return whether the specified commitRequest can be returned to the node. Decision criteria: - If have got just n-f Commit requests then return request to node - If less than n-f of commit requests then probably don't have consensus on the request; don't return request to node ...
def canOrder(self, commit: Commit) -> Tuple[bool, Optional[str]]: """ Return whether the specified commitRequest can be returned to the node. Decision criteria: - If have got just n-f Commit requests then return request to node - If less than n-f of commit requests then probabl...
Return True if all previous COMMITs have been ordered
def all_prev_ordered(self, commit: Commit): """ Return True if all previous COMMITs have been ordered """ # TODO: This method does a lot of work, choose correct data # structures to make it efficient. viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo if self.last_...
Process checkpoint messages :return: whether processed (True) or stashed (False)
def process_checkpoint(self, msg: Checkpoint, sender: str) -> bool: """ Process checkpoint messages :return: whether processed (True) or stashed (False) """ self.logger.info('{} processing checkpoint {} from {}'.format(self, msg, sender)) result, reason = self.validator....
:param ppSeqNo: :return: True if ppSeqNo is less than or equal to last stable checkpoint, false otherwise
def is_pp_seq_no_stable(self, msg: Checkpoint): """ :param ppSeqNo: :return: True if ppSeqNo is less than or equal to last stable checkpoint, false otherwise """ pp_seq_no = msg.seqNoEnd ck = self.firstCheckPoint if ck: _, ckState = ck ...
Dequeue any received PRE-PREPAREs that did not have finalized requests or the replica was missing any PRE-PREPAREs before it :return:
def dequeue_pre_prepares(self): """ Dequeue any received PRE-PREPAREs that did not have finalized requests or the replica was missing any PRE-PREPAREs before it :return: """ ppsReady = [] # Check if any requests have become finalised belonging to any stashed ...
Checks if the `pp_seq_no` could have been in view `view_no`. It will return False when the `pp_seq_no` belongs to a later view than `view_no` else will return True :return:
def can_pp_seq_no_be_in_view(self, view_no, pp_seq_no): """ Checks if the `pp_seq_no` could have been in view `view_no`. It will return False when the `pp_seq_no` belongs to a later view than `view_no` else will return True :return: """ if view_no > self.viewNo: ...
Request preprepare
def _request_pre_prepare(self, three_pc_key: Tuple[int, int], stash_data: Optional[Tuple[str, str, str]] = None) -> bool: """ Request preprepare """ recipients = self.primaryName return self._request_three_phase_msg(three_pc_key, ...
Request preprepare
def _request_prepare(self, three_pc_key: Tuple[int, int], recipients: List[str] = None, stash_data: Optional[Tuple[str, str, str]] = None) -> bool: """ Request preprepare """ if recipients is None: recipients = self.node.nodes...
Request commit
def _request_commit(self, three_pc_key: Tuple[int, int], recipients: List[str] = None) -> bool: """ Request commit """ return self._request_three_phase_msg(three_pc_key, self.requested_commits, COMMIT, recipients)
Check if has an acceptable PRE_PREPARE already stashed, if not then check count of PREPAREs, make sure >f consistent PREPAREs are found, store the acceptable PREPARE state (digest, roots) for verification of the received PRE-PREPARE
def _request_pre_prepare_for_prepare(self, three_pc_key) -> bool: """ Check if has an acceptable PRE_PREPARE already stashed, if not then check count of PREPAREs, make sure >f consistent PREPAREs are found, store the acceptable PREPARE state (digest, roots) for verification of th...
Check if this PRE-PREPARE is not older than (not checking for greater than since batches maybe sent in less than 1 second) last PRE-PREPARE and in a sufficient range of local clock's UTC time. :param pp: :return:
def is_pre_prepare_time_correct(self, pp: PrePrepare, sender: str) -> bool: """ Check if this PRE-PREPARE is not older than (not checking for greater than since batches maybe sent in less than 1 second) last PRE-PREPARE and in a sufficient range of local clock's UTC time. :param ...
Returns True or False depending on the whether the time in PRE-PREPARE is acceptable. Can return True if time is not acceptable but sufficient PREPAREs are found to support the PRE-PREPARE :param pp: :return:
def is_pre_prepare_time_acceptable(self, pp: PrePrepare, sender: str) -> bool: """ Returns True or False depending on the whether the time in PRE-PREPARE is acceptable. Can return True if time is not acceptable but sufficient PREPAREs are found to support the PRE-PREPARE :param p...
Check if any PRE-PREPAREs that were stashed since their time was not acceptable, can now be accepted since enough PREPAREs are received
def _process_stashed_pre_prepare_for_time_if_possible( self, key: Tuple[int, int]): """ Check if any PRE-PREPAREs that were stashed since their time was not acceptable, can now be accepted since enough PREPAREs are received """ self.logger.debug('{} going to process s...
Send a message to the node on which this replica resides. :param stat: :param rid: remote id of one recipient (sends to all recipients if None) :param msg: the message to send
def send(self, msg, stat=None) -> None: """ Send a message to the node on which this replica resides. :param stat: :param rid: remote id of one recipient (sends to all recipients if None) :param msg: the message to send """ self.logger.trace("{} sending {}".forma...
Revert changes to ledger (uncommitted) and state made by any requests that have not been ordered.
def revert_unordered_batches(self): """ Revert changes to ledger (uncommitted) and state made by any requests that have not been ordered. """ i = 0 for key in sorted(self.batches.keys(), reverse=True): if compare_3PC_keys(self.last_ordered_3pc, key) > 0: ...
Remove any 3 phase messages till the last ordered key and also remove any corresponding request keys
def _remove_till_caught_up_3pc(self, last_caught_up_3PC): """ Remove any 3 phase messages till the last ordered key and also remove any corresponding request keys """ outdated_pre_prepares = {} for key, pp in self.prePrepares.items(): if compare_3PC_keys(key, ...
Remove any Ordered that the replica might be sending to node which is less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is passed else remove all ordered, needed in catchup
def _remove_ordered_from_queue(self, last_caught_up_3PC=None): """ Remove any Ordered that the replica might be sending to node which is less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is passed else remove all ordered, needed in catchup """ to_remove =...
Remove stashed received checkpoints up to `till_3pc_key` if provided, otherwise remove all stashed received checkpoints
def _remove_stashed_checkpoints(self, till_3pc_key=None): """ Remove stashed received checkpoints up to `till_3pc_key` if provided, otherwise remove all stashed received checkpoints """ if till_3pc_key is None: self.stashedRecvdCheckpoints.clear() self.log...
Checks whether the given port is available
def checkPortAvailable(ha): """Checks whether the given port is available""" # Not sure why OS would allow binding to one type and not other. # Checking for port available for TCP and UDP. sockTypes = (socket.SOCK_DGRAM, socket.SOCK_STREAM) for typ in sockTypes: sock = socket.socket(socket.A...
A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false
def evenCompare(a: str, b: str) -> bool: """ A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false """ ab = a.encode('utf-8') b...
Create a map where every node is connected every other node. Assume each key in the returned dictionary to be connected to each item in its value(list). :param names: a list of node names :return: a dictionary of name -> list(name).
def distributedConnectionMap(names: List[str]) -> OrderedDict: """ Create a map where every node is connected every other node. Assume each key in the returned dictionary to be connected to each item in its value(list). :param names: a list of node names :return: a dictionary of name -> list(na...
Bandwidth. Formula: BW = SMA(H - L)
def band_width(high_data, low_data, period): """ Bandwidth. Formula: BW = SMA(H - L) """ catch_errors.check_for_input_len_diff(high_data, low_data) diff = np.array(high_data) - np.array(low_data) bw = sma(diff, period) return bw
Center Band. Formula: CB = SMA(TP)
def center_band(close_data, high_data, low_data, period): """ Center Band. Formula: CB = SMA(TP) """ tp = typical_price(close_data, high_data, low_data) cb = sma(tp, period) return cb
Upper Band. Formula: UB = CB + BW
def upper_band(close_data, high_data, low_data, period): """ Upper Band. Formula: UB = CB + BW """ cb = center_band(close_data, high_data, low_data, period) bw = band_width(high_data, low_data, period) ub = cb + bw return ub
Simple Moving Average. Formula: SUM(data / N)
def simple_moving_average(data, period): """ Simple Moving Average. Formula: SUM(data / N) """ catch_errors.check_for_period_error(data, period) # Mean of Empty Slice RuntimeWarning doesn't affect output so it is # supressed with warnings.catch_warnings(): warnings.simplefil...
Lower Band. Formula: LB = CB - BW
def lower_band(close_data, high_data, low_data, period): """ Lower Band. Formula: LB = CB - BW """ cb = center_band(close_data, high_data, low_data, period) bw = band_width(high_data, low_data, period) lb = cb - bw return lb
Average True Range Percent. Formula: ATRP = (ATR / CLOSE) * 100
def average_true_range_percent(close_data, period): """ Average True Range Percent. Formula: ATRP = (ATR / CLOSE) * 100 """ catch_errors.check_for_period_error(close_data, period) atrp = (atr(close_data, period) / np.array(close_data)) * 100 return atrp
On Balance Volume. Formula: start = 1 if CLOSEt > CLOSEt-1 obv = obvt-1 + volumet elif CLOSEt < CLOSEt-1 obv = obvt-1 - volumet elif CLOSEt == CLOSTt-1 obv = obvt-1
def on_balance_volume(close_data, volume): """ On Balance Volume. Formula: start = 1 if CLOSEt > CLOSEt-1 obv = obvt-1 + volumet elif CLOSEt < CLOSEt-1 obv = obvt-1 - volumet elif CLOSEt == CLOSTt-1 obv = obvt-1 """ catch_errors.check_for_input_len_diff(close...
Rate of Change. Formula: (Close - Close n periods ago) / (Close n periods ago) * 100
def rate_of_change(data, period): """ Rate of Change. Formula: (Close - Close n periods ago) / (Close n periods ago) * 100 """ catch_errors.check_for_period_error(data, period) rocs = [((data[idx] - data[idx - (period - 1)]) / data[idx - (period - 1)]) * 100 for idx in range(perio...
Average True Range. Formula: ATRt = ATRt-1 * (n - 1) + TRt / n
def average_true_range(close_data, period): """ Average True Range. Formula: ATRt = ATRt-1 * (n - 1) + TRt / n """ tr = true_range(close_data, period) atr = smoothed_moving_average(tr, period) atr[0:period-1] = tr[0:period-1] return atr
Accumulation/Distribution. Formula: A/D = (Ct - Lt) - (Ht - Ct) / (Ht - Lt) * Vt + A/Dt-1
def accumulation_distribution(close_data, high_data, low_data, volume): """ Accumulation/Distribution. Formula: A/D = (Ct - Lt) - (Ht - Ct) / (Ht - Lt) * Vt + A/Dt-1 """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) ad = np.zeros(len(close...
Relative Strength Index. Formula: RSI = 100 - (100 / 1 + (prevGain/prevLoss))
def relative_strength_index(data, period): """ Relative Strength Index. Formula: RSI = 100 - (100 / 1 + (prevGain/prevLoss)) """ catch_errors.check_for_period_error(data, period) period = int(period) changes = [data_tup[1] - data_tup[0] for data_tup in zip(data[::1], data[1::1])] ...
Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1))
def vertical_horizontal_filter(data, period): """ Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1)) """ catch_errors.check_for_period_error(data, period) vhf = [abs(np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1])) / sum([ab...
Buying Pressure. Formula: BP = current close - min()
def buying_pressure(close_data, low_data): """ Buying Pressure. Formula: BP = current close - min() """ catch_errors.check_for_input_len_diff(close_data, low_data) bp = [close_data[idx] - np.min([low_data[idx], close_data[idx-1]]) for idx in range(1, len(close_data))] bp = fill_for_nonc...
Ultimate Oscillator. Formula: UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1)
def ultimate_oscillator(close_data, low_data): """ Ultimate Oscillator. Formula: UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1) """ a7 = 4 * average_7(close_data, low_data) a14 = 2 * average_14(close_data, low_data) a28 = average_28(close_data, low_data) uo = 100 * ((a7...
Aroon Up. Formula: AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100
def aroon_up(data, period): """ Aroon Up. Formula: AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100 """ catch_errors.check_for_period_error(data, period) period = int(period) a_up = [((period - list(reversed(data[idx+1-period:idx+1])).index(np.max(data[...