repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
bcb/jsonrpcclient
jsonrpcclient/response.py
sort_response
def sort_response(response: Dict[str, Any]) -> OrderedDict: """ Sort the keys in a JSON-RPC response object. This has no effect other than making it nicer to read. Useful in Python 3.5 only, dictionaries are already sorted in newer Python versions. Example:: >>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'})) {"jsonrpc": "2.0", "result": 5, "id": 1} Args: response: Deserialized JSON-RPC response. Returns: The same response, sorted in an OrderedDict. """ root_order = ["jsonrpc", "result", "error", "id"] error_order = ["code", "message", "data"] req = OrderedDict(sorted(response.items(), key=lambda k: root_order.index(k[0]))) if "error" in response: req["error"] = OrderedDict( sorted(response["error"].items(), key=lambda k: error_order.index(k[0])) ) return req
python
def sort_response(response: Dict[str, Any]) -> OrderedDict: """ Sort the keys in a JSON-RPC response object. This has no effect other than making it nicer to read. Useful in Python 3.5 only, dictionaries are already sorted in newer Python versions. Example:: >>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'})) {"jsonrpc": "2.0", "result": 5, "id": 1} Args: response: Deserialized JSON-RPC response. Returns: The same response, sorted in an OrderedDict. """ root_order = ["jsonrpc", "result", "error", "id"] error_order = ["code", "message", "data"] req = OrderedDict(sorted(response.items(), key=lambda k: root_order.index(k[0]))) if "error" in response: req["error"] = OrderedDict( sorted(response["error"].items(), key=lambda k: error_order.index(k[0])) ) return req
[ "def", "sort_response", "(", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "OrderedDict", ":", "root_order", "=", "[", "\"jsonrpc\"", ",", "\"result\"", ",", "\"error\"", ",", "\"id\"", "]", "error_order", "=", "[", "\"code\"", ",", "\"message\"", ",", "\"data\"", "]", "req", "=", "OrderedDict", "(", "sorted", "(", "response", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "root_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")", "if", "\"error\"", "in", "response", ":", "req", "[", "\"error\"", "]", "=", "OrderedDict", "(", "sorted", "(", "response", "[", "\"error\"", "]", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "error_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")", "return", "req" ]
Sort the keys in a JSON-RPC response object. This has no effect other than making it nicer to read. Useful in Python 3.5 only, dictionaries are already sorted in newer Python versions. Example:: >>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'})) {"jsonrpc": "2.0", "result": 5, "id": 1} Args: response: Deserialized JSON-RPC response. Returns: The same response, sorted in an OrderedDict.
[ "Sort", "the", "keys", "in", "a", "JSON", "-", "RPC", "response", "object", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/response.py#L13-L38
bcb/jsonrpcclient
jsonrpcclient/response.py
total_results
def total_results( data: Union[List[JSONRPCResponse], JSONRPCResponse, None], *, ok: bool = True ) -> int: """ Returns the total parsed responses, given the return value from parse(). """ if isinstance(data, list): return sum([1 for d in data if d.ok == ok]) elif isinstance(data, JSONRPCResponse): return int(data.ok == ok) return 0
python
def total_results( data: Union[List[JSONRPCResponse], JSONRPCResponse, None], *, ok: bool = True ) -> int: """ Returns the total parsed responses, given the return value from parse(). """ if isinstance(data, list): return sum([1 for d in data if d.ok == ok]) elif isinstance(data, JSONRPCResponse): return int(data.ok == ok) return 0
[ "def", "total_results", "(", "data", ":", "Union", "[", "List", "[", "JSONRPCResponse", "]", ",", "JSONRPCResponse", ",", "None", "]", ",", "*", ",", "ok", ":", "bool", "=", "True", ")", "->", "int", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "return", "sum", "(", "[", "1", "for", "d", "in", "data", "if", "d", ".", "ok", "==", "ok", "]", ")", "elif", "isinstance", "(", "data", ",", "JSONRPCResponse", ")", ":", "return", "int", "(", "data", ".", "ok", "==", "ok", ")", "return", "0" ]
Returns the total parsed responses, given the return value from parse().
[ "Returns", "the", "total", "parsed", "responses", "given", "the", "return", "value", "from", "parse", "()", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/response.py#L121-L131
bcb/jsonrpcclient
jsonrpcclient/clients/aiohttp_client.py
AiohttpClient.send_message
async def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ with async_timeout.timeout(self.timeout): async with self.session.post( self.endpoint, data=request, ssl=self.ssl ) as response: response_text = await response.text() return Response(response_text, raw=response)
python
async def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ with async_timeout.timeout(self.timeout): async with self.session.post( self.endpoint, data=request, ssl=self.ssl ) as response: response_text = await response.text() return Response(response_text, raw=response)
[ "async", "def", "send_message", "(", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "with", "async_timeout", ".", "timeout", "(", "self", ".", "timeout", ")", ":", "async", "with", "self", ".", "session", ".", "post", "(", "self", ".", "endpoint", ",", "data", "=", "request", ",", "ssl", "=", "self", ".", "ssl", ")", "as", "response", ":", "response_text", "=", "await", "response", ".", "text", "(", ")", "return", "Response", "(", "response_text", ",", "raw", "=", "response", ")" ]
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
[ "Transport", "the", "message", "to", "the", "server", "and", "return", "the", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/aiohttp_client.py#L53-L71
bcb/jsonrpcclient
jsonrpcclient/clients/websockets_client.py
WebSocketsClient.send_message
async def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ await self.socket.send(request) if response_expected: response_text = await self.socket.recv() return Response(response_text) return Response("")
python
async def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ await self.socket.send(request) if response_expected: response_text = await self.socket.recv() return Response(response_text) return Response("")
[ "async", "def", "send_message", "(", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "await", "self", ".", "socket", ".", "send", "(", "request", ")", "if", "response_expected", ":", "response_text", "=", "await", "self", ".", "socket", ".", "recv", "(", ")", "return", "Response", "(", "response_text", ")", "return", "Response", "(", "\"\"", ")" ]
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
[ "Transport", "the", "message", "to", "the", "server", "and", "return", "the", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/websockets_client.py#L25-L42
bcb/jsonrpcclient
jsonrpcclient/config.py
parse_callable
def parse_callable(path: str) -> Iterator: """ ConfigParser converter. Calls the specified object, e.g. Option "id_generators.decimal" returns `id_generators.decimal()`. """ module = path[: path.rindex(".")] callable_name = path[path.rindex(".") + 1 :] callable_ = getattr(importlib.import_module(module), callable_name) return callable_()
python
def parse_callable(path: str) -> Iterator: """ ConfigParser converter. Calls the specified object, e.g. Option "id_generators.decimal" returns `id_generators.decimal()`. """ module = path[: path.rindex(".")] callable_name = path[path.rindex(".") + 1 :] callable_ = getattr(importlib.import_module(module), callable_name) return callable_()
[ "def", "parse_callable", "(", "path", ":", "str", ")", "->", "Iterator", ":", "module", "=", "path", "[", ":", "path", ".", "rindex", "(", "\".\"", ")", "]", "callable_name", "=", "path", "[", "path", ".", "rindex", "(", "\".\"", ")", "+", "1", ":", "]", "callable_", "=", "getattr", "(", "importlib", ".", "import_module", "(", "module", ")", ",", "callable_name", ")", "return", "callable_", "(", ")" ]
ConfigParser converter. Calls the specified object, e.g. Option "id_generators.decimal" returns `id_generators.decimal()`.
[ "ConfigParser", "converter", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/config.py#L12-L22
bcb/jsonrpcclient
jsonrpcclient/id_generators.py
random
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]: """ A random string. Not unique, but has around 1 in a million chance of collision (with the default 8 character length). e.g. 'fubui5e6' Args: length: Length of the random string. chars: The characters to randomly choose from. """ while True: yield "".join([choice(chars) for _ in range(length)])
python
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]: """ A random string. Not unique, but has around 1 in a million chance of collision (with the default 8 character length). e.g. 'fubui5e6' Args: length: Length of the random string. chars: The characters to randomly choose from. """ while True: yield "".join([choice(chars) for _ in range(length)])
[ "def", "random", "(", "length", ":", "int", "=", "8", ",", "chars", ":", "str", "=", "digits", "+", "ascii_lowercase", ")", "->", "Iterator", "[", "str", "]", ":", "while", "True", ":", "yield", "\"\"", ".", "join", "(", "[", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "length", ")", "]", ")" ]
A random string. Not unique, but has around 1 in a million chance of collision (with the default 8 character length). e.g. 'fubui5e6' Args: length: Length of the random string. chars: The characters to randomly choose from.
[ "A", "random", "string", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/id_generators.py#L40-L52
bcb/jsonrpcclient
jsonrpcclient/parse.py
get_response
def get_response(response: Dict[str, Any]) -> JSONRPCResponse: """ Converts a deserialized response into a JSONRPCResponse object. The dictionary be either an error or success response, never a notification. Args: response: Deserialized response dictionary. We can assume the response is valid JSON-RPC here, since it passed the jsonschema validation. """ if "error" in response: return ErrorResponse(**response) return SuccessResponse(**response)
python
def get_response(response: Dict[str, Any]) -> JSONRPCResponse: """ Converts a deserialized response into a JSONRPCResponse object. The dictionary be either an error or success response, never a notification. Args: response: Deserialized response dictionary. We can assume the response is valid JSON-RPC here, since it passed the jsonschema validation. """ if "error" in response: return ErrorResponse(**response) return SuccessResponse(**response)
[ "def", "get_response", "(", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "JSONRPCResponse", ":", "if", "\"error\"", "in", "response", ":", "return", "ErrorResponse", "(", "*", "*", "response", ")", "return", "SuccessResponse", "(", "*", "*", "response", ")" ]
Converts a deserialized response into a JSONRPCResponse object. The dictionary be either an error or success response, never a notification. Args: response: Deserialized response dictionary. We can assume the response is valid JSON-RPC here, since it passed the jsonschema validation.
[ "Converts", "a", "deserialized", "response", "into", "a", "JSONRPCResponse", "object", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/parse.py#L18-L30
bcb/jsonrpcclient
jsonrpcclient/parse.py
parse
def parse( response_text: str, *, batch: bool, validate_against_schema: bool = True ) -> Union[JSONRPCResponse, List[JSONRPCResponse]]: """ Parses response text, returning JSONRPCResponse objects. Args: response_text: JSON-RPC response string. batch: If the response_text is an empty string, this determines how to parse. validate_against_schema: Validate against the json-rpc schema. Returns: Either a JSONRPCResponse, or a list of them. Raises: json.JSONDecodeError: The response was not valid JSON. jsonschema.ValidationError: The response was not a valid JSON-RPC response object. """ # If the response is empty, we can't deserialize it; an empty string is valid # JSON-RPC, but not valid JSON. if not response_text: if batch: # An empty string is a valid response to a batch request, when there were # only notifications in the batch. return [] else: # An empty string is valid response to a Notification request. return NotificationResponse() # If a string, ensure it's json-deserializable deserialized = deserialize(response_text) # Validate the response against the Response schema (raises # jsonschema.ValidationError if invalid) if validate_against_schema: jsonschema.validate(deserialized, schema) # Batch response if isinstance(deserialized, list): return [get_response(r) for r in deserialized if "id" in r] # Single response return get_response(deserialized)
python
def parse( response_text: str, *, batch: bool, validate_against_schema: bool = True ) -> Union[JSONRPCResponse, List[JSONRPCResponse]]: """ Parses response text, returning JSONRPCResponse objects. Args: response_text: JSON-RPC response string. batch: If the response_text is an empty string, this determines how to parse. validate_against_schema: Validate against the json-rpc schema. Returns: Either a JSONRPCResponse, or a list of them. Raises: json.JSONDecodeError: The response was not valid JSON. jsonschema.ValidationError: The response was not a valid JSON-RPC response object. """ # If the response is empty, we can't deserialize it; an empty string is valid # JSON-RPC, but not valid JSON. if not response_text: if batch: # An empty string is a valid response to a batch request, when there were # only notifications in the batch. return [] else: # An empty string is valid response to a Notification request. return NotificationResponse() # If a string, ensure it's json-deserializable deserialized = deserialize(response_text) # Validate the response against the Response schema (raises # jsonschema.ValidationError if invalid) if validate_against_schema: jsonschema.validate(deserialized, schema) # Batch response if isinstance(deserialized, list): return [get_response(r) for r in deserialized if "id" in r] # Single response return get_response(deserialized)
[ "def", "parse", "(", "response_text", ":", "str", ",", "*", ",", "batch", ":", "bool", ",", "validate_against_schema", ":", "bool", "=", "True", ")", "->", "Union", "[", "JSONRPCResponse", ",", "List", "[", "JSONRPCResponse", "]", "]", ":", "# If the response is empty, we can't deserialize it; an empty string is valid", "# JSON-RPC, but not valid JSON.", "if", "not", "response_text", ":", "if", "batch", ":", "# An empty string is a valid response to a batch request, when there were", "# only notifications in the batch.", "return", "[", "]", "else", ":", "# An empty string is valid response to a Notification request.", "return", "NotificationResponse", "(", ")", "# If a string, ensure it's json-deserializable", "deserialized", "=", "deserialize", "(", "response_text", ")", "# Validate the response against the Response schema (raises", "# jsonschema.ValidationError if invalid)", "if", "validate_against_schema", ":", "jsonschema", ".", "validate", "(", "deserialized", ",", "schema", ")", "# Batch response", "if", "isinstance", "(", "deserialized", ",", "list", ")", ":", "return", "[", "get_response", "(", "r", ")", "for", "r", "in", "deserialized", "if", "\"id\"", "in", "r", "]", "# Single response", "return", "get_response", "(", "deserialized", ")" ]
Parses response text, returning JSONRPCResponse objects. Args: response_text: JSON-RPC response string. batch: If the response_text is an empty string, this determines how to parse. validate_against_schema: Validate against the json-rpc schema. Returns: Either a JSONRPCResponse, or a list of them. Raises: json.JSONDecodeError: The response was not valid JSON. jsonschema.ValidationError: The response was not a valid JSON-RPC response object.
[ "Parses", "response", "text", "returning", "JSONRPCResponse", "objects", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/parse.py#L33-L75
bcb/jsonrpcclient
jsonrpcclient/async_client.py
AsyncClient.send
async def send( self, request: Union[str, Dict, List], trim_log_values: bool = False, validate_against_schema: bool = True, **kwargs: Any ) -> Response: """ Async version of Client.send. """ # We need both the serialized and deserialized version of the request if isinstance(request, str): request_text = request request_deserialized = deserialize(request) else: request_text = serialize(request) request_deserialized = request batch = isinstance(request_deserialized, list) response_expected = batch or "id" in request_deserialized self.log_request(request_text, trim_log_values=trim_log_values) response = await self.send_message( request_text, response_expected=response_expected, **kwargs ) self.log_response(response, trim_log_values=trim_log_values) self.validate_response(response) response.data = parse( response.text, batch=batch, validate_against_schema=validate_against_schema ) # If received a single error response, raise if isinstance(response.data, ErrorResponse): raise ReceivedErrorResponseError(response.data) return response
python
async def send( self, request: Union[str, Dict, List], trim_log_values: bool = False, validate_against_schema: bool = True, **kwargs: Any ) -> Response: """ Async version of Client.send. """ # We need both the serialized and deserialized version of the request if isinstance(request, str): request_text = request request_deserialized = deserialize(request) else: request_text = serialize(request) request_deserialized = request batch = isinstance(request_deserialized, list) response_expected = batch or "id" in request_deserialized self.log_request(request_text, trim_log_values=trim_log_values) response = await self.send_message( request_text, response_expected=response_expected, **kwargs ) self.log_response(response, trim_log_values=trim_log_values) self.validate_response(response) response.data = parse( response.text, batch=batch, validate_against_schema=validate_against_schema ) # If received a single error response, raise if isinstance(response.data, ErrorResponse): raise ReceivedErrorResponseError(response.data) return response
[ "async", "def", "send", "(", "self", ",", "request", ":", "Union", "[", "str", ",", "Dict", ",", "List", "]", ",", "trim_log_values", ":", "bool", "=", "False", ",", "validate_against_schema", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "# We need both the serialized and deserialized version of the request", "if", "isinstance", "(", "request", ",", "str", ")", ":", "request_text", "=", "request", "request_deserialized", "=", "deserialize", "(", "request", ")", "else", ":", "request_text", "=", "serialize", "(", "request", ")", "request_deserialized", "=", "request", "batch", "=", "isinstance", "(", "request_deserialized", ",", "list", ")", "response_expected", "=", "batch", "or", "\"id\"", "in", "request_deserialized", "self", ".", "log_request", "(", "request_text", ",", "trim_log_values", "=", "trim_log_values", ")", "response", "=", "await", "self", ".", "send_message", "(", "request_text", ",", "response_expected", "=", "response_expected", ",", "*", "*", "kwargs", ")", "self", ".", "log_response", "(", "response", ",", "trim_log_values", "=", "trim_log_values", ")", "self", ".", "validate_response", "(", "response", ")", "response", ".", "data", "=", "parse", "(", "response", ".", "text", ",", "batch", "=", "batch", ",", "validate_against_schema", "=", "validate_against_schema", ")", "# If received a single error response, raise", "if", "isinstance", "(", "response", ".", "data", ",", "ErrorResponse", ")", ":", "raise", "ReceivedErrorResponseError", "(", "response", ".", "data", ")", "return", "response" ]
Async version of Client.send.
[ "Async", "version", "of", "Client", ".", "send", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/async_client.py#L32-L63
bcb/jsonrpcclient
jsonrpcclient/clients/tornado_client.py
TornadoClient.send_message
async def send_message( # type: ignore self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ headers = dict(self.DEFAULT_HEADERS) headers.update(kwargs.pop("headers", {})) response = await self.client.fetch( self.endpoint, method="POST", body=request, headers=headers, **kwargs ) return Response(response.body.decode(), raw=response)
python
async def send_message( # type: ignore self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ headers = dict(self.DEFAULT_HEADERS) headers.update(kwargs.pop("headers", {})) response = await self.client.fetch( self.endpoint, method="POST", body=request, headers=headers, **kwargs ) return Response(response.body.decode(), raw=response)
[ "async", "def", "send_message", "(", "# type: ignore", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "headers", "=", "dict", "(", "self", ".", "DEFAULT_HEADERS", ")", "headers", ".", "update", "(", "kwargs", ".", "pop", "(", "\"headers\"", ",", "{", "}", ")", ")", "response", "=", "await", "self", ".", "client", ".", "fetch", "(", "self", ".", "endpoint", ",", "method", "=", "\"POST\"", ",", "body", "=", "request", ",", "headers", "=", "headers", ",", "*", "*", "kwargs", ")", "return", "Response", "(", "response", ".", "body", ".", "decode", "(", ")", ",", "raw", "=", "response", ")" ]
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
[ "Transport", "the", "message", "to", "the", "server", "and", "return", "the", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/tornado_client.py#L46-L66
bcb/jsonrpcclient
jsonrpcclient/__main__.py
main
def main( context: click.core.Context, method: str, request_type: str, id: Any, send: str ) -> None: """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if "=" not in a] named = {a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a} # Create the request if request_type == "notify": req = Notification(method, *positional, **named) else: req = Request(method, *positional, request_id=id, **named) # type: ignore # Sending? if send: client = HTTPClient(send) try: response = client.send(req) except JsonRpcClientError as e: click.echo(str(e), err=True) exit_status = 1 else: click.echo(response.text) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
python
def main( context: click.core.Context, method: str, request_type: str, id: Any, send: str ) -> None: """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if "=" not in a] named = {a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a} # Create the request if request_type == "notify": req = Notification(method, *positional, **named) else: req = Request(method, *positional, request_id=id, **named) # type: ignore # Sending? if send: client = HTTPClient(send) try: response = client.send(req) except JsonRpcClientError as e: click.echo(str(e), err=True) exit_status = 1 else: click.echo(response.text) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
[ "def", "main", "(", "context", ":", "click", ".", "core", ".", "Context", ",", "method", ":", "str", ",", "request_type", ":", "str", ",", "id", ":", "Any", ",", "send", ":", "str", ")", "->", "None", ":", "exit_status", "=", "0", "# Extract the jsonrpc arguments", "positional", "=", "[", "a", "for", "a", "in", "context", ".", "args", "if", "\"=\"", "not", "in", "a", "]", "named", "=", "{", "a", ".", "split", "(", "\"=\"", ")", "[", "0", "]", ":", "a", ".", "split", "(", "\"=\"", ")", "[", "1", "]", "for", "a", "in", "context", ".", "args", "if", "\"=\"", "in", "a", "}", "# Create the request", "if", "request_type", "==", "\"notify\"", ":", "req", "=", "Notification", "(", "method", ",", "*", "positional", ",", "*", "*", "named", ")", "else", ":", "req", "=", "Request", "(", "method", ",", "*", "positional", ",", "request_id", "=", "id", ",", "*", "*", "named", ")", "# type: ignore", "# Sending?", "if", "send", ":", "client", "=", "HTTPClient", "(", "send", ")", "try", ":", "response", "=", "client", ".", "send", "(", "req", ")", "except", "JsonRpcClientError", "as", "e", ":", "click", ".", "echo", "(", "str", "(", "e", ")", ",", "err", "=", "True", ")", "exit_status", "=", "1", "else", ":", "click", ".", "echo", "(", "response", ".", "text", ")", "# Otherwise, simply output the JSON-RPC request.", "else", ":", "click", ".", "echo", "(", "str", "(", "req", ")", ")", "sys", ".", "exit", "(", "exit_status", ")" ]
Create a JSON-RPC request.
[ "Create", "a", "JSON", "-", "RPC", "request", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/__main__.py#L40-L68
bcb/jsonrpcclient
jsonrpcclient/log.py
log_
def log_( message: str, logger: logging.Logger, level: str = "info", extra: Optional[Dict] = None, trim: bool = False, ) -> None: """ Log a request or response Args: message: JSON-RPC request or response string. level: Log level. extra: More details to include in the log entry. trim: Abbreviate log messages. """ if extra is None: extra = {} # Clean up the message for logging if message: message = message.replace("\n", "").replace(" ", " ").replace("{ ", "{") if trim: message = _trim_message(message) # Log. getattr(logger, level)(message, extra=extra)
python
def log_( message: str, logger: logging.Logger, level: str = "info", extra: Optional[Dict] = None, trim: bool = False, ) -> None: """ Log a request or response Args: message: JSON-RPC request or response string. level: Log level. extra: More details to include in the log entry. trim: Abbreviate log messages. """ if extra is None: extra = {} # Clean up the message for logging if message: message = message.replace("\n", "").replace(" ", " ").replace("{ ", "{") if trim: message = _trim_message(message) # Log. getattr(logger, level)(message, extra=extra)
[ "def", "log_", "(", "message", ":", "str", ",", "logger", ":", "logging", ".", "Logger", ",", "level", ":", "str", "=", "\"info\"", ",", "extra", ":", "Optional", "[", "Dict", "]", "=", "None", ",", "trim", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "if", "extra", "is", "None", ":", "extra", "=", "{", "}", "# Clean up the message for logging", "if", "message", ":", "message", "=", "message", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", ".", "replace", "(", "\" \"", ",", "\" \"", ")", ".", "replace", "(", "\"{ \"", ",", "\"{\"", ")", "if", "trim", ":", "message", "=", "_trim_message", "(", "message", ")", "# Log.", "getattr", "(", "logger", ",", "level", ")", "(", "message", ",", "extra", "=", "extra", ")" ]
Log a request or response Args: message: JSON-RPC request or response string. level: Log level. extra: More details to include in the log entry. trim: Abbreviate log messages.
[ "Log", "a", "request", "or", "response" ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/log.py#L54-L78
bcb/jsonrpcclient
jsonrpcclient/requests.py
sort_request
def sort_request(request: Dict[str, Any]) -> OrderedDict: """ Sort a JSON-RPC request dict. This has no effect other than making the request nicer to read. >>> json.dumps(sort_request( ... {'id': 2, 'params': [2, 3], 'method': 'add', 'jsonrpc': '2.0'})) '{"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2}' Args: request: JSON-RPC request in dict format. """ sort_order = ["jsonrpc", "method", "params", "id"] return OrderedDict(sorted(request.items(), key=lambda k: sort_order.index(k[0])))
python
def sort_request(request: Dict[str, Any]) -> OrderedDict: """ Sort a JSON-RPC request dict. This has no effect other than making the request nicer to read. >>> json.dumps(sort_request( ... {'id': 2, 'params': [2, 3], 'method': 'add', 'jsonrpc': '2.0'})) '{"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2}' Args: request: JSON-RPC request in dict format. """ sort_order = ["jsonrpc", "method", "params", "id"] return OrderedDict(sorted(request.items(), key=lambda k: sort_order.index(k[0])))
[ "def", "sort_request", "(", "request", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "OrderedDict", ":", "sort_order", "=", "[", "\"jsonrpc\"", ",", "\"method\"", ",", "\"params\"", ",", "\"id\"", "]", "return", "OrderedDict", "(", "sorted", "(", "request", ".", "items", "(", ")", ",", "key", "=", "lambda", "k", ":", "sort_order", ".", "index", "(", "k", "[", "0", "]", ")", ")", ")" ]
Sort a JSON-RPC request dict. This has no effect other than making the request nicer to read. >>> json.dumps(sort_request( ... {'id': 2, 'params': [2, 3], 'method': 'add', 'jsonrpc': '2.0'})) '{"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2}' Args: request: JSON-RPC request in dict format.
[ "Sort", "a", "JSON", "-", "RPC", "request", "dict", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/requests.py#L18-L32
bcb/jsonrpcclient
jsonrpcclient/client.py
Client.basic_logging
def basic_logging(self) -> None: """ Call this on the client object to create log handlers to output request and response messages. """ # Request handler if len(request_log.handlers) == 0: request_handler = logging.StreamHandler() request_handler.setFormatter( logging.Formatter(fmt=self.DEFAULT_REQUEST_LOG_FORMAT) ) request_log.addHandler(request_handler) request_log.setLevel(logging.INFO) # Response handler if len(response_log.handlers) == 0: response_handler = logging.StreamHandler() response_handler.setFormatter( logging.Formatter(fmt=self.DEFAULT_RESPONSE_LOG_FORMAT) ) response_log.addHandler(response_handler) response_log.setLevel(logging.INFO)
python
def basic_logging(self) -> None: """ Call this on the client object to create log handlers to output request and response messages. """ # Request handler if len(request_log.handlers) == 0: request_handler = logging.StreamHandler() request_handler.setFormatter( logging.Formatter(fmt=self.DEFAULT_REQUEST_LOG_FORMAT) ) request_log.addHandler(request_handler) request_log.setLevel(logging.INFO) # Response handler if len(response_log.handlers) == 0: response_handler = logging.StreamHandler() response_handler.setFormatter( logging.Formatter(fmt=self.DEFAULT_RESPONSE_LOG_FORMAT) ) response_log.addHandler(response_handler) response_log.setLevel(logging.INFO)
[ "def", "basic_logging", "(", "self", ")", "->", "None", ":", "# Request handler", "if", "len", "(", "request_log", ".", "handlers", ")", "==", "0", ":", "request_handler", "=", "logging", ".", "StreamHandler", "(", ")", "request_handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "fmt", "=", "self", ".", "DEFAULT_REQUEST_LOG_FORMAT", ")", ")", "request_log", ".", "addHandler", "(", "request_handler", ")", "request_log", ".", "setLevel", "(", "logging", ".", "INFO", ")", "# Response handler", "if", "len", "(", "response_log", ".", "handlers", ")", "==", "0", ":", "response_handler", "=", "logging", ".", "StreamHandler", "(", ")", "response_handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "fmt", "=", "self", ".", "DEFAULT_RESPONSE_LOG_FORMAT", ")", ")", "response_log", ".", "addHandler", "(", "response_handler", ")", "response_log", ".", "setLevel", "(", "logging", ".", "INFO", ")" ]
Call this on the client object to create log handlers to output request and response messages.
[ "Call", "this", "on", "the", "client", "object", "to", "create", "log", "handlers", "to", "output", "request", "and", "response", "messages", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/client.py#L57-L77
bcb/jsonrpcclient
jsonrpcclient/client.py
Client.log_request
def log_request( self, request: str, trim_log_values: bool = False, **kwargs: Any ) -> None: """ Log a request. Args: request: The JSON-RPC request string. trim_log_values: Log an abbreviated version of the request. """ return log_(request, request_log, "info", trim=trim_log_values, **kwargs)
python
def log_request( self, request: str, trim_log_values: bool = False, **kwargs: Any ) -> None: """ Log a request. Args: request: The JSON-RPC request string. trim_log_values: Log an abbreviated version of the request. """ return log_(request, request_log, "info", trim=trim_log_values, **kwargs)
[ "def", "log_request", "(", "self", ",", "request", ":", "str", ",", "trim_log_values", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "return", "log_", "(", "request", ",", "request_log", ",", "\"info\"", ",", "trim", "=", "trim_log_values", ",", "*", "*", "kwargs", ")" ]
Log a request. Args: request: The JSON-RPC request string. trim_log_values: Log an abbreviated version of the request.
[ "Log", "a", "request", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/client.py#L80-L90
bcb/jsonrpcclient
jsonrpcclient/client.py
Client.log_response
def log_response( self, response: Response, trim_log_values: bool = False, **kwargs: Any ) -> None: """ Log a response. Note this is different to log_request, in that it takes a Response object, not a string. Args: response: The Response object to log. Note this is different to log_request which takes a string. trim_log_values: Log an abbreviated version of the response. """ return log_(response.text, response_log, "info", trim=trim_log_values, **kwargs)
python
def log_response( self, response: Response, trim_log_values: bool = False, **kwargs: Any ) -> None: """ Log a response. Note this is different to log_request, in that it takes a Response object, not a string. Args: response: The Response object to log. Note this is different to log_request which takes a string. trim_log_values: Log an abbreviated version of the response. """ return log_(response.text, response_log, "info", trim=trim_log_values, **kwargs)
[ "def", "log_response", "(", "self", ",", "response", ":", "Response", ",", "trim_log_values", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "return", "log_", "(", "response", ".", "text", ",", "response_log", ",", "\"info\"", ",", "trim", "=", "trim_log_values", ",", "*", "*", "kwargs", ")" ]
Log a response. Note this is different to log_request, in that it takes a Response object, not a string. Args: response: The Response object to log. Note this is different to log_request which takes a string. trim_log_values: Log an abbreviated version of the response.
[ "Log", "a", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/client.py#L93-L107
bcb/jsonrpcclient
jsonrpcclient/client.py
Client.notify
def notify( self, method_name: str, *args: Any, trim_log_values: Optional[bool] = None, validate_against_schema: Optional[bool] = None, **kwargs: Any ) -> Response: """ Send a JSON-RPC request, without expecting a response. Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema. """ return self.send( Notification(method_name, *args, **kwargs), trim_log_values=trim_log_values, validate_against_schema=validate_against_schema, )
python
def notify( self, method_name: str, *args: Any, trim_log_values: Optional[bool] = None, validate_against_schema: Optional[bool] = None, **kwargs: Any ) -> Response: """ Send a JSON-RPC request, without expecting a response. Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema. """ return self.send( Notification(method_name, *args, **kwargs), trim_log_values=trim_log_values, validate_against_schema=validate_against_schema, )
[ "def", "notify", "(", "self", ",", "method_name", ":", "str", ",", "*", "args", ":", "Any", ",", "trim_log_values", ":", "Optional", "[", "bool", "]", "=", "None", ",", "validate_against_schema", ":", "Optional", "[", "bool", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "return", "self", ".", "send", "(", "Notification", "(", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ",", "trim_log_values", "=", "trim_log_values", ",", "validate_against_schema", "=", "validate_against_schema", ",", ")" ]
Send a JSON-RPC request, without expecting a response. Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema.
[ "Send", "a", "JSON", "-", "RPC", "request", "without", "expecting", "a", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/client.py#L181-L203
bcb/jsonrpcclient
jsonrpcclient/client.py
Client.request
def request( self, method_name: str, *args: Any, trim_log_values: bool = False, validate_against_schema: bool = True, id_generator: Optional[Iterator] = None, **kwargs: Any ) -> Response: """ Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema. id_generator: Iterable of values to use as the "id" part of the request. """ return self.send( Request(method_name, id_generator=id_generator, *args, **kwargs), trim_log_values=trim_log_values, validate_against_schema=validate_against_schema, )
python
def request( self, method_name: str, *args: Any, trim_log_values: bool = False, validate_against_schema: bool = True, id_generator: Optional[Iterator] = None, **kwargs: Any ) -> Response: """ Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema. id_generator: Iterable of values to use as the "id" part of the request. """ return self.send( Request(method_name, id_generator=id_generator, *args, **kwargs), trim_log_values=trim_log_values, validate_against_schema=validate_against_schema, )
[ "def", "request", "(", "self", ",", "method_name", ":", "str", ",", "*", "args", ":", "Any", ",", "trim_log_values", ":", "bool", "=", "False", ",", "validate_against_schema", ":", "bool", "=", "True", ",", "id_generator", ":", "Optional", "[", "Iterator", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "return", "self", ".", "send", "(", "Request", "(", "method_name", ",", "id_generator", "=", "id_generator", ",", "*", "args", ",", "*", "*", "kwargs", ")", ",", "trim_log_values", "=", "trim_log_values", ",", "validate_against_schema", "=", "validate_against_schema", ",", ")" ]
Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the remote procedure. trim_log_values: Abbreviate the log entries of requests and responses. validate_against_schema: Validate response against the JSON-RPC schema. id_generator: Iterable of values to use as the "id" part of the request.
[ "Send", "a", "request", "by", "passing", "the", "method", "and", "arguments", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/client.py#L206-L233
bcb/jsonrpcclient
jsonrpcclient/clients/socket_client.py
SocketClient.send_message
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ payload = str(request) + self.delimiter self.socket.send(payload.encode(self.encoding)) response = bytes() decoded = None # Receive the response until we find the delimiter. # TODO Do not wait for a response if the message sent is a notification. while True: response += self.socket.recv(1024) decoded = response.decode(self.encoding) if len(decoded) < self.delimiter_length: continue # TODO Check that're not in the middle of the response. elif decoded[-self.delimiter_length :] == self.delimiter: break assert decoded is not None return Response(decoded[: -self.delimiter_length])
python
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ payload = str(request) + self.delimiter self.socket.send(payload.encode(self.encoding)) response = bytes() decoded = None # Receive the response until we find the delimiter. # TODO Do not wait for a response if the message sent is a notification. while True: response += self.socket.recv(1024) decoded = response.decode(self.encoding) if len(decoded) < self.delimiter_length: continue # TODO Check that're not in the middle of the response. elif decoded[-self.delimiter_length :] == self.delimiter: break assert decoded is not None return Response(decoded[: -self.delimiter_length])
[ "def", "send_message", "(", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "payload", "=", "str", "(", "request", ")", "+", "self", ".", "delimiter", "self", ".", "socket", ".", "send", "(", "payload", ".", "encode", "(", "self", ".", "encoding", ")", ")", "response", "=", "bytes", "(", ")", "decoded", "=", "None", "# Receive the response until we find the delimiter.", "# TODO Do not wait for a response if the message sent is a notification.", "while", "True", ":", "response", "+=", "self", ".", "socket", ".", "recv", "(", "1024", ")", "decoded", "=", "response", ".", "decode", "(", "self", ".", "encoding", ")", "if", "len", "(", "decoded", ")", "<", "self", ".", "delimiter_length", ":", "continue", "# TODO Check that're not in the middle of the response.", "elif", "decoded", "[", "-", "self", ".", "delimiter_length", ":", "]", "==", "self", ".", "delimiter", ":", "break", "assert", "decoded", "is", "not", "None", "return", "Response", "(", "decoded", "[", ":", "-", "self", ".", "delimiter_length", "]", ")" ]
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
[ "Transport", "the", "message", "to", "the", "server", "and", "return", "the", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/socket_client.py#L35-L68
bcb/jsonrpcclient
jsonrpcclient/clients/http_client.py
HTTPClient.send_message
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ response = self.session.post(self.endpoint, data=request.encode(), **kwargs) return Response(response.text, raw=response)
python
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ response = self.session.post(self.endpoint, data=request.encode(), **kwargs) return Response(response.text, raw=response)
[ "def", "send_message", "(", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "response", "=", "self", ".", "session", ".", "post", "(", "self", ".", "endpoint", ",", "data", "=", "request", ".", "encode", "(", ")", ",", "*", "*", "kwargs", ")", "return", "Response", "(", "response", ".", "text", ",", "raw", "=", "response", ")" ]
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
[ "Transport", "the", "message", "to", "the", "server", "and", "return", "the", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/http_client.py#L50-L64
bcb/jsonrpcclient
jsonrpcclient/clients/zeromq_client.py
ZeroMQClient.send_message
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ self.socket.send_string(request) return Response(self.socket.recv().decode())
python
def send_message( self, request: str, response_expected: bool, **kwargs: Any ) -> Response: """ Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object. """ self.socket.send_string(request) return Response(self.socket.recv().decode())
[ "def", "send_message", "(", "self", ",", "request", ":", "str", ",", "response_expected", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Response", ":", "self", ".", "socket", ".", "send_string", "(", "request", ")", "return", "Response", "(", "self", ".", "socket", ".", "recv", "(", ")", ".", "decode", "(", ")", ")" ]
Transport the message to the server and return the response. Args: request: The JSON-RPC request string. response_expected: Whether the request expects a response. Returns: A Response object.
[ "Transport", "the", "message", "to", "the", "server", "and", "return", "the", "response", "." ]
train
https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/zeromq_client.py#L28-L42
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.init
def init(self, acct: Account, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the TotalSupply method in ope4 that initialize smart contract parameter. :param acct: an Account class that used to sign the transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('init') tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, acct, payer_acct, gas_limit, gas_price, func) return tx_hash
python
def init(self, acct: Account, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the TotalSupply method in ope4 that initialize smart contract parameter. :param acct: an Account class that used to sign the transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('init') tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, acct, payer_acct, gas_limit, gas_price, func) return tx_hash
[ "def", "init", "(", "self", ",", "acct", ":", "Account", ",", "payer_acct", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "str", ":", "func", "=", "InvokeFunction", "(", "'init'", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_neo_vm_transaction", "(", "self", ".", "__hex_contract_address", ",", "acct", ",", "payer_acct", ",", "gas_limit", ",", "gas_price", ",", "func", ")", "return", "tx_hash" ]
This interface is used to call the TotalSupply method in ope4 that initialize smart contract parameter. :param acct: an Account class that used to sign the transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "call", "the", "TotalSupply", "method", "in", "ope4", "that", "initialize", "smart", "contract", "parameter", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L73-L87
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.get_total_supply
def get_total_supply(self) -> int: """ This interface is used to call the TotalSupply method in ope4 that return the total supply of the oep4 token. :return: the total supply of the oep4 token. """ func = InvokeFunction('totalSupply') response = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: total_supply = ContractDataParser.to_int(response['Result']) except SDKException: total_supply = 0 return total_supply
python
def get_total_supply(self) -> int: """ This interface is used to call the TotalSupply method in ope4 that return the total supply of the oep4 token. :return: the total supply of the oep4 token. """ func = InvokeFunction('totalSupply') response = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: total_supply = ContractDataParser.to_int(response['Result']) except SDKException: total_supply = 0 return total_supply
[ "def", "get_total_supply", "(", "self", ")", "->", "int", ":", "func", "=", "InvokeFunction", "(", "'totalSupply'", ")", "response", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_neo_vm_transaction_pre_exec", "(", "self", ".", "__hex_contract_address", ",", "None", ",", "func", ")", "try", ":", "total_supply", "=", "ContractDataParser", ".", "to_int", "(", "response", "[", "'Result'", "]", ")", "except", "SDKException", ":", "total_supply", "=", "0", "return", "total_supply" ]
This interface is used to call the TotalSupply method in ope4 that return the total supply of the oep4 token. :return: the total supply of the oep4 token.
[ "This", "interface", "is", "used", "to", "call", "the", "TotalSupply", "method", "in", "ope4", "that", "return", "the", "total", "supply", "of", "the", "oep4", "token", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L89-L102
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.balance_of
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address. """ func = InvokeFunction('balanceOf') Oep4.__b58_address_check(b58_address) address = Address.b58decode(b58_address).to_bytes() func.set_params_value(address) result = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: balance = ContractDataParser.to_int(result['Result']) except SDKException: balance = 0 return balance
python
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address. """ func = InvokeFunction('balanceOf') Oep4.__b58_address_check(b58_address) address = Address.b58decode(b58_address).to_bytes() func.set_params_value(address) result = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: balance = ContractDataParser.to_int(result['Result']) except SDKException: balance = 0 return balance
[ "def", "balance_of", "(", "self", ",", "b58_address", ":", "str", ")", "->", "int", ":", "func", "=", "InvokeFunction", "(", "'balanceOf'", ")", "Oep4", ".", "__b58_address_check", "(", "b58_address", ")", "address", "=", "Address", ".", "b58decode", "(", "b58_address", ")", ".", "to_bytes", "(", ")", "func", ".", "set_params_value", "(", "address", ")", "result", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_neo_vm_transaction_pre_exec", "(", "self", ".", "__hex_contract_address", ",", "None", ",", "func", ")", "try", ":", "balance", "=", "ContractDataParser", ".", "to_int", "(", "result", "[", "'Result'", "]", ")", "except", "SDKException", ":", "balance", "=", "0", "return", "balance" ]
This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encode address.
[ "This", "interface", "is", "used", "to", "call", "the", "BalanceOf", "method", "in", "ope4", "that", "query", "the", "ope4", "token", "balance", "of", "the", "given", "base58", "encode", "address", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L104-L121
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.transfer
def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('transfer') if not isinstance(value, int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) if value < 0: raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.')) if not isinstance(from_acct, Account): raise SDKException(ErrorCode.param_err('the data type of from_acct should be Account.')) Oep4.__b58_address_check(b58_to_address) from_address = from_acct.get_address().to_bytes() to_address = Address.b58decode(b58_to_address).to_bytes() func.set_params_value(from_address, to_address, value) tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, from_acct, payer_acct, gas_limit, gas_price, func, False) return tx_hash
python
def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('transfer') if not isinstance(value, int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) if value < 0: raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.')) if not isinstance(from_acct, Account): raise SDKException(ErrorCode.param_err('the data type of from_acct should be Account.')) Oep4.__b58_address_check(b58_to_address) from_address = from_acct.get_address().to_bytes() to_address = Address.b58decode(b58_to_address).to_bytes() func.set_params_value(from_address, to_address, value) tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, from_acct, payer_acct, gas_limit, gas_price, func, False) return tx_hash
[ "def", "transfer", "(", "self", ",", "from_acct", ":", "Account", ",", "b58_to_address", ":", "str", ",", "value", ":", "int", ",", "payer_acct", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "str", ":", "func", "=", "InvokeFunction", "(", "'transfer'", ")", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of value should be int.'", ")", ")", "if", "value", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the value should be equal or great than 0.'", ")", ")", "if", "not", "isinstance", "(", "from_acct", ",", "Account", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of from_acct should be Account.'", ")", ")", "Oep4", ".", "__b58_address_check", "(", "b58_to_address", ")", "from_address", "=", "from_acct", ".", "get_address", "(", ")", ".", "to_bytes", "(", ")", "to_address", "=", "Address", ".", "b58decode", "(", "b58_to_address", ")", ".", "to_bytes", "(", ")", "func", ".", "set_params_value", "(", "from_address", ",", "to_address", ",", "value", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_neo_vm_transaction", "(", "self", ".", "__hex_contract_address", ",", "from_acct", ",", "payer_acct", ",", "gas_limit", ",", "gas_price", ",", "func", ",", "False", ")", "return", "tx_hash" ]
This interface is used to call the Transfer method in ope4 that transfer an amount of tokens from one account to another account. :param from_acct: an Account class that send the oep4 token. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "call", "the", "Transfer", "method", "in", "ope4", "that", "transfer", "an", "amount", "of", "tokens", "from", "one", "account", "to", "another", "account", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L123-L150
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.transfer_multi
def transfer_multi(self, transfer_list: list, payer_acct: Account, signers: list, gas_limit: int, gas_price: int): """ This interface is used to call the TransferMulti method in ope4 that allow transfer amount of token from multiple from-account to multiple to-account multiple times. :param transfer_list: a parameter list with each item contains three sub-items: base58 encode transaction sender address, base58 encode transaction receiver address, amount of token in transaction. :param payer_acct: an Account class that used to pay for the transaction. :param signers: a signer list used to sign this transaction which should contained all sender in args. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('transferMulti') for index, item in enumerate(transfer_list): Oep4.__b58_address_check(item[0]) Oep4.__b58_address_check(item[1]) if not isinstance(item[2], int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) if item[2] < 0: raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.')) from_address_array = Address.b58decode(item[0]).to_bytes() to_address_array = Address.b58decode(item[1]).to_bytes() transfer_list[index] = [from_address_array, to_address_array, item[2]] for item in transfer_list: func.add_params_value(item) params = func.create_invoke_code() unix_time_now = int(time.time()) params.append(0x67) bytearray_contract_address = bytearray.fromhex(self.__hex_contract_address) bytearray_contract_address.reverse() for i in bytearray_contract_address: params.append(i) if len(signers) == 0: raise SDKException(ErrorCode.param_err('payer account is None.')) payer_address = payer_acct.get_address().to_bytes() tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_address, params, bytearray(), []) for signer in signers: tx.add_sign_transaction(signer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
python
def transfer_multi(self, transfer_list: list, payer_acct: Account, signers: list, gas_limit: int, gas_price: int): """ This interface is used to call the TransferMulti method in ope4 that allow transfer amount of token from multiple from-account to multiple to-account multiple times. :param transfer_list: a parameter list with each item contains three sub-items: base58 encode transaction sender address, base58 encode transaction receiver address, amount of token in transaction. :param payer_acct: an Account class that used to pay for the transaction. :param signers: a signer list used to sign this transaction which should contained all sender in args. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('transferMulti') for index, item in enumerate(transfer_list): Oep4.__b58_address_check(item[0]) Oep4.__b58_address_check(item[1]) if not isinstance(item[2], int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) if item[2] < 0: raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.')) from_address_array = Address.b58decode(item[0]).to_bytes() to_address_array = Address.b58decode(item[1]).to_bytes() transfer_list[index] = [from_address_array, to_address_array, item[2]] for item in transfer_list: func.add_params_value(item) params = func.create_invoke_code() unix_time_now = int(time.time()) params.append(0x67) bytearray_contract_address = bytearray.fromhex(self.__hex_contract_address) bytearray_contract_address.reverse() for i in bytearray_contract_address: params.append(i) if len(signers) == 0: raise SDKException(ErrorCode.param_err('payer account is None.')) payer_address = payer_acct.get_address().to_bytes() tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_address, params, bytearray(), []) for signer in signers: tx.add_sign_transaction(signer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
[ "def", "transfer_multi", "(", "self", ",", "transfer_list", ":", "list", ",", "payer_acct", ":", "Account", ",", "signers", ":", "list", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "func", "=", "InvokeFunction", "(", "'transferMulti'", ")", "for", "index", ",", "item", "in", "enumerate", "(", "transfer_list", ")", ":", "Oep4", ".", "__b58_address_check", "(", "item", "[", "0", "]", ")", "Oep4", ".", "__b58_address_check", "(", "item", "[", "1", "]", ")", "if", "not", "isinstance", "(", "item", "[", "2", "]", ",", "int", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of value should be int.'", ")", ")", "if", "item", "[", "2", "]", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the value should be equal or great than 0.'", ")", ")", "from_address_array", "=", "Address", ".", "b58decode", "(", "item", "[", "0", "]", ")", ".", "to_bytes", "(", ")", "to_address_array", "=", "Address", ".", "b58decode", "(", "item", "[", "1", "]", ")", ".", "to_bytes", "(", ")", "transfer_list", "[", "index", "]", "=", "[", "from_address_array", ",", "to_address_array", ",", "item", "[", "2", "]", "]", "for", "item", "in", "transfer_list", ":", "func", ".", "add_params_value", "(", "item", ")", "params", "=", "func", ".", "create_invoke_code", "(", ")", "unix_time_now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "params", ".", "append", "(", "0x67", ")", "bytearray_contract_address", "=", "bytearray", ".", "fromhex", "(", "self", ".", "__hex_contract_address", ")", "bytearray_contract_address", ".", "reverse", "(", ")", "for", "i", "in", "bytearray_contract_address", ":", "params", ".", "append", "(", "i", ")", "if", "len", "(", "signers", ")", "==", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'payer account is None.'", ")", ")", "payer_address", "=", "payer_acct", ".", "get_address", "(", ")", ".", "to_bytes", "(", ")", "tx", "=", "Transaction", "(", "0", ",", "0xd1", ",", "unix_time_now", ",", "gas_price", ",", "gas_limit", ",", "payer_address", ",", "params", ",", "bytearray", "(", ")", ",", "[", "]", ")", "for", "signer", "in", "signers", ":", "tx", ".", "add_sign_transaction", "(", "signer", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")", "return", "tx_hash" ]
This interface is used to call the TransferMulti method in ope4 that allow transfer amount of token from multiple from-account to multiple to-account multiple times. :param transfer_list: a parameter list with each item contains three sub-items: base58 encode transaction sender address, base58 encode transaction receiver address, amount of token in transaction. :param payer_acct: an Account class that used to pay for the transaction. :param signers: a signer list used to sign this transaction which should contained all sender in args. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "call", "the", "TransferMulti", "method", "in", "ope4", "that", "allow", "transfer", "amount", "of", "token", "from", "multiple", "from", "-", "account", "to", "multiple", "to", "-", "account", "multiple", "times", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L175-L218
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.approve
def approve(self, owner_acct: Account, b58_spender_address: str, amount: int, payer_acct: Account, gas_limit: int, gas_price: int): """ This interface is used to call the Approve method in ope4 that allows spender to withdraw a certain amount of oep4 token from owner account multiple times. If this function is called again, it will overwrite the current allowance with new value. :param owner_acct: an Account class that indicate the owner. :param b58_spender_address: a base58 encode address that be allowed to spend the oep4 token in owner's account. :param amount: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('approve') if not isinstance(amount, int): raise SDKException(ErrorCode.param_err('the data type of amount should be int.')) if amount < 0: raise SDKException(ErrorCode.param_err('the amount should be equal or great than 0.')) owner_address = owner_acct.get_address().to_bytes() Oep4.__b58_address_check(b58_spender_address) spender_address = Address.b58decode(b58_spender_address).to_bytes() func.set_params_value(owner_address, spender_address, amount) tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, owner_acct, payer_acct, gas_limit, gas_price, func) return tx_hash
python
def approve(self, owner_acct: Account, b58_spender_address: str, amount: int, payer_acct: Account, gas_limit: int, gas_price: int): """ This interface is used to call the Approve method in ope4 that allows spender to withdraw a certain amount of oep4 token from owner account multiple times. If this function is called again, it will overwrite the current allowance with new value. :param owner_acct: an Account class that indicate the owner. :param b58_spender_address: a base58 encode address that be allowed to spend the oep4 token in owner's account. :param amount: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('approve') if not isinstance(amount, int): raise SDKException(ErrorCode.param_err('the data type of amount should be int.')) if amount < 0: raise SDKException(ErrorCode.param_err('the amount should be equal or great than 0.')) owner_address = owner_acct.get_address().to_bytes() Oep4.__b58_address_check(b58_spender_address) spender_address = Address.b58decode(b58_spender_address).to_bytes() func.set_params_value(owner_address, spender_address, amount) tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, owner_acct, payer_acct, gas_limit, gas_price, func) return tx_hash
[ "def", "approve", "(", "self", ",", "owner_acct", ":", "Account", ",", "b58_spender_address", ":", "str", ",", "amount", ":", "int", ",", "payer_acct", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "func", "=", "InvokeFunction", "(", "'approve'", ")", "if", "not", "isinstance", "(", "amount", ",", "int", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of amount should be int.'", ")", ")", "if", "amount", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the amount should be equal or great than 0.'", ")", ")", "owner_address", "=", "owner_acct", ".", "get_address", "(", ")", ".", "to_bytes", "(", ")", "Oep4", ".", "__b58_address_check", "(", "b58_spender_address", ")", "spender_address", "=", "Address", ".", "b58decode", "(", "b58_spender_address", ")", ".", "to_bytes", "(", ")", "func", ".", "set_params_value", "(", "owner_address", ",", "spender_address", ",", "amount", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_neo_vm_transaction", "(", "self", ".", "__hex_contract_address", ",", "owner_acct", ",", "payer_acct", ",", "gas_limit", ",", "gas_price", ",", "func", ")", "return", "tx_hash" ]
This interface is used to call the Approve method in ope4 that allows spender to withdraw a certain amount of oep4 token from owner account multiple times. If this function is called again, it will overwrite the current allowance with new value. :param owner_acct: an Account class that indicate the owner. :param b58_spender_address: a base58 encode address that be allowed to spend the oep4 token in owner's account. :param amount: an int value that indicate the amount oep4 token that will be transferred in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "call", "the", "Approve", "method", "in", "ope4", "that", "allows", "spender", "to", "withdraw", "a", "certain", "amount", "of", "oep4", "token", "from", "owner", "account", "multiple", "times", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L220-L247
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.allowance
def allowance(self, b58_owner_address: str, b58_spender_address: str): """ This interface is used to call the Allowance method in ope4 that query the amount of spender still allowed to withdraw from owner account. :param b58_owner_address: a base58 encode address that represent owner's account. :param b58_spender_address: a base58 encode address that represent spender's account. :return: the amount of oep4 token that owner allow spender to transfer from the owner account. """ func = InvokeFunction('allowance') Oep4.__b58_address_check(b58_owner_address) owner = Address.b58decode(b58_owner_address).to_bytes() Oep4.__b58_address_check(b58_spender_address) spender = Address.b58decode(b58_spender_address).to_bytes() func.set_params_value(owner, spender) result = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: allowance = ContractDataParser.to_int(result['Result']) except SDKException: allowance = 0 return allowance
python
def allowance(self, b58_owner_address: str, b58_spender_address: str): """ This interface is used to call the Allowance method in ope4 that query the amount of spender still allowed to withdraw from owner account. :param b58_owner_address: a base58 encode address that represent owner's account. :param b58_spender_address: a base58 encode address that represent spender's account. :return: the amount of oep4 token that owner allow spender to transfer from the owner account. """ func = InvokeFunction('allowance') Oep4.__b58_address_check(b58_owner_address) owner = Address.b58decode(b58_owner_address).to_bytes() Oep4.__b58_address_check(b58_spender_address) spender = Address.b58decode(b58_spender_address).to_bytes() func.set_params_value(owner, spender) result = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func) try: allowance = ContractDataParser.to_int(result['Result']) except SDKException: allowance = 0 return allowance
[ "def", "allowance", "(", "self", ",", "b58_owner_address", ":", "str", ",", "b58_spender_address", ":", "str", ")", ":", "func", "=", "InvokeFunction", "(", "'allowance'", ")", "Oep4", ".", "__b58_address_check", "(", "b58_owner_address", ")", "owner", "=", "Address", ".", "b58decode", "(", "b58_owner_address", ")", ".", "to_bytes", "(", ")", "Oep4", ".", "__b58_address_check", "(", "b58_spender_address", ")", "spender", "=", "Address", ".", "b58decode", "(", "b58_spender_address", ")", ".", "to_bytes", "(", ")", "func", ".", "set_params_value", "(", "owner", ",", "spender", ")", "result", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_neo_vm_transaction_pre_exec", "(", "self", ".", "__hex_contract_address", ",", "None", ",", "func", ")", "try", ":", "allowance", "=", "ContractDataParser", ".", "to_int", "(", "result", "[", "'Result'", "]", ")", "except", "SDKException", ":", "allowance", "=", "0", "return", "allowance" ]
This interface is used to call the Allowance method in ope4 that query the amount of spender still allowed to withdraw from owner account. :param b58_owner_address: a base58 encode address that represent owner's account. :param b58_spender_address: a base58 encode address that represent spender's account. :return: the amount of oep4 token that owner allow spender to transfer from the owner account.
[ "This", "interface", "is", "used", "to", "call", "the", "Allowance", "method", "in", "ope4", "that", "query", "the", "amount", "of", "spender", "still", "allowed", "to", "withdraw", "from", "owner", "account", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L249-L269
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/oep4.py
Oep4.transfer_from
def transfer_from(self, spender_acct: Account, b58_from_address: str, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int): """ This interface is used to call the Allowance method in ope4 that allow spender to withdraw amount of oep4 token from from-account to to-account. :param spender_acct: an Account class that actually spend oep4 token. :param b58_from_address: an base58 encode address that actually pay oep4 token for the spender's spending. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: the amount of ope4 token in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('transferFrom') Oep4.__b58_address_check(b58_from_address) Oep4.__b58_address_check(b58_to_address) if not isinstance(spender_acct, Account): raise SDKException(ErrorCode.param_err('the data type of spender_acct should be Account.')) spender_address_array = spender_acct.get_address().to_bytes() from_address_array = Address.b58decode(b58_from_address).to_bytes() to_address_array = Address.b58decode(b58_to_address).to_bytes() if not isinstance(value, int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) func.set_params_value(spender_address_array, from_address_array, to_address_array, value) params = func.create_invoke_code() unix_time_now = int(time.time()) params.append(0x67) bytearray_contract_address = bytearray.fromhex(self.__hex_contract_address) bytearray_contract_address.reverse() for i in bytearray_contract_address: params.append(i) if payer_acct is None: raise SDKException(ErrorCode.param_err('payer account is None.')) payer_address_array = payer_acct.get_address().to_bytes() tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_address_array, params, bytearray(), []) tx.sign_transaction(spender_acct) if spender_acct.get_address_base58() != payer_acct.get_address_base58(): tx.add_sign_transaction(payer_acct) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
python
def transfer_from(self, spender_acct: Account, b58_from_address: str, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int): """ This interface is used to call the Allowance method in ope4 that allow spender to withdraw amount of oep4 token from from-account to to-account. :param spender_acct: an Account class that actually spend oep4 token. :param b58_from_address: an base58 encode address that actually pay oep4 token for the spender's spending. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: the amount of ope4 token in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value. """ func = InvokeFunction('transferFrom') Oep4.__b58_address_check(b58_from_address) Oep4.__b58_address_check(b58_to_address) if not isinstance(spender_acct, Account): raise SDKException(ErrorCode.param_err('the data type of spender_acct should be Account.')) spender_address_array = spender_acct.get_address().to_bytes() from_address_array = Address.b58decode(b58_from_address).to_bytes() to_address_array = Address.b58decode(b58_to_address).to_bytes() if not isinstance(value, int): raise SDKException(ErrorCode.param_err('the data type of value should be int.')) func.set_params_value(spender_address_array, from_address_array, to_address_array, value) params = func.create_invoke_code() unix_time_now = int(time.time()) params.append(0x67) bytearray_contract_address = bytearray.fromhex(self.__hex_contract_address) bytearray_contract_address.reverse() for i in bytearray_contract_address: params.append(i) if payer_acct is None: raise SDKException(ErrorCode.param_err('payer account is None.')) payer_address_array = payer_acct.get_address().to_bytes() tx = Transaction(0, 0xd1, unix_time_now, gas_price, gas_limit, payer_address_array, params, bytearray(), []) tx.sign_transaction(spender_acct) if spender_acct.get_address_base58() != payer_acct.get_address_base58(): tx.add_sign_transaction(payer_acct) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
[ "def", "transfer_from", "(", "self", ",", "spender_acct", ":", "Account", ",", "b58_from_address", ":", "str", ",", "b58_to_address", ":", "str", ",", "value", ":", "int", ",", "payer_acct", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "func", "=", "InvokeFunction", "(", "'transferFrom'", ")", "Oep4", ".", "__b58_address_check", "(", "b58_from_address", ")", "Oep4", ".", "__b58_address_check", "(", "b58_to_address", ")", "if", "not", "isinstance", "(", "spender_acct", ",", "Account", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of spender_acct should be Account.'", ")", ")", "spender_address_array", "=", "spender_acct", ".", "get_address", "(", ")", ".", "to_bytes", "(", ")", "from_address_array", "=", "Address", ".", "b58decode", "(", "b58_from_address", ")", ".", "to_bytes", "(", ")", "to_address_array", "=", "Address", ".", "b58decode", "(", "b58_to_address", ")", ".", "to_bytes", "(", ")", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of value should be int.'", ")", ")", "func", ".", "set_params_value", "(", "spender_address_array", ",", "from_address_array", ",", "to_address_array", ",", "value", ")", "params", "=", "func", ".", "create_invoke_code", "(", ")", "unix_time_now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "params", ".", "append", "(", "0x67", ")", "bytearray_contract_address", "=", "bytearray", ".", "fromhex", "(", "self", ".", "__hex_contract_address", ")", "bytearray_contract_address", ".", "reverse", "(", ")", "for", "i", "in", "bytearray_contract_address", ":", "params", ".", "append", "(", "i", ")", "if", "payer_acct", "is", "None", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'payer account is None.'", ")", ")", "payer_address_array", "=", "payer_acct", ".", "get_address", "(", ")", ".", "to_bytes", "(", ")", "tx", "=", "Transaction", "(", "0", ",", "0xd1", ",", "unix_time_now", ",", "gas_price", ",", "gas_limit", ",", "payer_address_array", ",", "params", ",", "bytearray", "(", ")", ",", "[", "]", ")", "tx", ".", "sign_transaction", "(", "spender_acct", ")", "if", "spender_acct", ".", "get_address_base58", "(", ")", "!=", "payer_acct", ".", "get_address_base58", "(", ")", ":", "tx", ".", "add_sign_transaction", "(", "payer_acct", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")", "return", "tx_hash" ]
This interface is used to call the Allowance method in ope4 that allow spender to withdraw amount of oep4 token from from-account to to-account. :param spender_acct: an Account class that actually spend oep4 token. :param b58_from_address: an base58 encode address that actually pay oep4 token for the spender's spending. :param b58_to_address: a base58 encode address that receive the oep4 token. :param value: the amount of ope4 token in this transaction. :param payer_acct: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: the hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "call", "the", "Allowance", "method", "in", "ope4", "that", "allow", "spender", "to", "withdraw", "amount", "of", "oep4", "token", "from", "from", "-", "account", "to", "to", "-", "account", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L271-L314
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.import_identity
def import_identity(self, label: str, encrypted_pri_key: str, pwd: str, salt: str, b58_address: str) -> Identity: """ This interface is used to import identity by providing encrypted private key, password, salt and base58 encode address which should be correspond to the encrypted private key provided. :param label: a label for identity. :param encrypted_pri_key: an encrypted private key in base64 encoding from. :param pwd: a password which is used to encrypt and decrypt the private key. :param salt: a salt value which will be used in the process of encrypt private key. :param b58_address: a base58 encode address which correspond with the encrypted private key provided. :return: if succeed, an Identity object will be returned. """ scrypt_n = Scrypt().n pri_key = Account.get_gcm_decoded_private_key(encrypted_pri_key, pwd, b58_address, salt, scrypt_n, self.scheme) info = self.__create_identity(label, pwd, salt, pri_key) for identity in self.wallet_in_mem.identities: if identity.ont_id == info.ont_id: return identity raise SDKException(ErrorCode.other_error('Import identity failed.'))
python
def import_identity(self, label: str, encrypted_pri_key: str, pwd: str, salt: str, b58_address: str) -> Identity: """ This interface is used to import identity by providing encrypted private key, password, salt and base58 encode address which should be correspond to the encrypted private key provided. :param label: a label for identity. :param encrypted_pri_key: an encrypted private key in base64 encoding from. :param pwd: a password which is used to encrypt and decrypt the private key. :param salt: a salt value which will be used in the process of encrypt private key. :param b58_address: a base58 encode address which correspond with the encrypted private key provided. :return: if succeed, an Identity object will be returned. """ scrypt_n = Scrypt().n pri_key = Account.get_gcm_decoded_private_key(encrypted_pri_key, pwd, b58_address, salt, scrypt_n, self.scheme) info = self.__create_identity(label, pwd, salt, pri_key) for identity in self.wallet_in_mem.identities: if identity.ont_id == info.ont_id: return identity raise SDKException(ErrorCode.other_error('Import identity failed.'))
[ "def", "import_identity", "(", "self", ",", "label", ":", "str", ",", "encrypted_pri_key", ":", "str", ",", "pwd", ":", "str", ",", "salt", ":", "str", ",", "b58_address", ":", "str", ")", "->", "Identity", ":", "scrypt_n", "=", "Scrypt", "(", ")", ".", "n", "pri_key", "=", "Account", ".", "get_gcm_decoded_private_key", "(", "encrypted_pri_key", ",", "pwd", ",", "b58_address", ",", "salt", ",", "scrypt_n", ",", "self", ".", "scheme", ")", "info", "=", "self", ".", "__create_identity", "(", "label", ",", "pwd", ",", "salt", ",", "pri_key", ")", "for", "identity", "in", "self", ".", "wallet_in_mem", ".", "identities", ":", "if", "identity", ".", "ont_id", "==", "info", ".", "ont_id", ":", "return", "identity", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'Import identity failed.'", ")", ")" ]
This interface is used to import identity by providing encrypted private key, password, salt and base58 encode address which should be correspond to the encrypted private key provided. :param label: a label for identity. :param encrypted_pri_key: an encrypted private key in base64 encoding from. :param pwd: a password which is used to encrypt and decrypt the private key. :param salt: a salt value which will be used in the process of encrypt private key. :param b58_address: a base58 encode address which correspond with the encrypted private key provided. :return: if succeed, an Identity object will be returned.
[ "This", "interface", "is", "used", "to", "import", "identity", "by", "providing", "encrypted", "private", "key", "password", "salt", "and", "base58", "encode", "address", "which", "should", "be", "correspond", "to", "the", "encrypted", "private", "key", "provided", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L140-L158
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.create_identity_from_private_key
def create_identity_from_private_key(self, label: str, pwd: str, private_key: str) -> Identity: """ This interface is used to create identity based on given label, password and private key. :param label: a label for identity. :param pwd: a password which will be used to encrypt and decrypt the private key. :param private_key: a private key in the form of string. :return: if succeed, an Identity object will be returned. """ salt = get_random_hex_str(16) identity = self.__create_identity(label, pwd, salt, private_key) return identity
python
def create_identity_from_private_key(self, label: str, pwd: str, private_key: str) -> Identity: """ This interface is used to create identity based on given label, password and private key. :param label: a label for identity. :param pwd: a password which will be used to encrypt and decrypt the private key. :param private_key: a private key in the form of string. :return: if succeed, an Identity object will be returned. """ salt = get_random_hex_str(16) identity = self.__create_identity(label, pwd, salt, private_key) return identity
[ "def", "create_identity_from_private_key", "(", "self", ",", "label", ":", "str", ",", "pwd", ":", "str", ",", "private_key", ":", "str", ")", "->", "Identity", ":", "salt", "=", "get_random_hex_str", "(", "16", ")", "identity", "=", "self", ".", "__create_identity", "(", "label", ",", "pwd", ",", "salt", ",", "private_key", ")", "return", "identity" ]
This interface is used to create identity based on given label, password and private key. :param label: a label for identity. :param pwd: a password which will be used to encrypt and decrypt the private key. :param private_key: a private key in the form of string. :return: if succeed, an Identity object will be returned.
[ "This", "interface", "is", "used", "to", "create", "identity", "based", "on", "given", "label", "password", "and", "private", "key", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L178-L189
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.create_account
def create_account(self, pwd: str, label: str = '') -> Account: """ This interface is used to create account based on given password and label. :param label: a label for account. :param pwd: a password which will be used to encrypt and decrypt the private key :return: if succeed, return an data structure which contain the information of a wallet account. """ pri_key = get_random_hex_str(64) salt = get_random_hex_str(16) if len(label) == 0 or label is None: label = uuid.uuid4().hex[0:8] acct = self.__create_account(label, pwd, salt, pri_key, True) return self.get_account_by_b58_address(acct.get_address_base58(), pwd)
python
def create_account(self, pwd: str, label: str = '') -> Account: """ This interface is used to create account based on given password and label. :param label: a label for account. :param pwd: a password which will be used to encrypt and decrypt the private key :return: if succeed, return an data structure which contain the information of a wallet account. """ pri_key = get_random_hex_str(64) salt = get_random_hex_str(16) if len(label) == 0 or label is None: label = uuid.uuid4().hex[0:8] acct = self.__create_account(label, pwd, salt, pri_key, True) return self.get_account_by_b58_address(acct.get_address_base58(), pwd)
[ "def", "create_account", "(", "self", ",", "pwd", ":", "str", ",", "label", ":", "str", "=", "''", ")", "->", "Account", ":", "pri_key", "=", "get_random_hex_str", "(", "64", ")", "salt", "=", "get_random_hex_str", "(", "16", ")", "if", "len", "(", "label", ")", "==", "0", "or", "label", "is", "None", ":", "label", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "[", "0", ":", "8", "]", "acct", "=", "self", ".", "__create_account", "(", "label", ",", "pwd", ",", "salt", ",", "pri_key", ",", "True", ")", "return", "self", ".", "get_account_by_b58_address", "(", "acct", ".", "get_address_base58", "(", ")", ",", "pwd", ")" ]
This interface is used to create account based on given password and label. :param label: a label for account. :param pwd: a password which will be used to encrypt and decrypt the private key :return: if succeed, return an data structure which contain the information of a wallet account.
[ "This", "interface", "is", "used", "to", "create", "account", "based", "on", "given", "password", "and", "label", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L191-L204
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.import_account
def import_account(self, label: str, encrypted_pri_key: str, pwd: str, b58_address: str, b64_salt: str, n: int = 16384) -> AccountData: """ This interface is used to import account by providing account data. :param label: str, wallet label :param encrypted_pri_key: str, an encrypted private key in base64 encoding from :param pwd: str, a password which is used to encrypt and decrypt the private key :param b58_address: str, a base58 encode wallet address value :param b64_salt: str, a base64 encode salt value which is used in the encryption of private key :param n: int, CPU/Memory cost parameter. It must be a power of 2 and less than :math:`2^{32}` :return: if succeed, return an data structure which contain the information of a wallet account. if failed, return a None object. """ salt = base64.b64decode(b64_salt.encode('ascii')).decode('latin-1') private_key = Account.get_gcm_decoded_private_key(encrypted_pri_key, pwd, b58_address, salt, n, self.scheme) acct_info = self.create_account_info(label, pwd, salt, private_key) for acct in self.wallet_in_mem.accounts: if not isinstance(acct, AccountData): raise SDKException(ErrorCode.other_error('Invalid account data in memory.')) if acct_info.address_base58 == acct.b58_address: return acct raise SDKException(ErrorCode.other_error('Import account failed.'))
python
def import_account(self, label: str, encrypted_pri_key: str, pwd: str, b58_address: str, b64_salt: str, n: int = 16384) -> AccountData: """ This interface is used to import account by providing account data. :param label: str, wallet label :param encrypted_pri_key: str, an encrypted private key in base64 encoding from :param pwd: str, a password which is used to encrypt and decrypt the private key :param b58_address: str, a base58 encode wallet address value :param b64_salt: str, a base64 encode salt value which is used in the encryption of private key :param n: int, CPU/Memory cost parameter. It must be a power of 2 and less than :math:`2^{32}` :return: if succeed, return an data structure which contain the information of a wallet account. if failed, return a None object. """ salt = base64.b64decode(b64_salt.encode('ascii')).decode('latin-1') private_key = Account.get_gcm_decoded_private_key(encrypted_pri_key, pwd, b58_address, salt, n, self.scheme) acct_info = self.create_account_info(label, pwd, salt, private_key) for acct in self.wallet_in_mem.accounts: if not isinstance(acct, AccountData): raise SDKException(ErrorCode.other_error('Invalid account data in memory.')) if acct_info.address_base58 == acct.b58_address: return acct raise SDKException(ErrorCode.other_error('Import account failed.'))
[ "def", "import_account", "(", "self", ",", "label", ":", "str", ",", "encrypted_pri_key", ":", "str", ",", "pwd", ":", "str", ",", "b58_address", ":", "str", ",", "b64_salt", ":", "str", ",", "n", ":", "int", "=", "16384", ")", "->", "AccountData", ":", "salt", "=", "base64", ".", "b64decode", "(", "b64_salt", ".", "encode", "(", "'ascii'", ")", ")", ".", "decode", "(", "'latin-1'", ")", "private_key", "=", "Account", ".", "get_gcm_decoded_private_key", "(", "encrypted_pri_key", ",", "pwd", ",", "b58_address", ",", "salt", ",", "n", ",", "self", ".", "scheme", ")", "acct_info", "=", "self", ".", "create_account_info", "(", "label", ",", "pwd", ",", "salt", ",", "private_key", ")", "for", "acct", "in", "self", ".", "wallet_in_mem", ".", "accounts", ":", "if", "not", "isinstance", "(", "acct", ",", "AccountData", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'Invalid account data in memory.'", ")", ")", "if", "acct_info", ".", "address_base58", "==", "acct", ".", "b58_address", ":", "return", "acct", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'Import account failed.'", ")", ")" ]
This interface is used to import account by providing account data. :param label: str, wallet label :param encrypted_pri_key: str, an encrypted private key in base64 encoding from :param pwd: str, a password which is used to encrypt and decrypt the private key :param b58_address: str, a base58 encode wallet address value :param b64_salt: str, a base64 encode salt value which is used in the encryption of private key :param n: int, CPU/Memory cost parameter. It must be a power of 2 and less than :math:`2^{32}` :return: if succeed, return an data structure which contain the information of a wallet account. if failed, return a None object.
[ "This", "interface", "is", "used", "to", "import", "account", "by", "providing", "account", "data", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L289-L312
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.create_account_from_private_key
def create_account_from_private_key(self, password: str, private_key: str, label: str = '') -> AccountData: """ This interface is used to create account by providing an encrypted private key and it's decrypt password. :param label: a label for account. :param password: a password which is used to decrypt the encrypted private key. :param private_key: a private key in the form of string. :return: if succeed, return an AccountData object. if failed, return a None object. """ salt = get_random_hex_str(16) if len(label) == 0 or label is None: label = uuid.uuid4().hex[0:8] info = self.create_account_info(label, password, salt, private_key) for acct in self.wallet_in_mem.accounts: if info.address_base58 == acct.b58_address: return acct raise SDKException(ErrorCode.other_error(f'Create account from key {private_key} failed.'))
python
def create_account_from_private_key(self, password: str, private_key: str, label: str = '') -> AccountData: """ This interface is used to create account by providing an encrypted private key and it's decrypt password. :param label: a label for account. :param password: a password which is used to decrypt the encrypted private key. :param private_key: a private key in the form of string. :return: if succeed, return an AccountData object. if failed, return a None object. """ salt = get_random_hex_str(16) if len(label) == 0 or label is None: label = uuid.uuid4().hex[0:8] info = self.create_account_info(label, password, salt, private_key) for acct in self.wallet_in_mem.accounts: if info.address_base58 == acct.b58_address: return acct raise SDKException(ErrorCode.other_error(f'Create account from key {private_key} failed.'))
[ "def", "create_account_from_private_key", "(", "self", ",", "password", ":", "str", ",", "private_key", ":", "str", ",", "label", ":", "str", "=", "''", ")", "->", "AccountData", ":", "salt", "=", "get_random_hex_str", "(", "16", ")", "if", "len", "(", "label", ")", "==", "0", "or", "label", "is", "None", ":", "label", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "[", "0", ":", "8", "]", "info", "=", "self", ".", "create_account_info", "(", "label", ",", "password", ",", "salt", ",", "private_key", ")", "for", "acct", "in", "self", ".", "wallet_in_mem", ".", "accounts", ":", "if", "info", ".", "address_base58", "==", "acct", ".", "b58_address", ":", "return", "acct", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "f'Create account from key {private_key} failed.'", ")", ")" ]
This interface is used to create account by providing an encrypted private key and it's decrypt password. :param label: a label for account. :param password: a password which is used to decrypt the encrypted private key. :param private_key: a private key in the form of string. :return: if succeed, return an AccountData object. if failed, return a None object.
[ "This", "interface", "is", "used", "to", "create", "account", "by", "providing", "an", "encrypted", "private", "key", "and", "it", "s", "decrypt", "password", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L324-L341
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.get_account_by_ont_id
def get_account_by_ont_id(self, ont_id: str, password: str) -> Account: """ :param ont_id: OntId. :param password: a password which is used to decrypt the encrypted private key. :return: """ WalletManager.__check_ont_id(ont_id) for identity in self.wallet_in_mem.identities: if identity.ont_id == ont_id: addr = identity.ont_id.replace(DID_ONT, "") key = identity.controls[0].key salt = base64.b64decode(identity.controls[0].salt) n = self.wallet_in_mem.scrypt.n private_key = Account.get_gcm_decoded_private_key(key, password, addr, salt, n, self.scheme) return Account(private_key, self.scheme) raise SDKException(ErrorCode.other_error(f'Get account {ont_id} failed.'))
python
def get_account_by_ont_id(self, ont_id: str, password: str) -> Account: """ :param ont_id: OntId. :param password: a password which is used to decrypt the encrypted private key. :return: """ WalletManager.__check_ont_id(ont_id) for identity in self.wallet_in_mem.identities: if identity.ont_id == ont_id: addr = identity.ont_id.replace(DID_ONT, "") key = identity.controls[0].key salt = base64.b64decode(identity.controls[0].salt) n = self.wallet_in_mem.scrypt.n private_key = Account.get_gcm_decoded_private_key(key, password, addr, salt, n, self.scheme) return Account(private_key, self.scheme) raise SDKException(ErrorCode.other_error(f'Get account {ont_id} failed.'))
[ "def", "get_account_by_ont_id", "(", "self", ",", "ont_id", ":", "str", ",", "password", ":", "str", ")", "->", "Account", ":", "WalletManager", ".", "__check_ont_id", "(", "ont_id", ")", "for", "identity", "in", "self", ".", "wallet_in_mem", ".", "identities", ":", "if", "identity", ".", "ont_id", "==", "ont_id", ":", "addr", "=", "identity", ".", "ont_id", ".", "replace", "(", "DID_ONT", ",", "\"\"", ")", "key", "=", "identity", ".", "controls", "[", "0", "]", ".", "key", "salt", "=", "base64", ".", "b64decode", "(", "identity", ".", "controls", "[", "0", "]", ".", "salt", ")", "n", "=", "self", ".", "wallet_in_mem", ".", "scrypt", ".", "n", "private_key", "=", "Account", ".", "get_gcm_decoded_private_key", "(", "key", ",", "password", ",", "addr", ",", "salt", ",", "n", ",", "self", ".", "scheme", ")", "return", "Account", "(", "private_key", ",", "self", ".", "scheme", ")", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "f'Get account {ont_id} failed.'", ")", ")" ]
:param ont_id: OntId. :param password: a password which is used to decrypt the encrypted private key. :return:
[ ":", "param", "ont_id", ":", "OntId", ".", ":", "param", "password", ":", "a", "password", "which", "is", "used", "to", "decrypt", "the", "encrypted", "private", "key", ".", ":", "return", ":" ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L351-L366
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.get_account_by_b58_address
def get_account_by_b58_address(self, b58_address: str, password: str) -> Account: """ :param b58_address: a base58 encode address. :param password: a password which is used to decrypt the encrypted private key. :return: """ acct = self.get_account_data_by_b58_address(b58_address) n = self.wallet_in_mem.scrypt.n salt = base64.b64decode(acct.salt) private_key = Account.get_gcm_decoded_private_key(acct.key, password, b58_address, salt, n, self.scheme) return Account(private_key, self.scheme)
python
def get_account_by_b58_address(self, b58_address: str, password: str) -> Account: """ :param b58_address: a base58 encode address. :param password: a password which is used to decrypt the encrypted private key. :return: """ acct = self.get_account_data_by_b58_address(b58_address) n = self.wallet_in_mem.scrypt.n salt = base64.b64decode(acct.salt) private_key = Account.get_gcm_decoded_private_key(acct.key, password, b58_address, salt, n, self.scheme) return Account(private_key, self.scheme)
[ "def", "get_account_by_b58_address", "(", "self", ",", "b58_address", ":", "str", ",", "password", ":", "str", ")", "->", "Account", ":", "acct", "=", "self", ".", "get_account_data_by_b58_address", "(", "b58_address", ")", "n", "=", "self", ".", "wallet_in_mem", ".", "scrypt", ".", "n", "salt", "=", "base64", ".", "b64decode", "(", "acct", ".", "salt", ")", "private_key", "=", "Account", ".", "get_gcm_decoded_private_key", "(", "acct", ".", "key", ",", "password", ",", "b58_address", ",", "salt", ",", "n", ",", "self", ".", "scheme", ")", "return", "Account", "(", "private_key", ",", "self", ".", "scheme", ")" ]
:param b58_address: a base58 encode address. :param password: a password which is used to decrypt the encrypted private key. :return:
[ ":", "param", "b58_address", ":", "a", "base58", "encode", "address", ".", ":", "param", "password", ":", "a", "password", "which", "is", "used", "to", "decrypt", "the", "encrypted", "private", "key", ".", ":", "return", ":" ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L422-L432
ontio/ontology-python-sdk
ontology/wallet/wallet_manager.py
WalletManager.get_default_account_data
def get_default_account_data(self) -> AccountData: """ This interface is used to get the default account in WalletManager. :return: an AccountData object that contain all the information of a default account. """ for acct in self.wallet_in_mem.accounts: if not isinstance(acct, AccountData): raise SDKException(ErrorCode.other_error('Invalid account data in memory.')) if acct.is_default: return acct raise SDKException(ErrorCode.get_default_account_err)
python
def get_default_account_data(self) -> AccountData: """ This interface is used to get the default account in WalletManager. :return: an AccountData object that contain all the information of a default account. """ for acct in self.wallet_in_mem.accounts: if not isinstance(acct, AccountData): raise SDKException(ErrorCode.other_error('Invalid account data in memory.')) if acct.is_default: return acct raise SDKException(ErrorCode.get_default_account_err)
[ "def", "get_default_account_data", "(", "self", ")", "->", "AccountData", ":", "for", "acct", "in", "self", ".", "wallet_in_mem", ".", "accounts", ":", "if", "not", "isinstance", "(", "acct", ",", "AccountData", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'Invalid account data in memory.'", ")", ")", "if", "acct", ".", "is_default", ":", "return", "acct", "raise", "SDKException", "(", "ErrorCode", ".", "get_default_account_err", ")" ]
This interface is used to get the default account in WalletManager. :return: an AccountData object that contain all the information of a default account.
[ "This", "interface", "is", "used", "to", "get", "the", "default", "account", "in", "WalletManager", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet_manager.py#L440-L451
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/abi/abi_info.py
AbiInfo.get_function
def get_function(self, name: str) -> AbiFunction or None: """ This interface is used to get an AbiFunction object from AbiInfo object by given function name. :param name: the function name in abi file :return: if succeed, an AbiFunction will constructed based on given function name """ for func in self.functions: if func['name'] == name: return AbiFunction(func['name'], func['parameters'], func.get('returntype', '')) return None
python
def get_function(self, name: str) -> AbiFunction or None: """ This interface is used to get an AbiFunction object from AbiInfo object by given function name. :param name: the function name in abi file :return: if succeed, an AbiFunction will constructed based on given function name """ for func in self.functions: if func['name'] == name: return AbiFunction(func['name'], func['parameters'], func.get('returntype', '')) return None
[ "def", "get_function", "(", "self", ",", "name", ":", "str", ")", "->", "AbiFunction", "or", "None", ":", "for", "func", "in", "self", ".", "functions", ":", "if", "func", "[", "'name'", "]", "==", "name", ":", "return", "AbiFunction", "(", "func", "[", "'name'", "]", ",", "func", "[", "'parameters'", "]", ",", "func", ".", "get", "(", "'returntype'", ",", "''", ")", ")", "return", "None" ]
This interface is used to get an AbiFunction object from AbiInfo object by given function name. :param name: the function name in abi file :return: if succeed, an AbiFunction will constructed based on given function name
[ "This", "interface", "is", "used", "to", "get", "an", "AbiFunction", "object", "from", "AbiInfo", "object", "by", "given", "function", "name", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/abi/abi_info.py#L17-L27
ontio/ontology-python-sdk
ontology/crypto/ecies.py
ECIES.__uncompress_public_key
def __uncompress_public_key(public_key: bytes) -> bytes: """ Uncompress the compressed public key. :param public_key: compressed public key :return: uncompressed public key """ is_even = public_key.startswith(b'\x02') x = string_to_number(public_key[1:]) curve = NIST256p.curve order = NIST256p.order p = curve.p() alpha = (pow(x, 3, p) + (curve.a() * x) + curve.b()) % p beta = square_root_mod_prime(alpha, p) if is_even == bool(beta & 1): y = p - beta else: y = beta point = Point(curve, x, y, order) return b''.join([number_to_string(point.x(), order), number_to_string(point.y(), order)])
python
def __uncompress_public_key(public_key: bytes) -> bytes: """ Uncompress the compressed public key. :param public_key: compressed public key :return: uncompressed public key """ is_even = public_key.startswith(b'\x02') x = string_to_number(public_key[1:]) curve = NIST256p.curve order = NIST256p.order p = curve.p() alpha = (pow(x, 3, p) + (curve.a() * x) + curve.b()) % p beta = square_root_mod_prime(alpha, p) if is_even == bool(beta & 1): y = p - beta else: y = beta point = Point(curve, x, y, order) return b''.join([number_to_string(point.x(), order), number_to_string(point.y(), order)])
[ "def", "__uncompress_public_key", "(", "public_key", ":", "bytes", ")", "->", "bytes", ":", "is_even", "=", "public_key", ".", "startswith", "(", "b'\\x02'", ")", "x", "=", "string_to_number", "(", "public_key", "[", "1", ":", "]", ")", "curve", "=", "NIST256p", ".", "curve", "order", "=", "NIST256p", ".", "order", "p", "=", "curve", ".", "p", "(", ")", "alpha", "=", "(", "pow", "(", "x", ",", "3", ",", "p", ")", "+", "(", "curve", ".", "a", "(", ")", "*", "x", ")", "+", "curve", ".", "b", "(", ")", ")", "%", "p", "beta", "=", "square_root_mod_prime", "(", "alpha", ",", "p", ")", "if", "is_even", "==", "bool", "(", "beta", "&", "1", ")", ":", "y", "=", "p", "-", "beta", "else", ":", "y", "=", "beta", "point", "=", "Point", "(", "curve", ",", "x", ",", "y", ",", "order", ")", "return", "b''", ".", "join", "(", "[", "number_to_string", "(", "point", ".", "x", "(", ")", ",", "order", ")", ",", "number_to_string", "(", "point", ".", "y", "(", ")", ",", "order", ")", "]", ")" ]
Uncompress the compressed public key. :param public_key: compressed public key :return: uncompressed public key
[ "Uncompress", "the", "compressed", "public", "key", ".", ":", "param", "public_key", ":", "compressed", "public", "key", ":", "return", ":", "uncompressed", "public", "key" ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/crypto/ecies.py#L64-L83
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_version
def get_version(self, is_full: bool = False) -> dict or str: """ This interface is used to get the version information of the connected node in current network. Return: the version information of the connected node. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_VERSION) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_version(self, is_full: bool = False) -> dict or str: """ This interface is used to get the version information of the connected node in current network. Return: the version information of the connected node. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_VERSION) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_version", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", "or", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_VERSION", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the version information of the connected node in current network. Return: the version information of the connected node.
[ "This", "interface", "is", "used", "to", "get", "the", "version", "information", "of", "the", "connected", "node", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L152-L163
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_connection_count
def get_connection_count(self, is_full: bool = False) -> int: """ This interface is used to get the current number of connections for the node in current network. Return: the number of connections. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_NODE_COUNT) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_connection_count(self, is_full: bool = False) -> int: """ This interface is used to get the current number of connections for the node in current network. Return: the number of connections. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_NODE_COUNT) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_connection_count", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "int", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_NODE_COUNT", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the current number of connections for the node in current network. Return: the number of connections.
[ "This", "interface", "is", "used", "to", "get", "the", "current", "number", "of", "connections", "for", "the", "node", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L165-L176
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_gas_price
def get_gas_price(self, is_full: bool = False) -> int or dict: """ This interface is used to get the gas price in current network. Return: the value of gas price. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_GAS_PRICE) response = self.__post(self.__url, payload) if is_full: return response return response['result']['gasprice']
python
def get_gas_price(self, is_full: bool = False) -> int or dict: """ This interface is used to get the gas price in current network. Return: the value of gas price. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_GAS_PRICE) response = self.__post(self.__url, payload) if is_full: return response return response['result']['gasprice']
[ "def", "get_gas_price", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "int", "or", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_GAS_PRICE", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]", "[", "'gasprice'", "]" ]
This interface is used to get the gas price in current network. Return: the value of gas price.
[ "This", "interface", "is", "used", "to", "get", "the", "gas", "price", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L178-L189
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_network_id
def get_network_id(self, is_full: bool = False) -> int: """ This interface is used to get the network id of current network. Return: the network id of current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_NETWORK_ID) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_network_id(self, is_full: bool = False) -> int: """ This interface is used to get the network id of current network. Return: the network id of current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_NETWORK_ID) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_network_id", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "int", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_NETWORK_ID", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the network id of current network. Return: the network id of current network.
[ "This", "interface", "is", "used", "to", "get", "the", "network", "id", "of", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L191-L203
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_block_by_hash
def get_block_by_hash(self, block_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the hexadecimal hash value of specified block height in current network. :param block_hash: a hexadecimal value of block hash. :param is_full: :return: the block information of the specified block hash. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK, [block_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_block_by_hash(self, block_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the hexadecimal hash value of specified block height in current network. :param block_hash: a hexadecimal value of block hash. :param is_full: :return: the block information of the specified block hash. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK, [block_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_block_by_hash", "(", "self", ",", "block_hash", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_BLOCK", ",", "[", "block_hash", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the hexadecimal hash value of specified block height in current network. :param block_hash: a hexadecimal value of block hash. :param is_full: :return: the block information of the specified block hash.
[ "This", "interface", "is", "used", "to", "get", "the", "hexadecimal", "hash", "value", "of", "specified", "block", "height", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L205-L217
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_block_by_height
def get_block_by_height(self, height: int, is_full: bool = False) -> dict: """ This interface is used to get the block information by block height in current network. Return: the decimal total number of blocks in current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK, [height, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_block_by_height(self, height: int, is_full: bool = False) -> dict: """ This interface is used to get the block information by block height in current network. Return: the decimal total number of blocks in current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK, [height, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_block_by_height", "(", "self", ",", "height", ":", "int", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_BLOCK", ",", "[", "height", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the block information by block height in current network. Return: the decimal total number of blocks in current network.
[ "This", "interface", "is", "used", "to", "get", "the", "block", "information", "by", "block", "height", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L219-L230
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_block_count
def get_block_count(self, is_full: bool = False) -> int or dict: """ This interface is used to get the decimal block number in current network. Return: the decimal total number of blocks in current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK_COUNT) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_block_count(self, is_full: bool = False) -> int or dict: """ This interface is used to get the decimal block number in current network. Return: the decimal total number of blocks in current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK_COUNT) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_block_count", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "int", "or", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_BLOCK_COUNT", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the decimal block number in current network. Return: the decimal total number of blocks in current network.
[ "This", "interface", "is", "used", "to", "get", "the", "decimal", "block", "number", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L232-L243
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_block_height
def get_block_height(self, is_full: bool = False) -> int or dict: """ This interface is used to get the decimal block height in current network. Return: the decimal total height of blocks in current network. """ response = self.get_block_count(is_full=True) response['result'] -= 1 if is_full: return response return response['result']
python
def get_block_height(self, is_full: bool = False) -> int or dict: """ This interface is used to get the decimal block height in current network. Return: the decimal total height of blocks in current network. """ response = self.get_block_count(is_full=True) response['result'] -= 1 if is_full: return response return response['result']
[ "def", "get_block_height", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "int", "or", "dict", ":", "response", "=", "self", ".", "get_block_count", "(", "is_full", "=", "True", ")", "response", "[", "'result'", "]", "-=", "1", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the decimal block height in current network. Return: the decimal total height of blocks in current network.
[ "This", "interface", "is", "used", "to", "get", "the", "decimal", "block", "height", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L245-L256
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_current_block_hash
def get_current_block_hash(self, is_full: bool = False) -> str: """ This interface is used to get the hexadecimal hash value of the highest block in current network. Return: the hexadecimal hash value of the highest block in current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_CURRENT_BLOCK_HASH) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_current_block_hash(self, is_full: bool = False) -> str: """ This interface is used to get the hexadecimal hash value of the highest block in current network. Return: the hexadecimal hash value of the highest block in current network. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_CURRENT_BLOCK_HASH) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_current_block_hash", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_CURRENT_BLOCK_HASH", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the hexadecimal hash value of the highest block in current network. Return: the hexadecimal hash value of the highest block in current network.
[ "This", "interface", "is", "used", "to", "get", "the", "hexadecimal", "hash", "value", "of", "the", "highest", "block", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L272-L283
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_block_hash_by_height
def get_block_hash_by_height(self, height: int, is_full: bool = False) -> str: """ This interface is used to get the hexadecimal hash value of specified block height in current network. :param height: a decimal block height value. :param is_full: :return: the hexadecimal hash value of the specified block height. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK_HASH, [height, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_block_hash_by_height(self, height: int, is_full: bool = False) -> str: """ This interface is used to get the hexadecimal hash value of specified block height in current network. :param height: a decimal block height value. :param is_full: :return: the hexadecimal hash value of the specified block height. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BLOCK_HASH, [height, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_block_hash_by_height", "(", "self", ",", "height", ":", "int", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_BLOCK_HASH", ",", "[", "height", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the hexadecimal hash value of specified block height in current network. :param height: a decimal block height value. :param is_full: :return: the hexadecimal hash value of the specified block height.
[ "This", "interface", "is", "used", "to", "get", "the", "hexadecimal", "hash", "value", "of", "specified", "block", "height", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L285-L297
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_balance
def get_balance(self, b58_address: str, is_full: bool = False) -> dict: """ This interface is used to get the account balance of specified base58 encoded address in current network. :param b58_address: a base58 encoded account address. :param is_full: :return: the value of account balance in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BALANCE, [b58_address, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_balance(self, b58_address: str, is_full: bool = False) -> dict: """ This interface is used to get the account balance of specified base58 encoded address in current network. :param b58_address: a base58 encoded account address. :param is_full: :return: the value of account balance in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_BALANCE, [b58_address, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_balance", "(", "self", ",", "b58_address", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_BALANCE", ",", "[", "b58_address", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the account balance of specified base58 encoded address in current network. :param b58_address: a base58 encoded account address. :param is_full: :return: the value of account balance in dictionary form.
[ "This", "interface", "is", "used", "to", "get", "the", "account", "balance", "of", "specified", "base58", "encoded", "address", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L299-L311
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_allowance
def get_allowance(self, asset_name: str, from_address: str, to_address: str, is_full: bool = False) -> str: """ This interface is used to get the the allowance from transfer-from account to transfer-to account in current network. :param asset_name: :param from_address: a base58 encoded account address. :param to_address: a base58 encoded account address. :param is_full: :return: the information of allowance in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_ALLOWANCE, [asset_name, from_address, to_address]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_allowance(self, asset_name: str, from_address: str, to_address: str, is_full: bool = False) -> str: """ This interface is used to get the the allowance from transfer-from account to transfer-to account in current network. :param asset_name: :param from_address: a base58 encoded account address. :param to_address: a base58 encoded account address. :param is_full: :return: the information of allowance in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_ALLOWANCE, [asset_name, from_address, to_address]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_allowance", "(", "self", ",", "asset_name", ":", "str", ",", "from_address", ":", "str", ",", "to_address", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_ALLOWANCE", ",", "[", "asset_name", ",", "from_address", ",", "to_address", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the the allowance from transfer-from account to transfer-to account in current network. :param asset_name: :param from_address: a base58 encoded account address. :param to_address: a base58 encoded account address. :param is_full: :return: the information of allowance in dictionary form.
[ "This", "interface", "is", "used", "to", "get", "the", "the", "allowance", "from", "transfer", "-", "from", "account", "to", "transfer", "-", "to", "account", "in", "current", "network", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L320-L335
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_storage
def get_storage(self, hex_contract_address: str, hex_key: str, is_full: bool = False) -> str: """ This interface is used to get the corresponding stored value based on hexadecimal contract address and stored key. :param hex_contract_address: hexadecimal contract address. :param hex_key: a hexadecimal stored key. :param is_full: :return: the information of contract storage. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_STORAGE, [hex_contract_address, hex_key, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_storage(self, hex_contract_address: str, hex_key: str, is_full: bool = False) -> str: """ This interface is used to get the corresponding stored value based on hexadecimal contract address and stored key. :param hex_contract_address: hexadecimal contract address. :param hex_key: a hexadecimal stored key. :param is_full: :return: the information of contract storage. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_STORAGE, [hex_contract_address, hex_key, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_storage", "(", "self", ",", "hex_contract_address", ":", "str", ",", "hex_key", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_STORAGE", ",", "[", "hex_contract_address", ",", "hex_key", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the corresponding stored value based on hexadecimal contract address and stored key. :param hex_contract_address: hexadecimal contract address. :param hex_key: a hexadecimal stored key. :param is_full: :return: the information of contract storage.
[ "This", "interface", "is", "used", "to", "get", "the", "corresponding", "stored", "value", "based", "on", "hexadecimal", "contract", "address", "and", "stored", "key", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L337-L351
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_smart_contract_event_by_tx_hash
def get_smart_contract_event_by_tx_hash(self, tx_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the corresponding smart contract event based on the height of block. :param tx_hash: a hexadecimal hash value. :param is_full: :return: the information of smart contract event in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT_EVENT, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_smart_contract_event_by_tx_hash(self, tx_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the corresponding smart contract event based on the height of block. :param tx_hash: a hexadecimal hash value. :param is_full: :return: the information of smart contract event in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT_EVENT, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_smart_contract_event_by_tx_hash", "(", "self", ",", "tx_hash", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_SMART_CONTRACT_EVENT", ",", "[", "tx_hash", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the corresponding smart contract event based on the height of block. :param tx_hash: a hexadecimal hash value. :param is_full: :return: the information of smart contract event in dictionary form.
[ "This", "interface", "is", "used", "to", "get", "the", "corresponding", "smart", "contract", "event", "based", "on", "the", "height", "of", "block", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L353-L365
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_smart_contract_event_by_height
def get_smart_contract_event_by_height(self, height: int, is_full: bool = False) -> List[dict]: """ This interface is used to get the corresponding smart contract event based on the height of block. :param height: a decimal height value. :param is_full: :return: the information of smart contract event in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT_EVENT, [height, 1]) response = self.__post(self.__url, payload) if is_full: return response event_list = response['result'] if event_list is None: event_list = list() return event_list
python
def get_smart_contract_event_by_height(self, height: int, is_full: bool = False) -> List[dict]: """ This interface is used to get the corresponding smart contract event based on the height of block. :param height: a decimal height value. :param is_full: :return: the information of smart contract event in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT_EVENT, [height, 1]) response = self.__post(self.__url, payload) if is_full: return response event_list = response['result'] if event_list is None: event_list = list() return event_list
[ "def", "get_smart_contract_event_by_height", "(", "self", ",", "height", ":", "int", ",", "is_full", ":", "bool", "=", "False", ")", "->", "List", "[", "dict", "]", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_SMART_CONTRACT_EVENT", ",", "[", "height", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "event_list", "=", "response", "[", "'result'", "]", "if", "event_list", "is", "None", ":", "event_list", "=", "list", "(", ")", "return", "event_list" ]
This interface is used to get the corresponding smart contract event based on the height of block. :param height: a decimal height value. :param is_full: :return: the information of smart contract event in dictionary form.
[ "This", "interface", "is", "used", "to", "get", "the", "corresponding", "smart", "contract", "event", "based", "on", "the", "height", "of", "block", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L367-L382
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_transaction_by_tx_hash
def get_transaction_by_tx_hash(self, tx_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the corresponding transaction information based on the specified hash value. :param tx_hash: str, a hexadecimal hash value. :param is_full: :return: dict """ payload = self.generate_json_rpc_payload(RpcMethod.GET_TRANSACTION, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_transaction_by_tx_hash(self, tx_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the corresponding transaction information based on the specified hash value. :param tx_hash: str, a hexadecimal hash value. :param is_full: :return: dict """ payload = self.generate_json_rpc_payload(RpcMethod.GET_TRANSACTION, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_transaction_by_tx_hash", "(", "self", ",", "tx_hash", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_TRANSACTION", ",", "[", "tx_hash", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the corresponding transaction information based on the specified hash value. :param tx_hash: str, a hexadecimal hash value. :param is_full: :return: dict
[ "This", "interface", "is", "used", "to", "get", "the", "corresponding", "transaction", "information", "based", "on", "the", "specified", "hash", "value", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L387-L399
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_smart_contract
def get_smart_contract(self, hex_contract_address: str, is_full: bool = False) -> dict: """ This interface is used to get the information of smart contract based on the specified hexadecimal hash value. :param hex_contract_address: str, a hexadecimal hash value. :param is_full: :return: the information of smart contract in dictionary form. """ if not isinstance(hex_contract_address, str): raise SDKException(ErrorCode.param_err('a hexadecimal contract address is required.')) if len(hex_contract_address) != 40: raise SDKException(ErrorCode.param_err('the length of the contract address should be 40 bytes.')) payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT, [hex_contract_address, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_smart_contract(self, hex_contract_address: str, is_full: bool = False) -> dict: """ This interface is used to get the information of smart contract based on the specified hexadecimal hash value. :param hex_contract_address: str, a hexadecimal hash value. :param is_full: :return: the information of smart contract in dictionary form. """ if not isinstance(hex_contract_address, str): raise SDKException(ErrorCode.param_err('a hexadecimal contract address is required.')) if len(hex_contract_address) != 40: raise SDKException(ErrorCode.param_err('the length of the contract address should be 40 bytes.')) payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT, [hex_contract_address, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_smart_contract", "(", "self", ",", "hex_contract_address", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "if", "not", "isinstance", "(", "hex_contract_address", ",", "str", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'a hexadecimal contract address is required.'", ")", ")", "if", "len", "(", "hex_contract_address", ")", "!=", "40", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the length of the contract address should be 40 bytes.'", ")", ")", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_SMART_CONTRACT", ",", "[", "hex_contract_address", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the information of smart contract based on the specified hexadecimal hash value. :param hex_contract_address: str, a hexadecimal hash value. :param is_full: :return: the information of smart contract in dictionary form.
[ "This", "interface", "is", "used", "to", "get", "the", "information", "of", "smart", "contract", "based", "on", "the", "specified", "hexadecimal", "hash", "value", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L401-L417
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.get_merkle_proof
def get_merkle_proof(self, tx_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the corresponding merkle proof based on the specified hexadecimal hash value. :param tx_hash: an hexadecimal transaction hash value. :param is_full: :return: the merkle proof in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_MERKLE_PROOF, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def get_merkle_proof(self, tx_hash: str, is_full: bool = False) -> dict: """ This interface is used to get the corresponding merkle proof based on the specified hexadecimal hash value. :param tx_hash: an hexadecimal transaction hash value. :param is_full: :return: the merkle proof in dictionary form. """ payload = self.generate_json_rpc_payload(RpcMethod.GET_MERKLE_PROOF, [tx_hash, 1]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "get_merkle_proof", "(", "self", ",", "tx_hash", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_MERKLE_PROOF", ",", "[", "tx_hash", ",", "1", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to get the corresponding merkle proof based on the specified hexadecimal hash value. :param tx_hash: an hexadecimal transaction hash value. :param is_full: :return: the merkle proof in dictionary form.
[ "This", "interface", "is", "used", "to", "get", "the", "corresponding", "merkle", "proof", "based", "on", "the", "specified", "hexadecimal", "hash", "value", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L419-L431
ontio/ontology-python-sdk
ontology/network/rpc.py
RpcClient.send_raw_transaction
def send_raw_transaction(self, tx: Transaction, is_full: bool = False) -> str: """ This interface is used to send the transaction into the network. :param tx: Transaction object in ontology Python SDK. :param is_full: :return: a hexadecimal transaction hash value. """ tx_data = tx.serialize(is_hex=True) payload = self.generate_json_rpc_payload(RpcMethod.SEND_TRANSACTION, [tx_data]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
python
def send_raw_transaction(self, tx: Transaction, is_full: bool = False) -> str: """ This interface is used to send the transaction into the network. :param tx: Transaction object in ontology Python SDK. :param is_full: :return: a hexadecimal transaction hash value. """ tx_data = tx.serialize(is_hex=True) payload = self.generate_json_rpc_payload(RpcMethod.SEND_TRANSACTION, [tx_data]) response = self.__post(self.__url, payload) if is_full: return response return response['result']
[ "def", "send_raw_transaction", "(", "self", ",", "tx", ":", "Transaction", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "tx_data", "=", "tx", ".", "serialize", "(", "is_hex", "=", "True", ")", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "SEND_TRANSACTION", ",", "[", "tx_data", "]", ")", "response", "=", "self", ".", "__post", "(", "self", ".", "__url", ",", "payload", ")", "if", "is_full", ":", "return", "response", "return", "response", "[", "'result'", "]" ]
This interface is used to send the transaction into the network. :param tx: Transaction object in ontology Python SDK. :param is_full: :return: a hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "send", "the", "transaction", "into", "the", "network", ".", ":", "param", "tx", ":", "Transaction", "object", "in", "ontology", "Python", "SDK", ".", ":", "param", "is_full", ":", ":", "return", ":", "a", "hexadecimal", "transaction", "hash", "value", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L447-L459
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.parse_ddo
def parse_ddo(ont_id: str, serialized_ddo: str or bytes) -> dict: """ This interface is used to deserialize a hexadecimal string into a DDO object in the from of dict. :param ont_id: the unique ID for identity. :param serialized_ddo: an serialized description object of ONT ID in form of str or bytes. :return: a description object of ONT ID in the from of dict. """ if len(serialized_ddo) == 0: return dict() if isinstance(serialized_ddo, str): stream = StreamManager.get_stream(bytearray.fromhex(serialized_ddo)) elif isinstance(serialized_ddo, bytes): stream = StreamManager.get_stream(serialized_ddo) else: raise SDKException(ErrorCode.params_type_error('bytes or str parameter is required.')) reader = BinaryReader(stream) try: public_key_bytes = reader.read_var_bytes() except SDKException: public_key_bytes = b'' try: attribute_bytes = reader.read_var_bytes() except SDKException: attribute_bytes = b'' try: recovery_bytes = reader.read_var_bytes() except SDKException: recovery_bytes = b'' if len(recovery_bytes) != 0: b58_recovery = Address(recovery_bytes).b58encode() else: b58_recovery = '' pub_keys = OntId.parse_pub_keys(ont_id, public_key_bytes) attribute_list = OntId.parse_attributes(attribute_bytes) ddo = dict(Owners=pub_keys, Attributes=attribute_list, Recovery=b58_recovery, OntId=ont_id) return ddo
python
def parse_ddo(ont_id: str, serialized_ddo: str or bytes) -> dict: """ This interface is used to deserialize a hexadecimal string into a DDO object in the from of dict. :param ont_id: the unique ID for identity. :param serialized_ddo: an serialized description object of ONT ID in form of str or bytes. :return: a description object of ONT ID in the from of dict. """ if len(serialized_ddo) == 0: return dict() if isinstance(serialized_ddo, str): stream = StreamManager.get_stream(bytearray.fromhex(serialized_ddo)) elif isinstance(serialized_ddo, bytes): stream = StreamManager.get_stream(serialized_ddo) else: raise SDKException(ErrorCode.params_type_error('bytes or str parameter is required.')) reader = BinaryReader(stream) try: public_key_bytes = reader.read_var_bytes() except SDKException: public_key_bytes = b'' try: attribute_bytes = reader.read_var_bytes() except SDKException: attribute_bytes = b'' try: recovery_bytes = reader.read_var_bytes() except SDKException: recovery_bytes = b'' if len(recovery_bytes) != 0: b58_recovery = Address(recovery_bytes).b58encode() else: b58_recovery = '' pub_keys = OntId.parse_pub_keys(ont_id, public_key_bytes) attribute_list = OntId.parse_attributes(attribute_bytes) ddo = dict(Owners=pub_keys, Attributes=attribute_list, Recovery=b58_recovery, OntId=ont_id) return ddo
[ "def", "parse_ddo", "(", "ont_id", ":", "str", ",", "serialized_ddo", ":", "str", "or", "bytes", ")", "->", "dict", ":", "if", "len", "(", "serialized_ddo", ")", "==", "0", ":", "return", "dict", "(", ")", "if", "isinstance", "(", "serialized_ddo", ",", "str", ")", ":", "stream", "=", "StreamManager", ".", "get_stream", "(", "bytearray", ".", "fromhex", "(", "serialized_ddo", ")", ")", "elif", "isinstance", "(", "serialized_ddo", ",", "bytes", ")", ":", "stream", "=", "StreamManager", ".", "get_stream", "(", "serialized_ddo", ")", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "params_type_error", "(", "'bytes or str parameter is required.'", ")", ")", "reader", "=", "BinaryReader", "(", "stream", ")", "try", ":", "public_key_bytes", "=", "reader", ".", "read_var_bytes", "(", ")", "except", "SDKException", ":", "public_key_bytes", "=", "b''", "try", ":", "attribute_bytes", "=", "reader", ".", "read_var_bytes", "(", ")", "except", "SDKException", ":", "attribute_bytes", "=", "b''", "try", ":", "recovery_bytes", "=", "reader", ".", "read_var_bytes", "(", ")", "except", "SDKException", ":", "recovery_bytes", "=", "b''", "if", "len", "(", "recovery_bytes", ")", "!=", "0", ":", "b58_recovery", "=", "Address", "(", "recovery_bytes", ")", ".", "b58encode", "(", ")", "else", ":", "b58_recovery", "=", "''", "pub_keys", "=", "OntId", ".", "parse_pub_keys", "(", "ont_id", ",", "public_key_bytes", ")", "attribute_list", "=", "OntId", ".", "parse_attributes", "(", "attribute_bytes", ")", "ddo", "=", "dict", "(", "Owners", "=", "pub_keys", ",", "Attributes", "=", "attribute_list", ",", "Recovery", "=", "b58_recovery", ",", "OntId", "=", "ont_id", ")", "return", "ddo" ]
This interface is used to deserialize a hexadecimal string into a DDO object in the from of dict. :param ont_id: the unique ID for identity. :param serialized_ddo: an serialized description object of ONT ID in form of str or bytes. :return: a description object of ONT ID in the from of dict.
[ "This", "interface", "is", "used", "to", "deserialize", "a", "hexadecimal", "string", "into", "a", "DDO", "object", "in", "the", "from", "of", "dict", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L110-L146
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.get_ddo
def get_ddo(self, ont_id: str) -> dict: """ This interface is used to get a DDO object in the from of dict. :param ont_id: the unique ID for identity. :return: a description object of ONT ID in the from of dict. """ args = dict(ontid=ont_id.encode('utf-8')) invoke_code = build_vm.build_native_invoke_code(self.__contract_address, self.__version, 'getDDO', args) unix_time_now = int(time()) tx = Transaction(0, 0xd1, unix_time_now, 0, 0, None, invoke_code, bytearray(), []) response = self.__sdk.rpc.send_raw_transaction_pre_exec(tx) ddo = OntId.parse_ddo(ont_id, response['Result']) return ddo
python
def get_ddo(self, ont_id: str) -> dict: """ This interface is used to get a DDO object in the from of dict. :param ont_id: the unique ID for identity. :return: a description object of ONT ID in the from of dict. """ args = dict(ontid=ont_id.encode('utf-8')) invoke_code = build_vm.build_native_invoke_code(self.__contract_address, self.__version, 'getDDO', args) unix_time_now = int(time()) tx = Transaction(0, 0xd1, unix_time_now, 0, 0, None, invoke_code, bytearray(), []) response = self.__sdk.rpc.send_raw_transaction_pre_exec(tx) ddo = OntId.parse_ddo(ont_id, response['Result']) return ddo
[ "def", "get_ddo", "(", "self", ",", "ont_id", ":", "str", ")", "->", "dict", ":", "args", "=", "dict", "(", "ontid", "=", "ont_id", ".", "encode", "(", "'utf-8'", ")", ")", "invoke_code", "=", "build_vm", ".", "build_native_invoke_code", "(", "self", ".", "__contract_address", ",", "self", ".", "__version", ",", "'getDDO'", ",", "args", ")", "unix_time_now", "=", "int", "(", "time", "(", ")", ")", "tx", "=", "Transaction", "(", "0", ",", "0xd1", ",", "unix_time_now", ",", "0", ",", "0", ",", "None", ",", "invoke_code", ",", "bytearray", "(", ")", ",", "[", "]", ")", "response", "=", "self", ".", "__sdk", ".", "rpc", ".", "send_raw_transaction_pre_exec", "(", "tx", ")", "ddo", "=", "OntId", ".", "parse_ddo", "(", "ont_id", ",", "response", "[", "'Result'", "]", ")", "return", "ddo" ]
This interface is used to get a DDO object in the from of dict. :param ont_id: the unique ID for identity. :return: a description object of ONT ID in the from of dict.
[ "This", "interface", "is", "used", "to", "get", "a", "DDO", "object", "in", "the", "from", "of", "dict", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L171-L184
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.registry_ont_id
def registry_ont_id(self, ont_id: str, ctrl_acct: Account, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a Transaction object which is used to registry ontid. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value. """ if not isinstance(ctrl_acct, Account) or not isinstance(payer, Account): raise SDKException(ErrorCode.require_acct_params) b58_payer_address = payer.get_address_base58() bytes_ctrl_pub_key = ctrl_acct.get_public_key_bytes() tx = self.new_registry_ont_id_transaction(ont_id, bytes_ctrl_pub_key, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(ctrl_acct) tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
python
def registry_ont_id(self, ont_id: str, ctrl_acct: Account, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a Transaction object which is used to registry ontid. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value. """ if not isinstance(ctrl_acct, Account) or not isinstance(payer, Account): raise SDKException(ErrorCode.require_acct_params) b58_payer_address = payer.get_address_base58() bytes_ctrl_pub_key = ctrl_acct.get_public_key_bytes() tx = self.new_registry_ont_id_transaction(ont_id, bytes_ctrl_pub_key, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(ctrl_acct) tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
[ "def", "registry_ont_id", "(", "self", ",", "ont_id", ":", "str", ",", "ctrl_acct", ":", "Account", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "if", "not", "isinstance", "(", "ctrl_acct", ",", "Account", ")", "or", "not", "isinstance", "(", "payer", ",", "Account", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "require_acct_params", ")", "b58_payer_address", "=", "payer", ".", "get_address_base58", "(", ")", "bytes_ctrl_pub_key", "=", "ctrl_acct", ".", "get_public_key_bytes", "(", ")", "tx", "=", "self", ".", "new_registry_ont_id_transaction", "(", "ont_id", ",", "bytes_ctrl_pub_key", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "ctrl_acct", ")", "tx", ".", "add_sign_transaction", "(", "payer", ")", "return", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")" ]
This interface is used to send a Transaction object which is used to registry ontid. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "send", "a", "Transaction", "object", "which", "is", "used", "to", "registry", "ontid", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L187-L205
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.add_public_key
def add_public_key(self, ont_id: str, operator: Account, hex_new_public_key: str, payer: Account, gas_limit: int, gas_price: int, is_recovery: bool = False): """ This interface is used to send a Transaction object which is used to add public key. :param ont_id: OntId. :param operator: an Account object which indicate who will sign for the transaction. :param hex_new_public_key: the new hexadecimal public key in the form of string. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :param is_recovery: indicate whether ctrl account is a recovery account. :return: a hexadecimal transaction hash value. """ if not isinstance(operator, Account) or not isinstance(payer, Account): raise SDKException(ErrorCode.require_acct_params) if is_recovery: bytes_operator = operator.get_address_bytes() else: bytes_operator = operator.get_public_key_bytes() b58_payer_address = payer.get_address_base58() tx = self.new_add_public_key_transaction(ont_id, bytes_operator, hex_new_public_key, b58_payer_address, gas_limit, gas_price, is_recovery) tx.sign_transaction(operator) tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
python
def add_public_key(self, ont_id: str, operator: Account, hex_new_public_key: str, payer: Account, gas_limit: int, gas_price: int, is_recovery: bool = False): """ This interface is used to send a Transaction object which is used to add public key. :param ont_id: OntId. :param operator: an Account object which indicate who will sign for the transaction. :param hex_new_public_key: the new hexadecimal public key in the form of string. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :param is_recovery: indicate whether ctrl account is a recovery account. :return: a hexadecimal transaction hash value. """ if not isinstance(operator, Account) or not isinstance(payer, Account): raise SDKException(ErrorCode.require_acct_params) if is_recovery: bytes_operator = operator.get_address_bytes() else: bytes_operator = operator.get_public_key_bytes() b58_payer_address = payer.get_address_base58() tx = self.new_add_public_key_transaction(ont_id, bytes_operator, hex_new_public_key, b58_payer_address, gas_limit, gas_price, is_recovery) tx.sign_transaction(operator) tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
[ "def", "add_public_key", "(", "self", ",", "ont_id", ":", "str", ",", "operator", ":", "Account", ",", "hex_new_public_key", ":", "str", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ",", "is_recovery", ":", "bool", "=", "False", ")", ":", "if", "not", "isinstance", "(", "operator", ",", "Account", ")", "or", "not", "isinstance", "(", "payer", ",", "Account", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "require_acct_params", ")", "if", "is_recovery", ":", "bytes_operator", "=", "operator", ".", "get_address_bytes", "(", ")", "else", ":", "bytes_operator", "=", "operator", ".", "get_public_key_bytes", "(", ")", "b58_payer_address", "=", "payer", ".", "get_address_base58", "(", ")", "tx", "=", "self", ".", "new_add_public_key_transaction", "(", "ont_id", ",", "bytes_operator", ",", "hex_new_public_key", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ",", "is_recovery", ")", "tx", ".", "sign_transaction", "(", "operator", ")", "tx", ".", "add_sign_transaction", "(", "payer", ")", "return", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")" ]
This interface is used to send a Transaction object which is used to add public key. :param ont_id: OntId. :param operator: an Account object which indicate who will sign for the transaction. :param hex_new_public_key: the new hexadecimal public key in the form of string. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :param is_recovery: indicate whether ctrl account is a recovery account. :return: a hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "send", "a", "Transaction", "object", "which", "is", "used", "to", "add", "public", "key", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L208-L233
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.add_attribute
def add_attribute(self, ont_id: str, ctrl_acct: Account, attributes: Attribute, payer: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to send a Transaction object which is used to add attribute. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param attributes: a list of attributes we want to add. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value. """ if not isinstance(ctrl_acct, Account) or not isinstance(payer, Account): raise SDKException(ErrorCode.require_acct_params) pub_key = ctrl_acct.get_public_key_bytes() b58_payer_address = payer.get_address_base58() tx = self.new_add_attribute_transaction(ont_id, pub_key, attributes, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(ctrl_acct) tx.add_sign_transaction(payer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
python
def add_attribute(self, ont_id: str, ctrl_acct: Account, attributes: Attribute, payer: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to send a Transaction object which is used to add attribute. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param attributes: a list of attributes we want to add. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value. """ if not isinstance(ctrl_acct, Account) or not isinstance(payer, Account): raise SDKException(ErrorCode.require_acct_params) pub_key = ctrl_acct.get_public_key_bytes() b58_payer_address = payer.get_address_base58() tx = self.new_add_attribute_transaction(ont_id, pub_key, attributes, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(ctrl_acct) tx.add_sign_transaction(payer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
[ "def", "add_attribute", "(", "self", ",", "ont_id", ":", "str", ",", "ctrl_acct", ":", "Account", ",", "attributes", ":", "Attribute", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "str", ":", "if", "not", "isinstance", "(", "ctrl_acct", ",", "Account", ")", "or", "not", "isinstance", "(", "payer", ",", "Account", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "require_acct_params", ")", "pub_key", "=", "ctrl_acct", ".", "get_public_key_bytes", "(", ")", "b58_payer_address", "=", "payer", ".", "get_address_base58", "(", ")", "tx", "=", "self", ".", "new_add_attribute_transaction", "(", "ont_id", ",", "pub_key", ",", "attributes", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "ctrl_acct", ")", "tx", ".", "add_sign_transaction", "(", "payer", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")", "return", "tx_hash" ]
This interface is used to send a Transaction object which is used to add attribute. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param attributes: a list of attributes we want to add. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "send", "a", "Transaction", "object", "which", "is", "used", "to", "add", "attribute", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L264-L285
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.remove_attribute
def remove_attribute(self, ont_id: str, operator: Account, attrib_key: str, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a Transaction object which is used to remove attribute. :param ont_id: OntId. :param operator: an Account object which indicate who will sign for the transaction. :param attrib_key: a string which is used to indicate which attribute we want to remove. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value. """ pub_key = operator.get_public_key_bytes() b58_payer_address = payer.get_address_base58() tx = self.new_remove_attribute_transaction(ont_id, pub_key, attrib_key, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(operator) tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
python
def remove_attribute(self, ont_id: str, operator: Account, attrib_key: str, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a Transaction object which is used to remove attribute. :param ont_id: OntId. :param operator: an Account object which indicate who will sign for the transaction. :param attrib_key: a string which is used to indicate which attribute we want to remove. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value. """ pub_key = operator.get_public_key_bytes() b58_payer_address = payer.get_address_base58() tx = self.new_remove_attribute_transaction(ont_id, pub_key, attrib_key, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(operator) tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
[ "def", "remove_attribute", "(", "self", ",", "ont_id", ":", "str", ",", "operator", ":", "Account", ",", "attrib_key", ":", "str", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "pub_key", "=", "operator", ".", "get_public_key_bytes", "(", ")", "b58_payer_address", "=", "payer", ".", "get_address_base58", "(", ")", "tx", "=", "self", ".", "new_remove_attribute_transaction", "(", "ont_id", ",", "pub_key", ",", "attrib_key", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "operator", ")", "tx", ".", "add_sign_transaction", "(", "payer", ")", "return", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")" ]
This interface is used to send a Transaction object which is used to remove attribute. :param ont_id: OntId. :param operator: an Account object which indicate who will sign for the transaction. :param attrib_key: a string which is used to indicate which attribute we want to remove. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "send", "a", "Transaction", "object", "which", "is", "used", "to", "remove", "attribute", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L288-L306
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.add_recovery
def add_recovery(self, ont_id: str, ctrl_acct: Account, b58_recovery_address: str, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a Transaction object which is used to add the recovery. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to add the recovery. """ b58_payer_address = payer.get_address_base58() pub_key = ctrl_acct.get_public_key_bytes() tx = self.new_add_recovery_transaction(ont_id, pub_key, b58_recovery_address, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(ctrl_acct) tx.add_sign_transaction(payer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
python
def add_recovery(self, ont_id: str, ctrl_acct: Account, b58_recovery_address: str, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a Transaction object which is used to add the recovery. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to add the recovery. """ b58_payer_address = payer.get_address_base58() pub_key = ctrl_acct.get_public_key_bytes() tx = self.new_add_recovery_transaction(ont_id, pub_key, b58_recovery_address, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(ctrl_acct) tx.add_sign_transaction(payer) tx_hash = self.__sdk.get_network().send_raw_transaction(tx) return tx_hash
[ "def", "add_recovery", "(", "self", ",", "ont_id", ":", "str", ",", "ctrl_acct", ":", "Account", ",", "b58_recovery_address", ":", "str", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "b58_payer_address", "=", "payer", ".", "get_address_base58", "(", ")", "pub_key", "=", "ctrl_acct", ".", "get_public_key_bytes", "(", ")", "tx", "=", "self", ".", "new_add_recovery_transaction", "(", "ont_id", ",", "pub_key", ",", "b58_recovery_address", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "ctrl_acct", ")", "tx", ".", "add_sign_transaction", "(", "payer", ")", "tx_hash", "=", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")", "return", "tx_hash" ]
This interface is used to send a Transaction object which is used to add the recovery. :param ont_id: OntId. :param ctrl_acct: an Account object which indicate who will sign for the transaction. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param payer: an Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to add the recovery.
[ "This", "interface", "is", "used", "to", "send", "a", "Transaction", "object", "which", "is", "used", "to", "add", "the", "recovery", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L309-L329
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.new_registry_ont_id_transaction
def new_registry_ont_id_transaction(self, ont_id: str, pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: """ This interface is used to generate a Transaction object which is used to register ONT ID. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to register ONT ID. """ if isinstance(pub_key, str): bytes_ctrl_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_ctrl_pub_key = pub_key else: raise SDKException(ErrorCode.param_err('a bytes or str type of public key is required.')) args = dict(ontid=ont_id.encode('utf-8'), ctrl_pk=bytes_ctrl_pub_key) tx = self.__generate_transaction('regIDWithPublicKey', args, b58_payer_address, gas_limit, gas_price) return tx
python
def new_registry_ont_id_transaction(self, ont_id: str, pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: """ This interface is used to generate a Transaction object which is used to register ONT ID. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to register ONT ID. """ if isinstance(pub_key, str): bytes_ctrl_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_ctrl_pub_key = pub_key else: raise SDKException(ErrorCode.param_err('a bytes or str type of public key is required.')) args = dict(ontid=ont_id.encode('utf-8'), ctrl_pk=bytes_ctrl_pub_key) tx = self.__generate_transaction('regIDWithPublicKey', args, b58_payer_address, gas_limit, gas_price) return tx
[ "def", "new_registry_ont_id_transaction", "(", "self", ",", "ont_id", ":", "str", ",", "pub_key", ":", "str", "or", "bytes", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "Transaction", ":", "if", "isinstance", "(", "pub_key", ",", "str", ")", ":", "bytes_ctrl_pub_key", "=", "bytes", ".", "fromhex", "(", "pub_key", ")", "elif", "isinstance", "(", "pub_key", ",", "bytes", ")", ":", "bytes_ctrl_pub_key", "=", "pub_key", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'a bytes or str type of public key is required.'", ")", ")", "args", "=", "dict", "(", "ontid", "=", "ont_id", ".", "encode", "(", "'utf-8'", ")", ",", "ctrl_pk", "=", "bytes_ctrl_pub_key", ")", "tx", "=", "self", ".", "__generate_transaction", "(", "'regIDWithPublicKey'", ",", "args", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "return", "tx" ]
This interface is used to generate a Transaction object which is used to register ONT ID. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to register ONT ID.
[ "This", "interface", "is", "used", "to", "generate", "a", "Transaction", "object", "which", "is", "used", "to", "register", "ONT", "ID", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L386-L406
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.new_add_public_key_transaction
def new_add_public_key_transaction(self, ont_id: str, bytes_operator: bytes, new_pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int, is_recovery: bool = False): """ This interface is used to send a Transaction object which is used to add public key. :param ont_id: OntId. :param bytes_operator: operator args in from of bytes. :param new_pub_key: the new hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :param is_recovery: indicate whether ctrl account is a recovery account. :return: a Transaction object which is used to add public key. """ if isinstance(new_pub_key, str): bytes_new_pub_key = bytes.fromhex(new_pub_key) elif isinstance(new_pub_key, bytes): bytes_new_pub_key = new_pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) if is_recovery: args = dict(ontid=ont_id, pk=bytes_new_pub_key, operator=bytes_operator) else: args = dict(ontid=ont_id, pk=bytes_new_pub_key, operator=bytes_operator) tx = self.__generate_transaction('addKey', args, b58_payer_address, gas_limit, gas_price) return tx
python
def new_add_public_key_transaction(self, ont_id: str, bytes_operator: bytes, new_pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int, is_recovery: bool = False): """ This interface is used to send a Transaction object which is used to add public key. :param ont_id: OntId. :param bytes_operator: operator args in from of bytes. :param new_pub_key: the new hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :param is_recovery: indicate whether ctrl account is a recovery account. :return: a Transaction object which is used to add public key. """ if isinstance(new_pub_key, str): bytes_new_pub_key = bytes.fromhex(new_pub_key) elif isinstance(new_pub_key, bytes): bytes_new_pub_key = new_pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) if is_recovery: args = dict(ontid=ont_id, pk=bytes_new_pub_key, operator=bytes_operator) else: args = dict(ontid=ont_id, pk=bytes_new_pub_key, operator=bytes_operator) tx = self.__generate_transaction('addKey', args, b58_payer_address, gas_limit, gas_price) return tx
[ "def", "new_add_public_key_transaction", "(", "self", ",", "ont_id", ":", "str", ",", "bytes_operator", ":", "bytes", ",", "new_pub_key", ":", "str", "or", "bytes", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ",", "is_recovery", ":", "bool", "=", "False", ")", ":", "if", "isinstance", "(", "new_pub_key", ",", "str", ")", ":", "bytes_new_pub_key", "=", "bytes", ".", "fromhex", "(", "new_pub_key", ")", "elif", "isinstance", "(", "new_pub_key", ",", "bytes", ")", ":", "bytes_new_pub_key", "=", "new_pub_key", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "params_type_error", "(", "'a bytes or str type of public key is required.'", ")", ")", "if", "is_recovery", ":", "args", "=", "dict", "(", "ontid", "=", "ont_id", ",", "pk", "=", "bytes_new_pub_key", ",", "operator", "=", "bytes_operator", ")", "else", ":", "args", "=", "dict", "(", "ontid", "=", "ont_id", ",", "pk", "=", "bytes_new_pub_key", ",", "operator", "=", "bytes_operator", ")", "tx", "=", "self", ".", "__generate_transaction", "(", "'addKey'", ",", "args", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "return", "tx" ]
This interface is used to send a Transaction object which is used to add public key. :param ont_id: OntId. :param bytes_operator: operator args in from of bytes. :param new_pub_key: the new hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :param is_recovery: indicate whether ctrl account is a recovery account. :return: a Transaction object which is used to add public key.
[ "This", "interface", "is", "used", "to", "send", "a", "Transaction", "object", "which", "is", "used", "to", "add", "public", "key", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L409-L435
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.new_revoke_public_key_transaction
def new_revoke_public_key_transaction(self, ont_id: str, bytes_operator: bytes, revoked_pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to remove public key. :param ont_id: OntId. :param bytes_operator: operator args in from of bytes. :param revoked_pub_key: a public key string which will be removed. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to remove public key. """ if isinstance(revoked_pub_key, str): bytes_revoked_pub_key = bytes.fromhex(revoked_pub_key) elif isinstance(revoked_pub_key, bytes): bytes_revoked_pub_key = revoked_pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_ont_id = ont_id.encode('utf-8') args = dict(ontid=bytes_ont_id, pk=bytes_revoked_pub_key, operator=bytes_operator) tx = self.__generate_transaction('removeKey', args, b58_payer_address, gas_limit, gas_price) return tx
python
def new_revoke_public_key_transaction(self, ont_id: str, bytes_operator: bytes, revoked_pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to remove public key. :param ont_id: OntId. :param bytes_operator: operator args in from of bytes. :param revoked_pub_key: a public key string which will be removed. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to remove public key. """ if isinstance(revoked_pub_key, str): bytes_revoked_pub_key = bytes.fromhex(revoked_pub_key) elif isinstance(revoked_pub_key, bytes): bytes_revoked_pub_key = revoked_pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_ont_id = ont_id.encode('utf-8') args = dict(ontid=bytes_ont_id, pk=bytes_revoked_pub_key, operator=bytes_operator) tx = self.__generate_transaction('removeKey', args, b58_payer_address, gas_limit, gas_price) return tx
[ "def", "new_revoke_public_key_transaction", "(", "self", ",", "ont_id", ":", "str", ",", "bytes_operator", ":", "bytes", ",", "revoked_pub_key", ":", "str", "or", "bytes", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "if", "isinstance", "(", "revoked_pub_key", ",", "str", ")", ":", "bytes_revoked_pub_key", "=", "bytes", ".", "fromhex", "(", "revoked_pub_key", ")", "elif", "isinstance", "(", "revoked_pub_key", ",", "bytes", ")", ":", "bytes_revoked_pub_key", "=", "revoked_pub_key", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "params_type_error", "(", "'a bytes or str type of public key is required.'", ")", ")", "bytes_ont_id", "=", "ont_id", ".", "encode", "(", "'utf-8'", ")", "args", "=", "dict", "(", "ontid", "=", "bytes_ont_id", ",", "pk", "=", "bytes_revoked_pub_key", ",", "operator", "=", "bytes_operator", ")", "tx", "=", "self", ".", "__generate_transaction", "(", "'removeKey'", ",", "args", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "return", "tx" ]
This interface is used to generate a Transaction object which is used to remove public key. :param ont_id: OntId. :param bytes_operator: operator args in from of bytes. :param revoked_pub_key: a public key string which will be removed. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to remove public key.
[ "This", "interface", "is", "used", "to", "generate", "a", "Transaction", "object", "which", "is", "used", "to", "remove", "public", "key", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L438-L460
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.new_add_attribute_transaction
def new_add_attribute_transaction(self, ont_id: str, pub_key: str or bytes, attributes: Attribute, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to add attribute. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param attributes: a list of attributes we want to add. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to add attribute. """ if isinstance(pub_key, str): bytes_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_ont_id = ont_id.encode('utf-8') args = dict(ontid=bytes_ont_id) attrib_dict = attributes.to_dict() args = dict(**args, **attrib_dict) args['pubkey'] = bytes_pub_key tx = self.__generate_transaction('addAttributes', args, b58_payer_address, gas_limit, gas_price) return tx
python
def new_add_attribute_transaction(self, ont_id: str, pub_key: str or bytes, attributes: Attribute, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to add attribute. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param attributes: a list of attributes we want to add. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to add attribute. """ if isinstance(pub_key, str): bytes_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_ont_id = ont_id.encode('utf-8') args = dict(ontid=bytes_ont_id) attrib_dict = attributes.to_dict() args = dict(**args, **attrib_dict) args['pubkey'] = bytes_pub_key tx = self.__generate_transaction('addAttributes', args, b58_payer_address, gas_limit, gas_price) return tx
[ "def", "new_add_attribute_transaction", "(", "self", ",", "ont_id", ":", "str", ",", "pub_key", ":", "str", "or", "bytes", ",", "attributes", ":", "Attribute", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "if", "isinstance", "(", "pub_key", ",", "str", ")", ":", "bytes_pub_key", "=", "bytes", ".", "fromhex", "(", "pub_key", ")", "elif", "isinstance", "(", "pub_key", ",", "bytes", ")", ":", "bytes_pub_key", "=", "pub_key", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "params_type_error", "(", "'a bytes or str type of public key is required.'", ")", ")", "bytes_ont_id", "=", "ont_id", ".", "encode", "(", "'utf-8'", ")", "args", "=", "dict", "(", "ontid", "=", "bytes_ont_id", ")", "attrib_dict", "=", "attributes", ".", "to_dict", "(", ")", "args", "=", "dict", "(", "*", "*", "args", ",", "*", "*", "attrib_dict", ")", "args", "[", "'pubkey'", "]", "=", "bytes_pub_key", "tx", "=", "self", ".", "__generate_transaction", "(", "'addAttributes'", ",", "args", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "return", "tx" ]
This interface is used to generate a Transaction object which is used to add attribute. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param attributes: a list of attributes we want to add. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to add attribute.
[ "This", "interface", "is", "used", "to", "generate", "a", "Transaction", "object", "which", "is", "used", "to", "add", "attribute", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L463-L488
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.new_remove_attribute_transaction
def new_remove_attribute_transaction(self, ont_id: str, pub_key: str or bytes, attrib_key: str, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to remove attribute. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param attrib_key: a string which is used to indicate which attribute we want to remove. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to remove attribute. """ if isinstance(pub_key, str): bytes_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) args = dict(ontid=ont_id.encode('utf-8'), attrib_key=attrib_key.encode('utf-8'), pk=bytes_pub_key) tx = self.__generate_transaction('removeAttribute', args, b58_payer_address, gas_limit, gas_price) return tx
python
def new_remove_attribute_transaction(self, ont_id: str, pub_key: str or bytes, attrib_key: str, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to remove attribute. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param attrib_key: a string which is used to indicate which attribute we want to remove. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to remove attribute. """ if isinstance(pub_key, str): bytes_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) args = dict(ontid=ont_id.encode('utf-8'), attrib_key=attrib_key.encode('utf-8'), pk=bytes_pub_key) tx = self.__generate_transaction('removeAttribute', args, b58_payer_address, gas_limit, gas_price) return tx
[ "def", "new_remove_attribute_transaction", "(", "self", ",", "ont_id", ":", "str", ",", "pub_key", ":", "str", "or", "bytes", ",", "attrib_key", ":", "str", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "if", "isinstance", "(", "pub_key", ",", "str", ")", ":", "bytes_pub_key", "=", "bytes", ".", "fromhex", "(", "pub_key", ")", "elif", "isinstance", "(", "pub_key", ",", "bytes", ")", ":", "bytes_pub_key", "=", "pub_key", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "params_type_error", "(", "'a bytes or str type of public key is required.'", ")", ")", "args", "=", "dict", "(", "ontid", "=", "ont_id", ".", "encode", "(", "'utf-8'", ")", ",", "attrib_key", "=", "attrib_key", ".", "encode", "(", "'utf-8'", ")", ",", "pk", "=", "bytes_pub_key", ")", "tx", "=", "self", ".", "__generate_transaction", "(", "'removeAttribute'", ",", "args", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "return", "tx" ]
This interface is used to generate a Transaction object which is used to remove attribute. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param attrib_key: a string which is used to indicate which attribute we want to remove. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which is used to remove attribute.
[ "This", "interface", "is", "used", "to", "generate", "a", "Transaction", "object", "which", "is", "used", "to", "remove", "attribute", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L491-L512
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/ontid.py
OntId.new_add_recovery_transaction
def new_add_recovery_transaction(self, ont_id: str, pub_key: str or bytes, b58_recovery_address: str, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to add the recovery. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: """ if isinstance(pub_key, str): bytes_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_recovery_address = Address.b58decode(b58_recovery_address).to_bytes() args = dict(ontid=ont_id.encode('utf-8'), recovery=bytes_recovery_address, pk=bytes_pub_key) tx = self.__generate_transaction('addRecovery', args, b58_payer_address, gas_limit, gas_price) return tx
python
def new_add_recovery_transaction(self, ont_id: str, pub_key: str or bytes, b58_recovery_address: str, b58_payer_address: str, gas_limit: int, gas_price: int): """ This interface is used to generate a Transaction object which is used to add the recovery. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: """ if isinstance(pub_key, str): bytes_pub_key = bytes.fromhex(pub_key) elif isinstance(pub_key, bytes): bytes_pub_key = pub_key else: raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.')) bytes_recovery_address = Address.b58decode(b58_recovery_address).to_bytes() args = dict(ontid=ont_id.encode('utf-8'), recovery=bytes_recovery_address, pk=bytes_pub_key) tx = self.__generate_transaction('addRecovery', args, b58_payer_address, gas_limit, gas_price) return tx
[ "def", "new_add_recovery_transaction", "(", "self", ",", "ont_id", ":", "str", ",", "pub_key", ":", "str", "or", "bytes", ",", "b58_recovery_address", ":", "str", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "if", "isinstance", "(", "pub_key", ",", "str", ")", ":", "bytes_pub_key", "=", "bytes", ".", "fromhex", "(", "pub_key", ")", "elif", "isinstance", "(", "pub_key", ",", "bytes", ")", ":", "bytes_pub_key", "=", "pub_key", "else", ":", "raise", "SDKException", "(", "ErrorCode", ".", "params_type_error", "(", "'a bytes or str type of public key is required.'", ")", ")", "bytes_recovery_address", "=", "Address", ".", "b58decode", "(", "b58_recovery_address", ")", ".", "to_bytes", "(", ")", "args", "=", "dict", "(", "ontid", "=", "ont_id", ".", "encode", "(", "'utf-8'", ")", ",", "recovery", "=", "bytes_recovery_address", ",", "pk", "=", "bytes_pub_key", ")", "tx", "=", "self", ".", "__generate_transaction", "(", "'addRecovery'", ",", "args", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "return", "tx" ]
This interface is used to generate a Transaction object which is used to add the recovery. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_recovery_address: a base58 encode address which indicate who is the recovery. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return:
[ "This", "interface", "is", "used", "to", "generate", "a", "Transaction", "object", "which", "is", "used", "to", "add", "the", "recovery", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L515-L537
ontio/ontology-python-sdk
ontology/core/transaction.py
Transaction.sign_transaction
def sign_transaction(self, signer: Account): """ This interface is used to sign the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ tx_hash = self.hash256() sig_data = signer.generate_signature(tx_hash) sig = [Sig([signer.get_public_key_bytes()], 1, [sig_data])] self.sig_list = sig
python
def sign_transaction(self, signer: Account): """ This interface is used to sign the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ tx_hash = self.hash256() sig_data = signer.generate_signature(tx_hash) sig = [Sig([signer.get_public_key_bytes()], 1, [sig_data])] self.sig_list = sig
[ "def", "sign_transaction", "(", "self", ",", "signer", ":", "Account", ")", ":", "tx_hash", "=", "self", ".", "hash256", "(", ")", "sig_data", "=", "signer", ".", "generate_signature", "(", "tx_hash", ")", "sig", "=", "[", "Sig", "(", "[", "signer", ".", "get_public_key_bytes", "(", ")", "]", ",", "1", ",", "[", "sig_data", "]", ")", "]", "self", ".", "sig_list", "=", "sig" ]
This interface is used to sign the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed.
[ "This", "interface", "is", "used", "to", "sign", "the", "transaction", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/core/transaction.py#L137-L147
ontio/ontology-python-sdk
ontology/core/transaction.py
Transaction.add_sign_transaction
def add_sign_transaction(self, signer: Account): """ This interface is used to add signature into the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ if self.sig_list is None or len(self.sig_list) == 0: self.sig_list = [] elif len(self.sig_list) >= TX_MAX_SIG_SIZE: raise SDKException(ErrorCode.param_err('the number of transaction signatures should not be over 16')) tx_hash = self.hash256() sig_data = signer.generate_signature(tx_hash) sig = Sig([signer.get_public_key_bytes()], 1, [sig_data]) self.sig_list.append(sig)
python
def add_sign_transaction(self, signer: Account): """ This interface is used to add signature into the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ if self.sig_list is None or len(self.sig_list) == 0: self.sig_list = [] elif len(self.sig_list) >= TX_MAX_SIG_SIZE: raise SDKException(ErrorCode.param_err('the number of transaction signatures should not be over 16')) tx_hash = self.hash256() sig_data = signer.generate_signature(tx_hash) sig = Sig([signer.get_public_key_bytes()], 1, [sig_data]) self.sig_list.append(sig)
[ "def", "add_sign_transaction", "(", "self", ",", "signer", ":", "Account", ")", ":", "if", "self", ".", "sig_list", "is", "None", "or", "len", "(", "self", ".", "sig_list", ")", "==", "0", ":", "self", ".", "sig_list", "=", "[", "]", "elif", "len", "(", "self", ".", "sig_list", ")", ">=", "TX_MAX_SIG_SIZE", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the number of transaction signatures should not be over 16'", ")", ")", "tx_hash", "=", "self", ".", "hash256", "(", ")", "sig_data", "=", "signer", ".", "generate_signature", "(", "tx_hash", ")", "sig", "=", "Sig", "(", "[", "signer", ".", "get_public_key_bytes", "(", ")", "]", ",", "1", ",", "[", "sig_data", "]", ")", "self", ".", "sig_list", ".", "append", "(", "sig", ")" ]
This interface is used to add signature into the transaction. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed.
[ "This", "interface", "is", "used", "to", "add", "signature", "into", "the", "transaction", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/core/transaction.py#L149-L163
ontio/ontology-python-sdk
ontology/core/transaction.py
Transaction.add_multi_sign_transaction
def add_multi_sign_transaction(self, m: int, pub_keys: List[bytes] or List[str], signer: Account): """ This interface is used to generate an Transaction object which has multi signature. :param tx: a Transaction object which will be signed. :param m: the amount of signer. :param pub_keys: a list of public keys. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ for index, pk in enumerate(pub_keys): if isinstance(pk, str): pub_keys[index] = pk.encode('ascii') pub_keys = ProgramBuilder.sort_public_keys(pub_keys) tx_hash = self.hash256() sig_data = signer.generate_signature(tx_hash) if self.sig_list is None or len(self.sig_list) == 0: self.sig_list = [] elif len(self.sig_list) >= TX_MAX_SIG_SIZE: raise SDKException(ErrorCode.param_err('the number of transaction signatures should not be over 16')) else: for i in range(len(self.sig_list)): if self.sig_list[i].public_keys == pub_keys: if len(self.sig_list[i].sig_data) + 1 > len(pub_keys): raise SDKException(ErrorCode.param_err('too more sigData')) if self.sig_list[i].m != m: raise SDKException(ErrorCode.param_err('M error')) self.sig_list[i].sig_data.append(sig_data) return sig = Sig(pub_keys, m, [sig_data]) self.sig_list.append(sig)
python
def add_multi_sign_transaction(self, m: int, pub_keys: List[bytes] or List[str], signer: Account): """ This interface is used to generate an Transaction object which has multi signature. :param tx: a Transaction object which will be signed. :param m: the amount of signer. :param pub_keys: a list of public keys. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed. """ for index, pk in enumerate(pub_keys): if isinstance(pk, str): pub_keys[index] = pk.encode('ascii') pub_keys = ProgramBuilder.sort_public_keys(pub_keys) tx_hash = self.hash256() sig_data = signer.generate_signature(tx_hash) if self.sig_list is None or len(self.sig_list) == 0: self.sig_list = [] elif len(self.sig_list) >= TX_MAX_SIG_SIZE: raise SDKException(ErrorCode.param_err('the number of transaction signatures should not be over 16')) else: for i in range(len(self.sig_list)): if self.sig_list[i].public_keys == pub_keys: if len(self.sig_list[i].sig_data) + 1 > len(pub_keys): raise SDKException(ErrorCode.param_err('too more sigData')) if self.sig_list[i].m != m: raise SDKException(ErrorCode.param_err('M error')) self.sig_list[i].sig_data.append(sig_data) return sig = Sig(pub_keys, m, [sig_data]) self.sig_list.append(sig)
[ "def", "add_multi_sign_transaction", "(", "self", ",", "m", ":", "int", ",", "pub_keys", ":", "List", "[", "bytes", "]", "or", "List", "[", "str", "]", ",", "signer", ":", "Account", ")", ":", "for", "index", ",", "pk", "in", "enumerate", "(", "pub_keys", ")", ":", "if", "isinstance", "(", "pk", ",", "str", ")", ":", "pub_keys", "[", "index", "]", "=", "pk", ".", "encode", "(", "'ascii'", ")", "pub_keys", "=", "ProgramBuilder", ".", "sort_public_keys", "(", "pub_keys", ")", "tx_hash", "=", "self", ".", "hash256", "(", ")", "sig_data", "=", "signer", ".", "generate_signature", "(", "tx_hash", ")", "if", "self", ".", "sig_list", "is", "None", "or", "len", "(", "self", ".", "sig_list", ")", "==", "0", ":", "self", ".", "sig_list", "=", "[", "]", "elif", "len", "(", "self", ".", "sig_list", ")", ">=", "TX_MAX_SIG_SIZE", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the number of transaction signatures should not be over 16'", ")", ")", "else", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "sig_list", ")", ")", ":", "if", "self", ".", "sig_list", "[", "i", "]", ".", "public_keys", "==", "pub_keys", ":", "if", "len", "(", "self", ".", "sig_list", "[", "i", "]", ".", "sig_data", ")", "+", "1", ">", "len", "(", "pub_keys", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'too more sigData'", ")", ")", "if", "self", ".", "sig_list", "[", "i", "]", ".", "m", "!=", "m", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'M error'", ")", ")", "self", ".", "sig_list", "[", "i", "]", ".", "sig_data", ".", "append", "(", "sig_data", ")", "return", "sig", "=", "Sig", "(", "pub_keys", ",", "m", ",", "[", "sig_data", "]", ")", "self", ".", "sig_list", ".", "append", "(", "sig", ")" ]
This interface is used to generate an Transaction object which has multi signature. :param tx: a Transaction object which will be signed. :param m: the amount of signer. :param pub_keys: a list of public keys. :param signer: an Account object which will sign the transaction. :return: a Transaction object which has been signed.
[ "This", "interface", "is", "used", "to", "generate", "an", "Transaction", "object", "which", "has", "multi", "signature", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/core/transaction.py#L165-L195
ontio/ontology-python-sdk
ontology/io/memory_stream.py
StreamManager.get_stream
def get_stream(data=None): """ Get a MemoryStream instance. Args: data (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: MemoryStream: instance. """ if len(__mstreams_available__) == 0: if data: mstream = MemoryStream(data) mstream.seek(0) else: mstream = MemoryStream() __mstreams__.append(mstream) return mstream mstream = __mstreams_available__.pop() if data is not None and len(data): mstream.clean_up() mstream.write(data) mstream.seek(0) return mstream
python
def get_stream(data=None): """ Get a MemoryStream instance. Args: data (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: MemoryStream: instance. """ if len(__mstreams_available__) == 0: if data: mstream = MemoryStream(data) mstream.seek(0) else: mstream = MemoryStream() __mstreams__.append(mstream) return mstream mstream = __mstreams_available__.pop() if data is not None and len(data): mstream.clean_up() mstream.write(data) mstream.seek(0) return mstream
[ "def", "get_stream", "(", "data", "=", "None", ")", ":", "if", "len", "(", "__mstreams_available__", ")", "==", "0", ":", "if", "data", ":", "mstream", "=", "MemoryStream", "(", "data", ")", "mstream", ".", "seek", "(", "0", ")", "else", ":", "mstream", "=", "MemoryStream", "(", ")", "__mstreams__", ".", "append", "(", "mstream", ")", "return", "mstream", "mstream", "=", "__mstreams_available__", ".", "pop", "(", ")", "if", "data", "is", "not", "None", "and", "len", "(", "data", ")", ":", "mstream", ".", "clean_up", "(", ")", "mstream", ".", "write", "(", "data", ")", "mstream", ".", "seek", "(", "0", ")", "return", "mstream" ]
Get a MemoryStream instance. Args: data (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: MemoryStream: instance.
[ "Get", "a", "MemoryStream", "instance", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/memory_stream.py#L28-L55
ontio/ontology-python-sdk
ontology/common/address.py
Address.address_from_vm_code
def address_from_vm_code(code: str): """ generate contract address from avm bytecode. :param code: str :return: Address """ script_hash = Address.to_script_hash(bytearray.fromhex(code))[::-1] return Address(script_hash)
python
def address_from_vm_code(code: str): """ generate contract address from avm bytecode. :param code: str :return: Address """ script_hash = Address.to_script_hash(bytearray.fromhex(code))[::-1] return Address(script_hash)
[ "def", "address_from_vm_code", "(", "code", ":", "str", ")", ":", "script_hash", "=", "Address", ".", "to_script_hash", "(", "bytearray", ".", "fromhex", "(", "code", ")", ")", "[", ":", ":", "-", "1", "]", "return", "Address", "(", "script_hash", ")" ]
generate contract address from avm bytecode. :param code: str :return: Address
[ "generate", "contract", "address", "from", "avm", "bytecode", ".", ":", "param", "code", ":", "str", ":", "return", ":", "Address" ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/common/address.py#L47-L54
ontio/ontology-python-sdk
ontology/account/account.py
Account.export_gcm_encrypted_private_key
def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str: """ This interface is used to export an AES algorithm encrypted private key with the mode of GCM. :param password: the secret pass phrase to generate the keys from. :param salt: A string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. It is recommended to be at least 8 bytes long. :param n: CPU/memory cost parameter. It must be a power of 2 and less than 2**32 :return: an gcm encrypted private key in the form of string. """ r = 8 p = 8 dk_len = 64 scrypt = Scrypt(n, r, p, dk_len) derived_key = scrypt.generate_kd(password, salt) iv = derived_key[0:12] key = derived_key[32:64] hdr = self.__address.b58encode().encode() mac_tag, cipher_text = AESHandler.aes_gcm_encrypt_with_iv(self.__private_key, hdr, key, iv) encrypted_key = bytes.hex(cipher_text) + bytes.hex(mac_tag) encrypted_key_str = base64.b64encode(bytes.fromhex(encrypted_key)) return encrypted_key_str.decode('utf-8')
python
def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str: """ This interface is used to export an AES algorithm encrypted private key with the mode of GCM. :param password: the secret pass phrase to generate the keys from. :param salt: A string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. It is recommended to be at least 8 bytes long. :param n: CPU/memory cost parameter. It must be a power of 2 and less than 2**32 :return: an gcm encrypted private key in the form of string. """ r = 8 p = 8 dk_len = 64 scrypt = Scrypt(n, r, p, dk_len) derived_key = scrypt.generate_kd(password, salt) iv = derived_key[0:12] key = derived_key[32:64] hdr = self.__address.b58encode().encode() mac_tag, cipher_text = AESHandler.aes_gcm_encrypt_with_iv(self.__private_key, hdr, key, iv) encrypted_key = bytes.hex(cipher_text) + bytes.hex(mac_tag) encrypted_key_str = base64.b64encode(bytes.fromhex(encrypted_key)) return encrypted_key_str.decode('utf-8')
[ "def", "export_gcm_encrypted_private_key", "(", "self", ",", "password", ":", "str", ",", "salt", ":", "str", ",", "n", ":", "int", "=", "16384", ")", "->", "str", ":", "r", "=", "8", "p", "=", "8", "dk_len", "=", "64", "scrypt", "=", "Scrypt", "(", "n", ",", "r", ",", "p", ",", "dk_len", ")", "derived_key", "=", "scrypt", ".", "generate_kd", "(", "password", ",", "salt", ")", "iv", "=", "derived_key", "[", "0", ":", "12", "]", "key", "=", "derived_key", "[", "32", ":", "64", "]", "hdr", "=", "self", ".", "__address", ".", "b58encode", "(", ")", ".", "encode", "(", ")", "mac_tag", ",", "cipher_text", "=", "AESHandler", ".", "aes_gcm_encrypt_with_iv", "(", "self", ".", "__private_key", ",", "hdr", ",", "key", ",", "iv", ")", "encrypted_key", "=", "bytes", ".", "hex", "(", "cipher_text", ")", "+", "bytes", ".", "hex", "(", "mac_tag", ")", "encrypted_key_str", "=", "base64", ".", "b64encode", "(", "bytes", ".", "fromhex", "(", "encrypted_key", ")", ")", "return", "encrypted_key_str", ".", "decode", "(", "'utf-8'", ")" ]
This interface is used to export an AES algorithm encrypted private key with the mode of GCM. :param password: the secret pass phrase to generate the keys from. :param salt: A string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. It is recommended to be at least 8 bytes long. :param n: CPU/memory cost parameter. It must be a power of 2 and less than 2**32 :return: an gcm encrypted private key in the form of string.
[ "This", "interface", "is", "used", "to", "export", "an", "AES", "algorithm", "encrypted", "private", "key", "with", "the", "mode", "of", "GCM", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/account/account.py#L108-L130
ontio/ontology-python-sdk
ontology/account/account.py
Account.get_gcm_decoded_private_key
def get_gcm_decoded_private_key(encrypted_key_str: str, password: str, b58_address: str, salt: str, n: int, scheme: SignatureScheme) -> str: """ This interface is used to decrypt an private key which has been encrypted. :param encrypted_key_str: an gcm encrypted private key in the form of string. :param password: the secret pass phrase to generate the keys from. :param b58_address: a base58 encode address which should be correspond with the private key. :param salt: a string to use for better protection from dictionary attacks. :param n: CPU/memory cost parameter. :param scheme: the signature scheme. :return: a private key in the form of string. """ r = 8 p = 8 dk_len = 64 scrypt = Scrypt(n, r, p, dk_len) derived_key = scrypt.generate_kd(password, salt) iv = derived_key[0:12] key = derived_key[32:64] encrypted_key = base64.b64decode(encrypted_key_str).hex() mac_tag = bytes.fromhex(encrypted_key[64:96]) cipher_text = bytes.fromhex(encrypted_key[0:64]) private_key = AESHandler.aes_gcm_decrypt_with_iv(cipher_text, b58_address.encode(), mac_tag, key, iv) if len(private_key) == 0: raise SDKException(ErrorCode.decrypt_encrypted_private_key_error) acct = Account(private_key, scheme) if acct.get_address().b58encode() != b58_address: raise SDKException(ErrorCode.other_error('Address error.')) return private_key.hex()
python
def get_gcm_decoded_private_key(encrypted_key_str: str, password: str, b58_address: str, salt: str, n: int, scheme: SignatureScheme) -> str: """ This interface is used to decrypt an private key which has been encrypted. :param encrypted_key_str: an gcm encrypted private key in the form of string. :param password: the secret pass phrase to generate the keys from. :param b58_address: a base58 encode address which should be correspond with the private key. :param salt: a string to use for better protection from dictionary attacks. :param n: CPU/memory cost parameter. :param scheme: the signature scheme. :return: a private key in the form of string. """ r = 8 p = 8 dk_len = 64 scrypt = Scrypt(n, r, p, dk_len) derived_key = scrypt.generate_kd(password, salt) iv = derived_key[0:12] key = derived_key[32:64] encrypted_key = base64.b64decode(encrypted_key_str).hex() mac_tag = bytes.fromhex(encrypted_key[64:96]) cipher_text = bytes.fromhex(encrypted_key[0:64]) private_key = AESHandler.aes_gcm_decrypt_with_iv(cipher_text, b58_address.encode(), mac_tag, key, iv) if len(private_key) == 0: raise SDKException(ErrorCode.decrypt_encrypted_private_key_error) acct = Account(private_key, scheme) if acct.get_address().b58encode() != b58_address: raise SDKException(ErrorCode.other_error('Address error.')) return private_key.hex()
[ "def", "get_gcm_decoded_private_key", "(", "encrypted_key_str", ":", "str", ",", "password", ":", "str", ",", "b58_address", ":", "str", ",", "salt", ":", "str", ",", "n", ":", "int", ",", "scheme", ":", "SignatureScheme", ")", "->", "str", ":", "r", "=", "8", "p", "=", "8", "dk_len", "=", "64", "scrypt", "=", "Scrypt", "(", "n", ",", "r", ",", "p", ",", "dk_len", ")", "derived_key", "=", "scrypt", ".", "generate_kd", "(", "password", ",", "salt", ")", "iv", "=", "derived_key", "[", "0", ":", "12", "]", "key", "=", "derived_key", "[", "32", ":", "64", "]", "encrypted_key", "=", "base64", ".", "b64decode", "(", "encrypted_key_str", ")", ".", "hex", "(", ")", "mac_tag", "=", "bytes", ".", "fromhex", "(", "encrypted_key", "[", "64", ":", "96", "]", ")", "cipher_text", "=", "bytes", ".", "fromhex", "(", "encrypted_key", "[", "0", ":", "64", "]", ")", "private_key", "=", "AESHandler", ".", "aes_gcm_decrypt_with_iv", "(", "cipher_text", ",", "b58_address", ".", "encode", "(", ")", ",", "mac_tag", ",", "key", ",", "iv", ")", "if", "len", "(", "private_key", ")", "==", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "decrypt_encrypted_private_key_error", ")", "acct", "=", "Account", "(", "private_key", ",", "scheme", ")", "if", "acct", ".", "get_address", "(", ")", ".", "b58encode", "(", ")", "!=", "b58_address", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'Address error.'", ")", ")", "return", "private_key", ".", "hex", "(", ")" ]
This interface is used to decrypt an private key which has been encrypted. :param encrypted_key_str: an gcm encrypted private key in the form of string. :param password: the secret pass phrase to generate the keys from. :param b58_address: a base58 encode address which should be correspond with the private key. :param salt: a string to use for better protection from dictionary attacks. :param n: CPU/memory cost parameter. :param scheme: the signature scheme. :return: a private key in the form of string.
[ "This", "interface", "is", "used", "to", "decrypt", "an", "private", "key", "which", "has", "been", "encrypted", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/account/account.py#L133-L162
ontio/ontology-python-sdk
ontology/account/account.py
Account.export_wif
def export_wif(self) -> str: """ This interface is used to get export ECDSA private key in the form of WIF which is a way to encoding an ECDSA private key and make it easier to copy. :return: a WIF encode private key. """ data = b''.join([b'\x80', self.__private_key, b'\01']) checksum = Digest.hash256(data[0:34]) wif = base58.b58encode(b''.join([data, checksum[0:4]])) return wif.decode('ascii')
python
def export_wif(self) -> str: """ This interface is used to get export ECDSA private key in the form of WIF which is a way to encoding an ECDSA private key and make it easier to copy. :return: a WIF encode private key. """ data = b''.join([b'\x80', self.__private_key, b'\01']) checksum = Digest.hash256(data[0:34]) wif = base58.b58encode(b''.join([data, checksum[0:4]])) return wif.decode('ascii')
[ "def", "export_wif", "(", "self", ")", "->", "str", ":", "data", "=", "b''", ".", "join", "(", "[", "b'\\x80'", ",", "self", ".", "__private_key", ",", "b'\\01'", "]", ")", "checksum", "=", "Digest", ".", "hash256", "(", "data", "[", "0", ":", "34", "]", ")", "wif", "=", "base58", ".", "b58encode", "(", "b''", ".", "join", "(", "[", "data", ",", "checksum", "[", "0", ":", "4", "]", "]", ")", ")", "return", "wif", ".", "decode", "(", "'ascii'", ")" ]
This interface is used to get export ECDSA private key in the form of WIF which is a way to encoding an ECDSA private key and make it easier to copy. :return: a WIF encode private key.
[ "This", "interface", "is", "used", "to", "get", "export", "ECDSA", "private", "key", "in", "the", "form", "of", "WIF", "which", "is", "a", "way", "to", "encoding", "an", "ECDSA", "private", "key", "and", "make", "it", "easier", "to", "copy", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/account/account.py#L216-L226
ontio/ontology-python-sdk
ontology/account/account.py
Account.get_private_key_from_wif
def get_private_key_from_wif(wif: str) -> bytes: """ This interface is used to decode a WIF encode ECDSA private key. :param wif: a WIF encode private key. :return: a ECDSA private key in the form of bytes. """ if wif is None or wif is "": raise Exception("none wif") data = base58.b58decode(wif) if len(data) != 38 or data[0] != 0x80 or data[33] != 0x01: raise Exception("wif wrong") checksum = Digest.hash256(data[0:34]) for i in range(4): if data[len(data) - 4 + i] != checksum[i]: raise Exception("wif wrong") return data[1:33]
python
def get_private_key_from_wif(wif: str) -> bytes: """ This interface is used to decode a WIF encode ECDSA private key. :param wif: a WIF encode private key. :return: a ECDSA private key in the form of bytes. """ if wif is None or wif is "": raise Exception("none wif") data = base58.b58decode(wif) if len(data) != 38 or data[0] != 0x80 or data[33] != 0x01: raise Exception("wif wrong") checksum = Digest.hash256(data[0:34]) for i in range(4): if data[len(data) - 4 + i] != checksum[i]: raise Exception("wif wrong") return data[1:33]
[ "def", "get_private_key_from_wif", "(", "wif", ":", "str", ")", "->", "bytes", ":", "if", "wif", "is", "None", "or", "wif", "is", "\"\"", ":", "raise", "Exception", "(", "\"none wif\"", ")", "data", "=", "base58", ".", "b58decode", "(", "wif", ")", "if", "len", "(", "data", ")", "!=", "38", "or", "data", "[", "0", "]", "!=", "0x80", "or", "data", "[", "33", "]", "!=", "0x01", ":", "raise", "Exception", "(", "\"wif wrong\"", ")", "checksum", "=", "Digest", ".", "hash256", "(", "data", "[", "0", ":", "34", "]", ")", "for", "i", "in", "range", "(", "4", ")", ":", "if", "data", "[", "len", "(", "data", ")", "-", "4", "+", "i", "]", "!=", "checksum", "[", "i", "]", ":", "raise", "Exception", "(", "\"wif wrong\"", ")", "return", "data", "[", "1", ":", "33", "]" ]
This interface is used to decode a WIF encode ECDSA private key. :param wif: a WIF encode private key. :return: a ECDSA private key in the form of bytes.
[ "This", "interface", "is", "used", "to", "decode", "a", "WIF", "encode", "ECDSA", "private", "key", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/account/account.py#L229-L245
ontio/ontology-python-sdk
ontology/crypto/kdf.py
pbkdf2
def pbkdf2(seed: str or bytes, dk_len: int) -> bytes: """ Derive one key from a seed. :param seed: the secret pass phrase to generate the keys from. :param dk_len: the length in bytes of every derived key. :return: """ key = b'' index = 1 bytes_seed = str_to_bytes(seed) while len(key) < dk_len: key += Digest.sha256(b''.join([bytes_seed, index.to_bytes(4, 'big', signed=True)])) index += 1 return key[:dk_len]
python
def pbkdf2(seed: str or bytes, dk_len: int) -> bytes: """ Derive one key from a seed. :param seed: the secret pass phrase to generate the keys from. :param dk_len: the length in bytes of every derived key. :return: """ key = b'' index = 1 bytes_seed = str_to_bytes(seed) while len(key) < dk_len: key += Digest.sha256(b''.join([bytes_seed, index.to_bytes(4, 'big', signed=True)])) index += 1 return key[:dk_len]
[ "def", "pbkdf2", "(", "seed", ":", "str", "or", "bytes", ",", "dk_len", ":", "int", ")", "->", "bytes", ":", "key", "=", "b''", "index", "=", "1", "bytes_seed", "=", "str_to_bytes", "(", "seed", ")", "while", "len", "(", "key", ")", "<", "dk_len", ":", "key", "+=", "Digest", ".", "sha256", "(", "b''", ".", "join", "(", "[", "bytes_seed", ",", "index", ".", "to_bytes", "(", "4", ",", "'big'", ",", "signed", "=", "True", ")", "]", ")", ")", "index", "+=", "1", "return", "key", "[", ":", "dk_len", "]" ]
Derive one key from a seed. :param seed: the secret pass phrase to generate the keys from. :param dk_len: the length in bytes of every derived key. :return:
[ "Derive", "one", "key", "from", "a", "seed", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/crypto/kdf.py#L9-L23
ontio/ontology-python-sdk
ontology/core/program.py
ProgramBuilder.sort_public_keys
def sort_public_keys(pub_keys: List[bytes] or List[str]): """ :param pub_keys: a list of public keys in format of bytes. :return: sorted public keys. """ for index, key in enumerate(pub_keys): if isinstance(key, str): pub_keys[index] = bytes.fromhex(key) return sorted(pub_keys, key=ProgramBuilder.compare_pubkey)
python
def sort_public_keys(pub_keys: List[bytes] or List[str]): """ :param pub_keys: a list of public keys in format of bytes. :return: sorted public keys. """ for index, key in enumerate(pub_keys): if isinstance(key, str): pub_keys[index] = bytes.fromhex(key) return sorted(pub_keys, key=ProgramBuilder.compare_pubkey)
[ "def", "sort_public_keys", "(", "pub_keys", ":", "List", "[", "bytes", "]", "or", "List", "[", "str", "]", ")", ":", "for", "index", ",", "key", "in", "enumerate", "(", "pub_keys", ")", ":", "if", "isinstance", "(", "key", ",", "str", ")", ":", "pub_keys", "[", "index", "]", "=", "bytes", ".", "fromhex", "(", "key", ")", "return", "sorted", "(", "pub_keys", ",", "key", "=", "ProgramBuilder", ".", "compare_pubkey", ")" ]
:param pub_keys: a list of public keys in format of bytes. :return: sorted public keys.
[ ":", "param", "pub_keys", ":", "a", "list", "of", "public", "keys", "in", "format", "of", "bytes", ".", ":", "return", ":", "sorted", "public", "keys", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/core/program.py#L94-L102
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/abi/abi_function.py
AbiFunction.set_params_value
def set_params_value(self, *params): """ This interface is used to set parameter value for an function in abi file. """ if len(params) != len(self.parameters): raise Exception("parameter error") temp = self.parameters self.parameters = [] for i in range(len(params)): self.parameters.append(Parameter(temp[i]['name'], temp[i]['type'])) self.parameters[i].set_value(params[i])
python
def set_params_value(self, *params): """ This interface is used to set parameter value for an function in abi file. """ if len(params) != len(self.parameters): raise Exception("parameter error") temp = self.parameters self.parameters = [] for i in range(len(params)): self.parameters.append(Parameter(temp[i]['name'], temp[i]['type'])) self.parameters[i].set_value(params[i])
[ "def", "set_params_value", "(", "self", ",", "*", "params", ")", ":", "if", "len", "(", "params", ")", "!=", "len", "(", "self", ".", "parameters", ")", ":", "raise", "Exception", "(", "\"parameter error\"", ")", "temp", "=", "self", ".", "parameters", "self", ".", "parameters", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "params", ")", ")", ":", "self", ".", "parameters", ".", "append", "(", "Parameter", "(", "temp", "[", "i", "]", "[", "'name'", "]", ",", "temp", "[", "i", "]", "[", "'type'", "]", ")", ")", "self", ".", "parameters", "[", "i", "]", ".", "set_value", "(", "params", "[", "i", "]", ")" ]
This interface is used to set parameter value for an function in abi file.
[ "This", "interface", "is", "used", "to", "set", "parameter", "value", "for", "an", "function", "in", "abi", "file", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/abi/abi_function.py#L12-L22
ontio/ontology-python-sdk
ontology/smart_contract/neo_contract/abi/abi_function.py
AbiFunction.get_parameter
def get_parameter(self, param_name: str) -> Parameter: """ This interface is used to get a Parameter object from an AbiFunction object which contain given function parameter's name, type and value. :param param_name: a string used to indicate which parameter we want to get from AbiFunction. :return: a Parameter object which contain given function parameter's name, type and value. """ for p in self.parameters: if p.name == param_name: return p raise SDKException(ErrorCode.param_err('get parameter failed.'))
python
def get_parameter(self, param_name: str) -> Parameter: """ This interface is used to get a Parameter object from an AbiFunction object which contain given function parameter's name, type and value. :param param_name: a string used to indicate which parameter we want to get from AbiFunction. :return: a Parameter object which contain given function parameter's name, type and value. """ for p in self.parameters: if p.name == param_name: return p raise SDKException(ErrorCode.param_err('get parameter failed.'))
[ "def", "get_parameter", "(", "self", ",", "param_name", ":", "str", ")", "->", "Parameter", ":", "for", "p", "in", "self", ".", "parameters", ":", "if", "p", ".", "name", "==", "param_name", ":", "return", "p", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'get parameter failed.'", ")", ")" ]
This interface is used to get a Parameter object from an AbiFunction object which contain given function parameter's name, type and value. :param param_name: a string used to indicate which parameter we want to get from AbiFunction. :return: a Parameter object which contain given function parameter's name, type and value.
[ "This", "interface", "is", "used", "to", "get", "a", "Parameter", "object", "from", "an", "AbiFunction", "object", "which", "contain", "given", "function", "parameter", "s", "name", "type", "and", "value", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/abi/abi_function.py#L24-L35
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.unpack
def unpack(self, fmt, length=1): """ Unpack the stream contents according to the specified format in `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. length (int): amount of bytes to read. Returns: variable: the result according to the specified format. """ try: info = struct.unpack(fmt, self.stream.read(length))[0] except struct.error as e: raise SDKException(ErrorCode.unpack_error(e.args[0])) return info
python
def unpack(self, fmt, length=1): """ Unpack the stream contents according to the specified format in `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. length (int): amount of bytes to read. Returns: variable: the result according to the specified format. """ try: info = struct.unpack(fmt, self.stream.read(length))[0] except struct.error as e: raise SDKException(ErrorCode.unpack_error(e.args[0])) return info
[ "def", "unpack", "(", "self", ",", "fmt", ",", "length", "=", "1", ")", ":", "try", ":", "info", "=", "struct", ".", "unpack", "(", "fmt", ",", "self", ".", "stream", ".", "read", "(", "length", ")", ")", "[", "0", "]", "except", "struct", ".", "error", "as", "e", ":", "raise", "SDKException", "(", "ErrorCode", ".", "unpack_error", "(", "e", ".", "args", "[", "0", "]", ")", ")", "return", "info" ]
Unpack the stream contents according to the specified format in `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. length (int): amount of bytes to read. Returns: variable: the result according to the specified format.
[ "Unpack", "the", "stream", "contents", "according", "to", "the", "specified", "format", "in", "fmt", ".", "For", "more", "information", "about", "the", "fmt", "format", "see", ":", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", "/", "library", "/", "struct", ".", "html" ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L37-L53
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_byte
def read_byte(self, do_ord=True) -> int: """ Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred. """ try: if do_ord: return ord(self.stream.read(1)) else: return self.stream.read(1) except Exception as e: raise SDKException(ErrorCode.read_byte_error(e.args[0]))
python
def read_byte(self, do_ord=True) -> int: """ Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred. """ try: if do_ord: return ord(self.stream.read(1)) else: return self.stream.read(1) except Exception as e: raise SDKException(ErrorCode.read_byte_error(e.args[0]))
[ "def", "read_byte", "(", "self", ",", "do_ord", "=", "True", ")", "->", "int", ":", "try", ":", "if", "do_ord", ":", "return", "ord", "(", "self", ".", "stream", ".", "read", "(", "1", ")", ")", "else", ":", "return", "self", ".", "stream", ".", "read", "(", "1", ")", "except", "Exception", "as", "e", ":", "raise", "SDKException", "(", "ErrorCode", ".", "read_byte_error", "(", "e", ".", "args", "[", "0", "]", ")", ")" ]
Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred.
[ "Read", "a", "single", "byte", ".", "Args", ":", "do_ord", "(", "bool", ")", ":", "(", "default", "True", ")", "convert", "the", "byte", "to", "an", "ordinal", "first", ".", "Returns", ":", "bytes", ":", "a", "single", "byte", "if", "successful", ".", "0", "(", "int", ")", "if", "an", "exception", "occurred", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L55-L69
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_bytes
def read_bytes(self, length) -> bytes: """ Read the specified number of bytes from the stream. Args: length (int): number of bytes to read. Returns: bytes: `length` number of bytes. """ value = self.stream.read(length) return value
python
def read_bytes(self, length) -> bytes: """ Read the specified number of bytes from the stream. Args: length (int): number of bytes to read. Returns: bytes: `length` number of bytes. """ value = self.stream.read(length) return value
[ "def", "read_bytes", "(", "self", ",", "length", ")", "->", "bytes", ":", "value", "=", "self", ".", "stream", ".", "read", "(", "length", ")", "return", "value" ]
Read the specified number of bytes from the stream. Args: length (int): number of bytes to read. Returns: bytes: `length` number of bytes.
[ "Read", "the", "specified", "number", "of", "bytes", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L71-L82
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_float
def read_float(self, little_endian=True): """ Read 4 bytes as a float value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: float: """ if little_endian: endian = "<" else: endian = ">" return self.unpack("%sf" % endian, 4)
python
def read_float(self, little_endian=True): """ Read 4 bytes as a float value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: float: """ if little_endian: endian = "<" else: endian = ">" return self.unpack("%sf" % endian, 4)
[ "def", "read_float", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "\"%sf\"", "%", "endian", ",", "4", ")" ]
Read 4 bytes as a float value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: float:
[ "Read", "4", "bytes", "as", "a", "float", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L102-L116
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_double
def read_double(self, little_endian=True): """ Read 8 bytes as a double value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: float: """ if little_endian: endian = "<" else: endian = ">" return self.unpack("%sd" % endian, 8)
python
def read_double(self, little_endian=True): """ Read 8 bytes as a double value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: float: """ if little_endian: endian = "<" else: endian = ">" return self.unpack("%sd" % endian, 8)
[ "def", "read_double", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "\"%sd\"", "%", "endian", ",", "8", ")" ]
Read 8 bytes as a double value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: float:
[ "Read", "8", "bytes", "as", "a", "double", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L118-L132
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_int8
def read_int8(self, little_endian=True): """ Read 1 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sb' % endian)
python
def read_int8(self, little_endian=True): """ Read 1 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sb' % endian)
[ "def", "read_int8", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sb'", "%", "endian", ")" ]
Read 1 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "1", "byte", "as", "a", "signed", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L134-L148
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_uint8
def read_uint8(self, little_endian=True): """ Read 1 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sB' % endian)
python
def read_uint8(self, little_endian=True): """ Read 1 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sB' % endian)
[ "def", "read_uint8", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sB'", "%", "endian", ")" ]
Read 1 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "1", "byte", "as", "an", "unsigned", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L150-L164
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_int16
def read_int16(self, little_endian=True): """ Read 2 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sh' % endian, 2)
python
def read_int16(self, little_endian=True): """ Read 2 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sh' % endian, 2)
[ "def", "read_int16", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sh'", "%", "endian", ",", "2", ")" ]
Read 2 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "2", "byte", "as", "a", "signed", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L166-L180
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_uint16
def read_uint16(self, little_endian=True): """ Read 2 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sH' % endian, 2)
python
def read_uint16(self, little_endian=True): """ Read 2 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sH' % endian, 2)
[ "def", "read_uint16", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sH'", "%", "endian", ",", "2", ")" ]
Read 2 byte as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "2", "byte", "as", "an", "unsigned", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L182-L196
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_int32
def read_int32(self, little_endian=True): """ Read 4 bytes as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%si' % endian, 4)
python
def read_int32(self, little_endian=True): """ Read 4 bytes as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%si' % endian, 4)
[ "def", "read_int32", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%si'", "%", "endian", ",", "4", ")" ]
Read 4 bytes as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "4", "bytes", "as", "a", "signed", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L198-L212
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_uint32
def read_uint32(self, little_endian=True): """ Read 4 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sI' % endian, 4)
python
def read_uint32(self, little_endian=True): """ Read 4 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sI' % endian, 4)
[ "def", "read_uint32", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sI'", "%", "endian", ",", "4", ")" ]
Read 4 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "4", "bytes", "as", "an", "unsigned", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L214-L228
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_int64
def read_int64(self, little_endian=True): """ Read 8 bytes as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sq' % endian, 8)
python
def read_int64(self, little_endian=True): """ Read 8 bytes as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sq' % endian, 8)
[ "def", "read_int64", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sq'", "%", "endian", ",", "8", ")" ]
Read 8 bytes as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "8", "bytes", "as", "a", "signed", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L230-L244
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_uint64
def read_uint64(self, little_endian=True): """ Read 8 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sQ' % endian, 8)
python
def read_uint64(self, little_endian=True): """ Read 8 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" else: endian = ">" return self.unpack('%sQ' % endian, 8)
[ "def", "read_uint64", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sQ'", "%", "endian", ",", "8", ")" ]
Read 8 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
[ "Read", "8", "bytes", "as", "an", "unsigned", "integer", "value", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L246-L260
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_var_int
def read_var_int(self, max_size=sys.maxsize): """ Read a variable length integer from the stream. The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: max_size (int): (Optional) maximum number of bytes to read. Returns: int: """ fb = self.read_byte() if fb is 0: return fb if hex(fb) == '0xfd': value = self.read_uint16() elif hex(fb) == '0xfe': value = self.read_uint32() elif hex(fb) == '0xff': value = self.read_uint64() else: value = fb if value > max_size: raise SDKException(ErrorCode.param_err('Invalid format')) return int(value)
python
def read_var_int(self, max_size=sys.maxsize): """ Read a variable length integer from the stream. The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: max_size (int): (Optional) maximum number of bytes to read. Returns: int: """ fb = self.read_byte() if fb is 0: return fb if hex(fb) == '0xfd': value = self.read_uint16() elif hex(fb) == '0xfe': value = self.read_uint32() elif hex(fb) == '0xff': value = self.read_uint64() else: value = fb if value > max_size: raise SDKException(ErrorCode.param_err('Invalid format')) return int(value)
[ "def", "read_var_int", "(", "self", ",", "max_size", "=", "sys", ".", "maxsize", ")", ":", "fb", "=", "self", ".", "read_byte", "(", ")", "if", "fb", "is", "0", ":", "return", "fb", "if", "hex", "(", "fb", ")", "==", "'0xfd'", ":", "value", "=", "self", ".", "read_uint16", "(", ")", "elif", "hex", "(", "fb", ")", "==", "'0xfe'", ":", "value", "=", "self", ".", "read_uint32", "(", ")", "elif", "hex", "(", "fb", ")", "==", "'0xff'", ":", "value", "=", "self", ".", "read_uint64", "(", ")", "else", ":", "value", "=", "fb", "if", "value", ">", "max_size", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'Invalid format'", ")", ")", "return", "int", "(", "value", ")" ]
Read a variable length integer from the stream. The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: max_size (int): (Optional) maximum number of bytes to read. Returns: int:
[ "Read", "a", "variable", "length", "integer", "from", "the", "stream", ".", "The", "NEO", "network", "protocol", "supports", "encoded", "storage", "for", "space", "saving", ".", "See", ":", "http", ":", "//", "docs", ".", "neo", ".", "org", "/", "en", "-", "us", "/", "node", "/", "network", "-", "protocol", ".", "html#convention" ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L262-L286
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_var_bytes
def read_var_bytes(self, max_size=sys.maxsize) -> bytes: """ Read a variable length of bytes from the stream. Args: max_size (int): (Optional) maximum number of bytes to read. Returns: bytes: """ length = self.read_var_int(max_size) return self.read_bytes(length)
python
def read_var_bytes(self, max_size=sys.maxsize) -> bytes: """ Read a variable length of bytes from the stream. Args: max_size (int): (Optional) maximum number of bytes to read. Returns: bytes: """ length = self.read_var_int(max_size) return self.read_bytes(length)
[ "def", "read_var_bytes", "(", "self", ",", "max_size", "=", "sys", ".", "maxsize", ")", "->", "bytes", ":", "length", "=", "self", ".", "read_var_int", "(", "max_size", ")", "return", "self", ".", "read_bytes", "(", "length", ")" ]
Read a variable length of bytes from the stream. Args: max_size (int): (Optional) maximum number of bytes to read. Returns: bytes:
[ "Read", "a", "variable", "length", "of", "bytes", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L288-L299
ontio/ontology-python-sdk
ontology/io/binary_reader.py
BinaryReader.read_str
def read_str(self): """ Read a string from the stream. Returns: str: """ length = self.read_uint8() return self.unpack(str(length) + 's', length)
python
def read_str(self): """ Read a string from the stream. Returns: str: """ length = self.read_uint8() return self.unpack(str(length) + 's', length)
[ "def", "read_str", "(", "self", ")", ":", "length", "=", "self", ".", "read_uint8", "(", ")", "return", "self", ".", "unpack", "(", "str", "(", "length", ")", "+", "'s'", ",", "length", ")" ]
Read a string from the stream. Returns: str:
[ "Read", "a", "string", "from", "the", "stream", "." ]
train
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L301-L309