id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
235,300 | numba/llvmlite | llvmlite/binding/analysis.py | view_dot_graph | def view_dot_graph(graph, filename=None, view=False):
"""
View the given DOT source. If view is True, the image is rendered
and viewed by the default application in the system. The file path of
the output is returned. If view is False, a graphviz.Source object is
returned. If view is False and the environment is in a IPython session,
an IPython image object is returned and can be displayed inline in the
notebook.
This function requires the graphviz package.
Args
----
- graph [str]: a DOT source code
- filename [str]: optional. if given and view is True, this specifies
the file path for the rendered output to write to.
- view [bool]: if True, opens the rendered output file.
"""
# Optionally depends on graphviz package
import graphviz as gv
src = gv.Source(graph)
if view:
# Returns the output file path
return src.render(filename, view=view)
else:
# Attempts to show the graph in IPython notebook
try:
__IPYTHON__
except NameError:
return src
else:
import IPython.display as display
format = 'svg'
return display.SVG(data=src.pipe(format)) | python | def view_dot_graph(graph, filename=None, view=False):
# Optionally depends on graphviz package
import graphviz as gv
src = gv.Source(graph)
if view:
# Returns the output file path
return src.render(filename, view=view)
else:
# Attempts to show the graph in IPython notebook
try:
__IPYTHON__
except NameError:
return src
else:
import IPython.display as display
format = 'svg'
return display.SVG(data=src.pipe(format)) | [
"def",
"view_dot_graph",
"(",
"graph",
",",
"filename",
"=",
"None",
",",
"view",
"=",
"False",
")",
":",
"# Optionally depends on graphviz package",
"import",
"graphviz",
"as",
"gv",
"src",
"=",
"gv",
".",
"Source",
"(",
"graph",
")",
"if",
"view",
":",
"... | View the given DOT source. If view is True, the image is rendered
and viewed by the default application in the system. The file path of
the output is returned. If view is False, a graphviz.Source object is
returned. If view is False and the environment is in a IPython session,
an IPython image object is returned and can be displayed inline in the
notebook.
This function requires the graphviz package.
Args
----
- graph [str]: a DOT source code
- filename [str]: optional. if given and view is True, this specifies
the file path for the rendered output to write to.
- view [bool]: if True, opens the rendered output file. | [
"View",
"the",
"given",
"DOT",
"source",
".",
"If",
"view",
"is",
"True",
"the",
"image",
"is",
"rendered",
"and",
"viewed",
"by",
"the",
"default",
"application",
"in",
"the",
"system",
".",
"The",
"file",
"path",
"of",
"the",
"output",
"is",
"returned"... | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/analysis.py#L32-L67 |
235,301 | numba/llvmlite | llvmlite/binding/value.py | TypeRef.element_type | def element_type(self):
"""
Returns the pointed-to type. When the type is not a pointer,
raises exception.
"""
if not self.is_pointer:
raise ValueError("Type {} is not a pointer".format(self))
return TypeRef(ffi.lib.LLVMPY_GetElementType(self)) | python | def element_type(self):
if not self.is_pointer:
raise ValueError("Type {} is not a pointer".format(self))
return TypeRef(ffi.lib.LLVMPY_GetElementType(self)) | [
"def",
"element_type",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_pointer",
":",
"raise",
"ValueError",
"(",
"\"Type {} is not a pointer\"",
".",
"format",
"(",
"self",
")",
")",
"return",
"TypeRef",
"(",
"ffi",
".",
"lib",
".",
"LLVMPY_GetElementT... | Returns the pointed-to type. When the type is not a pointer,
raises exception. | [
"Returns",
"the",
"pointed",
"-",
"to",
"type",
".",
"When",
"the",
"type",
"is",
"not",
"a",
"pointer",
"raises",
"exception",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L64-L71 |
235,302 | numba/llvmlite | llvmlite/binding/value.py | ValueRef.add_function_attribute | def add_function_attribute(self, attr):
"""Only works on function value
Parameters
-----------
attr : str
attribute name
"""
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
attrname = str(attr)
attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName(
_encode_string(attrname), len(attrname))
if attrval == 0:
raise ValueError('no such attribute {!r}'.format(attrname))
ffi.lib.LLVMPY_AddFunctionAttr(self, attrval) | python | def add_function_attribute(self, attr):
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
attrname = str(attr)
attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName(
_encode_string(attrname), len(attrname))
if attrval == 0:
raise ValueError('no such attribute {!r}'.format(attrname))
ffi.lib.LLVMPY_AddFunctionAttr(self, attrval) | [
"def",
"add_function_attribute",
"(",
"self",
",",
"attr",
")",
":",
"if",
"not",
"self",
".",
"is_function",
":",
"raise",
"ValueError",
"(",
"'expected function value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"attrname",
"=",
"str",
"(",
... | Only works on function value
Parameters
-----------
attr : str
attribute name | [
"Only",
"works",
"on",
"function",
"value"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L181-L196 |
235,303 | numba/llvmlite | llvmlite/binding/value.py | ValueRef.attributes | def attributes(self):
"""
Return an iterator over this value's attributes.
The iterator will yield a string for each attribute.
"""
itr = iter(())
if self.is_function:
it = ffi.lib.LLVMPY_FunctionAttributesIter(self)
itr = _AttributeListIterator(it)
elif self.is_instruction:
if self.opcode == 'call':
it = ffi.lib.LLVMPY_CallInstAttributesIter(self)
itr = _AttributeListIterator(it)
elif self.opcode == 'invoke':
it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self)
itr = _AttributeListIterator(it)
elif self.is_global:
it = ffi.lib.LLVMPY_GlobalAttributesIter(self)
itr = _AttributeSetIterator(it)
elif self.is_argument:
it = ffi.lib.LLVMPY_ArgumentAttributesIter(self)
itr = _AttributeSetIterator(it)
return itr | python | def attributes(self):
itr = iter(())
if self.is_function:
it = ffi.lib.LLVMPY_FunctionAttributesIter(self)
itr = _AttributeListIterator(it)
elif self.is_instruction:
if self.opcode == 'call':
it = ffi.lib.LLVMPY_CallInstAttributesIter(self)
itr = _AttributeListIterator(it)
elif self.opcode == 'invoke':
it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self)
itr = _AttributeListIterator(it)
elif self.is_global:
it = ffi.lib.LLVMPY_GlobalAttributesIter(self)
itr = _AttributeSetIterator(it)
elif self.is_argument:
it = ffi.lib.LLVMPY_ArgumentAttributesIter(self)
itr = _AttributeSetIterator(it)
return itr | [
"def",
"attributes",
"(",
"self",
")",
":",
"itr",
"=",
"iter",
"(",
"(",
")",
")",
"if",
"self",
".",
"is_function",
":",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_FunctionAttributesIter",
"(",
"self",
")",
"itr",
"=",
"_AttributeListIterator",
"(",
... | Return an iterator over this value's attributes.
The iterator will yield a string for each attribute. | [
"Return",
"an",
"iterator",
"over",
"this",
"value",
"s",
"attributes",
".",
"The",
"iterator",
"will",
"yield",
"a",
"string",
"for",
"each",
"attribute",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L218-L240 |
235,304 | numba/llvmlite | llvmlite/binding/value.py | ValueRef.blocks | def blocks(self):
"""
Return an iterator over this function's blocks.
The iterator will yield a ValueRef for each block.
"""
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_FunctionBlocksIter(self)
parents = self._parents.copy()
parents.update(function=self)
return _BlocksIterator(it, parents) | python | def blocks(self):
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_FunctionBlocksIter(self)
parents = self._parents.copy()
parents.update(function=self)
return _BlocksIterator(it, parents) | [
"def",
"blocks",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_function",
":",
"raise",
"ValueError",
"(",
"'expected function value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_FunctionBlocksI... | Return an iterator over this function's blocks.
The iterator will yield a ValueRef for each block. | [
"Return",
"an",
"iterator",
"over",
"this",
"function",
"s",
"blocks",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"block",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L243-L253 |
235,305 | numba/llvmlite | llvmlite/binding/value.py | ValueRef.arguments | def arguments(self):
"""
Return an iterator over this function's arguments.
The iterator will yield a ValueRef for each argument.
"""
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_FunctionArgumentsIter(self)
parents = self._parents.copy()
parents.update(function=self)
return _ArgumentsIterator(it, parents) | python | def arguments(self):
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_FunctionArgumentsIter(self)
parents = self._parents.copy()
parents.update(function=self)
return _ArgumentsIterator(it, parents) | [
"def",
"arguments",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_function",
":",
"raise",
"ValueError",
"(",
"'expected function value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_FunctionArgu... | Return an iterator over this function's arguments.
The iterator will yield a ValueRef for each argument. | [
"Return",
"an",
"iterator",
"over",
"this",
"function",
"s",
"arguments",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"argument",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L256-L266 |
235,306 | numba/llvmlite | llvmlite/binding/value.py | ValueRef.instructions | def instructions(self):
"""
Return an iterator over this block's instructions.
The iterator will yield a ValueRef for each instruction.
"""
if not self.is_block:
raise ValueError('expected block value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_BlockInstructionsIter(self)
parents = self._parents.copy()
parents.update(block=self)
return _InstructionsIterator(it, parents) | python | def instructions(self):
if not self.is_block:
raise ValueError('expected block value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_BlockInstructionsIter(self)
parents = self._parents.copy()
parents.update(block=self)
return _InstructionsIterator(it, parents) | [
"def",
"instructions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_block",
":",
"raise",
"ValueError",
"(",
"'expected block value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_BlockInstructio... | Return an iterator over this block's instructions.
The iterator will yield a ValueRef for each instruction. | [
"Return",
"an",
"iterator",
"over",
"this",
"block",
"s",
"instructions",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"instruction",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L269-L279 |
235,307 | numba/llvmlite | llvmlite/binding/value.py | ValueRef.operands | def operands(self):
"""
Return an iterator over this instruction's operands.
The iterator will yield a ValueRef for each operand.
"""
if not self.is_instruction:
raise ValueError('expected instruction value, got %s'
% (self._kind,))
it = ffi.lib.LLVMPY_InstructionOperandsIter(self)
parents = self._parents.copy()
parents.update(instruction=self)
return _OperandsIterator(it, parents) | python | def operands(self):
if not self.is_instruction:
raise ValueError('expected instruction value, got %s'
% (self._kind,))
it = ffi.lib.LLVMPY_InstructionOperandsIter(self)
parents = self._parents.copy()
parents.update(instruction=self)
return _OperandsIterator(it, parents) | [
"def",
"operands",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_instruction",
":",
"raise",
"ValueError",
"(",
"'expected instruction value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_Instruc... | Return an iterator over this instruction's operands.
The iterator will yield a ValueRef for each operand. | [
"Return",
"an",
"iterator",
"over",
"this",
"instruction",
"s",
"operands",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"operand",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L282-L293 |
235,308 | numba/llvmlite | llvmlite/ir/transforms.py | replace_all_calls | def replace_all_calls(mod, orig, repl):
"""Replace all calls to `orig` to `repl` in module `mod`.
Returns the references to the returned calls
"""
rc = ReplaceCalls(orig, repl)
rc.visit(mod)
return rc.calls | python | def replace_all_calls(mod, orig, repl):
rc = ReplaceCalls(orig, repl)
rc.visit(mod)
return rc.calls | [
"def",
"replace_all_calls",
"(",
"mod",
",",
"orig",
",",
"repl",
")",
":",
"rc",
"=",
"ReplaceCalls",
"(",
"orig",
",",
"repl",
")",
"rc",
".",
"visit",
"(",
"mod",
")",
"return",
"rc",
".",
"calls"
] | Replace all calls to `orig` to `repl` in module `mod`.
Returns the references to the returned calls | [
"Replace",
"all",
"calls",
"to",
"orig",
"to",
"repl",
"in",
"module",
"mod",
".",
"Returns",
"the",
"references",
"to",
"the",
"returned",
"calls"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/transforms.py#L58-L64 |
235,309 | rm-hull/luma.oled | luma/oled/device/color.py | color_device.display | def display(self, image):
"""
Renders a 24-bit RGB image to the Color OLED display.
:param image: The image to render.
:type image: PIL.Image.Image
"""
assert(image.mode == self.mode)
assert(image.size == self.size)
image = self.preprocess(image)
if self.framebuffer.redraw_required(image):
left, top, right, bottom = self._apply_offsets(self.framebuffer.bounding_box)
width = right - left
height = bottom - top
self._set_position(top, right, bottom, left)
i = 0
buf = bytearray(width * height * 2)
for r, g, b in self.framebuffer.getdata():
if not(r == g == b == 0):
# 65K format 1
buf[i] = r & 0xF8 | g >> 5
buf[i + 1] = g << 3 & 0xE0 | b >> 3
i += 2
self.data(list(buf)) | python | def display(self, image):
assert(image.mode == self.mode)
assert(image.size == self.size)
image = self.preprocess(image)
if self.framebuffer.redraw_required(image):
left, top, right, bottom = self._apply_offsets(self.framebuffer.bounding_box)
width = right - left
height = bottom - top
self._set_position(top, right, bottom, left)
i = 0
buf = bytearray(width * height * 2)
for r, g, b in self.framebuffer.getdata():
if not(r == g == b == 0):
# 65K format 1
buf[i] = r & 0xF8 | g >> 5
buf[i + 1] = g << 3 & 0xE0 | b >> 3
i += 2
self.data(list(buf)) | [
"def",
"display",
"(",
"self",
",",
"image",
")",
":",
"assert",
"(",
"image",
".",
"mode",
"==",
"self",
".",
"mode",
")",
"assert",
"(",
"image",
".",
"size",
"==",
"self",
".",
"size",
")",
"image",
"=",
"self",
".",
"preprocess",
"(",
"image",
... | Renders a 24-bit RGB image to the Color OLED display.
:param image: The image to render.
:type image: PIL.Image.Image | [
"Renders",
"a",
"24",
"-",
"bit",
"RGB",
"image",
"to",
"the",
"Color",
"OLED",
"display",
"."
] | 76055aa2ca486dc2f9def49754b74ffbccdc5491 | https://github.com/rm-hull/luma.oled/blob/76055aa2ca486dc2f9def49754b74ffbccdc5491/luma/oled/device/color.py#L68-L96 |
235,310 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | events_for_onchain_secretreveal | def events_for_onchain_secretreveal(
target_state: TargetTransferState,
channel_state: NettingChannelState,
block_number: BlockNumber,
block_hash: BlockHash,
) -> List[Event]:
""" Emits the event for revealing the secret on-chain if the transfer
can not be settled off-chain.
"""
transfer = target_state.transfer
expiration = transfer.lock.expiration
safe_to_wait, _ = is_safe_to_wait(
expiration,
channel_state.reveal_timeout,
block_number,
)
secret_known_offchain = channel.is_secret_known_offchain(
channel_state.partner_state,
transfer.lock.secrethash,
)
has_onchain_reveal_started = (
target_state.state == TargetTransferState.ONCHAIN_SECRET_REVEAL
)
if not safe_to_wait and secret_known_offchain and not has_onchain_reveal_started:
target_state.state = TargetTransferState.ONCHAIN_SECRET_REVEAL
secret = channel.get_secret(
channel_state.partner_state,
transfer.lock.secrethash,
)
assert secret, 'secret should be known at this point'
return secret_registry.events_for_onchain_secretreveal(
channel_state=channel_state,
secret=secret,
expiration=expiration,
block_hash=block_hash,
)
return list() | python | def events_for_onchain_secretreveal(
target_state: TargetTransferState,
channel_state: NettingChannelState,
block_number: BlockNumber,
block_hash: BlockHash,
) -> List[Event]:
transfer = target_state.transfer
expiration = transfer.lock.expiration
safe_to_wait, _ = is_safe_to_wait(
expiration,
channel_state.reveal_timeout,
block_number,
)
secret_known_offchain = channel.is_secret_known_offchain(
channel_state.partner_state,
transfer.lock.secrethash,
)
has_onchain_reveal_started = (
target_state.state == TargetTransferState.ONCHAIN_SECRET_REVEAL
)
if not safe_to_wait and secret_known_offchain and not has_onchain_reveal_started:
target_state.state = TargetTransferState.ONCHAIN_SECRET_REVEAL
secret = channel.get_secret(
channel_state.partner_state,
transfer.lock.secrethash,
)
assert secret, 'secret should be known at this point'
return secret_registry.events_for_onchain_secretreveal(
channel_state=channel_state,
secret=secret,
expiration=expiration,
block_hash=block_hash,
)
return list() | [
"def",
"events_for_onchain_secretreveal",
"(",
"target_state",
":",
"TargetTransferState",
",",
"channel_state",
":",
"NettingChannelState",
",",
"block_number",
":",
"BlockNumber",
",",
"block_hash",
":",
"BlockHash",
",",
")",
"->",
"List",
"[",
"Event",
"]",
":",... | Emits the event for revealing the secret on-chain if the transfer
can not be settled off-chain. | [
"Emits",
"the",
"event",
"for",
"revealing",
"the",
"secret",
"on",
"-",
"chain",
"if",
"the",
"transfer",
"can",
"not",
"be",
"settled",
"off",
"-",
"chain",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L59-L98 |
235,311 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | handle_inittarget | def handle_inittarget(
state_change: ActionInitTarget,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
""" Handles an ActionInitTarget state change. """
transfer = state_change.transfer
route = state_change.route
assert channel_state.identifier == transfer.balance_proof.channel_identifier
is_valid, channel_events, errormsg = channel.handle_receive_lockedtransfer(
channel_state,
transfer,
)
if is_valid:
# A valid balance proof does not mean the payment itself is still valid.
# e.g. the lock may be near expiration or have expired. This is fine. The
# message with an unusable lock must be handled to properly synchronize the
# local view of the partner's channel state, allowing the next balance
# proofs to be handled. This however, must only be done once, which is
# enforced by the nonce increasing sequentially, which is verified by
# the handler handle_receive_lockedtransfer.
target_state = TargetTransferState(route, transfer)
safe_to_wait, _ = is_safe_to_wait(
transfer.lock.expiration,
channel_state.reveal_timeout,
block_number,
)
# If there is not enough time to safely unlock the lock on-chain
# silently let the transfer expire. The target task must be created to
# handle the ReceiveLockExpired state change, which will clear the
# expired lock.
if safe_to_wait:
message_identifier = message_identifier_from_prng(pseudo_random_generator)
recipient = transfer.initiator
secret_request = SendSecretRequest(
recipient=Address(recipient),
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=message_identifier,
payment_identifier=transfer.payment_identifier,
amount=transfer.lock.amount,
expiration=transfer.lock.expiration,
secrethash=transfer.lock.secrethash,
)
channel_events.append(secret_request)
iteration = TransitionResult(target_state, channel_events)
else:
# If the balance proof is not valid, do *not* create a task. Otherwise it's
# possible for an attacker to send multiple invalid transfers, and increase
# the memory usage of this Node.
unlock_failed = EventUnlockClaimFailed(
identifier=transfer.payment_identifier,
secrethash=transfer.lock.secrethash,
reason=errormsg,
)
channel_events.append(unlock_failed)
iteration = TransitionResult(None, channel_events)
return iteration | python | def handle_inittarget(
state_change: ActionInitTarget,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
transfer = state_change.transfer
route = state_change.route
assert channel_state.identifier == transfer.balance_proof.channel_identifier
is_valid, channel_events, errormsg = channel.handle_receive_lockedtransfer(
channel_state,
transfer,
)
if is_valid:
# A valid balance proof does not mean the payment itself is still valid.
# e.g. the lock may be near expiration or have expired. This is fine. The
# message with an unusable lock must be handled to properly synchronize the
# local view of the partner's channel state, allowing the next balance
# proofs to be handled. This however, must only be done once, which is
# enforced by the nonce increasing sequentially, which is verified by
# the handler handle_receive_lockedtransfer.
target_state = TargetTransferState(route, transfer)
safe_to_wait, _ = is_safe_to_wait(
transfer.lock.expiration,
channel_state.reveal_timeout,
block_number,
)
# If there is not enough time to safely unlock the lock on-chain
# silently let the transfer expire. The target task must be created to
# handle the ReceiveLockExpired state change, which will clear the
# expired lock.
if safe_to_wait:
message_identifier = message_identifier_from_prng(pseudo_random_generator)
recipient = transfer.initiator
secret_request = SendSecretRequest(
recipient=Address(recipient),
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=message_identifier,
payment_identifier=transfer.payment_identifier,
amount=transfer.lock.amount,
expiration=transfer.lock.expiration,
secrethash=transfer.lock.secrethash,
)
channel_events.append(secret_request)
iteration = TransitionResult(target_state, channel_events)
else:
# If the balance proof is not valid, do *not* create a task. Otherwise it's
# possible for an attacker to send multiple invalid transfers, and increase
# the memory usage of this Node.
unlock_failed = EventUnlockClaimFailed(
identifier=transfer.payment_identifier,
secrethash=transfer.lock.secrethash,
reason=errormsg,
)
channel_events.append(unlock_failed)
iteration = TransitionResult(None, channel_events)
return iteration | [
"def",
"handle_inittarget",
"(",
"state_change",
":",
"ActionInitTarget",
",",
"channel_state",
":",
"NettingChannelState",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
",",
"block_number",
":",
"BlockNumber",
",",
")",
"->",
"TransitionResult",
"[",
... | Handles an ActionInitTarget state change. | [
"Handles",
"an",
"ActionInitTarget",
"state",
"change",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L101-L164 |
235,312 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | handle_offchain_secretreveal | def handle_offchain_secretreveal(
target_state: TargetTransferState,
state_change: ReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
""" Validates and handles a ReceiveSecretReveal state change. """
valid_secret = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=target_state.transfer.lock.secrethash,
secret=state_change.secret,
)
has_transfer_expired = channel.is_transfer_expired(
transfer=target_state.transfer,
affected_channel=channel_state,
block_number=block_number,
)
if valid_secret and not has_transfer_expired:
channel.register_offchain_secret(
channel_state=channel_state,
secret=state_change.secret,
secrethash=state_change.secrethash,
)
route = target_state.route
message_identifier = message_identifier_from_prng(pseudo_random_generator)
target_state.state = TargetTransferState.OFFCHAIN_SECRET_REVEAL
target_state.secret = state_change.secret
recipient = route.node_address
reveal = SendSecretReveal(
recipient=recipient,
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=message_identifier,
secret=target_state.secret,
)
iteration = TransitionResult(target_state, [reveal])
else:
# TODO: event for byzantine behavior
iteration = TransitionResult(target_state, list())
return iteration | python | def handle_offchain_secretreveal(
target_state: TargetTransferState,
state_change: ReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
valid_secret = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=target_state.transfer.lock.secrethash,
secret=state_change.secret,
)
has_transfer_expired = channel.is_transfer_expired(
transfer=target_state.transfer,
affected_channel=channel_state,
block_number=block_number,
)
if valid_secret and not has_transfer_expired:
channel.register_offchain_secret(
channel_state=channel_state,
secret=state_change.secret,
secrethash=state_change.secrethash,
)
route = target_state.route
message_identifier = message_identifier_from_prng(pseudo_random_generator)
target_state.state = TargetTransferState.OFFCHAIN_SECRET_REVEAL
target_state.secret = state_change.secret
recipient = route.node_address
reveal = SendSecretReveal(
recipient=recipient,
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=message_identifier,
secret=target_state.secret,
)
iteration = TransitionResult(target_state, [reveal])
else:
# TODO: event for byzantine behavior
iteration = TransitionResult(target_state, list())
return iteration | [
"def",
"handle_offchain_secretreveal",
"(",
"target_state",
":",
"TargetTransferState",
",",
"state_change",
":",
"ReceiveSecretReveal",
",",
"channel_state",
":",
"NettingChannelState",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
",",
"block_number",
":... | Validates and handles a ReceiveSecretReveal state change. | [
"Validates",
"and",
"handles",
"a",
"ReceiveSecretReveal",
"state",
"change",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L167-L212 |
235,313 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | handle_onchain_secretreveal | def handle_onchain_secretreveal(
target_state: TargetTransferState,
state_change: ContractReceiveSecretReveal,
channel_state: NettingChannelState,
) -> TransitionResult[TargetTransferState]:
""" Validates and handles a ContractReceiveSecretReveal state change. """
valid_secret = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=target_state.transfer.lock.secrethash,
secret=state_change.secret,
)
if valid_secret:
channel.register_onchain_secret(
channel_state=channel_state,
secret=state_change.secret,
secrethash=state_change.secrethash,
secret_reveal_block_number=state_change.block_number,
)
target_state.state = TargetTransferState.ONCHAIN_UNLOCK
target_state.secret = state_change.secret
return TransitionResult(target_state, list()) | python | def handle_onchain_secretreveal(
target_state: TargetTransferState,
state_change: ContractReceiveSecretReveal,
channel_state: NettingChannelState,
) -> TransitionResult[TargetTransferState]:
valid_secret = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=target_state.transfer.lock.secrethash,
secret=state_change.secret,
)
if valid_secret:
channel.register_onchain_secret(
channel_state=channel_state,
secret=state_change.secret,
secrethash=state_change.secrethash,
secret_reveal_block_number=state_change.block_number,
)
target_state.state = TargetTransferState.ONCHAIN_UNLOCK
target_state.secret = state_change.secret
return TransitionResult(target_state, list()) | [
"def",
"handle_onchain_secretreveal",
"(",
"target_state",
":",
"TargetTransferState",
",",
"state_change",
":",
"ContractReceiveSecretReveal",
",",
"channel_state",
":",
"NettingChannelState",
",",
")",
"->",
"TransitionResult",
"[",
"TargetTransferState",
"]",
":",
"val... | Validates and handles a ContractReceiveSecretReveal state change. | [
"Validates",
"and",
"handles",
"a",
"ContractReceiveSecretReveal",
"state",
"change",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L215-L238 |
235,314 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | handle_unlock | def handle_unlock(
target_state: TargetTransferState,
state_change: ReceiveUnlock,
channel_state: NettingChannelState,
) -> TransitionResult[TargetTransferState]:
""" Handles a ReceiveUnlock state change. """
balance_proof_sender = state_change.balance_proof.sender
is_valid, events, _ = channel.handle_unlock(
channel_state,
state_change,
)
next_target_state: Optional[TargetTransferState] = target_state
if is_valid:
transfer = target_state.transfer
payment_received_success = EventPaymentReceivedSuccess(
payment_network_identifier=channel_state.payment_network_identifier,
token_network_identifier=TokenNetworkID(channel_state.token_network_identifier),
identifier=transfer.payment_identifier,
amount=TokenAmount(transfer.lock.amount),
initiator=transfer.initiator,
)
unlock_success = EventUnlockClaimSuccess(
transfer.payment_identifier,
transfer.lock.secrethash,
)
send_processed = SendProcessed(
recipient=balance_proof_sender,
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=state_change.message_identifier,
)
events.extend([payment_received_success, unlock_success, send_processed])
next_target_state = None
return TransitionResult(next_target_state, events) | python | def handle_unlock(
target_state: TargetTransferState,
state_change: ReceiveUnlock,
channel_state: NettingChannelState,
) -> TransitionResult[TargetTransferState]:
balance_proof_sender = state_change.balance_proof.sender
is_valid, events, _ = channel.handle_unlock(
channel_state,
state_change,
)
next_target_state: Optional[TargetTransferState] = target_state
if is_valid:
transfer = target_state.transfer
payment_received_success = EventPaymentReceivedSuccess(
payment_network_identifier=channel_state.payment_network_identifier,
token_network_identifier=TokenNetworkID(channel_state.token_network_identifier),
identifier=transfer.payment_identifier,
amount=TokenAmount(transfer.lock.amount),
initiator=transfer.initiator,
)
unlock_success = EventUnlockClaimSuccess(
transfer.payment_identifier,
transfer.lock.secrethash,
)
send_processed = SendProcessed(
recipient=balance_proof_sender,
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=state_change.message_identifier,
)
events.extend([payment_received_success, unlock_success, send_processed])
next_target_state = None
return TransitionResult(next_target_state, events) | [
"def",
"handle_unlock",
"(",
"target_state",
":",
"TargetTransferState",
",",
"state_change",
":",
"ReceiveUnlock",
",",
"channel_state",
":",
"NettingChannelState",
",",
")",
"->",
"TransitionResult",
"[",
"TargetTransferState",
"]",
":",
"balance_proof_sender",
"=",
... | Handles a ReceiveUnlock state change. | [
"Handles",
"a",
"ReceiveUnlock",
"state",
"change",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L241-L279 |
235,315 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | handle_block | def handle_block(
target_state: TargetTransferState,
channel_state: NettingChannelState,
block_number: BlockNumber,
block_hash: BlockHash,
) -> TransitionResult[TargetTransferState]:
""" After Raiden learns about a new block this function must be called to
handle expiration of the hash time lock.
"""
transfer = target_state.transfer
events: List[Event] = list()
lock = transfer.lock
secret_known = channel.is_secret_known(
channel_state.partner_state,
lock.secrethash,
)
lock_has_expired, _ = channel.is_lock_expired(
end_state=channel_state.our_state,
lock=lock,
block_number=block_number,
lock_expiration_threshold=channel.get_receiver_expiration_threshold(lock),
)
if lock_has_expired and target_state.state != 'expired':
failed = EventUnlockClaimFailed(
identifier=transfer.payment_identifier,
secrethash=transfer.lock.secrethash,
reason=f'lock expired',
)
target_state.state = TargetTransferState.EXPIRED
events = [failed]
elif secret_known:
events = events_for_onchain_secretreveal(
target_state=target_state,
channel_state=channel_state,
block_number=block_number,
block_hash=block_hash,
)
return TransitionResult(target_state, events) | python | def handle_block(
target_state: TargetTransferState,
channel_state: NettingChannelState,
block_number: BlockNumber,
block_hash: BlockHash,
) -> TransitionResult[TargetTransferState]:
transfer = target_state.transfer
events: List[Event] = list()
lock = transfer.lock
secret_known = channel.is_secret_known(
channel_state.partner_state,
lock.secrethash,
)
lock_has_expired, _ = channel.is_lock_expired(
end_state=channel_state.our_state,
lock=lock,
block_number=block_number,
lock_expiration_threshold=channel.get_receiver_expiration_threshold(lock),
)
if lock_has_expired and target_state.state != 'expired':
failed = EventUnlockClaimFailed(
identifier=transfer.payment_identifier,
secrethash=transfer.lock.secrethash,
reason=f'lock expired',
)
target_state.state = TargetTransferState.EXPIRED
events = [failed]
elif secret_known:
events = events_for_onchain_secretreveal(
target_state=target_state,
channel_state=channel_state,
block_number=block_number,
block_hash=block_hash,
)
return TransitionResult(target_state, events) | [
"def",
"handle_block",
"(",
"target_state",
":",
"TargetTransferState",
",",
"channel_state",
":",
"NettingChannelState",
",",
"block_number",
":",
"BlockNumber",
",",
"block_hash",
":",
"BlockHash",
",",
")",
"->",
"TransitionResult",
"[",
"TargetTransferState",
"]",... | After Raiden learns about a new block this function must be called to
handle expiration of the hash time lock. | [
"After",
"Raiden",
"learns",
"about",
"a",
"new",
"block",
"this",
"function",
"must",
"be",
"called",
"to",
"handle",
"expiration",
"of",
"the",
"hash",
"time",
"lock",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L282-L322 |
235,316 | raiden-network/raiden | raiden/transfer/mediated_transfer/target.py | state_transition | def state_transition(
target_state: Optional[TargetTransferState],
state_change: StateChange,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
""" State machine for the target node of a mediated transfer. """
# pylint: disable=too-many-branches,unidiomatic-typecheck
iteration = TransitionResult(target_state, list())
if type(state_change) == ActionInitTarget:
assert isinstance(state_change, ActionInitTarget), MYPY_ANNOTATION
if target_state is None:
iteration = handle_inittarget(
state_change,
channel_state,
pseudo_random_generator,
block_number,
)
elif type(state_change) == Block:
assert isinstance(state_change, Block), MYPY_ANNOTATION
assert state_change.block_number == block_number
assert target_state, 'Block state changes should be accompanied by a valid target state'
iteration = handle_block(
target_state=target_state,
channel_state=channel_state,
block_number=state_change.block_number,
block_hash=state_change.block_hash,
)
elif type(state_change) == ReceiveSecretReveal:
assert isinstance(state_change, ReceiveSecretReveal), MYPY_ANNOTATION
assert target_state, 'ReceiveSecretReveal should be accompanied by a valid target state'
iteration = handle_offchain_secretreveal(
target_state=target_state,
state_change=state_change,
channel_state=channel_state,
pseudo_random_generator=pseudo_random_generator,
block_number=block_number,
)
elif type(state_change) == ContractReceiveSecretReveal:
assert isinstance(state_change, ContractReceiveSecretReveal), MYPY_ANNOTATION
msg = 'ContractReceiveSecretReveal should be accompanied by a valid target state'
assert target_state, msg
iteration = handle_onchain_secretreveal(
target_state,
state_change,
channel_state,
)
elif type(state_change) == ReceiveUnlock:
assert isinstance(state_change, ReceiveUnlock), MYPY_ANNOTATION
assert target_state, 'ReceiveUnlock should be accompanied by a valid target state'
iteration = handle_unlock(
target_state=target_state,
state_change=state_change,
channel_state=channel_state,
)
elif type(state_change) == ReceiveLockExpired:
assert isinstance(state_change, ReceiveLockExpired), MYPY_ANNOTATION
assert target_state, 'ReceiveLockExpired should be accompanied by a valid target state'
iteration = handle_lock_expired(
target_state=target_state,
state_change=state_change,
channel_state=channel_state,
block_number=block_number,
)
sanity_check(
old_state=target_state,
new_state=iteration.new_state,
channel_state=channel_state,
)
return iteration | python | def state_transition(
target_state: Optional[TargetTransferState],
state_change: StateChange,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
# pylint: disable=too-many-branches,unidiomatic-typecheck
iteration = TransitionResult(target_state, list())
if type(state_change) == ActionInitTarget:
assert isinstance(state_change, ActionInitTarget), MYPY_ANNOTATION
if target_state is None:
iteration = handle_inittarget(
state_change,
channel_state,
pseudo_random_generator,
block_number,
)
elif type(state_change) == Block:
assert isinstance(state_change, Block), MYPY_ANNOTATION
assert state_change.block_number == block_number
assert target_state, 'Block state changes should be accompanied by a valid target state'
iteration = handle_block(
target_state=target_state,
channel_state=channel_state,
block_number=state_change.block_number,
block_hash=state_change.block_hash,
)
elif type(state_change) == ReceiveSecretReveal:
assert isinstance(state_change, ReceiveSecretReveal), MYPY_ANNOTATION
assert target_state, 'ReceiveSecretReveal should be accompanied by a valid target state'
iteration = handle_offchain_secretreveal(
target_state=target_state,
state_change=state_change,
channel_state=channel_state,
pseudo_random_generator=pseudo_random_generator,
block_number=block_number,
)
elif type(state_change) == ContractReceiveSecretReveal:
assert isinstance(state_change, ContractReceiveSecretReveal), MYPY_ANNOTATION
msg = 'ContractReceiveSecretReveal should be accompanied by a valid target state'
assert target_state, msg
iteration = handle_onchain_secretreveal(
target_state,
state_change,
channel_state,
)
elif type(state_change) == ReceiveUnlock:
assert isinstance(state_change, ReceiveUnlock), MYPY_ANNOTATION
assert target_state, 'ReceiveUnlock should be accompanied by a valid target state'
iteration = handle_unlock(
target_state=target_state,
state_change=state_change,
channel_state=channel_state,
)
elif type(state_change) == ReceiveLockExpired:
assert isinstance(state_change, ReceiveLockExpired), MYPY_ANNOTATION
assert target_state, 'ReceiveLockExpired should be accompanied by a valid target state'
iteration = handle_lock_expired(
target_state=target_state,
state_change=state_change,
channel_state=channel_state,
block_number=block_number,
)
sanity_check(
old_state=target_state,
new_state=iteration.new_state,
channel_state=channel_state,
)
return iteration | [
"def",
"state_transition",
"(",
"target_state",
":",
"Optional",
"[",
"TargetTransferState",
"]",
",",
"state_change",
":",
"StateChange",
",",
"channel_state",
":",
"NettingChannelState",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
",",
"block_numbe... | State machine for the target node of a mediated transfer. | [
"State",
"machine",
"for",
"the",
"target",
"node",
"of",
"a",
"mediated",
"transfer",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/target.py#L352-L426 |
235,317 | raiden-network/raiden | raiden/encoding/messages.py | wrap | def wrap(data):
""" Try to decode data into a message, might return None if the data is invalid. """
try:
cmdid = data[0]
except IndexError:
log.warning('data is empty')
return None
try:
message_type = CMDID_MESSAGE[cmdid]
except KeyError:
log.error('unknown cmdid %s', cmdid)
return None
try:
message = message_type(data)
except ValueError:
log.error('trying to decode invalid message')
return None
return message | python | def wrap(data):
try:
cmdid = data[0]
except IndexError:
log.warning('data is empty')
return None
try:
message_type = CMDID_MESSAGE[cmdid]
except KeyError:
log.error('unknown cmdid %s', cmdid)
return None
try:
message = message_type(data)
except ValueError:
log.error('trying to decode invalid message')
return None
return message | [
"def",
"wrap",
"(",
"data",
")",
":",
"try",
":",
"cmdid",
"=",
"data",
"[",
"0",
"]",
"except",
"IndexError",
":",
"log",
".",
"warning",
"(",
"'data is empty'",
")",
"return",
"None",
"try",
":",
"message_type",
"=",
"CMDID_MESSAGE",
"[",
"cmdid",
"]... | Try to decode data into a message, might return None if the data is invalid. | [
"Try",
"to",
"decode",
"data",
"into",
"a",
"message",
"might",
"return",
"None",
"if",
"the",
"data",
"is",
"invalid",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/encoding/messages.py#L286-L306 |
235,318 | raiden-network/raiden | raiden/utils/solc.py | solidity_resolve_address | def solidity_resolve_address(hex_code, library_symbol, library_address):
""" Change the bytecode to use the given library address.
Args:
hex_code (bin): The bytecode encoded in hexadecimal.
library_name (str): The library that will be resolved.
library_address (str): The address of the library.
Returns:
bin: The bytecode encoded in hexadecimal with the library references
resolved.
"""
if library_address.startswith('0x'):
raise ValueError('Address should not contain the 0x prefix')
try:
decode_hex(library_address)
except TypeError:
raise ValueError(
'library_address contains invalid characters, it must be hex encoded.')
if len(library_symbol) != 40 or len(library_address) != 40:
raise ValueError('Address with wrong length')
return hex_code.replace(library_symbol, library_address) | python | def solidity_resolve_address(hex_code, library_symbol, library_address):
if library_address.startswith('0x'):
raise ValueError('Address should not contain the 0x prefix')
try:
decode_hex(library_address)
except TypeError:
raise ValueError(
'library_address contains invalid characters, it must be hex encoded.')
if len(library_symbol) != 40 or len(library_address) != 40:
raise ValueError('Address with wrong length')
return hex_code.replace(library_symbol, library_address) | [
"def",
"solidity_resolve_address",
"(",
"hex_code",
",",
"library_symbol",
",",
"library_address",
")",
":",
"if",
"library_address",
".",
"startswith",
"(",
"'0x'",
")",
":",
"raise",
"ValueError",
"(",
"'Address should not contain the 0x prefix'",
")",
"try",
":",
... | Change the bytecode to use the given library address.
Args:
hex_code (bin): The bytecode encoded in hexadecimal.
library_name (str): The library that will be resolved.
library_address (str): The address of the library.
Returns:
bin: The bytecode encoded in hexadecimal with the library references
resolved. | [
"Change",
"the",
"bytecode",
"to",
"use",
"the",
"given",
"library",
"address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/solc.py#L8-L32 |
235,319 | raiden-network/raiden | raiden/utils/solc.py | solidity_library_symbol | def solidity_library_symbol(library_name):
""" Return the symbol used in the bytecode to represent the `library_name`. """
# the symbol is always 40 characters in length with the minimum of two
# leading and trailing underscores
length = min(len(library_name), 36)
library_piece = library_name[:length]
hold_piece = '_' * (36 - length)
return '__{library}{hold}__'.format(
library=library_piece,
hold=hold_piece,
) | python | def solidity_library_symbol(library_name):
# the symbol is always 40 characters in length with the minimum of two
# leading and trailing underscores
length = min(len(library_name), 36)
library_piece = library_name[:length]
hold_piece = '_' * (36 - length)
return '__{library}{hold}__'.format(
library=library_piece,
hold=hold_piece,
) | [
"def",
"solidity_library_symbol",
"(",
"library_name",
")",
":",
"# the symbol is always 40 characters in length with the minimum of two",
"# leading and trailing underscores",
"length",
"=",
"min",
"(",
"len",
"(",
"library_name",
")",
",",
"36",
")",
"library_piece",
"=",
... | Return the symbol used in the bytecode to represent the `library_name`. | [
"Return",
"the",
"symbol",
"used",
"in",
"the",
"bytecode",
"to",
"represent",
"the",
"library_name",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/solc.py#L48-L60 |
235,320 | raiden-network/raiden | raiden/utils/solc.py | compile_files_cwd | def compile_files_cwd(*args, **kwargs):
"""change working directory to contract's dir in order to avoid symbol
name conflicts"""
# get root directory of the contracts
compile_wd = os.path.commonprefix(args[0])
# edge case - compiling a single file
if os.path.isfile(compile_wd):
compile_wd = os.path.dirname(compile_wd)
# remove prefix from the files
if compile_wd[-1] != '/':
compile_wd += '/'
file_list = [
x.replace(compile_wd, '')
for x in args[0]
]
cwd = os.getcwd()
try:
os.chdir(compile_wd)
compiled_contracts = compile_files(
source_files=file_list,
# We need to specify output values here because py-solc by default
# provides them all and does not know that "clone-bin" does not exist
# in solidity >= v0.5.0
output_values=('abi', 'asm', 'ast', 'bin', 'bin-runtime'),
**kwargs,
)
finally:
os.chdir(cwd)
return compiled_contracts | python | def compile_files_cwd(*args, **kwargs):
# get root directory of the contracts
compile_wd = os.path.commonprefix(args[0])
# edge case - compiling a single file
if os.path.isfile(compile_wd):
compile_wd = os.path.dirname(compile_wd)
# remove prefix from the files
if compile_wd[-1] != '/':
compile_wd += '/'
file_list = [
x.replace(compile_wd, '')
for x in args[0]
]
cwd = os.getcwd()
try:
os.chdir(compile_wd)
compiled_contracts = compile_files(
source_files=file_list,
# We need to specify output values here because py-solc by default
# provides them all and does not know that "clone-bin" does not exist
# in solidity >= v0.5.0
output_values=('abi', 'asm', 'ast', 'bin', 'bin-runtime'),
**kwargs,
)
finally:
os.chdir(cwd)
return compiled_contracts | [
"def",
"compile_files_cwd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# get root directory of the contracts",
"compile_wd",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"args",
"[",
"0",
"]",
")",
"# edge case - compiling a single file",
"if",
"... | change working directory to contract's dir in order to avoid symbol
name conflicts | [
"change",
"working",
"directory",
"to",
"contract",
"s",
"dir",
"in",
"order",
"to",
"avoid",
"symbol",
"name",
"conflicts"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/solc.py#L76-L104 |
235,321 | raiden-network/raiden | raiden/accounts.py | AccountManager.get_privkey | def get_privkey(self, address: AddressHex, password: str) -> PrivateKey:
"""Find the keystore file for an account, unlock it and get the private key
Args:
address: The Ethereum address for which to find the keyfile in the system
password: Mostly for testing purposes. A password can be provided
as the function argument here. If it's not then the
user is interactively queried for one.
Returns
The private key associated with the address
"""
address = add_0x_prefix(address).lower()
if not self.address_in_keystore(address):
raise ValueError('Keystore file not found for %s' % address)
with open(self.accounts[address]) as data_file:
data = json.load(data_file)
acc = Account(data, password, self.accounts[address])
return acc.privkey | python | def get_privkey(self, address: AddressHex, password: str) -> PrivateKey:
address = add_0x_prefix(address).lower()
if not self.address_in_keystore(address):
raise ValueError('Keystore file not found for %s' % address)
with open(self.accounts[address]) as data_file:
data = json.load(data_file)
acc = Account(data, password, self.accounts[address])
return acc.privkey | [
"def",
"get_privkey",
"(",
"self",
",",
"address",
":",
"AddressHex",
",",
"password",
":",
"str",
")",
"->",
"PrivateKey",
":",
"address",
"=",
"add_0x_prefix",
"(",
"address",
")",
".",
"lower",
"(",
")",
"if",
"not",
"self",
".",
"address_in_keystore",
... | Find the keystore file for an account, unlock it and get the private key
Args:
address: The Ethereum address for which to find the keyfile in the system
password: Mostly for testing purposes. A password can be provided
as the function argument here. If it's not then the
user is interactively queried for one.
Returns
The private key associated with the address | [
"Find",
"the",
"keystore",
"file",
"for",
"an",
"account",
"unlock",
"it",
"and",
"get",
"the",
"private",
"key"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/accounts.py#L135-L155 |
235,322 | raiden-network/raiden | raiden/accounts.py | Account.load | def load(cls, path: str, password: str = None) -> 'Account':
"""Load an account from a keystore file.
Args:
path: full path to the keyfile
password: the password to decrypt the key file or `None` to leave it encrypted
"""
with open(path) as f:
keystore = json.load(f)
if not check_keystore_json(keystore):
raise ValueError('Invalid keystore file')
return Account(keystore, password, path=path) | python | def load(cls, path: str, password: str = None) -> 'Account':
with open(path) as f:
keystore = json.load(f)
if not check_keystore_json(keystore):
raise ValueError('Invalid keystore file')
return Account(keystore, password, path=path) | [
"def",
"load",
"(",
"cls",
",",
"path",
":",
"str",
",",
"password",
":",
"str",
"=",
"None",
")",
"->",
"'Account'",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"keystore",
"=",
"json",
".",
"load",
"(",
"f",
")",
"if",
"not",
"chec... | Load an account from a keystore file.
Args:
path: full path to the keyfile
password: the password to decrypt the key file or `None` to leave it encrypted | [
"Load",
"an",
"account",
"from",
"a",
"keystore",
"file",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/accounts.py#L186-L197 |
235,323 | raiden-network/raiden | raiden/accounts.py | Account.dump | def dump(self, include_address=True, include_id=True) -> str:
"""Dump the keystore for later disk storage.
The result inherits the entries `'crypto'` and `'version`' from `account.keystore`, and
adds `'address'` and `'id'` in accordance with the parameters `'include_address'` and
`'include_id`'.
If address or id are not known, they are not added, even if requested.
Args:
include_address: flag denoting if the address should be included or not
include_id: flag denoting if the id should be included or not
"""
d = {
'crypto': self.keystore['crypto'],
'version': self.keystore['version'],
}
if include_address and self.address is not None:
d['address'] = remove_0x_prefix(encode_hex(self.address))
if include_id and self.uuid is not None:
d['id'] = self.uuid
return json.dumps(d) | python | def dump(self, include_address=True, include_id=True) -> str:
d = {
'crypto': self.keystore['crypto'],
'version': self.keystore['version'],
}
if include_address and self.address is not None:
d['address'] = remove_0x_prefix(encode_hex(self.address))
if include_id and self.uuid is not None:
d['id'] = self.uuid
return json.dumps(d) | [
"def",
"dump",
"(",
"self",
",",
"include_address",
"=",
"True",
",",
"include_id",
"=",
"True",
")",
"->",
"str",
":",
"d",
"=",
"{",
"'crypto'",
":",
"self",
".",
"keystore",
"[",
"'crypto'",
"]",
",",
"'version'",
":",
"self",
".",
"keystore",
"["... | Dump the keystore for later disk storage.
The result inherits the entries `'crypto'` and `'version`' from `account.keystore`, and
adds `'address'` and `'id'` in accordance with the parameters `'include_address'` and
`'include_id`'.
If address or id are not known, they are not added, even if requested.
Args:
include_address: flag denoting if the address should be included or not
include_id: flag denoting if the id should be included or not | [
"Dump",
"the",
"keystore",
"for",
"later",
"disk",
"storage",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/accounts.py#L199-L220 |
235,324 | raiden-network/raiden | raiden/accounts.py | Account.unlock | def unlock(self, password: str):
"""Unlock the account with a password.
If the account is already unlocked, nothing happens, even if the password is wrong.
Raises:
ValueError: (originating in ethereum.keys) if the password is wrong
(and the account is locked)
"""
if self.locked:
self._privkey = decode_keyfile_json(self.keystore, password.encode('UTF-8'))
self.locked = False
# get address such that it stays accessible after a subsequent lock
self._fill_address() | python | def unlock(self, password: str):
if self.locked:
self._privkey = decode_keyfile_json(self.keystore, password.encode('UTF-8'))
self.locked = False
# get address such that it stays accessible after a subsequent lock
self._fill_address() | [
"def",
"unlock",
"(",
"self",
",",
"password",
":",
"str",
")",
":",
"if",
"self",
".",
"locked",
":",
"self",
".",
"_privkey",
"=",
"decode_keyfile_json",
"(",
"self",
".",
"keystore",
",",
"password",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
"self",
... | Unlock the account with a password.
If the account is already unlocked, nothing happens, even if the password is wrong.
Raises:
ValueError: (originating in ethereum.keys) if the password is wrong
(and the account is locked) | [
"Unlock",
"the",
"account",
"with",
"a",
"password",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/accounts.py#L222-L235 |
235,325 | raiden-network/raiden | raiden/accounts.py | Account.uuid | def uuid(self, value):
"""Set the UUID. Set it to `None` in order to remove it."""
if value is not None:
self.keystore['id'] = value
elif 'id' in self.keystore:
self.keystore.pop('id') | python | def uuid(self, value):
if value is not None:
self.keystore['id'] = value
elif 'id' in self.keystore:
self.keystore.pop('id') | [
"def",
"uuid",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"keystore",
"[",
"'id'",
"]",
"=",
"value",
"elif",
"'id'",
"in",
"self",
".",
"keystore",
":",
"self",
".",
"keystore",
".",
"pop",
"(",
"'... | Set the UUID. Set it to `None` in order to remove it. | [
"Set",
"the",
"UUID",
".",
"Set",
"it",
"to",
"None",
"in",
"order",
"to",
"remove",
"it",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/accounts.py#L289-L294 |
235,326 | raiden-network/raiden | raiden/storage/migrations/v21_to_v22.py | recover_chain_id | def recover_chain_id(storage: SQLiteStorage) -> ChainID:
"""We can reasonably assume, that any database has only one value for `chain_id` at this point
in time.
"""
action_init_chain = json.loads(storage.get_state_changes(limit=1, offset=0)[0])
assert action_init_chain['_type'] == 'raiden.transfer.state_change.ActionInitChain'
return action_init_chain['chain_id'] | python | def recover_chain_id(storage: SQLiteStorage) -> ChainID:
action_init_chain = json.loads(storage.get_state_changes(limit=1, offset=0)[0])
assert action_init_chain['_type'] == 'raiden.transfer.state_change.ActionInitChain'
return action_init_chain['chain_id'] | [
"def",
"recover_chain_id",
"(",
"storage",
":",
"SQLiteStorage",
")",
"->",
"ChainID",
":",
"action_init_chain",
"=",
"json",
".",
"loads",
"(",
"storage",
".",
"get_state_changes",
"(",
"limit",
"=",
"1",
",",
"offset",
"=",
"0",
")",
"[",
"0",
"]",
")"... | We can reasonably assume, that any database has only one value for `chain_id` at this point
in time. | [
"We",
"can",
"reasonably",
"assume",
"that",
"any",
"database",
"has",
"only",
"one",
"value",
"for",
"chain_id",
"at",
"this",
"point",
"in",
"time",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v21_to_v22.py#L366-L373 |
235,327 | raiden-network/raiden | tools/scenario-player/scenario_player/runner.py | ScenarioRunner.determine_run_number | def determine_run_number(self) -> int:
"""Determine the current run number.
We check for a run number file, and use any number that is logged
there after incrementing it.
"""
run_number = 0
run_number_file = self.data_path.joinpath('run_number.txt')
if run_number_file.exists():
run_number = int(run_number_file.read_text()) + 1
run_number_file.write_text(str(run_number))
log.info('Run number', run_number=run_number)
return run_number | python | def determine_run_number(self) -> int:
run_number = 0
run_number_file = self.data_path.joinpath('run_number.txt')
if run_number_file.exists():
run_number = int(run_number_file.read_text()) + 1
run_number_file.write_text(str(run_number))
log.info('Run number', run_number=run_number)
return run_number | [
"def",
"determine_run_number",
"(",
"self",
")",
"->",
"int",
":",
"run_number",
"=",
"0",
"run_number_file",
"=",
"self",
".",
"data_path",
".",
"joinpath",
"(",
"'run_number.txt'",
")",
"if",
"run_number_file",
".",
"exists",
"(",
")",
":",
"run_number",
"... | Determine the current run number.
We check for a run number file, and use any number that is logged
there after incrementing it. | [
"Determine",
"the",
"current",
"run",
"number",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/runner.py#L125-L137 |
235,328 | raiden-network/raiden | tools/scenario-player/scenario_player/runner.py | ScenarioRunner.select_chain | def select_chain(self, chain_urls: Dict[str, List[str]]) -> Tuple[str, List[str]]:
"""Select a chain and return its name and RPC URL.
If the currently loaded scenario's designated chain is set to 'any',
we randomly select a chain from the given `chain_urls`.
Otherwise, we will return `ScenarioRunner.scenario.chain_name` and whatever value
may be associated with this key in `chain_urls`.
:raises ScenarioError:
if ScenarioRunner.scenario.chain_name is not one of `('any', 'Any', 'ANY')`
and it is not a key in `chain_urls`.
"""
chain_name = self.scenario.chain_name
if chain_name in ('any', 'Any', 'ANY'):
chain_name = random.choice(list(chain_urls.keys()))
log.info('Using chain', chain=chain_name)
try:
return chain_name, chain_urls[chain_name]
except KeyError:
raise ScenarioError(
f'The scenario requested chain "{chain_name}" for which no RPC-URL is known.',
) | python | def select_chain(self, chain_urls: Dict[str, List[str]]) -> Tuple[str, List[str]]:
chain_name = self.scenario.chain_name
if chain_name in ('any', 'Any', 'ANY'):
chain_name = random.choice(list(chain_urls.keys()))
log.info('Using chain', chain=chain_name)
try:
return chain_name, chain_urls[chain_name]
except KeyError:
raise ScenarioError(
f'The scenario requested chain "{chain_name}" for which no RPC-URL is known.',
) | [
"def",
"select_chain",
"(",
"self",
",",
"chain_urls",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"Tuple",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"chain_name",
"=",
"self",
".",
"scenario",
".",
"chain_name"... | Select a chain and return its name and RPC URL.
If the currently loaded scenario's designated chain is set to 'any',
we randomly select a chain from the given `chain_urls`.
Otherwise, we will return `ScenarioRunner.scenario.chain_name` and whatever value
may be associated with this key in `chain_urls`.
:raises ScenarioError:
if ScenarioRunner.scenario.chain_name is not one of `('any', 'Any', 'ANY')`
and it is not a key in `chain_urls`. | [
"Select",
"a",
"chain",
"and",
"return",
"its",
"name",
"and",
"RPC",
"URL",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/runner.py#L139-L161 |
235,329 | raiden-network/raiden | raiden/transfer/balance_proof.py | pack_balance_proof | def pack_balance_proof(
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
canonical_identifier: CanonicalIdentifier,
msg_type: MessageTypeId = MessageTypeId.BALANCE_PROOF,
) -> bytes:
"""Packs balance proof data to be signed
Packs the given arguments in a byte array in the same configuration the
contracts expect the signed data to have.
"""
return pack_data([
'address',
'uint256',
'uint256',
'uint256',
'bytes32',
'uint256',
'bytes32',
], [
canonical_identifier.token_network_address,
canonical_identifier.chain_identifier,
msg_type,
canonical_identifier.channel_identifier,
balance_hash,
nonce,
additional_hash,
]) | python | def pack_balance_proof(
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
canonical_identifier: CanonicalIdentifier,
msg_type: MessageTypeId = MessageTypeId.BALANCE_PROOF,
) -> bytes:
return pack_data([
'address',
'uint256',
'uint256',
'uint256',
'bytes32',
'uint256',
'bytes32',
], [
canonical_identifier.token_network_address,
canonical_identifier.chain_identifier,
msg_type,
canonical_identifier.channel_identifier,
balance_hash,
nonce,
additional_hash,
]) | [
"def",
"pack_balance_proof",
"(",
"nonce",
":",
"Nonce",
",",
"balance_hash",
":",
"BalanceHash",
",",
"additional_hash",
":",
"AdditionalHash",
",",
"canonical_identifier",
":",
"CanonicalIdentifier",
",",
"msg_type",
":",
"MessageTypeId",
"=",
"MessageTypeId",
".",
... | Packs balance proof data to be signed
Packs the given arguments in a byte array in the same configuration the
contracts expect the signed data to have. | [
"Packs",
"balance",
"proof",
"data",
"to",
"be",
"signed"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/balance_proof.py#L7-L35 |
235,330 | raiden-network/raiden | raiden/transfer/balance_proof.py | pack_balance_proof_update | def pack_balance_proof_update(
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
canonical_identifier: CanonicalIdentifier,
partner_signature: Signature,
) -> bytes:
"""Packs balance proof data to be signed for updateNonClosingBalanceProof
Packs the given arguments in a byte array in the same configuration the
contracts expect the signed data for updateNonClosingBalanceProof to have.
"""
return pack_balance_proof(
nonce=nonce,
balance_hash=balance_hash,
additional_hash=additional_hash,
canonical_identifier=canonical_identifier,
msg_type=MessageTypeId.BALANCE_PROOF_UPDATE,
) + partner_signature | python | def pack_balance_proof_update(
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
canonical_identifier: CanonicalIdentifier,
partner_signature: Signature,
) -> bytes:
return pack_balance_proof(
nonce=nonce,
balance_hash=balance_hash,
additional_hash=additional_hash,
canonical_identifier=canonical_identifier,
msg_type=MessageTypeId.BALANCE_PROOF_UPDATE,
) + partner_signature | [
"def",
"pack_balance_proof_update",
"(",
"nonce",
":",
"Nonce",
",",
"balance_hash",
":",
"BalanceHash",
",",
"additional_hash",
":",
"AdditionalHash",
",",
"canonical_identifier",
":",
"CanonicalIdentifier",
",",
"partner_signature",
":",
"Signature",
",",
")",
"->",... | Packs balance proof data to be signed for updateNonClosingBalanceProof
Packs the given arguments in a byte array in the same configuration the
contracts expect the signed data for updateNonClosingBalanceProof to have. | [
"Packs",
"balance",
"proof",
"data",
"to",
"be",
"signed",
"for",
"updateNonClosingBalanceProof"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/balance_proof.py#L38-L56 |
235,331 | raiden-network/raiden | raiden/network/transport/udp/healthcheck.py | healthcheck | def healthcheck(
transport: 'UDPTransport',
recipient: Address,
stop_event: Event,
event_healthy: Event,
event_unhealthy: Event,
nat_keepalive_retries: int,
nat_keepalive_timeout: int,
nat_invitation_timeout: int,
ping_nonce: Dict[str, Nonce],
):
""" Sends a periodical Ping to `recipient` to check its health. """
# pylint: disable=too-many-branches
log.debug(
'starting healthcheck for',
node=pex(transport.address),
to=pex(recipient),
)
# The state of the node is unknown, the events are set to allow the tasks
# to do work.
last_state = NODE_NETWORK_UNKNOWN
transport.set_node_network_state(
recipient,
last_state,
)
# Always call `clear` before `set`, since only `set` does context-switches
# it's easier to reason about tasks that are waiting on both events.
# Wait for the end-point registration or for the node to quit
try:
transport.get_host_port(recipient)
except UnknownAddress:
log.debug(
'waiting for endpoint registration',
node=pex(transport.address),
to=pex(recipient),
)
event_healthy.clear()
event_unhealthy.set()
backoff = udp_utils.timeout_exponential_backoff(
nat_keepalive_retries,
nat_keepalive_timeout,
nat_invitation_timeout,
)
sleep = next(backoff)
while not stop_event.wait(sleep):
try:
transport.get_host_port(recipient)
except UnknownAddress:
sleep = next(backoff)
else:
break
# Don't wait to send the first Ping and to start sending messages if the
# endpoint is known
sleep = 0
event_unhealthy.clear()
event_healthy.set()
while not stop_event.wait(sleep):
sleep = nat_keepalive_timeout
ping_nonce['nonce'] = Nonce(ping_nonce['nonce'] + 1)
messagedata = transport.get_ping(ping_nonce['nonce'])
message_id = ('ping', ping_nonce['nonce'], recipient)
# Send Ping a few times before setting the node as unreachable
acknowledged = udp_utils.retry(
transport,
messagedata,
message_id,
recipient,
stop_event,
[nat_keepalive_timeout] * nat_keepalive_retries,
)
if stop_event.is_set():
return
if not acknowledged:
log.debug(
'node is unresponsive',
node=pex(transport.address),
to=pex(recipient),
current_state=last_state,
new_state=NODE_NETWORK_UNREACHABLE,
retries=nat_keepalive_retries,
timeout=nat_keepalive_timeout,
)
# The node is not healthy, clear the event to stop all queue
# tasks
last_state = NODE_NETWORK_UNREACHABLE
transport.set_node_network_state(
recipient,
last_state,
)
event_healthy.clear()
event_unhealthy.set()
# Retry until recovery, used for:
# - Checking node status.
# - Nat punching.
acknowledged = udp_utils.retry(
transport,
messagedata,
message_id,
recipient,
stop_event,
repeat(nat_invitation_timeout),
)
if acknowledged:
current_state = views.get_node_network_status(
views.state_from_raiden(transport.raiden),
recipient,
)
if last_state != NODE_NETWORK_REACHABLE:
log.debug(
'node answered',
node=pex(transport.raiden.address),
to=pex(recipient),
current_state=current_state,
new_state=NODE_NETWORK_REACHABLE,
)
last_state = NODE_NETWORK_REACHABLE
transport.set_node_network_state(
recipient,
last_state,
)
event_unhealthy.clear()
event_healthy.set() | python | def healthcheck(
transport: 'UDPTransport',
recipient: Address,
stop_event: Event,
event_healthy: Event,
event_unhealthy: Event,
nat_keepalive_retries: int,
nat_keepalive_timeout: int,
nat_invitation_timeout: int,
ping_nonce: Dict[str, Nonce],
):
# pylint: disable=too-many-branches
log.debug(
'starting healthcheck for',
node=pex(transport.address),
to=pex(recipient),
)
# The state of the node is unknown, the events are set to allow the tasks
# to do work.
last_state = NODE_NETWORK_UNKNOWN
transport.set_node_network_state(
recipient,
last_state,
)
# Always call `clear` before `set`, since only `set` does context-switches
# it's easier to reason about tasks that are waiting on both events.
# Wait for the end-point registration or for the node to quit
try:
transport.get_host_port(recipient)
except UnknownAddress:
log.debug(
'waiting for endpoint registration',
node=pex(transport.address),
to=pex(recipient),
)
event_healthy.clear()
event_unhealthy.set()
backoff = udp_utils.timeout_exponential_backoff(
nat_keepalive_retries,
nat_keepalive_timeout,
nat_invitation_timeout,
)
sleep = next(backoff)
while not stop_event.wait(sleep):
try:
transport.get_host_port(recipient)
except UnknownAddress:
sleep = next(backoff)
else:
break
# Don't wait to send the first Ping and to start sending messages if the
# endpoint is known
sleep = 0
event_unhealthy.clear()
event_healthy.set()
while not stop_event.wait(sleep):
sleep = nat_keepalive_timeout
ping_nonce['nonce'] = Nonce(ping_nonce['nonce'] + 1)
messagedata = transport.get_ping(ping_nonce['nonce'])
message_id = ('ping', ping_nonce['nonce'], recipient)
# Send Ping a few times before setting the node as unreachable
acknowledged = udp_utils.retry(
transport,
messagedata,
message_id,
recipient,
stop_event,
[nat_keepalive_timeout] * nat_keepalive_retries,
)
if stop_event.is_set():
return
if not acknowledged:
log.debug(
'node is unresponsive',
node=pex(transport.address),
to=pex(recipient),
current_state=last_state,
new_state=NODE_NETWORK_UNREACHABLE,
retries=nat_keepalive_retries,
timeout=nat_keepalive_timeout,
)
# The node is not healthy, clear the event to stop all queue
# tasks
last_state = NODE_NETWORK_UNREACHABLE
transport.set_node_network_state(
recipient,
last_state,
)
event_healthy.clear()
event_unhealthy.set()
# Retry until recovery, used for:
# - Checking node status.
# - Nat punching.
acknowledged = udp_utils.retry(
transport,
messagedata,
message_id,
recipient,
stop_event,
repeat(nat_invitation_timeout),
)
if acknowledged:
current_state = views.get_node_network_status(
views.state_from_raiden(transport.raiden),
recipient,
)
if last_state != NODE_NETWORK_REACHABLE:
log.debug(
'node answered',
node=pex(transport.raiden.address),
to=pex(recipient),
current_state=current_state,
new_state=NODE_NETWORK_REACHABLE,
)
last_state = NODE_NETWORK_REACHABLE
transport.set_node_network_state(
recipient,
last_state,
)
event_unhealthy.clear()
event_healthy.set() | [
"def",
"healthcheck",
"(",
"transport",
":",
"'UDPTransport'",
",",
"recipient",
":",
"Address",
",",
"stop_event",
":",
"Event",
",",
"event_healthy",
":",
"Event",
",",
"event_unhealthy",
":",
"Event",
",",
"nat_keepalive_retries",
":",
"int",
",",
"nat_keepal... | Sends a periodical Ping to `recipient` to check its health. | [
"Sends",
"a",
"periodical",
"Ping",
"to",
"recipient",
"to",
"check",
"its",
"health",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/healthcheck.py#L32-L171 |
235,332 | raiden-network/raiden | raiden/network/proxies/token_network_registry.py | TokenNetworkRegistry.get_token_network | def get_token_network(
self,
token_address: TokenAddress,
block_identifier: BlockSpecification = 'latest',
) -> Optional[Address]:
""" Return the token network address for the given token or None if
there is no correspoding address.
"""
if not isinstance(token_address, T_TargetAddress):
raise ValueError('token_address must be an address')
address = self.proxy.contract.functions.token_to_token_networks(
to_checksum_address(token_address),
).call(block_identifier=block_identifier)
address = to_canonical_address(address)
if is_same_address(address, NULL_ADDRESS):
return None
return address | python | def get_token_network(
self,
token_address: TokenAddress,
block_identifier: BlockSpecification = 'latest',
) -> Optional[Address]:
if not isinstance(token_address, T_TargetAddress):
raise ValueError('token_address must be an address')
address = self.proxy.contract.functions.token_to_token_networks(
to_checksum_address(token_address),
).call(block_identifier=block_identifier)
address = to_canonical_address(address)
if is_same_address(address, NULL_ADDRESS):
return None
return address | [
"def",
"get_token_network",
"(",
"self",
",",
"token_address",
":",
"TokenAddress",
",",
"block_identifier",
":",
"BlockSpecification",
"=",
"'latest'",
",",
")",
"->",
"Optional",
"[",
"Address",
"]",
":",
"if",
"not",
"isinstance",
"(",
"token_address",
",",
... | Return the token network address for the given token or None if
there is no correspoding address. | [
"Return",
"the",
"token",
"network",
"address",
"for",
"the",
"given",
"token",
"or",
"None",
"if",
"there",
"is",
"no",
"correspoding",
"address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network_registry.py#L79-L98 |
235,333 | raiden-network/raiden | raiden/network/proxies/token_network_registry.py | TokenNetworkRegistry.add_token_with_limits | def add_token_with_limits(
self,
token_address: TokenAddress,
channel_participant_deposit_limit: TokenAmount,
token_network_deposit_limit: TokenAmount,
) -> Address:
"""
Register token of `token_address` with the token network.
The limits apply for version 0.13.0 and above of raiden-contracts,
since instantiation also takes the limits as constructor arguments.
"""
return self._add_token(
token_address=token_address,
additional_arguments={
'_channel_participant_deposit_limit': channel_participant_deposit_limit,
'_token_network_deposit_limit': token_network_deposit_limit,
},
) | python | def add_token_with_limits(
self,
token_address: TokenAddress,
channel_participant_deposit_limit: TokenAmount,
token_network_deposit_limit: TokenAmount,
) -> Address:
return self._add_token(
token_address=token_address,
additional_arguments={
'_channel_participant_deposit_limit': channel_participant_deposit_limit,
'_token_network_deposit_limit': token_network_deposit_limit,
},
) | [
"def",
"add_token_with_limits",
"(",
"self",
",",
"token_address",
":",
"TokenAddress",
",",
"channel_participant_deposit_limit",
":",
"TokenAmount",
",",
"token_network_deposit_limit",
":",
"TokenAmount",
",",
")",
"->",
"Address",
":",
"return",
"self",
".",
"_add_t... | Register token of `token_address` with the token network.
The limits apply for version 0.13.0 and above of raiden-contracts,
since instantiation also takes the limits as constructor arguments. | [
"Register",
"token",
"of",
"token_address",
"with",
"the",
"token",
"network",
".",
"The",
"limits",
"apply",
"for",
"version",
"0",
".",
"13",
".",
"0",
"and",
"above",
"of",
"raiden",
"-",
"contracts",
"since",
"instantiation",
"also",
"takes",
"the",
"l... | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network_registry.py#L100-L117 |
235,334 | raiden-network/raiden | raiden/network/proxies/token_network_registry.py | TokenNetworkRegistry.add_token_without_limits | def add_token_without_limits(
self,
token_address: TokenAddress,
) -> Address:
"""
Register token of `token_address` with the token network.
This applies for versions prior to 0.13.0 of raiden-contracts,
since limits were hardcoded into the TokenNetwork contract.
"""
return self._add_token(
token_address=token_address,
additional_arguments=dict(),
) | python | def add_token_without_limits(
self,
token_address: TokenAddress,
) -> Address:
return self._add_token(
token_address=token_address,
additional_arguments=dict(),
) | [
"def",
"add_token_without_limits",
"(",
"self",
",",
"token_address",
":",
"TokenAddress",
",",
")",
"->",
"Address",
":",
"return",
"self",
".",
"_add_token",
"(",
"token_address",
"=",
"token_address",
",",
"additional_arguments",
"=",
"dict",
"(",
")",
",",
... | Register token of `token_address` with the token network.
This applies for versions prior to 0.13.0 of raiden-contracts,
since limits were hardcoded into the TokenNetwork contract. | [
"Register",
"token",
"of",
"token_address",
"with",
"the",
"token",
"network",
".",
"This",
"applies",
"for",
"versions",
"prior",
"to",
"0",
".",
"13",
".",
"0",
"of",
"raiden",
"-",
"contracts",
"since",
"limits",
"were",
"hardcoded",
"into",
"the",
"Tok... | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network_registry.py#L119-L131 |
235,335 | raiden-network/raiden | raiden/network/utils.py | get_free_port | def get_free_port(
initial_port: int = 0,
socket_kind: SocketKind = SocketKind.SOCK_STREAM,
reliable: bool = True,
):
"""
Find an unused TCP port.
Unless the `reliable` parameter is set to `True` (the default) this is prone to race
conditions - some other process may grab the port before the caller of this function has
a chance to use it.
When using `reliable` the port is forced into TIME_WAIT mode, ensuring that it will not be
considered 'free' by the OS for the next 60 seconds. This does however require that the
process using the port sets SO_REUSEADDR on it's sockets. Most 'server' applications do.
If `initial_port` is passed the function will try to find a port as close as possible.
Otherwise a random port is chosen by the OS.
Returns an iterator that will return unused port numbers.
"""
def _port_generator():
if initial_port == 0:
next_port = repeat(0)
else:
next_port = count(start=initial_port)
for port_candidate in next_port:
# Don't inline the variable until https://github.com/PyCQA/pylint/issues/1437 is fixed
sock = socket.socket(socket.AF_INET, socket_kind)
with closing(sock):
if reliable:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind(('127.0.0.1', port_candidate))
except OSError as ex:
if ex.errno == errno.EADDRINUSE:
continue
sock_addr = sock.getsockname()
port = sock_addr[1]
if reliable:
# Connect to the socket to force it into TIME_WAIT state
sock.listen(1)
# see above
sock2 = socket.socket(socket.AF_INET, socket_kind)
with closing(sock2):
sock2.connect(sock_addr)
sock.accept()
yield port
return _port_generator() | python | def get_free_port(
initial_port: int = 0,
socket_kind: SocketKind = SocketKind.SOCK_STREAM,
reliable: bool = True,
):
def _port_generator():
if initial_port == 0:
next_port = repeat(0)
else:
next_port = count(start=initial_port)
for port_candidate in next_port:
# Don't inline the variable until https://github.com/PyCQA/pylint/issues/1437 is fixed
sock = socket.socket(socket.AF_INET, socket_kind)
with closing(sock):
if reliable:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind(('127.0.0.1', port_candidate))
except OSError as ex:
if ex.errno == errno.EADDRINUSE:
continue
sock_addr = sock.getsockname()
port = sock_addr[1]
if reliable:
# Connect to the socket to force it into TIME_WAIT state
sock.listen(1)
# see above
sock2 = socket.socket(socket.AF_INET, socket_kind)
with closing(sock2):
sock2.connect(sock_addr)
sock.accept()
yield port
return _port_generator() | [
"def",
"get_free_port",
"(",
"initial_port",
":",
"int",
"=",
"0",
",",
"socket_kind",
":",
"SocketKind",
"=",
"SocketKind",
".",
"SOCK_STREAM",
",",
"reliable",
":",
"bool",
"=",
"True",
",",
")",
":",
"def",
"_port_generator",
"(",
")",
":",
"if",
"ini... | Find an unused TCP port.
Unless the `reliable` parameter is set to `True` (the default) this is prone to race
conditions - some other process may grab the port before the caller of this function has
a chance to use it.
When using `reliable` the port is forced into TIME_WAIT mode, ensuring that it will not be
considered 'free' by the OS for the next 60 seconds. This does however require that the
process using the port sets SO_REUSEADDR on it's sockets. Most 'server' applications do.
If `initial_port` is passed the function will try to find a port as close as possible.
Otherwise a random port is chosen by the OS.
Returns an iterator that will return unused port numbers. | [
"Find",
"an",
"unused",
"TCP",
"port",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/utils.py#L13-L64 |
235,336 | raiden-network/raiden | raiden/network/utils.py | get_http_rtt | def get_http_rtt(
url: str,
samples: int = 3,
method: str = 'head',
timeout: int = 1,
) -> Optional[float]:
"""
Determine the average HTTP RTT to `url` over the number of `samples`.
Returns `None` if the server is unreachable.
"""
durations = []
for _ in range(samples):
try:
durations.append(
requests.request(method, url, timeout=timeout).elapsed.total_seconds(),
)
except (RequestException, OSError):
return None
except Exception as ex:
print(ex)
return None
# Slight delay to avoid overloading
sleep(.125)
return sum(durations) / samples | python | def get_http_rtt(
url: str,
samples: int = 3,
method: str = 'head',
timeout: int = 1,
) -> Optional[float]:
durations = []
for _ in range(samples):
try:
durations.append(
requests.request(method, url, timeout=timeout).elapsed.total_seconds(),
)
except (RequestException, OSError):
return None
except Exception as ex:
print(ex)
return None
# Slight delay to avoid overloading
sleep(.125)
return sum(durations) / samples | [
"def",
"get_http_rtt",
"(",
"url",
":",
"str",
",",
"samples",
":",
"int",
"=",
"3",
",",
"method",
":",
"str",
"=",
"'head'",
",",
"timeout",
":",
"int",
"=",
"1",
",",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"durations",
"=",
"[",
"]",
... | Determine the average HTTP RTT to `url` over the number of `samples`.
Returns `None` if the server is unreachable. | [
"Determine",
"the",
"average",
"HTTP",
"RTT",
"to",
"url",
"over",
"the",
"number",
"of",
"samples",
".",
"Returns",
"None",
"if",
"the",
"server",
"is",
"unreachable",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/utils.py#L67-L90 |
235,337 | raiden-network/raiden | raiden/storage/migrations/v18_to_v19.py | _add_blockhash_to_state_changes | def _add_blockhash_to_state_changes(storage: SQLiteStorage, cache: BlockHashCache) -> None:
"""Adds blockhash to ContractReceiveXXX and ActionInitChain state changes"""
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.state_change.ContractReceive%'),
('_type', 'raiden.transfer.state_change.ActionInitChain'),
],
logical_and=False,
)
for state_changes_batch in batch_query:
# Gather query records to pass to gevent pool imap to have concurrent RPC calls
query_records = []
for state_change in state_changes_batch:
data = json.loads(state_change.data)
assert 'block_hash' not in data, 'v18 state changes cant contain blockhash'
record = BlockQueryAndUpdateRecord(
block_number=int(data['block_number']),
data=data,
state_change_identifier=state_change.state_change_identifier,
cache=cache,
)
query_records.append(record)
# Now perform the queries in parallel with gevent.Pool.imap and gather the
# updated tuple entries that will update the DB
updated_state_changes = []
pool_generator = Pool(batch_size).imap(
_query_blocknumber_and_update_statechange_data,
query_records,
)
for entry in pool_generator:
updated_state_changes.append(entry)
# Finally update the DB with a batched executemany()
storage.update_state_changes(updated_state_changes) | python | def _add_blockhash_to_state_changes(storage: SQLiteStorage, cache: BlockHashCache) -> None:
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.state_change.ContractReceive%'),
('_type', 'raiden.transfer.state_change.ActionInitChain'),
],
logical_and=False,
)
for state_changes_batch in batch_query:
# Gather query records to pass to gevent pool imap to have concurrent RPC calls
query_records = []
for state_change in state_changes_batch:
data = json.loads(state_change.data)
assert 'block_hash' not in data, 'v18 state changes cant contain blockhash'
record = BlockQueryAndUpdateRecord(
block_number=int(data['block_number']),
data=data,
state_change_identifier=state_change.state_change_identifier,
cache=cache,
)
query_records.append(record)
# Now perform the queries in parallel with gevent.Pool.imap and gather the
# updated tuple entries that will update the DB
updated_state_changes = []
pool_generator = Pool(batch_size).imap(
_query_blocknumber_and_update_statechange_data,
query_records,
)
for entry in pool_generator:
updated_state_changes.append(entry)
# Finally update the DB with a batched executemany()
storage.update_state_changes(updated_state_changes) | [
"def",
"_add_blockhash_to_state_changes",
"(",
"storage",
":",
"SQLiteStorage",
",",
"cache",
":",
"BlockHashCache",
")",
"->",
"None",
":",
"batch_size",
"=",
"50",
"batch_query",
"=",
"storage",
".",
"batch_query_state_changes",
"(",
"batch_size",
"=",
"batch_size... | Adds blockhash to ContractReceiveXXX and ActionInitChain state changes | [
"Adds",
"blockhash",
"to",
"ContractReceiveXXX",
"and",
"ActionInitChain",
"state",
"changes"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v18_to_v19.py#L53-L90 |
235,338 | raiden-network/raiden | raiden/storage/migrations/v18_to_v19.py | _add_blockhash_to_events | def _add_blockhash_to_events(storage: SQLiteStorage, cache: BlockHashCache) -> None:
"""Adds blockhash to all ContractSendXXX events"""
batch_query = storage.batch_query_event_records(
batch_size=500,
filters=[('_type', 'raiden.transfer.events.ContractSend%')],
)
for events_batch in batch_query:
updated_events = []
for event in events_batch:
data = json.loads(event.data)
assert 'triggered_by_block_hash' not in data, 'v18 events cant contain blockhash'
# Get the state_change that triggered the event and get its hash
matched_state_changes = storage.get_statechanges_by_identifier(
from_identifier=event.state_change_identifier,
to_identifier=event.state_change_identifier,
)
result_length = len(matched_state_changes)
msg = 'multiple state changes should not exist for the same identifier'
assert result_length == 1, msg
statechange_data = json.loads(matched_state_changes[0])
if 'block_hash' in statechange_data:
data['triggered_by_block_hash'] = statechange_data['block_hash']
elif 'block_number' in statechange_data:
block_number = int(statechange_data['block_number'])
data['triggered_by_block_hash'] = cache.get(block_number)
updated_events.append((
json.dumps(data),
event.event_identifier,
))
storage.update_events(updated_events) | python | def _add_blockhash_to_events(storage: SQLiteStorage, cache: BlockHashCache) -> None:
batch_query = storage.batch_query_event_records(
batch_size=500,
filters=[('_type', 'raiden.transfer.events.ContractSend%')],
)
for events_batch in batch_query:
updated_events = []
for event in events_batch:
data = json.loads(event.data)
assert 'triggered_by_block_hash' not in data, 'v18 events cant contain blockhash'
# Get the state_change that triggered the event and get its hash
matched_state_changes = storage.get_statechanges_by_identifier(
from_identifier=event.state_change_identifier,
to_identifier=event.state_change_identifier,
)
result_length = len(matched_state_changes)
msg = 'multiple state changes should not exist for the same identifier'
assert result_length == 1, msg
statechange_data = json.loads(matched_state_changes[0])
if 'block_hash' in statechange_data:
data['triggered_by_block_hash'] = statechange_data['block_hash']
elif 'block_number' in statechange_data:
block_number = int(statechange_data['block_number'])
data['triggered_by_block_hash'] = cache.get(block_number)
updated_events.append((
json.dumps(data),
event.event_identifier,
))
storage.update_events(updated_events) | [
"def",
"_add_blockhash_to_events",
"(",
"storage",
":",
"SQLiteStorage",
",",
"cache",
":",
"BlockHashCache",
")",
"->",
"None",
":",
"batch_query",
"=",
"storage",
".",
"batch_query_event_records",
"(",
"batch_size",
"=",
"500",
",",
"filters",
"=",
"[",
"(",
... | Adds blockhash to all ContractSendXXX events | [
"Adds",
"blockhash",
"to",
"all",
"ContractSendXXX",
"events"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v18_to_v19.py#L93-L125 |
235,339 | raiden-network/raiden | raiden/storage/migrations/v18_to_v19.py | _transform_snapshot | def _transform_snapshot(
raw_snapshot: str,
storage: SQLiteStorage,
cache: BlockHashCache,
) -> str:
"""Upgrades a single snapshot by adding the blockhash to it and to any pending transactions"""
snapshot = json.loads(raw_snapshot)
block_number = int(snapshot['block_number'])
snapshot['block_hash'] = cache.get(block_number)
pending_transactions = snapshot['pending_transactions']
new_pending_transactions = []
for transaction_data in pending_transactions:
if 'raiden.transfer.events.ContractSend' not in transaction_data['_type']:
raise InvalidDBData(
"Error during v18 -> v19 upgrade. Chain state's pending transactions "
"should only contain ContractSend transactions",
)
# For each pending transaction find the corresponding DB event record.
event_record = storage.get_latest_event_by_data_field(
filters=transaction_data,
)
if not event_record.data:
raise InvalidDBData(
'Error during v18 -> v19 upgrade. Could not find a database event '
'table entry for a pending transaction.',
)
event_record_data = json.loads(event_record.data)
transaction_data['triggered_by_block_hash'] = event_record_data['triggered_by_block_hash']
new_pending_transactions.append(transaction_data)
snapshot['pending_transactions'] = new_pending_transactions
return json.dumps(snapshot) | python | def _transform_snapshot(
raw_snapshot: str,
storage: SQLiteStorage,
cache: BlockHashCache,
) -> str:
snapshot = json.loads(raw_snapshot)
block_number = int(snapshot['block_number'])
snapshot['block_hash'] = cache.get(block_number)
pending_transactions = snapshot['pending_transactions']
new_pending_transactions = []
for transaction_data in pending_transactions:
if 'raiden.transfer.events.ContractSend' not in transaction_data['_type']:
raise InvalidDBData(
"Error during v18 -> v19 upgrade. Chain state's pending transactions "
"should only contain ContractSend transactions",
)
# For each pending transaction find the corresponding DB event record.
event_record = storage.get_latest_event_by_data_field(
filters=transaction_data,
)
if not event_record.data:
raise InvalidDBData(
'Error during v18 -> v19 upgrade. Could not find a database event '
'table entry for a pending transaction.',
)
event_record_data = json.loads(event_record.data)
transaction_data['triggered_by_block_hash'] = event_record_data['triggered_by_block_hash']
new_pending_transactions.append(transaction_data)
snapshot['pending_transactions'] = new_pending_transactions
return json.dumps(snapshot) | [
"def",
"_transform_snapshot",
"(",
"raw_snapshot",
":",
"str",
",",
"storage",
":",
"SQLiteStorage",
",",
"cache",
":",
"BlockHashCache",
",",
")",
"->",
"str",
":",
"snapshot",
"=",
"json",
".",
"loads",
"(",
"raw_snapshot",
")",
"block_number",
"=",
"int",... | Upgrades a single snapshot by adding the blockhash to it and to any pending transactions | [
"Upgrades",
"a",
"single",
"snapshot",
"by",
"adding",
"the",
"blockhash",
"to",
"it",
"and",
"to",
"any",
"pending",
"transactions"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v18_to_v19.py#L128-L162 |
235,340 | raiden-network/raiden | raiden/storage/migrations/v18_to_v19.py | _transform_snapshots_for_blockhash | def _transform_snapshots_for_blockhash(storage: SQLiteStorage, cache: BlockHashCache) -> None:
"""Upgrades the snapshots by adding the blockhash to it and to any pending transactions"""
snapshots = storage.get_snapshots()
snapshot_records = [
TransformSnapshotRecord(
data=snapshot.data,
identifier=snapshot.identifier,
storage=storage,
cache=cache,
)
for snapshot in snapshots
]
pool_generator = Pool(len(snapshots)).imap(_do_transform_snapshot, snapshot_records)
updated_snapshots_data = []
for result in pool_generator:
updated_snapshots_data.append(result)
storage.update_snapshots(updated_snapshots_data) | python | def _transform_snapshots_for_blockhash(storage: SQLiteStorage, cache: BlockHashCache) -> None:
snapshots = storage.get_snapshots()
snapshot_records = [
TransformSnapshotRecord(
data=snapshot.data,
identifier=snapshot.identifier,
storage=storage,
cache=cache,
)
for snapshot in snapshots
]
pool_generator = Pool(len(snapshots)).imap(_do_transform_snapshot, snapshot_records)
updated_snapshots_data = []
for result in pool_generator:
updated_snapshots_data.append(result)
storage.update_snapshots(updated_snapshots_data) | [
"def",
"_transform_snapshots_for_blockhash",
"(",
"storage",
":",
"SQLiteStorage",
",",
"cache",
":",
"BlockHashCache",
")",
"->",
"None",
":",
"snapshots",
"=",
"storage",
".",
"get_snapshots",
"(",
")",
"snapshot_records",
"=",
"[",
"TransformSnapshotRecord",
"(",... | Upgrades the snapshots by adding the blockhash to it and to any pending transactions | [
"Upgrades",
"the",
"snapshots",
"by",
"adding",
"the",
"blockhash",
"to",
"it",
"and",
"to",
"any",
"pending",
"transactions"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v18_to_v19.py#L181-L201 |
235,341 | raiden-network/raiden | raiden/storage/migrations/v18_to_v19.py | BlockHashCache.get | def get(self, block_number: BlockNumber) -> str:
"""Given a block number returns the hex representation of the blockhash"""
if block_number in self.mapping:
return self.mapping[block_number]
block_hash = self.web3.eth.getBlock(block_number)['hash']
block_hash = block_hash.hex()
self.mapping[block_number] = block_hash
return block_hash | python | def get(self, block_number: BlockNumber) -> str:
if block_number in self.mapping:
return self.mapping[block_number]
block_hash = self.web3.eth.getBlock(block_number)['hash']
block_hash = block_hash.hex()
self.mapping[block_number] = block_hash
return block_hash | [
"def",
"get",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
")",
"->",
"str",
":",
"if",
"block_number",
"in",
"self",
".",
"mapping",
":",
"return",
"self",
".",
"mapping",
"[",
"block_number",
"]",
"block_hash",
"=",
"self",
".",
"web3",
".",
... | Given a block number returns the hex representation of the blockhash | [
"Given",
"a",
"block",
"number",
"returns",
"the",
"hex",
"representation",
"of",
"the",
"blockhash"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v18_to_v19.py#L27-L35 |
235,342 | raiden-network/raiden | raiden/utils/gas_reserve.py | has_enough_gas_reserve | def has_enough_gas_reserve(
raiden,
channels_to_open: int = 0,
) -> Tuple[bool, int]:
""" Checks if the account has enough balance to handle the lifecycles of all
open channels as well as the to be created channels.
Note: This is just an estimation.
Args:
raiden: A raiden service instance
channels_to_open: The number of new channels that should be opened
Returns:
Tuple of a boolean denoting if the account has enough balance for
the remaining lifecycle events and the estimate for the remaining
lifecycle cost
"""
secure_reserve_estimate = get_reserve_estimate(raiden, channels_to_open)
current_account_balance = raiden.chain.client.balance(raiden.chain.client.address)
return secure_reserve_estimate <= current_account_balance, secure_reserve_estimate | python | def has_enough_gas_reserve(
raiden,
channels_to_open: int = 0,
) -> Tuple[bool, int]:
secure_reserve_estimate = get_reserve_estimate(raiden, channels_to_open)
current_account_balance = raiden.chain.client.balance(raiden.chain.client.address)
return secure_reserve_estimate <= current_account_balance, secure_reserve_estimate | [
"def",
"has_enough_gas_reserve",
"(",
"raiden",
",",
"channels_to_open",
":",
"int",
"=",
"0",
",",
")",
"->",
"Tuple",
"[",
"bool",
",",
"int",
"]",
":",
"secure_reserve_estimate",
"=",
"get_reserve_estimate",
"(",
"raiden",
",",
"channels_to_open",
")",
"cur... | Checks if the account has enough balance to handle the lifecycles of all
open channels as well as the to be created channels.
Note: This is just an estimation.
Args:
raiden: A raiden service instance
channels_to_open: The number of new channels that should be opened
Returns:
Tuple of a boolean denoting if the account has enough balance for
the remaining lifecycle events and the estimate for the remaining
lifecycle cost | [
"Checks",
"if",
"the",
"account",
"has",
"enough",
"balance",
"to",
"handle",
"the",
"lifecycles",
"of",
"all",
"open",
"channels",
"as",
"well",
"as",
"the",
"to",
"be",
"created",
"channels",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/gas_reserve.py#L126-L147 |
235,343 | raiden-network/raiden | raiden/transfer/merkle_tree.py | hash_pair | def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256:
""" Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the proof checker. The topological order is used as a
deterministic way of ordering the elements making sure the smart contract
verification and the python code are compatible.
"""
assert first is not None
if second is None:
return first
if first > second:
return sha3(second + first)
return sha3(first + second) | python | def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256:
assert first is not None
if second is None:
return first
if first > second:
return sha3(second + first)
return sha3(first + second) | [
"def",
"hash_pair",
"(",
"first",
":",
"Keccak256",
",",
"second",
":",
"Optional",
"[",
"Keccak256",
"]",
")",
"->",
"Keccak256",
":",
"assert",
"first",
"is",
"not",
"None",
"if",
"second",
"is",
"None",
":",
"return",
"first",
"if",
"first",
">",
"s... | Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the proof checker. The topological order is used as a
deterministic way of ordering the elements making sure the smart contract
verification and the python code are compatible. | [
"Computes",
"the",
"keccak",
"hash",
"of",
"the",
"elements",
"ordered",
"topologically",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L16-L33 |
235,344 | raiden-network/raiden | raiden/transfer/merkle_tree.py | compute_layers | def compute_layers(elements: List[Keccak256]) -> List[List[Keccak256]]:
""" Computes the layers of the merkletree.
First layer is the list of elements and the last layer is a list with a
single entry, the merkleroot.
"""
elements = list(elements) # consume generators
assert elements, 'Use make_empty_merkle_tree if there are no elements'
if not all(isinstance(item, bytes) for item in elements):
raise ValueError('all elements must be bytes')
if any(len(item) != 32 for item in elements):
raise HashLengthNot32()
if len(elements) != len(set(elements)):
raise ValueError('Duplicated element')
leaves = sorted(item for item in elements)
tree = [leaves]
layer = leaves
while len(layer) > 1:
paired_items = split_in_pairs(layer)
layer = [hash_pair(a, b) for a, b in paired_items]
tree.append(layer)
return tree | python | def compute_layers(elements: List[Keccak256]) -> List[List[Keccak256]]:
elements = list(elements) # consume generators
assert elements, 'Use make_empty_merkle_tree if there are no elements'
if not all(isinstance(item, bytes) for item in elements):
raise ValueError('all elements must be bytes')
if any(len(item) != 32 for item in elements):
raise HashLengthNot32()
if len(elements) != len(set(elements)):
raise ValueError('Duplicated element')
leaves = sorted(item for item in elements)
tree = [leaves]
layer = leaves
while len(layer) > 1:
paired_items = split_in_pairs(layer)
layer = [hash_pair(a, b) for a, b in paired_items]
tree.append(layer)
return tree | [
"def",
"compute_layers",
"(",
"elements",
":",
"List",
"[",
"Keccak256",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"Keccak256",
"]",
"]",
":",
"elements",
"=",
"list",
"(",
"elements",
")",
"# consume generators",
"assert",
"elements",
",",
"'Use make_empty_... | Computes the layers of the merkletree.
First layer is the list of elements and the last layer is a list with a
single entry, the merkleroot. | [
"Computes",
"the",
"layers",
"of",
"the",
"merkletree",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L36-L64 |
235,345 | raiden-network/raiden | raiden/transfer/merkle_tree.py | compute_merkleproof_for | def compute_merkleproof_for(merkletree: 'MerkleTreeState', element: Keccak256) -> List[Keccak256]:
""" Containment proof for element.
The proof contains only the entries that are sufficient to recompute the
merkleroot, from the leaf `element` up to `root`.
Raises:
IndexError: If the element is not part of the merkletree.
"""
idx = merkletree.layers[LEAVES].index(element)
proof = []
for layer in merkletree.layers:
if idx % 2:
pair = idx - 1
else:
pair = idx + 1
# with an odd number of elements the rightmost one does not have a pair.
if pair < len(layer):
proof.append(layer[pair])
# the tree is binary and balanced
idx = idx // 2
return proof | python | def compute_merkleproof_for(merkletree: 'MerkleTreeState', element: Keccak256) -> List[Keccak256]:
idx = merkletree.layers[LEAVES].index(element)
proof = []
for layer in merkletree.layers:
if idx % 2:
pair = idx - 1
else:
pair = idx + 1
# with an odd number of elements the rightmost one does not have a pair.
if pair < len(layer):
proof.append(layer[pair])
# the tree is binary and balanced
idx = idx // 2
return proof | [
"def",
"compute_merkleproof_for",
"(",
"merkletree",
":",
"'MerkleTreeState'",
",",
"element",
":",
"Keccak256",
")",
"->",
"List",
"[",
"Keccak256",
"]",
":",
"idx",
"=",
"merkletree",
".",
"layers",
"[",
"LEAVES",
"]",
".",
"index",
"(",
"element",
")",
... | Containment proof for element.
The proof contains only the entries that are sufficient to recompute the
merkleroot, from the leaf `element` up to `root`.
Raises:
IndexError: If the element is not part of the merkletree. | [
"Containment",
"proof",
"for",
"element",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L67-L92 |
235,346 | raiden-network/raiden | raiden/transfer/merkle_tree.py | validate_proof | def validate_proof(proof: List[Keccak256], root: Keccak256, leaf_element: Keccak256) -> bool:
""" Checks that `leaf_element` was contained in the tree represented by
`merkleroot`.
"""
hash_ = leaf_element
for pair in proof:
hash_ = hash_pair(hash_, pair)
return hash_ == root | python | def validate_proof(proof: List[Keccak256], root: Keccak256, leaf_element: Keccak256) -> bool:
hash_ = leaf_element
for pair in proof:
hash_ = hash_pair(hash_, pair)
return hash_ == root | [
"def",
"validate_proof",
"(",
"proof",
":",
"List",
"[",
"Keccak256",
"]",
",",
"root",
":",
"Keccak256",
",",
"leaf_element",
":",
"Keccak256",
")",
"->",
"bool",
":",
"hash_",
"=",
"leaf_element",
"for",
"pair",
"in",
"proof",
":",
"hash_",
"=",
"hash_... | Checks that `leaf_element` was contained in the tree represented by
`merkleroot`. | [
"Checks",
"that",
"leaf_element",
"was",
"contained",
"in",
"the",
"tree",
"represented",
"by",
"merkleroot",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L95-L104 |
235,347 | raiden-network/raiden | raiden/transfer/merkle_tree.py | merkleroot | def merkleroot(merkletree: 'MerkleTreeState') -> Locksroot:
""" Return the root element of the merkle tree. """
assert merkletree.layers, 'the merkle tree layers are empty'
assert merkletree.layers[MERKLEROOT], 'the root layer is empty'
return Locksroot(merkletree.layers[MERKLEROOT][0]) | python | def merkleroot(merkletree: 'MerkleTreeState') -> Locksroot:
assert merkletree.layers, 'the merkle tree layers are empty'
assert merkletree.layers[MERKLEROOT], 'the root layer is empty'
return Locksroot(merkletree.layers[MERKLEROOT][0]) | [
"def",
"merkleroot",
"(",
"merkletree",
":",
"'MerkleTreeState'",
")",
"->",
"Locksroot",
":",
"assert",
"merkletree",
".",
"layers",
",",
"'the merkle tree layers are empty'",
"assert",
"merkletree",
".",
"layers",
"[",
"MERKLEROOT",
"]",
",",
"'the root layer is emp... | Return the root element of the merkle tree. | [
"Return",
"the",
"root",
"element",
"of",
"the",
"merkle",
"tree",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L107-L112 |
235,348 | raiden-network/raiden | raiden/storage/migrations/v19_to_v20.py | _add_onchain_locksroot_to_channel_settled_state_changes | def _add_onchain_locksroot_to_channel_settled_state_changes(
raiden: RaidenService,
storage: SQLiteStorage,
) -> None:
""" Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
ContractReceiveChannelSettled. """
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.state_change.ContractReceiveChannelSettled'),
],
)
for state_changes_batch in batch_query:
updated_state_changes = list()
for state_change in state_changes_batch:
state_change_data = json.loads(state_change.data)
msg = 'v18 state changes cant contain our_onchain_locksroot'
assert 'our_onchain_locksroot' not in state_change_data, msg
msg = 'v18 state changes cant contain partner_onchain_locksroot'
assert 'partner_onchain_locksroot' not in state_change_data, msg
token_network_identifier = state_change_data['token_network_identifier']
channel_identifier = state_change_data['channel_identifier']
channel_new_state_change = _find_channel_new_state_change(
storage=storage,
token_network_address=token_network_identifier,
channel_identifier=channel_identifier,
)
if not channel_new_state_change.data:
raise RaidenUnrecoverableError(
f'Could not find the state change for channel {channel_identifier}, '
f'token network address: {token_network_identifier} being created. ',
)
channel_state_data = json.loads(channel_new_state_change.data)
new_channel_state = channel_state_data['channel_state']
canonical_identifier = CanonicalIdentifier(
chain_identifier=-1,
token_network_address=to_canonical_address(token_network_identifier),
channel_identifier=int(channel_identifier),
)
our_locksroot, partner_locksroot = get_onchain_locksroots(
chain=raiden.chain,
canonical_identifier=canonical_identifier,
participant1=to_canonical_address(new_channel_state['our_state']['address']),
participant2=to_canonical_address(new_channel_state['partner_state']['address']),
block_identifier='latest',
)
state_change_data['our_onchain_locksroot'] = serialize_bytes(
our_locksroot,
)
state_change_data['partner_onchain_locksroot'] = serialize_bytes(
partner_locksroot,
)
updated_state_changes.append((
json.dumps(state_change_data),
state_change.state_change_identifier,
))
storage.update_state_changes(updated_state_changes) | python | def _add_onchain_locksroot_to_channel_settled_state_changes(
raiden: RaidenService,
storage: SQLiteStorage,
) -> None:
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.state_change.ContractReceiveChannelSettled'),
],
)
for state_changes_batch in batch_query:
updated_state_changes = list()
for state_change in state_changes_batch:
state_change_data = json.loads(state_change.data)
msg = 'v18 state changes cant contain our_onchain_locksroot'
assert 'our_onchain_locksroot' not in state_change_data, msg
msg = 'v18 state changes cant contain partner_onchain_locksroot'
assert 'partner_onchain_locksroot' not in state_change_data, msg
token_network_identifier = state_change_data['token_network_identifier']
channel_identifier = state_change_data['channel_identifier']
channel_new_state_change = _find_channel_new_state_change(
storage=storage,
token_network_address=token_network_identifier,
channel_identifier=channel_identifier,
)
if not channel_new_state_change.data:
raise RaidenUnrecoverableError(
f'Could not find the state change for channel {channel_identifier}, '
f'token network address: {token_network_identifier} being created. ',
)
channel_state_data = json.loads(channel_new_state_change.data)
new_channel_state = channel_state_data['channel_state']
canonical_identifier = CanonicalIdentifier(
chain_identifier=-1,
token_network_address=to_canonical_address(token_network_identifier),
channel_identifier=int(channel_identifier),
)
our_locksroot, partner_locksroot = get_onchain_locksroots(
chain=raiden.chain,
canonical_identifier=canonical_identifier,
participant1=to_canonical_address(new_channel_state['our_state']['address']),
participant2=to_canonical_address(new_channel_state['partner_state']['address']),
block_identifier='latest',
)
state_change_data['our_onchain_locksroot'] = serialize_bytes(
our_locksroot,
)
state_change_data['partner_onchain_locksroot'] = serialize_bytes(
partner_locksroot,
)
updated_state_changes.append((
json.dumps(state_change_data),
state_change.state_change_identifier,
))
storage.update_state_changes(updated_state_changes) | [
"def",
"_add_onchain_locksroot_to_channel_settled_state_changes",
"(",
"raiden",
":",
"RaidenService",
",",
"storage",
":",
"SQLiteStorage",
",",
")",
"->",
"None",
":",
"batch_size",
"=",
"50",
"batch_query",
"=",
"storage",
".",
"batch_query_state_changes",
"(",
"ba... | Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
ContractReceiveChannelSettled. | [
"Adds",
"our_onchain_locksroot",
"and",
"partner_onchain_locksroot",
"to",
"ContractReceiveChannelSettled",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v19_to_v20.py#L103-L168 |
235,349 | raiden-network/raiden | raiden/storage/migrations/v19_to_v20.py | _add_onchain_locksroot_to_snapshot | def _add_onchain_locksroot_to_snapshot(
raiden: RaidenService,
storage: SQLiteStorage,
snapshot_record: StateChangeRecord,
) -> str:
"""
Add `onchain_locksroot` to each NettingChannelEndState
"""
snapshot = json.loads(snapshot_record.data)
for payment_network in snapshot.get('identifiers_to_paymentnetworks', dict()).values():
for token_network in payment_network.get('tokennetworks', list()):
channelidentifiers_to_channels = token_network.get(
'channelidentifiers_to_channels',
dict(),
)
for channel in channelidentifiers_to_channels.values():
our_locksroot, partner_locksroot = _get_onchain_locksroots(
raiden=raiden,
storage=storage,
token_network=token_network,
channel=channel,
)
channel['our_state']['onchain_locksroot'] = serialize_bytes(our_locksroot)
channel['partner_state']['onchain_locksroot'] = serialize_bytes(partner_locksroot)
return json.dumps(snapshot, indent=4), snapshot_record.identifier | python | def _add_onchain_locksroot_to_snapshot(
raiden: RaidenService,
storage: SQLiteStorage,
snapshot_record: StateChangeRecord,
) -> str:
snapshot = json.loads(snapshot_record.data)
for payment_network in snapshot.get('identifiers_to_paymentnetworks', dict()).values():
for token_network in payment_network.get('tokennetworks', list()):
channelidentifiers_to_channels = token_network.get(
'channelidentifiers_to_channels',
dict(),
)
for channel in channelidentifiers_to_channels.values():
our_locksroot, partner_locksroot = _get_onchain_locksroots(
raiden=raiden,
storage=storage,
token_network=token_network,
channel=channel,
)
channel['our_state']['onchain_locksroot'] = serialize_bytes(our_locksroot)
channel['partner_state']['onchain_locksroot'] = serialize_bytes(partner_locksroot)
return json.dumps(snapshot, indent=4), snapshot_record.identifier | [
"def",
"_add_onchain_locksroot_to_snapshot",
"(",
"raiden",
":",
"RaidenService",
",",
"storage",
":",
"SQLiteStorage",
",",
"snapshot_record",
":",
"StateChangeRecord",
",",
")",
"->",
"str",
":",
"snapshot",
"=",
"json",
".",
"loads",
"(",
"snapshot_record",
"."... | Add `onchain_locksroot` to each NettingChannelEndState | [
"Add",
"onchain_locksroot",
"to",
"each",
"NettingChannelEndState"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v19_to_v20.py#L171-L197 |
235,350 | raiden-network/raiden | raiden/log_config.py | add_greenlet_name | def add_greenlet_name(
_logger: str,
_method_name: str,
event_dict: Dict[str, Any],
) -> Dict[str, Any]:
"""Add greenlet_name to the event dict for greenlets that have a non-default name."""
current_greenlet = gevent.getcurrent()
greenlet_name = getattr(current_greenlet, 'name', None)
if greenlet_name is not None and not greenlet_name.startswith('Greenlet-'):
event_dict['greenlet_name'] = greenlet_name
return event_dict | python | def add_greenlet_name(
_logger: str,
_method_name: str,
event_dict: Dict[str, Any],
) -> Dict[str, Any]:
current_greenlet = gevent.getcurrent()
greenlet_name = getattr(current_greenlet, 'name', None)
if greenlet_name is not None and not greenlet_name.startswith('Greenlet-'):
event_dict['greenlet_name'] = greenlet_name
return event_dict | [
"def",
"add_greenlet_name",
"(",
"_logger",
":",
"str",
",",
"_method_name",
":",
"str",
",",
"event_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"current_greenlet",
"=",
"gevent",
".",
"g... | Add greenlet_name to the event dict for greenlets that have a non-default name. | [
"Add",
"greenlet_name",
"to",
"the",
"event",
"dict",
"for",
"greenlets",
"that",
"have",
"a",
"non",
"-",
"default",
"name",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/log_config.py#L107-L117 |
235,351 | raiden-network/raiden | raiden/log_config.py | redactor | def redactor(blacklist: Dict[Pattern, str]) -> Callable[[str], str]:
"""Returns a function which transforms a str, replacing all matches for its replacement"""
def processor_wrapper(msg: str) -> str:
for regex, repl in blacklist.items():
if repl is None:
repl = '<redacted>'
msg = regex.sub(repl, msg)
return msg
return processor_wrapper | python | def redactor(blacklist: Dict[Pattern, str]) -> Callable[[str], str]:
def processor_wrapper(msg: str) -> str:
for regex, repl in blacklist.items():
if repl is None:
repl = '<redacted>'
msg = regex.sub(repl, msg)
return msg
return processor_wrapper | [
"def",
"redactor",
"(",
"blacklist",
":",
"Dict",
"[",
"Pattern",
",",
"str",
"]",
")",
"->",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
":",
"def",
"processor_wrapper",
"(",
"msg",
":",
"str",
")",
"->",
"str",
":",
"for",
"regex",
",",
... | Returns a function which transforms a str, replacing all matches for its replacement | [
"Returns",
"a",
"function",
"which",
"transforms",
"a",
"str",
"replacing",
"all",
"matches",
"for",
"its",
"replacement"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/log_config.py#L120-L128 |
235,352 | raiden-network/raiden | raiden/log_config.py | _wrap_tracebackexception_format | def _wrap_tracebackexception_format(redact: Callable[[str], str]):
"""Monkey-patch TracebackException.format to redact printed lines.
Only the last call will be effective. Consecutive calls will overwrite the
previous monkey patches.
"""
original_format = getattr(TracebackException, '_original', None)
if original_format is None:
original_format = TracebackException.format
setattr(TracebackException, '_original', original_format)
@wraps(original_format)
def tracebackexception_format(self, *, chain=True):
for line in original_format(self, chain=chain):
yield redact(line)
setattr(TracebackException, 'format', tracebackexception_format) | python | def _wrap_tracebackexception_format(redact: Callable[[str], str]):
original_format = getattr(TracebackException, '_original', None)
if original_format is None:
original_format = TracebackException.format
setattr(TracebackException, '_original', original_format)
@wraps(original_format)
def tracebackexception_format(self, *, chain=True):
for line in original_format(self, chain=chain):
yield redact(line)
setattr(TracebackException, 'format', tracebackexception_format) | [
"def",
"_wrap_tracebackexception_format",
"(",
"redact",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
")",
":",
"original_format",
"=",
"getattr",
"(",
"TracebackException",
",",
"'_original'",
",",
"None",
")",
"if",
"original_format",
"is",
"None"... | Monkey-patch TracebackException.format to redact printed lines.
Only the last call will be effective. Consecutive calls will overwrite the
previous monkey patches. | [
"Monkey",
"-",
"patch",
"TracebackException",
".",
"format",
"to",
"redact",
"printed",
"lines",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/log_config.py#L131-L147 |
235,353 | raiden-network/raiden | raiden/log_config.py | LogFilter.should_log | def should_log(self, logger_name: str, level: str) -> bool:
""" Returns if a message for the logger should be logged. """
if (logger_name, level) not in self._should_log:
log_level_per_rule = self._get_log_level(logger_name)
log_level_per_rule_numeric = getattr(logging, log_level_per_rule.upper(), 10)
log_level_event_numeric = getattr(logging, level.upper(), 10)
should_log = log_level_event_numeric >= log_level_per_rule_numeric
self._should_log[(logger_name, level)] = should_log
return self._should_log[(logger_name, level)] | python | def should_log(self, logger_name: str, level: str) -> bool:
if (logger_name, level) not in self._should_log:
log_level_per_rule = self._get_log_level(logger_name)
log_level_per_rule_numeric = getattr(logging, log_level_per_rule.upper(), 10)
log_level_event_numeric = getattr(logging, level.upper(), 10)
should_log = log_level_event_numeric >= log_level_per_rule_numeric
self._should_log[(logger_name, level)] = should_log
return self._should_log[(logger_name, level)] | [
"def",
"should_log",
"(",
"self",
",",
"logger_name",
":",
"str",
",",
"level",
":",
"str",
")",
"->",
"bool",
":",
"if",
"(",
"logger_name",
",",
"level",
")",
"not",
"in",
"self",
".",
"_should_log",
":",
"log_level_per_rule",
"=",
"self",
".",
"_get... | Returns if a message for the logger should be logged. | [
"Returns",
"if",
"a",
"message",
"for",
"the",
"logger",
"should",
"be",
"logged",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/log_config.py#L86-L95 |
235,354 | raiden-network/raiden | raiden/storage/migrations/v20_to_v21.py | _update_statechanges | def _update_statechanges(storage: SQLiteStorage):
"""
Update each ContractReceiveChannelNew's channel_state member
by setting the `mediation_fee` that was added to the NettingChannelState
"""
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.state_change.ContractReceiveChannelNew'),
],
)
for state_changes_batch in batch_query:
updated_state_changes = list()
for state_change in state_changes_batch:
data = json.loads(state_change.data)
msg = 'v20 ContractReceiveChannelNew channel state should not contain medation_fee'
assert 'mediation_fee' not in data['channel_state'], msg
data['channel_state']['mediation_fee'] = '0'
updated_state_changes.append((
json.dumps(data),
state_change.state_change_identifier,
))
storage.update_state_changes(updated_state_changes)
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.mediated_transfer.state_change.ActionInitInitiator'),
],
)
for state_changes_batch in batch_query:
updated_state_changes = list()
for state_change in state_changes_batch:
data = json.loads(state_change.data)
msg = 'v20 ActionInitInitiator transfer should not contain allocated_fee'
assert 'allocated_fee' not in data['transfer'], msg
data['transfer']['allocated_fee'] = '0'
updated_state_changes.append((
json.dumps(data),
state_change.state_change_identifier,
))
storage.update_state_changes(updated_state_changes) | python | def _update_statechanges(storage: SQLiteStorage):
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.state_change.ContractReceiveChannelNew'),
],
)
for state_changes_batch in batch_query:
updated_state_changes = list()
for state_change in state_changes_batch:
data = json.loads(state_change.data)
msg = 'v20 ContractReceiveChannelNew channel state should not contain medation_fee'
assert 'mediation_fee' not in data['channel_state'], msg
data['channel_state']['mediation_fee'] = '0'
updated_state_changes.append((
json.dumps(data),
state_change.state_change_identifier,
))
storage.update_state_changes(updated_state_changes)
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'raiden.transfer.mediated_transfer.state_change.ActionInitInitiator'),
],
)
for state_changes_batch in batch_query:
updated_state_changes = list()
for state_change in state_changes_batch:
data = json.loads(state_change.data)
msg = 'v20 ActionInitInitiator transfer should not contain allocated_fee'
assert 'allocated_fee' not in data['transfer'], msg
data['transfer']['allocated_fee'] = '0'
updated_state_changes.append((
json.dumps(data),
state_change.state_change_identifier,
))
storage.update_state_changes(updated_state_changes) | [
"def",
"_update_statechanges",
"(",
"storage",
":",
"SQLiteStorage",
")",
":",
"batch_size",
"=",
"50",
"batch_query",
"=",
"storage",
".",
"batch_query_state_changes",
"(",
"batch_size",
"=",
"batch_size",
",",
"filters",
"=",
"[",
"(",
"'_type'",
",",
"'raiden... | Update each ContractReceiveChannelNew's channel_state member
by setting the `mediation_fee` that was added to the NettingChannelState | [
"Update",
"each",
"ContractReceiveChannelNew",
"s",
"channel_state",
"member",
"by",
"setting",
"the",
"mediation_fee",
"that",
"was",
"added",
"to",
"the",
"NettingChannelState"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v20_to_v21.py#L52-L100 |
235,355 | raiden-network/raiden | raiden/blockchain/events.py | get_contract_events | def get_contract_events(
chain: BlockChainService,
abi: Dict,
contract_address: Address,
topics: Optional[List[str]],
from_block: BlockSpecification,
to_block: BlockSpecification,
) -> List[Dict]:
""" Query the blockchain for all events of the smart contract at
`contract_address` that match the filters `topics`, `from_block`, and
`to_block`.
"""
verify_block_number(from_block, 'from_block')
verify_block_number(to_block, 'to_block')
events = chain.client.get_filter_events(
contract_address,
topics=topics,
from_block=from_block,
to_block=to_block,
)
result = []
for event in events:
decoded_event = dict(decode_event(abi, event))
if event.get('blockNumber'):
decoded_event['block_number'] = event['blockNumber']
del decoded_event['blockNumber']
result.append(decoded_event)
return result | python | def get_contract_events(
chain: BlockChainService,
abi: Dict,
contract_address: Address,
topics: Optional[List[str]],
from_block: BlockSpecification,
to_block: BlockSpecification,
) -> List[Dict]:
verify_block_number(from_block, 'from_block')
verify_block_number(to_block, 'to_block')
events = chain.client.get_filter_events(
contract_address,
topics=topics,
from_block=from_block,
to_block=to_block,
)
result = []
for event in events:
decoded_event = dict(decode_event(abi, event))
if event.get('blockNumber'):
decoded_event['block_number'] = event['blockNumber']
del decoded_event['blockNumber']
result.append(decoded_event)
return result | [
"def",
"get_contract_events",
"(",
"chain",
":",
"BlockChainService",
",",
"abi",
":",
"Dict",
",",
"contract_address",
":",
"Address",
",",
"topics",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"from_block",
":",
"BlockSpecification",
",",
"to_... | Query the blockchain for all events of the smart contract at
`contract_address` that match the filters `topics`, `from_block`, and
`to_block`. | [
"Query",
"the",
"blockchain",
"for",
"all",
"events",
"of",
"the",
"smart",
"contract",
"at",
"contract_address",
"that",
"match",
"the",
"filters",
"topics",
"from_block",
"and",
"to_block",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain/events.py#L50-L78 |
235,356 | raiden-network/raiden | raiden/blockchain/events.py | get_token_network_registry_events | def get_token_network_registry_events(
chain: BlockChainService,
token_network_registry_address: PaymentNetworkID,
contract_manager: ContractManager,
events: Optional[List[str]] = ALL_EVENTS,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
""" Helper to get all events of the Registry contract at `registry_address`. """
return get_contract_events(
chain=chain,
abi=contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK_REGISTRY),
contract_address=Address(token_network_registry_address),
topics=events,
from_block=from_block,
to_block=to_block,
) | python | def get_token_network_registry_events(
chain: BlockChainService,
token_network_registry_address: PaymentNetworkID,
contract_manager: ContractManager,
events: Optional[List[str]] = ALL_EVENTS,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
return get_contract_events(
chain=chain,
abi=contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK_REGISTRY),
contract_address=Address(token_network_registry_address),
topics=events,
from_block=from_block,
to_block=to_block,
) | [
"def",
"get_token_network_registry_events",
"(",
"chain",
":",
"BlockChainService",
",",
"token_network_registry_address",
":",
"PaymentNetworkID",
",",
"contract_manager",
":",
"ContractManager",
",",
"events",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",... | Helper to get all events of the Registry contract at `registry_address`. | [
"Helper",
"to",
"get",
"all",
"events",
"of",
"the",
"Registry",
"contract",
"at",
"registry_address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain/events.py#L81-L97 |
235,357 | raiden-network/raiden | raiden/blockchain/events.py | get_token_network_events | def get_token_network_events(
chain: BlockChainService,
token_network_address: Address,
contract_manager: ContractManager,
events: Optional[List[str]] = ALL_EVENTS,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
""" Helper to get all events of the ChannelManagerContract at `token_address`. """
return get_contract_events(
chain,
contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),
token_network_address,
events,
from_block,
to_block,
) | python | def get_token_network_events(
chain: BlockChainService,
token_network_address: Address,
contract_manager: ContractManager,
events: Optional[List[str]] = ALL_EVENTS,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
return get_contract_events(
chain,
contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),
token_network_address,
events,
from_block,
to_block,
) | [
"def",
"get_token_network_events",
"(",
"chain",
":",
"BlockChainService",
",",
"token_network_address",
":",
"Address",
",",
"contract_manager",
":",
"ContractManager",
",",
"events",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"ALL_EVENTS",
",",
"... | Helper to get all events of the ChannelManagerContract at `token_address`. | [
"Helper",
"to",
"get",
"all",
"events",
"of",
"the",
"ChannelManagerContract",
"at",
"token_address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain/events.py#L100-L117 |
235,358 | raiden-network/raiden | raiden/blockchain/events.py | get_all_netting_channel_events | def get_all_netting_channel_events(
chain: BlockChainService,
token_network_address: TokenNetworkAddress,
netting_channel_identifier: ChannelID,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
""" Helper to get all events of a NettingChannelContract. """
filter_args = get_filter_args_for_all_events_from_channel(
token_network_address=token_network_address,
channel_identifier=netting_channel_identifier,
contract_manager=contract_manager,
from_block=from_block,
to_block=to_block,
)
return get_contract_events(
chain,
contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),
typing.Address(token_network_address),
filter_args['topics'],
from_block,
to_block,
) | python | def get_all_netting_channel_events(
chain: BlockChainService,
token_network_address: TokenNetworkAddress,
netting_channel_identifier: ChannelID,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> List[Dict]:
filter_args = get_filter_args_for_all_events_from_channel(
token_network_address=token_network_address,
channel_identifier=netting_channel_identifier,
contract_manager=contract_manager,
from_block=from_block,
to_block=to_block,
)
return get_contract_events(
chain,
contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),
typing.Address(token_network_address),
filter_args['topics'],
from_block,
to_block,
) | [
"def",
"get_all_netting_channel_events",
"(",
"chain",
":",
"BlockChainService",
",",
"token_network_address",
":",
"TokenNetworkAddress",
",",
"netting_channel_identifier",
":",
"ChannelID",
",",
"contract_manager",
":",
"ContractManager",
",",
"from_block",
":",
"BlockSpe... | Helper to get all events of a NettingChannelContract. | [
"Helper",
"to",
"get",
"all",
"events",
"of",
"a",
"NettingChannelContract",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain/events.py#L120-L145 |
235,359 | raiden-network/raiden | raiden/blockchain/events.py | decode_event_to_internal | def decode_event_to_internal(abi, log_event):
""" Enforce the binary for internal usage. """
# Note: All addresses inside the event_data must be decoded.
decoded_event = decode_event(abi, log_event)
if not decoded_event:
raise UnknownEventType()
# copy the attribute dict because that data structure is immutable
data = dict(decoded_event)
args = dict(data['args'])
data['args'] = args
# translate from web3's to raiden's name convention
data['block_number'] = log_event.pop('blockNumber')
data['transaction_hash'] = log_event.pop('transactionHash')
data['block_hash'] = bytes(log_event.pop('blockHash'))
assert data['block_number'], 'The event must have the block_number'
assert data['transaction_hash'], 'The event must have the transaction hash field'
event = data['event']
if event == EVENT_TOKEN_NETWORK_CREATED:
args['token_network_address'] = to_canonical_address(args['token_network_address'])
args['token_address'] = to_canonical_address(args['token_address'])
elif event == ChannelEvent.OPENED:
args['participant1'] = to_canonical_address(args['participant1'])
args['participant2'] = to_canonical_address(args['participant2'])
elif event == ChannelEvent.DEPOSIT:
args['participant'] = to_canonical_address(args['participant'])
elif event == ChannelEvent.BALANCE_PROOF_UPDATED:
args['closing_participant'] = to_canonical_address(args['closing_participant'])
elif event == ChannelEvent.CLOSED:
args['closing_participant'] = to_canonical_address(args['closing_participant'])
elif event == ChannelEvent.UNLOCKED:
args['participant'] = to_canonical_address(args['participant'])
args['partner'] = to_canonical_address(args['partner'])
return Event(
originating_contract=to_canonical_address(log_event['address']),
event_data=data,
) | python | def decode_event_to_internal(abi, log_event):
# Note: All addresses inside the event_data must be decoded.
decoded_event = decode_event(abi, log_event)
if not decoded_event:
raise UnknownEventType()
# copy the attribute dict because that data structure is immutable
data = dict(decoded_event)
args = dict(data['args'])
data['args'] = args
# translate from web3's to raiden's name convention
data['block_number'] = log_event.pop('blockNumber')
data['transaction_hash'] = log_event.pop('transactionHash')
data['block_hash'] = bytes(log_event.pop('blockHash'))
assert data['block_number'], 'The event must have the block_number'
assert data['transaction_hash'], 'The event must have the transaction hash field'
event = data['event']
if event == EVENT_TOKEN_NETWORK_CREATED:
args['token_network_address'] = to_canonical_address(args['token_network_address'])
args['token_address'] = to_canonical_address(args['token_address'])
elif event == ChannelEvent.OPENED:
args['participant1'] = to_canonical_address(args['participant1'])
args['participant2'] = to_canonical_address(args['participant2'])
elif event == ChannelEvent.DEPOSIT:
args['participant'] = to_canonical_address(args['participant'])
elif event == ChannelEvent.BALANCE_PROOF_UPDATED:
args['closing_participant'] = to_canonical_address(args['closing_participant'])
elif event == ChannelEvent.CLOSED:
args['closing_participant'] = to_canonical_address(args['closing_participant'])
elif event == ChannelEvent.UNLOCKED:
args['participant'] = to_canonical_address(args['participant'])
args['partner'] = to_canonical_address(args['partner'])
return Event(
originating_contract=to_canonical_address(log_event['address']),
event_data=data,
) | [
"def",
"decode_event_to_internal",
"(",
"abi",
",",
"log_event",
")",
":",
"# Note: All addresses inside the event_data must be decoded.",
"decoded_event",
"=",
"decode_event",
"(",
"abi",
",",
"log_event",
")",
"if",
"not",
"decoded_event",
":",
"raise",
"UnknownEventTyp... | Enforce the binary for internal usage. | [
"Enforce",
"the",
"binary",
"for",
"internal",
"usage",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain/events.py#L148-L195 |
235,360 | raiden-network/raiden | raiden/blockchain/events.py | BlockchainEvents.poll_blockchain_events | def poll_blockchain_events(self, block_number: typing.BlockNumber):
""" Poll for new blockchain events up to `block_number`. """
for event_listener in self.event_listeners:
assert isinstance(event_listener.filter, StatelessFilter)
for log_event in event_listener.filter.get_new_entries(block_number):
yield decode_event_to_internal(event_listener.abi, log_event) | python | def poll_blockchain_events(self, block_number: typing.BlockNumber):
for event_listener in self.event_listeners:
assert isinstance(event_listener.filter, StatelessFilter)
for log_event in event_listener.filter.get_new_entries(block_number):
yield decode_event_to_internal(event_listener.abi, log_event) | [
"def",
"poll_blockchain_events",
"(",
"self",
",",
"block_number",
":",
"typing",
".",
"BlockNumber",
")",
":",
"for",
"event_listener",
"in",
"self",
".",
"event_listeners",
":",
"assert",
"isinstance",
"(",
"event_listener",
".",
"filter",
",",
"StatelessFilter"... | Poll for new blockchain events up to `block_number`. | [
"Poll",
"for",
"new",
"blockchain",
"events",
"up",
"to",
"block_number",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain/events.py#L216-L223 |
235,361 | raiden-network/raiden | tools/genesis_builder.py | generate_accounts | def generate_accounts(seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: {
'privatekey': encode_hex(sha3(seed)),
'address': encode_hex(privatekey_to_address(sha3(seed))),
}
for seed in seeds
} | python | def generate_accounts(seeds):
return {
seed: {
'privatekey': encode_hex(sha3(seed)),
'address': encode_hex(privatekey_to_address(sha3(seed))),
}
for seed in seeds
} | [
"def",
"generate_accounts",
"(",
"seeds",
")",
":",
"return",
"{",
"seed",
":",
"{",
"'privatekey'",
":",
"encode_hex",
"(",
"sha3",
"(",
"seed",
")",
")",
",",
"'address'",
":",
"encode_hex",
"(",
"privatekey_to_address",
"(",
"sha3",
"(",
"seed",
")",
... | Create private keys and addresses for all seeds. | [
"Create",
"private",
"keys",
"and",
"addresses",
"for",
"all",
"seeds",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/genesis_builder.py#L9-L18 |
235,362 | raiden-network/raiden | tools/genesis_builder.py | mk_genesis | def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000):
"""
Create a genesis-block dict with allocation for all `accounts`.
:param accounts: list of account addresses (hex)
:param initial_alloc: the amount to allocate for the `accounts`
:return: genesis dict
"""
genesis = GENESIS_STUB.copy()
genesis['extraData'] = encode_hex(CLUSTER_NAME)
genesis['alloc'].update({
account: {
'balance': str(initial_alloc),
}
for account in accounts
})
# add the one-privatekey account ("1" * 64) for convenience
genesis['alloc']['19e7e376e7c213b7e7e7e46cc70a5dd086daff2a'] = dict(balance=str(initial_alloc))
return genesis | python | def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000):
genesis = GENESIS_STUB.copy()
genesis['extraData'] = encode_hex(CLUSTER_NAME)
genesis['alloc'].update({
account: {
'balance': str(initial_alloc),
}
for account in accounts
})
# add the one-privatekey account ("1" * 64) for convenience
genesis['alloc']['19e7e376e7c213b7e7e7e46cc70a5dd086daff2a'] = dict(balance=str(initial_alloc))
return genesis | [
"def",
"mk_genesis",
"(",
"accounts",
",",
"initial_alloc",
"=",
"denoms",
".",
"ether",
"*",
"100000000",
")",
":",
"genesis",
"=",
"GENESIS_STUB",
".",
"copy",
"(",
")",
"genesis",
"[",
"'extraData'",
"]",
"=",
"encode_hex",
"(",
"CLUSTER_NAME",
")",
"ge... | Create a genesis-block dict with allocation for all `accounts`.
:param accounts: list of account addresses (hex)
:param initial_alloc: the amount to allocate for the `accounts`
:return: genesis dict | [
"Create",
"a",
"genesis",
"-",
"block",
"dict",
"with",
"allocation",
"for",
"all",
"accounts",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/genesis_builder.py#L21-L39 |
235,363 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.token_address | def token_address(self) -> Address:
""" Return the token of this manager. """
return to_canonical_address(self.proxy.contract.functions.token().call()) | python | def token_address(self) -> Address:
return to_canonical_address(self.proxy.contract.functions.token().call()) | [
"def",
"token_address",
"(",
"self",
")",
"->",
"Address",
":",
"return",
"to_canonical_address",
"(",
"self",
".",
"proxy",
".",
"contract",
".",
"functions",
".",
"token",
"(",
")",
".",
"call",
"(",
")",
")"
] | Return the token of this manager. | [
"Return",
"the",
"token",
"of",
"this",
"manager",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L155-L157 |
235,364 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.new_netting_channel | def new_netting_channel(
self,
partner: Address,
settle_timeout: int,
given_block_identifier: BlockSpecification,
) -> ChannelID:
""" Creates a new channel in the TokenNetwork contract.
Args:
partner: The peer to open the channel with.
settle_timeout: The settle timeout to use for this channel.
given_block_identifier: The block identifier of the state change that
prompted this proxy action
Returns:
The ChannelID of the new netting channel.
"""
checking_block = self.client.get_checking_block()
self._new_channel_preconditions(
partner=partner,
settle_timeout=settle_timeout,
block_identifier=given_block_identifier,
)
log_details = {
'peer1': pex(self.node_address),
'peer2': pex(partner),
}
gas_limit = self.proxy.estimate_gas(
checking_block,
'openChannel',
participant1=self.node_address,
participant2=partner,
settle_timeout=settle_timeout,
)
if not gas_limit:
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='openChannel',
transaction_executed=False,
required_gas=GAS_REQUIRED_FOR_OPEN_CHANNEL,
block_identifier=checking_block,
)
self._new_channel_postconditions(
partner=partner,
block=checking_block,
)
log.critical('new_netting_channel call will fail', **log_details)
raise RaidenUnrecoverableError('Creating a new channel will fail')
log.debug('new_netting_channel called', **log_details)
# Prevent concurrent attempts to open a channel with the same token and
# partner address.
if gas_limit and partner not in self.open_channel_transactions:
new_open_channel_transaction = AsyncResult()
self.open_channel_transactions[partner] = new_open_channel_transaction
gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_OPEN_CHANNEL)
try:
transaction_hash = self.proxy.transact(
'openChannel',
gas_limit,
participant1=self.node_address,
participant2=partner,
settle_timeout=settle_timeout,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
if receipt_or_none:
self._new_channel_postconditions(
partner=partner,
block=receipt_or_none['blockNumber'],
)
log.critical('new_netting_channel failed', **log_details)
raise RaidenUnrecoverableError('creating new channel failed')
except Exception as e:
log.critical('new_netting_channel failed', **log_details)
new_open_channel_transaction.set_exception(e)
raise
else:
new_open_channel_transaction.set(transaction_hash)
finally:
self.open_channel_transactions.pop(partner, None)
else:
# All other concurrent threads should block on the result of opening this channel
self.open_channel_transactions[partner].get()
channel_identifier: ChannelID = self._detail_channel(
participant1=self.node_address,
participant2=partner,
block_identifier='latest',
).channel_identifier
log_details['channel_identifier'] = str(channel_identifier)
log.info('new_netting_channel successful', **log_details)
return channel_identifier | python | def new_netting_channel(
self,
partner: Address,
settle_timeout: int,
given_block_identifier: BlockSpecification,
) -> ChannelID:
checking_block = self.client.get_checking_block()
self._new_channel_preconditions(
partner=partner,
settle_timeout=settle_timeout,
block_identifier=given_block_identifier,
)
log_details = {
'peer1': pex(self.node_address),
'peer2': pex(partner),
}
gas_limit = self.proxy.estimate_gas(
checking_block,
'openChannel',
participant1=self.node_address,
participant2=partner,
settle_timeout=settle_timeout,
)
if not gas_limit:
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='openChannel',
transaction_executed=False,
required_gas=GAS_REQUIRED_FOR_OPEN_CHANNEL,
block_identifier=checking_block,
)
self._new_channel_postconditions(
partner=partner,
block=checking_block,
)
log.critical('new_netting_channel call will fail', **log_details)
raise RaidenUnrecoverableError('Creating a new channel will fail')
log.debug('new_netting_channel called', **log_details)
# Prevent concurrent attempts to open a channel with the same token and
# partner address.
if gas_limit and partner not in self.open_channel_transactions:
new_open_channel_transaction = AsyncResult()
self.open_channel_transactions[partner] = new_open_channel_transaction
gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_OPEN_CHANNEL)
try:
transaction_hash = self.proxy.transact(
'openChannel',
gas_limit,
participant1=self.node_address,
participant2=partner,
settle_timeout=settle_timeout,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
if receipt_or_none:
self._new_channel_postconditions(
partner=partner,
block=receipt_or_none['blockNumber'],
)
log.critical('new_netting_channel failed', **log_details)
raise RaidenUnrecoverableError('creating new channel failed')
except Exception as e:
log.critical('new_netting_channel failed', **log_details)
new_open_channel_transaction.set_exception(e)
raise
else:
new_open_channel_transaction.set(transaction_hash)
finally:
self.open_channel_transactions.pop(partner, None)
else:
# All other concurrent threads should block on the result of opening this channel
self.open_channel_transactions[partner].get()
channel_identifier: ChannelID = self._detail_channel(
participant1=self.node_address,
participant2=partner,
block_identifier='latest',
).channel_identifier
log_details['channel_identifier'] = str(channel_identifier)
log.info('new_netting_channel successful', **log_details)
return channel_identifier | [
"def",
"new_netting_channel",
"(",
"self",
",",
"partner",
":",
"Address",
",",
"settle_timeout",
":",
"int",
",",
"given_block_identifier",
":",
"BlockSpecification",
",",
")",
"->",
"ChannelID",
":",
"checking_block",
"=",
"self",
".",
"client",
".",
"get_chec... | Creates a new channel in the TokenNetwork contract.
Args:
partner: The peer to open the channel with.
settle_timeout: The settle timeout to use for this channel.
given_block_identifier: The block identifier of the state change that
prompted this proxy action
Returns:
The ChannelID of the new netting channel. | [
"Creates",
"a",
"new",
"channel",
"in",
"the",
"TokenNetwork",
"contract",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L209-L303 |
235,365 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork._channel_exists_and_not_settled | def _channel_exists_and_not_settled(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> bool:
"""Returns if the channel exists and is in a non-settled state"""
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
exists_and_not_settled = (
channel_state > ChannelState.NONEXISTENT and
channel_state < ChannelState.SETTLED
)
return exists_and_not_settled | python | def _channel_exists_and_not_settled(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> bool:
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
exists_and_not_settled = (
channel_state > ChannelState.NONEXISTENT and
channel_state < ChannelState.SETTLED
)
return exists_and_not_settled | [
"def",
"_channel_exists_and_not_settled",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
"=",
"None",
",",
")",
"->",
"bool",
"... | Returns if the channel exists and is in a non-settled state | [
"Returns",
"if",
"the",
"channel",
"exists",
"and",
"is",
"in",
"a",
"non",
"-",
"settled",
"state"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L332-L353 |
235,366 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork._detail_participant | def _detail_participant(
self,
channel_identifier: ChannelID,
participant: Address,
partner: Address,
block_identifier: BlockSpecification,
) -> ParticipantDetails:
""" Returns a dictionary with the channel participant information. """
data = self._call_and_check_result(
block_identifier,
'getChannelParticipantInfo',
channel_identifier=channel_identifier,
participant=to_checksum_address(participant),
partner=to_checksum_address(partner),
)
return ParticipantDetails(
address=participant,
deposit=data[ParticipantInfoIndex.DEPOSIT],
withdrawn=data[ParticipantInfoIndex.WITHDRAWN],
is_closer=data[ParticipantInfoIndex.IS_CLOSER],
balance_hash=data[ParticipantInfoIndex.BALANCE_HASH],
nonce=data[ParticipantInfoIndex.NONCE],
locksroot=data[ParticipantInfoIndex.LOCKSROOT],
locked_amount=data[ParticipantInfoIndex.LOCKED_AMOUNT],
) | python | def _detail_participant(
self,
channel_identifier: ChannelID,
participant: Address,
partner: Address,
block_identifier: BlockSpecification,
) -> ParticipantDetails:
data = self._call_and_check_result(
block_identifier,
'getChannelParticipantInfo',
channel_identifier=channel_identifier,
participant=to_checksum_address(participant),
partner=to_checksum_address(partner),
)
return ParticipantDetails(
address=participant,
deposit=data[ParticipantInfoIndex.DEPOSIT],
withdrawn=data[ParticipantInfoIndex.WITHDRAWN],
is_closer=data[ParticipantInfoIndex.IS_CLOSER],
balance_hash=data[ParticipantInfoIndex.BALANCE_HASH],
nonce=data[ParticipantInfoIndex.NONCE],
locksroot=data[ParticipantInfoIndex.LOCKSROOT],
locked_amount=data[ParticipantInfoIndex.LOCKED_AMOUNT],
) | [
"def",
"_detail_participant",
"(",
"self",
",",
"channel_identifier",
":",
"ChannelID",
",",
"participant",
":",
"Address",
",",
"partner",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
")",
"->",
"ParticipantDetails",
":",
"data",
"=",
... | Returns a dictionary with the channel participant information. | [
"Returns",
"a",
"dictionary",
"with",
"the",
"channel",
"participant",
"information",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L355-L380 |
235,367 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork._detail_channel | def _detail_channel(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> ChannelData:
""" Returns a ChannelData instance with the channel specific information.
If no specific channel_identifier is given then it tries to see if there
is a currently open channel and uses that identifier.
"""
channel_identifier = self._inspect_channel_identifier(
participant1=participant1,
participant2=participant2,
called_by_fn='_detail_channel(',
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
channel_data = self._call_and_check_result(
block_identifier,
'getChannelInfo',
channel_identifier=channel_identifier,
participant1=to_checksum_address(participant1),
participant2=to_checksum_address(participant2),
)
return ChannelData(
channel_identifier=channel_identifier,
settle_block_number=channel_data[ChannelInfoIndex.SETTLE_BLOCK],
state=channel_data[ChannelInfoIndex.STATE],
) | python | def _detail_channel(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> ChannelData:
channel_identifier = self._inspect_channel_identifier(
participant1=participant1,
participant2=participant2,
called_by_fn='_detail_channel(',
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
channel_data = self._call_and_check_result(
block_identifier,
'getChannelInfo',
channel_identifier=channel_identifier,
participant1=to_checksum_address(participant1),
participant2=to_checksum_address(participant2),
)
return ChannelData(
channel_identifier=channel_identifier,
settle_block_number=channel_data[ChannelInfoIndex.SETTLE_BLOCK],
state=channel_data[ChannelInfoIndex.STATE],
) | [
"def",
"_detail_channel",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
"=",
"None",
",",
")",
"->",
"ChannelData",
":",
"ch... | Returns a ChannelData instance with the channel specific information.
If no specific channel_identifier is given then it tries to see if there
is a currently open channel and uses that identifier. | [
"Returns",
"a",
"ChannelData",
"instance",
"with",
"the",
"channel",
"specific",
"information",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L382-L415 |
235,368 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.detail_participants | def detail_participants(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> ParticipantsDetails:
""" Returns a ParticipantsDetails instance with the participants'
channel information.
Note:
For now one of the participants has to be the node_address
"""
if self.node_address not in (participant1, participant2):
raise ValueError('One participant must be the node address')
if self.node_address == participant2:
participant1, participant2 = participant2, participant1
channel_identifier = self._inspect_channel_identifier(
participant1=participant1,
participant2=participant2,
called_by_fn='details_participants',
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
our_data = self._detail_participant(
channel_identifier=channel_identifier,
participant=participant1,
partner=participant2,
block_identifier=block_identifier,
)
partner_data = self._detail_participant(
channel_identifier=channel_identifier,
participant=participant2,
partner=participant1,
block_identifier=block_identifier,
)
return ParticipantsDetails(our_details=our_data, partner_details=partner_data) | python | def detail_participants(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> ParticipantsDetails:
if self.node_address not in (participant1, participant2):
raise ValueError('One participant must be the node address')
if self.node_address == participant2:
participant1, participant2 = participant2, participant1
channel_identifier = self._inspect_channel_identifier(
participant1=participant1,
participant2=participant2,
called_by_fn='details_participants',
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
our_data = self._detail_participant(
channel_identifier=channel_identifier,
participant=participant1,
partner=participant2,
block_identifier=block_identifier,
)
partner_data = self._detail_participant(
channel_identifier=channel_identifier,
participant=participant2,
partner=participant1,
block_identifier=block_identifier,
)
return ParticipantsDetails(our_details=our_data, partner_details=partner_data) | [
"def",
"detail_participants",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
"=",
"None",
",",
")",
"->",
"ParticipantsDetails",
... | Returns a ParticipantsDetails instance with the participants'
channel information.
Note:
For now one of the participants has to be the node_address | [
"Returns",
"a",
"ParticipantsDetails",
"instance",
"with",
"the",
"participants",
"channel",
"information",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L417-L456 |
235,369 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.detail | def detail(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> ChannelDetails:
""" Returns a ChannelDetails instance with all the details of the
channel and the channel participants.
Note:
For now one of the participants has to be the node_address
"""
if self.node_address not in (participant1, participant2):
raise ValueError('One participant must be the node address')
if self.node_address == participant2:
participant1, participant2 = participant2, participant1
channel_data = self._detail_channel(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
participants_data = self.detail_participants(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_data.channel_identifier,
)
chain_id = self.proxy.contract.functions.chain_id().call()
return ChannelDetails(
chain_id=chain_id,
channel_data=channel_data,
participants_data=participants_data,
) | python | def detail(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> ChannelDetails:
if self.node_address not in (participant1, participant2):
raise ValueError('One participant must be the node address')
if self.node_address == participant2:
participant1, participant2 = participant2, participant1
channel_data = self._detail_channel(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
participants_data = self.detail_participants(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_data.channel_identifier,
)
chain_id = self.proxy.contract.functions.chain_id().call()
return ChannelDetails(
chain_id=chain_id,
channel_data=channel_data,
participants_data=participants_data,
) | [
"def",
"detail",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
"=",
"None",
",",
")",
"->",
"ChannelDetails",
":",
"if",
"... | Returns a ChannelDetails instance with all the details of the
channel and the channel participants.
Note:
For now one of the participants has to be the node_address | [
"Returns",
"a",
"ChannelDetails",
"instance",
"with",
"all",
"the",
"details",
"of",
"the",
"channel",
"and",
"the",
"channel",
"participants",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L458-L495 |
235,370 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.channel_is_opened | def channel_is_opened(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
""" Returns true if the channel is in an open state, false otherwise. """
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
return channel_state == ChannelState.OPENED | python | def channel_is_opened(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
return channel_state == ChannelState.OPENED | [
"def",
"channel_is_opened",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
",",
")",
"->",
"bool",
":",
"try",
":",
"channel_... | Returns true if the channel is in an open state, false otherwise. | [
"Returns",
"true",
"if",
"the",
"channel",
"is",
"in",
"an",
"open",
"state",
"false",
"otherwise",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L505-L522 |
235,371 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.channel_is_closed | def channel_is_closed(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
""" Returns true if the channel is in a closed state, false otherwise. """
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
return channel_state == ChannelState.CLOSED | python | def channel_is_closed(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
return channel_state == ChannelState.CLOSED | [
"def",
"channel_is_closed",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
",",
")",
"->",
"bool",
":",
"try",
":",
"channel_... | Returns true if the channel is in a closed state, false otherwise. | [
"Returns",
"true",
"if",
"the",
"channel",
"is",
"in",
"a",
"closed",
"state",
"false",
"otherwise",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L524-L541 |
235,372 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.channel_is_settled | def channel_is_settled(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
""" Returns true if the channel is in a settled state, false otherwise. """
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
return channel_state >= ChannelState.SETTLED | python | def channel_is_settled(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
try:
channel_state = self._get_channel_state(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return False
return channel_state >= ChannelState.SETTLED | [
"def",
"channel_is_settled",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
",",
")",
"->",
"bool",
":",
"try",
":",
"channel... | Returns true if the channel is in a settled state, false otherwise. | [
"Returns",
"true",
"if",
"the",
"channel",
"is",
"in",
"a",
"settled",
"state",
"false",
"otherwise",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L543-L560 |
235,373 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.closing_address | def closing_address(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> Optional[Address]:
""" Returns the address of the closer, if the channel is closed and not settled. None
otherwise. """
try:
channel_data = self._detail_channel(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return None
if channel_data.state >= ChannelState.SETTLED:
return None
participants_data = self.detail_participants(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_data.channel_identifier,
)
if participants_data.our_details.is_closer:
return participants_data.our_details.address
elif participants_data.partner_details.is_closer:
return participants_data.partner_details.address
return None | python | def closing_address(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID = None,
) -> Optional[Address]:
try:
channel_data = self._detail_channel(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_identifier,
)
except RaidenRecoverableError:
return None
if channel_data.state >= ChannelState.SETTLED:
return None
participants_data = self.detail_participants(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
channel_identifier=channel_data.channel_identifier,
)
if participants_data.our_details.is_closer:
return participants_data.our_details.address
elif participants_data.partner_details.is_closer:
return participants_data.partner_details.address
return None | [
"def",
"closing_address",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
"=",
"None",
",",
")",
"->",
"Optional",
"[",
"Addre... | Returns the address of the closer, if the channel is closed and not settled. None
otherwise. | [
"Returns",
"the",
"address",
"of",
"the",
"closer",
"if",
"the",
"channel",
"is",
"closed",
"and",
"not",
"settled",
".",
"None",
"otherwise",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L562-L597 |
235,374 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.set_total_deposit | def set_total_deposit(
self,
given_block_identifier: BlockSpecification,
channel_identifier: ChannelID,
total_deposit: TokenAmount,
partner: Address,
):
""" Set channel's total deposit.
`total_deposit` has to be monotonically increasing, this is enforced by
the `TokenNetwork` smart contract. This is done for the same reason why
the balance proofs have a monotonically increasing transferred amount,
it simplifies the analysis of bad behavior and the handling code of
out-dated balance proofs.
Races to `set_total_deposit` are handled by the smart contract, where
largest total deposit wins. The end balance of the funding accounts is
undefined. E.g.
- Acc1 calls set_total_deposit with 10 tokens
- Acc2 calls set_total_deposit with 13 tokens
- If Acc2's transaction is mined first, then Acc1 token supply is left intact.
- If Acc1's transaction is mined first, then Acc2 will only move 3 tokens.
Races for the same account don't have any unexpeted side-effect.
Raises:
DepositMismatch: If the new request total deposit is lower than the
existing total deposit on-chain for the `given_block_identifier`.
RaidenRecoverableError: If the channel was closed meanwhile the
deposit was in transit.
RaidenUnrecoverableError: If the transaction was sucessful and the
deposit_amount is not as large as the requested value.
RuntimeError: If the token address is empty.
ValueError: If an argument is of the invalid type.
"""
if not isinstance(total_deposit, int):
raise ValueError('total_deposit needs to be an integer number.')
token_address = self.token_address()
token = Token(
jsonrpc_client=self.client,
token_address=token_address,
contract_manager=self.contract_manager,
)
checking_block = self.client.get_checking_block()
error_prefix = 'setTotalDeposit call will fail'
with self.channel_operations_lock[partner], self.deposit_lock:
previous_total_deposit = self._detail_participant(
channel_identifier=channel_identifier,
participant=self.node_address,
partner=partner,
block_identifier=given_block_identifier,
).deposit
amount_to_deposit = TokenAmount(total_deposit - previous_total_deposit)
log_details = {
'token_network': pex(self.address),
'channel_identifier': channel_identifier,
'node': pex(self.node_address),
'partner': pex(partner),
'new_total_deposit': total_deposit,
'previous_total_deposit': previous_total_deposit,
}
try:
self._deposit_preconditions(
channel_identifier=channel_identifier,
total_deposit=total_deposit,
partner=partner,
token=token,
previous_total_deposit=previous_total_deposit,
log_details=log_details,
block_identifier=given_block_identifier,
)
except NoStateForBlockIdentifier:
# If preconditions end up being on pruned state skip them. Estimate
# gas will stop us from sending a transaction that will fail
pass
# If there are channels being set up concurrenlty either the
# allowance must be accumulated *or* the calls to `approve` and
# `setTotalDeposit` must be serialized. This is necessary otherwise
# the deposit will fail.
#
# Calls to approve and setTotalDeposit are serialized with the
# deposit_lock to avoid transaction failure, because with two
# concurrent deposits, we may have the transactions executed in the
# following order
#
# - approve
# - approve
# - setTotalDeposit
# - setTotalDeposit
#
# in which case the second `approve` will overwrite the first,
# and the first `setTotalDeposit` will consume the allowance,
# making the second deposit fail.
token.approve(
allowed_address=Address(self.address),
allowance=amount_to_deposit,
)
gas_limit = self.proxy.estimate_gas(
checking_block,
'setTotalDeposit',
channel_identifier=channel_identifier,
participant=self.node_address,
total_deposit=total_deposit,
partner=partner,
)
if gas_limit:
gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT)
error_prefix = 'setTotalDeposit call failed'
log.debug('setTotalDeposit called', **log_details)
transaction_hash = self.proxy.transact(
'setTotalDeposit',
gas_limit,
channel_identifier=channel_identifier,
participant=self.node_address,
total_deposit=total_deposit,
partner=partner,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
transaction_executed = gas_limit is not None
if not transaction_executed or receipt_or_none:
if transaction_executed:
block = receipt_or_none['blockNumber']
else:
block = checking_block
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='setTotalDeposit',
transaction_executed=transaction_executed,
required_gas=GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT,
block_identifier=block,
)
error_type, msg = self._check_why_deposit_failed(
channel_identifier=channel_identifier,
partner=partner,
token=token,
amount_to_deposit=amount_to_deposit,
total_deposit=total_deposit,
transaction_executed=transaction_executed,
block_identifier=block,
)
error_msg = f'{error_prefix}. {msg}'
if error_type == RaidenRecoverableError:
log.warning(error_msg, **log_details)
else:
log.critical(error_msg, **log_details)
raise error_type(error_msg)
log.info('setTotalDeposit successful', **log_details) | python | def set_total_deposit(
self,
given_block_identifier: BlockSpecification,
channel_identifier: ChannelID,
total_deposit: TokenAmount,
partner: Address,
):
if not isinstance(total_deposit, int):
raise ValueError('total_deposit needs to be an integer number.')
token_address = self.token_address()
token = Token(
jsonrpc_client=self.client,
token_address=token_address,
contract_manager=self.contract_manager,
)
checking_block = self.client.get_checking_block()
error_prefix = 'setTotalDeposit call will fail'
with self.channel_operations_lock[partner], self.deposit_lock:
previous_total_deposit = self._detail_participant(
channel_identifier=channel_identifier,
participant=self.node_address,
partner=partner,
block_identifier=given_block_identifier,
).deposit
amount_to_deposit = TokenAmount(total_deposit - previous_total_deposit)
log_details = {
'token_network': pex(self.address),
'channel_identifier': channel_identifier,
'node': pex(self.node_address),
'partner': pex(partner),
'new_total_deposit': total_deposit,
'previous_total_deposit': previous_total_deposit,
}
try:
self._deposit_preconditions(
channel_identifier=channel_identifier,
total_deposit=total_deposit,
partner=partner,
token=token,
previous_total_deposit=previous_total_deposit,
log_details=log_details,
block_identifier=given_block_identifier,
)
except NoStateForBlockIdentifier:
# If preconditions end up being on pruned state skip them. Estimate
# gas will stop us from sending a transaction that will fail
pass
# If there are channels being set up concurrenlty either the
# allowance must be accumulated *or* the calls to `approve` and
# `setTotalDeposit` must be serialized. This is necessary otherwise
# the deposit will fail.
#
# Calls to approve and setTotalDeposit are serialized with the
# deposit_lock to avoid transaction failure, because with two
# concurrent deposits, we may have the transactions executed in the
# following order
#
# - approve
# - approve
# - setTotalDeposit
# - setTotalDeposit
#
# in which case the second `approve` will overwrite the first,
# and the first `setTotalDeposit` will consume the allowance,
# making the second deposit fail.
token.approve(
allowed_address=Address(self.address),
allowance=amount_to_deposit,
)
gas_limit = self.proxy.estimate_gas(
checking_block,
'setTotalDeposit',
channel_identifier=channel_identifier,
participant=self.node_address,
total_deposit=total_deposit,
partner=partner,
)
if gas_limit:
gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT)
error_prefix = 'setTotalDeposit call failed'
log.debug('setTotalDeposit called', **log_details)
transaction_hash = self.proxy.transact(
'setTotalDeposit',
gas_limit,
channel_identifier=channel_identifier,
participant=self.node_address,
total_deposit=total_deposit,
partner=partner,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
transaction_executed = gas_limit is not None
if not transaction_executed or receipt_or_none:
if transaction_executed:
block = receipt_or_none['blockNumber']
else:
block = checking_block
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='setTotalDeposit',
transaction_executed=transaction_executed,
required_gas=GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT,
block_identifier=block,
)
error_type, msg = self._check_why_deposit_failed(
channel_identifier=channel_identifier,
partner=partner,
token=token,
amount_to_deposit=amount_to_deposit,
total_deposit=total_deposit,
transaction_executed=transaction_executed,
block_identifier=block,
)
error_msg = f'{error_prefix}. {msg}'
if error_type == RaidenRecoverableError:
log.warning(error_msg, **log_details)
else:
log.critical(error_msg, **log_details)
raise error_type(error_msg)
log.info('setTotalDeposit successful', **log_details) | [
"def",
"set_total_deposit",
"(",
"self",
",",
"given_block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
",",
"total_deposit",
":",
"TokenAmount",
",",
"partner",
":",
"Address",
",",
")",
":",
"if",
"not",
"isinstance",
"(",... | Set channel's total deposit.
`total_deposit` has to be monotonically increasing, this is enforced by
the `TokenNetwork` smart contract. This is done for the same reason why
the balance proofs have a monotonically increasing transferred amount,
it simplifies the analysis of bad behavior and the handling code of
out-dated balance proofs.
Races to `set_total_deposit` are handled by the smart contract, where
largest total deposit wins. The end balance of the funding accounts is
undefined. E.g.
- Acc1 calls set_total_deposit with 10 tokens
- Acc2 calls set_total_deposit with 13 tokens
- If Acc2's transaction is mined first, then Acc1 token supply is left intact.
- If Acc1's transaction is mined first, then Acc2 will only move 3 tokens.
Races for the same account don't have any unexpeted side-effect.
Raises:
DepositMismatch: If the new request total deposit is lower than the
existing total deposit on-chain for the `given_block_identifier`.
RaidenRecoverableError: If the channel was closed meanwhile the
deposit was in transit.
RaidenUnrecoverableError: If the transaction was sucessful and the
deposit_amount is not as large as the requested value.
RuntimeError: If the token address is empty.
ValueError: If an argument is of the invalid type. | [
"Set",
"channel",
"s",
"total",
"deposit",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L681-L837 |
235,375 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.close | def close(
self,
channel_identifier: ChannelID,
partner: Address,
balance_hash: BalanceHash,
nonce: Nonce,
additional_hash: AdditionalHash,
signature: Signature,
given_block_identifier: BlockSpecification,
):
""" Close the channel using the provided balance proof.
Note:
This method must *not* be called without updating the application
state, otherwise the node may accept new transfers which cannot be
used, because the closer is not allowed to update the balance proof
submitted on chain after closing
Raises:
RaidenRecoverableError: If the channel is already closed.
RaidenUnrecoverableError: If the channel does not exist or is settled.
"""
log_details = {
'token_network': pex(self.address),
'node': pex(self.node_address),
'partner': pex(partner),
'nonce': nonce,
'balance_hash': encode_hex(balance_hash),
'additional_hash': encode_hex(additional_hash),
'signature': encode_hex(signature),
}
log.debug('closeChannel called', **log_details)
checking_block = self.client.get_checking_block()
try:
self._close_preconditions(
channel_identifier,
partner=partner,
block_identifier=given_block_identifier,
)
except NoStateForBlockIdentifier:
# If preconditions end up being on pruned state skip them. Estimate
# gas will stop us from sending a transaction that will fail
pass
error_prefix = 'closeChannel call will fail'
with self.channel_operations_lock[partner]:
gas_limit = self.proxy.estimate_gas(
checking_block,
'closeChannel',
channel_identifier=channel_identifier,
partner=partner,
balance_hash=balance_hash,
nonce=nonce,
additional_hash=additional_hash,
signature=signature,
)
if gas_limit:
error_prefix = 'closeChannel call failed'
transaction_hash = self.proxy.transact(
'closeChannel',
safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_CLOSE_CHANNEL),
channel_identifier=channel_identifier,
partner=partner,
balance_hash=balance_hash,
nonce=nonce,
additional_hash=additional_hash,
signature=signature,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
transaction_executed = gas_limit is not None
if not transaction_executed or receipt_or_none:
if transaction_executed:
block = receipt_or_none['blockNumber']
else:
block = checking_block
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='closeChannel',
transaction_executed=transaction_executed,
required_gas=GAS_REQUIRED_FOR_CLOSE_CHANNEL,
block_identifier=block,
)
error_type, msg = self._check_channel_state_for_close(
participant1=self.node_address,
participant2=partner,
block_identifier=block,
channel_identifier=channel_identifier,
)
if not error_type:
# error_type can also be None above in which case it's
# unknown reason why we would fail.
error_type = RaidenUnrecoverableError
error_msg = f'{error_prefix}. {msg}'
if error_type == RaidenRecoverableError:
log.warning(error_msg, **log_details)
else:
log.critical(error_msg, **log_details)
raise error_type(error_msg)
log.info('closeChannel successful', **log_details) | python | def close(
self,
channel_identifier: ChannelID,
partner: Address,
balance_hash: BalanceHash,
nonce: Nonce,
additional_hash: AdditionalHash,
signature: Signature,
given_block_identifier: BlockSpecification,
):
log_details = {
'token_network': pex(self.address),
'node': pex(self.node_address),
'partner': pex(partner),
'nonce': nonce,
'balance_hash': encode_hex(balance_hash),
'additional_hash': encode_hex(additional_hash),
'signature': encode_hex(signature),
}
log.debug('closeChannel called', **log_details)
checking_block = self.client.get_checking_block()
try:
self._close_preconditions(
channel_identifier,
partner=partner,
block_identifier=given_block_identifier,
)
except NoStateForBlockIdentifier:
# If preconditions end up being on pruned state skip them. Estimate
# gas will stop us from sending a transaction that will fail
pass
error_prefix = 'closeChannel call will fail'
with self.channel_operations_lock[partner]:
gas_limit = self.proxy.estimate_gas(
checking_block,
'closeChannel',
channel_identifier=channel_identifier,
partner=partner,
balance_hash=balance_hash,
nonce=nonce,
additional_hash=additional_hash,
signature=signature,
)
if gas_limit:
error_prefix = 'closeChannel call failed'
transaction_hash = self.proxy.transact(
'closeChannel',
safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_CLOSE_CHANNEL),
channel_identifier=channel_identifier,
partner=partner,
balance_hash=balance_hash,
nonce=nonce,
additional_hash=additional_hash,
signature=signature,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
transaction_executed = gas_limit is not None
if not transaction_executed or receipt_or_none:
if transaction_executed:
block = receipt_or_none['blockNumber']
else:
block = checking_block
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='closeChannel',
transaction_executed=transaction_executed,
required_gas=GAS_REQUIRED_FOR_CLOSE_CHANNEL,
block_identifier=block,
)
error_type, msg = self._check_channel_state_for_close(
participant1=self.node_address,
participant2=partner,
block_identifier=block,
channel_identifier=channel_identifier,
)
if not error_type:
# error_type can also be None above in which case it's
# unknown reason why we would fail.
error_type = RaidenUnrecoverableError
error_msg = f'{error_prefix}. {msg}'
if error_type == RaidenRecoverableError:
log.warning(error_msg, **log_details)
else:
log.critical(error_msg, **log_details)
raise error_type(error_msg)
log.info('closeChannel successful', **log_details) | [
"def",
"close",
"(",
"self",
",",
"channel_identifier",
":",
"ChannelID",
",",
"partner",
":",
"Address",
",",
"balance_hash",
":",
"BalanceHash",
",",
"nonce",
":",
"Nonce",
",",
"additional_hash",
":",
"AdditionalHash",
",",
"signature",
":",
"Signature",
",... | Close the channel using the provided balance proof.
Note:
This method must *not* be called without updating the application
state, otherwise the node may accept new transfers which cannot be
used, because the closer is not allowed to update the balance proof
submitted on chain after closing
Raises:
RaidenRecoverableError: If the channel is already closed.
RaidenUnrecoverableError: If the channel does not exist or is settled. | [
"Close",
"the",
"channel",
"using",
"the",
"provided",
"balance",
"proof",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L928-L1033 |
235,376 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.settle | def settle(
self,
channel_identifier: ChannelID,
transferred_amount: TokenAmount,
locked_amount: TokenAmount,
locksroot: Locksroot,
partner: Address,
partner_transferred_amount: TokenAmount,
partner_locked_amount: TokenAmount,
partner_locksroot: Locksroot,
given_block_identifier: BlockSpecification,
):
""" Settle the channel. """
log_details = {
'channel_identifier': channel_identifier,
'token_network': pex(self.address),
'node': pex(self.node_address),
'partner': pex(partner),
'transferred_amount': transferred_amount,
'locked_amount': locked_amount,
'locksroot': encode_hex(locksroot),
'partner_transferred_amount': partner_transferred_amount,
'partner_locked_amount': partner_locked_amount,
'partner_locksroot': encode_hex(partner_locksroot),
}
log.debug('settle called', **log_details)
checking_block = self.client.get_checking_block()
# and now find out
our_maximum = transferred_amount + locked_amount
partner_maximum = partner_transferred_amount + partner_locked_amount
# The second participant transferred + locked amount must be higher
our_bp_is_larger = our_maximum > partner_maximum
if our_bp_is_larger:
kwargs = {
'participant1': partner,
'participant1_transferred_amount': partner_transferred_amount,
'participant1_locked_amount': partner_locked_amount,
'participant1_locksroot': partner_locksroot,
'participant2': self.node_address,
'participant2_transferred_amount': transferred_amount,
'participant2_locked_amount': locked_amount,
'participant2_locksroot': locksroot,
}
else:
kwargs = {
'participant1': self.node_address,
'participant1_transferred_amount': transferred_amount,
'participant1_locked_amount': locked_amount,
'participant1_locksroot': locksroot,
'participant2': partner,
'participant2_transferred_amount': partner_transferred_amount,
'participant2_locked_amount': partner_locked_amount,
'participant2_locksroot': partner_locksroot,
}
try:
self._settle_preconditions(
channel_identifier=channel_identifier,
partner=partner,
block_identifier=given_block_identifier,
)
except NoStateForBlockIdentifier:
# If preconditions end up being on pruned state skip them. Estimate
# gas will stop us from sending a transaction that will fail
pass
with self.channel_operations_lock[partner]:
error_prefix = 'Call to settle will fail'
gas_limit = self.proxy.estimate_gas(
checking_block,
'settleChannel',
channel_identifier=channel_identifier,
**kwargs,
)
if gas_limit:
error_prefix = 'settle call failed'
gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SETTLE_CHANNEL)
transaction_hash = self.proxy.transact(
'settleChannel',
gas_limit,
channel_identifier=channel_identifier,
**kwargs,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
transaction_executed = gas_limit is not None
if not transaction_executed or receipt_or_none:
if transaction_executed:
block = receipt_or_none['blockNumber']
else:
block = checking_block
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='settleChannel',
transaction_executed=transaction_executed,
required_gas=GAS_REQUIRED_FOR_SETTLE_CHANNEL,
block_identifier=block,
)
msg = self._check_channel_state_after_settle(
participant1=self.node_address,
participant2=partner,
block_identifier=block,
channel_identifier=channel_identifier,
)
error_msg = f'{error_prefix}. {msg}'
log.critical(error_msg, **log_details)
raise RaidenUnrecoverableError(error_msg)
log.info('settle successful', **log_details) | python | def settle(
self,
channel_identifier: ChannelID,
transferred_amount: TokenAmount,
locked_amount: TokenAmount,
locksroot: Locksroot,
partner: Address,
partner_transferred_amount: TokenAmount,
partner_locked_amount: TokenAmount,
partner_locksroot: Locksroot,
given_block_identifier: BlockSpecification,
):
log_details = {
'channel_identifier': channel_identifier,
'token_network': pex(self.address),
'node': pex(self.node_address),
'partner': pex(partner),
'transferred_amount': transferred_amount,
'locked_amount': locked_amount,
'locksroot': encode_hex(locksroot),
'partner_transferred_amount': partner_transferred_amount,
'partner_locked_amount': partner_locked_amount,
'partner_locksroot': encode_hex(partner_locksroot),
}
log.debug('settle called', **log_details)
checking_block = self.client.get_checking_block()
# and now find out
our_maximum = transferred_amount + locked_amount
partner_maximum = partner_transferred_amount + partner_locked_amount
# The second participant transferred + locked amount must be higher
our_bp_is_larger = our_maximum > partner_maximum
if our_bp_is_larger:
kwargs = {
'participant1': partner,
'participant1_transferred_amount': partner_transferred_amount,
'participant1_locked_amount': partner_locked_amount,
'participant1_locksroot': partner_locksroot,
'participant2': self.node_address,
'participant2_transferred_amount': transferred_amount,
'participant2_locked_amount': locked_amount,
'participant2_locksroot': locksroot,
}
else:
kwargs = {
'participant1': self.node_address,
'participant1_transferred_amount': transferred_amount,
'participant1_locked_amount': locked_amount,
'participant1_locksroot': locksroot,
'participant2': partner,
'participant2_transferred_amount': partner_transferred_amount,
'participant2_locked_amount': partner_locked_amount,
'participant2_locksroot': partner_locksroot,
}
try:
self._settle_preconditions(
channel_identifier=channel_identifier,
partner=partner,
block_identifier=given_block_identifier,
)
except NoStateForBlockIdentifier:
# If preconditions end up being on pruned state skip them. Estimate
# gas will stop us from sending a transaction that will fail
pass
with self.channel_operations_lock[partner]:
error_prefix = 'Call to settle will fail'
gas_limit = self.proxy.estimate_gas(
checking_block,
'settleChannel',
channel_identifier=channel_identifier,
**kwargs,
)
if gas_limit:
error_prefix = 'settle call failed'
gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SETTLE_CHANNEL)
transaction_hash = self.proxy.transact(
'settleChannel',
gas_limit,
channel_identifier=channel_identifier,
**kwargs,
)
self.client.poll(transaction_hash)
receipt_or_none = check_transaction_threw(self.client, transaction_hash)
transaction_executed = gas_limit is not None
if not transaction_executed or receipt_or_none:
if transaction_executed:
block = receipt_or_none['blockNumber']
else:
block = checking_block
self.proxy.jsonrpc_client.check_for_insufficient_eth(
transaction_name='settleChannel',
transaction_executed=transaction_executed,
required_gas=GAS_REQUIRED_FOR_SETTLE_CHANNEL,
block_identifier=block,
)
msg = self._check_channel_state_after_settle(
participant1=self.node_address,
participant2=partner,
block_identifier=block,
channel_identifier=channel_identifier,
)
error_msg = f'{error_prefix}. {msg}'
log.critical(error_msg, **log_details)
raise RaidenUnrecoverableError(error_msg)
log.info('settle successful', **log_details) | [
"def",
"settle",
"(",
"self",
",",
"channel_identifier",
":",
"ChannelID",
",",
"transferred_amount",
":",
"TokenAmount",
",",
"locked_amount",
":",
"TokenAmount",
",",
"locksroot",
":",
"Locksroot",
",",
"partner",
":",
"Address",
",",
"partner_transferred_amount",... | Settle the channel. | [
"Settle",
"the",
"channel",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1337-L1449 |
235,377 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.events_filter | def events_filter(
self,
topics: List[str] = None,
from_block: BlockSpecification = None,
to_block: BlockSpecification = None,
) -> StatelessFilter:
""" Install a new filter for an array of topics emitted by the contract.
Args:
topics: A list of event ids to filter for. Can also be None,
in which case all events are queried.
from_block: The block number at which to start looking for events.
to_block: The block number at which to stop looking for events.
Return:
Filter: The filter instance.
"""
return self.client.new_filter(
self.address,
topics=topics,
from_block=from_block,
to_block=to_block,
) | python | def events_filter(
self,
topics: List[str] = None,
from_block: BlockSpecification = None,
to_block: BlockSpecification = None,
) -> StatelessFilter:
return self.client.new_filter(
self.address,
topics=topics,
from_block=from_block,
to_block=to_block,
) | [
"def",
"events_filter",
"(",
"self",
",",
"topics",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"from_block",
":",
"BlockSpecification",
"=",
"None",
",",
"to_block",
":",
"BlockSpecification",
"=",
"None",
",",
")",
"->",
"StatelessFilter",
":",
"retu... | Install a new filter for an array of topics emitted by the contract.
Args:
topics: A list of event ids to filter for. Can also be None,
in which case all events are queried.
from_block: The block number at which to start looking for events.
to_block: The block number at which to stop looking for events.
Return:
Filter: The filter instance. | [
"Install",
"a",
"new",
"filter",
"for",
"an",
"array",
"of",
"topics",
"emitted",
"by",
"the",
"contract",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1451-L1472 |
235,378 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork.all_events_filter | def all_events_filter(
self,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> StatelessFilter:
""" Install a new filter for all the events emitted by the current token network contract
Args:
from_block: Create filter starting from this block number (default: 0).
to_block: Create filter stopping at this block number (default: 'latest').
Return:
The filter instance.
"""
return self.events_filter(None, from_block, to_block) | python | def all_events_filter(
self,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> StatelessFilter:
return self.events_filter(None, from_block, to_block) | [
"def",
"all_events_filter",
"(",
"self",
",",
"from_block",
":",
"BlockSpecification",
"=",
"GENESIS_BLOCK_NUMBER",
",",
"to_block",
":",
"BlockSpecification",
"=",
"'latest'",
",",
")",
"->",
"StatelessFilter",
":",
"return",
"self",
".",
"events_filter",
"(",
"N... | Install a new filter for all the events emitted by the current token network contract
Args:
from_block: Create filter starting from this block number (default: 0).
to_block: Create filter stopping at this block number (default: 'latest').
Return:
The filter instance. | [
"Install",
"a",
"new",
"filter",
"for",
"all",
"the",
"events",
"emitted",
"by",
"the",
"current",
"token",
"network",
"contract"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1474-L1488 |
235,379 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork._check_for_outdated_channel | def _check_for_outdated_channel(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> None:
"""
Checks whether an operation is being executed on a channel
between two participants using an old channel identifier
"""
try:
onchain_channel_details = self._detail_channel(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
)
except RaidenRecoverableError:
return
onchain_channel_identifier = onchain_channel_details.channel_identifier
if onchain_channel_identifier != channel_identifier:
raise ChannelOutdatedError(
'Current channel identifier is outdated. '
f'current={channel_identifier}, '
f'new={onchain_channel_identifier}',
) | python | def _check_for_outdated_channel(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> None:
try:
onchain_channel_details = self._detail_channel(
participant1=participant1,
participant2=participant2,
block_identifier=block_identifier,
)
except RaidenRecoverableError:
return
onchain_channel_identifier = onchain_channel_details.channel_identifier
if onchain_channel_identifier != channel_identifier:
raise ChannelOutdatedError(
'Current channel identifier is outdated. '
f'current={channel_identifier}, '
f'new={onchain_channel_identifier}',
) | [
"def",
"_check_for_outdated_channel",
"(",
"self",
",",
"participant1",
":",
"Address",
",",
"participant2",
":",
"Address",
",",
"block_identifier",
":",
"BlockSpecification",
",",
"channel_identifier",
":",
"ChannelID",
",",
")",
"->",
"None",
":",
"try",
":",
... | Checks whether an operation is being executed on a channel
between two participants using an old channel identifier | [
"Checks",
"whether",
"an",
"operation",
"is",
"being",
"executed",
"on",
"a",
"channel",
"between",
"two",
"participants",
"using",
"an",
"old",
"channel",
"identifier"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1490-L1517 |
235,380 | raiden-network/raiden | raiden/network/proxies/token_network.py | TokenNetwork._check_channel_state_for_update | def _check_channel_state_for_update(
self,
channel_identifier: ChannelID,
closer: Address,
update_nonce: Nonce,
block_identifier: BlockSpecification,
) -> Optional[str]:
"""Check the channel state on chain to see if it has been updated.
Compare the nonce, we are about to update the contract with, with the
updated nonce in the onchain state and, if it's the same, return a
message with which the caller should raise a RaidenRecoverableError.
If all is okay return None.
"""
msg = None
closer_details = self._detail_participant(
channel_identifier=channel_identifier,
participant=closer,
partner=self.node_address,
block_identifier=block_identifier,
)
if closer_details.nonce == update_nonce:
msg = (
'updateNonClosingBalanceProof transaction has already '
'been mined and updated the channel succesfully.'
)
return msg | python | def _check_channel_state_for_update(
self,
channel_identifier: ChannelID,
closer: Address,
update_nonce: Nonce,
block_identifier: BlockSpecification,
) -> Optional[str]:
msg = None
closer_details = self._detail_participant(
channel_identifier=channel_identifier,
participant=closer,
partner=self.node_address,
block_identifier=block_identifier,
)
if closer_details.nonce == update_nonce:
msg = (
'updateNonClosingBalanceProof transaction has already '
'been mined and updated the channel succesfully.'
)
return msg | [
"def",
"_check_channel_state_for_update",
"(",
"self",
",",
"channel_identifier",
":",
"ChannelID",
",",
"closer",
":",
"Address",
",",
"update_nonce",
":",
"Nonce",
",",
"block_identifier",
":",
"BlockSpecification",
",",
")",
"->",
"Optional",
"[",
"str",
"]",
... | Check the channel state on chain to see if it has been updated.
Compare the nonce, we are about to update the contract with, with the
updated nonce in the onchain state and, if it's the same, return a
message with which the caller should raise a RaidenRecoverableError.
If all is okay return None. | [
"Check",
"the",
"channel",
"state",
"on",
"chain",
"to",
"see",
"if",
"it",
"has",
"been",
"updated",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1624-L1652 |
235,381 | raiden-network/raiden | raiden/network/transport/udp/udp_utils.py | event_first_of | def event_first_of(*events: _AbstractLinkable) -> Event:
""" Waits until one of `events` is set.
The event returned is /not/ cleared with any of the `events`, this value
must not be reused if the clearing behavior is used.
"""
first_finished = Event()
if not all(isinstance(e, _AbstractLinkable) for e in events):
raise ValueError('all events must be linkable')
for event in events:
event.rawlink(lambda _: first_finished.set())
return first_finished | python | def event_first_of(*events: _AbstractLinkable) -> Event:
first_finished = Event()
if not all(isinstance(e, _AbstractLinkable) for e in events):
raise ValueError('all events must be linkable')
for event in events:
event.rawlink(lambda _: first_finished.set())
return first_finished | [
"def",
"event_first_of",
"(",
"*",
"events",
":",
"_AbstractLinkable",
")",
"->",
"Event",
":",
"first_finished",
"=",
"Event",
"(",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"e",
",",
"_AbstractLinkable",
")",
"for",
"e",
"in",
"events",
")",
":"... | Waits until one of `events` is set.
The event returned is /not/ cleared with any of the `events`, this value
must not be reused if the clearing behavior is used. | [
"Waits",
"until",
"one",
"of",
"events",
"is",
"set",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L18-L32 |
235,382 | raiden-network/raiden | raiden/network/transport/udp/udp_utils.py | timeout_exponential_backoff | def timeout_exponential_backoff(
retries: int,
timeout: int,
maximum: int,
) -> Iterator[int]:
""" Timeouts generator with an exponential backoff strategy.
Timeouts start spaced by `timeout`, after `retries` exponentially increase
the retry delays until `maximum`, then maximum is returned indefinitely.
"""
yield timeout
tries = 1
while tries < retries:
tries += 1
yield timeout
while timeout < maximum:
timeout = min(timeout * 2, maximum)
yield timeout
while True:
yield maximum | python | def timeout_exponential_backoff(
retries: int,
timeout: int,
maximum: int,
) -> Iterator[int]:
yield timeout
tries = 1
while tries < retries:
tries += 1
yield timeout
while timeout < maximum:
timeout = min(timeout * 2, maximum)
yield timeout
while True:
yield maximum | [
"def",
"timeout_exponential_backoff",
"(",
"retries",
":",
"int",
",",
"timeout",
":",
"int",
",",
"maximum",
":",
"int",
",",
")",
"->",
"Iterator",
"[",
"int",
"]",
":",
"yield",
"timeout",
"tries",
"=",
"1",
"while",
"tries",
"<",
"retries",
":",
"t... | Timeouts generator with an exponential backoff strategy.
Timeouts start spaced by `timeout`, after `retries` exponentially increase
the retry delays until `maximum`, then maximum is returned indefinitely. | [
"Timeouts",
"generator",
"with",
"an",
"exponential",
"backoff",
"strategy",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L35-L57 |
235,383 | raiden-network/raiden | raiden/network/transport/udp/udp_utils.py | timeout_two_stage | def timeout_two_stage(
retries: int,
timeout1: int,
timeout2: int,
) -> Iterable[int]:
""" Timeouts generator with a two stage strategy
Timeouts start spaced by `timeout1`, after `retries` increase
to `timeout2` which is repeated indefinitely.
"""
for _ in range(retries):
yield timeout1
while True:
yield timeout2 | python | def timeout_two_stage(
retries: int,
timeout1: int,
timeout2: int,
) -> Iterable[int]:
for _ in range(retries):
yield timeout1
while True:
yield timeout2 | [
"def",
"timeout_two_stage",
"(",
"retries",
":",
"int",
",",
"timeout1",
":",
"int",
",",
"timeout2",
":",
"int",
",",
")",
"->",
"Iterable",
"[",
"int",
"]",
":",
"for",
"_",
"in",
"range",
"(",
"retries",
")",
":",
"yield",
"timeout1",
"while",
"Tr... | Timeouts generator with a two stage strategy
Timeouts start spaced by `timeout1`, after `retries` increase
to `timeout2` which is repeated indefinitely. | [
"Timeouts",
"generator",
"with",
"a",
"two",
"stage",
"strategy"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L60-L73 |
235,384 | raiden-network/raiden | raiden/network/transport/udp/udp_utils.py | retry | def retry(
transport: 'UDPTransport',
messagedata: bytes,
message_id: UDPMessageID,
recipient: Address,
stop_event: Event,
timeout_backoff: Iterable[int],
) -> bool:
""" Send messagedata until it's acknowledged.
Exit when:
- The message is delivered.
- Event_stop is set.
- The iterator timeout_backoff runs out.
Returns:
bool: True if the message was acknowledged, False otherwise.
"""
async_result = transport.maybe_sendraw_with_result(
recipient,
messagedata,
message_id,
)
event_quit = event_first_of(
async_result,
stop_event,
)
for timeout in timeout_backoff:
if event_quit.wait(timeout=timeout) is True:
break
log.debug(
'retrying message',
node=pex(transport.raiden.address),
recipient=pex(recipient),
msgid=message_id,
)
transport.maybe_sendraw_with_result(
recipient,
messagedata,
message_id,
)
return async_result.ready() | python | def retry(
transport: 'UDPTransport',
messagedata: bytes,
message_id: UDPMessageID,
recipient: Address,
stop_event: Event,
timeout_backoff: Iterable[int],
) -> bool:
async_result = transport.maybe_sendraw_with_result(
recipient,
messagedata,
message_id,
)
event_quit = event_first_of(
async_result,
stop_event,
)
for timeout in timeout_backoff:
if event_quit.wait(timeout=timeout) is True:
break
log.debug(
'retrying message',
node=pex(transport.raiden.address),
recipient=pex(recipient),
msgid=message_id,
)
transport.maybe_sendraw_with_result(
recipient,
messagedata,
message_id,
)
return async_result.ready() | [
"def",
"retry",
"(",
"transport",
":",
"'UDPTransport'",
",",
"messagedata",
":",
"bytes",
",",
"message_id",
":",
"UDPMessageID",
",",
"recipient",
":",
"Address",
",",
"stop_event",
":",
"Event",
",",
"timeout_backoff",
":",
"Iterable",
"[",
"int",
"]",
",... | Send messagedata until it's acknowledged.
Exit when:
- The message is delivered.
- Event_stop is set.
- The iterator timeout_backoff runs out.
Returns:
bool: True if the message was acknowledged, False otherwise. | [
"Send",
"messagedata",
"until",
"it",
"s",
"acknowledged",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L76-L125 |
235,385 | raiden-network/raiden | raiden/network/transport/udp/udp_utils.py | retry_with_recovery | def retry_with_recovery(
transport: 'UDPTransport',
messagedata: bytes,
message_id: UDPMessageID,
recipient: Address,
stop_event: Event,
event_healthy: Event,
event_unhealthy: Event,
backoff: Iterable[int],
) -> bool:
""" Send messagedata while the node is healthy until it's acknowledged.
Note:
backoff must be an infinite iterator, otherwise this task will
become a hot loop.
"""
# The underlying unhealthy will be cleared, care must be taken to properly
# clear stop_or_unhealthy too.
stop_or_unhealthy = event_first_of(
stop_event,
event_unhealthy,
)
acknowledged = False
while not stop_event.is_set() and not acknowledged:
# Packets must not be sent to an unhealthy node, nor should the task
# wait for it to become available if the message has been acknowledged.
if event_unhealthy.is_set():
log.debug(
'waiting for recipient to become available',
node=pex(transport.raiden.address),
recipient=pex(recipient),
)
wait_recovery(
stop_event,
event_healthy,
)
# Assume wait_recovery returned because unhealthy was cleared and
# continue execution, this is safe to do because stop_event is
# checked below.
stop_or_unhealthy.clear()
if stop_event.is_set():
return acknowledged
acknowledged = retry(
transport,
messagedata,
message_id,
recipient,
# retry will stop when this event is set, allowing this task to
# wait for recovery when the node becomes unhealthy or to quit if
# the stop event is set.
stop_or_unhealthy,
# Intentionally reusing backoff to restart from the last
# timeout/number of iterations.
backoff,
)
return acknowledged | python | def retry_with_recovery(
transport: 'UDPTransport',
messagedata: bytes,
message_id: UDPMessageID,
recipient: Address,
stop_event: Event,
event_healthy: Event,
event_unhealthy: Event,
backoff: Iterable[int],
) -> bool:
# The underlying unhealthy will be cleared, care must be taken to properly
# clear stop_or_unhealthy too.
stop_or_unhealthy = event_first_of(
stop_event,
event_unhealthy,
)
acknowledged = False
while not stop_event.is_set() and not acknowledged:
# Packets must not be sent to an unhealthy node, nor should the task
# wait for it to become available if the message has been acknowledged.
if event_unhealthy.is_set():
log.debug(
'waiting for recipient to become available',
node=pex(transport.raiden.address),
recipient=pex(recipient),
)
wait_recovery(
stop_event,
event_healthy,
)
# Assume wait_recovery returned because unhealthy was cleared and
# continue execution, this is safe to do because stop_event is
# checked below.
stop_or_unhealthy.clear()
if stop_event.is_set():
return acknowledged
acknowledged = retry(
transport,
messagedata,
message_id,
recipient,
# retry will stop when this event is set, allowing this task to
# wait for recovery when the node becomes unhealthy or to quit if
# the stop event is set.
stop_or_unhealthy,
# Intentionally reusing backoff to restart from the last
# timeout/number of iterations.
backoff,
)
return acknowledged | [
"def",
"retry_with_recovery",
"(",
"transport",
":",
"'UDPTransport'",
",",
"messagedata",
":",
"bytes",
",",
"message_id",
":",
"UDPMessageID",
",",
"recipient",
":",
"Address",
",",
"stop_event",
":",
"Event",
",",
"event_healthy",
":",
"Event",
",",
"event_un... | Send messagedata while the node is healthy until it's acknowledged.
Note:
backoff must be an infinite iterator, otherwise this task will
become a hot loop. | [
"Send",
"messagedata",
"while",
"the",
"node",
"is",
"healthy",
"until",
"it",
"s",
"acknowledged",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L142-L206 |
235,386 | raiden-network/raiden | raiden/network/proxies/secret_registry.py | SecretRegistry.get_secret_registration_block_by_secrethash | def get_secret_registration_block_by_secrethash(
self,
secrethash: SecretHash,
block_identifier: BlockSpecification,
) -> Optional[BlockNumber]:
"""Return the block number at which the secret for `secrethash` was
registered, None if the secret was never registered.
"""
result = self.proxy.contract.functions.getSecretRevealBlockHeight(
secrethash,
).call(block_identifier=block_identifier)
# Block 0 either represents the genesis block or an empty entry in the
# secret mapping. This is important for custom genesis files used while
# testing. To avoid problems the smart contract can be added as part of
# the genesis file, however it's important for its storage to be
# empty.
if result == 0:
return None
return result | python | def get_secret_registration_block_by_secrethash(
self,
secrethash: SecretHash,
block_identifier: BlockSpecification,
) -> Optional[BlockNumber]:
result = self.proxy.contract.functions.getSecretRevealBlockHeight(
secrethash,
).call(block_identifier=block_identifier)
# Block 0 either represents the genesis block or an empty entry in the
# secret mapping. This is important for custom genesis files used while
# testing. To avoid problems the smart contract can be added as part of
# the genesis file, however it's important for its storage to be
# empty.
if result == 0:
return None
return result | [
"def",
"get_secret_registration_block_by_secrethash",
"(",
"self",
",",
"secrethash",
":",
"SecretHash",
",",
"block_identifier",
":",
"BlockSpecification",
",",
")",
"->",
"Optional",
"[",
"BlockNumber",
"]",
":",
"result",
"=",
"self",
".",
"proxy",
".",
"contra... | Return the block number at which the secret for `secrethash` was
registered, None if the secret was never registered. | [
"Return",
"the",
"block",
"number",
"at",
"which",
"the",
"secret",
"for",
"secrethash",
"was",
"registered",
"None",
"if",
"the",
"secret",
"was",
"never",
"registered",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/secret_registry.py#L303-L323 |
235,387 | raiden-network/raiden | raiden/network/proxies/secret_registry.py | SecretRegistry.is_secret_registered | def is_secret_registered(
self,
secrethash: SecretHash,
block_identifier: BlockSpecification,
) -> bool:
"""True if the secret for `secrethash` is registered at `block_identifier`.
Throws NoStateForBlockIdentifier if the given block_identifier
is older than the pruning limit
"""
if not self.client.can_query_state_for_block(block_identifier):
raise NoStateForBlockIdentifier()
block = self.get_secret_registration_block_by_secrethash(
secrethash=secrethash,
block_identifier=block_identifier,
)
return block is not None | python | def is_secret_registered(
self,
secrethash: SecretHash,
block_identifier: BlockSpecification,
) -> bool:
if not self.client.can_query_state_for_block(block_identifier):
raise NoStateForBlockIdentifier()
block = self.get_secret_registration_block_by_secrethash(
secrethash=secrethash,
block_identifier=block_identifier,
)
return block is not None | [
"def",
"is_secret_registered",
"(",
"self",
",",
"secrethash",
":",
"SecretHash",
",",
"block_identifier",
":",
"BlockSpecification",
",",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"client",
".",
"can_query_state_for_block",
"(",
"block_identifier",
")",
... | True if the secret for `secrethash` is registered at `block_identifier`.
Throws NoStateForBlockIdentifier if the given block_identifier
is older than the pruning limit | [
"True",
"if",
"the",
"secret",
"for",
"secrethash",
"is",
"registered",
"at",
"block_identifier",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/secret_registry.py#L325-L342 |
235,388 | raiden-network/raiden | raiden/ui/console.py | ConsoleTools.register_token | def register_token(
self,
registry_address_hex: typing.AddressHex,
token_address_hex: typing.AddressHex,
retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
) -> TokenNetwork:
""" Register a token with the raiden token manager.
Args:
registry_address: registry address
token_address_hex (string): a hex encoded token address.
Returns:
The token network proxy.
"""
registry_address = decode_hex(registry_address_hex)
token_address = decode_hex(token_address_hex)
registry = self._raiden.chain.token_network_registry(registry_address)
contracts_version = self._raiden.contract_manager.contracts_version
if contracts_version == DEVELOPMENT_CONTRACT_VERSION:
token_network_address = registry.add_token_with_limits(
token_address=token_address,
channel_participant_deposit_limit=UINT256_MAX,
token_network_deposit_limit=UINT256_MAX,
)
else:
token_network_address = registry.add_token_without_limits(
token_address=token_address,
)
# Register the channel manager with the raiden registry
waiting.wait_for_payment_network(
self._raiden,
registry.address,
token_address,
retry_timeout,
)
return self._raiden.chain.token_network(token_network_address) | python | def register_token(
self,
registry_address_hex: typing.AddressHex,
token_address_hex: typing.AddressHex,
retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
) -> TokenNetwork:
registry_address = decode_hex(registry_address_hex)
token_address = decode_hex(token_address_hex)
registry = self._raiden.chain.token_network_registry(registry_address)
contracts_version = self._raiden.contract_manager.contracts_version
if contracts_version == DEVELOPMENT_CONTRACT_VERSION:
token_network_address = registry.add_token_with_limits(
token_address=token_address,
channel_participant_deposit_limit=UINT256_MAX,
token_network_deposit_limit=UINT256_MAX,
)
else:
token_network_address = registry.add_token_without_limits(
token_address=token_address,
)
# Register the channel manager with the raiden registry
waiting.wait_for_payment_network(
self._raiden,
registry.address,
token_address,
retry_timeout,
)
return self._raiden.chain.token_network(token_network_address) | [
"def",
"register_token",
"(",
"self",
",",
"registry_address_hex",
":",
"typing",
".",
"AddressHex",
",",
"token_address_hex",
":",
"typing",
".",
"AddressHex",
",",
"retry_timeout",
":",
"typing",
".",
"NetworkTimeout",
"=",
"DEFAULT_RETRY_TIMEOUT",
",",
")",
"->... | Register a token with the raiden token manager.
Args:
registry_address: registry address
token_address_hex (string): a hex encoded token address.
Returns:
The token network proxy. | [
"Register",
"a",
"token",
"with",
"the",
"raiden",
"token",
"manager",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/console.py#L219-L260 |
235,389 | raiden-network/raiden | raiden/ui/console.py | ConsoleTools.open_channel_with_funding | def open_channel_with_funding(
self,
registry_address_hex,
token_address_hex,
peer_address_hex,
total_deposit,
settle_timeout=None,
):
""" Convenience method to open a channel.
Args:
registry_address_hex (str): hex encoded address of the registry for the channel.
token_address_hex (str): hex encoded address of the token for the channel.
peer_address_hex (str): hex encoded address of the channel peer.
total_deposit (int): amount of total funding for the channel.
settle_timeout (int): amount of blocks for the settle time (if None use app defaults).
Return:
netting_channel: the (newly opened) netting channel object.
"""
# Check, if peer is discoverable
registry_address = decode_hex(registry_address_hex)
peer_address = decode_hex(peer_address_hex)
token_address = decode_hex(token_address_hex)
try:
self._discovery.get(peer_address)
except KeyError:
print('Error: peer {} not found in discovery'.format(peer_address_hex))
return None
self._api.channel_open(
registry_address,
token_address,
peer_address,
settle_timeout=settle_timeout,
)
return self._api.set_total_channel_deposit(
registry_address,
token_address,
peer_address,
total_deposit,
) | python | def open_channel_with_funding(
self,
registry_address_hex,
token_address_hex,
peer_address_hex,
total_deposit,
settle_timeout=None,
):
# Check, if peer is discoverable
registry_address = decode_hex(registry_address_hex)
peer_address = decode_hex(peer_address_hex)
token_address = decode_hex(token_address_hex)
try:
self._discovery.get(peer_address)
except KeyError:
print('Error: peer {} not found in discovery'.format(peer_address_hex))
return None
self._api.channel_open(
registry_address,
token_address,
peer_address,
settle_timeout=settle_timeout,
)
return self._api.set_total_channel_deposit(
registry_address,
token_address,
peer_address,
total_deposit,
) | [
"def",
"open_channel_with_funding",
"(",
"self",
",",
"registry_address_hex",
",",
"token_address_hex",
",",
"peer_address_hex",
",",
"total_deposit",
",",
"settle_timeout",
"=",
"None",
",",
")",
":",
"# Check, if peer is discoverable",
"registry_address",
"=",
"decode_h... | Convenience method to open a channel.
Args:
registry_address_hex (str): hex encoded address of the registry for the channel.
token_address_hex (str): hex encoded address of the token for the channel.
peer_address_hex (str): hex encoded address of the channel peer.
total_deposit (int): amount of total funding for the channel.
settle_timeout (int): amount of blocks for the settle time (if None use app defaults).
Return:
netting_channel: the (newly opened) netting channel object. | [
"Convenience",
"method",
"to",
"open",
"a",
"channel",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/console.py#L262-L304 |
235,390 | raiden-network/raiden | raiden/ui/console.py | ConsoleTools.wait_for_contract | def wait_for_contract(self, contract_address_hex, timeout=None):
""" Wait until a contract is mined
Args:
contract_address_hex (string): hex encoded address of the contract
timeout (int): time to wait for the contract to get mined
Returns:
True if the contract got mined, false otherwise
"""
contract_address = decode_hex(contract_address_hex)
start_time = time.time()
result = self._raiden.chain.client.web3.eth.getCode(
to_checksum_address(contract_address),
)
current_time = time.time()
while not result:
if timeout and start_time + timeout > current_time:
return False
result = self._raiden.chain.client.web3.eth.getCode(
to_checksum_address(contract_address),
)
gevent.sleep(0.5)
current_time = time.time()
return len(result) > 0 | python | def wait_for_contract(self, contract_address_hex, timeout=None):
contract_address = decode_hex(contract_address_hex)
start_time = time.time()
result = self._raiden.chain.client.web3.eth.getCode(
to_checksum_address(contract_address),
)
current_time = time.time()
while not result:
if timeout and start_time + timeout > current_time:
return False
result = self._raiden.chain.client.web3.eth.getCode(
to_checksum_address(contract_address),
)
gevent.sleep(0.5)
current_time = time.time()
return len(result) > 0 | [
"def",
"wait_for_contract",
"(",
"self",
",",
"contract_address_hex",
",",
"timeout",
"=",
"None",
")",
":",
"contract_address",
"=",
"decode_hex",
"(",
"contract_address_hex",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"self",
".",
... | Wait until a contract is mined
Args:
contract_address_hex (string): hex encoded address of the contract
timeout (int): time to wait for the contract to get mined
Returns:
True if the contract got mined, false otherwise | [
"Wait",
"until",
"a",
"contract",
"is",
"mined"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/console.py#L306-L334 |
235,391 | raiden-network/raiden | raiden/storage/sqlite.py | _filter_from_dict | def _filter_from_dict(current: Dict[str, Any]) -> Dict[str, Any]:
"""Takes in a nested dictionary as a filter and returns a flattened filter dictionary"""
filter_ = dict()
for k, v in current.items():
if isinstance(v, dict):
for sub, v2 in _filter_from_dict(v).items():
filter_[f'{k}.{sub}'] = v2
else:
filter_[k] = v
return filter_ | python | def _filter_from_dict(current: Dict[str, Any]) -> Dict[str, Any]:
filter_ = dict()
for k, v in current.items():
if isinstance(v, dict):
for sub, v2 in _filter_from_dict(v).items():
filter_[f'{k}.{sub}'] = v2
else:
filter_[k] = v
return filter_ | [
"def",
"_filter_from_dict",
"(",
"current",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"filter_",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"current",
".",
"items",
"(",
")",
":",
"if... | Takes in a nested dictionary as a filter and returns a flattened filter dictionary | [
"Takes",
"in",
"a",
"nested",
"dictionary",
"as",
"a",
"filter",
"and",
"returns",
"a",
"flattened",
"filter",
"dictionary"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L52-L63 |
235,392 | raiden-network/raiden | raiden/storage/sqlite.py | SQLiteStorage.log_run | def log_run(self):
""" Log timestamp and raiden version to help with debugging """
version = get_system_spec()['raiden']
cursor = self.conn.cursor()
cursor.execute('INSERT INTO runs(raiden_version) VALUES (?)', [version])
self.maybe_commit() | python | def log_run(self):
version = get_system_spec()['raiden']
cursor = self.conn.cursor()
cursor.execute('INSERT INTO runs(raiden_version) VALUES (?)', [version])
self.maybe_commit() | [
"def",
"log_run",
"(",
"self",
")",
":",
"version",
"=",
"get_system_spec",
"(",
")",
"[",
"'raiden'",
"]",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'INSERT INTO runs(raiden_version) VALUES (?)'",
",",
"[",... | Log timestamp and raiden version to help with debugging | [
"Log",
"timestamp",
"and",
"raiden",
"version",
"to",
"help",
"with",
"debugging"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L117-L122 |
235,393 | raiden-network/raiden | raiden/storage/sqlite.py | SQLiteStorage.delete_state_changes | def delete_state_changes(self, state_changes_to_delete: List[int]) -> None:
""" Delete state changes.
Args:
state_changes_to_delete: List of ids to delete.
"""
with self.write_lock, self.conn:
self.conn.executemany(
'DELETE FROM state_events WHERE identifier = ?',
state_changes_to_delete,
) | python | def delete_state_changes(self, state_changes_to_delete: List[int]) -> None:
with self.write_lock, self.conn:
self.conn.executemany(
'DELETE FROM state_events WHERE identifier = ?',
state_changes_to_delete,
) | [
"def",
"delete_state_changes",
"(",
"self",
",",
"state_changes_to_delete",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"with",
"self",
".",
"write_lock",
",",
"self",
".",
"conn",
":",
"self",
".",
"conn",
".",
"executemany",
"(",
"'DELETE FROM ... | Delete state changes.
Args:
state_changes_to_delete: List of ids to delete. | [
"Delete",
"state",
"changes",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L181-L191 |
235,394 | raiden-network/raiden | raiden/storage/sqlite.py | SQLiteStorage.batch_query_state_changes | def batch_query_state_changes(
self,
batch_size: int,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> Iterator[List[StateChangeRecord]]:
"""Batch query state change records with a given batch size and an optional filter
This is a generator function returning each batch to the caller to work with.
"""
limit = batch_size
offset = 0
result_length = 1
while result_length != 0:
result = self._get_state_changes(
limit=limit,
offset=offset,
filters=filters,
logical_and=logical_and,
)
result_length = len(result)
offset += result_length
yield result | python | def batch_query_state_changes(
self,
batch_size: int,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> Iterator[List[StateChangeRecord]]:
limit = batch_size
offset = 0
result_length = 1
while result_length != 0:
result = self._get_state_changes(
limit=limit,
offset=offset,
filters=filters,
logical_and=logical_and,
)
result_length = len(result)
offset += result_length
yield result | [
"def",
"batch_query_state_changes",
"(",
"self",
",",
"batch_size",
":",
"int",
",",
"filters",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"logical_and",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Iterator",
"[",
"... | Batch query state change records with a given batch size and an optional filter
This is a generator function returning each batch to the caller to work with. | [
"Batch",
"query",
"state",
"change",
"records",
"with",
"a",
"given",
"batch",
"size",
"and",
"an",
"optional",
"filter"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L390-L413 |
235,395 | raiden-network/raiden | raiden/storage/sqlite.py | SQLiteStorage._get_event_records | def _get_event_records(
self,
limit: int = None,
offset: int = None,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> List[EventRecord]:
""" Return a batch of event records
The batch size can be tweaked with the `limit` and `offset` arguments.
Additionally the returned events can be optionally filtered with
the `filters` parameter to search for specific data in the event data.
"""
cursor = self._form_and_execute_json_query(
query='SELECT identifier, source_statechange_id, data FROM state_events ',
limit=limit,
offset=offset,
filters=filters,
logical_and=logical_and,
)
result = [
EventRecord(
event_identifier=row[0],
state_change_identifier=row[1],
data=row[2],
) for row in cursor
]
return result | python | def _get_event_records(
self,
limit: int = None,
offset: int = None,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> List[EventRecord]:
cursor = self._form_and_execute_json_query(
query='SELECT identifier, source_statechange_id, data FROM state_events ',
limit=limit,
offset=offset,
filters=filters,
logical_and=logical_and,
)
result = [
EventRecord(
event_identifier=row[0],
state_change_identifier=row[1],
data=row[2],
) for row in cursor
]
return result | [
"def",
"_get_event_records",
"(",
"self",
",",
"limit",
":",
"int",
"=",
"None",
",",
"offset",
":",
"int",
"=",
"None",
",",
"filters",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"logical_and",
":",
"bool",
"=",... | Return a batch of event records
The batch size can be tweaked with the `limit` and `offset` arguments.
Additionally the returned events can be optionally filtered with
the `filters` parameter to search for specific data in the event data. | [
"Return",
"a",
"batch",
"of",
"event",
"records"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L469-L498 |
235,396 | raiden-network/raiden | raiden/storage/sqlite.py | SQLiteStorage.batch_query_event_records | def batch_query_event_records(
self,
batch_size: int,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> Iterator[List[EventRecord]]:
"""Batch query event records with a given batch size and an optional filter
This is a generator function returning each batch to the caller to work with.
"""
limit = batch_size
offset = 0
result_length = 1
while result_length != 0:
result = self._get_event_records(
limit=limit,
offset=offset,
filters=filters,
logical_and=logical_and,
)
result_length = len(result)
offset += result_length
yield result | python | def batch_query_event_records(
self,
batch_size: int,
filters: List[Tuple[str, Any]] = None,
logical_and: bool = True,
) -> Iterator[List[EventRecord]]:
limit = batch_size
offset = 0
result_length = 1
while result_length != 0:
result = self._get_event_records(
limit=limit,
offset=offset,
filters=filters,
logical_and=logical_and,
)
result_length = len(result)
offset += result_length
yield result | [
"def",
"batch_query_event_records",
"(",
"self",
",",
"batch_size",
":",
"int",
",",
"filters",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"logical_and",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Iterator",
"[",
"... | Batch query event records with a given batch size and an optional filter
This is a generator function returning each batch to the caller to work with. | [
"Batch",
"query",
"event",
"records",
"with",
"a",
"given",
"batch",
"size",
"and",
"an",
"optional",
"filter"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L500-L523 |
235,397 | raiden-network/raiden | raiden/storage/sqlite.py | SQLiteStorage.update_snapshots | def update_snapshots(self, snapshots_data: List[Tuple[str, int]]):
"""Given a list of snapshot data, update them in the DB
The snapshots_data should be a list of tuples of snapshots data
and identifiers in that order.
"""
cursor = self.conn.cursor()
cursor.executemany(
'UPDATE state_snapshot SET data=? WHERE identifier=?',
snapshots_data,
)
self.maybe_commit() | python | def update_snapshots(self, snapshots_data: List[Tuple[str, int]]):
cursor = self.conn.cursor()
cursor.executemany(
'UPDATE state_snapshot SET data=? WHERE identifier=?',
snapshots_data,
)
self.maybe_commit() | [
"def",
"update_snapshots",
"(",
"self",
",",
"snapshots_data",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
")",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"executemany",
"(",
"'UPDATE state_snapshot ... | Given a list of snapshot data, update them in the DB
The snapshots_data should be a list of tuples of snapshots data
and identifiers in that order. | [
"Given",
"a",
"list",
"of",
"snapshot",
"data",
"update",
"them",
"in",
"the",
"DB"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L566-L577 |
235,398 | raiden-network/raiden | raiden/transfer/views.py | all_neighbour_nodes | def all_neighbour_nodes(chain_state: ChainState) -> Set[Address]:
""" Return the identifiers for all nodes accross all payment networks which
have a channel open with this one.
"""
addresses = set()
for payment_network in chain_state.identifiers_to_paymentnetworks.values():
for token_network in payment_network.tokenidentifiers_to_tokennetworks.values():
channel_states = token_network.channelidentifiers_to_channels.values()
for channel_state in channel_states:
addresses.add(channel_state.partner_state.address)
return addresses | python | def all_neighbour_nodes(chain_state: ChainState) -> Set[Address]:
addresses = set()
for payment_network in chain_state.identifiers_to_paymentnetworks.values():
for token_network in payment_network.tokenidentifiers_to_tokennetworks.values():
channel_states = token_network.channelidentifiers_to_channels.values()
for channel_state in channel_states:
addresses.add(channel_state.partner_state.address)
return addresses | [
"def",
"all_neighbour_nodes",
"(",
"chain_state",
":",
"ChainState",
")",
"->",
"Set",
"[",
"Address",
"]",
":",
"addresses",
"=",
"set",
"(",
")",
"for",
"payment_network",
"in",
"chain_state",
".",
"identifiers_to_paymentnetworks",
".",
"values",
"(",
")",
"... | Return the identifiers for all nodes accross all payment networks which
have a channel open with this one. | [
"Return",
"the",
"identifiers",
"for",
"all",
"nodes",
"accross",
"all",
"payment",
"networks",
"which",
"have",
"a",
"channel",
"open",
"with",
"this",
"one",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L46-L58 |
235,399 | raiden-network/raiden | raiden/transfer/views.py | get_token_network_identifiers | def get_token_network_identifiers(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
) -> List[TokenNetworkID]:
""" Return the list of token networks registered with the given payment network. """
payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id)
if payment_network is not None:
return [
token_network.address
for token_network in payment_network.tokenidentifiers_to_tokennetworks.values()
]
return list() | python | def get_token_network_identifiers(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
) -> List[TokenNetworkID]:
payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id)
if payment_network is not None:
return [
token_network.address
for token_network in payment_network.tokenidentifiers_to_tokennetworks.values()
]
return list() | [
"def",
"get_token_network_identifiers",
"(",
"chain_state",
":",
"ChainState",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
")",
"->",
"List",
"[",
"TokenNetworkID",
"]",
":",
"payment_network",
"=",
"chain_state",
".",
"identifiers_to_paymentnetworks",
".",... | Return the list of token networks registered with the given payment network. | [
"Return",
"the",
"list",
"of",
"token",
"networks",
"registered",
"with",
"the",
"given",
"payment",
"network",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L187-L200 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.