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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
hyperledger/indy-plenum | plenum/client/wallet.py | Wallet.signRequest | def signRequest(self,
req: Request,
identifier: Identifier=None) -> Request:
"""
Signs request. Modifies reqId and signature. May modify identifier.
:param req: request
:param requestIdStore: request id generator
:param identifier: signer identifier
:return: signed request
"""
idr = self.requiredIdr(idr=identifier or req._identifier)
# idData = self._getIdData(idr)
req._identifier = idr
req.reqId = req.gen_req_id()
# req.digest = req.getDigest()
# QUESTION: `self.ids[idr]` would be overwritten if same identifier
# is used to send 2 requests, why is `IdData` persisted?
# self.ids[idr] = IdData(idData.signer, req.reqId)
req.signature = self.signMsg(msg=req.signingPayloadState(identifier=idr),
identifier=idr,
otherIdentifier=req.identifier)
return req | python | def signRequest(self,
req: Request,
identifier: Identifier=None) -> Request:
"""
Signs request. Modifies reqId and signature. May modify identifier.
:param req: request
:param requestIdStore: request id generator
:param identifier: signer identifier
:return: signed request
"""
idr = self.requiredIdr(idr=identifier or req._identifier)
# idData = self._getIdData(idr)
req._identifier = idr
req.reqId = req.gen_req_id()
# req.digest = req.getDigest()
# QUESTION: `self.ids[idr]` would be overwritten if same identifier
# is used to send 2 requests, why is `IdData` persisted?
# self.ids[idr] = IdData(idData.signer, req.reqId)
req.signature = self.signMsg(msg=req.signingPayloadState(identifier=idr),
identifier=idr,
otherIdentifier=req.identifier)
return req | [
"def",
"signRequest",
"(",
"self",
",",
"req",
":",
"Request",
",",
"identifier",
":",
"Identifier",
"=",
"None",
")",
"->",
"Request",
":",
"idr",
"=",
"self",
".",
"requiredIdr",
"(",
"idr",
"=",
"identifier",
"or",
"req",
".",
"_identifier",
")",
"#... | Signs request. Modifies reqId and signature. May modify identifier.
:param req: request
:param requestIdStore: request id generator
:param identifier: signer identifier
:return: signed request | [
"Signs",
"request",
".",
"Modifies",
"reqId",
"and",
"signature",
".",
"May",
"modify",
"identifier",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L180-L204 | train | 229,000 |
hyperledger/indy-plenum | plenum/client/wallet.py | Wallet.signOp | def signOp(self,
op: Dict,
identifier: Identifier=None) -> Request:
"""
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request object
"""
request = Request(operation=op,
protocolVersion=CURRENT_PROTOCOL_VERSION)
return self.signRequest(request, identifier) | python | def signOp(self,
op: Dict,
identifier: Identifier=None) -> Request:
"""
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request object
"""
request = Request(operation=op,
protocolVersion=CURRENT_PROTOCOL_VERSION)
return self.signRequest(request, identifier) | [
"def",
"signOp",
"(",
"self",
",",
"op",
":",
"Dict",
",",
"identifier",
":",
"Identifier",
"=",
"None",
")",
"->",
"Request",
":",
"request",
"=",
"Request",
"(",
"operation",
"=",
"op",
",",
"protocolVersion",
"=",
"CURRENT_PROTOCOL_VERSION",
")",
"retur... | Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request object | [
"Signs",
"the",
"message",
"if",
"a",
"signer",
"is",
"configured"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L206-L219 | train | 229,001 |
hyperledger/indy-plenum | plenum/client/wallet.py | Wallet.listIds | def listIds(self, exclude=list()):
"""
For each signer in this wallet, return its alias if present else
return its identifier.
:param exclude:
:return: List of identifiers/aliases.
"""
lst = list(self.aliasesToIds.keys())
others = set(self.idsToSigners.keys()) - \
set(self.aliasesToIds.values())
lst.extend(list(others))
for x in exclude:
lst.remove(x)
return lst | python | def listIds(self, exclude=list()):
"""
For each signer in this wallet, return its alias if present else
return its identifier.
:param exclude:
:return: List of identifiers/aliases.
"""
lst = list(self.aliasesToIds.keys())
others = set(self.idsToSigners.keys()) - \
set(self.aliasesToIds.values())
lst.extend(list(others))
for x in exclude:
lst.remove(x)
return lst | [
"def",
"listIds",
"(",
"self",
",",
"exclude",
"=",
"list",
"(",
")",
")",
":",
"lst",
"=",
"list",
"(",
"self",
".",
"aliasesToIds",
".",
"keys",
"(",
")",
")",
"others",
"=",
"set",
"(",
"self",
".",
"idsToSigners",
".",
"keys",
"(",
")",
")",
... | For each signer in this wallet, return its alias if present else
return its identifier.
:param exclude:
:return: List of identifiers/aliases. | [
"For",
"each",
"signer",
"in",
"this",
"wallet",
"return",
"its",
"alias",
"if",
"present",
"else",
"return",
"its",
"identifier",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L267-L281 | train | 229,002 |
hyperledger/indy-plenum | plenum/client/wallet.py | WalletStorageHelper.saveWallet | def saveWallet(self, wallet, fpath):
"""Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fpath`` exists and it's not a directory -
NotADirectoryError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param wallet: wallet to save
:param fpath: wallet file path, absolute or relative to
keyrings base dir
"""
if not fpath:
raise ValueError("empty path")
_fpath = self._normalize(fpath)
_dpath = _fpath.parent
try:
_dpath.relative_to(self._baseDir)
except ValueError:
raise ValueError(
"path {} is not is not relative to the keyrings {}".format(
fpath, self._baseDir))
self._createDirIfNotExists(_dpath)
# ensure permissions from the bottom of the directory hierarchy
while _dpath != self._baseDir:
self._ensurePermissions(_dpath, self.dmode)
_dpath = _dpath.parent
with _fpath.open("w") as wf:
self._ensurePermissions(_fpath, self.fmode)
encodedWallet = self.encode(wallet)
wf.write(encodedWallet)
logger.debug("stored wallet '{}' in {}".format(
wallet.name, _fpath))
return str(_fpath) | python | def saveWallet(self, wallet, fpath):
"""Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fpath`` exists and it's not a directory -
NotADirectoryError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param wallet: wallet to save
:param fpath: wallet file path, absolute or relative to
keyrings base dir
"""
if not fpath:
raise ValueError("empty path")
_fpath = self._normalize(fpath)
_dpath = _fpath.parent
try:
_dpath.relative_to(self._baseDir)
except ValueError:
raise ValueError(
"path {} is not is not relative to the keyrings {}".format(
fpath, self._baseDir))
self._createDirIfNotExists(_dpath)
# ensure permissions from the bottom of the directory hierarchy
while _dpath != self._baseDir:
self._ensurePermissions(_dpath, self.dmode)
_dpath = _dpath.parent
with _fpath.open("w") as wf:
self._ensurePermissions(_fpath, self.fmode)
encodedWallet = self.encode(wallet)
wf.write(encodedWallet)
logger.debug("stored wallet '{}' in {}".format(
wallet.name, _fpath))
return str(_fpath) | [
"def",
"saveWallet",
"(",
"self",
",",
"wallet",
",",
"fpath",
")",
":",
"if",
"not",
"fpath",
":",
"raise",
"ValueError",
"(",
"\"empty path\"",
")",
"_fpath",
"=",
"self",
".",
"_normalize",
"(",
"fpath",
")",
"_dpath",
"=",
"_fpath",
".",
"parent",
... | Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fpath`` exists and it's not a directory -
NotADirectoryError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param wallet: wallet to save
:param fpath: wallet file path, absolute or relative to
keyrings base dir | [
"Save",
"wallet",
"into",
"specified",
"localtion",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L351-L394 | train | 229,003 |
hyperledger/indy-plenum | plenum/client/wallet.py | WalletStorageHelper.loadWallet | def loadWallet(self, fpath):
"""Load wallet from specified localtion.
Returns loaded wallet.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param fpath: wallet file path, absolute or relative to
keyrings base dir
"""
if not fpath:
raise ValueError("empty path")
_fpath = self._normalize(fpath)
_dpath = _fpath.parent
try:
_dpath.relative_to(self._baseDir)
except ValueError:
raise ValueError(
"path {} is not is not relative to the wallets {}".format(
fpath, self._baseDir))
with _fpath.open() as wf:
wallet = self.decode(wf.read())
return wallet | python | def loadWallet(self, fpath):
"""Load wallet from specified localtion.
Returns loaded wallet.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param fpath: wallet file path, absolute or relative to
keyrings base dir
"""
if not fpath:
raise ValueError("empty path")
_fpath = self._normalize(fpath)
_dpath = _fpath.parent
try:
_dpath.relative_to(self._baseDir)
except ValueError:
raise ValueError(
"path {} is not is not relative to the wallets {}".format(
fpath, self._baseDir))
with _fpath.open() as wf:
wallet = self.decode(wf.read())
return wallet | [
"def",
"loadWallet",
"(",
"self",
",",
"fpath",
")",
":",
"if",
"not",
"fpath",
":",
"raise",
"ValueError",
"(",
"\"empty path\"",
")",
"_fpath",
"=",
"self",
".",
"_normalize",
"(",
"fpath",
")",
"_dpath",
"=",
"_fpath",
".",
"parent",
"try",
":",
"_d... | Load wallet from specified localtion.
Returns loaded wallet.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param fpath: wallet file path, absolute or relative to
keyrings base dir | [
"Load",
"wallet",
"from",
"specified",
"localtion",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L396-L424 | train | 229,004 |
hyperledger/indy-plenum | plenum/server/models.py | Prepares.addVote | def addVote(self, prepare: Prepare, voter: str) -> None:
"""
Add the specified PREPARE to this replica's list of received
PREPAREs.
:param prepare: the PREPARE to add to the list
:param voter: the name of the node who sent the PREPARE
"""
self._add_msg(prepare, voter) | python | def addVote(self, prepare: Prepare, voter: str) -> None:
"""
Add the specified PREPARE to this replica's list of received
PREPAREs.
:param prepare: the PREPARE to add to the list
:param voter: the name of the node who sent the PREPARE
"""
self._add_msg(prepare, voter) | [
"def",
"addVote",
"(",
"self",
",",
"prepare",
":",
"Prepare",
",",
"voter",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_add_msg",
"(",
"prepare",
",",
"voter",
")"
] | Add the specified PREPARE to this replica's list of received
PREPAREs.
:param prepare: the PREPARE to add to the list
:param voter: the name of the node who sent the PREPARE | [
"Add",
"the",
"specified",
"PREPARE",
"to",
"this",
"replica",
"s",
"list",
"of",
"received",
"PREPAREs",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/models.py#L62-L70 | train | 229,005 |
hyperledger/indy-plenum | plenum/server/models.py | Commits.addVote | def addVote(self, commit: Commit, voter: str) -> None:
"""
Add the specified COMMIT to this replica's list of received
COMMITs.
:param commit: the COMMIT to add to the list
:param voter: the name of the replica who sent the COMMIT
"""
super()._add_msg(commit, voter) | python | def addVote(self, commit: Commit, voter: str) -> None:
"""
Add the specified COMMIT to this replica's list of received
COMMITs.
:param commit: the COMMIT to add to the list
:param voter: the name of the replica who sent the COMMIT
"""
super()._add_msg(commit, voter) | [
"def",
"addVote",
"(",
"self",
",",
"commit",
":",
"Commit",
",",
"voter",
":",
"str",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"_add_msg",
"(",
"commit",
",",
"voter",
")"
] | Add the specified COMMIT to this replica's list of received
COMMITs.
:param commit: the COMMIT to add to the list
:param voter: the name of the replica who sent the COMMIT | [
"Add",
"the",
"specified",
"COMMIT",
"to",
"this",
"replica",
"s",
"list",
"of",
"received",
"COMMITs",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/models.py#L96-L104 | train | 229,006 |
hyperledger/indy-plenum | plenum/common/message_processor.py | MessageProcessor.discard | def discard(self, msg, reason, logMethod=logging.error, cliOutput=False):
"""
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:param cliOutput: if truthy, informs a CLI that the logged msg should
be printed
"""
reason = "" if not reason else " because {}".format(reason)
logMethod("{} discarding message {}{}".format(self, msg, reason),
extra={"cli": cliOutput}) | python | def discard(self, msg, reason, logMethod=logging.error, cliOutput=False):
"""
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:param cliOutput: if truthy, informs a CLI that the logged msg should
be printed
"""
reason = "" if not reason else " because {}".format(reason)
logMethod("{} discarding message {}{}".format(self, msg, reason),
extra={"cli": cliOutput}) | [
"def",
"discard",
"(",
"self",
",",
"msg",
",",
"reason",
",",
"logMethod",
"=",
"logging",
".",
"error",
",",
"cliOutput",
"=",
"False",
")",
":",
"reason",
"=",
"\"\"",
"if",
"not",
"reason",
"else",
"\" because {}\"",
".",
"format",
"(",
"reason",
"... | Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:param cliOutput: if truthy, informs a CLI that the logged msg should
be printed | [
"Discard",
"a",
"message",
"and",
"log",
"a",
"reason",
"using",
"the",
"specified",
"logMethod",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/message_processor.py#L18-L30 | train | 229,007 |
hyperledger/indy-plenum | plenum/common/message_processor.py | MessageProcessor.toDict | def toDict(self, msg: Dict) -> Dict:
"""
Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission
"""
if isinstance(msg, Request):
tmsg = msg.as_dict
elif hasattr(msg, "_asdict"):
tmsg = dict(msg._asdict())
elif hasattr(msg, "__dict__"):
tmsg = dict(msg.__dict__)
elif self.allowDictOnly:
raise ValueError("Message cannot be converted to an appropriate "
"format for transmission")
else:
tmsg = msg
return tmsg | python | def toDict(self, msg: Dict) -> Dict:
"""
Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission
"""
if isinstance(msg, Request):
tmsg = msg.as_dict
elif hasattr(msg, "_asdict"):
tmsg = dict(msg._asdict())
elif hasattr(msg, "__dict__"):
tmsg = dict(msg.__dict__)
elif self.allowDictOnly:
raise ValueError("Message cannot be converted to an appropriate "
"format for transmission")
else:
tmsg = msg
return tmsg | [
"def",
"toDict",
"(",
"self",
",",
"msg",
":",
"Dict",
")",
"->",
"Dict",
":",
"if",
"isinstance",
"(",
"msg",
",",
"Request",
")",
":",
"tmsg",
"=",
"msg",
".",
"as_dict",
"elif",
"hasattr",
"(",
"msg",
",",
"\"_asdict\"",
")",
":",
"tmsg",
"=",
... | Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission | [
"Return",
"a",
"dictionary",
"form",
"of",
"the",
"message"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/message_processor.py#L32-L52 | train | 229,008 |
hyperledger/indy-plenum | plenum/server/replica_freshness_checker.py | FreshnessChecker.update_freshness | def update_freshness(self, ledger_id, ts):
'''
Updates the time at which the ledger was updated.
Should be called whenever a txn for the ledger is ordered.
:param ledger_id: the ID of the ledgers a txn was ordered for
:param ts: the current time
:return: None
'''
if ledger_id in self._ledger_freshness:
self._ledger_freshness[ledger_id].last_updated = ts | python | def update_freshness(self, ledger_id, ts):
'''
Updates the time at which the ledger was updated.
Should be called whenever a txn for the ledger is ordered.
:param ledger_id: the ID of the ledgers a txn was ordered for
:param ts: the current time
:return: None
'''
if ledger_id in self._ledger_freshness:
self._ledger_freshness[ledger_id].last_updated = ts | [
"def",
"update_freshness",
"(",
"self",
",",
"ledger_id",
",",
"ts",
")",
":",
"if",
"ledger_id",
"in",
"self",
".",
"_ledger_freshness",
":",
"self",
".",
"_ledger_freshness",
"[",
"ledger_id",
"]",
".",
"last_updated",
"=",
"ts"
] | Updates the time at which the ledger was updated.
Should be called whenever a txn for the ledger is ordered.
:param ledger_id: the ID of the ledgers a txn was ordered for
:param ts: the current time
:return: None | [
"Updates",
"the",
"time",
"at",
"which",
"the",
"ledger",
"was",
"updated",
".",
"Should",
"be",
"called",
"whenever",
"a",
"txn",
"for",
"the",
"ledger",
"is",
"ordered",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica_freshness_checker.py#L50-L60 | train | 229,009 |
hyperledger/indy-plenum | plenum/server/replica_freshness_checker.py | FreshnessChecker.get_last_update_time | def get_last_update_time(self):
'''
Gets the time at which each ledger was updated.
Can be called at any time to get this information.
:return: an ordered dict of outdated ledgers sorted by last update time (from old to new)
and then by ledger ID (in case of equal update time)
'''
last_updated = {ledger_id: freshness_state.last_updated
for ledger_id, freshness_state in self._ledger_freshness.items()}
return OrderedDict(
sorted(
last_updated.items(),
key=lambda item: (item[1], item[0])
)
) | python | def get_last_update_time(self):
'''
Gets the time at which each ledger was updated.
Can be called at any time to get this information.
:return: an ordered dict of outdated ledgers sorted by last update time (from old to new)
and then by ledger ID (in case of equal update time)
'''
last_updated = {ledger_id: freshness_state.last_updated
for ledger_id, freshness_state in self._ledger_freshness.items()}
return OrderedDict(
sorted(
last_updated.items(),
key=lambda item: (item[1], item[0])
)
) | [
"def",
"get_last_update_time",
"(",
"self",
")",
":",
"last_updated",
"=",
"{",
"ledger_id",
":",
"freshness_state",
".",
"last_updated",
"for",
"ledger_id",
",",
"freshness_state",
"in",
"self",
".",
"_ledger_freshness",
".",
"items",
"(",
")",
"}",
"return",
... | Gets the time at which each ledger was updated.
Can be called at any time to get this information.
:return: an ordered dict of outdated ledgers sorted by last update time (from old to new)
and then by ledger ID (in case of equal update time) | [
"Gets",
"the",
"time",
"at",
"which",
"each",
"ledger",
"was",
"updated",
".",
"Can",
"be",
"called",
"at",
"any",
"time",
"to",
"get",
"this",
"information",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica_freshness_checker.py#L62-L77 | train | 229,010 |
hyperledger/indy-plenum | common/serializers/signing_serializer.py | SigningSerializer.serialize | def serialize(self, obj, level=0, objname=None, topLevelKeysToIgnore=None,
toBytes=True):
"""
Create a string representation of the given object.
Examples:
::
>>> serialize("str")
'str'
>>> serialize([1,2,3,4,5])
'1,2,3,4,5'
>>> signing.serlize({1:'a', 2:'b'})
'1:a|2:b'
>>> signing.serlize({1:'a', 2:'b', 3:[1,{2:'k'}]})
'1:a|2:b|3:1,2:k'
:param obj: the object to serlize
:param level: a parameter used internally for recursion to serialize nested
data structures
:param topLevelKeysToIgnore: the list of top level keys to ignore for
serialization
:return: a string representation of `obj`
"""
res = None
if not isinstance(obj, acceptableTypes):
error("invalid type found {}: {}".format(objname, obj))
elif isinstance(obj, str):
res = obj
elif isinstance(obj, dict):
if level > 0:
keys = list(obj.keys())
else:
topLevelKeysToIgnore = topLevelKeysToIgnore or []
keys = [k for k in obj.keys() if k not in topLevelKeysToIgnore]
keys.sort()
strs = []
for k in keys:
onm = ".".join([str(objname), str(k)]) if objname else k
strs.append(
str(k) + ":" + self.serialize(obj[k], level + 1, onm, toBytes=False))
res = "|".join(strs)
elif isinstance(obj, Iterable):
strs = []
for o in obj:
strs.append(self.serialize(
o, level + 1, objname, toBytes=False))
res = ",".join(strs)
elif obj is None:
res = ""
else:
res = str(obj)
# logger.trace("serialized msg {} into {}".format(obj, res))
if not toBytes:
return res
return res.encode('utf-8') | python | def serialize(self, obj, level=0, objname=None, topLevelKeysToIgnore=None,
toBytes=True):
"""
Create a string representation of the given object.
Examples:
::
>>> serialize("str")
'str'
>>> serialize([1,2,3,4,5])
'1,2,3,4,5'
>>> signing.serlize({1:'a', 2:'b'})
'1:a|2:b'
>>> signing.serlize({1:'a', 2:'b', 3:[1,{2:'k'}]})
'1:a|2:b|3:1,2:k'
:param obj: the object to serlize
:param level: a parameter used internally for recursion to serialize nested
data structures
:param topLevelKeysToIgnore: the list of top level keys to ignore for
serialization
:return: a string representation of `obj`
"""
res = None
if not isinstance(obj, acceptableTypes):
error("invalid type found {}: {}".format(objname, obj))
elif isinstance(obj, str):
res = obj
elif isinstance(obj, dict):
if level > 0:
keys = list(obj.keys())
else:
topLevelKeysToIgnore = topLevelKeysToIgnore or []
keys = [k for k in obj.keys() if k not in topLevelKeysToIgnore]
keys.sort()
strs = []
for k in keys:
onm = ".".join([str(objname), str(k)]) if objname else k
strs.append(
str(k) + ":" + self.serialize(obj[k], level + 1, onm, toBytes=False))
res = "|".join(strs)
elif isinstance(obj, Iterable):
strs = []
for o in obj:
strs.append(self.serialize(
o, level + 1, objname, toBytes=False))
res = ",".join(strs)
elif obj is None:
res = ""
else:
res = str(obj)
# logger.trace("serialized msg {} into {}".format(obj, res))
if not toBytes:
return res
return res.encode('utf-8') | [
"def",
"serialize",
"(",
"self",
",",
"obj",
",",
"level",
"=",
"0",
",",
"objname",
"=",
"None",
",",
"topLevelKeysToIgnore",
"=",
"None",
",",
"toBytes",
"=",
"True",
")",
":",
"res",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"accept... | Create a string representation of the given object.
Examples:
::
>>> serialize("str")
'str'
>>> serialize([1,2,3,4,5])
'1,2,3,4,5'
>>> signing.serlize({1:'a', 2:'b'})
'1:a|2:b'
>>> signing.serlize({1:'a', 2:'b', 3:[1,{2:'k'}]})
'1:a|2:b|3:1,2:k'
:param obj: the object to serlize
:param level: a parameter used internally for recursion to serialize nested
data structures
:param topLevelKeysToIgnore: the list of top level keys to ignore for
serialization
:return: a string representation of `obj` | [
"Create",
"a",
"string",
"representation",
"of",
"the",
"given",
"object",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/common/serializers/signing_serializer.py#L35-L92 | train | 229,011 |
hyperledger/indy-plenum | plenum/common/transaction_store.py | TransactionStore.reset | def reset(self):
"""
Clear the values of all attributes of the transaction store.
"""
self.getsCounter = 0
# dictionary of processed requests for each client. Value for each
# client is a dictionary with request id as key and transaction id as
# value
self.processedRequests = {} # type: Dict[str, Dict[int, str]]
# dictionary of responses to be sent for each client. Value for each
# client is an asyncio Queue
self.responses = {} # type: Dict[str, asyncio.Queue]
# dictionary with key as transaction id and `Reply` as
# value
self.transactions = {} | python | def reset(self):
"""
Clear the values of all attributes of the transaction store.
"""
self.getsCounter = 0
# dictionary of processed requests for each client. Value for each
# client is a dictionary with request id as key and transaction id as
# value
self.processedRequests = {} # type: Dict[str, Dict[int, str]]
# dictionary of responses to be sent for each client. Value for each
# client is an asyncio Queue
self.responses = {} # type: Dict[str, asyncio.Queue]
# dictionary with key as transaction id and `Reply` as
# value
self.transactions = {} | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"getsCounter",
"=",
"0",
"# dictionary of processed requests for each client. Value for each",
"# client is a dictionary with request id as key and transaction id as",
"# value",
"self",
".",
"processedRequests",
"=",
"{",
"}"... | Clear the values of all attributes of the transaction store. | [
"Clear",
"the",
"values",
"of",
"all",
"attributes",
"of",
"the",
"transaction",
"store",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/transaction_store.py#L33-L50 | train | 229,012 |
hyperledger/indy-plenum | plenum/common/transaction_store.py | TransactionStore.stop | def stop(self, timeout: int = 5) -> None:
"""
Try to stop the transaction store in the given timeout or raise an
exception.
"""
self.running = False
start = time.perf_counter()
while True:
if self.getsCounter == 0:
return True
elif time.perf_counter() <= start + timeout:
time.sleep(.1)
else:
raise StopTimeout("Stop timed out waiting for {} gets to "
"complete.".format(self.getsCounter)) | python | def stop(self, timeout: int = 5) -> None:
"""
Try to stop the transaction store in the given timeout or raise an
exception.
"""
self.running = False
start = time.perf_counter()
while True:
if self.getsCounter == 0:
return True
elif time.perf_counter() <= start + timeout:
time.sleep(.1)
else:
raise StopTimeout("Stop timed out waiting for {} gets to "
"complete.".format(self.getsCounter)) | [
"def",
"stop",
"(",
"self",
",",
"timeout",
":",
"int",
"=",
"5",
")",
"->",
"None",
":",
"self",
".",
"running",
"=",
"False",
"start",
"=",
"time",
".",
"perf_counter",
"(",
")",
"while",
"True",
":",
"if",
"self",
".",
"getsCounter",
"==",
"0",
... | Try to stop the transaction store in the given timeout or raise an
exception. | [
"Try",
"to",
"stop",
"the",
"transaction",
"store",
"in",
"the",
"given",
"timeout",
"or",
"raise",
"an",
"exception",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/transaction_store.py#L57-L71 | train | 229,013 |
hyperledger/indy-plenum | plenum/common/transaction_store.py | TransactionStore.addToProcessedTxns | def addToProcessedTxns(self,
identifier: str,
txnId: str,
reply: Reply) -> None:
"""
Add a client request to the transaction store's list of processed
requests.
"""
self.transactions[txnId] = reply
if identifier not in self.processedRequests:
self.processedRequests[identifier] = {}
self.processedRequests[identifier][reply.reqId] = txnId | python | def addToProcessedTxns(self,
identifier: str,
txnId: str,
reply: Reply) -> None:
"""
Add a client request to the transaction store's list of processed
requests.
"""
self.transactions[txnId] = reply
if identifier not in self.processedRequests:
self.processedRequests[identifier] = {}
self.processedRequests[identifier][reply.reqId] = txnId | [
"def",
"addToProcessedTxns",
"(",
"self",
",",
"identifier",
":",
"str",
",",
"txnId",
":",
"str",
",",
"reply",
":",
"Reply",
")",
"->",
"None",
":",
"self",
".",
"transactions",
"[",
"txnId",
"]",
"=",
"reply",
"if",
"identifier",
"not",
"in",
"self"... | Add a client request to the transaction store's list of processed
requests. | [
"Add",
"a",
"client",
"request",
"to",
"the",
"transaction",
"store",
"s",
"list",
"of",
"processed",
"requests",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/transaction_store.py#L73-L84 | train | 229,014 |
hyperledger/indy-plenum | plenum/common/transaction_store.py | TransactionStore.append | async def append(self, reply: Reply) \
-> None:
"""
Add the given Reply to this transaction store's list of responses.
Also add to processedRequests if not added previously.
"""
result = reply.result
identifier = result.get(f.IDENTIFIER.nm)
txnId = result.get(TXN_ID)
logger.debug("Reply being sent {}".format(reply))
if self._isNewTxn(identifier, reply, txnId):
self.addToProcessedTxns(identifier, txnId, reply)
if identifier not in self.responses:
self.responses[identifier] = asyncio.Queue()
await self.responses[identifier].put(reply) | python | async def append(self, reply: Reply) \
-> None:
"""
Add the given Reply to this transaction store's list of responses.
Also add to processedRequests if not added previously.
"""
result = reply.result
identifier = result.get(f.IDENTIFIER.nm)
txnId = result.get(TXN_ID)
logger.debug("Reply being sent {}".format(reply))
if self._isNewTxn(identifier, reply, txnId):
self.addToProcessedTxns(identifier, txnId, reply)
if identifier not in self.responses:
self.responses[identifier] = asyncio.Queue()
await self.responses[identifier].put(reply) | [
"async",
"def",
"append",
"(",
"self",
",",
"reply",
":",
"Reply",
")",
"->",
"None",
":",
"result",
"=",
"reply",
".",
"result",
"identifier",
"=",
"result",
".",
"get",
"(",
"f",
".",
"IDENTIFIER",
".",
"nm",
")",
"txnId",
"=",
"result",
".",
"ge... | Add the given Reply to this transaction store's list of responses.
Also add to processedRequests if not added previously. | [
"Add",
"the",
"given",
"Reply",
"to",
"this",
"transaction",
"store",
"s",
"list",
"of",
"responses",
".",
"Also",
"add",
"to",
"processedRequests",
"if",
"not",
"added",
"previously",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/transaction_store.py#L86-L100 | train | 229,015 |
hyperledger/indy-plenum | plenum/common/transaction_store.py | TransactionStore._isNewTxn | def _isNewTxn(self, identifier, reply, txnId) -> bool:
"""
If client is not in `processedRequests` or requestId is not there in
processed requests and txnId is present then its a new reply
"""
return (identifier not in self.processedRequests or
reply.reqId not in self.processedRequests[identifier]) and \
txnId is not None | python | def _isNewTxn(self, identifier, reply, txnId) -> bool:
"""
If client is not in `processedRequests` or requestId is not there in
processed requests and txnId is present then its a new reply
"""
return (identifier not in self.processedRequests or
reply.reqId not in self.processedRequests[identifier]) and \
txnId is not None | [
"def",
"_isNewTxn",
"(",
"self",
",",
"identifier",
",",
"reply",
",",
"txnId",
")",
"->",
"bool",
":",
"return",
"(",
"identifier",
"not",
"in",
"self",
".",
"processedRequests",
"or",
"reply",
".",
"reqId",
"not",
"in",
"self",
".",
"processedRequests",
... | If client is not in `processedRequests` or requestId is not there in
processed requests and txnId is present then its a new reply | [
"If",
"client",
"is",
"not",
"in",
"processedRequests",
"or",
"requestId",
"is",
"not",
"there",
"in",
"processed",
"requests",
"and",
"txnId",
"is",
"present",
"then",
"its",
"a",
"new",
"reply"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/transaction_store.py#L110-L117 | train | 229,016 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.add | def add(self, req: Request):
"""
Add the specified request to this request store.
"""
key = req.key
if key not in self:
self[key] = ReqState(req)
return self[key] | python | def add(self, req: Request):
"""
Add the specified request to this request store.
"""
key = req.key
if key not in self:
self[key] = ReqState(req)
return self[key] | [
"def",
"add",
"(",
"self",
",",
"req",
":",
"Request",
")",
":",
"key",
"=",
"req",
".",
"key",
"if",
"key",
"not",
"in",
"self",
":",
"self",
"[",
"key",
"]",
"=",
"ReqState",
"(",
"req",
")",
"return",
"self",
"[",
"key",
"]"
] | Add the specified request to this request store. | [
"Add",
"the",
"specified",
"request",
"to",
"this",
"request",
"store",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L74-L81 | train | 229,017 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.ordered_by_replica | def ordered_by_replica(self, request_key):
"""
Should be called by each replica when request is ordered or replica is removed.
"""
state = self.get(request_key)
if not state:
return
state.unordered_by_replicas_num -= 1 | python | def ordered_by_replica(self, request_key):
"""
Should be called by each replica when request is ordered or replica is removed.
"""
state = self.get(request_key)
if not state:
return
state.unordered_by_replicas_num -= 1 | [
"def",
"ordered_by_replica",
"(",
"self",
",",
"request_key",
")",
":",
"state",
"=",
"self",
".",
"get",
"(",
"request_key",
")",
"if",
"not",
"state",
":",
"return",
"state",
".",
"unordered_by_replicas_num",
"-=",
"1"
] | Should be called by each replica when request is ordered or replica is removed. | [
"Should",
"be",
"called",
"by",
"each",
"replica",
"when",
"request",
"is",
"ordered",
"or",
"replica",
"is",
"removed",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L89-L96 | train | 229,018 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.mark_as_forwarded | def mark_as_forwarded(self, req: Request, to: int):
"""
Works together with 'mark_as_executed' and 'free' methods.
It marks request as forwarded to 'to' replicas.
To let request be removed, it should be marked as executed and each of
'to' replicas should call 'free'.
"""
self[req.key].forwarded = True
self[req.key].forwardedTo = to
self[req.key].unordered_by_replicas_num = to | python | def mark_as_forwarded(self, req: Request, to: int):
"""
Works together with 'mark_as_executed' and 'free' methods.
It marks request as forwarded to 'to' replicas.
To let request be removed, it should be marked as executed and each of
'to' replicas should call 'free'.
"""
self[req.key].forwarded = True
self[req.key].forwardedTo = to
self[req.key].unordered_by_replicas_num = to | [
"def",
"mark_as_forwarded",
"(",
"self",
",",
"req",
":",
"Request",
",",
"to",
":",
"int",
")",
":",
"self",
"[",
"req",
".",
"key",
"]",
".",
"forwarded",
"=",
"True",
"self",
"[",
"req",
".",
"key",
"]",
".",
"forwardedTo",
"=",
"to",
"self",
... | Works together with 'mark_as_executed' and 'free' methods.
It marks request as forwarded to 'to' replicas.
To let request be removed, it should be marked as executed and each of
'to' replicas should call 'free'. | [
"Works",
"together",
"with",
"mark_as_executed",
"and",
"free",
"methods",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L98-L108 | train | 229,019 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.add_propagate | def add_propagate(self, req: Request, sender: str):
"""
Add the specified request to the list of received
PROPAGATEs.
:param req: the REQUEST to add
:param sender: the name of the node sending the msg
"""
data = self.add(req)
data.propagates[sender] = req | python | def add_propagate(self, req: Request, sender: str):
"""
Add the specified request to the list of received
PROPAGATEs.
:param req: the REQUEST to add
:param sender: the name of the node sending the msg
"""
data = self.add(req)
data.propagates[sender] = req | [
"def",
"add_propagate",
"(",
"self",
",",
"req",
":",
"Request",
",",
"sender",
":",
"str",
")",
":",
"data",
"=",
"self",
".",
"add",
"(",
"req",
")",
"data",
".",
"propagates",
"[",
"sender",
"]",
"=",
"req"
] | Add the specified request to the list of received
PROPAGATEs.
:param req: the REQUEST to add
:param sender: the name of the node sending the msg | [
"Add",
"the",
"specified",
"request",
"to",
"the",
"list",
"of",
"received",
"PROPAGATEs",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L110-L119 | train | 229,020 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.votes | def votes(self, req) -> int:
"""
Get the number of propagates for a given reqId and identifier.
"""
try:
votes = len(self[req.key].propagates)
except KeyError:
votes = 0
return votes | python | def votes(self, req) -> int:
"""
Get the number of propagates for a given reqId and identifier.
"""
try:
votes = len(self[req.key].propagates)
except KeyError:
votes = 0
return votes | [
"def",
"votes",
"(",
"self",
",",
"req",
")",
"->",
"int",
":",
"try",
":",
"votes",
"=",
"len",
"(",
"self",
"[",
"req",
".",
"key",
"]",
".",
"propagates",
")",
"except",
"KeyError",
":",
"votes",
"=",
"0",
"return",
"votes"
] | Get the number of propagates for a given reqId and identifier. | [
"Get",
"the",
"number",
"of",
"propagates",
"for",
"a",
"given",
"reqId",
"and",
"identifier",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L121-L129 | train | 229,021 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.mark_as_executed | def mark_as_executed(self, req: Request):
"""
Works together with 'mark_as_forwarded' and 'free' methods.
It makes request to be removed if all replicas request was
forwarded to freed it.
"""
state = self[req.key]
state.executed = True
self._clean(state) | python | def mark_as_executed(self, req: Request):
"""
Works together with 'mark_as_forwarded' and 'free' methods.
It makes request to be removed if all replicas request was
forwarded to freed it.
"""
state = self[req.key]
state.executed = True
self._clean(state) | [
"def",
"mark_as_executed",
"(",
"self",
",",
"req",
":",
"Request",
")",
":",
"state",
"=",
"self",
"[",
"req",
".",
"key",
"]",
"state",
".",
"executed",
"=",
"True",
"self",
".",
"_clean",
"(",
"state",
")"
] | Works together with 'mark_as_forwarded' and 'free' methods.
It makes request to be removed if all replicas request was
forwarded to freed it. | [
"Works",
"together",
"with",
"mark_as_forwarded",
"and",
"free",
"methods",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L141-L150 | train | 229,022 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.free | def free(self, request_key):
"""
Works together with 'mark_as_forwarded' and
'mark_as_executed' methods.
It makes request to be removed if all replicas request was
forwarded to freed it and if request executor marked it as executed.
"""
state = self.get(request_key)
if not state:
return
state.forwardedTo -= 1
self._clean(state) | python | def free(self, request_key):
"""
Works together with 'mark_as_forwarded' and
'mark_as_executed' methods.
It makes request to be removed if all replicas request was
forwarded to freed it and if request executor marked it as executed.
"""
state = self.get(request_key)
if not state:
return
state.forwardedTo -= 1
self._clean(state) | [
"def",
"free",
"(",
"self",
",",
"request_key",
")",
":",
"state",
"=",
"self",
".",
"get",
"(",
"request_key",
")",
"if",
"not",
"state",
":",
"return",
"state",
".",
"forwardedTo",
"-=",
"1",
"self",
".",
"_clean",
"(",
"state",
")"
] | Works together with 'mark_as_forwarded' and
'mark_as_executed' methods.
It makes request to be removed if all replicas request was
forwarded to freed it and if request executor marked it as executed. | [
"Works",
"together",
"with",
"mark_as_forwarded",
"and",
"mark_as_executed",
"methods",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L152-L164 | train | 229,023 |
hyperledger/indy-plenum | plenum/server/propagator.py | Requests.has_propagated | def has_propagated(self, req: Request, sender: str) -> bool:
"""
Check whether the request specified has already been propagated.
"""
return req.key in self and sender in self[req.key].propagates | python | def has_propagated(self, req: Request, sender: str) -> bool:
"""
Check whether the request specified has already been propagated.
"""
return req.key in self and sender in self[req.key].propagates | [
"def",
"has_propagated",
"(",
"self",
",",
"req",
":",
"Request",
",",
"sender",
":",
"str",
")",
"->",
"bool",
":",
"return",
"req",
".",
"key",
"in",
"self",
"and",
"sender",
"in",
"self",
"[",
"req",
".",
"key",
"]",
".",
"propagates"
] | Check whether the request specified has already been propagated. | [
"Check",
"whether",
"the",
"request",
"specified",
"has",
"already",
"been",
"propagated",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L180-L184 | train | 229,024 |
hyperledger/indy-plenum | plenum/server/propagator.py | Propagator.propagate | def propagate(self, request: Request, clientName):
"""
Broadcast a PROPAGATE to all other nodes
:param request: the REQUEST to propagate
"""
if self.requests.has_propagated(request, self.name):
logger.trace("{} already propagated {}".format(self, request))
else:
with self.metrics.measure_time(MetricsName.SEND_PROPAGATE_TIME):
self.requests.add_propagate(request, self.name)
propagate = self.createPropagate(request, clientName)
logger.debug("{} propagating request {} from client {}".format(self, request.key, clientName),
extra={"cli": True, "tags": ["node-propagate"]})
self.send(propagate) | python | def propagate(self, request: Request, clientName):
"""
Broadcast a PROPAGATE to all other nodes
:param request: the REQUEST to propagate
"""
if self.requests.has_propagated(request, self.name):
logger.trace("{} already propagated {}".format(self, request))
else:
with self.metrics.measure_time(MetricsName.SEND_PROPAGATE_TIME):
self.requests.add_propagate(request, self.name)
propagate = self.createPropagate(request, clientName)
logger.debug("{} propagating request {} from client {}".format(self, request.key, clientName),
extra={"cli": True, "tags": ["node-propagate"]})
self.send(propagate) | [
"def",
"propagate",
"(",
"self",
",",
"request",
":",
"Request",
",",
"clientName",
")",
":",
"if",
"self",
".",
"requests",
".",
"has_propagated",
"(",
"request",
",",
"self",
".",
"name",
")",
":",
"logger",
".",
"trace",
"(",
"\"{} already propagated {}... | Broadcast a PROPAGATE to all other nodes
:param request: the REQUEST to propagate | [
"Broadcast",
"a",
"PROPAGATE",
"to",
"all",
"other",
"nodes"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L203-L217 | train | 229,025 |
hyperledger/indy-plenum | plenum/server/propagator.py | Propagator.createPropagate | def createPropagate(
request: Union[Request, dict], client_name) -> Propagate:
"""
Create a new PROPAGATE for the given REQUEST.
:param request: the client REQUEST
:return: a new PROPAGATE msg
"""
if not isinstance(request, (Request, dict)):
logger.error("{}Request not formatted properly to create propagate"
.format(THREE_PC_PREFIX))
return
logger.trace("Creating PROPAGATE for REQUEST {}".format(request))
request = request.as_dict if isinstance(request, Request) else \
request
if isinstance(client_name, bytes):
client_name = client_name.decode()
return Propagate(request, client_name) | python | def createPropagate(
request: Union[Request, dict], client_name) -> Propagate:
"""
Create a new PROPAGATE for the given REQUEST.
:param request: the client REQUEST
:return: a new PROPAGATE msg
"""
if not isinstance(request, (Request, dict)):
logger.error("{}Request not formatted properly to create propagate"
.format(THREE_PC_PREFIX))
return
logger.trace("Creating PROPAGATE for REQUEST {}".format(request))
request = request.as_dict if isinstance(request, Request) else \
request
if isinstance(client_name, bytes):
client_name = client_name.decode()
return Propagate(request, client_name) | [
"def",
"createPropagate",
"(",
"request",
":",
"Union",
"[",
"Request",
",",
"dict",
"]",
",",
"client_name",
")",
"->",
"Propagate",
":",
"if",
"not",
"isinstance",
"(",
"request",
",",
"(",
"Request",
",",
"dict",
")",
")",
":",
"logger",
".",
"error... | Create a new PROPAGATE for the given REQUEST.
:param request: the client REQUEST
:return: a new PROPAGATE msg | [
"Create",
"a",
"new",
"PROPAGATE",
"for",
"the",
"given",
"REQUEST",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L220-L237 | train | 229,026 |
hyperledger/indy-plenum | plenum/server/propagator.py | Propagator.forward | def forward(self, request: Request):
"""
Forward the specified client REQUEST to the other replicas on this node
:param request: the REQUEST to propagate
"""
key = request.key
num_replicas = self.replicas.num_replicas
logger.debug('{} forwarding request {} to {} replicas'
.format(self, key, num_replicas))
self.replicas.pass_message(ReqKey(key))
self.monitor.requestUnOrdered(key)
self.requests.mark_as_forwarded(request, num_replicas) | python | def forward(self, request: Request):
"""
Forward the specified client REQUEST to the other replicas on this node
:param request: the REQUEST to propagate
"""
key = request.key
num_replicas = self.replicas.num_replicas
logger.debug('{} forwarding request {} to {} replicas'
.format(self, key, num_replicas))
self.replicas.pass_message(ReqKey(key))
self.monitor.requestUnOrdered(key)
self.requests.mark_as_forwarded(request, num_replicas) | [
"def",
"forward",
"(",
"self",
",",
"request",
":",
"Request",
")",
":",
"key",
"=",
"request",
".",
"key",
"num_replicas",
"=",
"self",
".",
"replicas",
".",
"num_replicas",
"logger",
".",
"debug",
"(",
"'{} forwarding request {} to {} replicas'",
".",
"forma... | Forward the specified client REQUEST to the other replicas on this node
:param request: the REQUEST to propagate | [
"Forward",
"the",
"specified",
"client",
"REQUEST",
"to",
"the",
"other",
"replicas",
"on",
"this",
"node"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L273-L285 | train | 229,027 |
hyperledger/indy-plenum | plenum/server/propagator.py | Propagator.recordAndPropagate | def recordAndPropagate(self, request: Request, clientName):
"""
Record the request in the list of requests and propagate.
:param request:
:param clientName:
"""
self.requests.add(request)
self.propagate(request, clientName)
self.tryForwarding(request) | python | def recordAndPropagate(self, request: Request, clientName):
"""
Record the request in the list of requests and propagate.
:param request:
:param clientName:
"""
self.requests.add(request)
self.propagate(request, clientName)
self.tryForwarding(request) | [
"def",
"recordAndPropagate",
"(",
"self",
",",
"request",
":",
"Request",
",",
"clientName",
")",
":",
"self",
".",
"requests",
".",
"add",
"(",
"request",
")",
"self",
".",
"propagate",
"(",
"request",
",",
"clientName",
")",
"self",
".",
"tryForwarding",... | Record the request in the list of requests and propagate.
:param request:
:param clientName: | [
"Record",
"the",
"request",
"in",
"the",
"list",
"of",
"requests",
"and",
"propagate",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L288-L297 | train | 229,028 |
hyperledger/indy-plenum | plenum/server/propagator.py | Propagator.tryForwarding | def tryForwarding(self, request: Request):
"""
Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request.
"""
cannot_reason_msg = self.canForward(request)
if cannot_reason_msg is None:
# If haven't got the client request(REQUEST) for the corresponding
# propagate request(PROPAGATE) but have enough propagate requests
# to move ahead
self.forward(request)
else:
logger.trace("{} not forwarding request {} to its replicas "
"since {}".format(self, request, cannot_reason_msg)) | python | def tryForwarding(self, request: Request):
"""
Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request.
"""
cannot_reason_msg = self.canForward(request)
if cannot_reason_msg is None:
# If haven't got the client request(REQUEST) for the corresponding
# propagate request(PROPAGATE) but have enough propagate requests
# to move ahead
self.forward(request)
else:
logger.trace("{} not forwarding request {} to its replicas "
"since {}".format(self, request, cannot_reason_msg)) | [
"def",
"tryForwarding",
"(",
"self",
",",
"request",
":",
"Request",
")",
":",
"cannot_reason_msg",
"=",
"self",
".",
"canForward",
"(",
"request",
")",
"if",
"cannot_reason_msg",
"is",
"None",
":",
"# If haven't got the client request(REQUEST) for the corresponding",
... | Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request. | [
"Try",
"to",
"forward",
"the",
"request",
"if",
"the",
"required",
"conditions",
"are",
"met",
".",
"See",
"the",
"method",
"canForward",
"for",
"the",
"conditions",
"to",
"check",
"before",
"forwarding",
"a",
"request",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/propagator.py#L299-L313 | train | 229,029 |
hyperledger/indy-plenum | stp_zmq/zstack.py | ZStack.removeRemote | def removeRemote(self, remote: Remote, clear=True):
"""
Currently not using clear
"""
name = remote.name
pkey = remote.publicKey
vkey = remote.verKey
if name in self.remotes:
self.remotes.pop(name)
self.remotesByKeys.pop(pkey, None)
self.verifiers.pop(vkey, None)
else:
logger.info('No remote named {} present') | python | def removeRemote(self, remote: Remote, clear=True):
"""
Currently not using clear
"""
name = remote.name
pkey = remote.publicKey
vkey = remote.verKey
if name in self.remotes:
self.remotes.pop(name)
self.remotesByKeys.pop(pkey, None)
self.verifiers.pop(vkey, None)
else:
logger.info('No remote named {} present') | [
"def",
"removeRemote",
"(",
"self",
",",
"remote",
":",
"Remote",
",",
"clear",
"=",
"True",
")",
":",
"name",
"=",
"remote",
".",
"name",
"pkey",
"=",
"remote",
".",
"publicKey",
"vkey",
"=",
"remote",
".",
"verKey",
"if",
"name",
"in",
"self",
".",... | Currently not using clear | [
"Currently",
"not",
"using",
"clear"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/zstack.py#L153-L165 | train | 229,030 |
hyperledger/indy-plenum | stp_zmq/zstack.py | ZStack.service | async def service(self, limit=None, quota: Optional[Quota] = None) -> int:
"""
Service `limit` number of received messages in this stack.
:param limit: the maximum number of messages to be processed. If None,
processes all of the messages in rxMsgs.
:return: the number of messages processed.
"""
if self.listener:
await self._serviceStack(self.age, quota)
else:
logger.info("{} is stopped".format(self))
r = len(self.rxMsgs)
if r > 0:
pracLimit = limit if limit else sys.maxsize
return self.processReceived(pracLimit)
return 0 | python | async def service(self, limit=None, quota: Optional[Quota] = None) -> int:
"""
Service `limit` number of received messages in this stack.
:param limit: the maximum number of messages to be processed. If None,
processes all of the messages in rxMsgs.
:return: the number of messages processed.
"""
if self.listener:
await self._serviceStack(self.age, quota)
else:
logger.info("{} is stopped".format(self))
r = len(self.rxMsgs)
if r > 0:
pracLimit = limit if limit else sys.maxsize
return self.processReceived(pracLimit)
return 0 | [
"async",
"def",
"service",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"quota",
":",
"Optional",
"[",
"Quota",
"]",
"=",
"None",
")",
"->",
"int",
":",
"if",
"self",
".",
"listener",
":",
"await",
"self",
".",
"_serviceStack",
"(",
"self",
".",
"a... | Service `limit` number of received messages in this stack.
:param limit: the maximum number of messages to be processed. If None,
processes all of the messages in rxMsgs.
:return: the number of messages processed. | [
"Service",
"limit",
"number",
"of",
"received",
"messages",
"in",
"this",
"stack",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/zstack.py#L445-L462 | train | 229,031 |
hyperledger/indy-plenum | stp_zmq/zstack.py | ZStack.connect | def connect(self,
name=None,
remoteId=None,
ha=None,
verKeyRaw=None,
publicKeyRaw=None):
"""
Connect to the node specified by name.
"""
if not name:
raise ValueError('Remote name should be specified')
publicKey = None
if name in self.remotes:
remote = self.remotes[name]
else:
publicKey = z85.encode(
publicKeyRaw) if publicKeyRaw else self.getPublicKey(name)
verKey = z85.encode(
verKeyRaw) if verKeyRaw else self.getVerKey(name)
if not ha or not publicKey or (self.isRestricted and not verKey):
raise ValueError('{} doesnt have enough info to connect. '
'Need ha, public key and verkey. {} {} {}'.
format(name, ha, verKey, publicKey))
remote = self.addRemote(name, ha, verKey, publicKey)
public, secret = self.selfEncKeys
remote.connect(self.ctx, public, secret)
logger.info("{}{} looking for {} at {}:{}"
.format(CONNECTION_PREFIX, self,
name or remote.name, *remote.ha),
extra={"cli": "PLAIN", "tags": ["node-looking"]})
# This should be scheduled as an async task
self.sendPingPong(remote, is_ping=True)
# re-send previously stashed pings/pongs from unknown remotes
logger.trace("{} stashed pongs: {}".format(self.name, str(self._stashed_pongs)))
if publicKey in self._stashed_pongs:
logger.trace("{} sending stashed pongs to {}".format(self.name, str(z85_to_friendly(publicKey))))
self._stashed_pongs.discard(publicKey)
self.sendPingPong(name, is_ping=False)
return remote.uid | python | def connect(self,
name=None,
remoteId=None,
ha=None,
verKeyRaw=None,
publicKeyRaw=None):
"""
Connect to the node specified by name.
"""
if not name:
raise ValueError('Remote name should be specified')
publicKey = None
if name in self.remotes:
remote = self.remotes[name]
else:
publicKey = z85.encode(
publicKeyRaw) if publicKeyRaw else self.getPublicKey(name)
verKey = z85.encode(
verKeyRaw) if verKeyRaw else self.getVerKey(name)
if not ha or not publicKey or (self.isRestricted and not verKey):
raise ValueError('{} doesnt have enough info to connect. '
'Need ha, public key and verkey. {} {} {}'.
format(name, ha, verKey, publicKey))
remote = self.addRemote(name, ha, verKey, publicKey)
public, secret = self.selfEncKeys
remote.connect(self.ctx, public, secret)
logger.info("{}{} looking for {} at {}:{}"
.format(CONNECTION_PREFIX, self,
name or remote.name, *remote.ha),
extra={"cli": "PLAIN", "tags": ["node-looking"]})
# This should be scheduled as an async task
self.sendPingPong(remote, is_ping=True)
# re-send previously stashed pings/pongs from unknown remotes
logger.trace("{} stashed pongs: {}".format(self.name, str(self._stashed_pongs)))
if publicKey in self._stashed_pongs:
logger.trace("{} sending stashed pongs to {}".format(self.name, str(z85_to_friendly(publicKey))))
self._stashed_pongs.discard(publicKey)
self.sendPingPong(name, is_ping=False)
return remote.uid | [
"def",
"connect",
"(",
"self",
",",
"name",
"=",
"None",
",",
"remoteId",
"=",
"None",
",",
"ha",
"=",
"None",
",",
"verKeyRaw",
"=",
"None",
",",
"publicKeyRaw",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"'Remote n... | Connect to the node specified by name. | [
"Connect",
"to",
"the",
"node",
"specified",
"by",
"name",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/zstack.py#L584-L629 | train | 229,032 |
hyperledger/indy-plenum | stp_zmq/zstack.py | ZStack.reconnectRemote | def reconnectRemote(self, remote):
"""
Disconnect remote and connect to it again
:param remote: instance of Remote from self.remotes
:param remoteName: name of remote
:return:
"""
if not isinstance(remote, Remote):
raise PlenumTypeError('remote', remote, Remote)
logger.info('{} reconnecting to {}'.format(self, remote))
public, secret = self.selfEncKeys
remote.disconnect()
remote.connect(self.ctx, public, secret)
self.sendPingPong(remote, is_ping=True) | python | def reconnectRemote(self, remote):
"""
Disconnect remote and connect to it again
:param remote: instance of Remote from self.remotes
:param remoteName: name of remote
:return:
"""
if not isinstance(remote, Remote):
raise PlenumTypeError('remote', remote, Remote)
logger.info('{} reconnecting to {}'.format(self, remote))
public, secret = self.selfEncKeys
remote.disconnect()
remote.connect(self.ctx, public, secret)
self.sendPingPong(remote, is_ping=True) | [
"def",
"reconnectRemote",
"(",
"self",
",",
"remote",
")",
":",
"if",
"not",
"isinstance",
"(",
"remote",
",",
"Remote",
")",
":",
"raise",
"PlenumTypeError",
"(",
"'remote'",
",",
"remote",
",",
"Remote",
")",
"logger",
".",
"info",
"(",
"'{} reconnecting... | Disconnect remote and connect to it again
:param remote: instance of Remote from self.remotes
:param remoteName: name of remote
:return: | [
"Disconnect",
"remote",
"and",
"connect",
"to",
"it",
"again"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/zstack.py#L631-L645 | train | 229,033 |
hyperledger/indy-plenum | plenum/persistence/db_hash_store.py | DbHashStore._readMultiple | def _readMultiple(self, start, end, db):
"""
Returns a list of hashes with serial numbers between start
and end, both inclusive.
"""
self._validatePos(start, end)
# Converting any bytearray to bytes
return [bytes(db.get(str(pos))) for pos in range(start, end + 1)] | python | def _readMultiple(self, start, end, db):
"""
Returns a list of hashes with serial numbers between start
and end, both inclusive.
"""
self._validatePos(start, end)
# Converting any bytearray to bytes
return [bytes(db.get(str(pos))) for pos in range(start, end + 1)] | [
"def",
"_readMultiple",
"(",
"self",
",",
"start",
",",
"end",
",",
"db",
")",
":",
"self",
".",
"_validatePos",
"(",
"start",
",",
"end",
")",
"# Converting any bytearray to bytes",
"return",
"[",
"bytes",
"(",
"db",
".",
"get",
"(",
"str",
"(",
"pos",
... | Returns a list of hashes with serial numbers between start
and end, both inclusive. | [
"Returns",
"a",
"list",
"of",
"hashes",
"with",
"serial",
"numbers",
"between",
"start",
"and",
"end",
"both",
"inclusive",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/persistence/db_hash_store.py#L67-L74 | train | 229,034 |
hyperledger/indy-plenum | state/trie/pruning_trie.py | pack_nibbles | def pack_nibbles(nibbles):
"""pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if odd number of nibbles
if oddlen:
nibbles = [flags] + nibbles
else:
nibbles = [flags, 0] + nibbles
o = b''
for i in range(0, len(nibbles), 2):
o += ascii_chr(16 * nibbles[i] + nibbles[i + 1])
return o | python | def pack_nibbles(nibbles):
"""pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if odd number of nibbles
if oddlen:
nibbles = [flags] + nibbles
else:
nibbles = [flags, 0] + nibbles
o = b''
for i in range(0, len(nibbles), 2):
o += ascii_chr(16 * nibbles[i] + nibbles[i + 1])
return o | [
"def",
"pack_nibbles",
"(",
"nibbles",
")",
":",
"if",
"nibbles",
"[",
"-",
"1",
"]",
"==",
"NIBBLE_TERMINATOR",
":",
"flags",
"=",
"2",
"nibbles",
"=",
"nibbles",
"[",
":",
"-",
"1",
"]",
"else",
":",
"flags",
"=",
"0",
"oddlen",
"=",
"len",
"(",
... | pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator | [
"pack",
"nibbles",
"to",
"binary"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/state/trie/pruning_trie.py#L140-L161 | train | 229,035 |
hyperledger/indy-plenum | state/trie/pruning_trie.py | Trie._get_last_node_for_prfx | def _get_last_node_for_prfx(self, node, key_prfx, seen_prfx):
""" get last node for the given prefix, also update `seen_prfx` to track the path already traversed
:param node: node in form of list, or BLANK_NODE
:param key_prfx: prefix to look for
:param seen_prfx: prefix already seen, updates with each call
:return:
BLANK_NODE if does not exist, otherwise value or hash
"""
node_type = self._get_node_type(node)
if node_type == NODE_TYPE_BLANK:
return BLANK_NODE
if node_type == NODE_TYPE_BRANCH:
# already reach the expected node
if not key_prfx:
return node
sub_node = self._decode_to_node(node[key_prfx[0]])
seen_prfx.append(key_prfx[0])
return self._get_last_node_for_prfx(sub_node, key_prfx[1:], seen_prfx)
# key value node
curr_key = key_nibbles_from_key_value_node(node)
if node_type == NODE_TYPE_LEAF:
# Return this node only if the complete prefix is part of the current key
if starts_with(curr_key, key_prfx):
# Do not update `seen_prefix` as node has the prefix
return node
else:
return BLANK_NODE
if node_type == NODE_TYPE_EXTENSION:
# traverse child nodes
if len(key_prfx) > len(curr_key):
if starts_with(key_prfx, curr_key):
sub_node = self._get_inner_node_from_extension(node)
seen_prfx.extend(curr_key)
return self._get_last_node_for_prfx(sub_node,
key_prfx[len(curr_key):],
seen_prfx)
else:
return BLANK_NODE
else:
if starts_with(curr_key, key_prfx):
# Do not update `seen_prefix` as node has the prefix
return node
else:
return BLANK_NODE | python | def _get_last_node_for_prfx(self, node, key_prfx, seen_prfx):
""" get last node for the given prefix, also update `seen_prfx` to track the path already traversed
:param node: node in form of list, or BLANK_NODE
:param key_prfx: prefix to look for
:param seen_prfx: prefix already seen, updates with each call
:return:
BLANK_NODE if does not exist, otherwise value or hash
"""
node_type = self._get_node_type(node)
if node_type == NODE_TYPE_BLANK:
return BLANK_NODE
if node_type == NODE_TYPE_BRANCH:
# already reach the expected node
if not key_prfx:
return node
sub_node = self._decode_to_node(node[key_prfx[0]])
seen_prfx.append(key_prfx[0])
return self._get_last_node_for_prfx(sub_node, key_prfx[1:], seen_prfx)
# key value node
curr_key = key_nibbles_from_key_value_node(node)
if node_type == NODE_TYPE_LEAF:
# Return this node only if the complete prefix is part of the current key
if starts_with(curr_key, key_prfx):
# Do not update `seen_prefix` as node has the prefix
return node
else:
return BLANK_NODE
if node_type == NODE_TYPE_EXTENSION:
# traverse child nodes
if len(key_prfx) > len(curr_key):
if starts_with(key_prfx, curr_key):
sub_node = self._get_inner_node_from_extension(node)
seen_prfx.extend(curr_key)
return self._get_last_node_for_prfx(sub_node,
key_prfx[len(curr_key):],
seen_prfx)
else:
return BLANK_NODE
else:
if starts_with(curr_key, key_prfx):
# Do not update `seen_prefix` as node has the prefix
return node
else:
return BLANK_NODE | [
"def",
"_get_last_node_for_prfx",
"(",
"self",
",",
"node",
",",
"key_prfx",
",",
"seen_prfx",
")",
":",
"node_type",
"=",
"self",
".",
"_get_node_type",
"(",
"node",
")",
"if",
"node_type",
"==",
"NODE_TYPE_BLANK",
":",
"return",
"BLANK_NODE",
"if",
"node_typ... | get last node for the given prefix, also update `seen_prfx` to track the path already traversed
:param node: node in form of list, or BLANK_NODE
:param key_prfx: prefix to look for
:param seen_prfx: prefix already seen, updates with each call
:return:
BLANK_NODE if does not exist, otherwise value or hash | [
"get",
"last",
"node",
"for",
"the",
"given",
"prefix",
"also",
"update",
"seen_prfx",
"to",
"track",
"the",
"path",
"already",
"traversed"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/state/trie/pruning_trie.py#L410-L459 | train | 229,036 |
hyperledger/indy-plenum | plenum/server/monitor.py | Monitor.metrics | def metrics(self):
"""
Calculate and return the metrics.
"""
masterThrp, backupThrp = self.getThroughputs(self.instances.masterId)
r = self.instance_throughput_ratio(self.instances.masterId)
m = [
("{} Monitor metrics:".format(self), None),
("Delta", self.Delta),
("Lambda", self.Lambda),
("Omega", self.Omega),
("instances started", self.instances.started),
("ordered request counts",
{i: r[0] for i, r in self.numOrderedRequests.items()}),
("ordered request durations",
{i: r[1] for i, r in self.numOrderedRequests.items()}),
("master request latencies", self.masterReqLatencies),
("client avg request latencies", {i: self.getLatency(i)
for i in self.instances.ids}),
("throughput", {i: self.getThroughput(i)
for i in self.instances.ids}),
("master throughput", masterThrp),
("total requests", self.totalRequests),
("avg backup throughput", backupThrp),
("master throughput ratio", r)]
return m | python | def metrics(self):
"""
Calculate and return the metrics.
"""
masterThrp, backupThrp = self.getThroughputs(self.instances.masterId)
r = self.instance_throughput_ratio(self.instances.masterId)
m = [
("{} Monitor metrics:".format(self), None),
("Delta", self.Delta),
("Lambda", self.Lambda),
("Omega", self.Omega),
("instances started", self.instances.started),
("ordered request counts",
{i: r[0] for i, r in self.numOrderedRequests.items()}),
("ordered request durations",
{i: r[1] for i, r in self.numOrderedRequests.items()}),
("master request latencies", self.masterReqLatencies),
("client avg request latencies", {i: self.getLatency(i)
for i in self.instances.ids}),
("throughput", {i: self.getThroughput(i)
for i in self.instances.ids}),
("master throughput", masterThrp),
("total requests", self.totalRequests),
("avg backup throughput", backupThrp),
("master throughput ratio", r)]
return m | [
"def",
"metrics",
"(",
"self",
")",
":",
"masterThrp",
",",
"backupThrp",
"=",
"self",
".",
"getThroughputs",
"(",
"self",
".",
"instances",
".",
"masterId",
")",
"r",
"=",
"self",
".",
"instance_throughput_ratio",
"(",
"self",
".",
"instances",
".",
"mast... | Calculate and return the metrics. | [
"Calculate",
"and",
"return",
"the",
"metrics",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L256-L281 | train | 229,037 |
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:
"""
Pretty printing for metrics
"""
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 | train | 229,038 |
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):
"""
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 | [
"def",
"reset",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}'s Monitor being reset\"",
".",
"format",
"(",
"self",
")",
")",
"instances_ids",
"=",
"self",
".",
"instances",
".",
"started",
".",
"keys",
"(",
")",
"self",
".",
"numOrderedRequest... | 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 | train | 229,039 |
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):
"""
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) | [
"def",
"addInstance",
"(",
"self",
",",
"inst_id",
")",
":",
"self",
".",
"instances",
".",
"add",
"(",
"inst_id",
")",
"self",
".",
"requestTracker",
".",
"add_instance",
"(",
"inst_id",
")",
"self",
".",
"numOrderedRequests",
"[",
"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 | train | 229,040 |
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:
"""
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 | [
"def",
"requestOrdered",
"(",
"self",
",",
"reqIdrs",
":",
"List",
"[",
"str",
"]",
",",
"instId",
":",
"int",
",",
"requests",
",",
"byMaster",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
":",
"now",
"=",
"time",
".",
"perf_counter",
"(",
")",
"... | 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 | train | 229,041 |
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):
"""
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) | [
"def",
"requestUnOrdered",
"(",
"self",
",",
"key",
":",
"str",
")",
":",
"now",
"=",
"time",
".",
"perf_counter",
"(",
")",
"if",
"self",
".",
"acc_monitor",
":",
"self",
".",
"acc_monitor",
".",
"update_time",
"(",
"now",
")",
"self",
".",
"acc_monit... | 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 | train | 229,042 |
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):
"""
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())) | [
"def",
"isMasterDegraded",
"(",
"self",
")",
":",
"if",
"self",
".",
"acc_monitor",
":",
"self",
".",
"acc_monitor",
".",
"update_time",
"(",
"time",
".",
"perf_counter",
"(",
")",
")",
"return",
"self",
".",
"acc_monitor",
".",
"is_master_degraded",
"(",
... | 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 | train | 229,043 |
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):
"""
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 | [
"def",
"areBackupsDegraded",
"(",
"self",
")",
":",
"slow_instances",
"=",
"[",
"]",
"if",
"self",
".",
"acc_monitor",
":",
"for",
"instance",
"in",
"self",
".",
"instances",
".",
"backupIds",
":",
"if",
"self",
".",
"acc_monitor",
".",
"is_instance_degraded... | Return slow instance. | [
"Return",
"slow",
"instance",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L441-L454 | train | 229,044 |
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):
"""
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 | [
"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"... | 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 | train | 229,045 |
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):
"""
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 | [
"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 \"",
"\"measurab... | 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 | train | 229,046 |
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):
"""
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 | [
"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",
"... | 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 | train | 229,047 |
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):
"""
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 | [
"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_la... | 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 | train | 229,048 |
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):
"""
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 | [
"def",
"getThroughputs",
"(",
"self",
",",
"desired_inst_id",
":",
"int",
")",
":",
"instance_thrp",
"=",
"self",
".",
"getThroughput",
"(",
"desired_inst_id",
")",
"totalReqs",
",",
"totalTm",
"=",
"self",
".",
"getInstanceMetrics",
"(",
"forAllExcept",
"=",
... | 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 | train | 229,049 |
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:
"""
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 | [
"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",... | 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 | train | 229,050 |
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]]:
"""
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 | [
"def",
"getInstanceMetrics",
"(",
"self",
",",
"forAllExcept",
":",
"int",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"int",
"]",
",",
"Optional",
"[",
"float",
"]",
"]",
":",
"m",
"=",
"[",
"(",
"reqs",
",",
"tm",
")",
"for",
"i",
",",
"(",
"reqs... | 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 | train | 229,051 |
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:
"""
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() | [
"def",
"getLatency",
"(",
"self",
",",
"instId",
":",
"int",
")",
"->",
"float",
":",
"if",
"len",
"(",
"self",
".",
"clientAvgReqLatencies",
")",
"==",
"0",
":",
"return",
"0.0",
"return",
"self",
".",
"clientAvgReqLatencies",
"[",
"instId",
"]",
".",
... | 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 | train | 229,052 |
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:
"""
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) | [
"def",
"_enqueue",
"(",
"self",
",",
"msg",
":",
"Any",
",",
"rid",
":",
"int",
",",
"signer",
":",
"Signer",
")",
"->",
"None",
":",
"if",
"rid",
"not",
"in",
"self",
".",
"outBoxes",
":",
"self",
".",
"outBoxes",
"[",
"rid",
"]",
"=",
"deque",
... | 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 | train | 229,053 |
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:
"""
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) | [
"def",
"_enqueueIntoAllRemotes",
"(",
"self",
",",
"msg",
":",
"Any",
",",
"signer",
":",
"Signer",
")",
"->",
"None",
":",
"for",
"rid",
"in",
"self",
".",
"remotes",
".",
"keys",
"(",
")",
":",
"self",
".",
"_enqueue",
"(",
"msg",
",",
"rid",
","... | 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 | train | 229,054 |
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:
"""
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 | [
"def",
"send",
"(",
"self",
",",
"msg",
":",
"Any",
",",
"*",
"rids",
":",
"Iterable",
"[",
"int",
"]",
",",
"signer",
":",
"Signer",
"=",
"None",
",",
"message_splitter",
"=",
"None",
")",
"->",
"None",
":",
"# Signing (if required) and serializing before... | 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 | train | 229,055 |
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:
"""
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] | [
"def",
"flushOutBoxes",
"(",
"self",
")",
"->",
"None",
":",
"removedRemotes",
"=",
"[",
"]",
"for",
"rid",
",",
"msgs",
"in",
"self",
".",
"outBoxes",
".",
"items",
"(",
")",
":",
"try",
":",
"dest",
"=",
"self",
".",
"remotes",
"[",
"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 | train | 229,056 |
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):
"""
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 | [
"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",
"... | 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 | train | 229,057 |
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:
"""
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) | [
"def",
"add",
"(",
"self",
",",
"prodable",
":",
"Prodable",
")",
"->",
"None",
":",
"if",
"prodable",
".",
"name",
"in",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"prodables",
"]",
":",
"raise",
"ProdableAlreadyAdded",
"(",
"\"Prodable {} ... | 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 | train | 229,058 |
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]:
"""
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") | [
"def",
"removeProdable",
"(",
"self",
",",
"prodable",
":",
"Prodable",
"=",
"None",
",",
"name",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"Prodable",
"]",
":",
"if",
"prodable",
":",
"self",
".",
"prodables",
".",
"remove",
"(",
"prodable"... | 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 | train | 229,059 |
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):
"""
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}) | [
"async",
"def",
"runOnceNicely",
"(",
"self",
")",
":",
"start",
"=",
"time",
".",
"perf_counter",
"(",
")",
"msgsProcessed",
"=",
"await",
"self",
".",
"prodAllOnce",
"(",
")",
"if",
"msgsProcessed",
"==",
"0",
":",
"# if no let other stuff run",
"await",
"... | 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 | train | 229,060 |
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):
"""
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) | [
"def",
"run",
"(",
"self",
",",
"*",
"coros",
":",
"CoroWrapper",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"raise",
"RuntimeError",
"(",
"\"not running!\"",
")",
"async",
"def",
"wrapper",
"(",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c... | 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 | train | 229,061 |
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):
"""
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) | [
"async",
"def",
"shutdown",
"(",
"self",
")",
":",
"logger",
".",
"display",
"(",
"\"Looper shutting down now...\"",
",",
"extra",
"=",
"{",
"\"cli\"",
":",
"False",
"}",
")",
"self",
".",
"running",
"=",
"False",
"start",
"=",
"time",
".",
"perf_counter",... | Shut down this Looper. | [
"Shut",
"down",
"this",
"Looper",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/looper.py#L271-L287 | train | 229,062 |
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",
... | 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 | train | 229,063 |
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):
"""
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) | [
"def",
"sign",
"(",
"self",
",",
"message",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"raw_signed",
"=",
"libnacl",
".",
"crypto_sign",
"(",
"message",
",",
"self",
".",
"_signing_key",
")",
"signature",
"=",
"encoder",
".",
"encode",
... | 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 | train | 229,064 |
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",
... | Verify the message | [
"Verify",
"the",
"message"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L232-L242 | train | 229,065 |
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):
"""
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),
) | [
"def",
"encrypt",
"(",
"self",
",",
"plaintext",
",",
"nonce",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"if",
"len",
"(",
"nonce",
")",
"!=",
"self",
".",
"NONCE_SIZE",
":",
"raise",
"ValueError",
"(",
"\"The nonce must be exactly %s byt... | 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 | train | 229,066 |
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):
"""
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 | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
",",
"nonce",
"=",
"None",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"# Decode our ciphertext",
"ciphertext",
"=",
"encoder",
".",
"decode",
"(",
"ciphertext",
")",
"if",
"nonce",
"is",
... | 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 | train | 229,067 |
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",
"=",
... | 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... | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/crypto/nacl_wrappers.py#L496-L518 | train | 229,068 |
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):
"""
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 | [
"def",
"getInstalledConfig",
"(",
"installDir",
",",
"configFile",
")",
":",
"configPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"installDir",
",",
"configFile",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"configPath",
")",
":",
"raise"... | 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 | train | 229,069 |
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):
"""
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 | [
"def",
"_getConfig",
"(",
"general_config_dir",
":",
"str",
"=",
"None",
")",
":",
"stp_config",
"=",
"STPConfig",
"(",
")",
"plenum_config",
"=",
"import_module",
"(",
"\"plenum.config\"",
")",
"config",
"=",
"stp_config",
"config",
".",
"__dict__",
".",
"upd... | 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 | train | 229,070 |
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:
"""
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)) | [
"def",
"getFunc",
"(",
"self",
",",
"o",
":",
"Any",
")",
"->",
"Callable",
":",
"for",
"cls",
",",
"func",
"in",
"self",
".",
"routes",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"cls",
")",
":",
"return",
"func",
"logger",
... | 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 | train | 229,071 |
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:
"""
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) | [
"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... | 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 | train | 229,072 |
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:
"""
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 | [
"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 | train | 229,073 |
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:
"""
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 | [
"async",
"def",
"handleAll",
"(",
"self",
",",
"deq",
":",
"deque",
",",
"limit",
"=",
"None",
")",
"->",
"int",
":",
"count",
"=",
"0",
"while",
"deq",
"and",
"(",
"not",
"limit",
"or",
"count",
"<",
"limit",
")",
":",
"count",
"+=",
"1",
"item"... | 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 | train | 229,074 |
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:
"""
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 | [
"def",
"handleAllSync",
"(",
"self",
",",
"deq",
":",
"deque",
",",
"limit",
"=",
"None",
")",
"->",
"int",
":",
"count",
"=",
"0",
"while",
"deq",
"and",
"(",
"not",
"limit",
"or",
"count",
"<",
"limit",
")",
":",
"count",
"+=",
"1",
"msg",
"=",... | 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 | train | 229,075 |
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):
"""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) | [
"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 | train | 229,076 |
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):
"""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 | [
"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 | train | 229,077 |
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]:
"""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 | [
"def",
"append",
"(",
"self",
",",
"new_leaf",
":",
"bytes",
")",
"->",
"List",
"[",
"bytes",
"]",
":",
"auditPath",
"=",
"list",
"(",
"reversed",
"(",
"self",
".",
"__hashes",
")",
")",
"self",
".",
"_push_subtree",
"(",
"[",
"new_leaf",
"]",
")",
... | 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 | train | 229,078 |
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]):
"""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 | [
"def",
"extend",
"(",
"self",
",",
"new_leaves",
":",
"List",
"[",
"bytes",
"]",
")",
":",
"size",
"=",
"len",
"(",
"new_leaves",
")",
"final_size",
"=",
"self",
".",
"tree_size",
"+",
"size",
"idx",
"=",
"0",
"while",
"True",
":",
"# keep pushing subt... | 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 | train | 229,079 |
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]):
"""Returns a new tree equal to this tree extended with new_leaves."""
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 | train | 229,080 |
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:
"""
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 | [
"def",
"verify_consistency",
"(",
"self",
",",
"expected_leaf_count",
")",
"->",
"bool",
":",
"if",
"expected_leaf_count",
"!=",
"self",
".",
"leafCount",
":",
"raise",
"ConsistencyVerificationFailed",
"(",
")",
"if",
"self",
".",
"get_expected_node_count",
"(",
"... | 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 | train | 229,081 |
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:
"""
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) | [
"def",
"isHex",
"(",
"val",
":",
"str",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"# only decodes utf-8 string",
"try",
":",
"val",
"=",
"val",
".",
"decode",
"(",
")",
"except",
"ValueError",
":",
"return",
"False... | 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 | train | 229,082 |
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):
"""
Implement exponential moving average
"""
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 | train | 229,083 |
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:
"""
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) | [
"def",
"getNodePosition",
"(",
"cls",
",",
"start",
",",
"height",
"=",
"None",
")",
"->",
"int",
":",
"pwr",
"=",
"highest_bit_set",
"(",
"start",
")",
"-",
"1",
"height",
"=",
"height",
"or",
"pwr",
"if",
"count_bits_set",
"(",
"start",
")",
"==",
... | 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 | train | 229,084 |
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):
"""
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 | [
"def",
"getPath",
"(",
"cls",
",",
"seqNo",
",",
"offset",
"=",
"0",
")",
":",
"if",
"offset",
">=",
"seqNo",
":",
"raise",
"ValueError",
"(",
"\"Offset should be less than serial number\"",
")",
"pwr",
"=",
"highest_bit_set",
"(",
"seqNo",
"-",
"1",
"-",
... | 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 | train | 229,085 |
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):
"""
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) | [
"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 | train | 229,086 |
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:
"""
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) | [
"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 | train | 229,087 |
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:
"""
Close current and start next chunk
"""
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",
".",... | 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 | train | 229,088 |
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:
"""
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)) | [
"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",
".",
"_openCh... | 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 | train | 229,089 |
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:
"""
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() | [
"def",
"reset",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"close",
"(",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"dataDir",
")",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"d... | 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 | train | 229,090 |
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):
"""
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) | [
"def",
"_listChunks",
"(",
"self",
")",
":",
"chunks",
"=",
"[",
"]",
"for",
"fileName",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"dataDir",
")",
":",
"index",
"=",
"ChunkedFileStore",
".",
"_fileNameToChunkIndex",
"(",
"fileName",
")",
"if",
"index... | 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 | train | 229,091 |
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:
"""
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 | [
"def",
"filterMsgs",
"(",
"self",
",",
"wrappedMsgs",
":",
"deque",
")",
"->",
"deque",
":",
"filtered",
"=",
"deque",
"(",
")",
"while",
"wrappedMsgs",
":",
"wrappedMsg",
"=",
"wrappedMsgs",
".",
"popleft",
"(",
")",
"msg",
",",
"sender",
"=",
"wrappedM... | 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 | train | 229,092 |
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):
"""Retrieve a plugin by 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 | train | 229,093 |
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:
""" Compares two instances. """
# 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",
"=="... | Compares two instances. | [
"Compares",
"two",
"instances",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/common/version.py#L39-L47 | train | 229,094 |
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):
"""
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 | [
"def",
"maintainConnections",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"now",
"=",
"time",
".",
"perf_counter",
"(",
")",
"if",
"now",
"<",
"self",
".",
"nextCheck",
"and",
"not",
"force",
":",
"return",
"False",
"self",
".",
"nextCheck",
"="... | Ensure appropriate connections. | [
"Ensure",
"appropriate",
"connections",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/kit_zstack.py#L54-L69 | train | 229,095 |
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:
"""
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 | [
"def",
"connectToMissing",
"(",
"self",
")",
"->",
"set",
":",
"missing",
"=",
"self",
".",
"reconcileNodeReg",
"(",
")",
"if",
"not",
"missing",
":",
"return",
"missing",
"logger",
".",
"info",
"(",
"\"{}{} found the following missing connections: {}\"",
".",
"... | 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 | train | 229,096 |
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):
"""
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) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"should_cb",
"=",
"None",
"attr_val",
"=",
"None",
"if",
"hasattr",
"(",
"record",
",",
"self",
".",
"typestr",
")",
":",
"attr_val",
"=",
"getattr",
"(",
"record",
",",
"self",
".",
"typestr",
")"... | 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 | train | 229,097 |
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:
"""
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) | [
"def",
"conns",
"(",
"self",
",",
"value",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_conns",
"==",
"value",
":",
"old",
"=",
"self",
".",
"_conns",
"self",
".",
"_conns",
"=",
"value",
"ins",
"=",
"value",
... | 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 | train | 229,098 |
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):
"""
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 | [
"def",
"findInNodeRegByHA",
"(",
"self",
",",
"remoteHa",
")",
":",
"regName",
"=",
"[",
"nm",
"for",
"nm",
",",
"ha",
"in",
"self",
".",
"registry",
".",
"items",
"(",
")",
"if",
"self",
".",
"sameAddr",
"(",
"ha",
",",
"remoteHa",
")",
"]",
"if",... | 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 | train | 229,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.