id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
248,000 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.prettymetrics | def prettymetrics(self) -> str:
"""
Pretty printing for metrics
"""
rendered = ["{}: {}".format(*m) for m in self.metrics()]
return "\n ".join(rendered) | python | def prettymetrics(self) -> str:
rendered = ["{}: {}".format(*m) for m in self.metrics()]
return "\n ".join(rendered) | [
"def",
"prettymetrics",
"(",
"self",
")",
"->",
"str",
":",
"rendered",
"=",
"[",
"\"{}: {}\"",
".",
"format",
"(",
"*",
"m",
")",
"for",
"m",
"in",
"self",
".",
"metrics",
"(",
")",
"]",
"return",
"\"\\n \"",
".",
"join",
"(",
"rendered",
")"
] | Pretty printing for metrics | [
"Pretty",
"printing",
"for",
"metrics"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L284-L289 |
248,001 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.reset | def reset(self):
"""
Reset the monitor. Sets all monitored values to defaults.
"""
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 = False
self.totalViewChanges += 1
self.lastKnownTraffic = self.calculateTraffic()
if self.acc_monitor:
self.acc_monitor.reset()
for i in instances_ids:
rm = self.create_throughput_measurement(self.config)
self.throughputs[i] = rm
lm = self.latency_measurement_cls(self.config)
self.clientAvgReqLatencies[i] = lm | python | 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 = False
self.totalViewChanges += 1
self.lastKnownTraffic = self.calculateTraffic()
if self.acc_monitor:
self.acc_monitor.reset()
for i in instances_ids:
rm = self.create_throughput_measurement(self.config)
self.throughputs[i] = rm
lm = self.latency_measurement_cls(self.config)
self.clientAvgReqLatencies[i] = lm | [
"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",
"=",
"False",
"self",
".",
"totalViewChanges",
"+=",
"1",
"self",
".",
"lastKnownTraffic",
"=",
"self",
".",
"calculateTraffic",
"(",
")",
"if",
"self",
".",
"acc_monitor",
":",
"self",
".",
"acc_monitor",
".",
"reset",
"(",
")",
"for",
"i",
"in",
"instances_ids",
":",
"rm",
"=",
"self",
".",
"create_throughput_measurement",
"(",
"self",
".",
"config",
")",
"self",
".",
"throughputs",
"[",
"i",
"]",
"=",
"rm",
"lm",
"=",
"self",
".",
"latency_measurement_cls",
"(",
"self",
".",
"config",
")",
"self",
".",
"clientAvgReqLatencies",
"[",
"i",
"]",
"=",
"lm"
] | Reset the monitor. Sets all monitored values to defaults. | [
"Reset",
"the",
"monitor",
".",
"Sets",
"all",
"monitored",
"values",
"to",
"defaults",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L308-L326 |
248,002 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.addInstance | def addInstance(self, inst_id):
"""
Add one protocol instance for monitoring.
"""
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)
self.clientAvgReqLatencies[inst_id] = lm
if self.acc_monitor:
self.acc_monitor.add_instance(inst_id) | python | 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)
self.clientAvgReqLatencies[inst_id] = lm
if self.acc_monitor:
self.acc_monitor.add_instance(inst_id) | [
"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",
")",
"self",
".",
"clientAvgReqLatencies",
"[",
"inst_id",
"]",
"=",
"lm",
"if",
"self",
".",
"acc_monitor",
":",
"self",
".",
"acc_monitor",
".",
"add_instance",
"(",
"inst_id",
")"
] | Add one protocol instance for monitoring. | [
"Add",
"one",
"protocol",
"instance",
"for",
"monitoring",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L328-L341 |
248,003 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.requestOrdered | def requestOrdered(self, reqIdrs: List[str], instId: int,
requests, byMaster: bool = False) -> Dict:
"""
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
"""
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 ordered request with digest {}".
format(key))
continue
if self.acc_monitor:
self.acc_monitor.request_ordered(key, instId)
if key in self.requestTracker.handled_unordered():
started = self.requestTracker.started(key)
logger.info('Consensus for ReqId: {} was achieved by {}:{} in {} seconds.'
.format(key, self.name, instId, now - started))
duration = self.requestTracker.order(instId, key, now)
self.throughputs[instId].add_request(now)
if key in requests:
identifier = requests[key].request.identifier
self.clientAvgReqLatencies[instId].add_duration(identifier, duration)
durations[key] = duration
reqs, tm = self.numOrderedRequests[instId]
orderedNow = len(durations)
self.numOrderedRequests[instId] = (reqs + orderedNow,
tm + sum(durations.values()))
# TODO: Inefficient, as on every request a minimum of a large list is
# calculated
if min(r[0] for r in self.numOrderedRequests.values()) == (reqs + orderedNow):
# If these requests is ordered by the last instance then increment
# total requests, but why is this important, why cant is ordering
# by master not enough?
self.totalRequests += orderedNow
self.postOnReqOrdered()
if 0 == reqs:
self.postOnNodeStarted(self.started)
return durations | python | 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 ordered request with digest {}".
format(key))
continue
if self.acc_monitor:
self.acc_monitor.request_ordered(key, instId)
if key in self.requestTracker.handled_unordered():
started = self.requestTracker.started(key)
logger.info('Consensus for ReqId: {} was achieved by {}:{} in {} seconds.'
.format(key, self.name, instId, now - started))
duration = self.requestTracker.order(instId, key, now)
self.throughputs[instId].add_request(now)
if key in requests:
identifier = requests[key].request.identifier
self.clientAvgReqLatencies[instId].add_duration(identifier, duration)
durations[key] = duration
reqs, tm = self.numOrderedRequests[instId]
orderedNow = len(durations)
self.numOrderedRequests[instId] = (reqs + orderedNow,
tm + sum(durations.values()))
# TODO: Inefficient, as on every request a minimum of a large list is
# calculated
if min(r[0] for r in self.numOrderedRequests.values()) == (reqs + orderedNow):
# If these requests is ordered by the last instance then increment
# total requests, but why is this important, why cant is ordering
# by master not enough?
self.totalRequests += orderedNow
self.postOnReqOrdered()
if 0 == reqs:
self.postOnNodeStarted(self.started)
return durations | [
"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 ordered request with digest {}\"",
".",
"format",
"(",
"key",
")",
")",
"continue",
"if",
"self",
".",
"acc_monitor",
":",
"self",
".",
"acc_monitor",
".",
"request_ordered",
"(",
"key",
",",
"instId",
")",
"if",
"key",
"in",
"self",
".",
"requestTracker",
".",
"handled_unordered",
"(",
")",
":",
"started",
"=",
"self",
".",
"requestTracker",
".",
"started",
"(",
"key",
")",
"logger",
".",
"info",
"(",
"'Consensus for ReqId: {} was achieved by {}:{} in {} seconds.'",
".",
"format",
"(",
"key",
",",
"self",
".",
"name",
",",
"instId",
",",
"now",
"-",
"started",
")",
")",
"duration",
"=",
"self",
".",
"requestTracker",
".",
"order",
"(",
"instId",
",",
"key",
",",
"now",
")",
"self",
".",
"throughputs",
"[",
"instId",
"]",
".",
"add_request",
"(",
"now",
")",
"if",
"key",
"in",
"requests",
":",
"identifier",
"=",
"requests",
"[",
"key",
"]",
".",
"request",
".",
"identifier",
"self",
".",
"clientAvgReqLatencies",
"[",
"instId",
"]",
".",
"add_duration",
"(",
"identifier",
",",
"duration",
")",
"durations",
"[",
"key",
"]",
"=",
"duration",
"reqs",
",",
"tm",
"=",
"self",
".",
"numOrderedRequests",
"[",
"instId",
"]",
"orderedNow",
"=",
"len",
"(",
"durations",
")",
"self",
".",
"numOrderedRequests",
"[",
"instId",
"]",
"=",
"(",
"reqs",
"+",
"orderedNow",
",",
"tm",
"+",
"sum",
"(",
"durations",
".",
"values",
"(",
")",
")",
")",
"# TODO: Inefficient, as on every request a minimum of a large list is",
"# calculated",
"if",
"min",
"(",
"r",
"[",
"0",
"]",
"for",
"r",
"in",
"self",
".",
"numOrderedRequests",
".",
"values",
"(",
")",
")",
"==",
"(",
"reqs",
"+",
"orderedNow",
")",
":",
"# If these requests is ordered by the last instance then increment",
"# total requests, but why is this important, why cant is ordering",
"# by master not enough?",
"self",
".",
"totalRequests",
"+=",
"orderedNow",
"self",
".",
"postOnReqOrdered",
"(",
")",
"if",
"0",
"==",
"reqs",
":",
"self",
".",
"postOnNodeStarted",
"(",
"self",
".",
"started",
")",
"return",
"durations"
] | 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 | [
"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"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L353-L400 |
248,004 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.requestUnOrdered | def requestUnOrdered(self, key: str):
"""
Record the time at which request ordering started.
"""
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) | python | 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) | [
"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. | [
"Record",
"the",
"time",
"at",
"which",
"request",
"ordering",
"started",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L402-L410 |
248,005 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.isMasterDegraded | def isMasterDegraded(self):
"""
Return whether the master instance is slow.
"""
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
# TODO for now, view_change procedure can take more that 15 minutes
# (5 minutes for catchup and 10 minutes for primary's answer).
# Therefore, view_change triggering by max latency now is not indicative.
# self.isMasterReqLatencyTooHigh() or
self.isMasterAvgReqLatencyTooHigh())) | python | 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
# TODO for now, view_change procedure can take more that 15 minutes
# (5 minutes for catchup and 10 minutes for primary's answer).
# Therefore, view_change triggering by max latency now is not indicative.
# self.isMasterReqLatencyTooHigh() or
self.isMasterAvgReqLatencyTooHigh())) | [
"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",
"# TODO for now, view_change procedure can take more that 15 minutes",
"# (5 minutes for catchup and 10 minutes for primary's answer).",
"# Therefore, view_change triggering by max latency now is not indicative.",
"# self.isMasterReqLatencyTooHigh() or",
"self",
".",
"isMasterAvgReqLatencyTooHigh",
"(",
")",
")",
")"
] | Return whether the master instance is slow. | [
"Return",
"whether",
"the",
"master",
"instance",
"is",
"slow",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L425-L439 |
248,006 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.areBackupsDegraded | def areBackupsDegraded(self):
"""
Return slow instance.
"""
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(instance):
slow_instances.append(instance)
return slow_instances | python | 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(instance):
slow_instances.append(instance)
return slow_instances | [
"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",
"(",
"instance",
")",
":",
"slow_instances",
".",
"append",
"(",
"instance",
")",
"return",
"slow_instances"
] | Return slow instance. | [
"Return",
"slow",
"instance",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L441-L454 |
248,007 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.instance_throughput_ratio | def instance_throughput_ratio(self, inst_id):
"""
The relative throughput of an instance compared to the backup
instances.
"""
inst_thrp, otherThrp = self.getThroughputs(inst_id)
# Backup throughput may be 0 so moving ahead only if it is not 0
r = inst_thrp / otherThrp if otherThrp and inst_thrp is not None \
else None
return r | python | def instance_throughput_ratio(self, inst_id):
inst_thrp, otherThrp = self.getThroughputs(inst_id)
# Backup throughput may be 0 so moving ahead only if it is not 0
r = inst_thrp / otherThrp if otherThrp and inst_thrp is not None \
else None
return r | [
"def",
"instance_throughput_ratio",
"(",
"self",
",",
"inst_id",
")",
":",
"inst_thrp",
",",
"otherThrp",
"=",
"self",
".",
"getThroughputs",
"(",
"inst_id",
")",
"# Backup throughput may be 0 so moving ahead only if it is not 0",
"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. | [
"The",
"relative",
"throughput",
"of",
"an",
"instance",
"compared",
"to",
"the",
"backup",
"instances",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L456-L466 |
248,008 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.is_instance_throughput_too_low | def is_instance_throughput_too_low(self, inst_id):
"""
Return whether the throughput of the master instance is greater than the
acceptable threshold
"""
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 ratio {} is lower than Delta {}.".
format(MONITORING_PREFIX, self, inst_id, r, self.Delta))
else:
logger.trace("{} instance {} throughput ratio {} is acceptable.".
format(self, inst_id, r))
return too_low | python | 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 ratio {} is lower than Delta {}.".
format(MONITORING_PREFIX, self, inst_id, r, self.Delta))
else:
logger.trace("{} instance {} throughput ratio {} is acceptable.".
format(self, inst_id, r))
return too_low | [
"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 ratio {} is lower than Delta {}.\"",
".",
"format",
"(",
"MONITORING_PREFIX",
",",
"self",
",",
"inst_id",
",",
"r",
",",
"self",
".",
"Delta",
")",
")",
"else",
":",
"logger",
".",
"trace",
"(",
"\"{} instance {} throughput ratio {} is acceptable.\"",
".",
"format",
"(",
"self",
",",
"inst_id",
",",
"r",
")",
")",
"return",
"too_low"
] | Return whether the throughput of the master instance is greater than the
acceptable threshold | [
"Return",
"whether",
"the",
"throughput",
"of",
"the",
"master",
"instance",
"is",
"greater",
"than",
"the",
"acceptable",
"threshold"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L475-L492 |
248,009 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.isMasterReqLatencyTooHigh | def isMasterReqLatencyTooHigh(self):
"""
Return whether the request latency of the master instance is greater
than the acceptable threshold
"""
# TODO for now, view_change procedure can take more that 15 minutes
# (5 minutes for catchup and 10 minutes for primary's answer).
# Therefore, view_change triggering by max latency is not indicative now.
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_PREFIX, self, r[1], r[0]))
else:
logger.trace("{} found master's latency to be lower than the "
"threshold for all requests.".format(self))
return r | python | def isMasterReqLatencyTooHigh(self):
# TODO for now, view_change procedure can take more that 15 minutes
# (5 minutes for catchup and 10 minutes for primary's answer).
# Therefore, view_change triggering by max latency is not indicative now.
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_PREFIX, self, r[1], r[0]))
else:
logger.trace("{} found master's latency to be lower than the "
"threshold for all requests.".format(self))
return r | [
"def",
"isMasterReqLatencyTooHigh",
"(",
"self",
")",
":",
"# TODO for now, view_change procedure can take more that 15 minutes",
"# (5 minutes for catchup and 10 minutes for primary's answer).",
"# Therefore, view_change triggering by max latency is not indicative now.",
"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_PREFIX",
",",
"self",
",",
"r",
"[",
"1",
"]",
",",
"r",
"[",
"0",
"]",
")",
")",
"else",
":",
"logger",
".",
"trace",
"(",
"\"{} found master's latency to be lower than the \"",
"\"threshold for all requests.\"",
".",
"format",
"(",
"self",
")",
")",
"return",
"r"
] | Return whether the request latency of the master instance is greater
than the acceptable threshold | [
"Return",
"whether",
"the",
"request",
"latency",
"of",
"the",
"master",
"instance",
"is",
"greater",
"than",
"the",
"acceptable",
"threshold"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L494-L512 |
248,010 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.is_instance_avg_req_latency_too_high | def is_instance_avg_req_latency_too_high(self, inst_id):
"""
Return whether the average request latency of an instance is
greater than the acceptable threshold
"""
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 master's and "
"backups's avg latency {} to be higher than the "
"threshold".format(MONITORING_PREFIX, self, d))
logger.trace(
"{}'s master's avg request latency is {} and backup's "
"avg request latency is {}".format(self, avg_lat, avg_lat_others))
return True | python | 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 master's and "
"backups's avg latency {} to be higher than the "
"threshold".format(MONITORING_PREFIX, self, d))
logger.trace(
"{}'s master's avg request latency is {} and backup's "
"avg request latency is {}".format(self, avg_lat, avg_lat_others))
return True | [
"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 master's and \"",
"\"backups's avg latency {} to be higher than the \"",
"\"threshold\"",
".",
"format",
"(",
"MONITORING_PREFIX",
",",
"self",
",",
"d",
")",
")",
"logger",
".",
"trace",
"(",
"\"{}'s master's avg request latency is {} and backup's \"",
"\"avg request latency is {}\"",
".",
"format",
"(",
"self",
",",
"avg_lat",
",",
"avg_lat_others",
")",
")",
"return",
"True"
] | Return whether the average request latency of an instance is
greater than the acceptable threshold | [
"Return",
"whether",
"the",
"average",
"request",
"latency",
"of",
"an",
"instance",
"is",
"greater",
"than",
"the",
"acceptable",
"threshold"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L521-L541 |
248,011 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.getThroughputs | def getThroughputs(self, desired_inst_id: int):
"""
Return a tuple of the throughput of the given instance and the average
throughput of the remaining instances.
:param instId: the id of the protocol instance
"""
instance_thrp = self.getThroughput(desired_inst_id)
totalReqs, totalTm = self.getInstanceMetrics(forAllExcept=desired_inst_id)
# Average backup replica's throughput
if len(self.throughputs) > 1:
thrs = []
for inst_id, thr_obj in self.throughputs.items():
if inst_id == desired_inst_id:
continue
thr = self.getThroughput(inst_id)
if thr is not None:
thrs.append(thr)
if thrs:
if desired_inst_id == self.instances.masterId:
other_thrp = self.throughput_avg_strategy_cls.get_avg(thrs)
else:
other_thrp = self.backup_throughput_avg_strategy_cls.get_avg(thrs)
else:
other_thrp = None
else:
other_thrp = None
if instance_thrp == 0:
if self.numOrderedRequests[desired_inst_id] == (0, 0):
avgReqsPerInst = (totalReqs or 0) / self.instances.count
if avgReqsPerInst <= 1:
# too early to tell if we need an instance change
instance_thrp = None
return instance_thrp, other_thrp | python | def getThroughputs(self, desired_inst_id: int):
instance_thrp = self.getThroughput(desired_inst_id)
totalReqs, totalTm = self.getInstanceMetrics(forAllExcept=desired_inst_id)
# Average backup replica's throughput
if len(self.throughputs) > 1:
thrs = []
for inst_id, thr_obj in self.throughputs.items():
if inst_id == desired_inst_id:
continue
thr = self.getThroughput(inst_id)
if thr is not None:
thrs.append(thr)
if thrs:
if desired_inst_id == self.instances.masterId:
other_thrp = self.throughput_avg_strategy_cls.get_avg(thrs)
else:
other_thrp = self.backup_throughput_avg_strategy_cls.get_avg(thrs)
else:
other_thrp = None
else:
other_thrp = None
if instance_thrp == 0:
if self.numOrderedRequests[desired_inst_id] == (0, 0):
avgReqsPerInst = (totalReqs or 0) / self.instances.count
if avgReqsPerInst <= 1:
# too early to tell if we need an instance change
instance_thrp = None
return instance_thrp, other_thrp | [
"def",
"getThroughputs",
"(",
"self",
",",
"desired_inst_id",
":",
"int",
")",
":",
"instance_thrp",
"=",
"self",
".",
"getThroughput",
"(",
"desired_inst_id",
")",
"totalReqs",
",",
"totalTm",
"=",
"self",
".",
"getInstanceMetrics",
"(",
"forAllExcept",
"=",
"desired_inst_id",
")",
"# Average backup replica's throughput",
"if",
"len",
"(",
"self",
".",
"throughputs",
")",
">",
"1",
":",
"thrs",
"=",
"[",
"]",
"for",
"inst_id",
",",
"thr_obj",
"in",
"self",
".",
"throughputs",
".",
"items",
"(",
")",
":",
"if",
"inst_id",
"==",
"desired_inst_id",
":",
"continue",
"thr",
"=",
"self",
".",
"getThroughput",
"(",
"inst_id",
")",
"if",
"thr",
"is",
"not",
"None",
":",
"thrs",
".",
"append",
"(",
"thr",
")",
"if",
"thrs",
":",
"if",
"desired_inst_id",
"==",
"self",
".",
"instances",
".",
"masterId",
":",
"other_thrp",
"=",
"self",
".",
"throughput_avg_strategy_cls",
".",
"get_avg",
"(",
"thrs",
")",
"else",
":",
"other_thrp",
"=",
"self",
".",
"backup_throughput_avg_strategy_cls",
".",
"get_avg",
"(",
"thrs",
")",
"else",
":",
"other_thrp",
"=",
"None",
"else",
":",
"other_thrp",
"=",
"None",
"if",
"instance_thrp",
"==",
"0",
":",
"if",
"self",
".",
"numOrderedRequests",
"[",
"desired_inst_id",
"]",
"==",
"(",
"0",
",",
"0",
")",
":",
"avgReqsPerInst",
"=",
"(",
"totalReqs",
"or",
"0",
")",
"/",
"self",
".",
"instances",
".",
"count",
"if",
"avgReqsPerInst",
"<=",
"1",
":",
"# too early to tell if we need an instance change",
"instance_thrp",
"=",
"None",
"return",
"instance_thrp",
",",
"other_thrp"
] | Return a tuple of the throughput of the given instance and the average
throughput of the remaining instances.
:param instId: the id of the protocol instance | [
"Return",
"a",
"tuple",
"of",
"the",
"throughput",
"of",
"the",
"given",
"instance",
"and",
"the",
"average",
"throughput",
"of",
"the",
"remaining",
"instances",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L543-L577 |
248,012 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.getThroughput | def getThroughput(self, instId: int) -> float:
"""
Return the throughput of the specified instance.
:param instId: the id of the protocol instance
"""
# We are using the instanceStarted time in the denominator instead of
# a time interval. This is alright for now as all the instances on a
# node are started at almost the same time.
if instId not in self.instances.ids:
return None
perf_time = time.perf_counter()
throughput = self.throughputs[instId].get_throughput(perf_time)
return throughput | python | def getThroughput(self, instId: int) -> float:
# We are using the instanceStarted time in the denominator instead of
# a time interval. This is alright for now as all the instances on a
# node are started at almost the same time.
if instId not in self.instances.ids:
return None
perf_time = time.perf_counter()
throughput = self.throughputs[instId].get_throughput(perf_time)
return throughput | [
"def",
"getThroughput",
"(",
"self",
",",
"instId",
":",
"int",
")",
"->",
"float",
":",
"# We are using the instanceStarted time in the denominator instead of",
"# a time interval. This is alright for now as all the instances on a",
"# node are started at almost the same time.",
"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.
:param instId: the id of the protocol instance | [
"Return",
"the",
"throughput",
"of",
"the",
"specified",
"instance",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L579-L592 |
248,013 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.getInstanceMetrics | def getInstanceMetrics(
self, forAllExcept: int) -> Tuple[Optional[int], Optional[float]]:
"""
Calculate and return the average throughput of all the instances except
the one specified as `forAllExcept`.
"""
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 | python | 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 | [
"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`. | [
"Calculate",
"and",
"return",
"the",
"average",
"throughput",
"of",
"all",
"the",
"instances",
"except",
"the",
"one",
"specified",
"as",
"forAllExcept",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L594-L607 |
248,014 | hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.getLatency | def getLatency(self, instId: int) -> float:
"""
Return a dict with client identifier as a key and calculated latency as a value
"""
if len(self.clientAvgReqLatencies) == 0:
return 0.0
return self.clientAvgReqLatencies[instId].get_avg_latency() | python | def getLatency(self, instId: int) -> float:
if len(self.clientAvgReqLatencies) == 0:
return 0.0
return self.clientAvgReqLatencies[instId].get_avg_latency() | [
"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 | [
"Return",
"a",
"dict",
"with",
"client",
"identifier",
"as",
"a",
"key",
"and",
"calculated",
"latency",
"as",
"a",
"value"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L624-L630 |
248,015 | hyperledger/indy-plenum | plenum/common/batched.py | Batched._enqueue | def _enqueue(self, msg: Any, rid: int, signer: Signer) -> None:
"""
Enqueue the message into the remote's queue.
:param msg: the message to enqueue
:param rid: the id of the remote node
"""
if rid not in self.outBoxes:
self.outBoxes[rid] = deque()
self.outBoxes[rid].append(msg) | python | 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) | [
"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.
:param msg: the message to enqueue
:param rid: the id of the remote node | [
"Enqueue",
"the",
"message",
"into",
"the",
"remote",
"s",
"queue",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/batched.py#L36-L45 |
248,016 | hyperledger/indy-plenum | plenum/common/batched.py | Batched._enqueueIntoAllRemotes | def _enqueueIntoAllRemotes(self, msg: Any, signer: Signer) -> None:
"""
Enqueue the specified message into all the remotes in the nodestack.
:param msg: the message to enqueue
"""
for rid in self.remotes.keys():
self._enqueue(msg, rid, signer) | python | def _enqueueIntoAllRemotes(self, msg: Any, signer: Signer) -> None:
for rid in self.remotes.keys():
self._enqueue(msg, rid, signer) | [
"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.
:param msg: the message to enqueue | [
"Enqueue",
"the",
"specified",
"message",
"into",
"all",
"the",
"remotes",
"in",
"the",
"nodestack",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/batched.py#L47-L54 |
248,017 | hyperledger/indy-plenum | plenum/common/batched.py | Batched.send | def send(self,
msg: Any, *
rids: Iterable[int],
signer: Signer = None,
message_splitter=None) -> None:
"""
Enqueue the given message into the outBoxes of the specified remotes
or into the outBoxes of all the remotes if rids is None
:param msg: the message to enqueue
:param rids: ids of the remotes to whose outBoxes
this message must be enqueued
:param message_splitter: callable that splits msg on
two smaller messages
"""
# Signing (if required) and serializing before enqueueing otherwise
# each call to `_enqueue` will have to sign it and `transmit` will try
# to serialize it which is waste of resources
message_parts, err_msg = \
self.prepare_for_sending(msg, signer, message_splitter)
# TODO: returning breaks contract of super class
if err_msg is not None:
return False, err_msg
if rids:
for r in rids:
for part in message_parts:
self._enqueue(part, r, signer)
else:
for part in message_parts:
self._enqueueIntoAllRemotes(part, signer)
return True, None | python | def send(self,
msg: Any, *
rids: Iterable[int],
signer: Signer = None,
message_splitter=None) -> None:
# Signing (if required) and serializing before enqueueing otherwise
# each call to `_enqueue` will have to sign it and `transmit` will try
# to serialize it which is waste of resources
message_parts, err_msg = \
self.prepare_for_sending(msg, signer, message_splitter)
# TODO: returning breaks contract of super class
if err_msg is not None:
return False, err_msg
if rids:
for r in rids:
for part in message_parts:
self._enqueue(part, r, signer)
else:
for part in message_parts:
self._enqueueIntoAllRemotes(part, signer)
return True, None | [
"def",
"send",
"(",
"self",
",",
"msg",
":",
"Any",
",",
"*",
"rids",
":",
"Iterable",
"[",
"int",
"]",
",",
"signer",
":",
"Signer",
"=",
"None",
",",
"message_splitter",
"=",
"None",
")",
"->",
"None",
":",
"# Signing (if required) and serializing before enqueueing otherwise",
"# each call to `_enqueue` will have to sign it and `transmit` will try",
"# to serialize it which is waste of resources",
"message_parts",
",",
"err_msg",
"=",
"self",
".",
"prepare_for_sending",
"(",
"msg",
",",
"signer",
",",
"message_splitter",
")",
"# TODO: returning breaks contract of super class",
"if",
"err_msg",
"is",
"not",
"None",
":",
"return",
"False",
",",
"err_msg",
"if",
"rids",
":",
"for",
"r",
"in",
"rids",
":",
"for",
"part",
"in",
"message_parts",
":",
"self",
".",
"_enqueue",
"(",
"part",
",",
"r",
",",
"signer",
")",
"else",
":",
"for",
"part",
"in",
"message_parts",
":",
"self",
".",
"_enqueueIntoAllRemotes",
"(",
"part",
",",
"signer",
")",
"return",
"True",
",",
"None"
] | Enqueue the given message into the outBoxes of the specified remotes
or into the outBoxes of all the remotes if rids is None
:param msg: the message to enqueue
:param rids: ids of the remotes to whose outBoxes
this message must be enqueued
:param message_splitter: callable that splits msg on
two smaller messages | [
"Enqueue",
"the",
"given",
"message",
"into",
"the",
"outBoxes",
"of",
"the",
"specified",
"remotes",
"or",
"into",
"the",
"outBoxes",
"of",
"all",
"the",
"remotes",
"if",
"rids",
"is",
"None"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/batched.py#L56-L88 |
248,018 | hyperledger/indy-plenum | plenum/common/batched.py | Batched.flushOutBoxes | def flushOutBoxes(self) -> None:
"""
Clear the outBoxes and transmit batched messages to remotes.
"""
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 transmissions".
format(self, len(msgs), dest))
logger.trace(" messages: {}".format(msgs))
batches = split_messages_on_batches(list(msgs),
self._make_batch,
self._test_batch_len,
)
msgs.clear()
if batches:
for batch, size in batches:
logger.trace("{} sending payload to {}: {}".format(
self, dest, batch))
self.metrics.add_event(MetricsName.TRANSPORT_BATCH_SIZE, size)
# Setting timeout to never expire
self.transmit(
batch,
rid,
timeout=self.messageTimeout,
serialized=True)
else:
logger.error("{} cannot create batch(es) for {}".format(self, dest))
else:
while msgs:
msg = msgs.popleft()
logger.trace(
"{} sending msg {} to {}".format(self, msg, dest))
self.metrics.add_event(MetricsName.TRANSPORT_BATCH_SIZE, 1)
# Setting timeout to never expire
self.transmit(msg, rid, timeout=self.messageTimeout,
serialized=True)
for rid in removedRemotes:
logger.warning("{}{} has removed rid {}"
.format(CONNECTION_PREFIX, self,
z85_to_friendly(rid)),
extra={"cli": False})
msgs = self.outBoxes[rid]
if msgs:
self.discard(msgs,
"{}rid {} no longer available"
.format(CONNECTION_PREFIX,
z85_to_friendly(rid)),
logMethod=logger.debug)
del self.outBoxes[rid] | python | 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 transmissions".
format(self, len(msgs), dest))
logger.trace(" messages: {}".format(msgs))
batches = split_messages_on_batches(list(msgs),
self._make_batch,
self._test_batch_len,
)
msgs.clear()
if batches:
for batch, size in batches:
logger.trace("{} sending payload to {}: {}".format(
self, dest, batch))
self.metrics.add_event(MetricsName.TRANSPORT_BATCH_SIZE, size)
# Setting timeout to never expire
self.transmit(
batch,
rid,
timeout=self.messageTimeout,
serialized=True)
else:
logger.error("{} cannot create batch(es) for {}".format(self, dest))
else:
while msgs:
msg = msgs.popleft()
logger.trace(
"{} sending msg {} to {}".format(self, msg, dest))
self.metrics.add_event(MetricsName.TRANSPORT_BATCH_SIZE, 1)
# Setting timeout to never expire
self.transmit(msg, rid, timeout=self.messageTimeout,
serialized=True)
for rid in removedRemotes:
logger.warning("{}{} has removed rid {}"
.format(CONNECTION_PREFIX, self,
z85_to_friendly(rid)),
extra={"cli": False})
msgs = self.outBoxes[rid]
if msgs:
self.discard(msgs,
"{}rid {} no longer available"
.format(CONNECTION_PREFIX,
z85_to_friendly(rid)),
logMethod=logger.debug)
del self.outBoxes[rid] | [
"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 transmissions\"",
".",
"format",
"(",
"self",
",",
"len",
"(",
"msgs",
")",
",",
"dest",
")",
")",
"logger",
".",
"trace",
"(",
"\" messages: {}\"",
".",
"format",
"(",
"msgs",
")",
")",
"batches",
"=",
"split_messages_on_batches",
"(",
"list",
"(",
"msgs",
")",
",",
"self",
".",
"_make_batch",
",",
"self",
".",
"_test_batch_len",
",",
")",
"msgs",
".",
"clear",
"(",
")",
"if",
"batches",
":",
"for",
"batch",
",",
"size",
"in",
"batches",
":",
"logger",
".",
"trace",
"(",
"\"{} sending payload to {}: {}\"",
".",
"format",
"(",
"self",
",",
"dest",
",",
"batch",
")",
")",
"self",
".",
"metrics",
".",
"add_event",
"(",
"MetricsName",
".",
"TRANSPORT_BATCH_SIZE",
",",
"size",
")",
"# Setting timeout to never expire",
"self",
".",
"transmit",
"(",
"batch",
",",
"rid",
",",
"timeout",
"=",
"self",
".",
"messageTimeout",
",",
"serialized",
"=",
"True",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"{} cannot create batch(es) for {}\"",
".",
"format",
"(",
"self",
",",
"dest",
")",
")",
"else",
":",
"while",
"msgs",
":",
"msg",
"=",
"msgs",
".",
"popleft",
"(",
")",
"logger",
".",
"trace",
"(",
"\"{} sending msg {} to {}\"",
".",
"format",
"(",
"self",
",",
"msg",
",",
"dest",
")",
")",
"self",
".",
"metrics",
".",
"add_event",
"(",
"MetricsName",
".",
"TRANSPORT_BATCH_SIZE",
",",
"1",
")",
"# Setting timeout to never expire",
"self",
".",
"transmit",
"(",
"msg",
",",
"rid",
",",
"timeout",
"=",
"self",
".",
"messageTimeout",
",",
"serialized",
"=",
"True",
")",
"for",
"rid",
"in",
"removedRemotes",
":",
"logger",
".",
"warning",
"(",
"\"{}{} has removed rid {}\"",
".",
"format",
"(",
"CONNECTION_PREFIX",
",",
"self",
",",
"z85_to_friendly",
"(",
"rid",
")",
")",
",",
"extra",
"=",
"{",
"\"cli\"",
":",
"False",
"}",
")",
"msgs",
"=",
"self",
".",
"outBoxes",
"[",
"rid",
"]",
"if",
"msgs",
":",
"self",
".",
"discard",
"(",
"msgs",
",",
"\"{}rid {} no longer available\"",
".",
"format",
"(",
"CONNECTION_PREFIX",
",",
"z85_to_friendly",
"(",
"rid",
")",
")",
",",
"logMethod",
"=",
"logger",
".",
"debug",
")",
"del",
"self",
".",
"outBoxes",
"[",
"rid",
"]"
] | Clear the outBoxes and transmit batched messages to remotes. | [
"Clear",
"the",
"outBoxes",
"and",
"transmit",
"batched",
"messages",
"to",
"remotes",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/batched.py#L90-L147 |
248,019 | hyperledger/indy-plenum | stp_core/loop/looper.py | Looper.prodAllOnce | async def prodAllOnce(self):
"""
Call `prod` once for each Prodable in this Looper
:return: the sum of the number of events executed successfully
"""
# TODO: looks like limit is always None???
limit = None
s = 0
for n in self.prodables:
s += await n.prod(limit)
return s | python | async def prodAllOnce(self):
# TODO: looks like limit is always None???
limit = None
s = 0
for n in self.prodables:
s += await n.prod(limit)
return s | [
"async",
"def",
"prodAllOnce",
"(",
"self",
")",
":",
"# TODO: looks like limit is always None???",
"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
:return: the sum of the number of events executed successfully | [
"Call",
"prod",
"once",
"for",
"each",
"Prodable",
"in",
"this",
"Looper"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L142-L153 |
248,020 | hyperledger/indy-plenum | stp_core/loop/looper.py | Looper.add | def add(self, prodable: Prodable) -> None:
"""
Add one Prodable object to this Looper's list of Prodables
:param prodable: the Prodable object to add
"""
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) | python | 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) | [
"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
:param prodable: the Prodable object to add | [
"Add",
"one",
"Prodable",
"object",
"to",
"this",
"Looper",
"s",
"list",
"of",
"Prodables"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L155-L166 |
248,021 | hyperledger/indy-plenum | stp_core/loop/looper.py | Looper.removeProdable | def removeProdable(self, prodable: Prodable=None, name: str=None) -> Optional[Prodable]:
"""
Remove the specified Prodable object from this Looper's list of Prodables
:param prodable: the Prodable to remove
"""
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.prodables.remove(prodable)
return prodable
else:
logger.warning("Trying to remove a prodable {} which is not present"
.format(prodable))
else:
logger.error("Provide a prodable object or a prodable name") | python | 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.prodables.remove(prodable)
return prodable
else:
logger.warning("Trying to remove a prodable {} which is not present"
.format(prodable))
else:
logger.error("Provide a prodable object or a prodable name") | [
"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",
".",
"prodables",
".",
"remove",
"(",
"prodable",
")",
"return",
"prodable",
"else",
":",
"logger",
".",
"warning",
"(",
"\"Trying to remove a prodable {} which is not present\"",
".",
"format",
"(",
"prodable",
")",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"Provide a prodable object or a prodable name\"",
")"
] | Remove the specified Prodable object from this Looper's list of Prodables
:param prodable: the Prodable to remove | [
"Remove",
"the",
"specified",
"Prodable",
"object",
"from",
"this",
"Looper",
"s",
"list",
"of",
"Prodables"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L168-L189 |
248,022 | hyperledger/indy-plenum | stp_core/loop/looper.py | Looper.runOnceNicely | async def runOnceNicely(self):
"""
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.
"""
start = time.perf_counter()
msgsProcessed = await self.prodAllOnce()
if msgsProcessed == 0:
# if no let other stuff run
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), extra={"cli": False}) | python | async def runOnceNicely(self):
start = time.perf_counter()
msgsProcessed = await self.prodAllOnce()
if msgsProcessed == 0:
# if no let other stuff run
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), extra={"cli": False}) | [
"async",
"def",
"runOnceNicely",
"(",
"self",
")",
":",
"start",
"=",
"time",
".",
"perf_counter",
"(",
")",
"msgsProcessed",
"=",
"await",
"self",
".",
"prodAllOnce",
"(",
")",
"if",
"msgsProcessed",
"==",
"0",
":",
"# if no let other stuff run",
"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",
")",
",",
"extra",
"=",
"{",
"\"cli\"",
":",
"False",
"}",
")"
] | 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. | [
"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",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L204-L217 |
248,023 | hyperledger/indy-plenum | stp_core/loop/looper.py | Looper.run | def run(self, *coros: CoroWrapper):
"""
Runs an arbitrary list of coroutines in order and then quits the loop,
if not running as a context manager.
"""
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):
results.append(await res)
else:
results.append(res)
else:
raise RuntimeError(
"don't know how to run {}".format(coro))
except Exception as ex:
logger.error("Error while running coroutine {}: {}".format(coro.__name__, ex.__repr__()))
raise ex
if len(results) == 1:
return results[0]
return results
if coros:
what = wrapper()
else:
# if no coros supplied, then assume we run forever
what = self.runFut
return self.loop.run_until_complete(what) | python | 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):
results.append(await res)
else:
results.append(res)
else:
raise RuntimeError(
"don't know how to run {}".format(coro))
except Exception as ex:
logger.error("Error while running coroutine {}: {}".format(coro.__name__, ex.__repr__()))
raise ex
if len(results) == 1:
return results[0]
return results
if coros:
what = wrapper()
else:
# if no coros supplied, then assume we run forever
what = self.runFut
return self.loop.run_until_complete(what) | [
"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",
")",
":",
"results",
".",
"append",
"(",
"await",
"res",
")",
"else",
":",
"results",
".",
"append",
"(",
"res",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"don't know how to run {}\"",
".",
"format",
"(",
"coro",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"error",
"(",
"\"Error while running coroutine {}: {}\"",
".",
"format",
"(",
"coro",
".",
"__name__",
",",
"ex",
".",
"__repr__",
"(",
")",
")",
")",
"raise",
"ex",
"if",
"len",
"(",
"results",
")",
"==",
"1",
":",
"return",
"results",
"[",
"0",
"]",
"return",
"results",
"if",
"coros",
":",
"what",
"=",
"wrapper",
"(",
")",
"else",
":",
"# if no coros supplied, then assume we run forever",
"what",
"=",
"self",
".",
"runFut",
"return",
"self",
".",
"loop",
".",
"run_until_complete",
"(",
"what",
")"
] | Runs an arbitrary list of coroutines in order and then quits the loop,
if not running as a context manager. | [
"Runs",
"an",
"arbitrary",
"list",
"of",
"coroutines",
"in",
"order",
"and",
"then",
"quits",
"the",
"loop",
"if",
"not",
"running",
"as",
"a",
"context",
"manager",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L229-L263 |
248,024 | hyperledger/indy-plenum | stp_core/loop/looper.py | Looper.shutdown | async def shutdown(self):
"""
Shut down this Looper.
"""
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_counter() - start), extra={"cli": False})
# Unset signal handlers, bug: https://bugs.python.org/issue23548
for sig_name in self.signals:
logger.debug("Unsetting handler for {}".format(sig_name))
sig_num = getattr(signal, sig_name)
self.loop.remove_signal_handler(sig_num) | python | 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_counter() - start), extra={"cli": False})
# Unset signal handlers, bug: https://bugs.python.org/issue23548
for sig_name in self.signals:
logger.debug("Unsetting handler for {}".format(sig_name))
sig_num = getattr(signal, sig_name)
self.loop.remove_signal_handler(sig_num) | [
"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_counter",
"(",
")",
"-",
"start",
")",
",",
"extra",
"=",
"{",
"\"cli\"",
":",
"False",
"}",
")",
"# Unset signal handlers, bug: https://bugs.python.org/issue23548",
"for",
"sig_name",
"in",
"self",
".",
"signals",
":",
"logger",
".",
"debug",
"(",
"\"Unsetting handler for {}\"",
".",
"format",
"(",
"sig_name",
")",
")",
"sig_num",
"=",
"getattr",
"(",
"signal",
",",
"sig_name",
")",
"self",
".",
"loop",
".",
"remove_signal_handler",
"(",
"sig_num",
")"
] | Shut down this Looper. | [
"Shut",
"down",
"this",
"Looper",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L271-L287 |
248,025 | hyperledger/indy-plenum | plenum/bls/bls_bft_factory.py | create_default_bls_bft_factory | def create_default_bls_bft_factory(node):
'''
Creates a default BLS factory to instantiate BLS BFT classes.
:param node: Node instance
:return: BLS factory instance
'''
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) | python | def create_default_bls_bft_factory(node):
'''
Creates a default BLS factory to instantiate BLS BFT classes.
:param node: Node instance
:return: BLS factory instance
'''
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) | [
"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.
:param node: Node instance
:return: BLS factory instance | [
"Creates",
"a",
"default",
"BLS",
"factory",
"to",
"instantiate",
"BLS",
"BFT",
"classes",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/bls/bls_bft_factory.py#L32-L41 |
248,026 | hyperledger/indy-plenum | stp_core/crypto/nacl_wrappers.py | SigningKey.sign | def sign(self, message, encoder=encoding.RawEncoder):
"""
Sign a message using this key.
:param message: [:class:`bytes`] The data to be signed.
:param encoder: A class that is used to encode the signed message.
:rtype: :class:`~SignedMessage`
"""
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_signed)
return SignedMessage._from_parts(signature, message, signed) | python | 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_signed)
return SignedMessage._from_parts(signature, message, signed) | [
"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_signed",
")",
"return",
"SignedMessage",
".",
"_from_parts",
"(",
"signature",
",",
"message",
",",
"signed",
")"
] | Sign a message using this key.
:param message: [:class:`bytes`] The data to be signed.
:param encoder: A class that is used to encode the signed message.
:rtype: :class:`~SignedMessage` | [
"Sign",
"a",
"message",
"using",
"this",
"key",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L162-L176 |
248,027 | hyperledger/indy-plenum | stp_core/crypto/nacl_wrappers.py | Verifier.verify | def verify(self, signature, msg):
'''
Verify the message
'''
if not self.key:
return False
try:
self.key.verify(signature + msg)
except ValueError:
return False
return True | python | def verify(self, signature, msg):
'''
Verify the message
'''
if not self.key:
return False
try:
self.key.verify(signature + msg)
except ValueError:
return False
return True | [
"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 | [
"Verify",
"the",
"message"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L232-L242 |
248,028 | hyperledger/indy-plenum | stp_core/crypto/nacl_wrappers.py | Box.encrypt | def encrypt(self, plaintext, nonce, encoder=encoding.RawEncoder):
"""
Encrypts the plaintext message using the given `nonce` and returns
the ciphertext encoded with the encoder.
.. warning:: It is **VITALLY** important that the nonce is a nonce,
i.e. it is a number used only once for any given key. If you fail
to do this, you compromise the privacy of the messages encrypted.
:param plaintext: [:class:`bytes`] The plaintext message to encrypt
:param nonce: [:class:`bytes`] The nonce to use in the encryption
:param encoder: The encoder to use to encode the ciphertext
:rtype: [:class:`nacl.utils.EncryptedMessage`]
"""
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(nonce)
encoded_ciphertext = encoder.encode(ciphertext)
return EncryptedMessage._from_parts(
encoded_nonce,
encoded_ciphertext,
encoder.encode(nonce + ciphertext),
) | python | 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(nonce)
encoded_ciphertext = encoder.encode(ciphertext)
return EncryptedMessage._from_parts(
encoded_nonce,
encoded_ciphertext,
encoder.encode(nonce + ciphertext),
) | [
"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",
"(",
"nonce",
")",
"encoded_ciphertext",
"=",
"encoder",
".",
"encode",
"(",
"ciphertext",
")",
"return",
"EncryptedMessage",
".",
"_from_parts",
"(",
"encoded_nonce",
",",
"encoded_ciphertext",
",",
"encoder",
".",
"encode",
"(",
"nonce",
"+",
"ciphertext",
")",
",",
")"
] | Encrypts the plaintext message using the given `nonce` and returns
the ciphertext encoded with the encoder.
.. warning:: It is **VITALLY** important that the nonce is a nonce,
i.e. it is a number used only once for any given key. If you fail
to do this, you compromise the privacy of the messages encrypted.
:param plaintext: [:class:`bytes`] The plaintext message to encrypt
:param nonce: [:class:`bytes`] The nonce to use in the encryption
:param encoder: The encoder to use to encode the ciphertext
:rtype: [:class:`nacl.utils.EncryptedMessage`] | [
"Encrypts",
"the",
"plaintext",
"message",
"using",
"the",
"given",
"nonce",
"and",
"returns",
"the",
"ciphertext",
"encoded",
"with",
"the",
"encoder",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L357-L388 |
248,029 | hyperledger/indy-plenum | stp_core/crypto/nacl_wrappers.py | Box.decrypt | def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder):
"""
Decrypts the ciphertext using the given nonce and returns the
plaintext message.
:param ciphertext: [:class:`bytes`] The encrypted message to decrypt
:param nonce: [:class:`bytes`] The nonce used when encrypting the
ciphertext
:param encoder: The encoder used to decode the ciphertext.
:rtype: [:class:`bytes`]
"""
# Decode our ciphertext
ciphertext = encoder.decode(ciphertext)
if nonce is None:
# If we were given the nonce and ciphertext combined, split them.
nonce = ciphertext[:self.NONCE_SIZE]
ciphertext = ciphertext[self.NONCE_SIZE:]
if len(nonce) != self.NONCE_SIZE:
raise ValueError("The nonce must be exactly %s bytes long" %
self.NONCE_SIZE)
plaintext = libnacl.crypto_box_open_afternm(
ciphertext,
nonce,
self._shared_key,
)
return plaintext | python | def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder):
# Decode our ciphertext
ciphertext = encoder.decode(ciphertext)
if nonce is None:
# If we were given the nonce and ciphertext combined, split them.
nonce = ciphertext[:self.NONCE_SIZE]
ciphertext = ciphertext[self.NONCE_SIZE:]
if len(nonce) != self.NONCE_SIZE:
raise ValueError("The nonce must be exactly %s bytes long" %
self.NONCE_SIZE)
plaintext = libnacl.crypto_box_open_afternm(
ciphertext,
nonce,
self._shared_key,
)
return plaintext | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
",",
"nonce",
"=",
"None",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"# Decode our ciphertext",
"ciphertext",
"=",
"encoder",
".",
"decode",
"(",
"ciphertext",
")",
"if",
"nonce",
"is",
"None",
":",
"# If we were given the nonce and ciphertext combined, split them.",
"nonce",
"=",
"ciphertext",
"[",
":",
"self",
".",
"NONCE_SIZE",
"]",
"ciphertext",
"=",
"ciphertext",
"[",
"self",
".",
"NONCE_SIZE",
":",
"]",
"if",
"len",
"(",
"nonce",
")",
"!=",
"self",
".",
"NONCE_SIZE",
":",
"raise",
"ValueError",
"(",
"\"The nonce must be exactly %s bytes long\"",
"%",
"self",
".",
"NONCE_SIZE",
")",
"plaintext",
"=",
"libnacl",
".",
"crypto_box_open_afternm",
"(",
"ciphertext",
",",
"nonce",
",",
"self",
".",
"_shared_key",
",",
")",
"return",
"plaintext"
] | Decrypts the ciphertext using the given nonce and returns the
plaintext message.
:param ciphertext: [:class:`bytes`] The encrypted message to decrypt
:param nonce: [:class:`bytes`] The nonce used when encrypting the
ciphertext
:param encoder: The encoder used to decode the ciphertext.
:rtype: [:class:`bytes`] | [
"Decrypts",
"the",
"ciphertext",
"using",
"the",
"given",
"nonce",
"and",
"returns",
"the",
"plaintext",
"message",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L390-L419 |
248,030 | hyperledger/indy-plenum | stp_core/crypto/nacl_wrappers.py | Privateer.decrypt | def decrypt(self, cipher, nonce, pubkey, dehex=False):
'''
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
Intended for the owner of .key
cypher is string
nonce is string
pub is Publican instance
'''
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 dehex else encoding.RawEncoder
if dehex and len(nonce) != box.NONCE_SIZE:
nonce = decoder.decode(nonce)
return box.decrypt(cipher, nonce, decoder) | python | def decrypt(self, cipher, nonce, pubkey, dehex=False):
'''
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
Intended for the owner of .key
cypher is string
nonce is string
pub is Publican instance
'''
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 dehex else encoding.RawEncoder
if dehex and len(nonce) != box.NONCE_SIZE:
nonce = decoder.decode(nonce)
return box.decrypt(cipher, nonce, decoder) | [
"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",
"dehex",
"else",
"encoding",
".",
"RawEncoder",
"if",
"dehex",
"and",
"len",
"(",
"nonce",
")",
"!=",
"box",
".",
"NONCE_SIZE",
":",
"nonce",
"=",
"decoder",
".",
"decode",
"(",
"nonce",
")",
"return",
"box",
".",
"decrypt",
"(",
"cipher",
",",
"nonce",
",",
"decoder",
")"
] | 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
Intended for the owner of .key
cypher is string
nonce is string
pub is Publican instance | [
"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"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L496-L518 |
248,031 | hyperledger/indy-plenum | plenum/common/config_util.py | getInstalledConfig | def getInstalledConfig(installDir, configFile):
"""
Reads config from the installation directory of Plenum.
:param installDir: installation directory of Plenum
:param configFile: name of the configuration file
:raises: FileNotFoundError
:return: the configuration as a python object
"""
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_spec(spec)
spec.loader.exec_module(config)
return config | python | 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_spec(spec)
spec.loader.exec_module(config)
return config | [
"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_spec",
"(",
"spec",
")",
"spec",
".",
"loader",
".",
"exec_module",
"(",
"config",
")",
"return",
"config"
] | Reads config from the installation directory of Plenum.
:param installDir: installation directory of Plenum
:param configFile: name of the configuration file
:raises: FileNotFoundError
:return: the configuration as a python object | [
"Reads",
"config",
"from",
"the",
"installation",
"directory",
"of",
"Plenum",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/config_util.py#L11-L27 |
248,032 | hyperledger/indy-plenum | plenum/common/config_util.py | _getConfig | def _getConfig(general_config_dir: str = None):
"""
Reads a file called config.py in the project directory
:raises: FileNotFoundError
:return: the configuration as a python object
"""
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:
raise Exception('GENERAL_CONFIG_DIR must be set')
extend_with_external_config(config, (config.GENERAL_CONFIG_DIR,
config.GENERAL_CONFIG_FILE))
# "unsafe" is a set of attributes that can set certain behaviors that
# are not safe, for example, 'disable_view_change' disables view changes
# from happening. This might be useful in testing scenarios, but never
# in a live network.
if not hasattr(config, 'unsafe'):
setattr(config, 'unsafe', set())
return config | python | 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:
raise Exception('GENERAL_CONFIG_DIR must be set')
extend_with_external_config(config, (config.GENERAL_CONFIG_DIR,
config.GENERAL_CONFIG_FILE))
# "unsafe" is a set of attributes that can set certain behaviors that
# are not safe, for example, 'disable_view_change' disables view changes
# from happening. This might be useful in testing scenarios, but never
# in a live network.
if not hasattr(config, 'unsafe'):
setattr(config, 'unsafe', set())
return config | [
"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",
":",
"raise",
"Exception",
"(",
"'GENERAL_CONFIG_DIR must be set'",
")",
"extend_with_external_config",
"(",
"config",
",",
"(",
"config",
".",
"GENERAL_CONFIG_DIR",
",",
"config",
".",
"GENERAL_CONFIG_FILE",
")",
")",
"# \"unsafe\" is a set of attributes that can set certain behaviors that",
"# are not safe, for example, 'disable_view_change' disables view changes",
"# from happening. This might be useful in testing scenarios, but never",
"# in a live network.",
"if",
"not",
"hasattr",
"(",
"config",
",",
"'unsafe'",
")",
":",
"setattr",
"(",
"config",
",",
"'unsafe'",
",",
"set",
"(",
")",
")",
"return",
"config"
] | Reads a file called config.py in the project directory
:raises: FileNotFoundError
:return: the configuration as a python object | [
"Reads",
"a",
"file",
"called",
"config",
".",
"py",
"in",
"the",
"project",
"directory"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/config_util.py#L68-L95 |
248,033 | hyperledger/indy-plenum | plenum/server/router.py | Router.getFunc | def getFunc(self, o: Any) -> Callable:
"""
Get the next function from the list of routes that is capable of
processing o's type.
:param o: the object to process
:return: the next function
"""
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("unhandled msg: {}".format(o)) | python | 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("unhandled msg: {}".format(o)) | [
"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",
"(",
"\"unhandled msg: {}\"",
".",
"format",
"(",
"o",
")",
")"
] | Get the next function from the list of routes that is capable of
processing o's type.
:param o: the object to process
:return: the next function | [
"Get",
"the",
"next",
"function",
"from",
"the",
"list",
"of",
"routes",
"that",
"is",
"capable",
"of",
"processing",
"o",
"s",
"type",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/router.py#L46-L60 |
248,034 | hyperledger/indy-plenum | plenum/server/router.py | Router.handleSync | def handleSync(self, msg: Any) -> Any:
"""
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.
:param msg: tuple of object and callable
"""
# If a plain python tuple and not a named tuple, a better alternative
# would be to create a named entity with the 3 characteristics below
# TODO: non-obvious tuple, re-factor!
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) | python | def handleSync(self, msg: Any) -> Any:
# If a plain python tuple and not a named tuple, a better alternative
# would be to create a named entity with the 3 characteristics below
# TODO: non-obvious tuple, re-factor!
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) | [
"def",
"handleSync",
"(",
"self",
",",
"msg",
":",
"Any",
")",
"->",
"Any",
":",
"# If a plain python tuple and not a named tuple, a better alternative",
"# would be to create a named entity with the 3 characteristics below",
"# TODO: non-obvious tuple, re-factor!",
"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.
:param msg: tuple of object and callable | [
"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",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/router.py#L63-L77 |
248,035 | hyperledger/indy-plenum | plenum/server/router.py | Router.handle | async def handle(self, msg: Any) -> Any:
"""
Handle both sync and async functions.
:param msg: a message
:return: the result of execution of the function corresponding to this message's type
"""
res = self.handleSync(msg)
if isawaitable(res):
return await res
else:
return res | python | async def handle(self, msg: Any) -> Any:
res = self.handleSync(msg)
if isawaitable(res):
return await res
else:
return res | [
"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.
:param msg: a message
:return: the result of execution of the function corresponding to this message's type | [
"Handle",
"both",
"sync",
"and",
"async",
"functions",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/router.py#L79-L90 |
248,036 | hyperledger/indy-plenum | plenum/server/router.py | Router.handleAll | async def handleAll(self, deq: deque, limit=None) -> int:
"""
Handle all items in a deque. Can call asynchronous handlers.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successfully
"""
count = 0
while deq and (not limit or count < limit):
count += 1
item = deq.popleft()
await self.handle(item)
return count | python | 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 | [
"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.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successfully | [
"Handle",
"all",
"items",
"in",
"a",
"deque",
".",
"Can",
"call",
"asynchronous",
"handlers",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/router.py#L92-L105 |
248,037 | hyperledger/indy-plenum | plenum/server/router.py | Router.handleAllSync | def handleAllSync(self, deq: deque, limit=None) -> int:
"""
Synchronously handle all items in a deque.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successfully
"""
count = 0
while deq and (not limit or count < limit):
count += 1
msg = deq.popleft()
self.handleSync(msg)
return count | python | 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 | [
"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.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successfully | [
"Synchronously",
"handle",
"all",
"items",
"in",
"a",
"deque",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/router.py#L107-L120 |
248,038 | hyperledger/indy-plenum | ledger/compact_merkle_tree.py | CompactMerkleTree.load | def load(self, other: merkle_tree.MerkleTree):
"""Load this tree from a dumb data object for serialisation.
The object must have attributes tree_size:int and hashes:list.
"""
self._update(other.tree_size, other.hashes) | python | def load(self, other: merkle_tree.MerkleTree):
self._update(other.tree_size, other.hashes) | [
"def",
"load",
"(",
"self",
",",
"other",
":",
"merkle_tree",
".",
"MerkleTree",
")",
":",
"self",
".",
"_update",
"(",
"other",
".",
"tree_size",
",",
"other",
".",
"hashes",
")"
] | Load this tree from a dumb data object for serialisation.
The object must have attributes tree_size:int and hashes:list. | [
"Load",
"this",
"tree",
"from",
"a",
"dumb",
"data",
"object",
"for",
"serialisation",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/compact_merkle_tree.py#L47-L52 |
248,039 | hyperledger/indy-plenum | ledger/compact_merkle_tree.py | CompactMerkleTree.save | def save(self, other: merkle_tree.MerkleTree):
"""Save this tree into a dumb data object for serialisation.
The object must have attributes tree_size:int and hashes:list.
"""
other.__tree_size = self.__tree_size
other.__hashes = self.__hashes | python | def save(self, other: merkle_tree.MerkleTree):
other.__tree_size = self.__tree_size
other.__hashes = self.__hashes | [
"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.
The object must have attributes tree_size:int and hashes:list. | [
"Save",
"this",
"tree",
"into",
"a",
"dumb",
"data",
"object",
"for",
"serialisation",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/compact_merkle_tree.py#L54-L60 |
248,040 | hyperledger/indy-plenum | ledger/compact_merkle_tree.py | CompactMerkleTree.append | def append(self, new_leaf: bytes) -> List[bytes]:
"""Append a new leaf onto the end of this tree and return the
audit path"""
auditPath = list(reversed(self.__hashes))
self._push_subtree([new_leaf])
return auditPath | python | def append(self, new_leaf: bytes) -> List[bytes]:
auditPath = list(reversed(self.__hashes))
self._push_subtree([new_leaf])
return auditPath | [
"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 | [
"Append",
"a",
"new",
"leaf",
"onto",
"the",
"end",
"of",
"this",
"tree",
"and",
"return",
"the",
"audit",
"path"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/compact_merkle_tree.py#L155-L160 |
248,041 | hyperledger/indy-plenum | ledger/compact_merkle_tree.py | CompactMerkleTree.extend | def extend(self, new_leaves: List[bytes]):
"""Extend this tree with new_leaves on the end.
The algorithm works by using _push_subtree() as a primitive, calling
it with the maximum number of allowed leaves until we can add the
remaining leaves as a valid entire (non-full) subtree in one go.
"""
size = len(new_leaves)
final_size = self.tree_size + size
idx = 0
while True:
# keep pushing subtrees until mintree_size > remaining
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])
idx += max_size
else:
break
# fill in rest of tree in one go, now that we can
if idx < size:
root_hash, hashes = self.__hasher._hash_full(new_leaves, idx, size)
self._update(final_size, self.hashes + hashes)
assert self.tree_size == final_size | python | def extend(self, new_leaves: List[bytes]):
size = len(new_leaves)
final_size = self.tree_size + size
idx = 0
while True:
# keep pushing subtrees until mintree_size > remaining
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])
idx += max_size
else:
break
# fill in rest of tree in one go, now that we can
if idx < size:
root_hash, hashes = self.__hasher._hash_full(new_leaves, idx, size)
self._update(final_size, self.hashes + hashes)
assert self.tree_size == final_size | [
"def",
"extend",
"(",
"self",
",",
"new_leaves",
":",
"List",
"[",
"bytes",
"]",
")",
":",
"size",
"=",
"len",
"(",
"new_leaves",
")",
"final_size",
"=",
"self",
".",
"tree_size",
"+",
"size",
"idx",
"=",
"0",
"while",
"True",
":",
"# keep pushing subtrees until mintree_size > remaining",
"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",
"]",
")",
"idx",
"+=",
"max_size",
"else",
":",
"break",
"# fill in rest of tree in one go, now that we can",
"if",
"idx",
"<",
"size",
":",
"root_hash",
",",
"hashes",
"=",
"self",
".",
"__hasher",
".",
"_hash_full",
"(",
"new_leaves",
",",
"idx",
",",
"size",
")",
"self",
".",
"_update",
"(",
"final_size",
",",
"self",
".",
"hashes",
"+",
"hashes",
")",
"assert",
"self",
".",
"tree_size",
"==",
"final_size"
] | Extend this tree with new_leaves on the end.
The algorithm works by using _push_subtree() as a primitive, calling
it with the maximum number of allowed leaves until we can add the
remaining leaves as a valid entire (non-full) subtree in one go. | [
"Extend",
"this",
"tree",
"with",
"new_leaves",
"on",
"the",
"end",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/compact_merkle_tree.py#L162-L185 |
248,042 | hyperledger/indy-plenum | ledger/compact_merkle_tree.py | CompactMerkleTree.extended | def extended(self, new_leaves: List[bytes]):
"""Returns a new tree equal to this tree extended with new_leaves."""
new_tree = self.__copy__()
new_tree.extend(new_leaves)
return new_tree | python | def extended(self, new_leaves: List[bytes]):
new_tree = self.__copy__()
new_tree.extend(new_leaves)
return new_tree | [
"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. | [
"Returns",
"a",
"new",
"tree",
"equal",
"to",
"this",
"tree",
"extended",
"with",
"new_leaves",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/compact_merkle_tree.py#L187-L191 |
248,043 | hyperledger/indy-plenum | ledger/compact_merkle_tree.py | CompactMerkleTree.verify_consistency | def verify_consistency(self, expected_leaf_count) -> bool:
"""
Check that the tree has same leaf count as expected and the
number of nodes are also as expected
"""
if expected_leaf_count != self.leafCount:
raise ConsistencyVerificationFailed()
if self.get_expected_node_count(self.leafCount) != self.nodeCount:
raise ConsistencyVerificationFailed()
return True | python | 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 | [
"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 | [
"Check",
"that",
"the",
"tree",
"has",
"same",
"leaf",
"count",
"as",
"expected",
"and",
"the",
"number",
"of",
"nodes",
"are",
"also",
"as",
"expected"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/compact_merkle_tree.py#L280-L289 |
248,044 | hyperledger/indy-plenum | state/util/utils.py | isHex | def isHex(val: str) -> bool:
"""
Return whether the given str represents a hex value or not
:param val: the string to check
:return: whether the given str represents a hex value
"""
if isinstance(val, bytes):
# only decodes utf-8 string
try:
val = val.decode()
except ValueError:
return False
return isinstance(val, str) and all(c in string.hexdigits for c in val) | python | def isHex(val: str) -> bool:
if isinstance(val, bytes):
# only decodes utf-8 string
try:
val = val.decode()
except ValueError:
return False
return isinstance(val, str) and all(c in string.hexdigits for c in val) | [
"def",
"isHex",
"(",
"val",
":",
"str",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"# only decodes utf-8 string",
"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
:param val: the string to check
:return: whether the given str represents a hex value | [
"Return",
"whether",
"the",
"given",
"str",
"represents",
"a",
"hex",
"value",
"or",
"not"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/state/util/utils.py#L80-L93 |
248,045 | hyperledger/indy-plenum | plenum/common/latency_measurements.py | EMALatencyMeasurementForEachClient._accumulate | def _accumulate(self, old_accum, next_val):
"""
Implement exponential moving average
"""
return old_accum * (1 - self.alpha) + next_val * self.alpha | python | def _accumulate(self, old_accum, next_val):
return old_accum * (1 - self.alpha) + next_val * self.alpha | [
"def",
"_accumulate",
"(",
"self",
",",
"old_accum",
",",
"next_val",
")",
":",
"return",
"old_accum",
"*",
"(",
"1",
"-",
"self",
".",
"alpha",
")",
"+",
"next_val",
"*",
"self",
".",
"alpha"
] | Implement exponential moving average | [
"Implement",
"exponential",
"moving",
"average"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/latency_measurements.py#L36-L40 |
248,046 | hyperledger/indy-plenum | ledger/hash_stores/hash_store.py | HashStore.getNodePosition | def getNodePosition(cls, start, height=None) -> int:
"""
Calculates node position based on start and height
:param start: The sequence number of the first leaf under this tree.
:param height: Height of this node in the merkle tree
:return: the node's position
"""
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) | python | 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) | [
"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
:param start: The sequence number of the first leaf under this tree.
:param height: Height of this node in the merkle tree
:return: the node's position | [
"Calculates",
"node",
"position",
"based",
"on",
"start",
"and",
"height"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/hash_stores/hash_store.py#L88-L104 |
248,047 | hyperledger/indy-plenum | ledger/hash_stores/hash_store.py | HashStore.getPath | def getPath(cls, seqNo, offset=0):
"""
Get the audit path of the leaf at the position specified by serNo.
:param seqNo: sequence number of the leaf to calculate the path for
:param offset: the sequence number of the node from where the path
should begin.
:return: tuple of leafs and nodes
"""
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(seqNo, c)
nodes.append(cls.getNodePosition(c, pwr))
return leafs, nodes | python | 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(seqNo, c)
nodes.append(cls.getNodePosition(c, pwr))
return leafs, nodes | [
"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",
"(",
"seqNo",
",",
"c",
")",
"nodes",
".",
"append",
"(",
"cls",
".",
"getNodePosition",
"(",
"c",
",",
"pwr",
")",
")",
"return",
"leafs",
",",
"nodes"
] | Get the audit path of the leaf at the position specified by serNo.
:param seqNo: sequence number of the leaf to calculate the path for
:param offset: the sequence number of the node from where the path
should begin.
:return: tuple of leafs and nodes | [
"Get",
"the",
"audit",
"path",
"of",
"the",
"leaf",
"at",
"the",
"position",
"specified",
"by",
"serNo",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/hash_stores/hash_store.py#L107-L127 |
248,048 | hyperledger/indy-plenum | ledger/hash_stores/hash_store.py | HashStore.readNodeByTree | def readNodeByTree(self, start, height=None):
"""
Fetches nodeHash based on start leaf and height of the node in the tree.
:return: the nodeHash
"""
pos = self.getNodePosition(start, height)
return self.readNode(pos) | python | def readNodeByTree(self, start, height=None):
pos = self.getNodePosition(start, height)
return self.readNode(pos) | [
"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.
:return: the nodeHash | [
"Fetches",
"nodeHash",
"based",
"on",
"start",
"leaf",
"and",
"height",
"of",
"the",
"node",
"in",
"the",
"tree",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/hash_stores/hash_store.py#L129-L136 |
248,049 | hyperledger/indy-plenum | ledger/hash_stores/hash_store.py | HashStore.is_consistent | def is_consistent(self) -> bool:
"""
Returns True if number of nodes are consistent with number of leaves
"""
from ledger.compact_merkle_tree import CompactMerkleTree
return self.nodeCount == CompactMerkleTree.get_expected_node_count(
self.leafCount) | python | def is_consistent(self) -> bool:
from ledger.compact_merkle_tree import CompactMerkleTree
return self.nodeCount == CompactMerkleTree.get_expected_node_count(
self.leafCount) | [
"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 | [
"Returns",
"True",
"if",
"number",
"of",
"nodes",
"are",
"consistent",
"with",
"number",
"of",
"leaves"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/hash_stores/hash_store.py#L139-L145 |
248,050 | hyperledger/indy-plenum | storage/chunked_file_store.py | ChunkedFileStore._startNextChunk | def _startNextChunk(self) -> None:
"""
Close current and start next chunk
"""
if self.currentChunk is None:
self._useLatestChunk()
else:
self._useChunk(self.currentChunkIndex + self.chunkSize) | python | def _startNextChunk(self) -> None:
if self.currentChunk is None:
self._useLatestChunk()
else:
self._useChunk(self.currentChunkIndex + self.chunkSize) | [
"def",
"_startNextChunk",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"currentChunk",
"is",
"None",
":",
"self",
".",
"_useLatestChunk",
"(",
")",
"else",
":",
"self",
".",
"_useChunk",
"(",
"self",
".",
"currentChunkIndex",
"+",
"self",
".",
"chunkSize",
")"
] | Close current and start next chunk | [
"Close",
"current",
"and",
"start",
"next",
"chunk"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/storage/chunked_file_store.py#L108-L115 |
248,051 | hyperledger/indy-plenum | storage/chunked_file_store.py | ChunkedFileStore.get | 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._get_key_location(key)
with self._openChunk(chunk_no) as chunk:
return chunk.get(str(offset)) | python | def get(self, key) -> str:
# TODO: get is creating files when a key is given which is more than
# the store size
chunk_no, offset = self._get_key_location(key)
with self._openChunk(chunk_no) as chunk:
return chunk.get(str(offset)) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
"->",
"str",
":",
"# TODO: get is creating files when a key is given which is more than",
"# the store size",
"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.
:return: value corresponding to specified key | [
"Determines",
"the",
"file",
"to",
"retrieve",
"the",
"data",
"from",
"and",
"retrieves",
"the",
"data",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/storage/chunked_file_store.py#L168-L178 |
248,052 | hyperledger/indy-plenum | storage/chunked_file_store.py | ChunkedFileStore.reset | 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() | python | def reset(self) -> None:
self.close()
for f in os.listdir(self.dataDir):
os.remove(os.path.join(self.dataDir, f))
self._useLatestChunk() | [
"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. | [
"Clear",
"all",
"data",
"in",
"file",
"storage",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/storage/chunked_file_store.py#L180-L187 |
248,053 | hyperledger/indy-plenum | storage/chunked_file_store.py | ChunkedFileStore._listChunks | 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:
chunks.append(index)
return sorted(chunks) | python | 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) | [
"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
:return: sorted list of available chunk indices | [
"Lists",
"stored",
"chunks"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/storage/chunked_file_store.py#L216-L227 |
248,054 | hyperledger/indy-plenum | plenum/server/primary_decider.py | PrimaryDecider.filterMsgs | 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:
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:
self.discard(wrappedMsg,
"its view no {} is less than the elector's {}"
.format(reqViewNo, self.viewNo),
logger.debug)
else:
filtered.append(wrappedMsg)
return filtered | python | 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:
self.discard(wrappedMsg,
"its view no {} is less than the elector's {}"
.format(reqViewNo, self.viewNo),
logger.debug)
else:
filtered.append(wrappedMsg)
return filtered | [
"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",
":",
"self",
".",
"discard",
"(",
"wrappedMsg",
",",
"\"its view no {} is less than the elector's {}\"",
".",
"format",
"(",
"reqViewNo",
",",
"self",
".",
"viewNo",
")",
",",
"logger",
".",
"debug",
")",
"else",
":",
"filtered",
".",
"append",
"(",
"wrappedMsg",
")",
"return",
"filtered"
] | Filters messages by view number so that only the messages that have the
current view number are retained.
:param wrappedMsgs: the messages to filter | [
"Filters",
"messages",
"by",
"view",
"number",
"so",
"that",
"only",
"the",
"messages",
"that",
"have",
"the",
"current",
"view",
"number",
"are",
"retained",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/primary_decider.py#L74-L97 |
248,055 | hyperledger/indy-plenum | plenum/server/plugin_loader.py | PluginLoader.get | def get(self, name):
"""Retrieve a plugin by name."""
try:
return self.plugins[name]
except KeyError:
raise RuntimeError("plugin {} does not exist".format(name)) | python | def get(self, name):
try:
return self.plugins[name]
except KeyError:
raise RuntimeError("plugin {} does not exist".format(name)) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"self",
".",
"plugins",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"RuntimeError",
"(",
"\"plugin {} does not exist\"",
".",
"format",
"(",
"name",
")",
")"
] | Retrieve a plugin by name. | [
"Retrieve",
"a",
"plugin",
"by",
"name",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/plugin_loader.py#L65-L70 |
248,056 | hyperledger/indy-plenum | common/version.py | VersionBase.cmp | 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 | python | def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:
# TODO types checking
if v1._version > v2._version:
return 1
elif v1._version == v2._version:
return 0
else:
return -1 | [
"def",
"cmp",
"(",
"cls",
",",
"v1",
":",
"'VersionBase'",
",",
"v2",
":",
"'VersionBase'",
")",
"->",
"int",
":",
"# TODO types checking",
"if",
"v1",
".",
"_version",
">",
"v2",
".",
"_version",
":",
"return",
"1",
"elif",
"v1",
".",
"_version",
"==",
"v2",
".",
"_version",
":",
"return",
"0",
"else",
":",
"return",
"-",
"1"
] | Compares two instances. | [
"Compares",
"two",
"instances",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/common/version.py#L39-L47 |
248,057 | hyperledger/indy-plenum | stp_zmq/kit_zstack.py | KITZStack.maintainConnections | 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
if self.isKeySharing
else self.config.RETRY_TIMEOUT_RESTRICTED)
missing = self.connectToMissing()
self.retryDisconnected(exclude=missing)
logger.trace("{} next check for retries in {:.2f} seconds"
.format(self, self.nextCheck - now))
return True | python | 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()
self.retryDisconnected(exclude=missing)
logger.trace("{} next check for retries in {:.2f} seconds"
.format(self, self.nextCheck - now))
return True | [
"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",
"(",
")",
"self",
".",
"retryDisconnected",
"(",
"exclude",
"=",
"missing",
")",
"logger",
".",
"trace",
"(",
"\"{} next check for retries in {:.2f} seconds\"",
".",
"format",
"(",
"self",
",",
"self",
".",
"nextCheck",
"-",
"now",
")",
")",
"return",
"True"
] | Ensure appropriate connections. | [
"Ensure",
"appropriate",
"connections",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/kit_zstack.py#L54-L69 |
248,058 | hyperledger/indy-plenum | stp_zmq/kit_zstack.py | KITZStack.connectToMissing | 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, ", ".join(missing)))
for name in missing:
try:
self.connect(name, ha=self.registry[name])
except (ValueError, KeyError, PublicKeyNotFoundOnDisk, VerKeyNotFoundOnDisk) as ex:
logger.warning('{}{} cannot connect to {} due to {}'.
format(CONNECTION_PREFIX, self, name, ex))
return missing | python | 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[name])
except (ValueError, KeyError, PublicKeyNotFoundOnDisk, VerKeyNotFoundOnDisk) as ex:
logger.warning('{}{} cannot connect to {} due to {}'.
format(CONNECTION_PREFIX, self, name, ex))
return missing | [
"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",
"[",
"name",
"]",
")",
"except",
"(",
"ValueError",
",",
"KeyError",
",",
"PublicKeyNotFoundOnDisk",
",",
"VerKeyNotFoundOnDisk",
")",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"'{}{} cannot connect to {} due to {}'",
".",
"format",
"(",
"CONNECTION_PREFIX",
",",
"self",
",",
"name",
",",
"ex",
")",
")",
"return",
"missing"
] | Try to connect to the missing nodes | [
"Try",
"to",
"connect",
"to",
"the",
"missing",
"nodes"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/kit_zstack.py#L107-L125 |
248,059 | hyperledger/indy-plenum | stp_core/common/logging/handlers.py | CallbackHandler.emit | 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 and record.levelno >= logging.INFO:
should_cb = True
if hasattr(record, 'tags'):
for t in record.tags:
if t in self.tags:
if self.tags[t]:
should_cb = True
continue
else:
should_cb = False
break
if should_cb:
self.callback(record, attr_val) | python | 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 t in self.tags:
if self.tags[t]:
should_cb = True
continue
else:
should_cb = False
break
if should_cb:
self.callback(record, attr_val) | [
"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",
"t",
"in",
"self",
".",
"tags",
":",
"if",
"self",
".",
"tags",
"[",
"t",
"]",
":",
"should_cb",
"=",
"True",
"continue",
"else",
":",
"should_cb",
"=",
"False",
"break",
"if",
"should_cb",
":",
"self",
".",
"callback",
"(",
"record",
",",
"attr_val",
")"
] | Passes the log record back to the CLI for rendering | [
"Passes",
"the",
"log",
"record",
"back",
"to",
"the",
"CLI",
"for",
"rendering"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/common/logging/handlers.py#L18-L39 |
248,060 | hyperledger/indy-plenum | stp_core/network/keep_in_touch.py | KITNetworkInterface.conns | 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.display("{}'s connections changed from {} to {}".format(self, old, value))
self._connsChanged(ins, outs) | python | 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) | [
"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. | [
"Updates",
"the",
"connection",
"count",
"of",
"this",
"node",
"if",
"not",
"already",
"done",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/keep_in_touch.py#L57-L67 |
248,061 | hyperledger/indy-plenum | stp_core/network/keep_in_touch.py | KITNetworkInterface.findInNodeRegByHA | 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 RuntimeError("more than one node registry entry with the "
"same ha {}: {}".format(remoteHa, regName))
if regName:
return regName[0]
return None | python | 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]
return None | [
"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",
"]",
"return",
"None"
] | Returns the name of the remote by HA if found in the node registry, else
returns None | [
"Returns",
"the",
"name",
"of",
"the",
"remote",
"by",
"HA",
"if",
"found",
"in",
"the",
"node",
"registry",
"else",
"returns",
"None"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/keep_in_touch.py#L110-L122 |
248,062 | hyperledger/indy-plenum | stp_core/network/keep_in_touch.py | KITNetworkInterface.getRemoteName | 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]
assert len(find) == 1
return find[0]
return remote.name | python | def getRemoteName(self, remote):
if remote.name not in self.registry:
find = [name for name, ha in self.registry.items()
if ha == remote.ha]
assert len(find) == 1
return find[0]
return remote.name | [
"def",
"getRemoteName",
"(",
"self",
",",
"remote",
")",
":",
"if",
"remote",
".",
"name",
"not",
"in",
"self",
".",
"registry",
":",
"find",
"=",
"[",
"name",
"for",
"name",
",",
"ha",
"in",
"self",
".",
"registry",
".",
"items",
"(",
")",
"if",
"ha",
"==",
"remote",
".",
"ha",
"]",
"assert",
"len",
"(",
"find",
")",
"==",
"1",
"return",
"find",
"[",
"0",
"]",
"return",
"remote",
".",
"name"
] | Returns the name of the remote object if found in node registry.
:param remote: the remote object | [
"Returns",
"the",
"name",
"of",
"the",
"remote",
"object",
"if",
"found",
"in",
"node",
"registry",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/keep_in_touch.py#L124-L135 |
248,063 | hyperledger/indy-plenum | stp_core/network/keep_in_touch.py | KITNetworkInterface.notConnectedNodes | 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 | python | def notConnectedNodes(self) -> Set[str]:
return set(self.registry.keys()) - self.conns | [
"def",
"notConnectedNodes",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"set",
"(",
"self",
".",
"registry",
".",
"keys",
"(",
")",
")",
"-",
"self",
".",
"conns"
] | Returns the names of nodes in the registry this node is NOT connected
to. | [
"Returns",
"the",
"names",
"of",
"nodes",
"in",
"the",
"registry",
"this",
"node",
"is",
"NOT",
"connected",
"to",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/keep_in_touch.py#L138-L143 |
248,064 | hyperledger/indy-plenum | stp_zmq/authenticator.py | MultiZapAuthenticator.start | 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(zapLoc)) | python | def start(self):
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(zapLoc)) | [
"def",
"start",
"(",
"self",
")",
":",
"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",
"(",
"zapLoc",
")",
")"
] | Create and bind the ZAP socket | [
"Create",
"and",
"bind",
"the",
"ZAP",
"socket"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/authenticator.py#L25-L31 |
248,065 | hyperledger/indy-plenum | stp_zmq/authenticator.py | MultiZapAuthenticator.stop | 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() | python | def stop(self):
if self.zap_socket:
self.log.debug(
'Stopping ZAP at {}'.format(self.zap_socket.LAST_ENDPOINT))
super().stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"zap_socket",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Stopping ZAP at {}'",
".",
"format",
"(",
"self",
".",
"zap_socket",
".",
"LAST_ENDPOINT",
")",
")",
"super",
"(",
")",
".",
"stop",
"(",
")"
] | Close the ZAP socket | [
"Close",
"the",
"ZAP",
"socket"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/authenticator.py#L33-L38 |
248,066 | hyperledger/indy-plenum | stp_zmq/authenticator.py | AsyncioAuthenticator.start | 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()) | python | def start(self):
super().start()
self.__poller = zmq.asyncio.Poller()
self.__poller.register(self.zap_socket, zmq.POLLIN)
self.__task = asyncio.ensure_future(self.__handle_zap()) | [
"def",
"start",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"start",
"(",
")",
"self",
".",
"__poller",
"=",
"zmq",
".",
"asyncio",
".",
"Poller",
"(",
")",
"self",
".",
"__poller",
".",
"register",
"(",
"self",
".",
"zap_socket",
",",
"zmq",
".",
"POLLIN",
")",
"self",
".",
"__task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"__handle_zap",
"(",
")",
")"
] | Start ZAP authentication | [
"Start",
"ZAP",
"authentication"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/authenticator.py#L88-L93 |
248,067 | hyperledger/indy-plenum | stp_zmq/authenticator.py | AsyncioAuthenticator.stop | 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() | python | def stop(self):
if self.__task:
self.__task.cancel()
if self.__poller:
self.__poller.unregister(self.zap_socket)
self.__poller = None
super().stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"__task",
":",
"self",
".",
"__task",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"__poller",
":",
"self",
".",
"__poller",
".",
"unregister",
"(",
"self",
".",
"zap_socket",
")",
"self",
".",
"__poller",
"=",
"None",
"super",
"(",
")",
".",
"stop",
"(",
")"
] | Stop ZAP authentication | [
"Stop",
"ZAP",
"authentication"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/authenticator.py#L95-L102 |
248,068 | hyperledger/indy-plenum | plenum/common/util.py | randomString | 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 string
"""
def randomStr(size):
if not isinstance(size, int):
raise PlenumTypeError('size', size, int)
if not size > 0:
raise PlenumValueError('size', size, '> 0')
# Approach 1
rv = randombytes(size // 2).hex()
return rv if size % 2 == 0 else rv + hex(randombytes_uniform(15))[-1]
# Approach 2 this is faster than Approach 1, but lovesh had a doubt
# that part of a random may not be truly random, so until
# we have definite proof going to retain it commented
# rstr = randombytes(size).hex()
# return rstr[:size]
return randomStr(size) | python | def randomString(size: int = 20) -> str:
def randomStr(size):
if not isinstance(size, int):
raise PlenumTypeError('size', size, int)
if not size > 0:
raise PlenumValueError('size', size, '> 0')
# Approach 1
rv = randombytes(size // 2).hex()
return rv if size % 2 == 0 else rv + hex(randombytes_uniform(15))[-1]
# Approach 2 this is faster than Approach 1, but lovesh had a doubt
# that part of a random may not be truly random, so until
# we have definite proof going to retain it commented
# rstr = randombytes(size).hex()
# return rstr[:size]
return randomStr(size) | [
"def",
"randomString",
"(",
"size",
":",
"int",
"=",
"20",
")",
"->",
"str",
":",
"def",
"randomStr",
"(",
"size",
")",
":",
"if",
"not",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"raise",
"PlenumTypeError",
"(",
"'size'",
",",
"size",
",",
"int",
")",
"if",
"not",
"size",
">",
"0",
":",
"raise",
"PlenumValueError",
"(",
"'size'",
",",
"size",
",",
"'> 0'",
")",
"# Approach 1",
"rv",
"=",
"randombytes",
"(",
"size",
"//",
"2",
")",
".",
"hex",
"(",
")",
"return",
"rv",
"if",
"size",
"%",
"2",
"==",
"0",
"else",
"rv",
"+",
"hex",
"(",
"randombytes_uniform",
"(",
"15",
")",
")",
"[",
"-",
"1",
"]",
"# Approach 2 this is faster than Approach 1, but lovesh had a doubt",
"# that part of a random may not be truly random, so until",
"# we have definite proof going to retain it commented",
"# rstr = randombytes(size).hex()",
"# return rstr[:size]",
"return",
"randomStr",
"(",
"size",
")"
] | 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 | [
"Generate",
"a",
"random",
"string",
"in",
"hex",
"of",
"the",
"specified",
"size"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/util.py#L48-L75 |
248,069 | hyperledger/indy-plenum | plenum/common/util.py | mostCommonElement | 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 json.dumps
is used with sort_keys=True
:return: element which is the most frequent in the collection and
the number of its occurrences
"""
class _Hashable(collections.abc.Hashable):
def __init__(self, orig):
self.orig = orig
if isinstance(orig, collections.Hashable):
self.hashable = orig
elif to_hashable_f is not None:
self.hashable = to_hashable_f(orig)
else:
self.hashable = json.dumps(orig, sort_keys=True)
def __eq__(self, other):
return self.hashable == other.hashable
def __hash__(self):
return hash(self.hashable)
_elements = (_Hashable(el) for el in elements)
most_common, counter = Counter(_elements).most_common(n=1)[0]
return most_common.orig, counter | python | def mostCommonElement(elements: Iterable[T], to_hashable_f: Callable=None):
class _Hashable(collections.abc.Hashable):
def __init__(self, orig):
self.orig = orig
if isinstance(orig, collections.Hashable):
self.hashable = orig
elif to_hashable_f is not None:
self.hashable = to_hashable_f(orig)
else:
self.hashable = json.dumps(orig, sort_keys=True)
def __eq__(self, other):
return self.hashable == other.hashable
def __hash__(self):
return hash(self.hashable)
_elements = (_Hashable(el) for el in elements)
most_common, counter = Counter(_elements).most_common(n=1)[0]
return most_common.orig, counter | [
"def",
"mostCommonElement",
"(",
"elements",
":",
"Iterable",
"[",
"T",
"]",
",",
"to_hashable_f",
":",
"Callable",
"=",
"None",
")",
":",
"class",
"_Hashable",
"(",
"collections",
".",
"abc",
".",
"Hashable",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"orig",
")",
":",
"self",
".",
"orig",
"=",
"orig",
"if",
"isinstance",
"(",
"orig",
",",
"collections",
".",
"Hashable",
")",
":",
"self",
".",
"hashable",
"=",
"orig",
"elif",
"to_hashable_f",
"is",
"not",
"None",
":",
"self",
".",
"hashable",
"=",
"to_hashable_f",
"(",
"orig",
")",
"else",
":",
"self",
".",
"hashable",
"=",
"json",
".",
"dumps",
"(",
"orig",
",",
"sort_keys",
"=",
"True",
")",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"hashable",
"==",
"other",
".",
"hashable",
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"hashable",
")",
"_elements",
"=",
"(",
"_Hashable",
"(",
"el",
")",
"for",
"el",
"in",
"elements",
")",
"most_common",
",",
"counter",
"=",
"Counter",
"(",
"_elements",
")",
".",
"most_common",
"(",
"n",
"=",
"1",
")",
"[",
"0",
"]",
"return",
"most_common",
".",
"orig",
",",
"counter"
] | 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 frequent in the collection and
the number of its occurrences | [
"Find",
"the",
"most",
"frequent",
"element",
"of",
"a",
"collection",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/util.py#L92-L122 |
248,070 | hyperledger/indy-plenum | plenum/common/util.py | objSearchReplace | 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 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 recursion. optional. defaults to `set()`
:param logMsg: a custom log message
"""
if checked is None:
checked = set()
checked.add(id(obj))
pairs = [(i, getattr(obj, i)) for i in dir(obj) if not i.startswith("__")]
if isinstance(obj, Mapping):
pairs += [x for x in iteritems(obj)]
elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
pairs += [x for x in enumerate(obj)]
for nm, o in pairs:
if id(o) not in checked:
mutated = False
for old, new in toFrom.items():
if id(o) == id(old):
logging.debug(
"{}in object {}, attribute {} changed from {} to {}". format(
logMsg + ": " if logMsg else "", obj, nm, old, new))
if isinstance(obj, dict):
obj[nm] = new
else:
setattr(obj, nm, new)
mutated = True
if not mutated:
if deepLevel is not None and deepLevel == 0:
continue
objSearchReplace(o, toFrom, checked, logMsg, deepLevel -
1 if deepLevel is not None else deepLevel)
checked.remove(id(obj)) | python | def objSearchReplace(obj: Any,
toFrom: Dict[Any, Any],
checked: Set[Any]=None,
logMsg: str=None,
deepLevel: int=None) -> None:
if checked is None:
checked = set()
checked.add(id(obj))
pairs = [(i, getattr(obj, i)) for i in dir(obj) if not i.startswith("__")]
if isinstance(obj, Mapping):
pairs += [x for x in iteritems(obj)]
elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
pairs += [x for x in enumerate(obj)]
for nm, o in pairs:
if id(o) not in checked:
mutated = False
for old, new in toFrom.items():
if id(o) == id(old):
logging.debug(
"{}in object {}, attribute {} changed from {} to {}". format(
logMsg + ": " if logMsg else "", obj, nm, old, new))
if isinstance(obj, dict):
obj[nm] = new
else:
setattr(obj, nm, new)
mutated = True
if not mutated:
if deepLevel is not None and deepLevel == 0:
continue
objSearchReplace(o, toFrom, checked, logMsg, deepLevel -
1 if deepLevel is not None else deepLevel)
checked.remove(id(obj)) | [
"def",
"objSearchReplace",
"(",
"obj",
":",
"Any",
",",
"toFrom",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
"checked",
":",
"Set",
"[",
"Any",
"]",
"=",
"None",
",",
"logMsg",
":",
"str",
"=",
"None",
",",
"deepLevel",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"if",
"checked",
"is",
"None",
":",
"checked",
"=",
"set",
"(",
")",
"checked",
".",
"add",
"(",
"id",
"(",
"obj",
")",
")",
"pairs",
"=",
"[",
"(",
"i",
",",
"getattr",
"(",
"obj",
",",
"i",
")",
")",
"for",
"i",
"in",
"dir",
"(",
"obj",
")",
"if",
"not",
"i",
".",
"startswith",
"(",
"\"__\"",
")",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"Mapping",
")",
":",
"pairs",
"+=",
"[",
"x",
"for",
"x",
"in",
"iteritems",
"(",
"obj",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"Sequence",
",",
"Set",
")",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"pairs",
"+=",
"[",
"x",
"for",
"x",
"in",
"enumerate",
"(",
"obj",
")",
"]",
"for",
"nm",
",",
"o",
"in",
"pairs",
":",
"if",
"id",
"(",
"o",
")",
"not",
"in",
"checked",
":",
"mutated",
"=",
"False",
"for",
"old",
",",
"new",
"in",
"toFrom",
".",
"items",
"(",
")",
":",
"if",
"id",
"(",
"o",
")",
"==",
"id",
"(",
"old",
")",
":",
"logging",
".",
"debug",
"(",
"\"{}in object {}, attribute {} changed from {} to {}\"",
".",
"format",
"(",
"logMsg",
"+",
"\": \"",
"if",
"logMsg",
"else",
"\"\"",
",",
"obj",
",",
"nm",
",",
"old",
",",
"new",
")",
")",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"obj",
"[",
"nm",
"]",
"=",
"new",
"else",
":",
"setattr",
"(",
"obj",
",",
"nm",
",",
"new",
")",
"mutated",
"=",
"True",
"if",
"not",
"mutated",
":",
"if",
"deepLevel",
"is",
"not",
"None",
"and",
"deepLevel",
"==",
"0",
":",
"continue",
"objSearchReplace",
"(",
"o",
",",
"toFrom",
",",
"checked",
",",
"logMsg",
",",
"deepLevel",
"-",
"1",
"if",
"deepLevel",
"is",
"not",
"None",
"else",
"deepLevel",
")",
"checked",
".",
"remove",
"(",
"id",
"(",
"obj",
")",
")"
] | 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 recursion. optional. defaults to `set()`
:param logMsg: a custom log message | [
"Search",
"for",
"an",
"attribute",
"in",
"an",
"object",
"and",
"replace",
"it",
"with",
"another",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/util.py#L131-L174 |
248,071 | hyperledger/indy-plenum | plenum/common/util.py | runall | 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 | python | async def runall(corogen):
results = []
for c in corogen:
result = await c
results.append(result)
return results | [
"async",
"def",
"runall",
"(",
"corogen",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"corogen",
":",
"result",
"=",
"await",
"c",
"results",
".",
"append",
"(",
"result",
")",
"return",
"results"
] | Run an array of coroutines
:param corogen: a generator that generates coroutines
:return: list or returns of the coroutines | [
"Run",
"an",
"array",
"of",
"coroutines"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/util.py#L186-L197 |
248,072 | hyperledger/indy-plenum | plenum/common/util.py | prime_gen | 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
yield q
else:
x = p + q
while x in D:
x += p
D[x] = p | python | def prime_gen() -> int:
# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra
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
yield q
else:
x = p + q
while x in D:
x += p
D[x] = p | [
"def",
"prime_gen",
"(",
")",
"->",
"int",
":",
"# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra",
"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",
"yield",
"q",
"else",
":",
"x",
"=",
"p",
"+",
"q",
"while",
"x",
"in",
"D",
":",
"x",
"+=",
"p",
"D",
"[",
"x",
"]",
"=",
"p"
] | A generator for prime numbers starting from 2. | [
"A",
"generator",
"for",
"prime",
"numbers",
"starting",
"from",
"2",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/util.py#L254-L270 |
248,073 | hyperledger/indy-plenum | plenum/common/util.py | untilTrue | 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 timeout, False otherwise
"""
result = False
start = time.perf_counter()
elapsed = 0
while elapsed < timeout:
result = condition(*args)
if result:
break
await asyncio.sleep(.1)
elapsed = time.perf_counter() - start
return result | python | async def untilTrue(condition, *args, timeout=5) -> bool:
result = False
start = time.perf_counter()
elapsed = 0
while elapsed < timeout:
result = condition(*args)
if result:
break
await asyncio.sleep(.1)
elapsed = time.perf_counter() - start
return result | [
"async",
"def",
"untilTrue",
"(",
"condition",
",",
"*",
"args",
",",
"timeout",
"=",
"5",
")",
"->",
"bool",
":",
"result",
"=",
"False",
"start",
"=",
"time",
".",
"perf_counter",
"(",
")",
"elapsed",
"=",
"0",
"while",
"elapsed",
"<",
"timeout",
":",
"result",
"=",
"condition",
"(",
"*",
"args",
")",
"if",
"result",
":",
"break",
"await",
"asyncio",
".",
"sleep",
"(",
".1",
")",
"elapsed",
"=",
"time",
".",
"perf_counter",
"(",
")",
"-",
"start",
"return",
"result"
] | 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 | [
"Keep",
"checking",
"the",
"condition",
"till",
"it",
"is",
"true",
"or",
"a",
"timeout",
"is",
"reached"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/util.py#L273-L290 |
248,074 | hyperledger/indy-plenum | plenum/common/stacks.py | ClientZStack.transmitToClient | 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 isinstance(remoteName, str):
remoteName = remoteName.encode()
self.send(payload, remoteName)
except Exception as ex:
# TODO: This should not be an error since the client might not have
# sent the request to all nodes but only some nodes and other
# nodes might have got this request through PROPAGATE and thus
# might not have connection with the client.
logger.error(
"{}{} unable to send message {} to client {}; Exception: {}" .format(
CONNECTION_PREFIX, self, msg, remoteName, ex.__repr__())) | python | def transmitToClient(self, msg: Any, remoteName: str):
payload = self.prepForSending(msg)
try:
if isinstance(remoteName, str):
remoteName = remoteName.encode()
self.send(payload, remoteName)
except Exception as ex:
# TODO: This should not be an error since the client might not have
# sent the request to all nodes but only some nodes and other
# nodes might have got this request through PROPAGATE and thus
# might not have connection with the client.
logger.error(
"{}{} unable to send message {} to client {}; Exception: {}" .format(
CONNECTION_PREFIX, self, msg, remoteName, ex.__repr__())) | [
"def",
"transmitToClient",
"(",
"self",
",",
"msg",
":",
"Any",
",",
"remoteName",
":",
"str",
")",
":",
"payload",
"=",
"self",
".",
"prepForSending",
"(",
"msg",
")",
"try",
":",
"if",
"isinstance",
"(",
"remoteName",
",",
"str",
")",
":",
"remoteName",
"=",
"remoteName",
".",
"encode",
"(",
")",
"self",
".",
"send",
"(",
"payload",
",",
"remoteName",
")",
"except",
"Exception",
"as",
"ex",
":",
"# TODO: This should not be an error since the client might not have",
"# sent the request to all nodes but only some nodes and other",
"# nodes might have got this request through PROPAGATE and thus",
"# might not have connection with the client.",
"logger",
".",
"error",
"(",
"\"{}{} unable to send message {} to client {}; Exception: {}\"",
".",
"format",
"(",
"CONNECTION_PREFIX",
",",
"self",
",",
"msg",
",",
"remoteName",
",",
"ex",
".",
"__repr__",
"(",
")",
")",
")"
] | Transmit the specified message to the remote client specified by `remoteName`.
:param msg: a message
:param remoteName: the name of the remote | [
"Transmit",
"the",
"specified",
"message",
"to",
"the",
"remote",
"client",
"specified",
"by",
"remoteName",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/stacks.py#L139-L158 |
248,075 | hyperledger/indy-plenum | plenum/server/catchup/catchup_rep_service.py | CatchupRepService._has_valid_catchup_replies | 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 transactions ready to be processed
"""
# TODO: Remove after stop passing seqNo here
assert seq_no == txns_to_process[0][0]
# Here seqNo has to be the seqNo of first transaction of
# `catchupReplies`
# Get the transactions in the catchup reply which has sequence
# number `seqNo`
node_name, catchup_rep = self._find_catchup_reply_for_seq_no(seq_no)
txns = catchup_rep.txns
# Add only those transaction in the temporary tree from the above
# batch which are not present in the ledger
# Integer keys being converted to strings when marshaled to JSON
txns = [self._provider.transform_txn_for_ledger(txn)
for s, txn in txns_to_process[:len(txns)]
if str(s) in txns]
# Creating a temporary tree which will be used to verify consistency
# proof, by inserting transactions. Duplicating a merkle tree is not
# expensive since we are using a compact merkle tree.
temp_tree = self._ledger.treeWithAppliedTxns(txns)
proof = catchup_rep.consProof
final_size = self._catchup_till.final_size
final_hash = self._catchup_till.final_hash
try:
logger.info("{} verifying proof for {}, {}, {}, {}, {}".
format(self, temp_tree.tree_size, final_size,
temp_tree.root_hash, final_hash, proof))
verified = self._provider.verifier(self._ledger_id).verify_tree_consistency(
temp_tree.tree_size,
final_size,
temp_tree.root_hash,
Ledger.strToHash(final_hash),
[Ledger.strToHash(p) for p in proof]
)
except Exception as ex:
logger.info("{} could not verify catchup reply {} since {}".format(self, catchup_rep, ex))
verified = False
return bool(verified), node_name, len(txns) | python | def _has_valid_catchup_replies(self, seq_no: int, txns_to_process: List[Tuple[int, Any]]) -> Tuple[bool, str, int]:
# TODO: Remove after stop passing seqNo here
assert seq_no == txns_to_process[0][0]
# Here seqNo has to be the seqNo of first transaction of
# `catchupReplies`
# Get the transactions in the catchup reply which has sequence
# number `seqNo`
node_name, catchup_rep = self._find_catchup_reply_for_seq_no(seq_no)
txns = catchup_rep.txns
# Add only those transaction in the temporary tree from the above
# batch which are not present in the ledger
# Integer keys being converted to strings when marshaled to JSON
txns = [self._provider.transform_txn_for_ledger(txn)
for s, txn in txns_to_process[:len(txns)]
if str(s) in txns]
# Creating a temporary tree which will be used to verify consistency
# proof, by inserting transactions. Duplicating a merkle tree is not
# expensive since we are using a compact merkle tree.
temp_tree = self._ledger.treeWithAppliedTxns(txns)
proof = catchup_rep.consProof
final_size = self._catchup_till.final_size
final_hash = self._catchup_till.final_hash
try:
logger.info("{} verifying proof for {}, {}, {}, {}, {}".
format(self, temp_tree.tree_size, final_size,
temp_tree.root_hash, final_hash, proof))
verified = self._provider.verifier(self._ledger_id).verify_tree_consistency(
temp_tree.tree_size,
final_size,
temp_tree.root_hash,
Ledger.strToHash(final_hash),
[Ledger.strToHash(p) for p in proof]
)
except Exception as ex:
logger.info("{} could not verify catchup reply {} since {}".format(self, catchup_rep, ex))
verified = False
return bool(verified), node_name, len(txns) | [
"def",
"_has_valid_catchup_replies",
"(",
"self",
",",
"seq_no",
":",
"int",
",",
"txns_to_process",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"Any",
"]",
"]",
")",
"->",
"Tuple",
"[",
"bool",
",",
"str",
",",
"int",
"]",
":",
"# TODO: Remove after stop passing seqNo here",
"assert",
"seq_no",
"==",
"txns_to_process",
"[",
"0",
"]",
"[",
"0",
"]",
"# Here seqNo has to be the seqNo of first transaction of",
"# `catchupReplies`",
"# Get the transactions in the catchup reply which has sequence",
"# number `seqNo`",
"node_name",
",",
"catchup_rep",
"=",
"self",
".",
"_find_catchup_reply_for_seq_no",
"(",
"seq_no",
")",
"txns",
"=",
"catchup_rep",
".",
"txns",
"# Add only those transaction in the temporary tree from the above",
"# batch which are not present in the ledger",
"# Integer keys being converted to strings when marshaled to JSON",
"txns",
"=",
"[",
"self",
".",
"_provider",
".",
"transform_txn_for_ledger",
"(",
"txn",
")",
"for",
"s",
",",
"txn",
"in",
"txns_to_process",
"[",
":",
"len",
"(",
"txns",
")",
"]",
"if",
"str",
"(",
"s",
")",
"in",
"txns",
"]",
"# Creating a temporary tree which will be used to verify consistency",
"# proof, by inserting transactions. Duplicating a merkle tree is not",
"# expensive since we are using a compact merkle tree.",
"temp_tree",
"=",
"self",
".",
"_ledger",
".",
"treeWithAppliedTxns",
"(",
"txns",
")",
"proof",
"=",
"catchup_rep",
".",
"consProof",
"final_size",
"=",
"self",
".",
"_catchup_till",
".",
"final_size",
"final_hash",
"=",
"self",
".",
"_catchup_till",
".",
"final_hash",
"try",
":",
"logger",
".",
"info",
"(",
"\"{} verifying proof for {}, {}, {}, {}, {}\"",
".",
"format",
"(",
"self",
",",
"temp_tree",
".",
"tree_size",
",",
"final_size",
",",
"temp_tree",
".",
"root_hash",
",",
"final_hash",
",",
"proof",
")",
")",
"verified",
"=",
"self",
".",
"_provider",
".",
"verifier",
"(",
"self",
".",
"_ledger_id",
")",
".",
"verify_tree_consistency",
"(",
"temp_tree",
".",
"tree_size",
",",
"final_size",
",",
"temp_tree",
".",
"root_hash",
",",
"Ledger",
".",
"strToHash",
"(",
"final_hash",
")",
",",
"[",
"Ledger",
".",
"strToHash",
"(",
"p",
")",
"for",
"p",
"in",
"proof",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"info",
"(",
"\"{} could not verify catchup reply {} since {}\"",
".",
"format",
"(",
"self",
",",
"catchup_rep",
",",
"ex",
")",
")",
"verified",
"=",
"False",
"return",
"bool",
"(",
"verified",
")",
",",
"node_name",
",",
"len",
"(",
"txns",
")"
] | 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 | [
"Transforms",
"transactions",
"for",
"ledger!"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/catchup/catchup_rep_service.py#L374-L425 |
248,076 | hyperledger/indy-plenum | plenum/common/stack_manager.py | TxnStackManager._parse_pool_transaction_file | 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:
txn_data = get_payload_data(txn)
nodeName = txn_data[DATA][ALIAS]
clientStackName = nodeName + CLIENT_STACK_SUFFIX
nHa = (txn_data[DATA][NODE_IP], txn_data[DATA][NODE_PORT]) \
if (NODE_IP in txn_data[DATA] and NODE_PORT in txn_data[DATA]) \
else None
cHa = (txn_data[DATA][CLIENT_IP], txn_data[DATA][CLIENT_PORT]) \
if (CLIENT_IP in txn_data[DATA] and CLIENT_PORT in txn_data[DATA]) \
else None
if nHa:
nodeReg[nodeName] = HA(*nHa)
if cHa:
cliNodeReg[clientStackName] = HA(*cHa)
try:
# TODO: Need to handle abbreviated verkey
key_type = 'verkey'
verkey = cryptonymToHex(str(txn_data[TARGET_NYM]))
key_type = 'identifier'
cryptonymToHex(get_from(txn))
except ValueError:
logger.exception(
'Invalid {}. Rebuild pool transactions.'.format(key_type))
exit('Invalid {}. Rebuild pool transactions.'.format(key_type))
nodeKeys[nodeName] = verkey
services = txn_data[DATA].get(SERVICES)
if isinstance(services, list):
if VALIDATOR in services:
activeValidators.add(nodeName)
else:
activeValidators.discard(nodeName) | python | def _parse_pool_transaction_file(
ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
ledger_size=None):
for _, txn in ledger.getAllTxn(to=ledger_size):
if get_type(txn) == NODE:
txn_data = get_payload_data(txn)
nodeName = txn_data[DATA][ALIAS]
clientStackName = nodeName + CLIENT_STACK_SUFFIX
nHa = (txn_data[DATA][NODE_IP], txn_data[DATA][NODE_PORT]) \
if (NODE_IP in txn_data[DATA] and NODE_PORT in txn_data[DATA]) \
else None
cHa = (txn_data[DATA][CLIENT_IP], txn_data[DATA][CLIENT_PORT]) \
if (CLIENT_IP in txn_data[DATA] and CLIENT_PORT in txn_data[DATA]) \
else None
if nHa:
nodeReg[nodeName] = HA(*nHa)
if cHa:
cliNodeReg[clientStackName] = HA(*cHa)
try:
# TODO: Need to handle abbreviated verkey
key_type = 'verkey'
verkey = cryptonymToHex(str(txn_data[TARGET_NYM]))
key_type = 'identifier'
cryptonymToHex(get_from(txn))
except ValueError:
logger.exception(
'Invalid {}. Rebuild pool transactions.'.format(key_type))
exit('Invalid {}. Rebuild pool transactions.'.format(key_type))
nodeKeys[nodeName] = verkey
services = txn_data[DATA].get(SERVICES)
if isinstance(services, list):
if VALIDATOR in services:
activeValidators.add(nodeName)
else:
activeValidators.discard(nodeName) | [
"def",
"_parse_pool_transaction_file",
"(",
"ledger",
",",
"nodeReg",
",",
"cliNodeReg",
",",
"nodeKeys",
",",
"activeValidators",
",",
"ledger_size",
"=",
"None",
")",
":",
"for",
"_",
",",
"txn",
"in",
"ledger",
".",
"getAllTxn",
"(",
"to",
"=",
"ledger_size",
")",
":",
"if",
"get_type",
"(",
"txn",
")",
"==",
"NODE",
":",
"txn_data",
"=",
"get_payload_data",
"(",
"txn",
")",
"nodeName",
"=",
"txn_data",
"[",
"DATA",
"]",
"[",
"ALIAS",
"]",
"clientStackName",
"=",
"nodeName",
"+",
"CLIENT_STACK_SUFFIX",
"nHa",
"=",
"(",
"txn_data",
"[",
"DATA",
"]",
"[",
"NODE_IP",
"]",
",",
"txn_data",
"[",
"DATA",
"]",
"[",
"NODE_PORT",
"]",
")",
"if",
"(",
"NODE_IP",
"in",
"txn_data",
"[",
"DATA",
"]",
"and",
"NODE_PORT",
"in",
"txn_data",
"[",
"DATA",
"]",
")",
"else",
"None",
"cHa",
"=",
"(",
"txn_data",
"[",
"DATA",
"]",
"[",
"CLIENT_IP",
"]",
",",
"txn_data",
"[",
"DATA",
"]",
"[",
"CLIENT_PORT",
"]",
")",
"if",
"(",
"CLIENT_IP",
"in",
"txn_data",
"[",
"DATA",
"]",
"and",
"CLIENT_PORT",
"in",
"txn_data",
"[",
"DATA",
"]",
")",
"else",
"None",
"if",
"nHa",
":",
"nodeReg",
"[",
"nodeName",
"]",
"=",
"HA",
"(",
"*",
"nHa",
")",
"if",
"cHa",
":",
"cliNodeReg",
"[",
"clientStackName",
"]",
"=",
"HA",
"(",
"*",
"cHa",
")",
"try",
":",
"# TODO: Need to handle abbreviated verkey",
"key_type",
"=",
"'verkey'",
"verkey",
"=",
"cryptonymToHex",
"(",
"str",
"(",
"txn_data",
"[",
"TARGET_NYM",
"]",
")",
")",
"key_type",
"=",
"'identifier'",
"cryptonymToHex",
"(",
"get_from",
"(",
"txn",
")",
")",
"except",
"ValueError",
":",
"logger",
".",
"exception",
"(",
"'Invalid {}. Rebuild pool transactions.'",
".",
"format",
"(",
"key_type",
")",
")",
"exit",
"(",
"'Invalid {}. Rebuild pool transactions.'",
".",
"format",
"(",
"key_type",
")",
")",
"nodeKeys",
"[",
"nodeName",
"]",
"=",
"verkey",
"services",
"=",
"txn_data",
"[",
"DATA",
"]",
".",
"get",
"(",
"SERVICES",
")",
"if",
"isinstance",
"(",
"services",
",",
"list",
")",
":",
"if",
"VALIDATOR",
"in",
"services",
":",
"activeValidators",
".",
"add",
"(",
"nodeName",
")",
"else",
":",
"activeValidators",
".",
"discard",
"(",
"nodeName",
")"
] | helper function for parseLedgerForHaAndKeys | [
"helper",
"function",
"for",
"parseLedgerForHaAndKeys"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/stack_manager.py#L58-L98 |
248,077 | hyperledger/indy-plenum | ledger/merkle_verifier.py | MerkleVerifier.verify_tree_consistency | 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:
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 tree.
proof: the consistency proof.
Returns:
True. The return value is enforced by a decorator and need not be
checked by the caller.
Raises:
ConsistencyError: the proof indicates an inconsistency
(this is usually really serious!).
ProofError: the proof is invalid.
ValueError: supplied tree sizes are invalid.
"""
old_size = old_tree_size
new_size = new_tree_size
if old_size < 0 or new_size < 0:
raise ValueError("Negative tree size")
if old_size > new_size:
raise ValueError("Older tree has bigger size (%d vs %d), did "
"you supply inputs in the wrong order?" %
(old_size, new_size))
if old_size == new_size:
if old_root == new_root:
if proof:
logging.debug("Trees are identical, ignoring proof")
return True
else:
raise error.ConsistencyError("Inconsistency: different root "
"hashes for the same tree size")
if old_size == 0:
if proof:
# A consistency proof with an empty tree is an empty proof.
# Anything is consistent with an empty tree, so ignore whatever
# bogus proof was supplied. Note we do not verify here that the
# root hash is a valid hash for an empty tree.
logging.debug("Ignoring non-empty consistency proof for "
"empty tree.")
return True
# Now 0 < old_size < new_size
# A consistency proof is essentially an audit proof for the node with
# index old_size - 1 in the newer tree. The sole difference is that
# the path is already hashed together into a single hash up until the
# first audit node that occurs in the newer tree only.
node = old_size - 1
last_node = new_size - 1
# While we are the right child, everything is in both trees,
# so move one level up.
while node % 2:
node //= 2
last_node //= 2
p = iter(proof)
try:
if node:
# Compute the two root hashes in parallel.
new_hash = old_hash = next(p)
else:
# The old tree was balanced (2**k nodes), so we already have
# the first root hash.
new_hash = old_hash = old_root
while node:
if node % 2:
# node is a right child: left sibling exists in both trees.
next_node = next(p)
old_hash = self.hasher.hash_children(next_node, old_hash)
new_hash = self.hasher.hash_children(next_node, new_hash)
elif node < last_node:
# node is a left child: right sibling only exists in the
# newer tree.
new_hash = self.hasher.hash_children(new_hash, next(p))
# else node == last_node: node is a left child with no sibling
# in either tree.
node //= 2
last_node //= 2
# Now old_hash is the hash of the first subtree. If the two trees
# have different height, continue the path until the new root.
while last_node:
n = next(p)
new_hash = self.hasher.hash_children(new_hash, n)
last_node //= 2
# If the second hash does not match, the proof is invalid for the
# given pair. If, on the other hand, the newer hash matches but the
# older one doesn't, then the proof (together with the signatures
# on the hashes) is proof of inconsistency.
# Continue to find out.
if new_hash != new_root:
raise error.ProofError("Bad Merkle proof: second root hash "
"does not match. Expected hash: %s "
", computed hash: %s" %
(hexlify(new_root).strip(),
hexlify(new_hash).strip()))
elif old_hash != old_root:
raise error.ConsistencyError("Inconsistency: first root hash "
"does not match. Expected hash: "
"%s, computed hash: %s" %
(hexlify(old_root).strip(),
hexlify(old_hash).strip())
)
except StopIteration:
raise error.ProofError("Merkle proof is too short")
# We've already verified consistency, so accept the proof even if
# there's garbage left over (but log a warning).
try:
next(p)
except StopIteration:
pass
else:
logging.debug("Proof has extra nodes")
return True | python | def verify_tree_consistency(self, old_tree_size: int, new_tree_size: int,
old_root: bytes, new_root: bytes,
proof: Sequence[bytes]):
old_size = old_tree_size
new_size = new_tree_size
if old_size < 0 or new_size < 0:
raise ValueError("Negative tree size")
if old_size > new_size:
raise ValueError("Older tree has bigger size (%d vs %d), did "
"you supply inputs in the wrong order?" %
(old_size, new_size))
if old_size == new_size:
if old_root == new_root:
if proof:
logging.debug("Trees are identical, ignoring proof")
return True
else:
raise error.ConsistencyError("Inconsistency: different root "
"hashes for the same tree size")
if old_size == 0:
if proof:
# A consistency proof with an empty tree is an empty proof.
# Anything is consistent with an empty tree, so ignore whatever
# bogus proof was supplied. Note we do not verify here that the
# root hash is a valid hash for an empty tree.
logging.debug("Ignoring non-empty consistency proof for "
"empty tree.")
return True
# Now 0 < old_size < new_size
# A consistency proof is essentially an audit proof for the node with
# index old_size - 1 in the newer tree. The sole difference is that
# the path is already hashed together into a single hash up until the
# first audit node that occurs in the newer tree only.
node = old_size - 1
last_node = new_size - 1
# While we are the right child, everything is in both trees,
# so move one level up.
while node % 2:
node //= 2
last_node //= 2
p = iter(proof)
try:
if node:
# Compute the two root hashes in parallel.
new_hash = old_hash = next(p)
else:
# The old tree was balanced (2**k nodes), so we already have
# the first root hash.
new_hash = old_hash = old_root
while node:
if node % 2:
# node is a right child: left sibling exists in both trees.
next_node = next(p)
old_hash = self.hasher.hash_children(next_node, old_hash)
new_hash = self.hasher.hash_children(next_node, new_hash)
elif node < last_node:
# node is a left child: right sibling only exists in the
# newer tree.
new_hash = self.hasher.hash_children(new_hash, next(p))
# else node == last_node: node is a left child with no sibling
# in either tree.
node //= 2
last_node //= 2
# Now old_hash is the hash of the first subtree. If the two trees
# have different height, continue the path until the new root.
while last_node:
n = next(p)
new_hash = self.hasher.hash_children(new_hash, n)
last_node //= 2
# If the second hash does not match, the proof is invalid for the
# given pair. If, on the other hand, the newer hash matches but the
# older one doesn't, then the proof (together with the signatures
# on the hashes) is proof of inconsistency.
# Continue to find out.
if new_hash != new_root:
raise error.ProofError("Bad Merkle proof: second root hash "
"does not match. Expected hash: %s "
", computed hash: %s" %
(hexlify(new_root).strip(),
hexlify(new_hash).strip()))
elif old_hash != old_root:
raise error.ConsistencyError("Inconsistency: first root hash "
"does not match. Expected hash: "
"%s, computed hash: %s" %
(hexlify(old_root).strip(),
hexlify(old_hash).strip())
)
except StopIteration:
raise error.ProofError("Merkle proof is too short")
# We've already verified consistency, so accept the proof even if
# there's garbage left over (but log a warning).
try:
next(p)
except StopIteration:
pass
else:
logging.debug("Proof has extra nodes")
return True | [
"def",
"verify_tree_consistency",
"(",
"self",
",",
"old_tree_size",
":",
"int",
",",
"new_tree_size",
":",
"int",
",",
"old_root",
":",
"bytes",
",",
"new_root",
":",
"bytes",
",",
"proof",
":",
"Sequence",
"[",
"bytes",
"]",
")",
":",
"old_size",
"=",
"old_tree_size",
"new_size",
"=",
"new_tree_size",
"if",
"old_size",
"<",
"0",
"or",
"new_size",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Negative tree size\"",
")",
"if",
"old_size",
">",
"new_size",
":",
"raise",
"ValueError",
"(",
"\"Older tree has bigger size (%d vs %d), did \"",
"\"you supply inputs in the wrong order?\"",
"%",
"(",
"old_size",
",",
"new_size",
")",
")",
"if",
"old_size",
"==",
"new_size",
":",
"if",
"old_root",
"==",
"new_root",
":",
"if",
"proof",
":",
"logging",
".",
"debug",
"(",
"\"Trees are identical, ignoring proof\"",
")",
"return",
"True",
"else",
":",
"raise",
"error",
".",
"ConsistencyError",
"(",
"\"Inconsistency: different root \"",
"\"hashes for the same tree size\"",
")",
"if",
"old_size",
"==",
"0",
":",
"if",
"proof",
":",
"# A consistency proof with an empty tree is an empty proof.",
"# Anything is consistent with an empty tree, so ignore whatever",
"# bogus proof was supplied. Note we do not verify here that the",
"# root hash is a valid hash for an empty tree.",
"logging",
".",
"debug",
"(",
"\"Ignoring non-empty consistency proof for \"",
"\"empty tree.\"",
")",
"return",
"True",
"# Now 0 < old_size < new_size",
"# A consistency proof is essentially an audit proof for the node with",
"# index old_size - 1 in the newer tree. The sole difference is that",
"# the path is already hashed together into a single hash up until the",
"# first audit node that occurs in the newer tree only.",
"node",
"=",
"old_size",
"-",
"1",
"last_node",
"=",
"new_size",
"-",
"1",
"# While we are the right child, everything is in both trees,",
"# so move one level up.",
"while",
"node",
"%",
"2",
":",
"node",
"//=",
"2",
"last_node",
"//=",
"2",
"p",
"=",
"iter",
"(",
"proof",
")",
"try",
":",
"if",
"node",
":",
"# Compute the two root hashes in parallel.",
"new_hash",
"=",
"old_hash",
"=",
"next",
"(",
"p",
")",
"else",
":",
"# The old tree was balanced (2**k nodes), so we already have",
"# the first root hash.",
"new_hash",
"=",
"old_hash",
"=",
"old_root",
"while",
"node",
":",
"if",
"node",
"%",
"2",
":",
"# node is a right child: left sibling exists in both trees.",
"next_node",
"=",
"next",
"(",
"p",
")",
"old_hash",
"=",
"self",
".",
"hasher",
".",
"hash_children",
"(",
"next_node",
",",
"old_hash",
")",
"new_hash",
"=",
"self",
".",
"hasher",
".",
"hash_children",
"(",
"next_node",
",",
"new_hash",
")",
"elif",
"node",
"<",
"last_node",
":",
"# node is a left child: right sibling only exists in the",
"# newer tree.",
"new_hash",
"=",
"self",
".",
"hasher",
".",
"hash_children",
"(",
"new_hash",
",",
"next",
"(",
"p",
")",
")",
"# else node == last_node: node is a left child with no sibling",
"# in either tree.",
"node",
"//=",
"2",
"last_node",
"//=",
"2",
"# Now old_hash is the hash of the first subtree. If the two trees",
"# have different height, continue the path until the new root.",
"while",
"last_node",
":",
"n",
"=",
"next",
"(",
"p",
")",
"new_hash",
"=",
"self",
".",
"hasher",
".",
"hash_children",
"(",
"new_hash",
",",
"n",
")",
"last_node",
"//=",
"2",
"# If the second hash does not match, the proof is invalid for the",
"# given pair. If, on the other hand, the newer hash matches but the",
"# older one doesn't, then the proof (together with the signatures",
"# on the hashes) is proof of inconsistency.",
"# Continue to find out.",
"if",
"new_hash",
"!=",
"new_root",
":",
"raise",
"error",
".",
"ProofError",
"(",
"\"Bad Merkle proof: second root hash \"",
"\"does not match. Expected hash: %s \"",
"\", computed hash: %s\"",
"%",
"(",
"hexlify",
"(",
"new_root",
")",
".",
"strip",
"(",
")",
",",
"hexlify",
"(",
"new_hash",
")",
".",
"strip",
"(",
")",
")",
")",
"elif",
"old_hash",
"!=",
"old_root",
":",
"raise",
"error",
".",
"ConsistencyError",
"(",
"\"Inconsistency: first root hash \"",
"\"does not match. Expected hash: \"",
"\"%s, computed hash: %s\"",
"%",
"(",
"hexlify",
"(",
"old_root",
")",
".",
"strip",
"(",
")",
",",
"hexlify",
"(",
"old_hash",
")",
".",
"strip",
"(",
")",
")",
")",
"except",
"StopIteration",
":",
"raise",
"error",
".",
"ProofError",
"(",
"\"Merkle proof is too short\"",
")",
"# We've already verified consistency, so accept the proof even if",
"# there's garbage left over (but log a warning).",
"try",
":",
"next",
"(",
"p",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"logging",
".",
"debug",
"(",
"\"Proof has extra nodes\"",
")",
"return",
"True"
] | 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 tree.
proof: the consistency proof.
Returns:
True. The return value is enforced by a decorator and need not be
checked by the caller.
Raises:
ConsistencyError: the proof indicates an inconsistency
(this is usually really serious!).
ProofError: the proof is invalid.
ValueError: supplied tree sizes are invalid. | [
"Verify",
"the",
"consistency",
"between",
"two",
"root",
"hashes",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/ledger/merkle_verifier.py#L23-L153 |
248,078 | hyperledger/indy-plenum | plenum/server/has_action_queue.py | HasActionQueue._schedule | 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 seconds > 0:
nxt = time.perf_counter() + seconds
if nxt < self.aqNextCheck:
self.aqNextCheck = nxt
logger.trace("{} scheduling action {} with id {} to run in {} "
"seconds".format(self, get_func_name(action),
self.aid, seconds))
self.aqStash.append((nxt, (action, self.aid)))
else:
logger.trace("{} scheduling action {} with id {} to run now".
format(self, get_func_name(action), self.aid))
self.actionQueue.append((action, self.aid))
if action not in self.scheduled:
self.scheduled[action] = []
self.scheduled[action].append(self.aid)
return self.aid | python | def _schedule(self, action: Callable, seconds: int=0) -> int:
self.aid += 1
if seconds > 0:
nxt = time.perf_counter() + seconds
if nxt < self.aqNextCheck:
self.aqNextCheck = nxt
logger.trace("{} scheduling action {} with id {} to run in {} "
"seconds".format(self, get_func_name(action),
self.aid, seconds))
self.aqStash.append((nxt, (action, self.aid)))
else:
logger.trace("{} scheduling action {} with id {} to run now".
format(self, get_func_name(action), self.aid))
self.actionQueue.append((action, self.aid))
if action not in self.scheduled:
self.scheduled[action] = []
self.scheduled[action].append(self.aid)
return self.aid | [
"def",
"_schedule",
"(",
"self",
",",
"action",
":",
"Callable",
",",
"seconds",
":",
"int",
"=",
"0",
")",
"->",
"int",
":",
"self",
".",
"aid",
"+=",
"1",
"if",
"seconds",
">",
"0",
":",
"nxt",
"=",
"time",
".",
"perf_counter",
"(",
")",
"+",
"seconds",
"if",
"nxt",
"<",
"self",
".",
"aqNextCheck",
":",
"self",
".",
"aqNextCheck",
"=",
"nxt",
"logger",
".",
"trace",
"(",
"\"{} scheduling action {} with id {} to run in {} \"",
"\"seconds\"",
".",
"format",
"(",
"self",
",",
"get_func_name",
"(",
"action",
")",
",",
"self",
".",
"aid",
",",
"seconds",
")",
")",
"self",
".",
"aqStash",
".",
"append",
"(",
"(",
"nxt",
",",
"(",
"action",
",",
"self",
".",
"aid",
")",
")",
")",
"else",
":",
"logger",
".",
"trace",
"(",
"\"{} scheduling action {} with id {} to run now\"",
".",
"format",
"(",
"self",
",",
"get_func_name",
"(",
"action",
")",
",",
"self",
".",
"aid",
")",
")",
"self",
".",
"actionQueue",
".",
"append",
"(",
"(",
"action",
",",
"self",
".",
"aid",
")",
")",
"if",
"action",
"not",
"in",
"self",
".",
"scheduled",
":",
"self",
".",
"scheduled",
"[",
"action",
"]",
"=",
"[",
"]",
"self",
".",
"scheduled",
"[",
"action",
"]",
".",
"append",
"(",
"self",
".",
"aid",
")",
"return",
"self",
".",
"aid"
] | 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 | [
"Schedule",
"an",
"action",
"to",
"be",
"executed",
"after",
"seconds",
"seconds",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/has_action_queue.py#L23-L48 |
248,079 | hyperledger/indy-plenum | plenum/server/has_action_queue.py | HasActionQueue._cancel | def _cancel(self, action: Callable = None, aid: int = None):
"""
Cancel scheduled events
:param action: (optional) scheduled action. If specified, all
scheduled events for the action are cancelled.
:param aid: (options) scheduled event id. If specified,
scheduled event with the aid is cancelled.
"""
if action is not None:
if action in self.scheduled:
logger.trace("{} cancelling all events for action {}, ids: {}"
"".format(self, action, self.scheduled[action]))
self.scheduled[action].clear()
elif aid is not None:
for action, aids in self.scheduled.items():
try:
aids.remove(aid)
except ValueError:
pass
else:
logger.trace("{} cancelled action {} with id {}".format(self, action, aid))
break | python | def _cancel(self, action: Callable = None, aid: int = None):
if action is not None:
if action in self.scheduled:
logger.trace("{} cancelling all events for action {}, ids: {}"
"".format(self, action, self.scheduled[action]))
self.scheduled[action].clear()
elif aid is not None:
for action, aids in self.scheduled.items():
try:
aids.remove(aid)
except ValueError:
pass
else:
logger.trace("{} cancelled action {} with id {}".format(self, action, aid))
break | [
"def",
"_cancel",
"(",
"self",
",",
"action",
":",
"Callable",
"=",
"None",
",",
"aid",
":",
"int",
"=",
"None",
")",
":",
"if",
"action",
"is",
"not",
"None",
":",
"if",
"action",
"in",
"self",
".",
"scheduled",
":",
"logger",
".",
"trace",
"(",
"\"{} cancelling all events for action {}, ids: {}\"",
"\"\"",
".",
"format",
"(",
"self",
",",
"action",
",",
"self",
".",
"scheduled",
"[",
"action",
"]",
")",
")",
"self",
".",
"scheduled",
"[",
"action",
"]",
".",
"clear",
"(",
")",
"elif",
"aid",
"is",
"not",
"None",
":",
"for",
"action",
",",
"aids",
"in",
"self",
".",
"scheduled",
".",
"items",
"(",
")",
":",
"try",
":",
"aids",
".",
"remove",
"(",
"aid",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"logger",
".",
"trace",
"(",
"\"{} cancelled action {} with id {}\"",
".",
"format",
"(",
"self",
",",
"action",
",",
"aid",
")",
")",
"break"
] | Cancel scheduled events
:param action: (optional) scheduled action. If specified, all
scheduled events for the action are cancelled.
:param aid: (options) scheduled event id. If specified,
scheduled event with the aid is cancelled. | [
"Cancel",
"scheduled",
"events"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/has_action_queue.py#L50-L72 |
248,080 | hyperledger/indy-plenum | plenum/server/has_action_queue.py | HasActionQueue._serviceActions | 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 in list(self.aqStash):
nxt, action = d
if tm > nxt:
self.actionQueue.appendleft(action)
self.aqStash.remove(d)
if nxt < earliest:
earliest = nxt
self.aqNextCheck = earliest
count = len(self.actionQueue)
while self.actionQueue:
action, aid = self.actionQueue.popleft()
assert action in self.scheduled
if aid in self.scheduled[action]:
self.scheduled[action].remove(aid)
logger.trace("{} running action {} with id {}".
format(self, get_func_name(action), aid))
action()
else:
logger.trace("{} not running cancelled action {} with id {}".
format(self, get_func_name(action), aid))
return count | python | def _serviceActions(self) -> int:
if self.aqStash:
tm = time.perf_counter()
if tm > self.aqNextCheck:
earliest = float('inf')
for d in list(self.aqStash):
nxt, action = d
if tm > nxt:
self.actionQueue.appendleft(action)
self.aqStash.remove(d)
if nxt < earliest:
earliest = nxt
self.aqNextCheck = earliest
count = len(self.actionQueue)
while self.actionQueue:
action, aid = self.actionQueue.popleft()
assert action in self.scheduled
if aid in self.scheduled[action]:
self.scheduled[action].remove(aid)
logger.trace("{} running action {} with id {}".
format(self, get_func_name(action), aid))
action()
else:
logger.trace("{} not running cancelled action {} with id {}".
format(self, get_func_name(action), aid))
return count | [
"def",
"_serviceActions",
"(",
"self",
")",
"->",
"int",
":",
"if",
"self",
".",
"aqStash",
":",
"tm",
"=",
"time",
".",
"perf_counter",
"(",
")",
"if",
"tm",
">",
"self",
".",
"aqNextCheck",
":",
"earliest",
"=",
"float",
"(",
"'inf'",
")",
"for",
"d",
"in",
"list",
"(",
"self",
".",
"aqStash",
")",
":",
"nxt",
",",
"action",
"=",
"d",
"if",
"tm",
">",
"nxt",
":",
"self",
".",
"actionQueue",
".",
"appendleft",
"(",
"action",
")",
"self",
".",
"aqStash",
".",
"remove",
"(",
"d",
")",
"if",
"nxt",
"<",
"earliest",
":",
"earliest",
"=",
"nxt",
"self",
".",
"aqNextCheck",
"=",
"earliest",
"count",
"=",
"len",
"(",
"self",
".",
"actionQueue",
")",
"while",
"self",
".",
"actionQueue",
":",
"action",
",",
"aid",
"=",
"self",
".",
"actionQueue",
".",
"popleft",
"(",
")",
"assert",
"action",
"in",
"self",
".",
"scheduled",
"if",
"aid",
"in",
"self",
".",
"scheduled",
"[",
"action",
"]",
":",
"self",
".",
"scheduled",
"[",
"action",
"]",
".",
"remove",
"(",
"aid",
")",
"logger",
".",
"trace",
"(",
"\"{} running action {} with id {}\"",
".",
"format",
"(",
"self",
",",
"get_func_name",
"(",
"action",
")",
",",
"aid",
")",
")",
"action",
"(",
")",
"else",
":",
"logger",
".",
"trace",
"(",
"\"{} not running cancelled action {} with id {}\"",
".",
"format",
"(",
"self",
",",
"get_func_name",
"(",
"action",
")",
",",
"aid",
")",
")",
"return",
"count"
] | Run all pending actions in the action queue.
:return: number of actions executed. | [
"Run",
"all",
"pending",
"actions",
"in",
"the",
"action",
"queue",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/has_action_queue.py#L74-L104 |
248,081 | hyperledger/indy-plenum | plenum/server/node.py | Node.execute_pool_txns | 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_txns = self.default_executer(three_pc_batch)
for txn in committed_txns:
self.poolManager.onPoolMembershipChange(txn)
return committed_txns | python | def execute_pool_txns(self, three_pc_batch) -> List:
committed_txns = self.default_executer(three_pc_batch)
for txn in committed_txns:
self.poolManager.onPoolMembershipChange(txn)
return committed_txns | [
"def",
"execute_pool_txns",
"(",
"self",
",",
"three_pc_batch",
")",
"->",
"List",
":",
"committed_txns",
"=",
"self",
".",
"default_executer",
"(",
"three_pc_batch",
")",
"for",
"txn",
"in",
"committed_txns",
":",
"self",
".",
"poolManager",
".",
"onPoolMembershipChange",
"(",
"txn",
")",
"return",
"committed_txns"
] | 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 | [
"Execute",
"a",
"transaction",
"that",
"involves",
"consensus",
"pool",
"management",
"like",
"adding",
"a",
"node",
"client",
"or",
"a",
"steward",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L637-L648 |
248,082 | hyperledger/indy-plenum | plenum/server/node.py | Node.init_state_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'.format(self))
for seq_no, txn in ledger.getAllTxn():
txn = self.update_txn_with_extra_data(txn)
reqHandler.updateState([txn, ], isCommitted=True)
state.commit(rootHash=state.headHash) | python | def init_state_from_ledger(self, state: State, ledger: Ledger, reqHandler):
if state.isEmpty:
logger.info('{} found state to be empty, recreating from '
'ledger'.format(self))
for seq_no, txn in ledger.getAllTxn():
txn = self.update_txn_with_extra_data(txn)
reqHandler.updateState([txn, ], isCommitted=True)
state.commit(rootHash=state.headHash) | [
"def",
"init_state_from_ledger",
"(",
"self",
",",
"state",
":",
"State",
",",
"ledger",
":",
"Ledger",
",",
"reqHandler",
")",
":",
"if",
"state",
".",
"isEmpty",
":",
"logger",
".",
"info",
"(",
"'{} found state to be empty, recreating from '",
"'ledger'",
".",
"format",
"(",
"self",
")",
")",
"for",
"seq_no",
",",
"txn",
"in",
"ledger",
".",
"getAllTxn",
"(",
")",
":",
"txn",
"=",
"self",
".",
"update_txn_with_extra_data",
"(",
"txn",
")",
"reqHandler",
".",
"updateState",
"(",
"[",
"txn",
",",
"]",
",",
"isCommitted",
"=",
"True",
")",
"state",
".",
"commit",
"(",
"rootHash",
"=",
"state",
".",
"headHash",
")"
] | If the trie is empty then initialize it by applying
txns from ledger. | [
"If",
"the",
"trie",
"is",
"empty",
"then",
"initialize",
"it",
"by",
"applying",
"txns",
"from",
"ledger",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L663-L674 |
248,083 | hyperledger/indy-plenum | plenum/server/node.py | Node.on_view_change_start | 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()
logger.info("{} resetting monitor stats at view change start".format(self))
self.monitor.reset()
self.processStashedMsgsForView(self.viewNo)
self.backup_instance_faulty_processor.restore_replicas()
self.drop_primaries()
pop_keys(self.msgsForFutureViews, lambda x: x <= self.viewNo)
self.logNodeInfo()
# Keep on doing catchup until >(n-f) nodes LedgerStatus same on have a
# prepared certificate the first PRE-PREPARE of the new view
logger.info('{}{} changed to view {}, will start catchup now'.
format(VIEW_CHANGE_PREFIX, self, self.viewNo))
self._cancel(self._check_view_change_completed)
self._schedule(action=self._check_view_change_completed,
seconds=self._view_change_timeout)
# Set to 0 even when set to 0 in `on_view_change_complete` since
# catchup might be started due to several reasons.
self.catchup_rounds_without_txns = 0
self.last_sent_pp_store_helper.erase_last_sent_pp_seq_no() | python | def on_view_change_start(self):
self.view_changer.start_view_change_ts = self.utc_epoch()
for replica in self.replicas.values():
replica.on_view_change_start()
logger.info("{} resetting monitor stats at view change start".format(self))
self.monitor.reset()
self.processStashedMsgsForView(self.viewNo)
self.backup_instance_faulty_processor.restore_replicas()
self.drop_primaries()
pop_keys(self.msgsForFutureViews, lambda x: x <= self.viewNo)
self.logNodeInfo()
# Keep on doing catchup until >(n-f) nodes LedgerStatus same on have a
# prepared certificate the first PRE-PREPARE of the new view
logger.info('{}{} changed to view {}, will start catchup now'.
format(VIEW_CHANGE_PREFIX, self, self.viewNo))
self._cancel(self._check_view_change_completed)
self._schedule(action=self._check_view_change_completed,
seconds=self._view_change_timeout)
# Set to 0 even when set to 0 in `on_view_change_complete` since
# catchup might be started due to several reasons.
self.catchup_rounds_without_txns = 0
self.last_sent_pp_store_helper.erase_last_sent_pp_seq_no() | [
"def",
"on_view_change_start",
"(",
"self",
")",
":",
"self",
".",
"view_changer",
".",
"start_view_change_ts",
"=",
"self",
".",
"utc_epoch",
"(",
")",
"for",
"replica",
"in",
"self",
".",
"replicas",
".",
"values",
"(",
")",
":",
"replica",
".",
"on_view_change_start",
"(",
")",
"logger",
".",
"info",
"(",
"\"{} resetting monitor stats at view change start\"",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"monitor",
".",
"reset",
"(",
")",
"self",
".",
"processStashedMsgsForView",
"(",
"self",
".",
"viewNo",
")",
"self",
".",
"backup_instance_faulty_processor",
".",
"restore_replicas",
"(",
")",
"self",
".",
"drop_primaries",
"(",
")",
"pop_keys",
"(",
"self",
".",
"msgsForFutureViews",
",",
"lambda",
"x",
":",
"x",
"<=",
"self",
".",
"viewNo",
")",
"self",
".",
"logNodeInfo",
"(",
")",
"# Keep on doing catchup until >(n-f) nodes LedgerStatus same on have a",
"# prepared certificate the first PRE-PREPARE of the new view",
"logger",
".",
"info",
"(",
"'{}{} changed to view {}, will start catchup now'",
".",
"format",
"(",
"VIEW_CHANGE_PREFIX",
",",
"self",
",",
"self",
".",
"viewNo",
")",
")",
"self",
".",
"_cancel",
"(",
"self",
".",
"_check_view_change_completed",
")",
"self",
".",
"_schedule",
"(",
"action",
"=",
"self",
".",
"_check_view_change_completed",
",",
"seconds",
"=",
"self",
".",
"_view_change_timeout",
")",
"# Set to 0 even when set to 0 in `on_view_change_complete` since",
"# catchup might be started due to several reasons.",
"self",
".",
"catchup_rounds_without_txns",
"=",
"0",
"self",
".",
"last_sent_pp_store_helper",
".",
"erase_last_sent_pp_seq_no",
"(",
")"
] | Notifies node about the fact that view changed to let it
prepare for election | [
"Notifies",
"node",
"about",
"the",
"fact",
"that",
"view",
"changed",
"to",
"let",
"it",
"prepare",
"for",
"election"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L791-L821 |
248,084 | hyperledger/indy-plenum | plenum/server/node.py | Node.on_view_change_complete | 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:
raise LogicError(
"{} Not all replicas have "
"primaries: {}".format(self, self.replicas.primary_name_by_inst_id)
)
self._cancel(self._check_view_change_completed)
for replica in self.replicas.values():
replica.on_view_change_done()
self.view_changer.last_completed_view_no = self.view_changer.view_no
# Remove already ordered requests from requests list after view change
# If view change happen when one half of nodes ordered on master
# instance and backup but other only on master then we need to clear
# requests list. We do this to stop transactions ordering on backup
# replicas that have already been ordered on master.
# Test for this case in plenum/test/view_change/
# test_no_propagate_request_on_different_last_ordered_before_vc.py
for replica in self.replicas.values():
replica.clear_requests_and_fix_last_ordered()
self.monitor.reset() | python | def on_view_change_complete(self):
self.future_primaries_handler.set_node_state()
if not self.replicas.all_instances_have_primary:
raise LogicError(
"{} Not all replicas have "
"primaries: {}".format(self, self.replicas.primary_name_by_inst_id)
)
self._cancel(self._check_view_change_completed)
for replica in self.replicas.values():
replica.on_view_change_done()
self.view_changer.last_completed_view_no = self.view_changer.view_no
# Remove already ordered requests from requests list after view change
# If view change happen when one half of nodes ordered on master
# instance and backup but other only on master then we need to clear
# requests list. We do this to stop transactions ordering on backup
# replicas that have already been ordered on master.
# Test for this case in plenum/test/view_change/
# test_no_propagate_request_on_different_last_ordered_before_vc.py
for replica in self.replicas.values():
replica.clear_requests_and_fix_last_ordered()
self.monitor.reset() | [
"def",
"on_view_change_complete",
"(",
"self",
")",
":",
"self",
".",
"future_primaries_handler",
".",
"set_node_state",
"(",
")",
"if",
"not",
"self",
".",
"replicas",
".",
"all_instances_have_primary",
":",
"raise",
"LogicError",
"(",
"\"{} Not all replicas have \"",
"\"primaries: {}\"",
".",
"format",
"(",
"self",
",",
"self",
".",
"replicas",
".",
"primary_name_by_inst_id",
")",
")",
"self",
".",
"_cancel",
"(",
"self",
".",
"_check_view_change_completed",
")",
"for",
"replica",
"in",
"self",
".",
"replicas",
".",
"values",
"(",
")",
":",
"replica",
".",
"on_view_change_done",
"(",
")",
"self",
".",
"view_changer",
".",
"last_completed_view_no",
"=",
"self",
".",
"view_changer",
".",
"view_no",
"# Remove already ordered requests from requests list after view change",
"# If view change happen when one half of nodes ordered on master",
"# instance and backup but other only on master then we need to clear",
"# requests list. We do this to stop transactions ordering on backup",
"# replicas that have already been ordered on master.",
"# Test for this case in plenum/test/view_change/",
"# test_no_propagate_request_on_different_last_ordered_before_vc.py",
"for",
"replica",
"in",
"self",
".",
"replicas",
".",
"values",
"(",
")",
":",
"replica",
".",
"clear_requests_and_fix_last_ordered",
"(",
")",
"self",
".",
"monitor",
".",
"reset",
"(",
")"
] | View change completes for a replica when it has been decided which was
the last ppSeqNo and state and txn root for previous view | [
"View",
"change",
"completes",
"for",
"a",
"replica",
"when",
"it",
"has",
"been",
"decided",
"which",
"was",
"the",
"last",
"ppSeqNo",
"and",
"state",
"and",
"txn",
"root",
"for",
"previous",
"view"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L823-L851 |
248,085 | hyperledger/indy-plenum | plenum/server/node.py | Node.onStopping | 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_epoch())
self.logstats()
self.reset()
# Stop the ledgers
for ledger in self.ledgers:
try:
ledger.stop()
except Exception as ex:
logger.exception('{} got exception while stopping ledger: {}'.format(self, ex))
self.nodestack.stop()
self.clientstack.stop()
self.closeAllKVStores()
self._info_tool.stop()
self.mode = None
self.execute_hook(NodeHooks.POST_NODE_STOPPED) | python | def onStopping(self):
# 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_epoch())
self.logstats()
self.reset()
# Stop the ledgers
for ledger in self.ledgers:
try:
ledger.stop()
except Exception as ex:
logger.exception('{} got exception while stopping ledger: {}'.format(self, ex))
self.nodestack.stop()
self.clientstack.stop()
self.closeAllKVStores()
self._info_tool.stop()
self.mode = None
self.execute_hook(NodeHooks.POST_NODE_STOPPED) | [
"def",
"onStopping",
"(",
"self",
")",
":",
"# 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_epoch",
"(",
")",
")",
"self",
".",
"logstats",
"(",
")",
"self",
".",
"reset",
"(",
")",
"# Stop the ledgers",
"for",
"ledger",
"in",
"self",
".",
"ledgers",
":",
"try",
":",
"ledger",
".",
"stop",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"exception",
"(",
"'{} got exception while stopping ledger: {}'",
".",
"format",
"(",
"self",
",",
"ex",
")",
")",
"self",
".",
"nodestack",
".",
"stop",
"(",
")",
"self",
".",
"clientstack",
".",
"stop",
"(",
")",
"self",
".",
"closeAllKVStores",
"(",
")",
"self",
".",
"_info_tool",
".",
"stop",
"(",
")",
"self",
".",
"mode",
"=",
"None",
"self",
".",
"execute_hook",
"(",
"NodeHooks",
".",
"POST_NODE_STOPPED",
")"
] | Actions to be performed on stopping the node.
- Close the UDP socket of the nodestack | [
"Actions",
"to",
"be",
"performed",
"on",
"stopping",
"the",
"node",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1248-L1275 |
248,086 | hyperledger/indy-plenum | plenum/server/node.py | Node.prod | 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
"""
c = 0
if self.last_prod_started:
self.metrics.add_event(MetricsName.LOOPER_RUN_TIME_SPENT, time.perf_counter() - self.last_prod_started)
self.last_prod_started = time.perf_counter()
self.quota_control.update_state({
'request_queue_size': len(self.monitor.requestTracker.unordered())}
)
if self.status is not Status.stopped:
c += await self.serviceReplicas(limit)
c += await self.serviceNodeMsgs(limit)
c += await self.serviceClientMsgs(limit)
with self.metrics.measure_time(MetricsName.SERVICE_NODE_ACTIONS_TIME):
c += self._serviceActions()
with self.metrics.measure_time(MetricsName.SERVICE_TIMERS_TIME):
self.timer.service()
with self.metrics.measure_time(MetricsName.SERVICE_MONITOR_ACTIONS_TIME):
c += self.monitor._serviceActions()
c += await self.serviceViewChanger(limit)
c += await self.service_observable(limit)
c += await self.service_observer(limit)
with self.metrics.measure_time(MetricsName.FLUSH_OUTBOXES_TIME):
self.nodestack.flushOutBoxes()
if self.isGoing():
with self.metrics.measure_time(MetricsName.SERVICE_NODE_LIFECYCLE_TIME):
self.nodestack.serviceLifecycle()
with self.metrics.measure_time(MetricsName.SERVICE_CLIENT_STACK_TIME):
self.clientstack.serviceClientStack()
return c | python | async def prod(self, limit: int = None) -> int:
c = 0
if self.last_prod_started:
self.metrics.add_event(MetricsName.LOOPER_RUN_TIME_SPENT, time.perf_counter() - self.last_prod_started)
self.last_prod_started = time.perf_counter()
self.quota_control.update_state({
'request_queue_size': len(self.monitor.requestTracker.unordered())}
)
if self.status is not Status.stopped:
c += await self.serviceReplicas(limit)
c += await self.serviceNodeMsgs(limit)
c += await self.serviceClientMsgs(limit)
with self.metrics.measure_time(MetricsName.SERVICE_NODE_ACTIONS_TIME):
c += self._serviceActions()
with self.metrics.measure_time(MetricsName.SERVICE_TIMERS_TIME):
self.timer.service()
with self.metrics.measure_time(MetricsName.SERVICE_MONITOR_ACTIONS_TIME):
c += self.monitor._serviceActions()
c += await self.serviceViewChanger(limit)
c += await self.service_observable(limit)
c += await self.service_observer(limit)
with self.metrics.measure_time(MetricsName.FLUSH_OUTBOXES_TIME):
self.nodestack.flushOutBoxes()
if self.isGoing():
with self.metrics.measure_time(MetricsName.SERVICE_NODE_LIFECYCLE_TIME):
self.nodestack.serviceLifecycle()
with self.metrics.measure_time(MetricsName.SERVICE_CLIENT_STACK_TIME):
self.clientstack.serviceClientStack()
return c | [
"async",
"def",
"prod",
"(",
"self",
",",
"limit",
":",
"int",
"=",
"None",
")",
"->",
"int",
":",
"c",
"=",
"0",
"if",
"self",
".",
"last_prod_started",
":",
"self",
".",
"metrics",
".",
"add_event",
"(",
"MetricsName",
".",
"LOOPER_RUN_TIME_SPENT",
",",
"time",
".",
"perf_counter",
"(",
")",
"-",
"self",
".",
"last_prod_started",
")",
"self",
".",
"last_prod_started",
"=",
"time",
".",
"perf_counter",
"(",
")",
"self",
".",
"quota_control",
".",
"update_state",
"(",
"{",
"'request_queue_size'",
":",
"len",
"(",
"self",
".",
"monitor",
".",
"requestTracker",
".",
"unordered",
"(",
")",
")",
"}",
")",
"if",
"self",
".",
"status",
"is",
"not",
"Status",
".",
"stopped",
":",
"c",
"+=",
"await",
"self",
".",
"serviceReplicas",
"(",
"limit",
")",
"c",
"+=",
"await",
"self",
".",
"serviceNodeMsgs",
"(",
"limit",
")",
"c",
"+=",
"await",
"self",
".",
"serviceClientMsgs",
"(",
"limit",
")",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_NODE_ACTIONS_TIME",
")",
":",
"c",
"+=",
"self",
".",
"_serviceActions",
"(",
")",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_TIMERS_TIME",
")",
":",
"self",
".",
"timer",
".",
"service",
"(",
")",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_MONITOR_ACTIONS_TIME",
")",
":",
"c",
"+=",
"self",
".",
"monitor",
".",
"_serviceActions",
"(",
")",
"c",
"+=",
"await",
"self",
".",
"serviceViewChanger",
"(",
"limit",
")",
"c",
"+=",
"await",
"self",
".",
"service_observable",
"(",
"limit",
")",
"c",
"+=",
"await",
"self",
".",
"service_observer",
"(",
"limit",
")",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"FLUSH_OUTBOXES_TIME",
")",
":",
"self",
".",
"nodestack",
".",
"flushOutBoxes",
"(",
")",
"if",
"self",
".",
"isGoing",
"(",
")",
":",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_NODE_LIFECYCLE_TIME",
")",
":",
"self",
".",
"nodestack",
".",
"serviceLifecycle",
"(",
")",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_CLIENT_STACK_TIME",
")",
":",
"self",
".",
"clientstack",
".",
"serviceClientStack",
"(",
")",
"return",
"c"
] | .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 | [
".",
"opened",
"This",
"function",
"is",
"executed",
"by",
"the",
"node",
"each",
"time",
"it",
"gets",
"its",
"share",
"of",
"CPU",
"time",
"from",
"the",
"event",
"loop",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1309-L1349 |
248,087 | hyperledger/indy-plenum | plenum/server/node.py | Node.serviceNodeMsgs | 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.SERVICE_NODE_STACK_TIME):
n = await self.nodestack.service(limit, self.quota_control.node_quota)
self.metrics.add_event(MetricsName.NODE_STACK_MESSAGES_PROCESSED, n)
await self.processNodeInBox()
return n | python | async def serviceNodeMsgs(self, limit: int) -> int:
with self.metrics.measure_time(MetricsName.SERVICE_NODE_STACK_TIME):
n = await self.nodestack.service(limit, self.quota_control.node_quota)
self.metrics.add_event(MetricsName.NODE_STACK_MESSAGES_PROCESSED, n)
await self.processNodeInBox()
return n | [
"async",
"def",
"serviceNodeMsgs",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"int",
":",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"SERVICE_NODE_STACK_TIME",
")",
":",
"n",
"=",
"await",
"self",
".",
"nodestack",
".",
"service",
"(",
"limit",
",",
"self",
".",
"quota_control",
".",
"node_quota",
")",
"self",
".",
"metrics",
".",
"add_event",
"(",
"MetricsName",
".",
"NODE_STACK_MESSAGES_PROCESSED",
",",
"n",
")",
"await",
"self",
".",
"processNodeInBox",
"(",
")",
"return",
"n"
] | Process `limit` number of messages from the nodeInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed | [
"Process",
"limit",
"number",
"of",
"messages",
"from",
"the",
"nodeInBox",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1368-L1381 |
248,088 | hyperledger/indy-plenum | plenum/server/node.py | Node.serviceClientMsgs | 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, self.quota_control.client_quota)
self.metrics.add_event(MetricsName.CLIENT_STACK_MESSAGES_PROCESSED, c)
await self.processClientInBox()
return c | python | async def serviceClientMsgs(self, limit: int) -> int:
c = await self.clientstack.service(limit, self.quota_control.client_quota)
self.metrics.add_event(MetricsName.CLIENT_STACK_MESSAGES_PROCESSED, c)
await self.processClientInBox()
return c | [
"async",
"def",
"serviceClientMsgs",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"int",
":",
"c",
"=",
"await",
"self",
".",
"clientstack",
".",
"service",
"(",
"limit",
",",
"self",
".",
"quota_control",
".",
"client_quota",
")",
"self",
".",
"metrics",
".",
"add_event",
"(",
"MetricsName",
".",
"CLIENT_STACK_MESSAGES_PROCESSED",
",",
"c",
")",
"await",
"self",
".",
"processClientInBox",
"(",
")",
"return",
"c"
] | Process `limit` number of messages from the clientInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed | [
"Process",
"limit",
"number",
"of",
"messages",
"from",
"the",
"clientInBox",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1384-L1395 |
248,089 | hyperledger/indy-plenum | plenum/server/node.py | Node.serviceViewChanger | 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 = await self.serviceViewChangerInbox(limit)
return o + i | python | async def serviceViewChanger(self, limit) -> int:
if not self.isReady():
return 0
o = self.serviceViewChangerOutBox(limit)
i = await self.serviceViewChangerInbox(limit)
return o + i | [
"async",
"def",
"serviceViewChanger",
"(",
"self",
",",
"limit",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"return",
"0",
"o",
"=",
"self",
".",
"serviceViewChangerOutBox",
"(",
"limit",
")",
"i",
"=",
"await",
"self",
".",
"serviceViewChangerInbox",
"(",
"limit",
")",
"return",
"o",
"+",
"i"
] | Service the view_changer's inBox, outBox and action queues.
:return: the number of messages successfully serviced | [
"Service",
"the",
"view_changer",
"s",
"inBox",
"outBox",
"and",
"action",
"queues",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1398-L1408 |
248,090 | hyperledger/indy-plenum | plenum/server/node.py | Node.service_observable | 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._observable.serviceQueues(limit)
return o + i | python | async def service_observable(self, limit) -> int:
if not self.isReady():
return 0
o = self._service_observable_out_box(limit)
i = await self._observable.serviceQueues(limit)
return o + i | [
"async",
"def",
"service_observable",
"(",
"self",
",",
"limit",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"return",
"0",
"o",
"=",
"self",
".",
"_service_observable_out_box",
"(",
"limit",
")",
"i",
"=",
"await",
"self",
".",
"_observable",
".",
"serviceQueues",
"(",
"limit",
")",
"return",
"o",
"+",
"i"
] | Service the observable's inBox and outBox
:return: the number of messages successfully serviced | [
"Service",
"the",
"observable",
"s",
"inBox",
"and",
"outBox"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1411-L1421 |
248,091 | hyperledger/indy-plenum | plenum/server/node.py | Node._service_observable_out_box | 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:
break
msg = self._observable.get_output()
if not msg:
break
msg_count += 1
msg, observer_ids = msg
# TODO: it's assumed that all Observers are connected the same way as Validators
self.sendToNodes(msg, observer_ids)
return msg_count | python | def _service_observable_out_box(self, limit: int = None) -> int:
msg_count = 0
while True:
if limit and msg_count >= limit:
break
msg = self._observable.get_output()
if not msg:
break
msg_count += 1
msg, observer_ids = msg
# TODO: it's assumed that all Observers are connected the same way as Validators
self.sendToNodes(msg, observer_ids)
return msg_count | [
"def",
"_service_observable_out_box",
"(",
"self",
",",
"limit",
":",
"int",
"=",
"None",
")",
"->",
"int",
":",
"msg_count",
"=",
"0",
"while",
"True",
":",
"if",
"limit",
"and",
"msg_count",
">=",
"limit",
":",
"break",
"msg",
"=",
"self",
".",
"_observable",
".",
"get_output",
"(",
")",
"if",
"not",
"msg",
":",
"break",
"msg_count",
"+=",
"1",
"msg",
",",
"observer_ids",
"=",
"msg",
"# TODO: it's assumed that all Observers are connected the same way as Validators",
"self",
".",
"sendToNodes",
"(",
"msg",
",",
"observer_ids",
")",
"return",
"msg_count"
] | Service at most `limit` number of messages from the observable's outBox.
:return: the number of messages successfully serviced. | [
"Service",
"at",
"most",
"limit",
"number",
"of",
"messages",
"from",
"the",
"observable",
"s",
"outBox",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1423-L1442 |
248,092 | hyperledger/indy-plenum | plenum/server/node.py | Node.service_observer | 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) | python | async def service_observer(self, limit) -> int:
if not self.isReady():
return 0
return await self._observer.serviceQueues(limit) | [
"async",
"def",
"service_observer",
"(",
"self",
",",
"limit",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"return",
"0",
"return",
"await",
"self",
".",
"_observer",
".",
"serviceQueues",
"(",
"limit",
")"
] | Service the observer's inBox and outBox
:return: the number of messages successfully serviced | [
"Service",
"the",
"observer",
"s",
"inBox",
"and",
"outBox"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1445-L1453 |
248,093 | hyperledger/indy-plenum | plenum/server/node.py | Node._ask_for_ledger_status | 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_name, ledger_id)) | python | def _ask_for_ledger_status(self, node_name: str, ledger_id):
self.request_msg(LEDGER_STATUS, {f.LEDGER_ID.nm: ledger_id},
[node_name, ])
logger.info("{} asking {} for ledger status of ledger {}".format(self, node_name, ledger_id)) | [
"def",
"_ask_for_ledger_status",
"(",
"self",
",",
"node_name",
":",
"str",
",",
"ledger_id",
")",
":",
"self",
".",
"request_msg",
"(",
"LEDGER_STATUS",
",",
"{",
"f",
".",
"LEDGER_ID",
".",
"nm",
":",
"ledger_id",
"}",
",",
"[",
"node_name",
",",
"]",
")",
"logger",
".",
"info",
"(",
"\"{} asking {} for ledger status of ledger {}\"",
".",
"format",
"(",
"self",
",",
"node_name",
",",
"ledger_id",
")",
")"
] | Ask other node for LedgerStatus | [
"Ask",
"other",
"node",
"for",
"LedgerStatus"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1525-L1531 |
248,094 | hyperledger/indy-plenum | plenum/server/node.py | Node.checkInstances | 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.
This method is called whenever a connection with a new node is
established.
"""
logger.debug("{} choosing to start election on the basis of count {} and nodes {}".
format(self, self.connectedNodeCount, self.nodestack.conns)) | python | def checkInstances(self) -> None:
# TODO: Is this method really needed?
logger.debug("{} choosing to start election on the basis of count {} and nodes {}".
format(self, self.connectedNodeCount, self.nodestack.conns)) | [
"def",
"checkInstances",
"(",
"self",
")",
"->",
"None",
":",
"# TODO: Is this method really needed?",
"logger",
".",
"debug",
"(",
"\"{} choosing to start election on the basis of count {} and nodes {}\"",
".",
"format",
"(",
"self",
",",
"self",
".",
"connectedNodeCount",
",",
"self",
".",
"nodestack",
".",
"conns",
")",
")"
] | 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. | [
"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",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1587-L1597 |
248,095 | hyperledger/indy-plenum | plenum/server/node.py | Node.adjustReplicas | 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 replica_num < new_required_number_of_instances:
self.replicas.add_replica(replica_num)
self.processStashedMsgsForReplica(replica_num)
replica_num += 1
while replica_num > new_required_number_of_instances:
replica_num -= 1
self.replicas.remove_replica(replica_num)
pop_keys(self.msgsForFutureReplicas, lambda inst_id: inst_id < new_required_number_of_instances)
if len(self.primaries_disconnection_times) < new_required_number_of_instances:
self.primaries_disconnection_times.extend(
[None] * (new_required_number_of_instances - len(self.primaries_disconnection_times)))
elif len(self.primaries_disconnection_times) > new_required_number_of_instances:
self.primaries_disconnection_times = self.primaries_disconnection_times[:new_required_number_of_instances] | python | def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
# TODO: refactor this
replica_num = old_required_number_of_instances
while replica_num < new_required_number_of_instances:
self.replicas.add_replica(replica_num)
self.processStashedMsgsForReplica(replica_num)
replica_num += 1
while replica_num > new_required_number_of_instances:
replica_num -= 1
self.replicas.remove_replica(replica_num)
pop_keys(self.msgsForFutureReplicas, lambda inst_id: inst_id < new_required_number_of_instances)
if len(self.primaries_disconnection_times) < new_required_number_of_instances:
self.primaries_disconnection_times.extend(
[None] * (new_required_number_of_instances - len(self.primaries_disconnection_times)))
elif len(self.primaries_disconnection_times) > new_required_number_of_instances:
self.primaries_disconnection_times = self.primaries_disconnection_times[:new_required_number_of_instances] | [
"def",
"adjustReplicas",
"(",
"self",
",",
"old_required_number_of_instances",
":",
"int",
",",
"new_required_number_of_instances",
":",
"int",
")",
":",
"# TODO: refactor this",
"replica_num",
"=",
"old_required_number_of_instances",
"while",
"replica_num",
"<",
"new_required_number_of_instances",
":",
"self",
".",
"replicas",
".",
"add_replica",
"(",
"replica_num",
")",
"self",
".",
"processStashedMsgsForReplica",
"(",
"replica_num",
")",
"replica_num",
"+=",
"1",
"while",
"replica_num",
">",
"new_required_number_of_instances",
":",
"replica_num",
"-=",
"1",
"self",
".",
"replicas",
".",
"remove_replica",
"(",
"replica_num",
")",
"pop_keys",
"(",
"self",
".",
"msgsForFutureReplicas",
",",
"lambda",
"inst_id",
":",
"inst_id",
"<",
"new_required_number_of_instances",
")",
"if",
"len",
"(",
"self",
".",
"primaries_disconnection_times",
")",
"<",
"new_required_number_of_instances",
":",
"self",
".",
"primaries_disconnection_times",
".",
"extend",
"(",
"[",
"None",
"]",
"*",
"(",
"new_required_number_of_instances",
"-",
"len",
"(",
"self",
".",
"primaries_disconnection_times",
")",
")",
")",
"elif",
"len",
"(",
"self",
".",
"primaries_disconnection_times",
")",
">",
"new_required_number_of_instances",
":",
"self",
".",
"primaries_disconnection_times",
"=",
"self",
".",
"primaries_disconnection_times",
"[",
":",
"new_required_number_of_instances",
"]"
] | Add or remove replicas depending on `f` | [
"Add",
"or",
"remove",
"replicas",
"depending",
"on",
"f"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1599-L1622 |
248,096 | hyperledger/indy-plenum | plenum/server/node.py | Node._check_view_change_completed | 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_progress:
logger.info('{} already completion view change'.format(self))
return False
self.view_changer.on_view_change_not_completed_in_time()
return True | python | def _check_view_change_completed(self):
logger.info('{} running the scheduled check for view change completion'.format(self))
if not self.view_changer.view_change_in_progress:
logger.info('{} already completion view change'.format(self))
return False
self.view_changer.on_view_change_not_completed_in_time()
return True | [
"def",
"_check_view_change_completed",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'{} running the scheduled check for view change completion'",
".",
"format",
"(",
"self",
")",
")",
"if",
"not",
"self",
".",
"view_changer",
".",
"view_change_in_progress",
":",
"logger",
".",
"info",
"(",
"'{} already completion view change'",
".",
"format",
"(",
"self",
")",
")",
"return",
"False",
"self",
".",
"view_changer",
".",
"on_view_change_not_completed_in_time",
"(",
")",
"return",
"True"
] | This thing checks whether new primary was elected.
If it was not - starts view change again | [
"This",
"thing",
"checks",
"whether",
"new",
"primary",
"was",
"elected",
".",
"If",
"it",
"was",
"not",
"-",
"starts",
"view",
"change",
"again"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1663-L1674 |
248,097 | hyperledger/indy-plenum | plenum/server/node.py | Node.service_replicas_outbox | 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(message, (PrePrepare, Prepare, Commit, Checkpoint)):
self.send(message)
elif isinstance(message, Ordered):
self.try_processing_ordered(message)
elif isinstance(message, tuple) and isinstance(message[1], Reject):
with self.metrics.measure_time(MetricsName.NODE_SEND_REJECT_TIME):
digest, reject = message
result_reject = Reject(
reject.identifier,
reject.reqId,
self.reasonForClientFromException(
reject.reason))
# TODO: What the case when reqKey will be not in requestSender dict
if digest in self.requestSender:
self.transmitToClient(result_reject, self.requestSender[digest])
self.doneProcessingReq(digest)
elif isinstance(message, Exception):
self.processEscalatedException(message)
else:
# TODO: should not this raise exception?
logger.error("Received msg {} and don't "
"know how to handle it".format(message))
return num_processed | python | def service_replicas_outbox(self, limit: int = None) -> int:
# TODO: rewrite this using Router
num_processed = 0
for message in self.replicas.get_output(limit):
num_processed += 1
if isinstance(message, (PrePrepare, Prepare, Commit, Checkpoint)):
self.send(message)
elif isinstance(message, Ordered):
self.try_processing_ordered(message)
elif isinstance(message, tuple) and isinstance(message[1], Reject):
with self.metrics.measure_time(MetricsName.NODE_SEND_REJECT_TIME):
digest, reject = message
result_reject = Reject(
reject.identifier,
reject.reqId,
self.reasonForClientFromException(
reject.reason))
# TODO: What the case when reqKey will be not in requestSender dict
if digest in self.requestSender:
self.transmitToClient(result_reject, self.requestSender[digest])
self.doneProcessingReq(digest)
elif isinstance(message, Exception):
self.processEscalatedException(message)
else:
# TODO: should not this raise exception?
logger.error("Received msg {} and don't "
"know how to handle it".format(message))
return num_processed | [
"def",
"service_replicas_outbox",
"(",
"self",
",",
"limit",
":",
"int",
"=",
"None",
")",
"->",
"int",
":",
"# TODO: rewrite this using Router",
"num_processed",
"=",
"0",
"for",
"message",
"in",
"self",
".",
"replicas",
".",
"get_output",
"(",
"limit",
")",
":",
"num_processed",
"+=",
"1",
"if",
"isinstance",
"(",
"message",
",",
"(",
"PrePrepare",
",",
"Prepare",
",",
"Commit",
",",
"Checkpoint",
")",
")",
":",
"self",
".",
"send",
"(",
"message",
")",
"elif",
"isinstance",
"(",
"message",
",",
"Ordered",
")",
":",
"self",
".",
"try_processing_ordered",
"(",
"message",
")",
"elif",
"isinstance",
"(",
"message",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"message",
"[",
"1",
"]",
",",
"Reject",
")",
":",
"with",
"self",
".",
"metrics",
".",
"measure_time",
"(",
"MetricsName",
".",
"NODE_SEND_REJECT_TIME",
")",
":",
"digest",
",",
"reject",
"=",
"message",
"result_reject",
"=",
"Reject",
"(",
"reject",
".",
"identifier",
",",
"reject",
".",
"reqId",
",",
"self",
".",
"reasonForClientFromException",
"(",
"reject",
".",
"reason",
")",
")",
"# TODO: What the case when reqKey will be not in requestSender dict",
"if",
"digest",
"in",
"self",
".",
"requestSender",
":",
"self",
".",
"transmitToClient",
"(",
"result_reject",
",",
"self",
".",
"requestSender",
"[",
"digest",
"]",
")",
"self",
".",
"doneProcessingReq",
"(",
"digest",
")",
"elif",
"isinstance",
"(",
"message",
",",
"Exception",
")",
":",
"self",
".",
"processEscalatedException",
"(",
"message",
")",
"else",
":",
"# TODO: should not this raise exception?",
"logger",
".",
"error",
"(",
"\"Received msg {} and don't \"",
"\"know how to handle it\"",
".",
"format",
"(",
"message",
")",
")",
"return",
"num_processed"
] | Process `limit` number of replica messages | [
"Process",
"limit",
"number",
"of",
"replica",
"messages"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1677-L1708 |
248,098 | hyperledger/indy-plenum | plenum/server/node.py | Node.master_primary_name | 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 None | python | def master_primary_name(self) -> Optional[str]:
master_primary_name = self.master_replica.primaryName
if master_primary_name:
return self.master_replica.getNodeName(master_primary_name)
return None | [
"def",
"master_primary_name",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"master_primary_name",
"=",
"self",
".",
"master_replica",
".",
"primaryName",
"if",
"master_primary_name",
":",
"return",
"self",
".",
"master_replica",
".",
"getNodeName",
"(",
"master_primary_name",
")",
"return",
"None"
] | Return the name of the primary node of the master instance | [
"Return",
"the",
"name",
"of",
"the",
"primary",
"node",
"of",
"the",
"master",
"instance"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1758-L1766 |
248,099 | hyperledger/indy-plenum | plenum/server/node.py | Node.msgHasAcceptableInstId | 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!
instId = getattr(msg, f.INST_ID.nm, None)
if not (isinstance(instId, int) and instId >= 0):
return False
if instId >= self.requiredNumberOfInstances:
if instId not in self.msgsForFutureReplicas:
self.msgsForFutureReplicas[instId] = deque()
self.msgsForFutureReplicas[instId].append((msg, frm))
logger.debug("{} queueing message {} for future protocol instance {}".format(self, msg, instId))
return False
return True | python | def msgHasAcceptableInstId(self, msg, frm) -> bool:
# TODO: refactor this! this should not do anything except checking!
instId = getattr(msg, f.INST_ID.nm, None)
if not (isinstance(instId, int) and instId >= 0):
return False
if instId >= self.requiredNumberOfInstances:
if instId not in self.msgsForFutureReplicas:
self.msgsForFutureReplicas[instId] = deque()
self.msgsForFutureReplicas[instId].append((msg, frm))
logger.debug("{} queueing message {} for future protocol instance {}".format(self, msg, instId))
return False
return True | [
"def",
"msgHasAcceptableInstId",
"(",
"self",
",",
"msg",
",",
"frm",
")",
"->",
"bool",
":",
"# TODO: refactor this! this should not do anything except checking!",
"instId",
"=",
"getattr",
"(",
"msg",
",",
"f",
".",
"INST_ID",
".",
"nm",
",",
"None",
")",
"if",
"not",
"(",
"isinstance",
"(",
"instId",
",",
"int",
")",
"and",
"instId",
">=",
"0",
")",
":",
"return",
"False",
"if",
"instId",
">=",
"self",
".",
"requiredNumberOfInstances",
":",
"if",
"instId",
"not",
"in",
"self",
".",
"msgsForFutureReplicas",
":",
"self",
".",
"msgsForFutureReplicas",
"[",
"instId",
"]",
"=",
"deque",
"(",
")",
"self",
".",
"msgsForFutureReplicas",
"[",
"instId",
"]",
".",
"append",
"(",
"(",
"msg",
",",
"frm",
")",
")",
"logger",
".",
"debug",
"(",
"\"{} queueing message {} for future protocol instance {}\"",
".",
"format",
"(",
"self",
",",
"msg",
",",
"instId",
")",
")",
"return",
"False",
"return",
"True"
] | Return true if the instance id of message corresponds to a correct
replica.
:param msg: the node message to validate
:return: | [
"Return",
"true",
"if",
"the",
"instance",
"id",
"of",
"message",
"corresponds",
"to",
"a",
"correct",
"replica",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1778-L1796 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.