id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,900 | neovim/pynvim | pynvim/api/nvim.py | Nvim.from_nvim | def from_nvim(cls, nvim):
"""Create a new Nvim instance from an existing instance."""
return cls(nvim._session, nvim.channel_id, nvim.metadata,
nvim.types, nvim._decode, nvim._err_cb) | python | def from_nvim(cls, nvim):
return cls(nvim._session, nvim.channel_id, nvim.metadata,
nvim.types, nvim._decode, nvim._err_cb) | [
"def",
"from_nvim",
"(",
"cls",
",",
"nvim",
")",
":",
"return",
"cls",
"(",
"nvim",
".",
"_session",
",",
"nvim",
".",
"channel_id",
",",
"nvim",
".",
"metadata",
",",
"nvim",
".",
"types",
",",
"nvim",
".",
"_decode",
",",
"nvim",
".",
"_err_cb",
... | Create a new Nvim instance from an existing instance. | [
"Create",
"a",
"new",
"Nvim",
"instance",
"from",
"an",
"existing",
"instance",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L95-L98 |
228,901 | neovim/pynvim | pynvim/api/nvim.py | Nvim.request | def request(self, name, *args, **kwargs):
r"""Send an API request or notification to nvim.
It is rarely needed to call this function directly, as most API
functions have python wrapper functions. The `api` object can
be also be used to call API functions as methods:
vim.api.err_write('ERROR\n', async_=True)
vim.current.buffer.api.get_mark('.')
is equivalent to
vim.request('nvim_err_write', 'ERROR\n', async_=True)
vim.request('nvim_buf_get_mark', vim.current.buffer, '.')
Normally a blocking request will be sent. If the `async_` flag is
present and True, a asynchronous notification is sent instead. This
will never block, and the return value or error is ignored.
"""
if (self._session._loop_thread is not None
and threading.current_thread() != self._session._loop_thread):
msg = ("Request from non-main thread.\n"
"Requests from different threads should be wrapped "
"with nvim.async_call(cb, ...) \n{}\n"
.format('\n'.join(format_stack(None, 5)[:-1])))
self.async_call(self._err_cb, msg)
raise NvimError("request from non-main thread")
decode = kwargs.pop('decode', self._decode)
args = walk(self._to_nvim, args)
res = self._session.request(name, *args, **kwargs)
return walk(self._from_nvim, res, decode=decode) | python | def request(self, name, *args, **kwargs):
r"""Send an API request or notification to nvim.
It is rarely needed to call this function directly, as most API
functions have python wrapper functions. The `api` object can
be also be used to call API functions as methods:
vim.api.err_write('ERROR\n', async_=True)
vim.current.buffer.api.get_mark('.')
is equivalent to
vim.request('nvim_err_write', 'ERROR\n', async_=True)
vim.request('nvim_buf_get_mark', vim.current.buffer, '.')
Normally a blocking request will be sent. If the `async_` flag is
present and True, a asynchronous notification is sent instead. This
will never block, and the return value or error is ignored.
"""
if (self._session._loop_thread is not None
and threading.current_thread() != self._session._loop_thread):
msg = ("Request from non-main thread.\n"
"Requests from different threads should be wrapped "
"with nvim.async_call(cb, ...) \n{}\n"
.format('\n'.join(format_stack(None, 5)[:-1])))
self.async_call(self._err_cb, msg)
raise NvimError("request from non-main thread")
decode = kwargs.pop('decode', self._decode)
args = walk(self._to_nvim, args)
res = self._session.request(name, *args, **kwargs)
return walk(self._from_nvim, res, decode=decode) | [
"def",
"request",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"self",
".",
"_session",
".",
"_loop_thread",
"is",
"not",
"None",
"and",
"threading",
".",
"current_thread",
"(",
")",
"!=",
"self",
".",
"... | r"""Send an API request or notification to nvim.
It is rarely needed to call this function directly, as most API
functions have python wrapper functions. The `api` object can
be also be used to call API functions as methods:
vim.api.err_write('ERROR\n', async_=True)
vim.current.buffer.api.get_mark('.')
is equivalent to
vim.request('nvim_err_write', 'ERROR\n', async_=True)
vim.request('nvim_buf_get_mark', vim.current.buffer, '.')
Normally a blocking request will be sent. If the `async_` flag is
present and True, a asynchronous notification is sent instead. This
will never block, and the return value or error is ignored. | [
"r",
"Send",
"an",
"API",
"request",
"or",
"notification",
"to",
"nvim",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L149-L183 |
228,902 | neovim/pynvim | pynvim/api/nvim.py | Nvim.with_decode | def with_decode(self, decode=True):
"""Initialize a new Nvim instance."""
return Nvim(self._session, self.channel_id,
self.metadata, self.types, decode, self._err_cb) | python | def with_decode(self, decode=True):
return Nvim(self._session, self.channel_id,
self.metadata, self.types, decode, self._err_cb) | [
"def",
"with_decode",
"(",
"self",
",",
"decode",
"=",
"True",
")",
":",
"return",
"Nvim",
"(",
"self",
".",
"_session",
",",
"self",
".",
"channel_id",
",",
"self",
".",
"metadata",
",",
"self",
".",
"types",
",",
"decode",
",",
"self",
".",
"_err_c... | Initialize a new Nvim instance. | [
"Initialize",
"a",
"new",
"Nvim",
"instance",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L250-L253 |
228,903 | neovim/pynvim | pynvim/api/nvim.py | Nvim.ui_attach | def ui_attach(self, width, height, rgb=None, **kwargs):
"""Register as a remote UI.
After this method is called, the client will receive redraw
notifications.
"""
options = kwargs
if rgb is not None:
options['rgb'] = rgb
return self.request('nvim_ui_attach', width, height, options) | python | def ui_attach(self, width, height, rgb=None, **kwargs):
options = kwargs
if rgb is not None:
options['rgb'] = rgb
return self.request('nvim_ui_attach', width, height, options) | [
"def",
"ui_attach",
"(",
"self",
",",
"width",
",",
"height",
",",
"rgb",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"kwargs",
"if",
"rgb",
"is",
"not",
"None",
":",
"options",
"[",
"'rgb'",
"]",
"=",
"rgb",
"return",
"self",
... | Register as a remote UI.
After this method is called, the client will receive redraw
notifications. | [
"Register",
"as",
"a",
"remote",
"UI",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L255-L264 |
228,904 | neovim/pynvim | pynvim/api/nvim.py | Nvim.call | def call(self, name, *args, **kwargs):
"""Call a vimscript function."""
return self.request('nvim_call_function', name, args, **kwargs) | python | def call(self, name, *args, **kwargs):
return self.request('nvim_call_function', name, args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'nvim_call_function'",
",",
"name",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call a vimscript function. | [
"Call",
"a",
"vimscript",
"function",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L297-L299 |
228,905 | neovim/pynvim | pynvim/api/nvim.py | Nvim.exec_lua | def exec_lua(self, code, *args, **kwargs):
"""Execute lua code.
Additional parameters are available as `...` inside the lua chunk.
Only statements are executed. To evaluate an expression, prefix it
with `return`: `return my_function(...)`
There is a shorthand syntax to call lua functions with arguments:
nvim.lua.func(1,2)
nvim.lua.mymod.myfunction(data, async_=True)
is equivalent to
nvim.exec_lua("return func(...)", 1, 2)
nvim.exec_lua("mymod.myfunction(...)", data, async_=True)
Note that with `async_=True` there is no return value.
"""
return self.request('nvim_execute_lua', code, args, **kwargs) | python | def exec_lua(self, code, *args, **kwargs):
return self.request('nvim_execute_lua', code, args, **kwargs) | [
"def",
"exec_lua",
"(",
"self",
",",
"code",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'nvim_execute_lua'",
",",
"code",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Execute lua code.
Additional parameters are available as `...` inside the lua chunk.
Only statements are executed. To evaluate an expression, prefix it
with `return`: `return my_function(...)`
There is a shorthand syntax to call lua functions with arguments:
nvim.lua.func(1,2)
nvim.lua.mymod.myfunction(data, async_=True)
is equivalent to
nvim.exec_lua("return func(...)", 1, 2)
nvim.exec_lua("mymod.myfunction(...)", data, async_=True)
Note that with `async_=True` there is no return value. | [
"Execute",
"lua",
"code",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L301-L320 |
228,906 | neovim/pynvim | pynvim/api/nvim.py | Nvim.feedkeys | def feedkeys(self, keys, options='', escape_csi=True):
"""Push `keys` to Nvim user input buffer.
Options can be a string with the following character flags:
- 'm': Remap keys. This is default.
- 'n': Do not remap keys.
- 't': Handle keys as if typed; otherwise they are handled as if coming
from a mapping. This matters for undo, opening folds, etc.
"""
return self.request('nvim_feedkeys', keys, options, escape_csi) | python | def feedkeys(self, keys, options='', escape_csi=True):
return self.request('nvim_feedkeys', keys, options, escape_csi) | [
"def",
"feedkeys",
"(",
"self",
",",
"keys",
",",
"options",
"=",
"''",
",",
"escape_csi",
"=",
"True",
")",
":",
"return",
"self",
".",
"request",
"(",
"'nvim_feedkeys'",
",",
"keys",
",",
"options",
",",
"escape_csi",
")"
] | Push `keys` to Nvim user input buffer.
Options can be a string with the following character flags:
- 'm': Remap keys. This is default.
- 'n': Do not remap keys.
- 't': Handle keys as if typed; otherwise they are handled as if coming
from a mapping. This matters for undo, opening folds, etc. | [
"Push",
"keys",
"to",
"Nvim",
"user",
"input",
"buffer",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L353-L362 |
228,907 | neovim/pynvim | pynvim/api/nvim.py | Nvim.replace_termcodes | def replace_termcodes(self, string, from_part=False, do_lt=True,
special=True):
r"""Replace any terminal code strings by byte sequences.
The returned sequences are Nvim's internal representation of keys,
for example:
<esc> -> '\x1b'
<cr> -> '\r'
<c-l> -> '\x0c'
<up> -> '\x80ku'
The returned sequences can be used as input to `feedkeys`.
"""
return self.request('nvim_replace_termcodes', string,
from_part, do_lt, special) | python | def replace_termcodes(self, string, from_part=False, do_lt=True,
special=True):
r"""Replace any terminal code strings by byte sequences.
The returned sequences are Nvim's internal representation of keys,
for example:
<esc> -> '\x1b'
<cr> -> '\r'
<c-l> -> '\x0c'
<up> -> '\x80ku'
The returned sequences can be used as input to `feedkeys`.
"""
return self.request('nvim_replace_termcodes', string,
from_part, do_lt, special) | [
"def",
"replace_termcodes",
"(",
"self",
",",
"string",
",",
"from_part",
"=",
"False",
",",
"do_lt",
"=",
"True",
",",
"special",
"=",
"True",
")",
":",
"return",
"self",
".",
"request",
"(",
"'nvim_replace_termcodes'",
",",
"string",
",",
"from_part",
",... | r"""Replace any terminal code strings by byte sequences.
The returned sequences are Nvim's internal representation of keys,
for example:
<esc> -> '\x1b'
<cr> -> '\r'
<c-l> -> '\x0c'
<up> -> '\x80ku'
The returned sequences can be used as input to `feedkeys`. | [
"r",
"Replace",
"any",
"terminal",
"code",
"strings",
"by",
"byte",
"sequences",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L374-L389 |
228,908 | neovim/pynvim | pynvim/api/nvim.py | Nvim.err_write | def err_write(self, msg, **kwargs):
r"""Print `msg` as an error message.
The message is buffered (won't display) until linefeed ("\n").
"""
if self._thread_invalid():
# special case: if a non-main thread writes to stderr
# i.e. due to an uncaught exception, pass it through
# without raising an additional exception.
self.async_call(self.err_write, msg, **kwargs)
return
return self.request('nvim_err_write', msg, **kwargs) | python | def err_write(self, msg, **kwargs):
r"""Print `msg` as an error message.
The message is buffered (won't display) until linefeed ("\n").
"""
if self._thread_invalid():
# special case: if a non-main thread writes to stderr
# i.e. due to an uncaught exception, pass it through
# without raising an additional exception.
self.async_call(self.err_write, msg, **kwargs)
return
return self.request('nvim_err_write', msg, **kwargs) | [
"def",
"err_write",
"(",
"self",
",",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_thread_invalid",
"(",
")",
":",
"# special case: if a non-main thread writes to stderr",
"# i.e. due to an uncaught exception, pass it through",
"# without raising an additi... | r"""Print `msg` as an error message.
The message is buffered (won't display) until linefeed ("\n"). | [
"r",
"Print",
"msg",
"as",
"an",
"error",
"message",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L398-L409 |
228,909 | neovim/pynvim | pynvim/api/nvim.py | Nvim.async_call | def async_call(self, fn, *args, **kwargs):
"""Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, just before it returns, to defer execution
that shouldn't block neovim.
"""
call_point = ''.join(format_stack(None, 5)[:-1])
def handler():
try:
fn(*args, **kwargs)
except Exception as err:
msg = ("error caught while executing async callback:\n"
"{!r}\n{}\n \nthe call was requested at\n{}"
.format(err, format_exc_skip(1), call_point))
self._err_cb(msg)
raise
self._session.threadsafe_call(handler) | python | def async_call(self, fn, *args, **kwargs):
call_point = ''.join(format_stack(None, 5)[:-1])
def handler():
try:
fn(*args, **kwargs)
except Exception as err:
msg = ("error caught while executing async callback:\n"
"{!r}\n{}\n \nthe call was requested at\n{}"
.format(err, format_exc_skip(1), call_point))
self._err_cb(msg)
raise
self._session.threadsafe_call(handler) | [
"def",
"async_call",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"call_point",
"=",
"''",
".",
"join",
"(",
"format_stack",
"(",
"None",
",",
"5",
")",
"[",
":",
"-",
"1",
"]",
")",
"def",
"handler",
"(",
")",
... | Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, just before it returns, to defer execution
that shouldn't block neovim. | [
"Schedule",
"fn",
"to",
"be",
"called",
"by",
"the",
"event",
"loop",
"soon",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L433-L454 |
228,910 | neovim/pynvim | pynvim/api/buffer.py | Buffer.append | def append(self, lines, index=-1):
"""Append a string or list of lines to the buffer."""
if isinstance(lines, (basestring, bytes)):
lines = [lines]
return self.request('nvim_buf_set_lines', index, index, True, lines) | python | def append(self, lines, index=-1):
if isinstance(lines, (basestring, bytes)):
lines = [lines]
return self.request('nvim_buf_set_lines', index, index, True, lines) | [
"def",
"append",
"(",
"self",
",",
"lines",
",",
"index",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"lines",
",",
"(",
"basestring",
",",
"bytes",
")",
")",
":",
"lines",
"=",
"[",
"lines",
"]",
"return",
"self",
".",
"request",
"(",
"'nv... | Append a string or list of lines to the buffer. | [
"Append",
"a",
"string",
"or",
"list",
"of",
"lines",
"to",
"the",
"buffer",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/buffer.py#L86-L90 |
228,911 | neovim/pynvim | pynvim/api/buffer.py | Buffer.add_highlight | def add_highlight(self, hl_group, line, col_start=0,
col_end=-1, src_id=-1, async_=None,
**kwargs):
"""Add a highlight to the buffer."""
async_ = check_async(async_, kwargs, src_id != 0)
return self.request('nvim_buf_add_highlight', src_id, hl_group,
line, col_start, col_end, async_=async_) | python | def add_highlight(self, hl_group, line, col_start=0,
col_end=-1, src_id=-1, async_=None,
**kwargs):
async_ = check_async(async_, kwargs, src_id != 0)
return self.request('nvim_buf_add_highlight', src_id, hl_group,
line, col_start, col_end, async_=async_) | [
"def",
"add_highlight",
"(",
"self",
",",
"hl_group",
",",
"line",
",",
"col_start",
"=",
"0",
",",
"col_end",
"=",
"-",
"1",
",",
"src_id",
"=",
"-",
"1",
",",
"async_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"async_",
"=",
"check_async",... | Add a highlight to the buffer. | [
"Add",
"a",
"highlight",
"to",
"the",
"buffer",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/buffer.py#L100-L106 |
228,912 | neovim/pynvim | pynvim/api/buffer.py | Buffer.clear_highlight | def clear_highlight(self, src_id, line_start=0, line_end=-1, async_=None,
**kwargs):
"""Clear highlights from the buffer."""
async_ = check_async(async_, kwargs, True)
self.request('nvim_buf_clear_highlight', src_id,
line_start, line_end, async_=async_) | python | def clear_highlight(self, src_id, line_start=0, line_end=-1, async_=None,
**kwargs):
async_ = check_async(async_, kwargs, True)
self.request('nvim_buf_clear_highlight', src_id,
line_start, line_end, async_=async_) | [
"def",
"clear_highlight",
"(",
"self",
",",
"src_id",
",",
"line_start",
"=",
"0",
",",
"line_end",
"=",
"-",
"1",
",",
"async_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"async_",
"=",
"check_async",
"(",
"async_",
",",
"kwargs",
",",
"True",... | Clear highlights from the buffer. | [
"Clear",
"highlights",
"from",
"the",
"buffer",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/buffer.py#L108-L113 |
228,913 | neovim/pynvim | pynvim/api/buffer.py | Buffer.update_highlights | def update_highlights(self, src_id, hls, clear_start=0, clear_end=-1,
clear=False, async_=True):
"""Add or update highlights in batch to avoid unnecessary redraws.
A `src_id` must have been allocated prior to use of this function. Use
for instance `nvim.new_highlight_source()` to get a src_id for your
plugin.
`hls` should be a list of highlight items. Each item should be a list
or tuple on the form `("GroupName", linenr, col_start, col_end)` or
`("GroupName", linenr)` to highlight an entire line.
By default existing highlights are preserved. Specify a line range with
clear_start and clear_end to replace highlights in this range. As a
shorthand, use clear=True to clear the entire buffer before adding the
new highlights.
"""
if clear and clear_start is None:
clear_start = 0
lua = self._session._get_lua_private()
lua.update_highlights(self, src_id, hls, clear_start, clear_end,
async_=async_) | python | def update_highlights(self, src_id, hls, clear_start=0, clear_end=-1,
clear=False, async_=True):
if clear and clear_start is None:
clear_start = 0
lua = self._session._get_lua_private()
lua.update_highlights(self, src_id, hls, clear_start, clear_end,
async_=async_) | [
"def",
"update_highlights",
"(",
"self",
",",
"src_id",
",",
"hls",
",",
"clear_start",
"=",
"0",
",",
"clear_end",
"=",
"-",
"1",
",",
"clear",
"=",
"False",
",",
"async_",
"=",
"True",
")",
":",
"if",
"clear",
"and",
"clear_start",
"is",
"None",
":... | Add or update highlights in batch to avoid unnecessary redraws.
A `src_id` must have been allocated prior to use of this function. Use
for instance `nvim.new_highlight_source()` to get a src_id for your
plugin.
`hls` should be a list of highlight items. Each item should be a list
or tuple on the form `("GroupName", linenr, col_start, col_end)` or
`("GroupName", linenr)` to highlight an entire line.
By default existing highlights are preserved. Specify a line range with
clear_start and clear_end to replace highlights in this range. As a
shorthand, use clear=True to clear the entire buffer before adding the
new highlights. | [
"Add",
"or",
"update",
"highlights",
"in",
"batch",
"to",
"avoid",
"unnecessary",
"redraws",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/buffer.py#L115-L136 |
228,914 | neovim/pynvim | pynvim/plugin/host.py | Host.start | def start(self, plugins):
"""Start listening for msgpack-rpc requests and notifications."""
self.nvim.run_loop(self._on_request,
self._on_notification,
lambda: self._load(plugins),
err_cb=self._on_async_err) | python | def start(self, plugins):
self.nvim.run_loop(self._on_request,
self._on_notification,
lambda: self._load(plugins),
err_cb=self._on_async_err) | [
"def",
"start",
"(",
"self",
",",
"plugins",
")",
":",
"self",
".",
"nvim",
".",
"run_loop",
"(",
"self",
".",
"_on_request",
",",
"self",
".",
"_on_notification",
",",
"lambda",
":",
"self",
".",
"_load",
"(",
"plugins",
")",
",",
"err_cb",
"=",
"se... | Start listening for msgpack-rpc requests and notifications. | [
"Start",
"listening",
"for",
"msgpack",
"-",
"rpc",
"requests",
"and",
"notifications",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/host.py#L64-L69 |
228,915 | neovim/pynvim | pynvim/plugin/host.py | Host._on_request | def _on_request(self, name, args):
"""Handle a msgpack-rpc request."""
if IS_PYTHON3:
name = decode_if_bytes(name)
handler = self._request_handlers.get(name, None)
if not handler:
msg = self._missing_handler_error(name, 'request')
error(msg)
raise ErrorResponse(msg)
debug('calling request handler for "%s", args: "%s"', name, args)
rv = handler(*args)
debug("request handler for '%s %s' returns: %s", name, args, rv)
return rv | python | def _on_request(self, name, args):
if IS_PYTHON3:
name = decode_if_bytes(name)
handler = self._request_handlers.get(name, None)
if not handler:
msg = self._missing_handler_error(name, 'request')
error(msg)
raise ErrorResponse(msg)
debug('calling request handler for "%s", args: "%s"', name, args)
rv = handler(*args)
debug("request handler for '%s %s' returns: %s", name, args, rv)
return rv | [
"def",
"_on_request",
"(",
"self",
",",
"name",
",",
"args",
")",
":",
"if",
"IS_PYTHON3",
":",
"name",
"=",
"decode_if_bytes",
"(",
"name",
")",
"handler",
"=",
"self",
".",
"_request_handlers",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"not",
... | Handle a msgpack-rpc request. | [
"Handle",
"a",
"msgpack",
"-",
"rpc",
"request",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/host.py#L93-L106 |
228,916 | neovim/pynvim | pynvim/plugin/host.py | Host._on_notification | def _on_notification(self, name, args):
"""Handle a msgpack-rpc notification."""
if IS_PYTHON3:
name = decode_if_bytes(name)
handler = self._notification_handlers.get(name, None)
if not handler:
msg = self._missing_handler_error(name, 'notification')
error(msg)
self._on_async_err(msg + "\n")
return
debug('calling notification handler for "%s", args: "%s"', name, args)
handler(*args) | python | def _on_notification(self, name, args):
if IS_PYTHON3:
name = decode_if_bytes(name)
handler = self._notification_handlers.get(name, None)
if not handler:
msg = self._missing_handler_error(name, 'notification')
error(msg)
self._on_async_err(msg + "\n")
return
debug('calling notification handler for "%s", args: "%s"', name, args)
handler(*args) | [
"def",
"_on_notification",
"(",
"self",
",",
"name",
",",
"args",
")",
":",
"if",
"IS_PYTHON3",
":",
"name",
"=",
"decode_if_bytes",
"(",
"name",
")",
"handler",
"=",
"self",
".",
"_notification_handlers",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",... | Handle a msgpack-rpc notification. | [
"Handle",
"a",
"msgpack",
"-",
"rpc",
"notification",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/host.py#L108-L120 |
228,917 | neovim/pynvim | pynvim/api/common.py | decode_if_bytes | def decode_if_bytes(obj, mode=True):
"""Decode obj if it is bytes."""
if mode is True:
mode = unicode_errors_default
if isinstance(obj, bytes):
return obj.decode("utf-8", errors=mode)
return obj | python | def decode_if_bytes(obj, mode=True):
if mode is True:
mode = unicode_errors_default
if isinstance(obj, bytes):
return obj.decode("utf-8", errors=mode)
return obj | [
"def",
"decode_if_bytes",
"(",
"obj",
",",
"mode",
"=",
"True",
")",
":",
"if",
"mode",
"is",
"True",
":",
"mode",
"=",
"unicode_errors_default",
"if",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
":",
"return",
"obj",
".",
"decode",
"(",
"\"utf-8\"",
... | Decode obj if it is bytes. | [
"Decode",
"obj",
"if",
"it",
"is",
"bytes",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/common.py#L164-L170 |
228,918 | neovim/pynvim | pynvim/api/common.py | Remote.request | def request(self, name, *args, **kwargs):
"""Wrapper for nvim.request."""
return self._session.request(name, self, *args, **kwargs) | python | def request(self, name, *args, **kwargs):
return self._session.request(name, self, *args, **kwargs) | [
"def",
"request",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_session",
".",
"request",
"(",
"name",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Wrapper for nvim.request. | [
"Wrapper",
"for",
"nvim",
".",
"request",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/common.py#L49-L51 |
228,919 | neovim/pynvim | pynvim/msgpack_rpc/msgpack_stream.py | MsgpackStream.send | def send(self, msg):
"""Queue `msg` for sending to Nvim."""
debug('sent %s', msg)
self.loop.send(self._packer.pack(msg)) | python | def send(self, msg):
debug('sent %s', msg)
self.loop.send(self._packer.pack(msg)) | [
"def",
"send",
"(",
"self",
",",
"msg",
")",
":",
"debug",
"(",
"'sent %s'",
",",
"msg",
")",
"self",
".",
"loop",
".",
"send",
"(",
"self",
".",
"_packer",
".",
"pack",
"(",
"msg",
")",
")"
] | Queue `msg` for sending to Nvim. | [
"Queue",
"msg",
"for",
"sending",
"to",
"Nvim",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/msgpack_stream.py#L31-L34 |
228,920 | neovim/pynvim | pynvim/msgpack_rpc/msgpack_stream.py | MsgpackStream.run | def run(self, message_cb):
"""Run the event loop to receive messages from Nvim.
While the event loop is running, `message_cb` will be called whenever
a message has been successfully parsed from the input stream.
"""
self._message_cb = message_cb
self.loop.run(self._on_data)
self._message_cb = None | python | def run(self, message_cb):
self._message_cb = message_cb
self.loop.run(self._on_data)
self._message_cb = None | [
"def",
"run",
"(",
"self",
",",
"message_cb",
")",
":",
"self",
".",
"_message_cb",
"=",
"message_cb",
"self",
".",
"loop",
".",
"run",
"(",
"self",
".",
"_on_data",
")",
"self",
".",
"_message_cb",
"=",
"None"
] | Run the event loop to receive messages from Nvim.
While the event loop is running, `message_cb` will be called whenever
a message has been successfully parsed from the input stream. | [
"Run",
"the",
"event",
"loop",
"to",
"receive",
"messages",
"from",
"Nvim",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/msgpack_stream.py#L36-L44 |
228,921 | neovim/pynvim | pynvim/msgpack_rpc/session.py | Session.threadsafe_call | def threadsafe_call(self, fn, *args, **kwargs):
"""Wrapper around `AsyncSession.threadsafe_call`."""
def handler():
try:
fn(*args, **kwargs)
except Exception:
warn("error caught while excecuting async callback\n%s\n",
format_exc())
def greenlet_wrapper():
gr = greenlet.greenlet(handler)
gr.switch()
self._async_session.threadsafe_call(greenlet_wrapper) | python | def threadsafe_call(self, fn, *args, **kwargs):
def handler():
try:
fn(*args, **kwargs)
except Exception:
warn("error caught while excecuting async callback\n%s\n",
format_exc())
def greenlet_wrapper():
gr = greenlet.greenlet(handler)
gr.switch()
self._async_session.threadsafe_call(greenlet_wrapper) | [
"def",
"threadsafe_call",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"handler",
"(",
")",
":",
"try",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"warn",
"(",
"... | Wrapper around `AsyncSession.threadsafe_call`. | [
"Wrapper",
"around",
"AsyncSession",
".",
"threadsafe_call",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/session.py#L35-L48 |
228,922 | neovim/pynvim | pynvim/msgpack_rpc/session.py | Session.request | def request(self, method, *args, **kwargs):
"""Send a msgpack-rpc request and block until as response is received.
If the event loop is running, this method must have been called by a
request or notification handler running on a greenlet. In that case,
send the quest and yield to the parent greenlet until a response is
available.
When the event loop is not running, it will perform a blocking request
like this:
- Send the request
- Run the loop until the response is available
- Put requests/notifications received while waiting into a queue
If the `async_` flag is present and True, a asynchronous notification
is sent instead. This will never block, and the return value or error
is ignored.
"""
async_ = check_async(kwargs.pop('async_', None), kwargs, False)
if async_:
self._async_session.notify(method, args)
return
if kwargs:
raise ValueError("request got unsupported keyword argument(s): {}"
.format(', '.join(kwargs.keys())))
if self._is_running:
v = self._yielding_request(method, args)
else:
v = self._blocking_request(method, args)
if not v:
# EOF
raise IOError('EOF')
err, rv = v
if err:
info("'Received error: %s", err)
raise self.error_wrapper(err)
return rv | python | def request(self, method, *args, **kwargs):
async_ = check_async(kwargs.pop('async_', None), kwargs, False)
if async_:
self._async_session.notify(method, args)
return
if kwargs:
raise ValueError("request got unsupported keyword argument(s): {}"
.format(', '.join(kwargs.keys())))
if self._is_running:
v = self._yielding_request(method, args)
else:
v = self._blocking_request(method, args)
if not v:
# EOF
raise IOError('EOF')
err, rv = v
if err:
info("'Received error: %s", err)
raise self.error_wrapper(err)
return rv | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"async_",
"=",
"check_async",
"(",
"kwargs",
".",
"pop",
"(",
"'async_'",
",",
"None",
")",
",",
"kwargs",
",",
"False",
")",
"if",
"async_",
":",
... | Send a msgpack-rpc request and block until as response is received.
If the event loop is running, this method must have been called by a
request or notification handler running on a greenlet. In that case,
send the quest and yield to the parent greenlet until a response is
available.
When the event loop is not running, it will perform a blocking request
like this:
- Send the request
- Run the loop until the response is available
- Put requests/notifications received while waiting into a queue
If the `async_` flag is present and True, a asynchronous notification
is sent instead. This will never block, and the return value or error
is ignored. | [
"Send",
"a",
"msgpack",
"-",
"rpc",
"request",
"and",
"block",
"until",
"as",
"response",
"is",
"received",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/session.py#L65-L103 |
228,923 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.Clone | def Clone(self):
"""
Clone self.
Returns:
AccountState:
"""
return AccountState(self.ScriptHash, self.IsFrozen, self.Votes, self.Balances) | python | def Clone(self):
return AccountState(self.ScriptHash, self.IsFrozen, self.Votes, self.Balances) | [
"def",
"Clone",
"(",
"self",
")",
":",
"return",
"AccountState",
"(",
"self",
".",
"ScriptHash",
",",
"self",
".",
"IsFrozen",
",",
"self",
".",
"Votes",
",",
"self",
".",
"Balances",
")"
] | Clone self.
Returns:
AccountState: | [
"Clone",
"self",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L63-L70 |
228,924 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.HasBalance | def HasBalance(self, assetId):
"""
Flag indicating if the asset has a balance.
Args:
assetId (UInt256):
Returns:
bool: True if a balance is present. False otherwise.
"""
for key, fixed8 in self.Balances.items():
if key == assetId:
return True
return False | python | def HasBalance(self, assetId):
for key, fixed8 in self.Balances.items():
if key == assetId:
return True
return False | [
"def",
"HasBalance",
"(",
"self",
",",
"assetId",
")",
":",
"for",
"key",
",",
"fixed8",
"in",
"self",
".",
"Balances",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"assetId",
":",
"return",
"True",
"return",
"False"
] | Flag indicating if the asset has a balance.
Args:
assetId (UInt256):
Returns:
bool: True if a balance is present. False otherwise. | [
"Flag",
"indicating",
"if",
"the",
"asset",
"has",
"a",
"balance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L154-L167 |
228,925 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.BalanceFor | def BalanceFor(self, assetId):
"""
Get the balance for a given asset id.
Args:
assetId (UInt256):
Returns:
Fixed8: balance value.
"""
for key, fixed8 in self.Balances.items():
if key == assetId:
return fixed8
return Fixed8(0) | python | def BalanceFor(self, assetId):
for key, fixed8 in self.Balances.items():
if key == assetId:
return fixed8
return Fixed8(0) | [
"def",
"BalanceFor",
"(",
"self",
",",
"assetId",
")",
":",
"for",
"key",
",",
"fixed8",
"in",
"self",
".",
"Balances",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"assetId",
":",
"return",
"fixed8",
"return",
"Fixed8",
"(",
"0",
")"
] | Get the balance for a given asset id.
Args:
assetId (UInt256):
Returns:
Fixed8: balance value. | [
"Get",
"the",
"balance",
"for",
"a",
"given",
"asset",
"id",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L169-L182 |
228,926 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.AddToBalance | def AddToBalance(self, assetId, fixed8_val):
"""
Add amount to the specified balance.
Args:
assetId (UInt256):
fixed8_val (Fixed8): amount to add.
"""
found = False
for key, balance in self.Balances.items():
if key == assetId:
self.Balances[assetId] = self.Balances[assetId] + fixed8_val
found = True
if not found:
self.Balances[assetId] = fixed8_val | python | def AddToBalance(self, assetId, fixed8_val):
found = False
for key, balance in self.Balances.items():
if key == assetId:
self.Balances[assetId] = self.Balances[assetId] + fixed8_val
found = True
if not found:
self.Balances[assetId] = fixed8_val | [
"def",
"AddToBalance",
"(",
"self",
",",
"assetId",
",",
"fixed8_val",
")",
":",
"found",
"=",
"False",
"for",
"key",
",",
"balance",
"in",
"self",
".",
"Balances",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"assetId",
":",
"self",
".",
"Balance... | Add amount to the specified balance.
Args:
assetId (UInt256):
fixed8_val (Fixed8): amount to add. | [
"Add",
"amount",
"to",
"the",
"specified",
"balance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L200-L214 |
228,927 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.SubtractFromBalance | def SubtractFromBalance(self, assetId, fixed8_val):
"""
Subtract amount to the specified balance.
Args:
assetId (UInt256):
fixed8_val (Fixed8): amount to add.
"""
found = False
for key, balance in self.Balances.items():
if key == assetId:
self.Balances[assetId] = self.Balances[assetId] - fixed8_val
found = True
if not found:
self.Balances[assetId] = fixed8_val * Fixed8(-1) | python | def SubtractFromBalance(self, assetId, fixed8_val):
found = False
for key, balance in self.Balances.items():
if key == assetId:
self.Balances[assetId] = self.Balances[assetId] - fixed8_val
found = True
if not found:
self.Balances[assetId] = fixed8_val * Fixed8(-1) | [
"def",
"SubtractFromBalance",
"(",
"self",
",",
"assetId",
",",
"fixed8_val",
")",
":",
"found",
"=",
"False",
"for",
"key",
",",
"balance",
"in",
"self",
".",
"Balances",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"assetId",
":",
"self",
".",
"... | Subtract amount to the specified balance.
Args:
assetId (UInt256):
fixed8_val (Fixed8): amount to add. | [
"Subtract",
"amount",
"to",
"the",
"specified",
"balance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L216-L230 |
228,928 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.AllBalancesZeroOrLess | def AllBalancesZeroOrLess(self):
"""
Flag indicating if all balances are 0 or less.
Returns:
bool: True if all balances are <= 0. False, otherwise.
"""
for key, fixed8 in self.Balances.items():
if fixed8.value > 0:
return False
return True | python | def AllBalancesZeroOrLess(self):
for key, fixed8 in self.Balances.items():
if fixed8.value > 0:
return False
return True | [
"def",
"AllBalancesZeroOrLess",
"(",
"self",
")",
":",
"for",
"key",
",",
"fixed8",
"in",
"self",
".",
"Balances",
".",
"items",
"(",
")",
":",
"if",
"fixed8",
".",
"value",
">",
"0",
":",
"return",
"False",
"return",
"True"
] | Flag indicating if all balances are 0 or less.
Returns:
bool: True if all balances are <= 0. False, otherwise. | [
"Flag",
"indicating",
"if",
"all",
"balances",
"are",
"0",
"or",
"less",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L232-L242 |
228,929 | CityOfZion/neo-python | neo/Core/State/AccountState.py | AccountState.ToByteArray | def ToByteArray(self):
"""
Serialize self and get the byte stream.
Returns:
bytes: serialized object.
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.Serialize(writer)
retval = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retval | python | def ToByteArray(self):
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.Serialize(writer)
retval = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retval | [
"def",
"ToByteArray",
"(",
"self",
")",
":",
"ms",
"=",
"StreamManager",
".",
"GetStream",
"(",
")",
"writer",
"=",
"BinaryWriter",
"(",
"ms",
")",
"self",
".",
"Serialize",
"(",
"writer",
")",
"retval",
"=",
"ms",
".",
"ToArray",
"(",
")",
"StreamMana... | Serialize self and get the byte stream.
Returns:
bytes: serialized object. | [
"Serialize",
"self",
"and",
"get",
"the",
"byte",
"stream",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L244-L258 |
228,930 | CityOfZion/neo-python | neo/Implementations/Notifications/LevelDB/NotificationDB.py | NotificationDB.start | def start(self):
"""
Handle EventHub events for SmartContract decorators
"""
self._events_to_write = []
self._new_contracts_to_write = []
@events.on(SmartContractEvent.CONTRACT_CREATED)
@events.on(SmartContractEvent.CONTRACT_MIGRATED)
def call_on_success_event(sc_event: SmartContractEvent):
self.on_smart_contract_created(sc_event)
@events.on(SmartContractEvent.RUNTIME_NOTIFY)
def call_on_event(sc_event: NotifyEvent):
self.on_smart_contract_event(sc_event)
Blockchain.Default().PersistCompleted.on_change += self.on_persist_completed | python | def start(self):
self._events_to_write = []
self._new_contracts_to_write = []
@events.on(SmartContractEvent.CONTRACT_CREATED)
@events.on(SmartContractEvent.CONTRACT_MIGRATED)
def call_on_success_event(sc_event: SmartContractEvent):
self.on_smart_contract_created(sc_event)
@events.on(SmartContractEvent.RUNTIME_NOTIFY)
def call_on_event(sc_event: NotifyEvent):
self.on_smart_contract_event(sc_event)
Blockchain.Default().PersistCompleted.on_change += self.on_persist_completed | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_events_to_write",
"=",
"[",
"]",
"self",
".",
"_new_contracts_to_write",
"=",
"[",
"]",
"@",
"events",
".",
"on",
"(",
"SmartContractEvent",
".",
"CONTRACT_CREATED",
")",
"@",
"events",
".",
"on",
"("... | Handle EventHub events for SmartContract decorators | [
"Handle",
"EventHub",
"events",
"for",
"SmartContract",
"decorators"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Notifications/LevelDB/NotificationDB.py#L78-L94 |
228,931 | CityOfZion/neo-python | neo/Core/Header.py | Header.FromTrimmedData | def FromTrimmedData(data, index):
"""
Deserialize into a Header object from the provided data.
Args:
data (bytes):
index: UNUSED
Returns:
Header:
"""
header = Header()
ms = StreamManager.GetStream(data)
reader = BinaryReader(ms)
header.DeserializeUnsigned(reader)
reader.ReadByte()
witness = Witness()
witness.Deserialize(reader)
header.Script = witness
StreamManager.ReleaseStream(ms)
return header | python | def FromTrimmedData(data, index):
header = Header()
ms = StreamManager.GetStream(data)
reader = BinaryReader(ms)
header.DeserializeUnsigned(reader)
reader.ReadByte()
witness = Witness()
witness.Deserialize(reader)
header.Script = witness
StreamManager.ReleaseStream(ms)
return header | [
"def",
"FromTrimmedData",
"(",
"data",
",",
"index",
")",
":",
"header",
"=",
"Header",
"(",
")",
"ms",
"=",
"StreamManager",
".",
"GetStream",
"(",
"data",
")",
"reader",
"=",
"BinaryReader",
"(",
"ms",
")",
"header",
".",
"DeserializeUnsigned",
"(",
"r... | Deserialize into a Header object from the provided data.
Args:
data (bytes):
index: UNUSED
Returns:
Header: | [
"Deserialize",
"into",
"a",
"Header",
"object",
"from",
"the",
"provided",
"data",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Header.py#L59-L84 |
228,932 | CityOfZion/neo-python | neo/SmartContract/ContractParameterType.py | ContractParameterType.FromString | def FromString(val):
"""
Create a ContractParameterType object from a str
Args:
val (str): the value to be converted to a ContractParameterType.
val can be hex encoded (b'07'), int (7), string int ("7"), or string literal ("String")
Returns:
ContractParameterType
"""
# first, check if the value supplied is the string literal of the enum (e.g. "String")
if isinstance(val, bytes):
val = val.decode('utf-8')
try:
return ContractParameterType[val]
except Exception as e:
# ignore a KeyError if the val isn't found in the Enum
pass
# second, check if the value supplied is bytes or hex-encoded (e.g. b'07')
try:
if isinstance(val, (bytearray, bytes)):
int_val = int.from_bytes(val, 'little')
else:
int_val = int.from_bytes(binascii.unhexlify(val), 'little')
except (binascii.Error, TypeError) as e:
# if it's not hex-encoded, then convert as int (e.g. "7" or 7)
int_val = int(val)
return ContractParameterType(int_val) | python | def FromString(val):
# first, check if the value supplied is the string literal of the enum (e.g. "String")
if isinstance(val, bytes):
val = val.decode('utf-8')
try:
return ContractParameterType[val]
except Exception as e:
# ignore a KeyError if the val isn't found in the Enum
pass
# second, check if the value supplied is bytes or hex-encoded (e.g. b'07')
try:
if isinstance(val, (bytearray, bytes)):
int_val = int.from_bytes(val, 'little')
else:
int_val = int.from_bytes(binascii.unhexlify(val), 'little')
except (binascii.Error, TypeError) as e:
# if it's not hex-encoded, then convert as int (e.g. "7" or 7)
int_val = int(val)
return ContractParameterType(int_val) | [
"def",
"FromString",
"(",
"val",
")",
":",
"# first, check if the value supplied is the string literal of the enum (e.g. \"String\")",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"val",
"=",
"val",
".",
"decode",
"(",
"'utf-8'",
")",
"try",
":",
"return"... | Create a ContractParameterType object from a str
Args:
val (str): the value to be converted to a ContractParameterType.
val can be hex encoded (b'07'), int (7), string int ("7"), or string literal ("String")
Returns:
ContractParameterType | [
"Create",
"a",
"ContractParameterType",
"object",
"from",
"a",
"str"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/ContractParameterType.py#L45-L77 |
228,933 | CityOfZion/neo-python | examples/build_raw_transactions.py | address_to_scripthash | def address_to_scripthash(address: str) -> UInt160:
"""Just a helper method"""
AddressVersion = 23 # fixed at this point
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != AddressVersion:
raise ValueError('Not correct Coin Version')
checksum_data = data[:21]
checksum = hashlib.sha256(hashlib.sha256(checksum_data).digest()).digest()[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21]) | python | def address_to_scripthash(address: str) -> UInt160:
AddressVersion = 23 # fixed at this point
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != AddressVersion:
raise ValueError('Not correct Coin Version')
checksum_data = data[:21]
checksum = hashlib.sha256(hashlib.sha256(checksum_data).digest()).digest()[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21]) | [
"def",
"address_to_scripthash",
"(",
"address",
":",
"str",
")",
"->",
"UInt160",
":",
"AddressVersion",
"=",
"23",
"# fixed at this point",
"data",
"=",
"b58decode",
"(",
"address",
")",
"if",
"len",
"(",
"data",
")",
"!=",
"25",
":",
"raise",
"ValueError",... | Just a helper method | [
"Just",
"a",
"helper",
"method"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/examples/build_raw_transactions.py#L219-L232 |
228,934 | CityOfZion/neo-python | neo/Core/FunctionCode.py | FunctionCode.HasStorage | def HasStorage(self):
"""
Flag indicating if storage is available.
Returns:
bool: True if available. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.HasStorage > 0 | python | def HasStorage(self):
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.HasStorage > 0 | [
"def",
"HasStorage",
"(",
"self",
")",
":",
"from",
"neo",
".",
"Core",
".",
"State",
".",
"ContractState",
"import",
"ContractPropertyState",
"return",
"self",
".",
"ContractProperties",
"&",
"ContractPropertyState",
".",
"HasStorage",
">",
"0"
] | Flag indicating if storage is available.
Returns:
bool: True if available. False otherwise. | [
"Flag",
"indicating",
"if",
"storage",
"is",
"available",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/FunctionCode.py#L23-L31 |
228,935 | CityOfZion/neo-python | neo/Core/FunctionCode.py | FunctionCode.HasDynamicInvoke | def HasDynamicInvoke(self):
"""
Flag indicating if dynamic invocation is supported.
Returns:
bool: True if supported. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.HasDynamicInvoke > 0 | python | def HasDynamicInvoke(self):
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.HasDynamicInvoke > 0 | [
"def",
"HasDynamicInvoke",
"(",
"self",
")",
":",
"from",
"neo",
".",
"Core",
".",
"State",
".",
"ContractState",
"import",
"ContractPropertyState",
"return",
"self",
".",
"ContractProperties",
"&",
"ContractPropertyState",
".",
"HasDynamicInvoke",
">",
"0"
] | Flag indicating if dynamic invocation is supported.
Returns:
bool: True if supported. False otherwise. | [
"Flag",
"indicating",
"if",
"dynamic",
"invocation",
"is",
"supported",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/FunctionCode.py#L34-L42 |
228,936 | CityOfZion/neo-python | neo/Core/FunctionCode.py | FunctionCode.IsPayable | def IsPayable(self):
"""
Flag indicating if the contract accepts payments.
Returns:
bool: True if supported. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.Payable > 0 | python | def IsPayable(self):
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.Payable > 0 | [
"def",
"IsPayable",
"(",
"self",
")",
":",
"from",
"neo",
".",
"Core",
".",
"State",
".",
"ContractState",
"import",
"ContractPropertyState",
"return",
"self",
".",
"ContractProperties",
"&",
"ContractPropertyState",
".",
"Payable",
">",
"0"
] | Flag indicating if the contract accepts payments.
Returns:
bool: True if supported. False otherwise. | [
"Flag",
"indicating",
"if",
"the",
"contract",
"accepts",
"payments",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/FunctionCode.py#L45-L53 |
228,937 | CityOfZion/neo-python | neo/Core/FunctionCode.py | FunctionCode.ScriptHash | def ScriptHash(self):
"""
Get the script hash.
Returns:
UInt160:
"""
if self._scriptHash is None:
self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=False)
return self._scriptHash | python | def ScriptHash(self):
if self._scriptHash is None:
self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=False)
return self._scriptHash | [
"def",
"ScriptHash",
"(",
"self",
")",
":",
"if",
"self",
".",
"_scriptHash",
"is",
"None",
":",
"self",
".",
"_scriptHash",
"=",
"Crypto",
".",
"ToScriptHash",
"(",
"self",
".",
"Script",
",",
"unhex",
"=",
"False",
")",
"return",
"self",
".",
"_scrip... | Get the script hash.
Returns:
UInt160: | [
"Get",
"the",
"script",
"hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/FunctionCode.py#L66-L76 |
228,938 | CityOfZion/neo-python | neo/Settings.py | SettingsHolder.setup | def setup(self, config_file):
""" Setup settings from a JSON config file """
def get_config_and_warn(key, default, abort=False):
value = config.get(key, None)
if not value:
print(f"Cannot find {key} in settings, using default value: {default}")
value = default
if abort:
sys.exit(-1)
return value
if not self.DATA_DIR_PATH:
# Setup default data dir
self.set_data_dir(None)
with open(config_file) as data_file:
data = json.load(data_file)
config = data['ProtocolConfiguration']
self.MAGIC = config['Magic']
self.ADDRESS_VERSION = config['AddressVersion']
self.STANDBY_VALIDATORS = config['StandbyValidators']
self.SEED_LIST = config['SeedList']
self.RPC_LIST = config['RPCList']
fees = config['SystemFee']
self.ALL_FEES = fees
self.ENROLLMENT_TX_FEE = fees['EnrollmentTransaction']
self.ISSUE_TX_FEE = fees['IssueTransaction']
self.PUBLISH_TX_FEE = fees['PublishTransaction']
self.REGISTER_TX_FEE = fees['RegisterTransaction']
config = data['ApplicationConfiguration']
self.LEVELDB_PATH = config['DataDirectoryPath']
self.RPC_PORT = int(config['RPCPort'])
self.NODE_PORT = int(config['NodePort'])
self.WS_PORT = config['WsPort']
self.URI_PREFIX = config['UriPrefix']
self.ACCEPT_INCOMING_PEERS = config.get('AcceptIncomingPeers', False)
self.BOOTSTRAP_NAME = get_config_and_warn('BootstrapName', "mainnet")
self.BOOTSTRAP_LOCATIONS = get_config_and_warn('BootstrapFiles', "abort", abort=True)
Helper.ADDRESS_VERSION = self.ADDRESS_VERSION
self.USE_DEBUG_STORAGE = config.get('DebugStorage', False)
self.DEBUG_STORAGE_PATH = config.get('DebugStoragePath', 'Chains/debugstorage')
self.NOTIFICATION_DB_PATH = config.get('NotificationDataPath', 'Chains/notification_data')
self.SERVICE_ENABLED = config.get('ServiceEnabled', self.ACCEPT_INCOMING_PEERS)
self.COMPILER_NEP_8 = config.get('CompilerNep8', False)
self.REST_SERVER = config.get('RestServer', self.DEFAULT_REST_SERVER)
self.RPC_SERVER = config.get('RPCServer', self.DEFAULT_RPC_SERVER) | python | def setup(self, config_file):
def get_config_and_warn(key, default, abort=False):
value = config.get(key, None)
if not value:
print(f"Cannot find {key} in settings, using default value: {default}")
value = default
if abort:
sys.exit(-1)
return value
if not self.DATA_DIR_PATH:
# Setup default data dir
self.set_data_dir(None)
with open(config_file) as data_file:
data = json.load(data_file)
config = data['ProtocolConfiguration']
self.MAGIC = config['Magic']
self.ADDRESS_VERSION = config['AddressVersion']
self.STANDBY_VALIDATORS = config['StandbyValidators']
self.SEED_LIST = config['SeedList']
self.RPC_LIST = config['RPCList']
fees = config['SystemFee']
self.ALL_FEES = fees
self.ENROLLMENT_TX_FEE = fees['EnrollmentTransaction']
self.ISSUE_TX_FEE = fees['IssueTransaction']
self.PUBLISH_TX_FEE = fees['PublishTransaction']
self.REGISTER_TX_FEE = fees['RegisterTransaction']
config = data['ApplicationConfiguration']
self.LEVELDB_PATH = config['DataDirectoryPath']
self.RPC_PORT = int(config['RPCPort'])
self.NODE_PORT = int(config['NodePort'])
self.WS_PORT = config['WsPort']
self.URI_PREFIX = config['UriPrefix']
self.ACCEPT_INCOMING_PEERS = config.get('AcceptIncomingPeers', False)
self.BOOTSTRAP_NAME = get_config_and_warn('BootstrapName', "mainnet")
self.BOOTSTRAP_LOCATIONS = get_config_and_warn('BootstrapFiles', "abort", abort=True)
Helper.ADDRESS_VERSION = self.ADDRESS_VERSION
self.USE_DEBUG_STORAGE = config.get('DebugStorage', False)
self.DEBUG_STORAGE_PATH = config.get('DebugStoragePath', 'Chains/debugstorage')
self.NOTIFICATION_DB_PATH = config.get('NotificationDataPath', 'Chains/notification_data')
self.SERVICE_ENABLED = config.get('ServiceEnabled', self.ACCEPT_INCOMING_PEERS)
self.COMPILER_NEP_8 = config.get('CompilerNep8', False)
self.REST_SERVER = config.get('RestServer', self.DEFAULT_REST_SERVER)
self.RPC_SERVER = config.get('RPCServer', self.DEFAULT_RPC_SERVER) | [
"def",
"setup",
"(",
"self",
",",
"config_file",
")",
":",
"def",
"get_config_and_warn",
"(",
"key",
",",
"default",
",",
"abort",
"=",
"False",
")",
":",
"value",
"=",
"config",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"not",
"value",
":",
... | Setup settings from a JSON config file | [
"Setup",
"settings",
"from",
"a",
"JSON",
"config",
"file"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Settings.py#L175-L226 |
228,939 | CityOfZion/neo-python | neo/Settings.py | SettingsHolder.setup_privnet | def setup_privnet(self, host=None):
"""
Load settings from the privnet JSON config file
Args:
host (string, optional): if supplied, uses this IP or domain as neo nodes. The host must
use these standard ports: P2P 20333, RPC 30333.
"""
self.setup(FILENAME_SETTINGS_PRIVNET)
if isinstance(host, str):
if ":" in host:
raise Exception("No protocol prefix or port allowed in host, use just the IP or domain.")
print("Using custom privatenet host:", host)
self.SEED_LIST = ["%s:20333" % host]
self.RPC_LIST = ["http://%s:30333" % host]
print("- P2P:", ", ".join(self.SEED_LIST))
print("- RPC:", ", ".join(self.RPC_LIST))
self.check_privatenet() | python | def setup_privnet(self, host=None):
self.setup(FILENAME_SETTINGS_PRIVNET)
if isinstance(host, str):
if ":" in host:
raise Exception("No protocol prefix or port allowed in host, use just the IP or domain.")
print("Using custom privatenet host:", host)
self.SEED_LIST = ["%s:20333" % host]
self.RPC_LIST = ["http://%s:30333" % host]
print("- P2P:", ", ".join(self.SEED_LIST))
print("- RPC:", ", ".join(self.RPC_LIST))
self.check_privatenet() | [
"def",
"setup_privnet",
"(",
"self",
",",
"host",
"=",
"None",
")",
":",
"self",
".",
"setup",
"(",
"FILENAME_SETTINGS_PRIVNET",
")",
"if",
"isinstance",
"(",
"host",
",",
"str",
")",
":",
"if",
"\":\"",
"in",
"host",
":",
"raise",
"Exception",
"(",
"\... | Load settings from the privnet JSON config file
Args:
host (string, optional): if supplied, uses this IP or domain as neo nodes. The host must
use these standard ports: P2P 20333, RPC 30333. | [
"Load",
"settings",
"from",
"the",
"privnet",
"JSON",
"config",
"file"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Settings.py#L236-L253 |
228,940 | CityOfZion/neo-python | neo/Settings.py | SettingsHolder.set_loglevel | def set_loglevel(self, level):
"""
Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels
"""
self.log_level = level
log_manager.config_stdio(default_level=level) | python | def set_loglevel(self, level):
self.log_level = level
log_manager.config_stdio(default_level=level) | [
"def",
"set_loglevel",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"log_level",
"=",
"level",
"log_manager",
".",
"config_stdio",
"(",
"default_level",
"=",
"level",
")"
] | Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels | [
"Set",
"the",
"minimum",
"loglevel",
"for",
"all",
"components"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Settings.py#L311-L319 |
228,941 | CityOfZion/neo-python | neo/Settings.py | SettingsHolder.check_chain_dir_exists | def check_chain_dir_exists(self, warn_migration=False):
"""
Checks to make sure there is a directory called ``Chains`` at the root of DATA_DIR_PATH
and creates it if it doesn't exist yet
"""
chain_path = os.path.join(self.DATA_DIR_PATH, 'Chains')
if not os.path.exists(chain_path):
try:
os.makedirs(chain_path)
logger.info("Created 'Chains' directory at %s " % chain_path)
except Exception as e:
logger.error("Could not create 'Chains' directory at %s %s" % (chain_path, e))
warn_migration = False
# Add a warning for migration purposes if we created a chain dir
if warn_migration and ROOT_INSTALL_PATH != self.DATA_DIR_PATH:
if os.path.exists(os.path.join(ROOT_INSTALL_PATH, 'Chains')):
logger.warning("[MIGRATION] You are now using the blockchain data at %s, but it appears you have existing data at %s/Chains" % (
chain_path, ROOT_INSTALL_PATH))
logger.warning(
"[MIGRATION] If you would like to use your existing data, please move any data at %s/Chains to %s " % (ROOT_INSTALL_PATH, chain_path))
logger.warning("[MIGRATION] Or you can continue using your existing data by starting your script with the `--datadir=.` flag") | python | def check_chain_dir_exists(self, warn_migration=False):
chain_path = os.path.join(self.DATA_DIR_PATH, 'Chains')
if not os.path.exists(chain_path):
try:
os.makedirs(chain_path)
logger.info("Created 'Chains' directory at %s " % chain_path)
except Exception as e:
logger.error("Could not create 'Chains' directory at %s %s" % (chain_path, e))
warn_migration = False
# Add a warning for migration purposes if we created a chain dir
if warn_migration and ROOT_INSTALL_PATH != self.DATA_DIR_PATH:
if os.path.exists(os.path.join(ROOT_INSTALL_PATH, 'Chains')):
logger.warning("[MIGRATION] You are now using the blockchain data at %s, but it appears you have existing data at %s/Chains" % (
chain_path, ROOT_INSTALL_PATH))
logger.warning(
"[MIGRATION] If you would like to use your existing data, please move any data at %s/Chains to %s " % (ROOT_INSTALL_PATH, chain_path))
logger.warning("[MIGRATION] Or you can continue using your existing data by starting your script with the `--datadir=.` flag") | [
"def",
"check_chain_dir_exists",
"(",
"self",
",",
"warn_migration",
"=",
"False",
")",
":",
"chain_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"DATA_DIR_PATH",
",",
"'Chains'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
... | Checks to make sure there is a directory called ``Chains`` at the root of DATA_DIR_PATH
and creates it if it doesn't exist yet | [
"Checks",
"to",
"make",
"sure",
"there",
"is",
"a",
"directory",
"called",
"Chains",
"at",
"the",
"root",
"of",
"DATA_DIR_PATH",
"and",
"creates",
"it",
"if",
"it",
"doesn",
"t",
"exist",
"yet"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Settings.py#L321-L343 |
228,942 | CityOfZion/neo-python | neo/Prompt/Commands/WalletAddress.py | SplitUnspentCoin | def SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee=Fixed8.Zero(), prompt_passwd=True):
"""
Split unspent asset vins into several vouts
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
index (int): index of the unspent vin to split
divisions (int): number of vouts to create
fee (Fixed8): A fee to be attached to the Transaction for network processing purposes.
prompt_passwd (bool): prompt password before processing the transaction
Returns:
neo.Core.TX.Transaction.ContractTransaction: contract transaction created
"""
if wallet is None:
print("Please open a wallet.")
return
unspent_items = wallet.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr)
if not unspent_items:
print(f"No unspent assets matching the arguments.")
return
if index < len(unspent_items):
unspent_item = unspent_items[index]
else:
print(f"unspent-items: {unspent_items}")
print(f"Could not find unspent item for asset {asset_id} with index {index}")
return
outputs = split_to_vouts(asset_id, from_addr, unspent_item.Output.Value, divisions)
# subtract a fee from the first vout
if outputs[0].Value > fee:
outputs[0].Value -= fee
else:
print("Fee could not be subtracted from outputs.")
return
contract_tx = ContractTransaction(outputs=outputs, inputs=[unspent_item.Reference])
ctx = ContractParametersContext(contract_tx)
wallet.Sign(ctx)
print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4))
if prompt_passwd:
passwd = prompt("[Password]> ", is_password=True)
if not wallet.ValidatePassword(passwd):
print("incorrect password")
return
if ctx.Completed:
contract_tx.scripts = ctx.GetScripts()
relayed = NodeLeader.Instance().Relay(contract_tx)
if relayed:
wallet.SaveTransaction(contract_tx)
print("Relayed Tx: %s " % contract_tx.Hash.ToString())
return contract_tx
else:
print("Could not relay tx %s " % contract_tx.Hash.ToString()) | python | def SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee=Fixed8.Zero(), prompt_passwd=True):
if wallet is None:
print("Please open a wallet.")
return
unspent_items = wallet.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr)
if not unspent_items:
print(f"No unspent assets matching the arguments.")
return
if index < len(unspent_items):
unspent_item = unspent_items[index]
else:
print(f"unspent-items: {unspent_items}")
print(f"Could not find unspent item for asset {asset_id} with index {index}")
return
outputs = split_to_vouts(asset_id, from_addr, unspent_item.Output.Value, divisions)
# subtract a fee from the first vout
if outputs[0].Value > fee:
outputs[0].Value -= fee
else:
print("Fee could not be subtracted from outputs.")
return
contract_tx = ContractTransaction(outputs=outputs, inputs=[unspent_item.Reference])
ctx = ContractParametersContext(contract_tx)
wallet.Sign(ctx)
print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4))
if prompt_passwd:
passwd = prompt("[Password]> ", is_password=True)
if not wallet.ValidatePassword(passwd):
print("incorrect password")
return
if ctx.Completed:
contract_tx.scripts = ctx.GetScripts()
relayed = NodeLeader.Instance().Relay(contract_tx)
if relayed:
wallet.SaveTransaction(contract_tx)
print("Relayed Tx: %s " % contract_tx.Hash.ToString())
return contract_tx
else:
print("Could not relay tx %s " % contract_tx.Hash.ToString()) | [
"def",
"SplitUnspentCoin",
"(",
"wallet",
",",
"asset_id",
",",
"from_addr",
",",
"index",
",",
"divisions",
",",
"fee",
"=",
"Fixed8",
".",
"Zero",
"(",
")",
",",
"prompt_passwd",
"=",
"True",
")",
":",
"if",
"wallet",
"is",
"None",
":",
"print",
"(",... | Split unspent asset vins into several vouts
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
index (int): index of the unspent vin to split
divisions (int): number of vouts to create
fee (Fixed8): A fee to be attached to the Transaction for network processing purposes.
prompt_passwd (bool): prompt password before processing the transaction
Returns:
neo.Core.TX.Transaction.ContractTransaction: contract transaction created | [
"Split",
"unspent",
"asset",
"vins",
"into",
"several",
"vouts"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Prompt/Commands/WalletAddress.py#L221-L285 |
228,943 | CityOfZion/neo-python | neo/Utils/plugin.py | load_class_from_path | def load_class_from_path(path_and_class: str):
"""
Dynamically load a class from a module at the specified path
Args:
path_and_class: relative path where to find the module and its class name
i.e. 'neo.<package>.<package>.<module>.<class name>'
Raises:
ValueError: if the Module or Class is not found.
Returns:
class object
"""
try:
module_path = '.'.join(path_and_class.split('.')[:-1])
module = importlib.import_module(module_path)
except ImportError as err:
raise ValueError(f"Failed to import module {module_path} with error: {err}")
try:
class_name = path_and_class.split('.')[-1]
class_obj = getattr(module, class_name)
return class_obj
except AttributeError as err:
raise ValueError(f"Failed to get class {class_name} with error: {err}") | python | def load_class_from_path(path_and_class: str):
try:
module_path = '.'.join(path_and_class.split('.')[:-1])
module = importlib.import_module(module_path)
except ImportError as err:
raise ValueError(f"Failed to import module {module_path} with error: {err}")
try:
class_name = path_and_class.split('.')[-1]
class_obj = getattr(module, class_name)
return class_obj
except AttributeError as err:
raise ValueError(f"Failed to get class {class_name} with error: {err}") | [
"def",
"load_class_from_path",
"(",
"path_and_class",
":",
"str",
")",
":",
"try",
":",
"module_path",
"=",
"'.'",
".",
"join",
"(",
"path_and_class",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"module",
"=",
"importlib",
".",
"import... | Dynamically load a class from a module at the specified path
Args:
path_and_class: relative path where to find the module and its class name
i.e. 'neo.<package>.<package>.<module>.<class name>'
Raises:
ValueError: if the Module or Class is not found.
Returns:
class object | [
"Dynamically",
"load",
"a",
"class",
"from",
"a",
"module",
"at",
"the",
"specified",
"path"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Utils/plugin.py#L4-L29 |
228,944 | CityOfZion/neo-python | neo/SmartContract/ApplicationEngine.py | ApplicationEngine.Run | def Run(script, container=None, exit_on_error=False, gas=Fixed8.Zero(), test_mode=True):
"""
Runs a script in a test invoke environment
Args:
script (bytes): The script to run
container (neo.Core.TX.Transaction): [optional] the transaction to use as the script container
Returns:
ApplicationEngine
"""
from neo.Core.Blockchain import Blockchain
from neo.SmartContract.StateMachine import StateMachine
from neo.EventHub import events
bc = Blockchain.Default()
accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState)
assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState)
validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState)
contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState)
storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem)
script_table = CachedScriptTable(contracts)
service = StateMachine(accounts, validators, assets, contracts, storages, None)
engine = ApplicationEngine(
trigger_type=TriggerType.Application,
container=container,
table=script_table,
service=service,
gas=gas,
testMode=test_mode,
exit_on_error=exit_on_error
)
script = binascii.unhexlify(script)
engine.LoadScript(script)
try:
success = engine.Execute()
engine.testMode = True
service.ExecutionCompleted(engine, success)
except Exception as e:
engine.testMode = True
service.ExecutionCompleted(engine, False, e)
for event in service.events_to_dispatch:
events.emit(event.event_type, event)
return engine | python | def Run(script, container=None, exit_on_error=False, gas=Fixed8.Zero(), test_mode=True):
from neo.Core.Blockchain import Blockchain
from neo.SmartContract.StateMachine import StateMachine
from neo.EventHub import events
bc = Blockchain.Default()
accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState)
assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState)
validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState)
contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState)
storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem)
script_table = CachedScriptTable(contracts)
service = StateMachine(accounts, validators, assets, contracts, storages, None)
engine = ApplicationEngine(
trigger_type=TriggerType.Application,
container=container,
table=script_table,
service=service,
gas=gas,
testMode=test_mode,
exit_on_error=exit_on_error
)
script = binascii.unhexlify(script)
engine.LoadScript(script)
try:
success = engine.Execute()
engine.testMode = True
service.ExecutionCompleted(engine, success)
except Exception as e:
engine.testMode = True
service.ExecutionCompleted(engine, False, e)
for event in service.events_to_dispatch:
events.emit(event.event_type, event)
return engine | [
"def",
"Run",
"(",
"script",
",",
"container",
"=",
"None",
",",
"exit_on_error",
"=",
"False",
",",
"gas",
"=",
"Fixed8",
".",
"Zero",
"(",
")",
",",
"test_mode",
"=",
"True",
")",
":",
"from",
"neo",
".",
"Core",
".",
"Blockchain",
"import",
"Block... | Runs a script in a test invoke environment
Args:
script (bytes): The script to run
container (neo.Core.TX.Transaction): [optional] the transaction to use as the script container
Returns:
ApplicationEngine | [
"Runs",
"a",
"script",
"in",
"a",
"test",
"invoke",
"environment"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/ApplicationEngine.py#L558-L610 |
228,945 | CityOfZion/neo-python | neo/SmartContract/Iterable/ConcatenatedEnumerator.py | ConcatenatedEnumerator.Next | def Next(self):
"""
Advances the iterator forward 1 step.
Returns:
bool: True if another item exists in the iterator, False otherwise.
"""
try:
self.key, self.value = next(self.current)
except StopIteration:
if self.current != self.second:
self.current = self.second
return self.Next()
return False
return True | python | def Next(self):
try:
self.key, self.value = next(self.current)
except StopIteration:
if self.current != self.second:
self.current = self.second
return self.Next()
return False
return True | [
"def",
"Next",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"key",
",",
"self",
".",
"value",
"=",
"next",
"(",
"self",
".",
"current",
")",
"except",
"StopIteration",
":",
"if",
"self",
".",
"current",
"!=",
"self",
".",
"second",
":",
"self",
... | Advances the iterator forward 1 step.
Returns:
bool: True if another item exists in the iterator, False otherwise. | [
"Advances",
"the",
"iterator",
"forward",
"1",
"step",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/Iterable/ConcatenatedEnumerator.py#L19-L36 |
228,946 | CityOfZion/neo-python | neo/Core/AssetType.py | AssetType.AllTypes | def AllTypes():
"""
Get a list of all available asset types.
Returns:
list: of AssetType items.
"""
return [AssetType.CreditFlag, AssetType.DutyFlag, AssetType.GoverningToken,
AssetType.UtilityToken, AssetType.Currency, AssetType.Share,
AssetType.Invoice, AssetType.Token] | python | def AllTypes():
return [AssetType.CreditFlag, AssetType.DutyFlag, AssetType.GoverningToken,
AssetType.UtilityToken, AssetType.Currency, AssetType.Share,
AssetType.Invoice, AssetType.Token] | [
"def",
"AllTypes",
"(",
")",
":",
"return",
"[",
"AssetType",
".",
"CreditFlag",
",",
"AssetType",
".",
"DutyFlag",
",",
"AssetType",
".",
"GoverningToken",
",",
"AssetType",
".",
"UtilityToken",
",",
"AssetType",
".",
"Currency",
",",
"AssetType",
".",
"Sha... | Get a list of all available asset types.
Returns:
list: of AssetType items. | [
"Get",
"a",
"list",
"of",
"all",
"available",
"asset",
"types",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/AssetType.py#L22-L31 |
228,947 | CityOfZion/neo-python | examples/smart-contract-rest-api.py | custom_background_code | def custom_background_code():
""" Custom code run in a background thread. Prints the current block height.
This function is run in a daemonized thread, which means it can be instantly killed at any
moment, whenever the main thread quits. If you need more safety, don't use a daemonized
thread and handle exiting this thread in another way (eg. with signals and events).
"""
while True:
logger.info("Block %s / %s", str(Blockchain.Default().Height), str(Blockchain.Default().HeaderHeight))
sleep(15) | python | def custom_background_code():
while True:
logger.info("Block %s / %s", str(Blockchain.Default().Height), str(Blockchain.Default().HeaderHeight))
sleep(15) | [
"def",
"custom_background_code",
"(",
")",
":",
"while",
"True",
":",
"logger",
".",
"info",
"(",
"\"Block %s / %s\"",
",",
"str",
"(",
"Blockchain",
".",
"Default",
"(",
")",
".",
"Height",
")",
",",
"str",
"(",
"Blockchain",
".",
"Default",
"(",
")",
... | Custom code run in a background thread. Prints the current block height.
This function is run in a daemonized thread, which means it can be instantly killed at any
moment, whenever the main thread quits. If you need more safety, don't use a daemonized
thread and handle exiting this thread in another way (eg. with signals and events). | [
"Custom",
"code",
"run",
"in",
"a",
"background",
"thread",
".",
"Prints",
"the",
"current",
"block",
"height",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/examples/smart-contract-rest-api.py#L95-L104 |
228,948 | CityOfZion/neo-python | neo/contrib/utils.py | wait_for_tx | def wait_for_tx(self, tx, max_seconds=120):
""" Wait for tx to show up on blockchain
Args:
tx (Transaction or UInt256 or str): Transaction or just the hash
max_seconds (float): maximum seconds to wait for tx to show up. default: 120
Returns:
True: if transaction was found
Raises:
AttributeError: if supplied tx is not Transaction or UInt256 or str
TxNotFoundInBlockchainError: if tx is not found in blockchain after max_seconds
"""
tx_hash = None
if isinstance(tx, (str, UInt256)):
tx_hash = str(tx)
elif isinstance(tx, Transaction):
tx_hash = tx.Hash.ToString()
else:
raise AttributeError("Supplied tx is type '%s', but must be Transaction or UInt256 or str" % type(tx))
wait_event = Event()
time_start = time.time()
while True:
# Try to find transaction in blockchain
_tx, height = Blockchain.Default().GetTransaction(tx_hash)
if height > -1:
return True
# Using a wait event for the delay because it is not blocking like time.sleep()
wait_event.wait(3)
seconds_passed = time.time() - time_start
if seconds_passed > max_seconds:
raise TxNotFoundInBlockchainError("Transaction with hash %s not found after %s seconds" % (tx_hash, int(seconds_passed))) | python | def wait_for_tx(self, tx, max_seconds=120):
tx_hash = None
if isinstance(tx, (str, UInt256)):
tx_hash = str(tx)
elif isinstance(tx, Transaction):
tx_hash = tx.Hash.ToString()
else:
raise AttributeError("Supplied tx is type '%s', but must be Transaction or UInt256 or str" % type(tx))
wait_event = Event()
time_start = time.time()
while True:
# Try to find transaction in blockchain
_tx, height = Blockchain.Default().GetTransaction(tx_hash)
if height > -1:
return True
# Using a wait event for the delay because it is not blocking like time.sleep()
wait_event.wait(3)
seconds_passed = time.time() - time_start
if seconds_passed > max_seconds:
raise TxNotFoundInBlockchainError("Transaction with hash %s not found after %s seconds" % (tx_hash, int(seconds_passed))) | [
"def",
"wait_for_tx",
"(",
"self",
",",
"tx",
",",
"max_seconds",
"=",
"120",
")",
":",
"tx_hash",
"=",
"None",
"if",
"isinstance",
"(",
"tx",
",",
"(",
"str",
",",
"UInt256",
")",
")",
":",
"tx_hash",
"=",
"str",
"(",
"tx",
")",
"elif",
"isinstanc... | Wait for tx to show up on blockchain
Args:
tx (Transaction or UInt256 or str): Transaction or just the hash
max_seconds (float): maximum seconds to wait for tx to show up. default: 120
Returns:
True: if transaction was found
Raises:
AttributeError: if supplied tx is not Transaction or UInt256 or str
TxNotFoundInBlockchainError: if tx is not found in blockchain after max_seconds | [
"Wait",
"for",
"tx",
"to",
"show",
"up",
"on",
"blockchain"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/contrib/utils.py#L13-L49 |
228,949 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.AddContract | def AddContract(self, contract):
"""
Add a contract to the wallet.
Args:
contract (Contract): a contract of type neo.SmartContract.Contract.
Raises:
Exception: Invalid operation - public key mismatch.
"""
if not contract.PublicKeyHash.ToBytes() in self._keys.keys():
raise Exception('Invalid operation - public key mismatch')
self._contracts[contract.ScriptHash.ToBytes()] = contract
if contract.ScriptHash in self._watch_only:
self._watch_only.remove(contract.ScriptHash) | python | def AddContract(self, contract):
if not contract.PublicKeyHash.ToBytes() in self._keys.keys():
raise Exception('Invalid operation - public key mismatch')
self._contracts[contract.ScriptHash.ToBytes()] = contract
if contract.ScriptHash in self._watch_only:
self._watch_only.remove(contract.ScriptHash) | [
"def",
"AddContract",
"(",
"self",
",",
"contract",
")",
":",
"if",
"not",
"contract",
".",
"PublicKeyHash",
".",
"ToBytes",
"(",
")",
"in",
"self",
".",
"_keys",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"'Invalid operation - public key mismatc... | Add a contract to the wallet.
Args:
contract (Contract): a contract of type neo.SmartContract.Contract.
Raises:
Exception: Invalid operation - public key mismatch. | [
"Add",
"a",
"contract",
"to",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L135-L150 |
228,950 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.AddWatchOnly | def AddWatchOnly(self, script_hash):
"""
Add a watch only address to the wallet.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Note:
Prints a warning to the console if the address already exists in the wallet.
"""
if script_hash in self._contracts:
logger.error("Address already in contracts")
return
self._watch_only.append(script_hash) | python | def AddWatchOnly(self, script_hash):
if script_hash in self._contracts:
logger.error("Address already in contracts")
return
self._watch_only.append(script_hash) | [
"def",
"AddWatchOnly",
"(",
"self",
",",
"script_hash",
")",
":",
"if",
"script_hash",
"in",
"self",
".",
"_contracts",
":",
"logger",
".",
"error",
"(",
"\"Address already in contracts\"",
")",
"return",
"self",
".",
"_watch_only",
".",
"append",
"(",
"script... | Add a watch only address to the wallet.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Note:
Prints a warning to the console if the address already exists in the wallet. | [
"Add",
"a",
"watch",
"only",
"address",
"to",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L152-L166 |
228,951 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.AddNEP5Token | def AddNEP5Token(self, token):
"""
Add a NEP-5 compliant token to the wallet.
Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token.
Note:
Prints a warning to the console if the token already exists in the wallet.
"""
if token.ScriptHash.ToBytes() in self._tokens.keys():
logger.error("Token already in wallet")
return
self._tokens[token.ScriptHash.ToBytes()] = token | python | def AddNEP5Token(self, token):
if token.ScriptHash.ToBytes() in self._tokens.keys():
logger.error("Token already in wallet")
return
self._tokens[token.ScriptHash.ToBytes()] = token | [
"def",
"AddNEP5Token",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
".",
"ScriptHash",
".",
"ToBytes",
"(",
")",
"in",
"self",
".",
"_tokens",
".",
"keys",
"(",
")",
":",
"logger",
".",
"error",
"(",
"\"Token already in wallet\"",
")",
"return",
... | Add a NEP-5 compliant token to the wallet.
Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token.
Note:
Prints a warning to the console if the token already exists in the wallet. | [
"Add",
"a",
"NEP",
"-",
"5",
"compliant",
"token",
"to",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L168-L181 |
228,952 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ChangePassword | def ChangePassword(self, password_old, password_new):
"""
Change the password used to protect the private key.
Args:
password_old (str): the current password used to encrypt the private key.
password_new (str): the new to be used password to encrypt the private key.
Returns:
bool: whether the password has been changed
"""
if not self.ValidatePassword(password_old):
return False
if isinstance(password_new, str):
password_new = password_new.encode('utf-8')
password_key = hashlib.sha256(password_new)
self.SaveStoredData("PasswordHash", password_key)
self.SaveStoredData("MasterKey", AES.new(self._master_key, AES.MODE_CBC, self._iv))
return True | python | def ChangePassword(self, password_old, password_new):
if not self.ValidatePassword(password_old):
return False
if isinstance(password_new, str):
password_new = password_new.encode('utf-8')
password_key = hashlib.sha256(password_new)
self.SaveStoredData("PasswordHash", password_key)
self.SaveStoredData("MasterKey", AES.new(self._master_key, AES.MODE_CBC, self._iv))
return True | [
"def",
"ChangePassword",
"(",
"self",
",",
"password_old",
",",
"password_new",
")",
":",
"if",
"not",
"self",
".",
"ValidatePassword",
"(",
"password_old",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"password_new",
",",
"str",
")",
":",
"password... | Change the password used to protect the private key.
Args:
password_old (str): the current password used to encrypt the private key.
password_new (str): the new to be used password to encrypt the private key.
Returns:
bool: whether the password has been changed | [
"Change",
"the",
"password",
"used",
"to",
"protect",
"the",
"private",
"key",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L195-L216 |
228,953 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ContainsKey | def ContainsKey(self, public_key):
"""
Test if the wallet contains the supplied public key.
Args:
public_key (edcsa.Curve.point): a public key to test for its existance. e.g. KeyPair.PublicKey
Returns:
bool: True if exists, False otherwise.
"""
return self.ContainsKeyHash(Crypto.ToScriptHash(public_key.encode_point(True), unhex=True)) | python | def ContainsKey(self, public_key):
return self.ContainsKeyHash(Crypto.ToScriptHash(public_key.encode_point(True), unhex=True)) | [
"def",
"ContainsKey",
"(",
"self",
",",
"public_key",
")",
":",
"return",
"self",
".",
"ContainsKeyHash",
"(",
"Crypto",
".",
"ToScriptHash",
"(",
"public_key",
".",
"encode_point",
"(",
"True",
")",
",",
"unhex",
"=",
"True",
")",
")"
] | Test if the wallet contains the supplied public key.
Args:
public_key (edcsa.Curve.point): a public key to test for its existance. e.g. KeyPair.PublicKey
Returns:
bool: True if exists, False otherwise. | [
"Test",
"if",
"the",
"wallet",
"contains",
"the",
"supplied",
"public",
"key",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L218-L228 |
228,954 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ContainsAddressStr | def ContainsAddressStr(self, address):
"""
Determine if the wallet contains the address.
Args:
address (str): a string representing the public key.
Returns:
bool: True, if the address is present in the wallet. False otherwise.
"""
for key, contract in self._contracts.items():
if contract.Address == address:
return True
return False | python | def ContainsAddressStr(self, address):
for key, contract in self._contracts.items():
if contract.Address == address:
return True
return False | [
"def",
"ContainsAddressStr",
"(",
"self",
",",
"address",
")",
":",
"for",
"key",
",",
"contract",
"in",
"self",
".",
"_contracts",
".",
"items",
"(",
")",
":",
"if",
"contract",
".",
"Address",
"==",
"address",
":",
"return",
"True",
"return",
"False"
] | Determine if the wallet contains the address.
Args:
address (str): a string representing the public key.
Returns:
bool: True, if the address is present in the wallet. False otherwise. | [
"Determine",
"if",
"the",
"wallet",
"contains",
"the",
"address",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L254-L267 |
228,955 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.CreateKey | def CreateKey(self, private_key=None):
"""
Create a KeyPair
Args:
private_key (iterable_of_ints): (optional) 32 byte private key
Returns:
KeyPair: a KeyPair instance
"""
if private_key is None:
private_key = bytes(Random.get_random_bytes(32))
key = KeyPair(priv_key=private_key)
self._keys[key.PublicKeyHash.ToBytes()] = key
return key | python | def CreateKey(self, private_key=None):
if private_key is None:
private_key = bytes(Random.get_random_bytes(32))
key = KeyPair(priv_key=private_key)
self._keys[key.PublicKeyHash.ToBytes()] = key
return key | [
"def",
"CreateKey",
"(",
"self",
",",
"private_key",
"=",
"None",
")",
":",
"if",
"private_key",
"is",
"None",
":",
"private_key",
"=",
"bytes",
"(",
"Random",
".",
"get_random_bytes",
"(",
"32",
")",
")",
"key",
"=",
"KeyPair",
"(",
"priv_key",
"=",
"... | Create a KeyPair
Args:
private_key (iterable_of_ints): (optional) 32 byte private key
Returns:
KeyPair: a KeyPair instance | [
"Create",
"a",
"KeyPair"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L269-L284 |
228,956 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.EncryptPrivateKey | def EncryptPrivateKey(self, decrypted):
"""
Encrypt the provided plaintext with the initialized private key.
Args:
decrypted (byte string): the plaintext to be encrypted.
Returns:
bytes: the ciphertext.
"""
aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
return aes.encrypt(decrypted) | python | def EncryptPrivateKey(self, decrypted):
aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
return aes.encrypt(decrypted) | [
"def",
"EncryptPrivateKey",
"(",
"self",
",",
"decrypted",
")",
":",
"aes",
"=",
"AES",
".",
"new",
"(",
"self",
".",
"_master_key",
",",
"AES",
".",
"MODE_CBC",
",",
"self",
".",
"_iv",
")",
"return",
"aes",
".",
"encrypt",
"(",
"decrypted",
")"
] | Encrypt the provided plaintext with the initialized private key.
Args:
decrypted (byte string): the plaintext to be encrypted.
Returns:
bytes: the ciphertext. | [
"Encrypt",
"the",
"provided",
"plaintext",
"with",
"the",
"initialized",
"private",
"key",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L286-L297 |
228,957 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.DecryptPrivateKey | def DecryptPrivateKey(self, encrypted_private_key):
"""
Decrypt the provided ciphertext with the initialized private key.
Args:
encrypted_private_key (byte string): the ciphertext to be decrypted.
Returns:
bytes: the ciphertext.
"""
aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
return aes.decrypt(encrypted_private_key) | python | def DecryptPrivateKey(self, encrypted_private_key):
aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
return aes.decrypt(encrypted_private_key) | [
"def",
"DecryptPrivateKey",
"(",
"self",
",",
"encrypted_private_key",
")",
":",
"aes",
"=",
"AES",
".",
"new",
"(",
"self",
".",
"_master_key",
",",
"AES",
".",
"MODE_CBC",
",",
"self",
".",
"_iv",
")",
"return",
"aes",
".",
"decrypt",
"(",
"encrypted_p... | Decrypt the provided ciphertext with the initialized private key.
Args:
encrypted_private_key (byte string): the ciphertext to be decrypted.
Returns:
bytes: the ciphertext. | [
"Decrypt",
"the",
"provided",
"ciphertext",
"with",
"the",
"initialized",
"private",
"key",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L299-L310 |
228,958 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.FindCoinsByVins | def FindCoinsByVins(self, vins):
"""
Looks through the current collection of coins in a wallet
and chooses coins that match the specified CoinReference objects.
Args:
vins: A list of ``neo.Core.CoinReference`` objects.
Returns:
list: A list of ``neo.Wallet.Coin`` objects.
"""
ret = []
for coin in self.GetCoins():
coinref = coin.Reference
for vin in vins:
if coinref.PrevIndex == vin.PrevIndex and \
coinref.PrevHash == vin.PrevHash:
ret.append(coin)
return ret | python | def FindCoinsByVins(self, vins):
ret = []
for coin in self.GetCoins():
coinref = coin.Reference
for vin in vins:
if coinref.PrevIndex == vin.PrevIndex and \
coinref.PrevHash == vin.PrevHash:
ret.append(coin)
return ret | [
"def",
"FindCoinsByVins",
"(",
"self",
",",
"vins",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"coin",
"in",
"self",
".",
"GetCoins",
"(",
")",
":",
"coinref",
"=",
"coin",
".",
"Reference",
"for",
"vin",
"in",
"vins",
":",
"if",
"coinref",
".",
"PrevI... | Looks through the current collection of coins in a wallet
and chooses coins that match the specified CoinReference objects.
Args:
vins: A list of ``neo.Core.CoinReference`` objects.
Returns:
list: A list of ``neo.Wallet.Coin`` objects. | [
"Looks",
"through",
"the",
"current",
"collection",
"of",
"coins",
"in",
"a",
"wallet",
"and",
"chooses",
"coins",
"that",
"match",
"the",
"specified",
"CoinReference",
"objects",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L347-L365 |
228,959 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.FindUnspentCoins | def FindUnspentCoins(self, from_addr=None, use_standard=False, watch_only_val=0):
"""
Finds unspent coin objects in the wallet.
Args:
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coins`` in the wallet that are not spent.
"""
ret = []
for coin in self.GetCoins():
if coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent == 0 and \
coin.State & CoinState.Locked == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == watch_only_val:
do_exclude = False
if self._vin_exclude:
for to_exclude in self._vin_exclude:
if coin.Reference.PrevIndex == to_exclude.PrevIndex and \
coin.Reference.PrevHash == to_exclude.PrevHash:
do_exclude = True
if do_exclude:
continue
if from_addr is not None:
if coin.Output.ScriptHash == from_addr:
ret.append(coin)
elif use_standard:
contract = self._contracts[coin.Output.ScriptHash.ToBytes()]
if contract.IsStandard:
ret.append(coin)
else:
ret.append(coin)
return ret | python | def FindUnspentCoins(self, from_addr=None, use_standard=False, watch_only_val=0):
ret = []
for coin in self.GetCoins():
if coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent == 0 and \
coin.State & CoinState.Locked == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == watch_only_val:
do_exclude = False
if self._vin_exclude:
for to_exclude in self._vin_exclude:
if coin.Reference.PrevIndex == to_exclude.PrevIndex and \
coin.Reference.PrevHash == to_exclude.PrevHash:
do_exclude = True
if do_exclude:
continue
if from_addr is not None:
if coin.Output.ScriptHash == from_addr:
ret.append(coin)
elif use_standard:
contract = self._contracts[coin.Output.ScriptHash.ToBytes()]
if contract.IsStandard:
ret.append(coin)
else:
ret.append(coin)
return ret | [
"def",
"FindUnspentCoins",
"(",
"self",
",",
"from_addr",
"=",
"None",
",",
"use_standard",
"=",
"False",
",",
"watch_only_val",
"=",
"0",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"coin",
"in",
"self",
".",
"GetCoins",
"(",
")",
":",
"if",
"coin",
".",... | Finds unspent coin objects in the wallet.
Args:
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coins`` in the wallet that are not spent. | [
"Finds",
"unspent",
"coin",
"objects",
"in",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L367-L409 |
228,960 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.FindUnspentCoinsByAsset | def FindUnspentCoinsByAsset(self, asset_id, from_addr=None, use_standard=False, watch_only_val=0):
"""
Finds unspent coin objects in the wallet limited to those of a certain asset type.
Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent
"""
coins = self.FindUnspentCoins(from_addr=from_addr, use_standard=use_standard, watch_only_val=watch_only_val)
return [coin for coin in coins if coin.Output.AssetId == asset_id] | python | def FindUnspentCoinsByAsset(self, asset_id, from_addr=None, use_standard=False, watch_only_val=0):
coins = self.FindUnspentCoins(from_addr=from_addr, use_standard=use_standard, watch_only_val=watch_only_val)
return [coin for coin in coins if coin.Output.AssetId == asset_id] | [
"def",
"FindUnspentCoinsByAsset",
"(",
"self",
",",
"asset_id",
",",
"from_addr",
"=",
"None",
",",
"use_standard",
"=",
"False",
",",
"watch_only_val",
"=",
"0",
")",
":",
"coins",
"=",
"self",
".",
"FindUnspentCoins",
"(",
"from_addr",
"=",
"from_addr",
",... | Finds unspent coin objects in the wallet limited to those of a certain asset type.
Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent | [
"Finds",
"unspent",
"coin",
"objects",
"in",
"the",
"wallet",
"limited",
"to",
"those",
"of",
"a",
"certain",
"asset",
"type",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L411-L426 |
228,961 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.FindUnspentCoinsByAssetAndTotal | def FindUnspentCoinsByAssetAndTotal(self, asset_id, amount, from_addr=None, use_standard=False, watch_only_val=0, reverse=False):
"""
Finds unspent coin objects totalling a requested value in the wallet limited to those of a certain asset type.
Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
amount (int): the amount of unspent coins that are being requested.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent. this list is empty if there are not enough coins to satisfy the request.
"""
coins = self.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr,
use_standard=use_standard, watch_only_val=watch_only_val)
sum = Fixed8(0)
for coin in coins:
sum = sum + coin.Output.Value
if sum < amount:
return None
coins = sorted(coins, key=lambda coin: coin.Output.Value.value)
if reverse:
coins.reverse()
total = Fixed8(0)
# go through all coins, see if one is an exact match. then we'll use that
for coin in coins:
if coin.Output.Value == amount:
return [coin]
to_ret = []
for coin in coins:
total = total + coin.Output.Value
to_ret.append(coin)
if total >= amount:
break
return to_ret | python | def FindUnspentCoinsByAssetAndTotal(self, asset_id, amount, from_addr=None, use_standard=False, watch_only_val=0, reverse=False):
coins = self.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr,
use_standard=use_standard, watch_only_val=watch_only_val)
sum = Fixed8(0)
for coin in coins:
sum = sum + coin.Output.Value
if sum < amount:
return None
coins = sorted(coins, key=lambda coin: coin.Output.Value.value)
if reverse:
coins.reverse()
total = Fixed8(0)
# go through all coins, see if one is an exact match. then we'll use that
for coin in coins:
if coin.Output.Value == amount:
return [coin]
to_ret = []
for coin in coins:
total = total + coin.Output.Value
to_ret.append(coin)
if total >= amount:
break
return to_ret | [
"def",
"FindUnspentCoinsByAssetAndTotal",
"(",
"self",
",",
"asset_id",
",",
"amount",
",",
"from_addr",
"=",
"None",
",",
"use_standard",
"=",
"False",
",",
"watch_only_val",
"=",
"0",
",",
"reverse",
"=",
"False",
")",
":",
"coins",
"=",
"self",
".",
"Fi... | Finds unspent coin objects totalling a requested value in the wallet limited to those of a certain asset type.
Args:
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
amount (int): the amount of unspent coins that are being requested.
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.
Returns:
list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent. this list is empty if there are not enough coins to satisfy the request. | [
"Finds",
"unspent",
"coin",
"objects",
"totalling",
"a",
"requested",
"value",
"in",
"the",
"wallet",
"limited",
"to",
"those",
"of",
"a",
"certain",
"asset",
"type",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L428-L472 |
228,962 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetUnclaimedCoins | def GetUnclaimedCoins(self):
"""
Gets coins in the wallet that have not been 'claimed', or redeemed for their gas value on the blockchain.
Returns:
list: a list of ``neo.Wallet.Coin`` that have 'claimable' value
"""
unclaimed = []
neo = Blockchain.SystemShare().Hash
for coin in self.GetCoins():
if coin.Output.AssetId == neo and \
coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent > 0 and \
coin.State & CoinState.Claimed == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == 0:
unclaimed.append(coin)
return unclaimed | python | def GetUnclaimedCoins(self):
unclaimed = []
neo = Blockchain.SystemShare().Hash
for coin in self.GetCoins():
if coin.Output.AssetId == neo and \
coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent > 0 and \
coin.State & CoinState.Claimed == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == 0:
unclaimed.append(coin)
return unclaimed | [
"def",
"GetUnclaimedCoins",
"(",
"self",
")",
":",
"unclaimed",
"=",
"[",
"]",
"neo",
"=",
"Blockchain",
".",
"SystemShare",
"(",
")",
".",
"Hash",
"for",
"coin",
"in",
"self",
".",
"GetCoins",
"(",
")",
":",
"if",
"coin",
".",
"Output",
".",
"AssetI... | Gets coins in the wallet that have not been 'claimed', or redeemed for their gas value on the blockchain.
Returns:
list: a list of ``neo.Wallet.Coin`` that have 'claimable' value | [
"Gets",
"coins",
"in",
"the",
"wallet",
"that",
"have",
"not",
"been",
"claimed",
"or",
"redeemed",
"for",
"their",
"gas",
"value",
"on",
"the",
"blockchain",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L474-L494 |
228,963 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetAvailableClaimTotal | def GetAvailableClaimTotal(self):
"""
Gets the total amount of Gas that this wallet is able to claim at a given moment.
Returns:
Fixed8: the amount of Gas available to claim as a Fixed8 number.
"""
coinrefs = [coin.Reference for coin in self.GetUnclaimedCoins()]
bonus = Blockchain.CalculateBonusIgnoreClaimed(coinrefs, True)
return bonus | python | def GetAvailableClaimTotal(self):
coinrefs = [coin.Reference for coin in self.GetUnclaimedCoins()]
bonus = Blockchain.CalculateBonusIgnoreClaimed(coinrefs, True)
return bonus | [
"def",
"GetAvailableClaimTotal",
"(",
"self",
")",
":",
"coinrefs",
"=",
"[",
"coin",
".",
"Reference",
"for",
"coin",
"in",
"self",
".",
"GetUnclaimedCoins",
"(",
")",
"]",
"bonus",
"=",
"Blockchain",
".",
"CalculateBonusIgnoreClaimed",
"(",
"coinrefs",
",",
... | Gets the total amount of Gas that this wallet is able to claim at a given moment.
Returns:
Fixed8: the amount of Gas available to claim as a Fixed8 number. | [
"Gets",
"the",
"total",
"amount",
"of",
"Gas",
"that",
"this",
"wallet",
"is",
"able",
"to",
"claim",
"at",
"a",
"given",
"moment",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L496-L505 |
228,964 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetUnavailableBonus | def GetUnavailableBonus(self):
"""
Gets the total claimable amount of Gas in the wallet that is not available to claim
because it has not yet been spent.
Returns:
Fixed8: the amount of Gas unavailable to claim.
"""
height = Blockchain.Default().Height + 1
unspents = self.FindUnspentCoinsByAsset(Blockchain.SystemShare().Hash)
refs = [coin.Reference for coin in unspents]
try:
unavailable_bonus = Blockchain.CalculateBonus(refs, height_end=height)
return unavailable_bonus
except Exception as e:
pass
return Fixed8(0) | python | def GetUnavailableBonus(self):
height = Blockchain.Default().Height + 1
unspents = self.FindUnspentCoinsByAsset(Blockchain.SystemShare().Hash)
refs = [coin.Reference for coin in unspents]
try:
unavailable_bonus = Blockchain.CalculateBonus(refs, height_end=height)
return unavailable_bonus
except Exception as e:
pass
return Fixed8(0) | [
"def",
"GetUnavailableBonus",
"(",
"self",
")",
":",
"height",
"=",
"Blockchain",
".",
"Default",
"(",
")",
".",
"Height",
"+",
"1",
"unspents",
"=",
"self",
".",
"FindUnspentCoinsByAsset",
"(",
"Blockchain",
".",
"SystemShare",
"(",
")",
".",
"Hash",
")",... | Gets the total claimable amount of Gas in the wallet that is not available to claim
because it has not yet been spent.
Returns:
Fixed8: the amount of Gas unavailable to claim. | [
"Gets",
"the",
"total",
"claimable",
"amount",
"of",
"Gas",
"in",
"the",
"wallet",
"that",
"is",
"not",
"available",
"to",
"claim",
"because",
"it",
"has",
"not",
"yet",
"been",
"spent",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L507-L523 |
228,965 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetKey | def GetKey(self, public_key_hash):
"""
Get the KeyPair belonging to the public key hash.
Args:
public_key_hash (UInt160): a public key hash to get the KeyPair for.
Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None
"""
if public_key_hash.ToBytes() in self._keys.keys():
return self._keys[public_key_hash.ToBytes()]
return None | python | def GetKey(self, public_key_hash):
if public_key_hash.ToBytes() in self._keys.keys():
return self._keys[public_key_hash.ToBytes()]
return None | [
"def",
"GetKey",
"(",
"self",
",",
"public_key_hash",
")",
":",
"if",
"public_key_hash",
".",
"ToBytes",
"(",
")",
"in",
"self",
".",
"_keys",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"_keys",
"[",
"public_key_hash",
".",
"ToBytes",
"(",
")",... | Get the KeyPair belonging to the public key hash.
Args:
public_key_hash (UInt160): a public key hash to get the KeyPair for.
Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None | [
"Get",
"the",
"KeyPair",
"belonging",
"to",
"the",
"public",
"key",
"hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L525-L537 |
228,966 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetKeyByScriptHash | def GetKeyByScriptHash(self, script_hash):
"""
Get the KeyPair belonging to the script hash.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None
"""
contract = self.GetContract(script_hash)
if contract:
return self.GetKey(contract.PublicKeyHash)
return None | python | def GetKeyByScriptHash(self, script_hash):
contract = self.GetContract(script_hash)
if contract:
return self.GetKey(contract.PublicKeyHash)
return None | [
"def",
"GetKeyByScriptHash",
"(",
"self",
",",
"script_hash",
")",
":",
"contract",
"=",
"self",
".",
"GetContract",
"(",
"script_hash",
")",
"if",
"contract",
":",
"return",
"self",
".",
"GetKey",
"(",
"contract",
".",
"PublicKeyHash",
")",
"return",
"None"... | Get the KeyPair belonging to the script hash.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None | [
"Get",
"the",
"KeyPair",
"belonging",
"to",
"the",
"script",
"hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L539-L552 |
228,967 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetTokenBalance | def GetTokenBalance(self, token, watch_only=0):
"""
Get the balance of the specified token.
Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token to get the balance from.
watch_only (bool): True, to limit to watch only wallets.
Returns:
Decimal: total balance for `token`.
"""
total = Decimal(0)
if watch_only > 0:
for addr in self._watch_only:
balance = token.GetBalance(self, addr)
total += balance
else:
for contract in self._contracts.values():
balance = token.GetBalance(self, contract.Address)
total += balance
return total | python | def GetTokenBalance(self, token, watch_only=0):
total = Decimal(0)
if watch_only > 0:
for addr in self._watch_only:
balance = token.GetBalance(self, addr)
total += balance
else:
for contract in self._contracts.values():
balance = token.GetBalance(self, contract.Address)
total += balance
return total | [
"def",
"GetTokenBalance",
"(",
"self",
",",
"token",
",",
"watch_only",
"=",
"0",
")",
":",
"total",
"=",
"Decimal",
"(",
"0",
")",
"if",
"watch_only",
">",
"0",
":",
"for",
"addr",
"in",
"self",
".",
"_watch_only",
":",
"balance",
"=",
"token",
".",... | Get the balance of the specified token.
Args:
token (NEP5Token): an instance of type neo.Wallets.NEP5Token to get the balance from.
watch_only (bool): True, to limit to watch only wallets.
Returns:
Decimal: total balance for `token`. | [
"Get",
"the",
"balance",
"of",
"the",
"specified",
"token",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L560-L581 |
228,968 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetBalance | def GetBalance(self, asset_id, watch_only=0):
"""
Get the balance of a specific token by its asset id.
Args:
asset_id (NEP5Token|TransactionOutput): an instance of type neo.Wallets.NEP5Token or neo.Core.TX.Transaction.TransactionOutput to get the balance from.
watch_only (bool): True, to limit to watch only wallets.
Returns:
Fixed8: total balance.
"""
total = Fixed8(0)
if type(asset_id) is NEP5Token.NEP5Token:
return self.GetTokenBalance(asset_id, watch_only)
for coin in self.GetCoins():
if coin.Output.AssetId == asset_id:
if coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent == 0 and \
coin.State & CoinState.Locked == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == watch_only:
total = total + coin.Output.Value
return total | python | def GetBalance(self, asset_id, watch_only=0):
total = Fixed8(0)
if type(asset_id) is NEP5Token.NEP5Token:
return self.GetTokenBalance(asset_id, watch_only)
for coin in self.GetCoins():
if coin.Output.AssetId == asset_id:
if coin.State & CoinState.Confirmed > 0 and \
coin.State & CoinState.Spent == 0 and \
coin.State & CoinState.Locked == 0 and \
coin.State & CoinState.Frozen == 0 and \
coin.State & CoinState.WatchOnly == watch_only:
total = total + coin.Output.Value
return total | [
"def",
"GetBalance",
"(",
"self",
",",
"asset_id",
",",
"watch_only",
"=",
"0",
")",
":",
"total",
"=",
"Fixed8",
"(",
"0",
")",
"if",
"type",
"(",
"asset_id",
")",
"is",
"NEP5Token",
".",
"NEP5Token",
":",
"return",
"self",
".",
"GetTokenBalance",
"("... | Get the balance of a specific token by its asset id.
Args:
asset_id (NEP5Token|TransactionOutput): an instance of type neo.Wallets.NEP5Token or neo.Core.TX.Transaction.TransactionOutput to get the balance from.
watch_only (bool): True, to limit to watch only wallets.
Returns:
Fixed8: total balance. | [
"Get",
"the",
"balance",
"of",
"a",
"specific",
"token",
"by",
"its",
"asset",
"id",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L583-L608 |
228,969 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ProcessBlocks | def ProcessBlocks(self, block_limit=1000):
"""
Method called on a loop to check the current height of the blockchain. If the height of the blockchain
is more than the current stored height in the wallet, we get the next block in line and
processes it.
In the case that the wallet height is far behind the height of the blockchain, we do this 1000
blocks at a time.
Args:
block_limit (int): the number of blocks to process synchronously. defaults to 1000. set to 0 to block until the wallet is fully rebuilt.
"""
self._lock.acquire()
try:
blockcount = 0
while self._current_height <= Blockchain.Default().Height and (block_limit == 0 or blockcount < block_limit):
block = Blockchain.Default().GetBlockByHeight(self._current_height)
if block is not None:
self.ProcessNewBlock(block)
else:
self._current_height += 1
blockcount += 1
self.SaveStoredData("Height", self._current_height)
except Exception as e:
logger.warn("Could not process ::: %s " % e)
finally:
self._lock.release() | python | def ProcessBlocks(self, block_limit=1000):
self._lock.acquire()
try:
blockcount = 0
while self._current_height <= Blockchain.Default().Height and (block_limit == 0 or blockcount < block_limit):
block = Blockchain.Default().GetBlockByHeight(self._current_height)
if block is not None:
self.ProcessNewBlock(block)
else:
self._current_height += 1
blockcount += 1
self.SaveStoredData("Height", self._current_height)
except Exception as e:
logger.warn("Could not process ::: %s " % e)
finally:
self._lock.release() | [
"def",
"ProcessBlocks",
"(",
"self",
",",
"block_limit",
"=",
"1000",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"blockcount",
"=",
"0",
"while",
"self",
".",
"_current_height",
"<=",
"Blockchain",
".",
"Default",
"(",
")",
"... | Method called on a loop to check the current height of the blockchain. If the height of the blockchain
is more than the current stored height in the wallet, we get the next block in line and
processes it.
In the case that the wallet height is far behind the height of the blockchain, we do this 1000
blocks at a time.
Args:
block_limit (int): the number of blocks to process synchronously. defaults to 1000. set to 0 to block until the wallet is fully rebuilt. | [
"Method",
"called",
"on",
"a",
"loop",
"to",
"check",
"the",
"current",
"height",
"of",
"the",
"blockchain",
".",
"If",
"the",
"height",
"of",
"the",
"blockchain",
"is",
"more",
"than",
"the",
"current",
"stored",
"height",
"in",
"the",
"wallet",
"we",
"... | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L638-L668 |
228,970 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ProcessNewBlock | def ProcessNewBlock(self, block):
"""
Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be
only processed after block 3.
Args:
block: (neo.Core.Block) a block on the blockchain.
"""
added = set()
changed = set()
deleted = set()
try:
# go through the list of transactions in the block and enumerate
# over their outputs
for tx in block.FullTransactions:
for index, output in enumerate(tx.outputs):
# check to see if the outputs in the tx are in this wallet
state = self.CheckAddressState(output.ScriptHash)
if state & AddressState.InWallet > 0:
# if it's in the wallet, check to see if the coin exists yet
key = CoinReference(tx.Hash, index)
# if it exists, update it, otherwise create a new one
if key in self._coins.keys():
coin = self._coins[key]
coin.State |= CoinState.Confirmed
changed.add(coin)
else:
newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Confirmed, transaction=tx)
self._coins[key] = newcoin
added.add(newcoin)
if state & AddressState.WatchOnly > 0:
self._coins[key].State |= CoinState.WatchOnly
changed.add(self._coins[key])
# now iterate over the inputs of the tx and do the same
for tx in block.FullTransactions:
for input in tx.inputs:
if input in self._coins.keys():
if self._coins[input].Output.AssetId == Blockchain.SystemShare().Hash:
coin = self._coins[input]
coin.State |= CoinState.Spent | CoinState.Confirmed
changed.add(coin)
else:
deleted.add(self._coins[input])
del self._coins[input]
for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]:
for ref in claimTx.Claims:
if ref in self._coins.keys():
deleted.add(self._coins[ref])
del self._coins[ref]
# update the current height of the wallet
self._current_height += 1
# in the case that another wallet implementation needs to do something
# with the coins that have been changed ( ie persist to db ) this
# method is called
self.OnProcessNewBlock(block, added, changed, deleted)
# this is not necessary at the moment, but any outside process
# that wants to subscribe to the balance changed event could do
# so from the BalanceChanged method
if len(added) + len(deleted) + len(changed) > 0:
self.BalanceChanged()
except Exception as e:
traceback.print_stack()
traceback.print_exc()
logger.error("could not process %s " % e) | python | def ProcessNewBlock(self, block):
added = set()
changed = set()
deleted = set()
try:
# go through the list of transactions in the block and enumerate
# over their outputs
for tx in block.FullTransactions:
for index, output in enumerate(tx.outputs):
# check to see if the outputs in the tx are in this wallet
state = self.CheckAddressState(output.ScriptHash)
if state & AddressState.InWallet > 0:
# if it's in the wallet, check to see if the coin exists yet
key = CoinReference(tx.Hash, index)
# if it exists, update it, otherwise create a new one
if key in self._coins.keys():
coin = self._coins[key]
coin.State |= CoinState.Confirmed
changed.add(coin)
else:
newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Confirmed, transaction=tx)
self._coins[key] = newcoin
added.add(newcoin)
if state & AddressState.WatchOnly > 0:
self._coins[key].State |= CoinState.WatchOnly
changed.add(self._coins[key])
# now iterate over the inputs of the tx and do the same
for tx in block.FullTransactions:
for input in tx.inputs:
if input in self._coins.keys():
if self._coins[input].Output.AssetId == Blockchain.SystemShare().Hash:
coin = self._coins[input]
coin.State |= CoinState.Spent | CoinState.Confirmed
changed.add(coin)
else:
deleted.add(self._coins[input])
del self._coins[input]
for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]:
for ref in claimTx.Claims:
if ref in self._coins.keys():
deleted.add(self._coins[ref])
del self._coins[ref]
# update the current height of the wallet
self._current_height += 1
# in the case that another wallet implementation needs to do something
# with the coins that have been changed ( ie persist to db ) this
# method is called
self.OnProcessNewBlock(block, added, changed, deleted)
# this is not necessary at the moment, but any outside process
# that wants to subscribe to the balance changed event could do
# so from the BalanceChanged method
if len(added) + len(deleted) + len(changed) > 0:
self.BalanceChanged()
except Exception as e:
traceback.print_stack()
traceback.print_exc()
logger.error("could not process %s " % e) | [
"def",
"ProcessNewBlock",
"(",
"self",
",",
"block",
")",
":",
"added",
"=",
"set",
"(",
")",
"changed",
"=",
"set",
"(",
")",
"deleted",
"=",
"set",
"(",
")",
"try",
":",
"# go through the list of transactions in the block and enumerate",
"# over their outputs",
... | Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be
only processed after block 3.
Args:
block: (neo.Core.Block) a block on the blockchain. | [
"Processes",
"a",
"block",
"on",
"the",
"blockchain",
".",
"This",
"should",
"be",
"done",
"in",
"a",
"sequential",
"order",
"ie",
"block",
"4",
"should",
"be",
"only",
"processed",
"after",
"block",
"3",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L670-L750 |
228,971 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.IsWalletTransaction | def IsWalletTransaction(self, tx):
"""
Verifies if a transaction belongs to the wallet.
Args:
tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify.
Returns:
bool: True, if transaction belongs to wallet. False, if not.
"""
for key, contract in self._contracts.items():
for output in tx.outputs:
if output.ScriptHash.ToBytes() == contract.ScriptHash.ToBytes():
return True
for script in tx.scripts:
if script.VerificationScript:
if bytes(contract.Script) == script.VerificationScript:
return True
for watch_script_hash in self._watch_only:
for output in tx.outputs:
if output.ScriptHash == watch_script_hash:
return True
for script in tx.scripts:
if Crypto.ToScriptHash(script.VerificationScript, unhex=False) == watch_script_hash:
return True
return False | python | def IsWalletTransaction(self, tx):
for key, contract in self._contracts.items():
for output in tx.outputs:
if output.ScriptHash.ToBytes() == contract.ScriptHash.ToBytes():
return True
for script in tx.scripts:
if script.VerificationScript:
if bytes(contract.Script) == script.VerificationScript:
return True
for watch_script_hash in self._watch_only:
for output in tx.outputs:
if output.ScriptHash == watch_script_hash:
return True
for script in tx.scripts:
if Crypto.ToScriptHash(script.VerificationScript, unhex=False) == watch_script_hash:
return True
return False | [
"def",
"IsWalletTransaction",
"(",
"self",
",",
"tx",
")",
":",
"for",
"key",
",",
"contract",
"in",
"self",
".",
"_contracts",
".",
"items",
"(",
")",
":",
"for",
"output",
"in",
"tx",
".",
"outputs",
":",
"if",
"output",
".",
"ScriptHash",
".",
"To... | Verifies if a transaction belongs to the wallet.
Args:
tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify.
Returns:
bool: True, if transaction belongs to wallet. False, if not. | [
"Verifies",
"if",
"a",
"transaction",
"belongs",
"to",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L772-L802 |
228,972 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.CheckAddressState | def CheckAddressState(self, script_hash):
"""
Determine the address state of the provided script hash.
Args:
script_hash (UInt160): a script hash to determine the address state of.
Returns:
AddressState: the address state.
"""
for key, contract in self._contracts.items():
if contract.ScriptHash.ToBytes() == script_hash.ToBytes():
return AddressState.InWallet
for watch in self._watch_only:
if watch == script_hash:
return AddressState.InWallet | AddressState.WatchOnly
return AddressState.NoState | python | def CheckAddressState(self, script_hash):
for key, contract in self._contracts.items():
if contract.ScriptHash.ToBytes() == script_hash.ToBytes():
return AddressState.InWallet
for watch in self._watch_only:
if watch == script_hash:
return AddressState.InWallet | AddressState.WatchOnly
return AddressState.NoState | [
"def",
"CheckAddressState",
"(",
"self",
",",
"script_hash",
")",
":",
"for",
"key",
",",
"contract",
"in",
"self",
".",
"_contracts",
".",
"items",
"(",
")",
":",
"if",
"contract",
".",
"ScriptHash",
".",
"ToBytes",
"(",
")",
"==",
"script_hash",
".",
... | Determine the address state of the provided script hash.
Args:
script_hash (UInt160): a script hash to determine the address state of.
Returns:
AddressState: the address state. | [
"Determine",
"the",
"address",
"state",
"of",
"the",
"provided",
"script",
"hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L804-L820 |
228,973 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ToScriptHash | def ToScriptHash(self, address):
"""
Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if the address string does not start with 'A' or the checksum fails
Returns:
UInt160: script hash.
"""
if len(address) == 34:
if address[0] == 'A':
data = b58decode(address)
if data[0] != self.AddressVersion:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21])
else:
raise Exception('Address format error')
else:
raise ValueError('Not correct Address, wrong length.') | python | def ToScriptHash(self, address):
if len(address) == 34:
if address[0] == 'A':
data = b58decode(address)
if data[0] != self.AddressVersion:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21])
else:
raise Exception('Address format error')
else:
raise ValueError('Not correct Address, wrong length.') | [
"def",
"ToScriptHash",
"(",
"self",
",",
"address",
")",
":",
"if",
"len",
"(",
"address",
")",
"==",
"34",
":",
"if",
"address",
"[",
"0",
"]",
"==",
"'A'",
":",
"data",
"=",
"b58decode",
"(",
"address",
")",
"if",
"data",
"[",
"0",
"]",
"!=",
... | Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if the address string does not start with 'A' or the checksum fails
Returns:
UInt160: script hash. | [
"Retrieve",
"the",
"script_hash",
"based",
"from",
"an",
"address",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L835-L862 |
228,974 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.ValidatePassword | def ValidatePassword(self, password):
"""
Validates if the provided password matches with the stored password.
Args:
password (string): a password.
Returns:
bool: the provided password matches with the stored password.
"""
password = to_aes_key(password)
return hashlib.sha256(password).digest() == self.LoadStoredData('PasswordHash') | python | def ValidatePassword(self, password):
password = to_aes_key(password)
return hashlib.sha256(password).digest() == self.LoadStoredData('PasswordHash') | [
"def",
"ValidatePassword",
"(",
"self",
",",
"password",
")",
":",
"password",
"=",
"to_aes_key",
"(",
"password",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"password",
")",
".",
"digest",
"(",
")",
"==",
"self",
".",
"LoadStoredData",
"(",
"'PasswordH... | Validates if the provided password matches with the stored password.
Args:
password (string): a password.
Returns:
bool: the provided password matches with the stored password. | [
"Validates",
"if",
"the",
"provided",
"password",
"matches",
"with",
"the",
"stored",
"password",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L864-L875 |
228,975 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetStandardAddress | def GetStandardAddress(self):
"""
Get the Wallet's default address.
Raises:
Exception: if no default contract address is set.
Returns:
UInt160: script hash.
"""
for contract in self._contracts.values():
if contract.IsStandard:
return contract.ScriptHash
raise Exception("Could not find a standard contract address") | python | def GetStandardAddress(self):
for contract in self._contracts.values():
if contract.IsStandard:
return contract.ScriptHash
raise Exception("Could not find a standard contract address") | [
"def",
"GetStandardAddress",
"(",
"self",
")",
":",
"for",
"contract",
"in",
"self",
".",
"_contracts",
".",
"values",
"(",
")",
":",
"if",
"contract",
".",
"IsStandard",
":",
"return",
"contract",
".",
"ScriptHash",
"raise",
"Exception",
"(",
"\"Could not f... | Get the Wallet's default address.
Raises:
Exception: if no default contract address is set.
Returns:
UInt160: script hash. | [
"Get",
"the",
"Wallet",
"s",
"default",
"address",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L877-L891 |
228,976 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetChangeAddress | def GetChangeAddress(self, from_addr=None):
"""
Get the address where change is send to.
Args:
from_address (UInt160): (optional) from address script hash.
Raises:
Exception: if change address could not be found.
Returns:
UInt160: script hash.
"""
if from_addr is not None:
for contract in self._contracts.values():
if contract.ScriptHash == from_addr:
return contract.ScriptHash
for contract in self._contracts.values():
if contract.IsStandard:
return contract.ScriptHash
if len(self._contracts.values()):
for k, v in self._contracts.items():
return v
raise Exception("Could not find change address") | python | def GetChangeAddress(self, from_addr=None):
if from_addr is not None:
for contract in self._contracts.values():
if contract.ScriptHash == from_addr:
return contract.ScriptHash
for contract in self._contracts.values():
if contract.IsStandard:
return contract.ScriptHash
if len(self._contracts.values()):
for k, v in self._contracts.items():
return v
raise Exception("Could not find change address") | [
"def",
"GetChangeAddress",
"(",
"self",
",",
"from_addr",
"=",
"None",
")",
":",
"if",
"from_addr",
"is",
"not",
"None",
":",
"for",
"contract",
"in",
"self",
".",
"_contracts",
".",
"values",
"(",
")",
":",
"if",
"contract",
".",
"ScriptHash",
"==",
"... | Get the address where change is send to.
Args:
from_address (UInt160): (optional) from address script hash.
Raises:
Exception: if change address could not be found.
Returns:
UInt160: script hash. | [
"Get",
"the",
"address",
"where",
"change",
"is",
"send",
"to",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L893-L919 |
228,977 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetDefaultContract | def GetDefaultContract(self):
"""
Get the default contract.
Returns:
contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.
Raises:
Exception: if no default contract is found.
Note:
Prints a warning to the console if the default contract could not be found.
"""
try:
return self.GetContracts()[0]
except Exception as e:
logger.error("Could not find default contract: %s" % str(e))
raise | python | def GetDefaultContract(self):
try:
return self.GetContracts()[0]
except Exception as e:
logger.error("Could not find default contract: %s" % str(e))
raise | [
"def",
"GetDefaultContract",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"GetContracts",
"(",
")",
"[",
"0",
"]",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Could not find default contract: %s\"",
"%",
"str",
"(",
... | Get the default contract.
Returns:
contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.
Raises:
Exception: if no default contract is found.
Note:
Prints a warning to the console if the default contract could not be found. | [
"Get",
"the",
"default",
"contract",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L921-L938 |
228,978 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetCoinAssets | def GetCoinAssets(self):
"""
Get asset ids of all coins present in the wallet.
Returns:
list: of UInt256 asset id's.
"""
assets = set()
for coin in self.GetCoins():
assets.add(coin.Output.AssetId)
return list(assets) | python | def GetCoinAssets(self):
assets = set()
for coin in self.GetCoins():
assets.add(coin.Output.AssetId)
return list(assets) | [
"def",
"GetCoinAssets",
"(",
"self",
")",
":",
"assets",
"=",
"set",
"(",
")",
"for",
"coin",
"in",
"self",
".",
"GetCoins",
"(",
")",
":",
"assets",
".",
"add",
"(",
"coin",
".",
"Output",
".",
"AssetId",
")",
"return",
"list",
"(",
"assets",
")"
... | Get asset ids of all coins present in the wallet.
Returns:
list: of UInt256 asset id's. | [
"Get",
"asset",
"ids",
"of",
"all",
"coins",
"present",
"in",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L949-L959 |
228,979 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.GetContract | def GetContract(self, script_hash):
"""
Get contract for specified script_hash.
Args:
script_hash (UInt160): a bytearray (len 20).
Returns:
Contract: if a contract was found matching the provided script hash, otherwise None
"""
if script_hash.ToBytes() in self._contracts.keys():
return self._contracts[script_hash.ToBytes()]
return None | python | def GetContract(self, script_hash):
if script_hash.ToBytes() in self._contracts.keys():
return self._contracts[script_hash.ToBytes()]
return None | [
"def",
"GetContract",
"(",
"self",
",",
"script_hash",
")",
":",
"if",
"script_hash",
".",
"ToBytes",
"(",
")",
"in",
"self",
".",
"_contracts",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"_contracts",
"[",
"script_hash",
".",
"ToBytes",
"(",
"... | Get contract for specified script_hash.
Args:
script_hash (UInt160): a bytearray (len 20).
Returns:
Contract: if a contract was found matching the provided script hash, otherwise None | [
"Get",
"contract",
"for",
"specified",
"script_hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L970-L982 |
228,980 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.SaveTransaction | def SaveTransaction(self, tx):
"""
This method is used to after a transaction has been made by this wallet. It updates the states of the coins
In the wallet to reflect the new balance, but the coins remain in a ``CoinState.UNCONFIRMED`` state until
The transaction has been processed by the network.
The results of these updates can be used by overriding the ``OnSaveTransaction`` method, and, for example
persisting the results to a database.
Args:
tx (Transaction): The transaction that has been made by this wallet.
Returns:
bool: True is successfully processes, otherwise False if input is not in the coin list, already spent or not confirmed.
"""
coins = self.GetCoins()
changed = []
added = []
deleted = []
found_coin = False
for input in tx.inputs:
coin = None
for coinref in coins:
test_coin = coinref.Reference
if test_coin == input:
coin = coinref
if coin is None:
return False
if coin.State & CoinState.Spent > 0:
return False
elif coin.State & CoinState.Confirmed == 0:
return False
coin.State |= CoinState.Spent
coin.State &= ~CoinState.Confirmed
changed.append(coin)
for index, output in enumerate(tx.outputs):
state = self.CheckAddressState(output.ScriptHash)
key = CoinReference(tx.Hash, index)
if state & AddressState.InWallet > 0:
newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Unconfirmed)
self._coins[key] = newcoin
if state & AddressState.WatchOnly > 0:
newcoin.State |= CoinState.WatchOnly
added.append(newcoin)
if isinstance(tx, ClaimTransaction):
# do claim stuff
for claim in tx.Claims:
claim_coin = self._coins[claim]
claim_coin.State |= CoinState.Claimed
claim_coin.State &= ~CoinState.Confirmed
changed.append(claim_coin)
self.OnSaveTransaction(tx, added, changed, deleted)
return True | python | def SaveTransaction(self, tx):
coins = self.GetCoins()
changed = []
added = []
deleted = []
found_coin = False
for input in tx.inputs:
coin = None
for coinref in coins:
test_coin = coinref.Reference
if test_coin == input:
coin = coinref
if coin is None:
return False
if coin.State & CoinState.Spent > 0:
return False
elif coin.State & CoinState.Confirmed == 0:
return False
coin.State |= CoinState.Spent
coin.State &= ~CoinState.Confirmed
changed.append(coin)
for index, output in enumerate(tx.outputs):
state = self.CheckAddressState(output.ScriptHash)
key = CoinReference(tx.Hash, index)
if state & AddressState.InWallet > 0:
newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Unconfirmed)
self._coins[key] = newcoin
if state & AddressState.WatchOnly > 0:
newcoin.State |= CoinState.WatchOnly
added.append(newcoin)
if isinstance(tx, ClaimTransaction):
# do claim stuff
for claim in tx.Claims:
claim_coin = self._coins[claim]
claim_coin.State |= CoinState.Claimed
claim_coin.State &= ~CoinState.Confirmed
changed.append(claim_coin)
self.OnSaveTransaction(tx, added, changed, deleted)
return True | [
"def",
"SaveTransaction",
"(",
"self",
",",
"tx",
")",
":",
"coins",
"=",
"self",
".",
"GetCoins",
"(",
")",
"changed",
"=",
"[",
"]",
"added",
"=",
"[",
"]",
"deleted",
"=",
"[",
"]",
"found_coin",
"=",
"False",
"for",
"input",
"in",
"tx",
".",
... | This method is used to after a transaction has been made by this wallet. It updates the states of the coins
In the wallet to reflect the new balance, but the coins remain in a ``CoinState.UNCONFIRMED`` state until
The transaction has been processed by the network.
The results of these updates can be used by overriding the ``OnSaveTransaction`` method, and, for example
persisting the results to a database.
Args:
tx (Transaction): The transaction that has been made by this wallet.
Returns:
bool: True is successfully processes, otherwise False if input is not in the coin list, already spent or not confirmed. | [
"This",
"method",
"is",
"used",
"to",
"after",
"a",
"transaction",
"has",
"been",
"made",
"by",
"this",
"wallet",
".",
"It",
"updates",
"the",
"states",
"of",
"the",
"coins",
"In",
"the",
"wallet",
"to",
"reflect",
"the",
"new",
"balance",
"but",
"the",
... | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L1118-L1182 |
228,981 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.SignMessage | def SignMessage(self, message, script_hash):
"""
Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message
"""
keypair = self.GetKeyByScriptHash(script_hash)
prikey = bytes(keypair.PrivateKey)
res = Crypto.Default().Sign(message, prikey)
return res, keypair.PublicKey | python | def SignMessage(self, message, script_hash):
keypair = self.GetKeyByScriptHash(script_hash)
prikey = bytes(keypair.PrivateKey)
res = Crypto.Default().Sign(message, prikey)
return res, keypair.PublicKey | [
"def",
"SignMessage",
"(",
"self",
",",
"message",
",",
"script_hash",
")",
":",
"keypair",
"=",
"self",
".",
"GetKeyByScriptHash",
"(",
"script_hash",
")",
"prikey",
"=",
"bytes",
"(",
"keypair",
".",
"PrivateKey",
")",
"res",
"=",
"Crypto",
".",
"Default... | Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message | [
"Sign",
"a",
"message",
"with",
"a",
"specified",
"script_hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L1217-L1232 |
228,982 | CityOfZion/neo-python | neo/Wallets/Wallet.py | Wallet.IsSynced | def IsSynced(self):
"""
Check if wallet is synced.
Returns:
bool: True if wallet is synced.
"""
if Blockchain.Default().Height == 0:
return False
if (int(100 * self._current_height / Blockchain.Default().Height)) < 100:
return False
else:
return True | python | def IsSynced(self):
if Blockchain.Default().Height == 0:
return False
if (int(100 * self._current_height / Blockchain.Default().Height)) < 100:
return False
else:
return True | [
"def",
"IsSynced",
"(",
"self",
")",
":",
"if",
"Blockchain",
".",
"Default",
"(",
")",
".",
"Height",
"==",
"0",
":",
"return",
"False",
"if",
"(",
"int",
"(",
"100",
"*",
"self",
".",
"_current_height",
"/",
"Blockchain",
".",
"Default",
"(",
")",
... | Check if wallet is synced.
Returns:
bool: True if wallet is synced. | [
"Check",
"if",
"wallet",
"is",
"synced",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L1254-L1268 |
228,983 | CityOfZion/neo-python | neo/Implementations/Wallets/peewee/UserWallet.py | UserWallet.Create | def Create(path, password, generate_default_key=True):
"""
Create a new user wallet.
Args:
path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet".
password (str): a 10 characters minimum password to secure the wallet with.
Returns:
UserWallet: a UserWallet instance.
"""
wallet = UserWallet(path=path, passwordKey=password, create=True)
if generate_default_key:
wallet.CreateKey()
return wallet | python | def Create(path, password, generate_default_key=True):
wallet = UserWallet(path=path, passwordKey=password, create=True)
if generate_default_key:
wallet.CreateKey()
return wallet | [
"def",
"Create",
"(",
"path",
",",
"password",
",",
"generate_default_key",
"=",
"True",
")",
":",
"wallet",
"=",
"UserWallet",
"(",
"path",
"=",
"path",
",",
"passwordKey",
"=",
"password",
",",
"create",
"=",
"True",
")",
"if",
"generate_default_key",
":... | Create a new user wallet.
Args:
path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet".
password (str): a 10 characters minimum password to secure the wallet with.
Returns:
UserWallet: a UserWallet instance. | [
"Create",
"a",
"new",
"user",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Wallets/peewee/UserWallet.py#L83-L97 |
228,984 | CityOfZion/neo-python | neo/Implementations/Wallets/peewee/UserWallet.py | UserWallet.CreateKey | def CreateKey(self, prikey=None):
"""
Create a KeyPair and store it encrypted in the database.
Args:
private_key (iterable_of_ints): (optional) 32 byte private key.
Returns:
KeyPair: a KeyPair instance.
"""
account = super(UserWallet, self).CreateKey(private_key=prikey)
self.OnCreateAccount(account)
contract = WalletContract.CreateSignatureContract(account.PublicKey)
self.AddContract(contract)
return account | python | def CreateKey(self, prikey=None):
account = super(UserWallet, self).CreateKey(private_key=prikey)
self.OnCreateAccount(account)
contract = WalletContract.CreateSignatureContract(account.PublicKey)
self.AddContract(contract)
return account | [
"def",
"CreateKey",
"(",
"self",
",",
"prikey",
"=",
"None",
")",
":",
"account",
"=",
"super",
"(",
"UserWallet",
",",
"self",
")",
".",
"CreateKey",
"(",
"private_key",
"=",
"prikey",
")",
"self",
".",
"OnCreateAccount",
"(",
"account",
")",
"contract"... | Create a KeyPair and store it encrypted in the database.
Args:
private_key (iterable_of_ints): (optional) 32 byte private key.
Returns:
KeyPair: a KeyPair instance. | [
"Create",
"a",
"KeyPair",
"and",
"store",
"it",
"encrypted",
"in",
"the",
"database",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Wallets/peewee/UserWallet.py#L99-L113 |
228,985 | CityOfZion/neo-python | neo/Implementations/Wallets/peewee/UserWallet.py | UserWallet.OnCreateAccount | def OnCreateAccount(self, account):
"""
Save a KeyPair in encrypted form into the database.
Args:
account (KeyPair):
"""
pubkey = account.PublicKey.encode_point(False)
pubkeyunhex = binascii.unhexlify(pubkey)
pub = pubkeyunhex[1:65]
priv = bytearray(account.PrivateKey)
decrypted = pub + priv
encrypted_pk = self.EncryptPrivateKey(bytes(decrypted))
db_account, created = Account.get_or_create(
PrivateKeyEncrypted=encrypted_pk, PublicKeyHash=account.PublicKeyHash.ToBytes())
db_account.save()
self.__dbaccount = db_account | python | def OnCreateAccount(self, account):
pubkey = account.PublicKey.encode_point(False)
pubkeyunhex = binascii.unhexlify(pubkey)
pub = pubkeyunhex[1:65]
priv = bytearray(account.PrivateKey)
decrypted = pub + priv
encrypted_pk = self.EncryptPrivateKey(bytes(decrypted))
db_account, created = Account.get_or_create(
PrivateKeyEncrypted=encrypted_pk, PublicKeyHash=account.PublicKeyHash.ToBytes())
db_account.save()
self.__dbaccount = db_account | [
"def",
"OnCreateAccount",
"(",
"self",
",",
"account",
")",
":",
"pubkey",
"=",
"account",
".",
"PublicKey",
".",
"encode_point",
"(",
"False",
")",
"pubkeyunhex",
"=",
"binascii",
".",
"unhexlify",
"(",
"pubkey",
")",
"pub",
"=",
"pubkeyunhex",
"[",
"1",
... | Save a KeyPair in encrypted form into the database.
Args:
account (KeyPair): | [
"Save",
"a",
"KeyPair",
"in",
"encrypted",
"form",
"into",
"the",
"database",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Wallets/peewee/UserWallet.py#L115-L133 |
228,986 | CityOfZion/neo-python | neo/Implementations/Wallets/peewee/UserWallet.py | UserWallet.AddContract | def AddContract(self, contract):
"""
Add a contract to the database.
Args:
contract(neo.SmartContract.Contract): a Contract instance.
"""
super(UserWallet, self).AddContract(contract)
try:
db_contract = Contract.get(ScriptHash=contract.ScriptHash.ToBytes())
db_contract.delete_instance()
except Exception as e:
logger.debug("contract does not exist yet")
sh = bytes(contract.ScriptHash.ToArray())
address, created = Address.get_or_create(ScriptHash=sh)
address.IsWatchOnly = False
address.save()
db_contract = Contract.create(RawData=contract.ToArray(),
ScriptHash=contract.ScriptHash.ToBytes(),
PublicKeyHash=contract.PublicKeyHash.ToBytes(),
Address=address,
Account=self.__dbaccount)
logger.debug("Creating db contract %s " % db_contract)
db_contract.save() | python | def AddContract(self, contract):
super(UserWallet, self).AddContract(contract)
try:
db_contract = Contract.get(ScriptHash=contract.ScriptHash.ToBytes())
db_contract.delete_instance()
except Exception as e:
logger.debug("contract does not exist yet")
sh = bytes(contract.ScriptHash.ToArray())
address, created = Address.get_or_create(ScriptHash=sh)
address.IsWatchOnly = False
address.save()
db_contract = Contract.create(RawData=contract.ToArray(),
ScriptHash=contract.ScriptHash.ToBytes(),
PublicKeyHash=contract.PublicKeyHash.ToBytes(),
Address=address,
Account=self.__dbaccount)
logger.debug("Creating db contract %s " % db_contract)
db_contract.save() | [
"def",
"AddContract",
"(",
"self",
",",
"contract",
")",
":",
"super",
"(",
"UserWallet",
",",
"self",
")",
".",
"AddContract",
"(",
"contract",
")",
"try",
":",
"db_contract",
"=",
"Contract",
".",
"get",
"(",
"ScriptHash",
"=",
"contract",
".",
"Script... | Add a contract to the database.
Args:
contract(neo.SmartContract.Contract): a Contract instance. | [
"Add",
"a",
"contract",
"to",
"the",
"database",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Wallets/peewee/UserWallet.py#L135-L162 |
228,987 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.Disconnect | def Disconnect(self, reason=None, isDead=True):
"""Close the connection with the remote node client."""
self.disconnecting = True
self.expect_verack_next = False
if reason:
logger.debug(f"Disconnecting with reason: {reason}")
self.stop_block_loop()
self.stop_header_loop()
self.stop_peerinfo_loop()
if isDead:
self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Forced disconnect by us")
self.leader.forced_disconnect_by_us += 1
self.disconnect_deferred = defer.Deferred()
self.disconnect_deferred.debug = True
# force disconnection without waiting on the other side
# calling later to give func caller time to add callbacks to the deferred
reactor.callLater(1, self.transport.abortConnection)
return self.disconnect_deferred | python | def Disconnect(self, reason=None, isDead=True):
self.disconnecting = True
self.expect_verack_next = False
if reason:
logger.debug(f"Disconnecting with reason: {reason}")
self.stop_block_loop()
self.stop_header_loop()
self.stop_peerinfo_loop()
if isDead:
self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Forced disconnect by us")
self.leader.forced_disconnect_by_us += 1
self.disconnect_deferred = defer.Deferred()
self.disconnect_deferred.debug = True
# force disconnection without waiting on the other side
# calling later to give func caller time to add callbacks to the deferred
reactor.callLater(1, self.transport.abortConnection)
return self.disconnect_deferred | [
"def",
"Disconnect",
"(",
"self",
",",
"reason",
"=",
"None",
",",
"isDead",
"=",
"True",
")",
":",
"self",
".",
"disconnecting",
"=",
"True",
"self",
".",
"expect_verack_next",
"=",
"False",
"if",
"reason",
":",
"logger",
".",
"debug",
"(",
"f\"Disconne... | Close the connection with the remote node client. | [
"Close",
"the",
"connection",
"with",
"the",
"remote",
"node",
"client",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L171-L190 |
228,988 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.Name | def Name(self):
"""
Get the peer name.
Returns:
str:
"""
name = ""
if self.Version:
name = self.Version.UserAgent
return name | python | def Name(self):
name = ""
if self.Version:
name = self.Version.UserAgent
return name | [
"def",
"Name",
"(",
"self",
")",
":",
"name",
"=",
"\"\"",
"if",
"self",
".",
"Version",
":",
"name",
"=",
"self",
".",
"Version",
".",
"UserAgent",
"return",
"name"
] | Get the peer name.
Returns:
str: | [
"Get",
"the",
"peer",
"name",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L199-L209 |
228,989 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.GetNetworkAddressWithTime | def GetNetworkAddressWithTime(self):
"""
Get a network address object.
Returns:
NetworkAddressWithTime: if we have a connection to a node.
None: otherwise.
"""
if self.port is not None and self.host is not None and self.Version is not None:
return NetworkAddressWithTime(self.host, self.port, self.Version.Services)
return None | python | def GetNetworkAddressWithTime(self):
if self.port is not None and self.host is not None and self.Version is not None:
return NetworkAddressWithTime(self.host, self.port, self.Version.Services)
return None | [
"def",
"GetNetworkAddressWithTime",
"(",
"self",
")",
":",
"if",
"self",
".",
"port",
"is",
"not",
"None",
"and",
"self",
".",
"host",
"is",
"not",
"None",
"and",
"self",
".",
"Version",
"is",
"not",
"None",
":",
"return",
"NetworkAddressWithTime",
"(",
... | Get a network address object.
Returns:
NetworkAddressWithTime: if we have a connection to a node.
None: otherwise. | [
"Get",
"a",
"network",
"address",
"object",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L211-L221 |
228,990 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.connectionMade | def connectionMade(self):
"""Callback handler from twisted when establishing a new connection."""
self.endpoint = self.transport.getPeer()
# get the reference to the Address object in NodeLeader so we can manipulate it properly.
tmp_addr = Address(f"{self.endpoint.host}:{self.endpoint.port}")
try:
known_idx = self.leader.KNOWN_ADDRS.index(tmp_addr)
self.address = self.leader.KNOWN_ADDRS[known_idx]
except ValueError:
# Not found.
self.leader.AddKnownAddress(tmp_addr)
self.address = tmp_addr
self.address.address = "%s:%s" % (self.endpoint.host, self.endpoint.port)
self.host = self.endpoint.host
self.port = int(self.endpoint.port)
self.leader.AddConnectedPeer(self)
self.leader.RemoveFromQueue(self.address)
self.leader.peers_connecting -= 1
logger.debug(f"{self.address} connection established")
if self.incoming_client:
# start protocol
self.SendVersion() | python | def connectionMade(self):
self.endpoint = self.transport.getPeer()
# get the reference to the Address object in NodeLeader so we can manipulate it properly.
tmp_addr = Address(f"{self.endpoint.host}:{self.endpoint.port}")
try:
known_idx = self.leader.KNOWN_ADDRS.index(tmp_addr)
self.address = self.leader.KNOWN_ADDRS[known_idx]
except ValueError:
# Not found.
self.leader.AddKnownAddress(tmp_addr)
self.address = tmp_addr
self.address.address = "%s:%s" % (self.endpoint.host, self.endpoint.port)
self.host = self.endpoint.host
self.port = int(self.endpoint.port)
self.leader.AddConnectedPeer(self)
self.leader.RemoveFromQueue(self.address)
self.leader.peers_connecting -= 1
logger.debug(f"{self.address} connection established")
if self.incoming_client:
# start protocol
self.SendVersion() | [
"def",
"connectionMade",
"(",
"self",
")",
":",
"self",
".",
"endpoint",
"=",
"self",
".",
"transport",
".",
"getPeer",
"(",
")",
"# get the reference to the Address object in NodeLeader so we can manipulate it properly.",
"tmp_addr",
"=",
"Address",
"(",
"f\"{self.endpoi... | Callback handler from twisted when establishing a new connection. | [
"Callback",
"handler",
"from",
"twisted",
"when",
"establishing",
"a",
"new",
"connection",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L235-L257 |
228,991 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.connectionLost | def connectionLost(self, reason=None):
"""Callback handler from twisted when a connection was lost."""
try:
self.connected = False
self.stop_block_loop()
self.stop_peerinfo_loop()
self.stop_header_loop()
self.ReleaseBlockRequests()
self.leader.RemoveConnectedPeer(self)
time_expired = self.time_expired(HEARTBEAT_BLOCKS)
# some NEO-cli versions have a 30s timeout to receive block/consensus or tx messages. By default neo-python doesn't respond to these requests
if time_expired > 20:
self.address.last_connection = Address.Now()
self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Premature disconnect")
if reason and reason.check(twisted_error.ConnectionDone):
# this might happen if they close our connection because they've reached max peers or something similar
logger.debug(f"{self.prefix} disconnected normally with reason:{reason.value}")
self._check_for_consecutive_disconnects("connection done")
elif reason and reason.check(twisted_error.ConnectionLost):
# Can be due to a timeout. Only if this happened again within 5 minutes do we label the node as bad
# because then it clearly doesn't want to talk to us or we have a bad connection to them.
# Otherwise allow for the node to be queued again by NodeLeader.
logger.debug(f"{self.prefix} disconnected with connectionlost reason: {reason.value}")
self._check_for_consecutive_disconnects("connection lost")
else:
logger.debug(f"{self.prefix} disconnected with reason: {reason.value}")
except Exception as e:
logger.error("Error with connection lost: %s " % e)
def try_me(err):
err.check(error.ConnectionAborted)
if self.disconnect_deferred:
d, self.disconnect_deferred = self.disconnect_deferred, None # type: defer.Deferred
d.addErrback(try_me)
if len(d.callbacks) > 0:
d.callback(reason)
else:
print("connLost, disconnect_deferred cancelling!")
d.cancel() | python | def connectionLost(self, reason=None):
try:
self.connected = False
self.stop_block_loop()
self.stop_peerinfo_loop()
self.stop_header_loop()
self.ReleaseBlockRequests()
self.leader.RemoveConnectedPeer(self)
time_expired = self.time_expired(HEARTBEAT_BLOCKS)
# some NEO-cli versions have a 30s timeout to receive block/consensus or tx messages. By default neo-python doesn't respond to these requests
if time_expired > 20:
self.address.last_connection = Address.Now()
self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Premature disconnect")
if reason and reason.check(twisted_error.ConnectionDone):
# this might happen if they close our connection because they've reached max peers or something similar
logger.debug(f"{self.prefix} disconnected normally with reason:{reason.value}")
self._check_for_consecutive_disconnects("connection done")
elif reason and reason.check(twisted_error.ConnectionLost):
# Can be due to a timeout. Only if this happened again within 5 minutes do we label the node as bad
# because then it clearly doesn't want to talk to us or we have a bad connection to them.
# Otherwise allow for the node to be queued again by NodeLeader.
logger.debug(f"{self.prefix} disconnected with connectionlost reason: {reason.value}")
self._check_for_consecutive_disconnects("connection lost")
else:
logger.debug(f"{self.prefix} disconnected with reason: {reason.value}")
except Exception as e:
logger.error("Error with connection lost: %s " % e)
def try_me(err):
err.check(error.ConnectionAborted)
if self.disconnect_deferred:
d, self.disconnect_deferred = self.disconnect_deferred, None # type: defer.Deferred
d.addErrback(try_me)
if len(d.callbacks) > 0:
d.callback(reason)
else:
print("connLost, disconnect_deferred cancelling!")
d.cancel() | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"connected",
"=",
"False",
"self",
".",
"stop_block_loop",
"(",
")",
"self",
".",
"stop_peerinfo_loop",
"(",
")",
"self",
".",
"stop_header_loop",
"(",
"... | Callback handler from twisted when a connection was lost. | [
"Callback",
"handler",
"from",
"twisted",
"when",
"a",
"connection",
"was",
"lost",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L259-L303 |
228,992 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.dataReceived | def dataReceived(self, data):
""" Called from Twisted whenever data is received. """
self.bytes_in += (len(data))
self.buffer_in = self.buffer_in + data
while self.CheckDataReceived():
pass | python | def dataReceived(self, data):
self.bytes_in += (len(data))
self.buffer_in = self.buffer_in + data
while self.CheckDataReceived():
pass | [
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"bytes_in",
"+=",
"(",
"len",
"(",
"data",
")",
")",
"self",
".",
"buffer_in",
"=",
"self",
".",
"buffer_in",
"+",
"data",
"while",
"self",
".",
"CheckDataReceived",
"(",
")",
":... | Called from Twisted whenever data is received. | [
"Called",
"from",
"Twisted",
"whenever",
"data",
"is",
"received",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L326-L332 |
228,993 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.CheckDataReceived | def CheckDataReceived(self):
"""Tries to extract a Message from the data buffer and process it."""
currentLength = len(self.buffer_in)
if currentLength < 24:
return False
# Extract the message header from the buffer, and return if not enough
# buffer to fully deserialize the message object.
try:
# Construct message
mstart = self.buffer_in[:24]
ms = StreamManager.GetStream(mstart)
reader = BinaryReader(ms)
m = Message()
# Extract message metadata
m.Magic = reader.ReadUInt32()
m.Command = reader.ReadFixedString(12).decode('utf-8')
m.Length = reader.ReadUInt32()
m.Checksum = reader.ReadUInt32()
# Return if not enough buffer to fully deserialize object.
messageExpectedLength = 24 + m.Length
if currentLength < messageExpectedLength:
return False
except Exception as e:
logger.debug(f"{self.prefix} Error: could not read message header from stream {e}")
# self.Log('Error: Could not read initial bytes %s ' % e)
return False
finally:
StreamManager.ReleaseStream(ms)
del reader
# The message header was successfully extracted, and we have enough enough buffer
# to extract the full payload
try:
# Extract message bytes from buffer and truncate buffer
mdata = self.buffer_in[:messageExpectedLength]
self.buffer_in = self.buffer_in[messageExpectedLength:]
# Deserialize message with payload
stream = StreamManager.GetStream(mdata)
reader = BinaryReader(stream)
message = Message()
message.Deserialize(reader)
if self.incoming_client and self.expect_verack_next:
if message.Command != 'verack':
self.Disconnect("Expected 'verack' got {}".format(message.Command))
# Propagate new message
self.MessageReceived(message)
except Exception as e:
logger.debug(f"{self.prefix} Could not extract message {e}")
# self.Log('Error: Could not extract message: %s ' % e)
return False
finally:
StreamManager.ReleaseStream(stream)
return True | python | def CheckDataReceived(self):
currentLength = len(self.buffer_in)
if currentLength < 24:
return False
# Extract the message header from the buffer, and return if not enough
# buffer to fully deserialize the message object.
try:
# Construct message
mstart = self.buffer_in[:24]
ms = StreamManager.GetStream(mstart)
reader = BinaryReader(ms)
m = Message()
# Extract message metadata
m.Magic = reader.ReadUInt32()
m.Command = reader.ReadFixedString(12).decode('utf-8')
m.Length = reader.ReadUInt32()
m.Checksum = reader.ReadUInt32()
# Return if not enough buffer to fully deserialize object.
messageExpectedLength = 24 + m.Length
if currentLength < messageExpectedLength:
return False
except Exception as e:
logger.debug(f"{self.prefix} Error: could not read message header from stream {e}")
# self.Log('Error: Could not read initial bytes %s ' % e)
return False
finally:
StreamManager.ReleaseStream(ms)
del reader
# The message header was successfully extracted, and we have enough enough buffer
# to extract the full payload
try:
# Extract message bytes from buffer and truncate buffer
mdata = self.buffer_in[:messageExpectedLength]
self.buffer_in = self.buffer_in[messageExpectedLength:]
# Deserialize message with payload
stream = StreamManager.GetStream(mdata)
reader = BinaryReader(stream)
message = Message()
message.Deserialize(reader)
if self.incoming_client and self.expect_verack_next:
if message.Command != 'verack':
self.Disconnect("Expected 'verack' got {}".format(message.Command))
# Propagate new message
self.MessageReceived(message)
except Exception as e:
logger.debug(f"{self.prefix} Could not extract message {e}")
# self.Log('Error: Could not extract message: %s ' % e)
return False
finally:
StreamManager.ReleaseStream(stream)
return True | [
"def",
"CheckDataReceived",
"(",
"self",
")",
":",
"currentLength",
"=",
"len",
"(",
"self",
".",
"buffer_in",
")",
"if",
"currentLength",
"<",
"24",
":",
"return",
"False",
"# Extract the message header from the buffer, and return if not enough",
"# buffer to fully deser... | Tries to extract a Message from the data buffer and process it. | [
"Tries",
"to",
"extract",
"a",
"Message",
"from",
"the",
"data",
"buffer",
"and",
"process",
"it",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L334-L397 |
228,994 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.HandlePeerInfoReceived | def HandlePeerInfoReceived(self, payload):
"""Process response of `self.RequestPeerInfo`."""
addrs = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.AddrPayload.AddrPayload')
if not addrs:
return
for nawt in addrs.NetworkAddressesWithTime:
self.leader.RemoteNodePeerReceived(nawt.Address, nawt.Port, self.prefix) | python | def HandlePeerInfoReceived(self, payload):
addrs = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.AddrPayload.AddrPayload')
if not addrs:
return
for nawt in addrs.NetworkAddressesWithTime:
self.leader.RemoteNodePeerReceived(nawt.Address, nawt.Port, self.prefix) | [
"def",
"HandlePeerInfoReceived",
"(",
"self",
",",
"payload",
")",
":",
"addrs",
"=",
"IOHelper",
".",
"AsSerializableWithType",
"(",
"payload",
",",
"'neo.Network.Payloads.AddrPayload.AddrPayload'",
")",
"if",
"not",
"addrs",
":",
"return",
"for",
"nawt",
"in",
"... | Process response of `self.RequestPeerInfo`. | [
"Process",
"response",
"of",
"self",
".",
"RequestPeerInfo",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L538-L546 |
228,995 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.SendVersion | def SendVersion(self):
"""Send our client version."""
m = Message("version", VersionPayload(settings.NODE_PORT, self.remote_nodeid, settings.VERSION_NAME))
self.SendSerializedMessage(m) | python | def SendVersion(self):
m = Message("version", VersionPayload(settings.NODE_PORT, self.remote_nodeid, settings.VERSION_NAME))
self.SendSerializedMessage(m) | [
"def",
"SendVersion",
"(",
"self",
")",
":",
"m",
"=",
"Message",
"(",
"\"version\"",
",",
"VersionPayload",
"(",
"settings",
".",
"NODE_PORT",
",",
"self",
".",
"remote_nodeid",
",",
"settings",
".",
"VERSION_NAME",
")",
")",
"self",
".",
"SendSerializedMes... | Send our client version. | [
"Send",
"our",
"client",
"version",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L569-L572 |
228,996 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.SendVerack | def SendVerack(self):
"""Send version acknowledge"""
m = Message('verack')
self.SendSerializedMessage(m)
self.expect_verack_next = True | python | def SendVerack(self):
m = Message('verack')
self.SendSerializedMessage(m)
self.expect_verack_next = True | [
"def",
"SendVerack",
"(",
"self",
")",
":",
"m",
"=",
"Message",
"(",
"'verack'",
")",
"self",
".",
"SendSerializedMessage",
"(",
"m",
")",
"self",
".",
"expect_verack_next",
"=",
"True"
] | Send version acknowledge | [
"Send",
"version",
"acknowledge"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L574-L578 |
228,997 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.HandleVersion | def HandleVersion(self, payload):
"""Process the response of `self.RequestVersion`."""
self.Version = IOHelper.AsSerializableWithType(payload, "neo.Network.Payloads.VersionPayload.VersionPayload")
if not self.Version:
return
if self.incoming_client:
if self.Version.Nonce == self.nodeid:
self.Disconnect()
self.SendVerack()
else:
self.nodeid = self.Version.Nonce
self.SendVersion() | python | def HandleVersion(self, payload):
self.Version = IOHelper.AsSerializableWithType(payload, "neo.Network.Payloads.VersionPayload.VersionPayload")
if not self.Version:
return
if self.incoming_client:
if self.Version.Nonce == self.nodeid:
self.Disconnect()
self.SendVerack()
else:
self.nodeid = self.Version.Nonce
self.SendVersion() | [
"def",
"HandleVersion",
"(",
"self",
",",
"payload",
")",
":",
"self",
".",
"Version",
"=",
"IOHelper",
".",
"AsSerializableWithType",
"(",
"payload",
",",
"\"neo.Network.Payloads.VersionPayload.VersionPayload\"",
")",
"if",
"not",
"self",
".",
"Version",
":",
"re... | Process the response of `self.RequestVersion`. | [
"Process",
"the",
"response",
"of",
"self",
".",
"RequestVersion",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L580-L593 |
228,998 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.HandleVerack | def HandleVerack(self):
"""Handle the `verack` response."""
m = Message('verack')
self.SendSerializedMessage(m)
self.leader.NodeCount += 1
self.identifier = self.leader.NodeCount
logger.debug(f"{self.prefix} Handshake complete!")
self.handshake_complete = True
self.ProtocolReady() | python | def HandleVerack(self):
m = Message('verack')
self.SendSerializedMessage(m)
self.leader.NodeCount += 1
self.identifier = self.leader.NodeCount
logger.debug(f"{self.prefix} Handshake complete!")
self.handshake_complete = True
self.ProtocolReady() | [
"def",
"HandleVerack",
"(",
"self",
")",
":",
"m",
"=",
"Message",
"(",
"'verack'",
")",
"self",
".",
"SendSerializedMessage",
"(",
"m",
")",
"self",
".",
"leader",
".",
"NodeCount",
"+=",
"1",
"self",
".",
"identifier",
"=",
"self",
".",
"leader",
"."... | Handle the `verack` response. | [
"Handle",
"the",
"verack",
"response",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L595-L603 |
228,999 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.SendSerializedMessage | def SendSerializedMessage(self, message):
"""
Send the `message` to the remote client.
Args:
message (neo.Network.Message):
"""
try:
ba = Helper.ToArray(message)
ba2 = binascii.unhexlify(ba)
self.bytes_out += len(ba2)
self.transport.write(ba2)
except Exception as e:
logger.debug(f"Could not send serialized message {e}") | python | def SendSerializedMessage(self, message):
try:
ba = Helper.ToArray(message)
ba2 = binascii.unhexlify(ba)
self.bytes_out += len(ba2)
self.transport.write(ba2)
except Exception as e:
logger.debug(f"Could not send serialized message {e}") | [
"def",
"SendSerializedMessage",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"ba",
"=",
"Helper",
".",
"ToArray",
"(",
"message",
")",
"ba2",
"=",
"binascii",
".",
"unhexlify",
"(",
"ba",
")",
"self",
".",
"bytes_out",
"+=",
"len",
"(",
"ba2",
... | Send the `message` to the remote client.
Args:
message (neo.Network.Message): | [
"Send",
"the",
"message",
"to",
"the",
"remote",
"client",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L638-L651 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.