idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
229,000
def signRequest ( self , req : Request , identifier : Identifier = None ) -> Request : idr = self . requiredIdr ( idr = identifier or req . _identifier ) req . _identifier = idr req . reqId = req . gen_req_id ( ) req . signature = self . signMsg ( msg = req . signingPayloadState ( identifier = idr ) , identifier = idr ...
Signs request . Modifies reqId and signature . May modify identifier .
229,001
def signOp ( self , op : Dict , identifier : Identifier = None ) -> Request : request = Request ( operation = op , protocolVersion = CURRENT_PROTOCOL_VERSION ) return self . signRequest ( request , identifier )
Signs the message if a signer is configured
229,002
def listIds ( self , exclude = list ( ) ) : lst = list ( self . aliasesToIds . keys ( ) ) others = set ( self . idsToSigners . keys ( ) ) - set ( self . aliasesToIds . values ( ) ) lst . extend ( list ( others ) ) for x in exclude : lst . remove ( x ) return lst
For each signer in this wallet return its alias if present else return its identifier .
229,003
def saveWallet ( self , wallet , fpath ) : if not fpath : raise ValueError ( "empty path" ) _fpath = self . _normalize ( fpath ) _dpath = _fpath . parent try : _dpath . relative_to ( self . _baseDir ) except ValueError : raise ValueError ( "path {} is not is not relative to the keyrings {}" . format ( fpath , self . _b...
Save wallet into specified localtion .
229,004
def loadWallet ( self , fpath ) : if not fpath : raise ValueError ( "empty path" ) _fpath = self . _normalize ( fpath ) _dpath = _fpath . parent try : _dpath . relative_to ( self . _baseDir ) except ValueError : raise ValueError ( "path {} is not is not relative to the wallets {}" . format ( fpath , self . _baseDir ) )...
Load wallet from specified localtion .
229,005
def addVote ( self , prepare : Prepare , voter : str ) -> None : self . _add_msg ( prepare , voter )
Add the specified PREPARE to this replica s list of received PREPAREs .
229,006
def addVote ( self , commit : Commit , voter : str ) -> None : super ( ) . _add_msg ( commit , voter )
Add the specified COMMIT to this replica s list of received COMMITs .
229,007
def discard ( self , msg , reason , logMethod = logging . error , cliOutput = False ) : reason = "" if not reason else " because {}" . format ( reason ) logMethod ( "{} discarding message {}{}" . format ( self , msg , reason ) , extra = { "cli" : cliOutput } )
Discard a message and log a reason using the specified logMethod .
229,008
def toDict ( self , msg : Dict ) -> Dict : if isinstance ( msg , Request ) : tmsg = msg . as_dict elif hasattr ( msg , "_asdict" ) : tmsg = dict ( msg . _asdict ( ) ) elif hasattr ( msg , "__dict__" ) : tmsg = dict ( msg . __dict__ ) elif self . allowDictOnly : raise ValueError ( "Message cannot be converted to an appr...
Return a dictionary form of the message
229,009
def update_freshness ( self , ledger_id , ts ) : if ledger_id in self . _ledger_freshness : self . _ledger_freshness [ ledger_id ] . last_updated = ts
Updates the time at which the ledger was updated . Should be called whenever a txn for the ledger is ordered .
229,010
def get_last_update_time ( self ) : last_updated = { ledger_id : freshness_state . last_updated for ledger_id , freshness_state in self . _ledger_freshness . items ( ) } return OrderedDict ( sorted ( last_updated . items ( ) , key = lambda item : ( item [ 1 ] , item [ 0 ] ) ) )
Gets the time at which each ledger was updated . Can be called at any time to get this information .
229,011
def serialize ( self , obj , level = 0 , objname = None , topLevelKeysToIgnore = None , toBytes = True ) : res = None if not isinstance ( obj , acceptableTypes ) : error ( "invalid type found {}: {}" . format ( objname , obj ) ) elif isinstance ( obj , str ) : res = obj elif isinstance ( obj , dict ) : if level > 0 : k...
Create a string representation of the given object .
229,012
def reset ( self ) : self . getsCounter = 0 self . processedRequests = { } self . responses = { } self . transactions = { }
Clear the values of all attributes of the transaction store .
229,013
def stop ( self , timeout : int = 5 ) -> None : self . running = False start = time . perf_counter ( ) while True : if self . getsCounter == 0 : return True elif time . perf_counter ( ) <= start + timeout : time . sleep ( .1 ) else : raise StopTimeout ( "Stop timed out waiting for {} gets to " "complete." . format ( se...
Try to stop the transaction store in the given timeout or raise an exception .
229,014
def addToProcessedTxns ( self , identifier : str , txnId : str , reply : Reply ) -> None : self . transactions [ txnId ] = reply if identifier not in self . processedRequests : self . processedRequests [ identifier ] = { } self . processedRequests [ identifier ] [ reply . reqId ] = txnId
Add a client request to the transaction store s list of processed requests .
229,015
async def append ( self , reply : Reply ) -> None : result = reply . result identifier = result . get ( f . IDENTIFIER . nm ) txnId = result . get ( TXN_ID ) logger . debug ( "Reply being sent {}" . format ( reply ) ) if self . _isNewTxn ( identifier , reply , txnId ) : self . addToProcessedTxns ( identifier , txnId , ...
Add the given Reply to this transaction store s list of responses . Also add to processedRequests if not added previously .
229,016
def _isNewTxn ( self , identifier , reply , txnId ) -> bool : return ( identifier not in self . processedRequests or reply . reqId not in self . processedRequests [ identifier ] ) and txnId is not None
If client is not in processedRequests or requestId is not there in processed requests and txnId is present then its a new reply
229,017
def add ( self , req : Request ) : key = req . key if key not in self : self [ key ] = ReqState ( req ) return self [ key ]
Add the specified request to this request store .
229,018
def ordered_by_replica ( self , request_key ) : state = self . get ( request_key ) if not state : return state . unordered_by_replicas_num -= 1
Should be called by each replica when request is ordered or replica is removed .
229,019
def mark_as_forwarded ( self , req : Request , to : int ) : self [ req . key ] . forwarded = True self [ req . key ] . forwardedTo = to self [ req . key ] . unordered_by_replicas_num = to
Works together with mark_as_executed and free methods .
229,020
def add_propagate ( self , req : Request , sender : str ) : data = self . add ( req ) data . propagates [ sender ] = req
Add the specified request to the list of received PROPAGATEs .
229,021
def votes ( self , req ) -> int : try : votes = len ( self [ req . key ] . propagates ) except KeyError : votes = 0 return votes
Get the number of propagates for a given reqId and identifier .
229,022
def mark_as_executed ( self , req : Request ) : state = self [ req . key ] state . executed = True self . _clean ( state )
Works together with mark_as_forwarded and free methods .
229,023
def free ( self , request_key ) : state = self . get ( request_key ) if not state : return state . forwardedTo -= 1 self . _clean ( state )
Works together with mark_as_forwarded and mark_as_executed methods .
229,024
def has_propagated ( self , req : Request , sender : str ) -> bool : return req . key in self and sender in self [ req . key ] . propagates
Check whether the request specified has already been propagated .
229,025
def propagate ( self , request : Request , clientName ) : if self . requests . has_propagated ( request , self . name ) : logger . trace ( "{} already propagated {}" . format ( self , request ) ) else : with self . metrics . measure_time ( MetricsName . SEND_PROPAGATE_TIME ) : self . requests . add_propagate ( request ...
Broadcast a PROPAGATE to all other nodes
229,026
def createPropagate ( request : Union [ Request , dict ] , client_name ) -> Propagate : if not isinstance ( request , ( Request , dict ) ) : logger . error ( "{}Request not formatted properly to create propagate" . format ( THREE_PC_PREFIX ) ) return logger . trace ( "Creating PROPAGATE for REQUEST {}" . format ( reque...
Create a new PROPAGATE for the given REQUEST .
229,027
def forward ( self , request : Request ) : key = request . key num_replicas = self . replicas . num_replicas logger . debug ( '{} forwarding request {} to {} replicas' . format ( self , key , num_replicas ) ) self . replicas . pass_message ( ReqKey ( key ) ) self . monitor . requestUnOrdered ( key ) self . requests . m...
Forward the specified client REQUEST to the other replicas on this node
229,028
def recordAndPropagate ( self , request : Request , clientName ) : self . requests . add ( request ) self . propagate ( request , clientName ) self . tryForwarding ( request )
Record the request in the list of requests and propagate .
229,029
def tryForwarding ( self , request : Request ) : cannot_reason_msg = self . canForward ( request ) if cannot_reason_msg is None : self . forward ( request ) else : logger . trace ( "{} not forwarding request {} to its replicas " "since {}" . format ( self , request , cannot_reason_msg ) )
Try to forward the request if the required conditions are met . See the method canForward for the conditions to check before forwarding a request .
229,030
def removeRemote ( self , remote : Remote , clear = True ) : name = remote . name pkey = remote . publicKey vkey = remote . verKey if name in self . remotes : self . remotes . pop ( name ) self . remotesByKeys . pop ( pkey , None ) self . verifiers . pop ( vkey , None ) else : logger . info ( 'No remote named {} presen...
Currently not using clear
229,031
async def service ( self , limit = None , quota : Optional [ Quota ] = None ) -> int : if self . listener : await self . _serviceStack ( self . age , quota ) else : logger . info ( "{} is stopped" . format ( self ) ) r = len ( self . rxMsgs ) if r > 0 : pracLimit = limit if limit else sys . maxsize return self . proces...
Service limit number of received messages in this stack .
229,032
def connect ( self , name = None , remoteId = None , ha = None , verKeyRaw = None , publicKeyRaw = None ) : if not name : raise ValueError ( 'Remote name should be specified' ) publicKey = None if name in self . remotes : remote = self . remotes [ name ] else : publicKey = z85 . encode ( publicKeyRaw ) if publicKeyRaw ...
Connect to the node specified by name .
229,033
def reconnectRemote ( self , remote ) : if not isinstance ( remote , Remote ) : raise PlenumTypeError ( 'remote' , remote , Remote ) logger . info ( '{} reconnecting to {}' . format ( self , remote ) ) public , secret = self . selfEncKeys remote . disconnect ( ) remote . connect ( self . ctx , public , secret ) self . ...
Disconnect remote and connect to it again
229,034
def _readMultiple ( self , start , end , db ) : self . _validatePos ( start , end ) return [ bytes ( db . get ( str ( pos ) ) ) for pos in range ( start , end + 1 ) ]
Returns a list of hashes with serial numbers between start and end both inclusive .
229,035
def pack_nibbles ( nibbles ) : if nibbles [ - 1 ] == NIBBLE_TERMINATOR : flags = 2 nibbles = nibbles [ : - 1 ] else : flags = 0 oddlen = len ( nibbles ) % 2 flags |= oddlen if oddlen : nibbles = [ flags ] + nibbles else : nibbles = [ flags , 0 ] + nibbles o = b'' for i in range ( 0 , len ( nibbles ) , 2 ) : o += ascii_...
pack nibbles to binary
229,036
def _get_last_node_for_prfx ( self , node , key_prfx , seen_prfx ) : node_type = self . _get_node_type ( node ) if node_type == NODE_TYPE_BLANK : return BLANK_NODE if node_type == NODE_TYPE_BRANCH : if not key_prfx : return node sub_node = self . _decode_to_node ( node [ key_prfx [ 0 ] ] ) seen_prfx . append ( key_prfx...
get last node for the given prefix also update seen_prfx to track the path already traversed
229,037
def metrics ( self ) : masterThrp , backupThrp = self . getThroughputs ( self . instances . masterId ) r = self . instance_throughput_ratio ( self . instances . masterId ) m = [ ( "{} Monitor metrics:" . format ( self ) , None ) , ( "Delta" , self . Delta ) , ( "Lambda" , self . Lambda ) , ( "Omega" , self . Omega ) , ...
Calculate and return the metrics .
229,038
def prettymetrics ( self ) -> str : rendered = [ "{}: {}" . format ( * m ) for m in self . metrics ( ) ] return "\n " . join ( rendered )
Pretty printing for metrics
229,039
def reset ( self ) : logger . debug ( "{}'s Monitor being reset" . format ( self ) ) instances_ids = self . instances . started . keys ( ) self . numOrderedRequests = { inst_id : ( 0 , 0 ) for inst_id in instances_ids } self . requestTracker . reset ( ) self . masterReqLatencies = { } self . masterReqLatencyTooHigh = F...
Reset the monitor . Sets all monitored values to defaults .
229,040
def addInstance ( self , inst_id ) : self . instances . add ( inst_id ) self . requestTracker . add_instance ( inst_id ) self . numOrderedRequests [ inst_id ] = ( 0 , 0 ) rm = self . create_throughput_measurement ( self . config ) self . throughputs [ inst_id ] = rm lm = self . latency_measurement_cls ( self . config )...
Add one protocol instance for monitoring .
229,041
def requestOrdered ( self , reqIdrs : List [ str ] , instId : int , requests , byMaster : bool = False ) -> Dict : now = time . perf_counter ( ) if self . acc_monitor : self . acc_monitor . update_time ( now ) durations = { } for key in reqIdrs : if key not in self . requestTracker : logger . debug ( "Got untracked ord...
Measure the time taken for ordering of a request and return it . Monitor might have been reset due to view change due to which this method returns None
229,042
def requestUnOrdered ( self , key : str ) : now = time . perf_counter ( ) if self . acc_monitor : self . acc_monitor . update_time ( now ) self . acc_monitor . request_received ( key ) self . requestTracker . start ( key , now )
Record the time at which request ordering started .
229,043
def isMasterDegraded ( self ) : if self . acc_monitor : self . acc_monitor . update_time ( time . perf_counter ( ) ) return self . acc_monitor . is_master_degraded ( ) else : return ( self . instances . masterId is not None and ( self . isMasterThroughputTooLow ( ) or self . isMasterAvgReqLatencyTooHigh ( ) ) )
Return whether the master instance is slow .
229,044
def areBackupsDegraded ( self ) : slow_instances = [ ] if self . acc_monitor : for instance in self . instances . backupIds : if self . acc_monitor . is_instance_degraded ( instance ) : slow_instances . append ( instance ) else : for instance in self . instances . backupIds : if self . is_instance_throughput_too_low ( ...
Return slow instance .
229,045
def instance_throughput_ratio ( self , inst_id ) : inst_thrp , otherThrp = self . getThroughputs ( inst_id ) r = inst_thrp / otherThrp if otherThrp and inst_thrp is not None else None return r
The relative throughput of an instance compared to the backup instances .
229,046
def is_instance_throughput_too_low ( self , inst_id ) : r = self . instance_throughput_ratio ( inst_id ) if r is None : logger . debug ( "{} instance {} throughput is not " "measurable." . format ( self , inst_id ) ) return None too_low = r < self . Delta if too_low : logger . display ( "{}{} instance {} throughput rat...
Return whether the throughput of the master instance is greater than the acceptable threshold
229,047
def isMasterReqLatencyTooHigh ( self ) : r = self . masterReqLatencyTooHigh or next ( ( ( key , lat ) for key , lat in self . masterReqLatencies . items ( ) if lat > self . Lambda ) , None ) if r : logger . display ( "{}{} found master's latency {} to be higher than the threshold for request {}." . format ( MONITORING_...
Return whether the request latency of the master instance is greater than the acceptable threshold
229,048
def is_instance_avg_req_latency_too_high ( self , inst_id ) : avg_lat , avg_lat_others = self . getLatencies ( ) if not avg_lat or not avg_lat_others : return False d = avg_lat - avg_lat_others if d < self . Omega : return False if inst_id == self . instances . masterId : logger . info ( "{}{} found difference between ...
Return whether the average request latency of an instance is greater than the acceptable threshold
229,049
def getThroughputs ( self , desired_inst_id : int ) : instance_thrp = self . getThroughput ( desired_inst_id ) totalReqs , totalTm = self . getInstanceMetrics ( forAllExcept = desired_inst_id ) if len ( self . throughputs ) > 1 : thrs = [ ] for inst_id , thr_obj in self . throughputs . items ( ) : if inst_id == desired...
Return a tuple of the throughput of the given instance and the average throughput of the remaining instances .
229,050
def getThroughput ( self , instId : int ) -> float : if instId not in self . instances . ids : return None perf_time = time . perf_counter ( ) throughput = self . throughputs [ instId ] . get_throughput ( perf_time ) return throughput
Return the throughput of the specified instance .
229,051
def getInstanceMetrics ( self , forAllExcept : int ) -> Tuple [ Optional [ int ] , Optional [ float ] ] : m = [ ( reqs , tm ) for i , ( reqs , tm ) in self . numOrderedRequests . items ( ) if i != forAllExcept ] if m : reqs , tm = zip ( * m ) return sum ( reqs ) , sum ( tm ) else : return None , None
Calculate and return the average throughput of all the instances except the one specified as forAllExcept .
229,052
def getLatency ( self , instId : int ) -> float : if len ( self . clientAvgReqLatencies ) == 0 : return 0.0 return self . clientAvgReqLatencies [ instId ] . get_avg_latency ( )
Return a dict with client identifier as a key and calculated latency as a value
229,053
def _enqueue ( self , msg : Any , rid : int , signer : Signer ) -> None : if rid not in self . outBoxes : self . outBoxes [ rid ] = deque ( ) self . outBoxes [ rid ] . append ( msg )
Enqueue the message into the remote s queue .
229,054
def _enqueueIntoAllRemotes ( self , msg : Any , signer : Signer ) -> None : for rid in self . remotes . keys ( ) : self . _enqueue ( msg , rid , signer )
Enqueue the specified message into all the remotes in the nodestack .
229,055
def send ( self , msg : Any , * rids : Iterable [ int ] , signer : Signer = None , message_splitter = None ) -> None : message_parts , err_msg = self . prepare_for_sending ( msg , signer , message_splitter ) if err_msg is not None : return False , err_msg if rids : for r in rids : for part in message_parts : self . _en...
Enqueue the given message into the outBoxes of the specified remotes or into the outBoxes of all the remotes if rids is None
229,056
def flushOutBoxes ( self ) -> None : removedRemotes = [ ] for rid , msgs in self . outBoxes . items ( ) : try : dest = self . remotes [ rid ] . name except KeyError : removedRemotes . append ( rid ) continue if msgs : if self . _should_batch ( msgs ) : logger . trace ( "{} batching {} msgs to {} into fewer transmission...
Clear the outBoxes and transmit batched messages to remotes .
229,057
async def prodAllOnce ( self ) : limit = None s = 0 for n in self . prodables : s += await n . prod ( limit ) return s
Call prod once for each Prodable in this Looper
229,058
def add ( self , prodable : Prodable ) -> None : if prodable . name in [ p . name for p in self . prodables ] : raise ProdableAlreadyAdded ( "Prodable {} already added." . format ( prodable . name ) ) self . prodables . append ( prodable ) if self . autoStart : prodable . start ( self . loop )
Add one Prodable object to this Looper s list of Prodables
229,059
def removeProdable ( self , prodable : Prodable = None , name : str = None ) -> Optional [ Prodable ] : if prodable : self . prodables . remove ( prodable ) return prodable elif name : for p in self . prodables : if hasattr ( p , "name" ) and getattr ( p , "name" ) == name : prodable = p break if prodable : self . prod...
Remove the specified Prodable object from this Looper s list of Prodables
229,060
async def runOnceNicely ( self ) : start = time . perf_counter ( ) msgsProcessed = await self . prodAllOnce ( ) if msgsProcessed == 0 : await asyncio . sleep ( 0.01 , loop = self . loop ) dur = time . perf_counter ( ) - start if dur >= 15 : logger . info ( "it took {:.3f} seconds to run once nicely" . format ( dur ) , ...
Execute runOnce with a small tolerance of 0 . 01 seconds so that the Prodables can complete their other asynchronous tasks not running on the event - loop .
229,061
def run ( self , * coros : CoroWrapper ) : if not self . running : raise RuntimeError ( "not running!" ) async def wrapper ( ) : results = [ ] for coro in coros : try : if inspect . isawaitable ( coro ) : results . append ( await coro ) elif inspect . isfunction ( coro ) : res = coro ( ) if inspect . isawaitable ( res ...
Runs an arbitrary list of coroutines in order and then quits the loop if not running as a context manager .
229,062
async def shutdown ( self ) : logger . display ( "Looper shutting down now..." , extra = { "cli" : False } ) self . running = False start = time . perf_counter ( ) if not self . runFut . done ( ) : await self . runFut self . stopall ( ) logger . display ( "Looper shut down in {:.3f} seconds." . format ( time . perf_cou...
Shut down this Looper .
229,063
def create_default_bls_bft_factory ( node ) : bls_keys_dir = os . path . join ( node . keys_dir , node . name ) bls_crypto_factory = create_default_bls_crypto_factory ( bls_keys_dir ) return BlsFactoryBftPlenum ( bls_crypto_factory , node )
Creates a default BLS factory to instantiate BLS BFT classes .
229,064
def sign ( self , message , encoder = encoding . RawEncoder ) : raw_signed = libnacl . crypto_sign ( message , self . _signing_key ) signature = encoder . encode ( raw_signed [ : libnacl . crypto_sign_BYTES ] ) message = encoder . encode ( raw_signed [ libnacl . crypto_sign_BYTES : ] ) signed = encoder . encode ( raw_s...
Sign a message using this key .
229,065
def verify ( self , signature , msg ) : if not self . key : return False try : self . key . verify ( signature + msg ) except ValueError : return False return True
Verify the message
229,066
def encrypt ( self , plaintext , nonce , encoder = encoding . RawEncoder ) : if len ( nonce ) != self . NONCE_SIZE : raise ValueError ( "The nonce must be exactly %s bytes long" % self . NONCE_SIZE ) ciphertext = libnacl . crypto_box_afternm ( plaintext , nonce , self . _shared_key , ) encoded_nonce = encoder . encode ...
Encrypts the plaintext message using the given nonce and returns the ciphertext encoded with the encoder .
229,067
def decrypt ( self , ciphertext , nonce = None , encoder = encoding . RawEncoder ) : ciphertext = encoder . decode ( ciphertext ) if nonce is None : nonce = ciphertext [ : self . NONCE_SIZE ] ciphertext = ciphertext [ self . NONCE_SIZE : ] if len ( nonce ) != self . NONCE_SIZE : raise ValueError ( "The nonce must be ex...
Decrypts the ciphertext using the given nonce and returns the plaintext message .
229,068
def decrypt ( self , cipher , nonce , pubkey , dehex = False ) : if not isinstance ( pubkey , PublicKey ) : if len ( pubkey ) == 32 : pubkey = PublicKey ( pubkey , encoding . RawEncoder ) else : pubkey = PublicKey ( pubkey , encoding . HexEncoder ) box = Box ( self . key , pubkey ) decoder = encoding . HexEncoder if de...
Return decrypted msg contained in cypher using nonce and shared key generated from . key and pubkey . If pubkey is hex encoded it is converted first If dehex is True then use HexEncoder otherwise use RawEncoder
229,069
def getInstalledConfig ( installDir , configFile ) : configPath = os . path . join ( installDir , configFile ) if not os . path . exists ( configPath ) : raise FileNotFoundError ( "No file found at location {}" . format ( configPath ) ) spec = spec_from_file_location ( configFile , configPath ) config = module_from_spe...
Reads config from the installation directory of Plenum .
229,070
def _getConfig ( general_config_dir : str = None ) : stp_config = STPConfig ( ) plenum_config = import_module ( "plenum.config" ) config = stp_config config . __dict__ . update ( plenum_config . __dict__ ) if general_config_dir : config . GENERAL_CONFIG_DIR = general_config_dir if not config . GENERAL_CONFIG_DIR : rais...
Reads a file called config . py in the project directory
229,071
def getFunc ( self , o : Any ) -> Callable : for cls , func in self . routes . items ( ) : if isinstance ( o , cls ) : return func logger . error ( "Unhandled msg {}, available handlers are:" . format ( o ) ) for cls in self . routes . keys ( ) : logger . error ( " {}" . format ( cls ) ) raise RuntimeError ( "unhandl...
Get the next function from the list of routes that is capable of processing o s type .
229,072
def handleSync ( self , msg : Any ) -> Any : if isinstance ( msg , tuple ) and len ( msg ) == 2 and not hasattr ( msg , '_field_types' ) : return self . getFunc ( msg [ 0 ] ) ( * msg ) else : return self . getFunc ( msg ) ( msg )
Pass the message as an argument to the function defined in routes . If the msg is a tuple pass the values as multiple arguments to the function .
229,073
async def handle ( self , msg : Any ) -> Any : res = self . handleSync ( msg ) if isawaitable ( res ) : return await res else : return res
Handle both sync and async functions .
229,074
async def handleAll ( self , deq : deque , limit = None ) -> int : count = 0 while deq and ( not limit or count < limit ) : count += 1 item = deq . popleft ( ) await self . handle ( item ) return count
Handle all items in a deque . Can call asynchronous handlers .
229,075
def handleAllSync ( self , deq : deque , limit = None ) -> int : count = 0 while deq and ( not limit or count < limit ) : count += 1 msg = deq . popleft ( ) self . handleSync ( msg ) return count
Synchronously handle all items in a deque .
229,076
def load ( self , other : merkle_tree . MerkleTree ) : self . _update ( other . tree_size , other . hashes )
Load this tree from a dumb data object for serialisation .
229,077
def save ( self , other : merkle_tree . MerkleTree ) : other . __tree_size = self . __tree_size other . __hashes = self . __hashes
Save this tree into a dumb data object for serialisation .
229,078
def append ( self , new_leaf : bytes ) -> List [ bytes ] : auditPath = list ( reversed ( self . __hashes ) ) self . _push_subtree ( [ new_leaf ] ) return auditPath
Append a new leaf onto the end of this tree and return the audit path
229,079
def extend ( self , new_leaves : List [ bytes ] ) : size = len ( new_leaves ) final_size = self . tree_size + size idx = 0 while True : max_h = self . __mintree_height max_size = 1 << ( max_h - 1 ) if max_h > 0 else 0 if max_h > 0 and size - idx >= max_size : self . _push_subtree ( new_leaves [ idx : idx + max_size ] )...
Extend this tree with new_leaves on the end .
229,080
def extended ( self , new_leaves : List [ bytes ] ) : new_tree = self . __copy__ ( ) new_tree . extend ( new_leaves ) return new_tree
Returns a new tree equal to this tree extended with new_leaves .
229,081
def verify_consistency ( self , expected_leaf_count ) -> bool : if expected_leaf_count != self . leafCount : raise ConsistencyVerificationFailed ( ) if self . get_expected_node_count ( self . leafCount ) != self . nodeCount : raise ConsistencyVerificationFailed ( ) return True
Check that the tree has same leaf count as expected and the number of nodes are also as expected
229,082
def isHex ( val : str ) -> bool : if isinstance ( val , bytes ) : try : val = val . decode ( ) except ValueError : return False return isinstance ( val , str ) and all ( c in string . hexdigits for c in val )
Return whether the given str represents a hex value or not
229,083
def _accumulate ( self , old_accum , next_val ) : return old_accum * ( 1 - self . alpha ) + next_val * self . alpha
Implement exponential moving average
229,084
def getNodePosition ( cls , start , height = None ) -> int : pwr = highest_bit_set ( start ) - 1 height = height or pwr if count_bits_set ( start ) == 1 : adj = height - pwr return start - 1 + adj else : c = pow ( 2 , pwr ) return cls . getNodePosition ( c , pwr ) + cls . getNodePosition ( start - c , height )
Calculates node position based on start and height
229,085
def getPath ( cls , seqNo , offset = 0 ) : if offset >= seqNo : raise ValueError ( "Offset should be less than serial number" ) pwr = highest_bit_set ( seqNo - 1 - offset ) - 1 if pwr <= 0 : if seqNo % 2 == 0 : return [ seqNo - 1 ] , [ ] else : return [ ] , [ ] c = pow ( 2 , pwr ) + offset leafs , nodes = cls . getPath...
Get the audit path of the leaf at the position specified by serNo .
229,086
def readNodeByTree ( self , start , height = None ) : pos = self . getNodePosition ( start , height ) return self . readNode ( pos )
Fetches nodeHash based on start leaf and height of the node in the tree .
229,087
def is_consistent ( self ) -> bool : from ledger . compact_merkle_tree import CompactMerkleTree return self . nodeCount == CompactMerkleTree . get_expected_node_count ( self . leafCount )
Returns True if number of nodes are consistent with number of leaves
229,088
def _startNextChunk ( self ) -> None : if self . currentChunk is None : self . _useLatestChunk ( ) else : self . _useChunk ( self . currentChunkIndex + self . chunkSize )
Close current and start next chunk
229,089
def get ( self , key ) -> str : chunk_no , offset = self . _get_key_location ( key ) with self . _openChunk ( chunk_no ) as chunk : return chunk . get ( str ( offset ) )
Determines the file to retrieve the data from and retrieves the data .
229,090
def reset ( self ) -> None : self . close ( ) for f in os . listdir ( self . dataDir ) : os . remove ( os . path . join ( self . dataDir , f ) ) self . _useLatestChunk ( )
Clear all data in file storage .
229,091
def _listChunks ( self ) : chunks = [ ] for fileName in os . listdir ( self . dataDir ) : index = ChunkedFileStore . _fileNameToChunkIndex ( fileName ) if index is not None : chunks . append ( index ) return sorted ( chunks )
Lists stored chunks
229,092
def filterMsgs ( self , wrappedMsgs : deque ) -> deque : filtered = deque ( ) while wrappedMsgs : wrappedMsg = wrappedMsgs . popleft ( ) msg , sender = wrappedMsg if hasattr ( msg , f . VIEW_NO . nm ) : reqViewNo = getattr ( msg , f . VIEW_NO . nm ) if reqViewNo == self . viewNo : filtered . append ( wrappedMsg ) else ...
Filters messages by view number so that only the messages that have the current view number are retained .
229,093
def get ( self , name ) : try : return self . plugins [ name ] except KeyError : raise RuntimeError ( "plugin {} does not exist" . format ( name ) )
Retrieve a plugin by name .
229,094
def cmp ( cls , v1 : 'VersionBase' , v2 : 'VersionBase' ) -> int : if v1 . _version > v2 . _version : return 1 elif v1 . _version == v2 . _version : return 0 else : return - 1
Compares two instances .
229,095
def maintainConnections ( self , force = False ) : now = time . perf_counter ( ) if now < self . nextCheck and not force : return False self . nextCheck = now + ( self . config . RETRY_TIMEOUT_NOT_RESTRICTED if self . isKeySharing else self . config . RETRY_TIMEOUT_RESTRICTED ) missing = self . connectToMissing ( ) sel...
Ensure appropriate connections .
229,096
def connectToMissing ( self ) -> set : missing = self . reconcileNodeReg ( ) if not missing : return missing logger . info ( "{}{} found the following missing connections: {}" . format ( CONNECTION_PREFIX , self , ", " . join ( missing ) ) ) for name in missing : try : self . connect ( name , ha = self . registry [ nam...
Try to connect to the missing nodes
229,097
def emit ( self , record ) : 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 and record . levelno >= logging . INFO : should_cb = True if hasattr ( record , 'tags' ) : for t in record . tags : if ...
Passes the log record back to the CLI for rendering
229,098
def conns ( self , value : Set [ str ] ) -> None : if not self . _conns == value : old = self . _conns self . _conns = value ins = value - old outs = old - value logger . display ( "{}'s connections changed from {} to {}" . format ( self , old , value ) ) self . _connsChanged ( ins , outs )
Updates the connection count of this node if not already done .
229,099
def findInNodeRegByHA ( self , remoteHa ) : regName = [ nm for nm , ha in self . registry . items ( ) if self . sameAddr ( ha , remoteHa ) ] if len ( regName ) > 1 : raise RuntimeError ( "more than one node registry entry with the " "same ha {}: {}" . format ( remoteHa , regName ) ) if regName : return regName [ 0 ] re...
Returns the name of the remote by HA if found in the node registry else returns None