signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def dump(self, include_address=True, include_id=True) -> str:
d = {<EOL>'<STR_LIT>': self.keystore['<STR_LIT>'],<EOL>'<STR_LIT:version>': self.keystore['<STR_LIT:version>'],<EOL>}<EOL>if include_address and self.address is not None:<EOL><INDENT>d['<STR_LIT:address>'] = remove_0x_prefix(encode_hex(self.address))<EOL><DEDENT>if include_id and self.uuid is not None:<EOL><INDENT>d['<...
Dump the keystore for later disk storage. The result inherits the entries `'crypto'` and `'version`' from `account.keystore`, and adds `'address'` and `'id'` in accordance with the parameters `'include_address'` and `'include_id`'. If address or id are not known, they are not added, ev...
f9370:c2:m2
def unlock(self, password: str):
if self.locked:<EOL><INDENT>self._privkey = decode_keyfile_json(self.keystore, password.encode('<STR_LIT>'))<EOL>self.locked = False<EOL>self._fill_address()<EOL><DEDENT>
Unlock the account with a password. If the account is already unlocked, nothing happens, even if the password is wrong. Raises: ValueError: (originating in ethereum.keys) if the password is wrong (and the account is locked)
f9370:c2:m3
def lock(self):
self._privkey = None<EOL>self.locked = True<EOL>
Relock an unlocked account. This method sets `account.privkey` to `None` (unlike `account.address` which is preserved). After calling this method, both `account.privkey` and `account.pubkey` are `None. `account.address` stays unchanged, even if it has been derived from the private key.
f9370:c2:m4
@property<EOL><INDENT>def privkey(self) -> PrivateKey:<DEDENT>
if not self.locked:<EOL><INDENT>return self._privkey<EOL><DEDENT>return None<EOL>
The account's private key or `None` if the account is locked
f9370:c2:m6
@property<EOL><INDENT>def pubkey(self) -> PublicKey:<DEDENT>
if not self.locked:<EOL><INDENT>return privatekey_to_publickey(self.privkey)<EOL><DEDENT>return None<EOL>
The account's public key or `None` if the account is locked
f9370:c2:m7
@property<EOL><INDENT>def address(self):<DEDENT>
if not self._address:<EOL><INDENT>self._fill_address()<EOL><DEDENT>return self._address<EOL>
The account's address or `None` if the address is not stored in the key file and cannot be reconstructed (because the account is locked)
f9370:c2:m8
@property<EOL><INDENT>def uuid(self):<DEDENT>
try:<EOL><INDENT>return self.keystore['<STR_LIT:id>']<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>
An optional unique identifier, formatted according to UUID version 4, or `None` if the account does not have an id
f9370:c2:m9
@uuid.setter<EOL><INDENT>def uuid(self, value):<DEDENT>
if value is not None:<EOL><INDENT>self.keystore['<STR_LIT:id>'] = value<EOL><DEDENT>elif '<STR_LIT:id>' in self.keystore:<EOL><INDENT>self.keystore.pop('<STR_LIT:id>')<EOL><DEDENT>
Set the UUID. Set it to `None` in order to remove it.
f9370:c2:m10
def _redact_secret(<EOL>data: Union[Dict, List],<EOL>) -> Union[Dict, List]:
if isinstance(data, dict):<EOL><INDENT>stack = [data]<EOL><DEDENT>else:<EOL><INDENT>stack = []<EOL><DEDENT>while stack:<EOL><INDENT>current = stack.pop()<EOL>if '<STR_LIT>' in current:<EOL><INDENT>current['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>stack.extend(<EOL>value<EOL>for value in current.values()<...
Modify `data` in-place and replace keys named `secret`.
f9371:m0
def start(self):
assert self.stop_event.ready(), f'<STR_LIT>'<EOL>self.stop_event.clear()<EOL>self.greenlets = list()<EOL>self.ready_to_process_events = False <EOL>if self.database_dir is not None:<EOL><INDENT>self.db_lock.acquire(timeout=<NUM_LIT:0>)<EOL>assert self.db_lock.is_locked, f'<STR_LIT>'<EOL><DEDENT>if self.config['<STR_LIT...
Start the node synchronously. Raises directly if anything went wrong on startup
f9371:c1:m1
def _run(self, *args, **kwargs):
self.greenlet.name = f'<STR_LIT>'<EOL>try:<EOL><INDENT>self.stop_event.wait()<EOL><DEDENT>except gevent.GreenletExit: <EOL><INDENT>self.stop_event.set()<EOL>gevent.killall([self.alarm, self.transport]) <EOL>raise <EOL><DEDENT>except Exception:<EOL><INDENT>self.stop()<EOL>raise<EOL><DEDENT>
Busy-wait on long-lived subtasks/greenlets, re-raise if any error occurs
f9371:c1:m2
def stop(self):
if self.stop_event.ready(): <EOL><INDENT>return<EOL><DEDENT>self.stop_event.set()<EOL>self.transport.stop()<EOL>self.alarm.stop()<EOL>self.transport.join()<EOL>self.alarm.join()<EOL>self.blockchain_events.uninstall_all_event_listeners()<EOL>self.wal.storage.conn.close()<EOL>if self.db_lock is not None:<EOL><INDENT>sel...
Stop the node gracefully. Raise if any stop-time error occurred on any subtask
f9371:c1:m3
def add_pending_greenlet(self, greenlet: Greenlet):
def remove(_):<EOL><INDENT>self.greenlets.remove(greenlet)<EOL><DEDENT>self.greenlets.append(greenlet)<EOL>greenlet.link_exception(self.on_error)<EOL>greenlet.link_value(remove)<EOL>
Ensures an error on the passed greenlet crashes self/main greenlet.
f9371:c1:m6
def _start_transport(self, chain_state: ChainState):
assert self.alarm.is_primed(), f'<STR_LIT>'<EOL>assert self.ready_to_process_events, f'<STR_LIT>'<EOL>self.transport.start(<EOL>raiden_service=self,<EOL>message_handler=self.message_handler,<EOL>prev_auth_data=chain_state.last_transport_authdata,<EOL>)<EOL>for neighbour in views.all_neighbour_nodes(chain_state):<EOL><I...
Initialize the transport and related facilities. Note: The transport must not be started before the node has caught up with the blockchain through `AlarmTask.first_run()`. This synchronization includes the on-chain channel state and is necessary to reject new mes...
f9371:c1:m8
def _start_alarm_task(self):
assert self.ready_to_process_events, f'<STR_LIT>'<EOL>self.alarm.start()<EOL>
Start the alarm task. Note: The alarm task must be started only when processing events is allowed, otherwise side-effects of blockchain events will be ignored.
f9371:c1:m9
def handle_and_track_state_change(self, state_change: StateChange):
for greenlet in self.handle_state_change(state_change):<EOL><INDENT>self.add_pending_greenlet(greenlet)<EOL><DEDENT>
Dispatch the state change and does not handle the exceptions. When the method is used the exceptions are tracked and re-raised in the raiden service thread.
f9371:c1:m13
def handle_state_change(self, state_change: StateChange) -> List[Greenlet]:
assert self.wal, f'<STR_LIT>'<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.address),<EOL>state_change=_redact_secret(serialize.JSONSerializer.serialize(state_change)),<EOL>)<EOL>old_state = views.state_from_raiden(self)<EOL>raiden_event_list = self.wal.log_and_dispatch(state_change)<EOL>current_state = views.state...
Dispatch the state change and return the processing threads. Use this for error reporting, failures in the returned greenlets, should be re-raised using `gevent.joinall` with `raise_error=True`.
f9371:c1:m14
def handle_event(self, raiden_event: RaidenEvent) -> Greenlet:
return gevent.spawn(self._handle_event, raiden_event)<EOL>
Spawn a new thread to handle a Raiden event. This will spawn a new greenlet to handle each event, which is important for two reasons: - Blockchain transactions can be queued without interfering with each other. - The calling thread is free to do more work. This is specially ...
f9371:c1:m15
def start_health_check_for(self, node_address: Address):
if self.transport:<EOL><INDENT>self.transport.start_health_check(node_address)<EOL><DEDENT>
Start health checking `node_address`. This function is a noop during initialization, because health checking can be started as a side effect of some events (e.g. new channel). For these cases the healthcheck will be started by `start_neighbours_healthcheck`.
f9371:c1:m18
def _initialize_transactions_queues(self, chain_state: ChainState):
assert self.alarm.is_primed(), f'<STR_LIT>'<EOL>pending_transactions = views.get_pending_transactions(chain_state)<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>num_pending_transactions=len(pending_transactions),<EOL>node=pex(self.address),<EOL>)<EOL>for transaction in pending_transactions:<EOL><INDENT>try:<EOL><INDENT>self.raid...
Initialize the pending transaction queue from the previous run. Note: This will only send the transactions which don't have their side-effects applied. Transactions which another node may have sent already will be detected by the alarm task's first run and cleared ...
f9371:c1:m20
def _initialize_payment_statuses(self, chain_state: ChainState):
with self.payment_identifier_lock:<EOL><INDENT>for task in chain_state.payment_mapping.secrethashes_to_task.values():<EOL><INDENT>if not isinstance(task, InitiatorTask):<EOL><INDENT>continue<EOL><DEDENT>initiator = next(iter(task.manager_state.initiator_transfers.values()))<EOL>transfer = initiator.transfer<EOL>transfe...
Re-initialize targets_to_identifiers_to_statuses. Restore the PaymentStatus for any pending payment. This is not tied to a specific protocol message but to the lifecycle of a payment, i.e. the status is re-created if a payment itself has not completed.
f9371:c1:m21
def _initialize_messages_queues(self, chain_state: ChainState):
assert not self.transport, f'<STR_LIT>'<EOL>assert self.alarm.is_primed(), f'<STR_LIT>'<EOL>events_queues = views.get_all_messagequeues(chain_state)<EOL>for queue_identifier, event_queue in events_queues.items():<EOL><INDENT>self.start_health_check_for(queue_identifier.recipient)<EOL>for event in event_queue:<EOL><INDE...
Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transport processes network messages too quickly, queueing new messages...
f9371:c1:m22
def _initialize_monitoring_services_queue(self, chain_state: ChainState):
msg = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>assert not self.transport, msg<EOL>msg = (<EOL>'<STR_LIT>'<EOL>)<EOL>assert self.wal, msg<EOL>current_balance_proofs = views.detect_balance_proof_change(<EOL>old_state=ChainState(<EOL>pseudo_random_generator=chain_state.pseudo_random_generator,<EOL>block_number=GENESIS_...
Send the monitoring requests for all current balance proofs. Note: The node must always send the *received* balance proof to the monitoring service, *before* sending its own locked transfer forward. If the monitoring service is updated after, then the following c...
f9371:c1:m23
def _initialize_whitelists(self, chain_state: ChainState):
for neighbour in views.all_neighbour_nodes(chain_state):<EOL><INDENT>if neighbour == ConnectionManager.BOOTSTRAP_ADDR:<EOL><INDENT>continue<EOL><DEDENT>self.transport.whitelist(neighbour)<EOL><DEDENT>events_queues = views.get_all_messagequeues(chain_state)<EOL>for event_queue in events_queues.values():<EOL><INDENT>for ...
Whitelist neighbors and mediated transfer targets on transport
f9371:c1:m24
def sign(self, message: Message):
if not isinstance(message, SignedMessage):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr(message)))<EOL><DEDENT>message.sign(self.signer)<EOL>
Sign message inplace.
f9371:c1:m25
def mediated_transfer_async(<EOL>self,<EOL>token_network_identifier: TokenNetworkID,<EOL>amount: PaymentAmount,<EOL>target: TargetAddress,<EOL>identifier: PaymentID,<EOL>fee: FeeAmount = MEDIATION_FEE,<EOL>secret: Secret = None,<EOL>secret_hash: SecretHash = None,<EOL>) -> PaymentStatus:
if secret is None:<EOL><INDENT>if secret_hash is None:<EOL><INDENT>secret = random_secret()<EOL><DEDENT>else:<EOL><INDENT>secret = EMPTY_SECRET<EOL><DEDENT><DEDENT>payment_status = self.start_mediated_transfer_with_secret(<EOL>token_network_identifier=token_network_identifier,<EOL>amount=amount,<EOL>fee=fee,<EOL>target...
Transfer `amount` between this node and `target`. This method will start an asynchronous transfer, the transfer might fail or succeed depending on a couple of factors: - Existence of a path that can be used, through the usage of direct or intermediary channels. - ...
f9371:c1:m28
def solidity_resolve_address(hex_code, library_symbol, library_address):
if library_address.startswith('<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>decode_hex(library_address)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>if len(library_symbol) != <NUM_LIT> or len(library_address) != <NUM_LIT>:<EOL><INDENT>ra...
Change the bytecode to use the given library address. Args: hex_code (bin): The bytecode encoded in hexadecimal. library_name (str): The library that will be resolved. library_address (str): The address of the library. Returns: bin: The bytecode encoded in hexadecimal with the ...
f9372:m0
def solidity_library_symbol(library_name):
<EOL>length = min(len(library_name), <NUM_LIT>)<EOL>library_piece = library_name[:length]<EOL>hold_piece = '<STR_LIT:_>' * (<NUM_LIT> - length)<EOL>return '<STR_LIT>'.format(<EOL>library=library_piece,<EOL>hold=hold_piece,<EOL>)<EOL>
Return the symbol used in the bytecode to represent the `library_name`.
f9372:m2
def solidity_unresolved_symbols(hex_code):
return set(re.findall(r"<STR_LIT>", hex_code))<EOL>
Return the unresolved symbols contained in the `hex_code`. Note: The binary representation should not be provided since this function relies on the fact that the '_' is invalid in hex encoding. Args: hex_code (str): The bytecode encoded as hexadecimal.
f9372:m3
def compile_files_cwd(*args, **kwargs):
<EOL>compile_wd = os.path.commonprefix(args[<NUM_LIT:0>])<EOL>if os.path.isfile(compile_wd):<EOL><INDENT>compile_wd = os.path.dirname(compile_wd)<EOL><DEDENT>if compile_wd[-<NUM_LIT:1>] != '<STR_LIT:/>':<EOL><INDENT>compile_wd += '<STR_LIT:/>'<EOL><DEDENT>file_list = [<EOL>x.replace(compile_wd, '<STR_LIT>')<EOL>for x i...
change working directory to contract's dir in order to avoid symbol name conflicts
f9372:m4
def eth_sign_sha3(data: bytes) -> bytes:
prefix = b'<STR_LIT>'<EOL>if not data.startswith(prefix):<EOL><INDENT>data = prefix + b'<STR_LIT>' % (len(data), data)<EOL><DEDENT>return keccak(data)<EOL>
eth_sign/recover compatible hasher Prefixes data with "\x19Ethereum Signed Message:\n<len(data)>"
f9374:m0
def recover(<EOL>data: bytes,<EOL>signature: Signature,<EOL>hasher: Callable[[bytes], bytes] = eth_sign_sha3,<EOL>) -> Address:
_hash = hasher(data)<EOL>if signature[-<NUM_LIT:1>] >= <NUM_LIT>: <EOL><INDENT>signature = Signature(signature[:-<NUM_LIT:1>] + bytes([signature[-<NUM_LIT:1>] - <NUM_LIT>]))<EOL><DEDENT>try:<EOL><INDENT>sig = keys.Signature(signature_bytes=signature)<EOL>public_key = keys.ecdsa_recover(message_hash=_hash, signature=si...
eth_recover address from data hash and signature
f9374:m1
@abstractmethod<EOL><INDENT>def sign(self, data: bytes, v: int = <NUM_LIT>) -> Signature:<DEDENT>
pass<EOL>
Sign data hash (as of EIP191) with this Signer's account
f9374:c0:m0
def sign(self, data: bytes, v: int = <NUM_LIT>) -> Signature:
assert v in (<NUM_LIT:0>, <NUM_LIT>), '<STR_LIT>'<EOL>_hash = eth_sign_sha3(data)<EOL>signature = self.private_key.sign_msg_hash(message_hash=_hash)<EOL>sig_bytes = signature.to_bytes()<EOL>return sig_bytes[:-<NUM_LIT:1>] + bytes([sig_bytes[-<NUM_LIT:1>] + v])<EOL>
Sign data hash with local private key
f9374:c1:m1
def apply_config_file(<EOL>command_function: Union[click.Command, click.Group],<EOL>cli_params: Dict[str, Any],<EOL>ctx,<EOL>config_file_option_name='<STR_LIT>',<EOL>):
paramname_to_param = {param.name: param for param in command_function.params}<EOL>path_params = {<EOL>param.name<EOL>for param in command_function.params<EOL>if isinstance(param.type, (click.Path, click.File))<EOL>}<EOL>config_file_path = Path(cli_params[config_file_option_name])<EOL>config_file_values = dict()<EOL>try...
Applies all options set in the config file to `cli_params`
f9376:m4
def get_matrix_servers(url: str) -> List[str]:
try:<EOL><INDENT>response = requests.get(url)<EOL>if response.status_code != <NUM_LIT:200>:<EOL><INDENT>raise requests.RequestException('<STR_LIT>')<EOL><DEDENT><DEDENT>except requests.RequestException as ex:<EOL><INDENT>raise RuntimeError(f'<STR_LIT>') from ex<EOL><DEDENT>available_servers = []<EOL>for line in respons...
Fetch a list of matrix servers from a text url '-' prefixes (YAML list) are cleaned. Comment lines /^\\s*#/ are ignored url: url of a text file returns: list of urls, default schema is https
f9376:m5
def write_dl(self, rows, col_max=<NUM_LIT:30>, col_spacing=<NUM_LIT:2>, widths=None):
rows = list(rows)<EOL>if widths is None:<EOL><INDENT>widths = measure_table(rows)<EOL><DEDENT>if len(widths) != <NUM_LIT:2>:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>first_col = min(widths[<NUM_LIT:0>], col_max) + col_spacing<EOL>for first, second in iter_rows(rows, len(widths)):<EOL><INDENT>self.write('<ST...
Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and ...
f9376:c0:m0
def make_context(self, info_name, args, parent=None, **extra):
for key, value in iter(self.context_settings.items()):<EOL><INDENT>if key not in extra:<EOL><INDENT>extra[key] = value<EOL><DEDENT><DEDENT>ctx = Context(self, info_name=info_name, parent=parent, **extra)<EOL>with ctx.scope(cleanup=False):<EOL><INDENT>self.parse_args(ctx, args)<EOL><DEDENT>return ctx<EOL>
This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name for the script or ...
f9376:c2:m0
def start(self):
if self.greenlet:<EOL><INDENT>raise RuntimeError(f'<STR_LIT>')<EOL><DEDENT>pristine = (<EOL>not self.greenlet.dead and<EOL>tuple(self.greenlet.args) == tuple(self.args) and<EOL>self.greenlet.kwargs == self.kwargs<EOL>)<EOL>if not pristine:<EOL><INDENT>self.greenlet = Greenlet(self._run, *self.args, **self.kwargs)<EOL>s...
Synchronously start task Reimplements in children an call super().start() at end to start _run() Start-time exceptions may be raised
f9377:c0:m1
def _run(self, *args, **kwargs):
raise NotImplementedError<EOL>
Reimplements in children to busy wait here This busy wait should be finished gracefully after stop(), or be killed and re-raise on subtasks exception
f9377:c0:m2
def stop(self):
raise NotImplementedError<EOL>
Synchronous stop, gracefully tells _run() to exit Should wait subtasks to finish. Stop-time exceptions may be raised, run exceptions should not (accessible via get())
f9377:c0:m3
def on_error(self, subtask: Greenlet):
log.error(<EOL>'<STR_LIT>',<EOL>this=self,<EOL>running=bool(self),<EOL>subtask=subtask,<EOL>exc=subtask.exception,<EOL>)<EOL>if not self.greenlet:<EOL><INDENT>return<EOL><DEDENT>self.greenlet.kill(subtask.exception)<EOL>
Default callback for substasks link_exception Default callback re-raises the exception inside _run()
f9377:c0:m4
def decode_event(abi: Dict, log: Dict):
if isinstance(log['<STR_LIT>'][<NUM_LIT:0>], str):<EOL><INDENT>log['<STR_LIT>'][<NUM_LIT:0>] = decode_hex(log['<STR_LIT>'][<NUM_LIT:0>])<EOL><DEDENT>elif isinstance(log['<STR_LIT>'][<NUM_LIT:0>], int):<EOL><INDENT>log['<STR_LIT>'][<NUM_LIT:0>] = decode_hex(hex(log['<STR_LIT>'][<NUM_LIT:0>]))<EOL><DEDENT>event_id = log[...
Helper function to unpack event data using a provided ABI Args: abi: The ABI of the contract, not the ABI of the event log: The raw event data Returns: The decoded event
f9378:m2
def put(self, item):
self._queue.put(item)<EOL>self.set()<EOL>
Add new item to the queue.
f9380:c0:m1
def get(self, block=True, timeout=None):
value = self._queue.get(block, timeout)<EOL>if self._queue.empty():<EOL><INDENT>self.clear()<EOL><DEDENT>return value<EOL>
Removes and returns an item from the queue.
f9380:c0:m2
def copy(self):
copy = self._queue.copy()<EOL>result = list()<EOL>while not copy.empty():<EOL><INDENT>result.append(copy.get_nowait())<EOL><DEDENT>return result<EOL>
Copies the current queue items.
f9380:c0:m5
def random_secret() -> Secret:
while True:<EOL><INDENT>secret = os.urandom(<NUM_LIT:32>)<EOL>if secret != constants.EMPTY_HASH:<EOL><INDENT>return Secret(secret)<EOL><DEDENT><DEDENT>
Return a random 32 byte secret except the 0 secret since it's not accepted in the contracts
f9382:m0
def address_checksum_and_decode(addr: str) -> Address:
if not is_0x_prefixed(addr):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not is_checksum_address(addr):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>addr_bytes = decode_hex(addr)<EOL>assert len(addr_bytes) in (<NUM_LIT:20>, <NUM_LIT:0>)<EOL>return Address(addr_bytes)<EOL>
Accepts a string address and turns it into binary. Makes sure that the string address provided starts is 0x prefixed and checksummed according to EIP55 specification
f9382:m3
def quantity_encoder(i: int) -> str:
return hex(i).rstrip('<STR_LIT:L>')<EOL>
Encode integer quantity `data`.
f9382:m6
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
if not ishash(private_key_bin):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return keys.PrivateKey(private_key_bin).public_key.to_bytes()<EOL>
Returns public key in bitcoins 'bin' encoding.
f9382:m11
def get_system_spec() -> Dict[str, str]:
import pkg_resources<EOL>import platform<EOL>if sys.platform == '<STR_LIT>':<EOL><INDENT>system_info = '<STR_LIT>'.format(<EOL>platform.mac_ver()[<NUM_LIT:0>],<EOL>platform.architecture()[<NUM_LIT:0>],<EOL>)<EOL><DEDENT>else:<EOL><INDENT>system_info = '<STR_LIT>'.format(<EOL>platform.system(),<EOL>'<STR_LIT:_>'.join(pa...
Collect information about the system and installation.
f9382:m15
def wait_until(func, wait_for=None, sleep_for=<NUM_LIT:0.5>):
res = func()<EOL>if res:<EOL><INDENT>return res<EOL><DEDENT>if wait_for:<EOL><INDENT>deadline = time.time() + wait_for<EOL>while not res and time.time() <= deadline:<EOL><INDENT>gevent.sleep(sleep_for)<EOL>res = func()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while not res:<EOL><INDENT>gevent.sleep(sleep_for)<EOL>res = fu...
Test for a function and wait for it to return a truth value or to timeout. Returns the value or None if a timeout is given and the function didn't return inside time timeout Args: func (callable): a function to be evaluated, use lambda if parameters are required wait_for (float, integer, Non...
f9382:m16
def split_in_pairs(arg: Iterable) -> Iterable[Tuple]:
<EOL>iterator = iter(arg)<EOL>return zip_longest(iterator, iterator)<EOL>
Split given iterable in pairs [a, b, c, d, e] -> [(a, b), (c, d), (e, None)]
f9382:m18
def create_default_identifier():
return random.randint(<NUM_LIT:0>, constants.UINT64_MAX)<EOL>
Generates a random identifier.
f9382:m19
def merge_dict(to_update: dict, other_dict: dict):
for key, value in other_dict.items():<EOL><INDENT>has_map = (<EOL>isinstance(value, collections.Mapping) and<EOL>isinstance(to_update.get(key, None), collections.Mapping)<EOL>)<EOL>if has_map:<EOL><INDENT>merge_dict(to_update[key], value)<EOL><DEDENT>else:<EOL><INDENT>to_update[key] = value<EOL><DEDENT><DEDENT>
merges b into a
f9382:m20
def safe_gas_limit(*estimates: int) -> int:
assert None not in estimates, '<STR_LIT>'<EOL>calculated_limit = max(estimates)<EOL>return int(calculated_limit * constants.GAS_FACTOR)<EOL>
Calculates a safe gas limit for a number of gas estimates including a security margin
f9382:m22
def to_rdn(rei: int) -> float:
return rei / <NUM_LIT:10> ** <NUM_LIT><EOL>
Convert REI value to RDN.
f9382:m23
def block_specification_to_number(block: BlockSpecification, web3: Web3) -> BlockNumber:
if isinstance(block, str):<EOL><INDENT>msg = f"<STR_LIT>"<EOL>assert block in ('<STR_LIT>', '<STR_LIT>'), msg<EOL>number = web3.eth.getBlock(block)['<STR_LIT>']<EOL><DEDENT>elif isinstance(block, T_BlockHash):<EOL><INDENT>number = web3.eth.getBlock(block)['<STR_LIT>']<EOL><DEDENT>elif isinstance(block, T_BlockNumber):<...
Converts a block specification to an actual block number
f9382:m24
def get_db_version(db_filename: Path) -> int:
assert os.path.exists(db_filename)<EOL>conn = sqlite3.connect(<EOL>str(db_filename),<EOL>detect_types=sqlite3.PARSE_DECLTYPES,<EOL>)<EOL>cursor = conn.cursor()<EOL>try:<EOL><INDENT>cursor.execute('<STR_LIT>')<EOL>result = cursor.fetchone()<EOL><DEDENT>except sqlite3.OperationalError:<EOL><INDENT>raise RuntimeError(<EOL...
Return the version value stored in the db
f9383:m3
def after_start_check(self):
try:<EOL><INDENT>if self.url.scheme == '<STR_LIT:http>':<EOL><INDENT>conn = HTTPConnection(self.host, self.port)<EOL><DEDENT>elif self.url.scheme == '<STR_LIT>':<EOL><INDENT>ssl_context = None<EOL>if not self.verify_tls:<EOL><INDENT>ssl_context = ssl._create_unverified_context()<EOL><DEDENT>conn = HTTPSConnection(<EOL>...
Check if defined URL returns expected status to a <method> request.
f9384:c0:m1
def start(self):
if self.pre_start_check():<EOL><INDENT>raise AlreadyRunning(self)<EOL><DEDENT>if self.process is None:<EOL><INDENT>command = self.command<EOL>if not self._shell:<EOL><INDENT>command = self.command_parts<EOL><DEDENT>if isinstance(self.stdio, (list, tuple)):<EOL><INDENT>stdin, stdout, stderr = self.stdio<EOL><DEDENT>else...
Reimplements Executor and SimpleExecutor start to allow setting stdin/stdout/stderr/cwd It may break input/output/communicate, but will ensure child output redirects won't break parent process by filling the PIPE. Also, catches ProcessExitedWithError and raise FileNotFoundError if exitcode was 127
f9384:c0:m2
def running(self) -> bool:
return super().running() or self.pre_start_check()<EOL>
Include pre_start_check in running, so stop will wait for the underlying listener
f9384:c0:m3
def pack_data(abi_types, values) -> bytes:
if len(abi_types) != len(values):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(len(abi_types), len(values)),<EOL>)<EOL><DEDENT>normalized_values = map_abi_data([abi_address_to_hex], abi_types, values)<EOL>return decode_hex('<STR_LIT>'.join(<EOL>remove_0x_prefix(hex_encode_abi_type(abi_type, valu...
Normalize data and pack them into a byte array
f9385:m0
def echo_node_alarm_callback(self, block_number):
if not self.ready.is_set():<EOL><INDENT>self.ready.set()<EOL><DEDENT>log.debug('<STR_LIT>', block_number=block_number)<EOL>if self.stop_signal is not None:<EOL><INDENT>return REMOVE_CALLBACK<EOL><DEDENT>else:<EOL><INDENT>self.greenlets.add(gevent.spawn(self.poll_all_received_events))<EOL>return True<EOL><DEDENT>
This can be registered with the raiden AlarmTask. If `EchoNode.stop()` is called, it will give the return signal to be removed from the AlarmTask callbacks.
f9386:c0:m1
def poll_all_received_events(self):
locked = False<EOL>try:<EOL><INDENT>with Timeout(<NUM_LIT:10>):<EOL><INDENT>locked = self.lock.acquire(blocking=False)<EOL>if not locked:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>received_transfers = self.api.get_raiden_events_payment_history(<EOL>token_address=self.token_address,<EOL>offset=self.last_poll_offs...
This will be triggered once for each `echo_node_alarm_callback`. It polls all channels for `EventPaymentReceivedSuccess` events, adds all new events to the `self.received_transfers` queue and respawns `self.echo_node_worker`, if it died.
f9386:c0:m2
def echo_worker(self):
log.debug('<STR_LIT>', qsize=self.received_transfers.qsize())<EOL>while self.stop_signal is None:<EOL><INDENT>if self.received_transfers.qsize() > <NUM_LIT:0>:<EOL><INDENT>transfer = self.received_transfers.get()<EOL>if transfer in self.seen_transfers:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>initiator=pex(transfer....
The `echo_worker` works through the `self.received_transfers` queue and spawns `self.on_transfer` greenlets for all not-yet-seen transfers.
f9386:c0:m3
def on_transfer(self, transfer):
echo_amount = <NUM_LIT:0><EOL>if transfer.amount % <NUM_LIT:3> == <NUM_LIT:0>:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>initiator=pex(transfer.initiator),<EOL>amount=transfer.amount,<EOL>identifier=transfer.identifier,<EOL>)<EOL>echo_amount = transfer.amount - <NUM_LIT:1><EOL><DEDENT>elif transfer.amount == <NUM_LIT:...
This handles the echo logic, as described in https://github.com/raiden-network/raiden/issues/651: - for transfers with an amount that satisfies `amount % 3 == 0`, it sends a transfer with an amount of `amount - 1` back to the initiator - for transfers with a "lucky number" a...
f9386:c0:m4
def has_enough_gas_reserve(<EOL>raiden,<EOL>channels_to_open: int = <NUM_LIT:0>,<EOL>) -> Tuple[bool, int]:
secure_reserve_estimate = get_reserve_estimate(raiden, channels_to_open)<EOL>current_account_balance = raiden.chain.client.balance(raiden.chain.client.address)<EOL>return secure_reserve_estimate <= current_account_balance, secure_reserve_estimate<EOL>
Checks if the account has enough balance to handle the lifecycles of all open channels as well as the to be created channels. Note: This is just an estimation. Args: raiden: A raiden service instance channels_to_open: The number of new channels that should be opened Returns: T...
f9387:m4
@parser.error_handler<EOL>def handle_request_parsing_error(<EOL>err,<EOL>_req,<EOL>_schema,<EOL>_err_status_code,<EOL>_err_headers,<EOL>):
abort(HTTPStatus.BAD_REQUEST, errors=err.messages)<EOL>
This handles request parsing errors generated for example by schema field validation failing.
f9390:m2
def hexbytes_to_str(map_: Dict):
for k, v in map_.items():<EOL><INDENT>if isinstance(v, HexBytes):<EOL><INDENT>map_[k] = encode_hex(v)<EOL><DEDENT><DEDENT>
Converts values that are of type `HexBytes` to strings.
f9390:m4
def encode_byte_values(map_: Dict):
for k, v in map_.items():<EOL><INDENT>if isinstance(v, bytes):<EOL><INDENT>map_[k] = encode_hex(v)<EOL><DEDENT><DEDENT>
Converts values that are of type `bytes` to strings.
f9390:m5
def normalize_events_list(old_list):
new_list = []<EOL>for _event in old_list:<EOL><INDENT>new_event = dict(_event)<EOL>if new_event.get('<STR_LIT:args>'):<EOL><INDENT>new_event['<STR_LIT:args>'] = dict(new_event['<STR_LIT:args>'])<EOL>encode_byte_values(new_event['<STR_LIT:args>'])<EOL><DEDENT>if new_event.get('<STR_LIT>'):<EOL><INDENT>del new_event['<ST...
Internally the `event_type` key is prefixed with underscore but the API returns an object without that prefix
f9390:m7
def unhandled_exception(self, exception: Exception):
log.critical(<EOL>'<STR_LIT>',<EOL>exc_info=True,<EOL>node=pex(self.rest_api.raiden_api.address),<EOL>)<EOL>self.greenlet.kill(exception)<EOL>return api_error([str(exception)], HTTPStatus.INTERNAL_SERVER_ERROR)<EOL>
Flask.errorhandler when an exception wasn't correctly handled
f9390:c0:m6
def get_connection_managers_info(self, registry_address: typing.PaymentNetworkID):
log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden_api.address),<EOL>registry_address=to_checksum_address(registry_address),<EOL>)<EOL>connection_managers = dict()<EOL>for token in self.raiden_api.get_tokens_list(registry_address):<EOL><INDENT>token_network_identifier = views.get_token_network_identifier_by_token_add...
Get a dict whose keys are token addresses and whose values are open channels, funds of last request, sum of deposits and number of channels
f9390:c1:m6
def get(self):
return self.rest_api.get_channel_list(<EOL>self.rest_api.raiden_api.raiden.default_registry.address,<EOL>)<EOL>
this translates to 'get all channels the node is connected with'
f9392:c2:m0
def get(self, **kwargs):
return self.rest_api.get_channel_list(<EOL>registry_address=self.rest_api.raiden_api.raiden.default_registry.address,<EOL>**kwargs,<EOL>)<EOL>
this translates to 'get all channels the node is connected to for the given token address'
f9392:c3:m0
def get(self):
return self.rest_api.get_tokens_list(<EOL>self.rest_api.raiden_api.raiden.default_registry.address,<EOL>)<EOL>
this translates to 'get all token addresses we have channels open for'
f9392:c5:m0
@staticmethod<EOL><INDENT>def get_total_deposit(channel_state):<DEDENT>
return channel_state.our_total_deposit<EOL>
Return our total deposit in the contract for this channel
f9393:c13:m3
def event_filter_for_payments(<EOL>event: architecture.Event,<EOL>token_network_identifier: TokenNetworkID = None,<EOL>partner_address: Address = None,<EOL>) -> bool:
is_matching_event = (<EOL>isinstance(event, EVENTS_PAYMENT_HISTORY_RELATED) and<EOL>(<EOL>token_network_identifier is None or<EOL>token_network_identifier == event.token_network_identifier<EOL>)<EOL>)<EOL>if not is_matching_event:<EOL><INDENT>return False<EOL><DEDENT>sent_and_target_matches = (<EOL>isinstance(event, (E...
Filters out non payment history related events - If no other args are given, all payment related events match - If a token network identifier is given then only payment events for that match - If a partner is also given then if the event is a payment sent event and the target matches it's returned. I...
f9394:m0
def token_network_register(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>channel_participant_deposit_limit: TokenAmount,<EOL>token_network_deposit_limit: TokenAmount,<EOL>retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,<EOL>) -> TokenNetworkAddress:
if not is_binary_address(registry_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if token_address in self.get_tokens_list(registry_address):<EOL><INDENT>raise AlreadyRegisteredTokenAddress('<STR_LIT>'...
Register the `token_address` in the blockchain. If the address is already registered but the event has not been processed this function will block until the next block to make sure the event is processed. Raises: InvalidAddress: If the registry_address or token_address is not ...
f9394:c0:m3
def token_network_connect(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>funds: TokenAmount,<EOL>initial_channel_target: int = <NUM_LIT:3>,<EOL>joinable_funds_target: float = <NUM_LIT>,<EOL>) -> None:
if not is_binary_address(registry_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>token_network_identifier = views.get_token_network_identifier_by_token_address(<EOL>chain_state=views.state_from_raiden...
Automatically maintain channels open for the given token network. Args: token_address: the ERC20 token network to connect to. funds: the amount of funds that can be used by the ConnectionMananger. initial_channel_target: number of channels to open proactively. jo...
f9394:c0:m4
def token_network_leave(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>) -> List[NettingChannelState]:
if not is_binary_address(registry_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if token_address not in self.get_tokens_list(registry_address):<EOL><INDENT>raise UnknownTokenAddress('<STR_LIT>')<EOL>...
Close all channels and wait for settlement.
f9394:c0:m5
def channel_open(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>partner_address: Address,<EOL>settle_timeout: BlockTimeout = None,<EOL>retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,<EOL>) -> ChannelID:
if settle_timeout is None:<EOL><INDENT>settle_timeout = self.raiden.config['<STR_LIT>']<EOL><DEDENT>if settle_timeout < self.raiden.config['<STR_LIT>'] * <NUM_LIT:2>:<EOL><INDENT>raise InvalidSettleTimeout(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>if not is_binary_address(registry_address):<EOL><INDENT>raise InvalidAddress('...
Open a channel with the peer at `partner_address` with the given `token_address`.
f9394:c0:m6
def set_total_channel_deposit(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>partner_address: Address,<EOL>total_deposit: TokenAmount,<EOL>retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,<EOL>):
chain_state = views.state_from_raiden(self.raiden)<EOL>token_addresses = views.get_token_identifiers(<EOL>chain_state,<EOL>registry_address,<EOL>)<EOL>channel_state = views.get_channelstate_for(<EOL>chain_state=chain_state,<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>partner_address=pa...
Set the `total_deposit` in the channel with the peer at `partner_address` and the given `token_address` in order to be able to do transfers. Raises: InvalidAddress: If either token_address or partner_address is not 20 bytes long. TransactionThrew: May happen for ...
f9394:c0:m7
def channel_close(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>partner_address: Address,<EOL>retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,<EOL>):
self.channel_batch_close(<EOL>registry_address=registry_address,<EOL>token_address=token_address,<EOL>partner_addresses=[partner_address],<EOL>retry_timeout=retry_timeout,<EOL>)<EOL>
Close a channel opened with `partner_address` for the given `token_address`. Race condition, this can fail if channel was closed externally.
f9394:c0:m8
def channel_batch_close(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>partner_addresses: List[Address],<EOL>retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,<EOL>):
if not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not all(map(is_binary_address, partner_addresses)):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>valid_tokens = views.get_token_identifiers(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>paymen...
Close a channel opened with `partner_address` for the given `token_address`. Race condition, this can fail if channel was closed externally.
f9394:c0:m9
def get_channel_list(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress = None,<EOL>partner_address: Address = None,<EOL>) -> List[NettingChannelState]:
if registry_address and not is_binary_address(registry_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if token_address and not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if partner_address:<EOL><INDENT>if not is_binary_address(partner_address):<EOL><...
Returns a list of channels associated with the optionally given `token_address` and/or `partner_address`. Args: token_address: an optionally provided token address partner_address: an optionally provided partner address Return: A list containing all chann...
f9394:c0:m10
def get_node_network_state(self, node_address: Address):
return views.get_node_network_status(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>node_address=node_address,<EOL>)<EOL>
Returns the currently network status of `node_address`.
f9394:c0:m11
def start_health_check_for(self, node_address: Address):
self.raiden.start_health_check_for(node_address)<EOL>
Returns the currently network status of `node_address`.
f9394:c0:m12
def get_tokens_list(self, registry_address: PaymentNetworkID):
tokens_list = views.get_token_identifiers(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=registry_address,<EOL>)<EOL>return tokens_list<EOL>
Returns a list of tokens the node knows about
f9394:c0:m13
def transfer_and_wait(<EOL>self,<EOL>registry_address: PaymentNetworkID,<EOL>token_address: TokenAddress,<EOL>amount: TokenAmount,<EOL>target: Address,<EOL>identifier: PaymentID = None,<EOL>transfer_timeout: int = None,<EOL>secret: Secret = None,<EOL>secret_hash: SecretHash = None,<EOL>):
<EOL>payment_status = self.transfer_async(<EOL>registry_address=registry_address,<EOL>token_address=token_address,<EOL>amount=amount,<EOL>target=target,<EOL>identifier=identifier,<EOL>secret=secret,<EOL>secret_hash=secret_hash,<EOL>)<EOL>payment_status.payment_done.wait(timeout=transfer_timeout)<EOL>return payment_stat...
Do a transfer with `target` with the given `amount` of `token_address`.
f9394:c0:m15
def create_monitoring_request(<EOL>self,<EOL>balance_proof: BalanceProofSignedState,<EOL>reward_amount: TokenAmount,<EOL>) -> Optional[RequestMonitoring]:
<EOL>monitor_request = RequestMonitoring.from_balance_proof_signed_state(<EOL>balance_proof=balance_proof,<EOL>reward_amount=reward_amount,<EOL>)<EOL>monitor_request.sign(self.raiden.signer)<EOL>return monitor_request<EOL>
This method can be used to create a `RequestMonitoring` message. It will contain all data necessary for an external monitoring service to - send an updateNonClosingBalanceProof transaction to the TokenNetwork contract, for the `balance_proof` that we received from a channel partner. - cl...
f9394:c0:m23
def from_dict_hook(data):
type_ = data.get('<STR_LIT>', None)<EOL>if type_ is not None:<EOL><INDENT>klass = _import_type(type_)<EOL>msg = '<STR_LIT>'<EOL>assert hasattr(klass, '<STR_LIT>'), msg<EOL>return klass.from_dict(data)<EOL><DEDENT>return data<EOL>
Decode internal objects encoded using `to_dict_hook`. This automatically imports the class defined in the `_type` metadata field, and calls the `from_dict` method hook to instantiate an object of that class. Note: Because this function will do automatic module loading it's really impor...
f9395:m1
def to_dict_hook(obj):
if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>result = obj.to_dict()<EOL>assert isinstance(result, dict), '<STR_LIT>'<EOL>result['<STR_LIT>'] = f'<STR_LIT>'<EOL>result['<STR_LIT>'] = <NUM_LIT:0><EOL>return result<EOL><DEDENT>raise TypeError(<EOL>f'<STR_LIT>',<EOL>)<EOL>
Convert internal objects to a serializable representation. During serialization if the object has the hook method `to_dict` it will be automatically called and metadata for decoding will be added. This allows for the translation of objects trees of arbitrary depth. E.g.: >>> class Root: >>> de...
f9395:m2
def _filter_from_dict(current: Dict[str, Any]) -> Dict[str, Any]:
filter_ = dict()<EOL>for k, v in current.items():<EOL><INDENT>if isinstance(v, dict):<EOL><INDENT>for sub, v2 in _filter_from_dict(v).items():<EOL><INDENT>filter_[f'<STR_LIT>'] = v2<EOL><DEDENT><DEDENT>else:<EOL><INDENT>filter_[k] = v<EOL><DEDENT><DEDENT>return filter_<EOL>
Takes in a nested dictionary as a filter and returns a flattened filter dictionary
f9396:m2
def log_run(self):
version = get_system_spec()['<STR_LIT>']<EOL>cursor = self.conn.cursor()<EOL>cursor.execute('<STR_LIT>', [version])<EOL>self.maybe_commit()<EOL>
Log timestamp and raiden version to help with debugging
f9396:c3:m2
def write_events(self, events):
with self.write_lock, self.conn:<EOL><INDENT>self.conn.executemany(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>events,<EOL>)<EOL><DEDENT>
Save events. Args: state_change_identifier: Id of the state change that generate these events. events: List of Event objects.
f9396:c3:m7
def delete_state_changes(self, state_changes_to_delete: List[int]) -> None:
with self.write_lock, self.conn:<EOL><INDENT>self.conn.executemany(<EOL>'<STR_LIT>',<EOL>state_changes_to_delete,<EOL>)<EOL><DEDENT>
Delete state changes. Args: state_changes_to_delete: List of ids to delete.
f9396:c3:m8
def get_snapshot_closest_to_state_change(<EOL>self,<EOL>state_change_identifier: int,<EOL>) -> Tuple[int, Any]:
if not (state_change_identifier == '<STR_LIT>' or isinstance(state_change_identifier, int)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>cursor = self.conn.cursor()<EOL>if state_change_identifier == '<STR_LIT>':<EOL><INDENT>cursor.execute(<EOL>'<STR_LIT>',<EOL>)<EOL>result = cursor.fetchone()<EOL>if result:<E...
Get snapshots earlier than state_change with provided ID.
f9396:c3:m10
def _get_state_changes(<EOL>self,<EOL>limit: int = None,<EOL>offset: int = None,<EOL>filters: List[Tuple[str, Any]] = None,<EOL>logical_and: bool = True,<EOL>) -> List[StateChangeRecord]:
cursor = self._form_and_execute_json_query(<EOL>query='<STR_LIT>',<EOL>limit=limit,<EOL>offset=offset,<EOL>filters=filters,<EOL>logical_and=logical_and,<EOL>)<EOL>result = [<EOL>StateChangeRecord(<EOL>state_change_identifier=row[<NUM_LIT:0>],<EOL>data=row[<NUM_LIT:1>],<EOL>)<EOL>for row in cursor<EOL>]<EOL>return resul...
Return a batch of state change records (identifier and data) The batch size can be tweaked with the `limit` and `offset` arguments. Additionally the returned state changes can be optionally filtered with the `filters` parameter to search for specific data in the state change data.
f9396:c3:m14