repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
numba/llvmlite
llvmlite/ir/builder.py
IRBuilder.asm
def asm(self, ftype, asm, constraint, args, side_effect, name=''): """ Inline assembler. """ asm = instructions.InlineAsm(ftype, asm, constraint, side_effect) return self.call(asm, args, name)
python
def asm(self, ftype, asm, constraint, args, side_effect, name=''): """ Inline assembler. """ asm = instructions.InlineAsm(ftype, asm, constraint, side_effect) return self.call(asm, args, name)
[ "def", "asm", "(", "self", ",", "ftype", ",", "asm", ",", "constraint", ",", "args", ",", "side_effect", ",", "name", "=", "''", ")", ":", "asm", "=", "instructions", ".", "InlineAsm", "(", "ftype", ",", "asm", ",", "constraint", ",", "side_effect", ...
Inline assembler.
[ "Inline", "assembler", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L829-L834
train
216,300
numba/llvmlite
llvmlite/ir/builder.py
IRBuilder.extract_element
def extract_element(self, vector, idx, name=''): """ Returns the value at position idx. """ instr = instructions.ExtractElement(self.block, vector, idx, name=name) self._insert(instr) return instr
python
def extract_element(self, vector, idx, name=''): """ Returns the value at position idx. """ instr = instructions.ExtractElement(self.block, vector, idx, name=name) self._insert(instr) return instr
[ "def", "extract_element", "(", "self", ",", "vector", ",", "idx", ",", "name", "=", "''", ")", ":", "instr", "=", "instructions", ".", "ExtractElement", "(", "self", ".", "block", ",", "vector", ",", "idx", ",", "name", "=", "name", ")", "self", ".",...
Returns the value at position idx.
[ "Returns", "the", "value", "at", "position", "idx", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L872-L878
train
216,301
numba/llvmlite
llvmlite/ir/module.py
Module.functions
def functions(self): """ A list of functions declared or defined in this module. """ return [v for v in self.globals.values() if isinstance(v, values.Function)]
python
def functions(self): """ A list of functions declared or defined in this module. """ return [v for v in self.globals.values() if isinstance(v, values.Function)]
[ "def", "functions", "(", "self", ")", ":", "return", "[", "v", "for", "v", "in", "self", ".", "globals", ".", "values", "(", ")", "if", "isinstance", "(", "v", ",", "values", ".", "Function", ")", "]" ]
A list of functions declared or defined in this module.
[ "A", "list", "of", "functions", "declared", "or", "defined", "in", "this", "module", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/module.py#L120-L125
train
216,302
numba/llvmlite
llvmlite/ir/module.py
Module.add_global
def add_global(self, globalvalue): """ Add a new global value. """ assert globalvalue.name not in self.globals self.globals[globalvalue.name] = globalvalue
python
def add_global(self, globalvalue): """ Add a new global value. """ assert globalvalue.name not in self.globals self.globals[globalvalue.name] = globalvalue
[ "def", "add_global", "(", "self", ",", "globalvalue", ")", ":", "assert", "globalvalue", ".", "name", "not", "in", "self", ".", "globals", "self", ".", "globals", "[", "globalvalue", ".", "name", "]", "=", "globalvalue" ]
Add a new global value.
[ "Add", "a", "new", "global", "value", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/module.py#L140-L145
train
216,303
numba/llvmlite
docs/gh-pages.py
sh2
def sh2(cmd): """Execute command in a subshell, return stdout. Stderr is unbuffered from the subshell.x""" p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment()) out = p.communicate()[0] retcode = p.returncode if retcode: raise CalledProcessError(retcode, cmd) else: return out.rstrip()
python
def sh2(cmd): """Execute command in a subshell, return stdout. Stderr is unbuffered from the subshell.x""" p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment()) out = p.communicate()[0] retcode = p.returncode if retcode: raise CalledProcessError(retcode, cmd) else: return out.rstrip()
[ "def", "sh2", "(", "cmd", ")", ":", "p", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "shell", "=", "True", ",", "env", "=", "sub_environment", "(", ")", ")", "out", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", "retcode"...
Execute command in a subshell, return stdout. Stderr is unbuffered from the subshell.x
[ "Execute", "command", "in", "a", "subshell", "return", "stdout", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/gh-pages.py#L53-L63
train
216,304
numba/llvmlite
docs/gh-pages.py
sh3
def sh3(cmd): """Execute command in a subshell, return stdout, stderr If anything appears in stderr, print it out to sys.stderr""" p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, env=sub_environment()) out, err = p.communicate() retcode = p.returncode if retcode: raise CalledProcessError(retcode, cmd) else: return out.rstrip(), err.rstrip()
python
def sh3(cmd): """Execute command in a subshell, return stdout, stderr If anything appears in stderr, print it out to sys.stderr""" p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, env=sub_environment()) out, err = p.communicate() retcode = p.returncode if retcode: raise CalledProcessError(retcode, cmd) else: return out.rstrip(), err.rstrip()
[ "def", "sh3", "(", "cmd", ")", ":", "p", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "shell", "=", "True", ",", "env", "=", "sub_environment", "(", ")", ")", "out", ",", "err", "=", "p", ".", "communic...
Execute command in a subshell, return stdout, stderr If anything appears in stderr, print it out to sys.stderr
[ "Execute", "command", "in", "a", "subshell", "return", "stdout", "stderr" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/gh-pages.py#L66-L77
train
216,305
numba/llvmlite
docs/gh-pages.py
init_repo
def init_repo(path): """clone the gh-pages repo if we haven't already.""" sh("git clone %s %s"%(pages_repo, path)) here = os.getcwd() cd(path) sh('git checkout gh-pages') cd(here)
python
def init_repo(path): """clone the gh-pages repo if we haven't already.""" sh("git clone %s %s"%(pages_repo, path)) here = os.getcwd() cd(path) sh('git checkout gh-pages') cd(here)
[ "def", "init_repo", "(", "path", ")", ":", "sh", "(", "\"git clone %s %s\"", "%", "(", "pages_repo", ",", "path", ")", ")", "here", "=", "os", ".", "getcwd", "(", ")", "cd", "(", "path", ")", "sh", "(", "'git checkout gh-pages'", ")", "cd", "(", "her...
clone the gh-pages repo if we haven't already.
[ "clone", "the", "gh", "-", "pages", "repo", "if", "we", "haven", "t", "already", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/gh-pages.py#L80-L86
train
216,306
numba/llvmlite
docs/source/user-guide/examples/ll_fpadd.py
create_execution_engine
def create_execution_engine(): """ Create an ExecutionEngine suitable for JIT code generation on the host CPU. The engine is reusable for an arbitrary number of modules. """ # Create a target machine representing the host target = llvm.Target.from_default_triple() target_machine = target.create_target_machine() # And an execution engine with an empty backing module backing_mod = llvm.parse_assembly("") engine = llvm.create_mcjit_compiler(backing_mod, target_machine) return engine
python
def create_execution_engine(): """ Create an ExecutionEngine suitable for JIT code generation on the host CPU. The engine is reusable for an arbitrary number of modules. """ # Create a target machine representing the host target = llvm.Target.from_default_triple() target_machine = target.create_target_machine() # And an execution engine with an empty backing module backing_mod = llvm.parse_assembly("") engine = llvm.create_mcjit_compiler(backing_mod, target_machine) return engine
[ "def", "create_execution_engine", "(", ")", ":", "# Create a target machine representing the host", "target", "=", "llvm", ".", "Target", ".", "from_default_triple", "(", ")", "target_machine", "=", "target", ".", "create_target_machine", "(", ")", "# And an execution eng...
Create an ExecutionEngine suitable for JIT code generation on the host CPU. The engine is reusable for an arbitrary number of modules.
[ "Create", "an", "ExecutionEngine", "suitable", "for", "JIT", "code", "generation", "on", "the", "host", "CPU", ".", "The", "engine", "is", "reusable", "for", "an", "arbitrary", "number", "of", "modules", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/source/user-guide/examples/ll_fpadd.py#L26-L38
train
216,307
numba/llvmlite
docs/source/user-guide/examples/ll_fpadd.py
compile_ir
def compile_ir(engine, llvm_ir): """ Compile the LLVM IR string with the given engine. The compiled module object is returned. """ # Create a LLVM module object from the IR mod = llvm.parse_assembly(llvm_ir) mod.verify() # Now add the module and make sure it is ready for execution engine.add_module(mod) engine.finalize_object() engine.run_static_constructors() return mod
python
def compile_ir(engine, llvm_ir): """ Compile the LLVM IR string with the given engine. The compiled module object is returned. """ # Create a LLVM module object from the IR mod = llvm.parse_assembly(llvm_ir) mod.verify() # Now add the module and make sure it is ready for execution engine.add_module(mod) engine.finalize_object() engine.run_static_constructors() return mod
[ "def", "compile_ir", "(", "engine", ",", "llvm_ir", ")", ":", "# Create a LLVM module object from the IR", "mod", "=", "llvm", ".", "parse_assembly", "(", "llvm_ir", ")", "mod", ".", "verify", "(", ")", "# Now add the module and make sure it is ready for execution", "en...
Compile the LLVM IR string with the given engine. The compiled module object is returned.
[ "Compile", "the", "LLVM", "IR", "string", "with", "the", "given", "engine", ".", "The", "compiled", "module", "object", "is", "returned", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/source/user-guide/examples/ll_fpadd.py#L41-L53
train
216,308
numba/llvmlite
llvmlite/binding/targets.py
get_default_triple
def get_default_triple(): """ Return the default target triple LLVM is configured to produce code for. """ with ffi.OutputString() as out: ffi.lib.LLVMPY_GetDefaultTargetTriple(out) return str(out)
python
def get_default_triple(): """ Return the default target triple LLVM is configured to produce code for. """ with ffi.OutputString() as out: ffi.lib.LLVMPY_GetDefaultTargetTriple(out) return str(out)
[ "def", "get_default_triple", "(", ")", ":", "with", "ffi", ".", "OutputString", "(", ")", "as", "out", ":", "ffi", ".", "lib", ".", "LLVMPY_GetDefaultTargetTriple", "(", "out", ")", "return", "str", "(", "out", ")" ]
Return the default target triple LLVM is configured to produce code for.
[ "Return", "the", "default", "target", "triple", "LLVM", "is", "configured", "to", "produce", "code", "for", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L72-L78
train
216,309
numba/llvmlite
llvmlite/binding/targets.py
TargetData.get_element_offset
def get_element_offset(self, ty, position): """ Get byte offset of type's ty element at the given position """ offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position) if offset == -1: raise ValueError("Could not determined offset of {}th " "element of the type '{}'. Is it a struct type?".format( position, str(ty))) return offset
python
def get_element_offset(self, ty, position): """ Get byte offset of type's ty element at the given position """ offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position) if offset == -1: raise ValueError("Could not determined offset of {}th " "element of the type '{}'. Is it a struct type?".format( position, str(ty))) return offset
[ "def", "get_element_offset", "(", "self", ",", "ty", ",", "position", ")", ":", "offset", "=", "ffi", ".", "lib", ".", "LLVMPY_OffsetOfElement", "(", "self", ",", "ty", ",", "position", ")", "if", "offset", "==", "-", "1", ":", "raise", "ValueError", "...
Get byte offset of type's ty element at the given position
[ "Get", "byte", "offset", "of", "type", "s", "ty", "element", "at", "the", "given", "position" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L136-L146
train
216,310
numba/llvmlite
llvmlite/binding/targets.py
Target.create_target_machine
def create_target_machine(self, cpu='', features='', opt=2, reloc='default', codemodel='jitdefault', jitdebug=False, printmc=False): """ Create a new TargetMachine for this target and the given options. Specifying codemodel='default' will result in the use of the "small" code model. Specifying codemodel='jitdefault' will result in the code model being picked based on platform bitness (32="small", 64="large"). """ assert 0 <= opt <= 3 assert reloc in RELOC assert codemodel in CODEMODEL triple = self._triple # MCJIT under Windows only supports ELF objects, see # http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html # Note we still want to produce regular COFF files in AOT mode. if os.name == 'nt' and codemodel == 'jitdefault': triple += '-elf' tm = ffi.lib.LLVMPY_CreateTargetMachine(self, _encode_string(triple), _encode_string(cpu), _encode_string(features), opt, _encode_string(reloc), _encode_string(codemodel), int(jitdebug), int(printmc), ) if tm: return TargetMachine(tm) else: raise RuntimeError("Cannot create target machine")
python
def create_target_machine(self, cpu='', features='', opt=2, reloc='default', codemodel='jitdefault', jitdebug=False, printmc=False): """ Create a new TargetMachine for this target and the given options. Specifying codemodel='default' will result in the use of the "small" code model. Specifying codemodel='jitdefault' will result in the code model being picked based on platform bitness (32="small", 64="large"). """ assert 0 <= opt <= 3 assert reloc in RELOC assert codemodel in CODEMODEL triple = self._triple # MCJIT under Windows only supports ELF objects, see # http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html # Note we still want to produce regular COFF files in AOT mode. if os.name == 'nt' and codemodel == 'jitdefault': triple += '-elf' tm = ffi.lib.LLVMPY_CreateTargetMachine(self, _encode_string(triple), _encode_string(cpu), _encode_string(features), opt, _encode_string(reloc), _encode_string(codemodel), int(jitdebug), int(printmc), ) if tm: return TargetMachine(tm) else: raise RuntimeError("Cannot create target machine")
[ "def", "create_target_machine", "(", "self", ",", "cpu", "=", "''", ",", "features", "=", "''", ",", "opt", "=", "2", ",", "reloc", "=", "'default'", ",", "codemodel", "=", "'jitdefault'", ",", "jitdebug", "=", "False", ",", "printmc", "=", "False", ")...
Create a new TargetMachine for this target and the given options. Specifying codemodel='default' will result in the use of the "small" code model. Specifying codemodel='jitdefault' will result in the code model being picked based on platform bitness (32="small", 64="large").
[ "Create", "a", "new", "TargetMachine", "for", "this", "target", "and", "the", "given", "options", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L217-L249
train
216,311
numba/llvmlite
llvmlite/binding/targets.py
TargetMachine._emit_to_memory
def _emit_to_memory(self, module, use_object=False): """Returns bytes of object code of the module. Args ---- use_object : bool Emit object code or (if False) emit assembly code. """ with ffi.OutputString() as outerr: mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module, int(use_object), outerr) if not mb: raise RuntimeError(str(outerr)) bufptr = ffi.lib.LLVMPY_GetBufferStart(mb) bufsz = ffi.lib.LLVMPY_GetBufferSize(mb) try: return string_at(bufptr, bufsz) finally: ffi.lib.LLVMPY_DisposeMemoryBuffer(mb)
python
def _emit_to_memory(self, module, use_object=False): """Returns bytes of object code of the module. Args ---- use_object : bool Emit object code or (if False) emit assembly code. """ with ffi.OutputString() as outerr: mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module, int(use_object), outerr) if not mb: raise RuntimeError(str(outerr)) bufptr = ffi.lib.LLVMPY_GetBufferStart(mb) bufsz = ffi.lib.LLVMPY_GetBufferSize(mb) try: return string_at(bufptr, bufsz) finally: ffi.lib.LLVMPY_DisposeMemoryBuffer(mb)
[ "def", "_emit_to_memory", "(", "self", ",", "module", ",", "use_object", "=", "False", ")", ":", "with", "ffi", ".", "OutputString", "(", ")", "as", "outerr", ":", "mb", "=", "ffi", ".", "lib", ".", "LLVMPY_TargetMachineEmitToMemory", "(", "self", ",", "...
Returns bytes of object code of the module. Args ---- use_object : bool Emit object code or (if False) emit assembly code.
[ "Returns", "bytes", "of", "object", "code", "of", "the", "module", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L285-L305
train
216,312
numba/llvmlite
llvmlite/binding/module.py
parse_assembly
def parse_assembly(llvmir, context=None): """ Create Module from a LLVM IR string """ if context is None: context = get_global_context() llvmir = _encode_string(llvmir) strbuf = c_char_p(llvmir) with ffi.OutputString() as errmsg: mod = ModuleRef( ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), context) if errmsg: mod.close() raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) return mod
python
def parse_assembly(llvmir, context=None): """ Create Module from a LLVM IR string """ if context is None: context = get_global_context() llvmir = _encode_string(llvmir) strbuf = c_char_p(llvmir) with ffi.OutputString() as errmsg: mod = ModuleRef( ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), context) if errmsg: mod.close() raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) return mod
[ "def", "parse_assembly", "(", "llvmir", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "get_global_context", "(", ")", "llvmir", "=", "_encode_string", "(", "llvmir", ")", "strbuf", "=", "c_char_p", "(", "llvmir"...
Create Module from a LLVM IR string
[ "Create", "Module", "from", "a", "LLVM", "IR", "string" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L12-L27
train
216,313
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.as_bitcode
def as_bitcode(self): """ Return the module's LLVM bitcode, as a bytes object. """ ptr = c_char_p(None) size = c_size_t(-1) ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size)) if not ptr: raise MemoryError try: assert size.value >= 0 return string_at(ptr, size.value) finally: ffi.lib.LLVMPY_DisposeString(ptr)
python
def as_bitcode(self): """ Return the module's LLVM bitcode, as a bytes object. """ ptr = c_char_p(None) size = c_size_t(-1) ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size)) if not ptr: raise MemoryError try: assert size.value >= 0 return string_at(ptr, size.value) finally: ffi.lib.LLVMPY_DisposeString(ptr)
[ "def", "as_bitcode", "(", "self", ")", ":", "ptr", "=", "c_char_p", "(", "None", ")", "size", "=", "c_size_t", "(", "-", "1", ")", "ffi", ".", "lib", ".", "LLVMPY_WriteBitcodeToString", "(", "self", ",", "byref", "(", "ptr", ")", ",", "byref", "(", ...
Return the module's LLVM bitcode, as a bytes object.
[ "Return", "the", "module", "s", "LLVM", "bitcode", "as", "a", "bytes", "object", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L62-L75
train
216,314
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.verify
def verify(self): """ Verify the module IR's correctness. RuntimeError is raised on error. """ with ffi.OutputString() as outmsg: if ffi.lib.LLVMPY_VerifyModule(self, outmsg): raise RuntimeError(str(outmsg))
python
def verify(self): """ Verify the module IR's correctness. RuntimeError is raised on error. """ with ffi.OutputString() as outmsg: if ffi.lib.LLVMPY_VerifyModule(self, outmsg): raise RuntimeError(str(outmsg))
[ "def", "verify", "(", "self", ")", ":", "with", "ffi", ".", "OutputString", "(", ")", "as", "outmsg", ":", "if", "ffi", ".", "lib", ".", "LLVMPY_VerifyModule", "(", "self", ",", "outmsg", ")", ":", "raise", "RuntimeError", "(", "str", "(", "outmsg", ...
Verify the module IR's correctness. RuntimeError is raised on error.
[ "Verify", "the", "module", "IR", "s", "correctness", ".", "RuntimeError", "is", "raised", "on", "error", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L110-L116
train
216,315
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.data_layout
def data_layout(self): """ This module's data layout specification, as a string. """ # LLVMGetDataLayout() points inside a std::string managed by LLVM. with ffi.OutputString(owned=False) as outmsg: ffi.lib.LLVMPY_GetDataLayout(self, outmsg) return str(outmsg)
python
def data_layout(self): """ This module's data layout specification, as a string. """ # LLVMGetDataLayout() points inside a std::string managed by LLVM. with ffi.OutputString(owned=False) as outmsg: ffi.lib.LLVMPY_GetDataLayout(self, outmsg) return str(outmsg)
[ "def", "data_layout", "(", "self", ")", ":", "# LLVMGetDataLayout() points inside a std::string managed by LLVM.", "with", "ffi", ".", "OutputString", "(", "owned", "=", "False", ")", "as", "outmsg", ":", "ffi", ".", "lib", ".", "LLVMPY_GetDataLayout", "(", "self", ...
This module's data layout specification, as a string.
[ "This", "module", "s", "data", "layout", "specification", "as", "a", "string", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L130-L137
train
216,316
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.triple
def triple(self): """ This module's target "triple" specification, as a string. """ # LLVMGetTarget() points inside a std::string managed by LLVM. with ffi.OutputString(owned=False) as outmsg: ffi.lib.LLVMPY_GetTarget(self, outmsg) return str(outmsg)
python
def triple(self): """ This module's target "triple" specification, as a string. """ # LLVMGetTarget() points inside a std::string managed by LLVM. with ffi.OutputString(owned=False) as outmsg: ffi.lib.LLVMPY_GetTarget(self, outmsg) return str(outmsg)
[ "def", "triple", "(", "self", ")", ":", "# LLVMGetTarget() points inside a std::string managed by LLVM.", "with", "ffi", ".", "OutputString", "(", "owned", "=", "False", ")", "as", "outmsg", ":", "ffi", ".", "lib", ".", "LLVMPY_GetTarget", "(", "self", ",", "out...
This module's target "triple" specification, as a string.
[ "This", "module", "s", "target", "triple", "specification", "as", "a", "string", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L146-L153
train
216,317
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.global_variables
def global_variables(self): """ Return an iterator over this module's global variables. The iterator will yield a ValueRef for each global variable. Note that global variables don't include functions (a function is a "global value" but not a "global variable" in LLVM parlance) """ it = ffi.lib.LLVMPY_ModuleGlobalsIter(self) return _GlobalsIterator(it, dict(module=self))
python
def global_variables(self): """ Return an iterator over this module's global variables. The iterator will yield a ValueRef for each global variable. Note that global variables don't include functions (a function is a "global value" but not a "global variable" in LLVM parlance) """ it = ffi.lib.LLVMPY_ModuleGlobalsIter(self) return _GlobalsIterator(it, dict(module=self))
[ "def", "global_variables", "(", "self", ")", ":", "it", "=", "ffi", ".", "lib", ".", "LLVMPY_ModuleGlobalsIter", "(", "self", ")", "return", "_GlobalsIterator", "(", "it", ",", "dict", "(", "module", "=", "self", ")", ")" ]
Return an iterator over this module's global variables. The iterator will yield a ValueRef for each global variable. Note that global variables don't include functions (a function is a "global value" but not a "global variable" in LLVM parlance)
[ "Return", "an", "iterator", "over", "this", "module", "s", "global", "variables", ".", "The", "iterator", "will", "yield", "a", "ValueRef", "for", "each", "global", "variable", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L171-L181
train
216,318
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.functions
def functions(self): """ Return an iterator over this module's functions. The iterator will yield a ValueRef for each function. """ it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) return _FunctionsIterator(it, dict(module=self))
python
def functions(self): """ Return an iterator over this module's functions. The iterator will yield a ValueRef for each function. """ it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) return _FunctionsIterator(it, dict(module=self))
[ "def", "functions", "(", "self", ")", ":", "it", "=", "ffi", ".", "lib", ".", "LLVMPY_ModuleFunctionsIter", "(", "self", ")", "return", "_FunctionsIterator", "(", "it", ",", "dict", "(", "module", "=", "self", ")", ")" ]
Return an iterator over this module's functions. The iterator will yield a ValueRef for each function.
[ "Return", "an", "iterator", "over", "this", "module", "s", "functions", ".", "The", "iterator", "will", "yield", "a", "ValueRef", "for", "each", "function", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L184-L190
train
216,319
numba/llvmlite
llvmlite/binding/module.py
ModuleRef.struct_types
def struct_types(self): """ Return an iterator over the struct types defined in the module. The iterator will yield a TypeRef. """ it = ffi.lib.LLVMPY_ModuleTypesIter(self) return _TypesIterator(it, dict(module=self))
python
def struct_types(self): """ Return an iterator over the struct types defined in the module. The iterator will yield a TypeRef. """ it = ffi.lib.LLVMPY_ModuleTypesIter(self) return _TypesIterator(it, dict(module=self))
[ "def", "struct_types", "(", "self", ")", ":", "it", "=", "ffi", ".", "lib", ".", "LLVMPY_ModuleTypesIter", "(", "self", ")", "return", "_TypesIterator", "(", "it", ",", "dict", "(", "module", "=", "self", ")", ")" ]
Return an iterator over the struct types defined in the module. The iterator will yield a TypeRef.
[ "Return", "an", "iterator", "over", "the", "struct", "types", "defined", "in", "the", "module", ".", "The", "iterator", "will", "yield", "a", "TypeRef", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L193-L199
train
216,320
numba/llvmlite
llvmlite/binding/options.py
set_option
def set_option(name, option): """ Set the given LLVM "command-line" option. For example set_option("test", "-debug-pass=Structure") would display all optimization passes when generating code. """ ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option))
python
def set_option(name, option): """ Set the given LLVM "command-line" option. For example set_option("test", "-debug-pass=Structure") would display all optimization passes when generating code. """ ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option))
[ "def", "set_option", "(", "name", ",", "option", ")", ":", "ffi", ".", "lib", ".", "LLVMPY_SetCommandLine", "(", "_encode_string", "(", "name", ")", ",", "_encode_string", "(", "option", ")", ")" ]
Set the given LLVM "command-line" option. For example set_option("test", "-debug-pass=Structure") would display all optimization passes when generating code.
[ "Set", "the", "given", "LLVM", "command", "-", "line", "option", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/options.py#L6-L14
train
216,321
numba/llvmlite
llvmlite/ir/types.py
Type._get_ll_pointer_type
def _get_ll_pointer_type(self, target_data, context=None): """ Convert this type object to an LLVM type. """ from . import Module, GlobalVariable from ..binding import parse_assembly if context is None: m = Module() else: m = Module(context=context) foo = GlobalVariable(m, self, name="foo") with parse_assembly(str(m)) as llmod: return llmod.get_global_variable(foo.name).type
python
def _get_ll_pointer_type(self, target_data, context=None): """ Convert this type object to an LLVM type. """ from . import Module, GlobalVariable from ..binding import parse_assembly if context is None: m = Module() else: m = Module(context=context) foo = GlobalVariable(m, self, name="foo") with parse_assembly(str(m)) as llmod: return llmod.get_global_variable(foo.name).type
[ "def", "_get_ll_pointer_type", "(", "self", ",", "target_data", ",", "context", "=", "None", ")", ":", "from", ".", "import", "Module", ",", "GlobalVariable", "from", ".", ".", "binding", "import", "parse_assembly", "if", "context", "is", "None", ":", "m", ...
Convert this type object to an LLVM type.
[ "Convert", "this", "type", "object", "to", "an", "LLVM", "type", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L35-L48
train
216,322
numba/llvmlite
llvmlite/ir/types.py
BaseStructType.structure_repr
def structure_repr(self): """ Return the LLVM IR for the structure representation """ ret = '{%s}' % ', '.join([str(x) for x in self.elements]) return self._wrap_packed(ret)
python
def structure_repr(self): """ Return the LLVM IR for the structure representation """ ret = '{%s}' % ', '.join([str(x) for x in self.elements]) return self._wrap_packed(ret)
[ "def", "structure_repr", "(", "self", ")", ":", "ret", "=", "'{%s}'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "elements", "]", ")", "return", "self", ".", "_wrap_packed", "(", "ret", ")" ]
Return the LLVM IR for the structure representation
[ "Return", "the", "LLVM", "IR", "for", "the", "structure", "representation" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L477-L482
train
216,323
numba/llvmlite
llvmlite/ir/types.py
IdentifiedStructType.get_declaration
def get_declaration(self): """ Returns the string for the declaration of the type """ if self.is_opaque: out = "{strrep} = type opaque".format(strrep=str(self)) else: out = "{strrep} = type {struct}".format( strrep=str(self), struct=self.structure_repr()) return out
python
def get_declaration(self): """ Returns the string for the declaration of the type """ if self.is_opaque: out = "{strrep} = type opaque".format(strrep=str(self)) else: out = "{strrep} = type {struct}".format( strrep=str(self), struct=self.structure_repr()) return out
[ "def", "get_declaration", "(", "self", ")", ":", "if", "self", ".", "is_opaque", ":", "out", "=", "\"{strrep} = type opaque\"", ".", "format", "(", "strrep", "=", "str", "(", "self", ")", ")", "else", ":", "out", "=", "\"{strrep} = type {struct}\"", ".", "...
Returns the string for the declaration of the type
[ "Returns", "the", "string", "for", "the", "declaration", "of", "the", "type" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L563-L572
train
216,324
numba/llvmlite
llvmlite/binding/ffi.py
ObjectRef.close
def close(self): """ Close this object and do any required clean-up actions. """ try: if not self._closed and not self._owned: self._dispose() finally: self.detach()
python
def close(self): """ Close this object and do any required clean-up actions. """ try: if not self._closed and not self._owned: self._dispose() finally: self.detach()
[ "def", "close", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "_closed", "and", "not", "self", ".", "_owned", ":", "self", ".", "_dispose", "(", ")", "finally", ":", "self", ".", "detach", "(", ")" ]
Close this object and do any required clean-up actions.
[ "Close", "this", "object", "and", "do", "any", "required", "clean", "-", "up", "actions", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/ffi.py#L226-L234
train
216,325
numba/llvmlite
llvmlite/binding/ffi.py
ObjectRef.detach
def detach(self): """ Detach the underlying LLVM resource without disposing of it. """ if not self._closed: del self._as_parameter_ self._closed = True self._ptr = None
python
def detach(self): """ Detach the underlying LLVM resource without disposing of it. """ if not self._closed: del self._as_parameter_ self._closed = True self._ptr = None
[ "def", "detach", "(", "self", ")", ":", "if", "not", "self", ".", "_closed", ":", "del", "self", ".", "_as_parameter_", "self", ".", "_closed", "=", "True", "self", ".", "_ptr", "=", "None" ]
Detach the underlying LLVM resource without disposing of it.
[ "Detach", "the", "underlying", "LLVM", "resource", "without", "disposing", "of", "it", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/ffi.py#L236-L243
train
216,326
numba/llvmlite
llvmlite/binding/dylib.py
load_library_permanently
def load_library_permanently(filename): """ Load an external library """ with ffi.OutputString() as outerr: if ffi.lib.LLVMPY_LoadLibraryPermanently( _encode_string(filename), outerr): raise RuntimeError(str(outerr))
python
def load_library_permanently(filename): """ Load an external library """ with ffi.OutputString() as outerr: if ffi.lib.LLVMPY_LoadLibraryPermanently( _encode_string(filename), outerr): raise RuntimeError(str(outerr))
[ "def", "load_library_permanently", "(", "filename", ")", ":", "with", "ffi", ".", "OutputString", "(", ")", "as", "outerr", ":", "if", "ffi", ".", "lib", ".", "LLVMPY_LoadLibraryPermanently", "(", "_encode_string", "(", "filename", ")", ",", "outerr", ")", "...
Load an external library
[ "Load", "an", "external", "library" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/dylib.py#L23-L30
train
216,327
numba/llvmlite
ffi/build.py
find_win32_generator
def find_win32_generator(): """ Find a suitable cmake "generator" under Windows. """ # XXX this assumes we will find a generator that's the same, or # compatible with, the one which was used to compile LLVM... cmake # seems a bit lacking here. cmake_dir = os.path.join(here_dir, 'dummy') # LLVM 4.0+ needs VS 2015 minimum. generators = [] if os.environ.get("CMAKE_GENERATOR"): generators.append(os.environ.get("CMAKE_GENERATOR")) # Drop generators that are too old vspat = re.compile(r'Visual Studio (\d+)') def drop_old_vs(g): m = vspat.match(g) if m is None: return True # keep those we don't recognize ver = int(m.group(1)) return ver >= 14 generators = list(filter(drop_old_vs, generators)) generators.append('Visual Studio 14 2015' + (' Win64' if is_64bit else '')) for generator in generators: build_dir = tempfile.mkdtemp() print("Trying generator %r" % (generator,)) try: try_cmake(cmake_dir, build_dir, generator) except subprocess.CalledProcessError: continue else: # Success return generator finally: shutil.rmtree(build_dir) raise RuntimeError("No compatible cmake generator installed on this machine")
python
def find_win32_generator(): """ Find a suitable cmake "generator" under Windows. """ # XXX this assumes we will find a generator that's the same, or # compatible with, the one which was used to compile LLVM... cmake # seems a bit lacking here. cmake_dir = os.path.join(here_dir, 'dummy') # LLVM 4.0+ needs VS 2015 minimum. generators = [] if os.environ.get("CMAKE_GENERATOR"): generators.append(os.environ.get("CMAKE_GENERATOR")) # Drop generators that are too old vspat = re.compile(r'Visual Studio (\d+)') def drop_old_vs(g): m = vspat.match(g) if m is None: return True # keep those we don't recognize ver = int(m.group(1)) return ver >= 14 generators = list(filter(drop_old_vs, generators)) generators.append('Visual Studio 14 2015' + (' Win64' if is_64bit else '')) for generator in generators: build_dir = tempfile.mkdtemp() print("Trying generator %r" % (generator,)) try: try_cmake(cmake_dir, build_dir, generator) except subprocess.CalledProcessError: continue else: # Success return generator finally: shutil.rmtree(build_dir) raise RuntimeError("No compatible cmake generator installed on this machine")
[ "def", "find_win32_generator", "(", ")", ":", "# XXX this assumes we will find a generator that's the same, or", "# compatible with, the one which was used to compile LLVM... cmake", "# seems a bit lacking here.", "cmake_dir", "=", "os", ".", "path", ".", "join", "(", "here_dir", "...
Find a suitable cmake "generator" under Windows.
[ "Find", "a", "suitable", "cmake", "generator", "under", "Windows", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/ffi/build.py#L48-L84
train
216,328
numba/llvmlite
llvmlite/ir/values.py
_escape_string
def _escape_string(text, _map={}): """ Escape the given bytestring for safe use as a LLVM array constant. """ if isinstance(text, str): text = text.encode('ascii') assert isinstance(text, (bytes, bytearray)) if not _map: for ch in range(256): if ch in _VALID_CHARS: _map[ch] = chr(ch) else: _map[ch] = '\\%02x' % ch if six.PY2: _map[chr(ch)] = _map[ch] buf = [_map[ch] for ch in text] return ''.join(buf)
python
def _escape_string(text, _map={}): """ Escape the given bytestring for safe use as a LLVM array constant. """ if isinstance(text, str): text = text.encode('ascii') assert isinstance(text, (bytes, bytearray)) if not _map: for ch in range(256): if ch in _VALID_CHARS: _map[ch] = chr(ch) else: _map[ch] = '\\%02x' % ch if six.PY2: _map[chr(ch)] = _map[ch] buf = [_map[ch] for ch in text] return ''.join(buf)
[ "def", "_escape_string", "(", "text", ",", "_map", "=", "{", "}", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "text", ".", "encode", "(", "'ascii'", ")", "assert", "isinstance", "(", "text", ",", "(", "bytes", ",",...
Escape the given bytestring for safe use as a LLVM array constant.
[ "Escape", "the", "given", "bytestring", "for", "safe", "use", "as", "a", "LLVM", "array", "constant", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L20-L38
train
216,329
numba/llvmlite
llvmlite/ir/values.py
_ConstOpMixin.bitcast
def bitcast(self, typ): """ Bitcast this pointer constant to the given type. """ if typ == self.type: return self op = "bitcast ({0} {1} to {2})".format(self.type, self.get_reference(), typ) return FormattedConstant(typ, op)
python
def bitcast(self, typ): """ Bitcast this pointer constant to the given type. """ if typ == self.type: return self op = "bitcast ({0} {1} to {2})".format(self.type, self.get_reference(), typ) return FormattedConstant(typ, op)
[ "def", "bitcast", "(", "self", ",", "typ", ")", ":", "if", "typ", "==", "self", ".", "type", ":", "return", "self", "op", "=", "\"bitcast ({0} {1} to {2})\"", ".", "format", "(", "self", ".", "type", ",", "self", ".", "get_reference", "(", ")", ",", ...
Bitcast this pointer constant to the given type.
[ "Bitcast", "this", "pointer", "constant", "to", "the", "given", "type", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L46-L54
train
216,330
numba/llvmlite
llvmlite/ir/values.py
_ConstOpMixin.inttoptr
def inttoptr(self, typ): """ Cast this integer constant to the given pointer type. """ if not isinstance(self.type, types.IntType): raise TypeError("can only call inttoptr() on integer constants, not '%s'" % (self.type,)) if not isinstance(typ, types.PointerType): raise TypeError("can only inttoptr() to pointer type, not '%s'" % (typ,)) op = "inttoptr ({0} {1} to {2})".format(self.type, self.get_reference(), typ) return FormattedConstant(typ, op)
python
def inttoptr(self, typ): """ Cast this integer constant to the given pointer type. """ if not isinstance(self.type, types.IntType): raise TypeError("can only call inttoptr() on integer constants, not '%s'" % (self.type,)) if not isinstance(typ, types.PointerType): raise TypeError("can only inttoptr() to pointer type, not '%s'" % (typ,)) op = "inttoptr ({0} {1} to {2})".format(self.type, self.get_reference(), typ) return FormattedConstant(typ, op)
[ "def", "inttoptr", "(", "self", ",", "typ", ")", ":", "if", "not", "isinstance", "(", "self", ".", "type", ",", "types", ".", "IntType", ")", ":", "raise", "TypeError", "(", "\"can only call inttoptr() on integer constants, not '%s'\"", "%", "(", "self", ".", ...
Cast this integer constant to the given pointer type.
[ "Cast", "this", "integer", "constant", "to", "the", "given", "pointer", "type", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L56-L70
train
216,331
numba/llvmlite
llvmlite/ir/values.py
_ConstOpMixin.gep
def gep(self, indices): """ Call getelementptr on this pointer constant. """ if not isinstance(self.type, types.PointerType): raise TypeError("can only call gep() on pointer constants, not '%s'" % (self.type,)) outtype = self.type for i in indices: outtype = outtype.gep(i) strindices = ["{0} {1}".format(idx.type, idx.get_reference()) for idx in indices] op = "getelementptr ({0}, {1} {2}, {3})".format( self.type.pointee, self.type, self.get_reference(), ', '.join(strindices)) return FormattedConstant(outtype.as_pointer(self.addrspace), op)
python
def gep(self, indices): """ Call getelementptr on this pointer constant. """ if not isinstance(self.type, types.PointerType): raise TypeError("can only call gep() on pointer constants, not '%s'" % (self.type,)) outtype = self.type for i in indices: outtype = outtype.gep(i) strindices = ["{0} {1}".format(idx.type, idx.get_reference()) for idx in indices] op = "getelementptr ({0}, {1} {2}, {3})".format( self.type.pointee, self.type, self.get_reference(), ', '.join(strindices)) return FormattedConstant(outtype.as_pointer(self.addrspace), op)
[ "def", "gep", "(", "self", ",", "indices", ")", ":", "if", "not", "isinstance", "(", "self", ".", "type", ",", "types", ".", "PointerType", ")", ":", "raise", "TypeError", "(", "\"can only call gep() on pointer constants, not '%s'\"", "%", "(", "self", ".", ...
Call getelementptr on this pointer constant.
[ "Call", "getelementptr", "on", "this", "pointer", "constant", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L72-L90
train
216,332
numba/llvmlite
llvmlite/ir/values.py
Constant.literal_array
def literal_array(cls, elems): """ Construct a literal array constant made of the given members. """ tys = [el.type for el in elems] if len(tys) == 0: raise ValueError("need at least one element") ty = tys[0] for other in tys: if ty != other: raise TypeError("all elements must have the same type") return cls(types.ArrayType(ty, len(elems)), elems)
python
def literal_array(cls, elems): """ Construct a literal array constant made of the given members. """ tys = [el.type for el in elems] if len(tys) == 0: raise ValueError("need at least one element") ty = tys[0] for other in tys: if ty != other: raise TypeError("all elements must have the same type") return cls(types.ArrayType(ty, len(elems)), elems)
[ "def", "literal_array", "(", "cls", ",", "elems", ")", ":", "tys", "=", "[", "el", ".", "type", "for", "el", "in", "elems", "]", "if", "len", "(", "tys", ")", "==", "0", ":", "raise", "ValueError", "(", "\"need at least one element\"", ")", "ty", "="...
Construct a literal array constant made of the given members.
[ "Construct", "a", "literal", "array", "constant", "made", "of", "the", "given", "members", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L147-L158
train
216,333
numba/llvmlite
llvmlite/ir/values.py
Constant.literal_struct
def literal_struct(cls, elems): """ Construct a literal structure constant made of the given members. """ tys = [el.type for el in elems] return cls(types.LiteralStructType(tys), elems)
python
def literal_struct(cls, elems): """ Construct a literal structure constant made of the given members. """ tys = [el.type for el in elems] return cls(types.LiteralStructType(tys), elems)
[ "def", "literal_struct", "(", "cls", ",", "elems", ")", ":", "tys", "=", "[", "el", ".", "type", "for", "el", "in", "elems", "]", "return", "cls", "(", "types", ".", "LiteralStructType", "(", "tys", ")", ",", "elems", ")" ]
Construct a literal structure constant made of the given members.
[ "Construct", "a", "literal", "structure", "constant", "made", "of", "the", "given", "members", "." ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L161-L166
train
216,334
numba/llvmlite
llvmlite/ir/values.py
Function.insert_basic_block
def insert_basic_block(self, before, name=''): """Insert block before """ blk = Block(parent=self, name=name) self.blocks.insert(before, blk) return blk
python
def insert_basic_block(self, before, name=''): """Insert block before """ blk = Block(parent=self, name=name) self.blocks.insert(before, blk) return blk
[ "def", "insert_basic_block", "(", "self", ",", "before", ",", "name", "=", "''", ")", ":", "blk", "=", "Block", "(", "parent", "=", "self", ",", "name", "=", "name", ")", "self", ".", "blocks", ".", "insert", "(", "before", ",", "blk", ")", "return...
Insert block before
[ "Insert", "block", "before" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L622-L627
train
216,335
numba/llvmlite
llvmlite/ir/values.py
Block.replace
def replace(self, old, new): """Replace an instruction""" if old.type != new.type: raise TypeError("new instruction has a different type") pos = self.instructions.index(old) self.instructions.remove(old) self.instructions.insert(pos, new) for bb in self.parent.basic_blocks: for instr in bb.instructions: instr.replace_usage(old, new)
python
def replace(self, old, new): """Replace an instruction""" if old.type != new.type: raise TypeError("new instruction has a different type") pos = self.instructions.index(old) self.instructions.remove(old) self.instructions.insert(pos, new) for bb in self.parent.basic_blocks: for instr in bb.instructions: instr.replace_usage(old, new)
[ "def", "replace", "(", "self", ",", "old", ",", "new", ")", ":", "if", "old", ".", "type", "!=", "new", ".", "type", ":", "raise", "TypeError", "(", "\"new instruction has a different type\"", ")", "pos", "=", "self", ".", "instructions", ".", "index", "...
Replace an instruction
[ "Replace", "an", "instruction" ]
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L796-L806
train
216,336
numba/llvmlite
llvmlite/binding/analysis.py
get_function_cfg
def get_function_cfg(func, show_inst=True): """Return a string of the control-flow graph of the function in DOT format. If the input `func` is not a materialized function, the module containing the function is parsed to create an actual LLVM module. The `show_inst` flag controls whether the instructions of each block are printed. """ assert func is not None if isinstance(func, ir.Function): mod = parse_assembly(str(func.module)) func = mod.get_function(func.name) # Assume func is a materialized function with ffi.OutputString() as dotstr: ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst) return str(dotstr)
python
def get_function_cfg(func, show_inst=True): """Return a string of the control-flow graph of the function in DOT format. If the input `func` is not a materialized function, the module containing the function is parsed to create an actual LLVM module. The `show_inst` flag controls whether the instructions of each block are printed. """ assert func is not None if isinstance(func, ir.Function): mod = parse_assembly(str(func.module)) func = mod.get_function(func.name) # Assume func is a materialized function with ffi.OutputString() as dotstr: ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst) return str(dotstr)
[ "def", "get_function_cfg", "(", "func", ",", "show_inst", "=", "True", ")", ":", "assert", "func", "is", "not", "None", "if", "isinstance", "(", "func", ",", "ir", ".", "Function", ")", ":", "mod", "=", "parse_assembly", "(", "str", "(", "func", ".", ...
Return a string of the control-flow graph of the function in DOT format. If the input `func` is not a materialized function, the module containing the function is parsed to create an actual LLVM module. The `show_inst` flag controls whether the instructions of each block are printed.
[ "Return", "a", "string", "of", "the", "control", "-", "flow", "graph", "of", "the", "function", "in", "DOT", "format", ".", "If", "the", "input", "func", "is", "not", "a", "materialized", "function", "the", "module", "containing", "the", "function", "is", ...
fcadf8af11947f3fd041c5d6526c5bf231564883
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/analysis.py#L14-L29
train
216,337
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): """ 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))
[ "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
train
216,338
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): """ 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))
[ "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
train
216,339
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): """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)
[ "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
train
216,340
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): """ 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
[ "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
train
216,341
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): """ 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)
[ "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
train
216,342
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): """ 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)
[ "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
train
216,343
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): """ 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)
[ "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
train
216,344
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): """ 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)
[ "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
train
216,345
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): """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
[ "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
train
216,346
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): """ 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))
[ "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
train
216,347
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]: """ 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()
[ "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
train
216,348
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]: """ 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
[ "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
train
216,349
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]: """ 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
[ "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
train
216,350
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]: """ 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())
[ "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
train
216,351
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]: """ 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)
[ "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
train
216,352
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]: """ 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)
[ "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
train
216,353
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]: """ 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
[ "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
train
216,354
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 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
[ "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
train
216,355
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): """ 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)
[ "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
train
216,356
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): """ 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, )
[ "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
train
216,357
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): """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
[ "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
train
216,358
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: """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
[ "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
train
216,359
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': """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)
[ "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
train
216,360
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: """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)
[ "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
train
216,361
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): """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()
[ "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
train
216,362
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): """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')
[ "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
train
216,363
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: """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']
[ "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
train
216,364
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: """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
[ "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
train
216,365
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]]: """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.', )
[ "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
train
216,366
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: """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, ])
[ "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
train
216,367
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: """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
[ "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
train
216,368
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], ): """ 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()
[ "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
train
216,369
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]: """ 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
[ "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
train
216,370
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: """ 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, }, )
[ "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
train
216,371
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: """ 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(), )
[ "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
train
216,372
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, ): """ 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()
[ "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
train
216,373
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]: """ 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
[ "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
train
216,374
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: """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)
[ "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
train
216,375
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: """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)
[ "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
train
216,376
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: """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)
[ "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
train
216,377
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: """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)
[ "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
train
216,378
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: """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
[ "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
train
216,379
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]: """ 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
[ "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
train
216,380
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: """ 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)
[ "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
train
216,381
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]]: """ 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
[ "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
train
216,382
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]: """ 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
[ "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
train
216,383
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: """ 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
[ "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
train
216,384
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: """ 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])
[ "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
train
216,385
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: """ 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)
[ "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
train
216,386
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: """ 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
[ "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
train
216,387
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]: """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
[ "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
train
216,388
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]: """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
[ "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
train
216,389
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]): """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)
[ "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
train
216,390
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: """ 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)]
[ "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
train
216,391
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): """ 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)
[ "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
train
216,392
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]: """ 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
[ "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
train
216,393
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]: """ 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, )
[ "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
train
216,394
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]: """ 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, )
[ "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
train
216,395
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]: """ 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, )
[ "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
train
216,396
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): """ 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, )
[ "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
train
216,397
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): """ 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)
[ "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
train
216,398
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): """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 }
[ "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
train
216,399