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['<STR_LIT:id>'] = self.uuid<EOL><DEDENT>return json.dumps(d)<EOL>
Dump the keystore for later disk storage. The result inherits the entries `'crypto'` and `'version`' from `account.keystore`, and adds `'address'` and `'id'` in accordance with the parameters `'include_address'` and `'include_id`'. If address or id are not known, they are not added, even if requested. Args: include_address: flag denoting if the address should be included or not include_id: flag denoting if the id should be included or not
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()<EOL>if isinstance(value, dict)<EOL>)<EOL><DEDENT><DEDENT>return data<EOL>
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>'] == '<STR_LIT>':<EOL><INDENT>endpoint_registration_greenlet = gevent.spawn(<EOL>self.discovery.register,<EOL>self.address,<EOL>self.config['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'],<EOL>self.config['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'],<EOL>)<EOL><DEDENT>self.maybe_upgrade_db()<EOL>storage = sqlite.SerializedSQLiteStorage(<EOL>database_path=self.database_path,<EOL>serializer=serialize.JSONSerializer(),<EOL>)<EOL>storage.update_version()<EOL>storage.log_run()<EOL>self.wal = wal.restore_to_state_change(<EOL>transition_function=node.state_transition,<EOL>storage=storage,<EOL>state_change_identifier='<STR_LIT>',<EOL>)<EOL>if self.wal.state_manager.current_state is None:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.address),<EOL>)<EOL>last_log_block_number = self.query_start_block<EOL>last_log_block_hash = self.chain.client.blockhash_from_blocknumber(<EOL>last_log_block_number,<EOL>)<EOL>state_change = ActionInitChain(<EOL>pseudo_random_generator=random.Random(),<EOL>block_number=last_log_block_number,<EOL>block_hash=last_log_block_hash,<EOL>our_address=self.chain.node_address,<EOL>chain_id=self.chain.network_id,<EOL>)<EOL>self.handle_and_track_state_change(state_change)<EOL>payment_network = PaymentNetworkState(<EOL>self.default_registry.address,<EOL>[], <EOL>)<EOL>state_change = ContractReceiveNewPaymentNetwork(<EOL>transaction_hash=constants.EMPTY_HASH,<EOL>payment_network=payment_network,<EOL>block_number=last_log_block_number,<EOL>block_hash=last_log_block_hash,<EOL>)<EOL>self.handle_and_track_state_change(state_change)<EOL><DEDENT>else:<EOL><INDENT>last_log_block_number = views.block_number(self.wal.state_manager.current_state)<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>last_restored_block=last_log_block_number,<EOL>node=pex(self.address),<EOL>)<EOL>known_networks = views.get_payment_network_identifiers(views.state_from_raiden(self))<EOL>if known_networks and self.default_registry.address not in known_networks:<EOL><INDENT>configured_registry = pex(self.default_registry.address)<EOL>known_registries = lpex(known_networks)<EOL>raise RuntimeError(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT><DEDENT>state_change_qty = self.wal.storage.count_state_changes()<EOL>self.snapshot_group = state_change_qty // SNAPSHOT_STATE_CHANGES_COUNT<EOL>self.install_all_blockchain_filters(<EOL>self.default_registry,<EOL>self.default_secret_registry,<EOL>last_log_block_number,<EOL>)<EOL>self.alarm.register_callback(self._callback_new_block)<EOL>self.alarm.first_run(last_log_block_number)<EOL>chain_state = views.state_from_raiden(self)<EOL>self._initialize_payment_statuses(chain_state)<EOL>self._initialize_transactions_queues(chain_state)<EOL>self._initialize_messages_queues(chain_state)<EOL>self._initialize_whitelists(chain_state)<EOL>self._initialize_monitoring_services_queue(chain_state)<EOL>self._initialize_ready_to_processed_events()<EOL>if self.config['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>endpoint_registration_greenlet.get() <EOL><DEDENT>self.alarm.link_exception(self.on_error)<EOL>self.transport.link_exception(self.on_error)<EOL>self._start_transport(chain_state)<EOL>self._start_alarm_task()<EOL>log.debug('<STR_LIT>', node=pex(self.address))<EOL>super().start()<EOL>
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>self.db_lock.release()<EOL><DEDENT>log.debug('<STR_LIT>', node=pex(self.address))<EOL>
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><INDENT>if neighbour != ConnectionManager.BOOTSTRAP_ADDR:<EOL><INDENT>self.start_health_check_for(neighbour)<EOL><DEDENT><DEDENT>
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 messages for closed channels.
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_from_raiden(self)<EOL>for changed_balance_proof in views.detect_balance_proof_change(old_state, current_state):<EOL><INDENT>update_services_from_balance_proof(self, current_state, changed_balance_proof)<EOL><DEDENT>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.address),<EOL>raiden_events=[<EOL>_redact_secret(serialize.JSONSerializer.serialize(event))<EOL>for event in raiden_event_list<EOL>],<EOL>)<EOL>greenlets: List[Greenlet] = list()<EOL>if self.ready_to_process_events:<EOL><INDENT>for raiden_event in raiden_event_list:<EOL><INDENT>greenlets.append(<EOL>self.handle_event(raiden_event=raiden_event),<EOL>)<EOL><DEDENT>state_changes_count = self.wal.storage.count_state_changes()<EOL>new_snapshot_group = (<EOL>state_changes_count // SNAPSHOT_STATE_CHANGES_COUNT<EOL>)<EOL>if new_snapshot_group > self.snapshot_group:<EOL><INDENT>log.debug('<STR_LIT>', snapshot_id=new_snapshot_group)<EOL>self.wal.snapshot()<EOL>self.snapshot_group = new_snapshot_group<EOL><DEDENT><DEDENT>return greenlets<EOL>
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 important for the AlarmTask thread, which will eventually cause the node to send transactions when a given Block is reached (e.g. registering a secret or settling a channel). Important: This is spawing a new greenlet for /each/ transaction. It's therefore /required/ that there is *NO* order among these.
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.raiden_event_handler.on_raiden_event(self, transaction)<EOL><DEDENT>except RaidenRecoverableError as e:<EOL><INDENT>log.error(str(e))<EOL><DEDENT>except InvalidDBData:<EOL><INDENT>raise<EOL><DEDENT>except RaidenUnrecoverableError as e:<EOL><INDENT>log_unrecoverable = (<EOL>self.config['<STR_LIT>'] == Environment.PRODUCTION and<EOL>not self.config['<STR_LIT>']<EOL>)<EOL>if log_unrecoverable:<EOL><INDENT>log.error(str(e))<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>
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 from the queue (e.g. A monitoring service update transfer).
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>transfer_description = initiator.transfer_description<EOL>target = transfer.target<EOL>identifier = transfer.payment_identifier<EOL>balance_proof = transfer.balance_proof<EOL>self.targets_to_identifiers_to_statuses[target][identifier] = PaymentStatus(<EOL>payment_identifier=identifier,<EOL>amount=transfer_description.amount,<EOL>token_network_identifier=TokenNetworkID(<EOL>balance_proof.token_network_identifier,<EOL>),<EOL>payment_done=AsyncResult(),<EOL>)<EOL><DEDENT><DEDENT>
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><INDENT>message = message_from_sendevent(event)<EOL>self.sign(message)<EOL>self.transport.send_async(queue_identifier, message)<EOL><DEDENT><DEDENT>
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 before any of the previous messages, resulting in new messages being out-of-order. The Alarm task must be started before this method is called, otherwise queues for channel closed while the node was offline won't be properly cleared. It is not bad but it is suboptimal.
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_BLOCK_NUMBER,<EOL>block_hash=constants.EMPTY_HASH,<EOL>our_address=chain_state.our_address,<EOL>chain_id=chain_state.chain_id,<EOL>),<EOL>current_state=chain_state,<EOL>)<EOL>for balance_proof in current_balance_proofs:<EOL><INDENT>update_services_from_balance_proof(self, chain_state, balance_proof)<EOL><DEDENT>
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 can happen: For a transfer A-B-C where this node is B - B receives T1 from A and processes it - B forwards its T2 to C * B crashes (the monitoring service is not updated) For the above scenario, the monitoring service would not have the latest balance proof received by B from A available with the lock for T1, but C would. If the channel B-C is closed and B does not come back online in time, the funds for the lock L1 can be lost. During restarts the rationale from above has to be replicated. Because the initialization code *is not* the same as the event handler. This means the balance proof updates must be done prior to the processing of the message queues.
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 event in event_queue:<EOL><INDENT>if isinstance(event, SendLockedTransfer):<EOL><INDENT>transfer = event.transfer<EOL>if transfer.initiator == self.address:<EOL><INDENT>self.transport.whitelist(address=transfer.target)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
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=target,<EOL>identifier=identifier,<EOL>secret=secret,<EOL>secret_hash=secret_hash,<EOL>)<EOL>return payment_status<EOL>
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. - Network speed, making the transfer sufficiently fast so it doesn't expire.
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>raise ValueError('<STR_LIT>')<EOL><DEDENT>return hex_code.replace(library_symbol, library_address)<EOL>
Change the bytecode to use the given library address. Args: hex_code (bin): The bytecode encoded in hexadecimal. library_name (str): The library that will be resolved. library_address (str): The address of the library. Returns: bin: The bytecode encoded in hexadecimal with the library references resolved.
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 in args[<NUM_LIT:0>]<EOL>]<EOL>cwd = os.getcwd()<EOL>try:<EOL><INDENT>os.chdir(compile_wd)<EOL>compiled_contracts = compile_files(<EOL>source_files=file_list,<EOL>output_values=('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'),<EOL>**kwargs,<EOL>)<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(cwd)<EOL><DEDENT>return compiled_contracts<EOL>
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=sig)<EOL><DEDENT>except BadSignature as e:<EOL><INDENT>raise InvalidSignature from e<EOL><DEDENT>return public_key.to_canonical_address()<EOL>
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:<EOL><INDENT>with config_file_path.open() as config_file:<EOL><INDENT>config_file_values = load(config_file)<EOL><DEDENT><DEDENT>except OSError as ex:<EOL><INDENT>config_file_param = paramname_to_param[config_file_option_name]<EOL>config_file_default_path = Path(<EOL>config_file_param.type.expand_default(config_file_param.get_default(ctx), cli_params),<EOL>)<EOL>default_config_missing = (<EOL>ex.errno == errno.ENOENT and<EOL>config_file_path.resolve() == config_file_default_path.resolve()<EOL>)<EOL>if default_config_missing:<EOL><INDENT>cli_params['<STR_LIT>'] = None<EOL><DEDENT>else:<EOL><INDENT>click.secho(f"<STR_LIT>", fg='<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>except TomlError as ex:<EOL><INDENT>click.secho(f'<STR_LIT>', fg='<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>for config_name, config_value in config_file_values.items():<EOL><INDENT>config_name_int = config_name.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>if config_name_int not in paramname_to_param:<EOL><INDENT>click.secho(<EOL>f"<STR_LIT>",<EOL>fg='<STR_LIT>',<EOL>)<EOL>continue<EOL><DEDENT>if config_name_int in path_params:<EOL><INDENT>config_value = os.path.expanduser(config_value)<EOL><DEDENT>if config_name_int == LOG_CONFIG_OPTION_NAME:<EOL><INDENT>config_value = {k: v.upper() for k, v in config_value.items()}<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>config_value = paramname_to_param[config_name_int].type.convert(<EOL>config_value,<EOL>paramname_to_param[config_name_int],<EOL>ctx,<EOL>)<EOL><DEDENT>except click.BadParameter as ex:<EOL><INDENT>click.secho(f"<STR_LIT>", fg='<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if cli_params[config_name_int] == paramname_to_param[config_name_int].get_default(ctx):<EOL><INDENT>cli_params[config_name_int] = config_value<EOL><DEDENT><DEDENT>
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 response.text.splitlines():<EOL><INDENT>line = line.strip(string.whitespace + '<STR_LIT:->')<EOL>if line.startswith('<STR_LIT:#>') or not line:<EOL><INDENT>continue<EOL><DEDENT>if not line.startswith('<STR_LIT:http>'):<EOL><INDENT>line = '<STR_LIT>' + line <EOL><DEDENT>available_servers.append(line)<EOL><DEDENT>return available_servers<EOL>
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('<STR_LIT>' % (self.current_indent, '<STR_LIT>', first))<EOL>if not second:<EOL><INDENT>self.write('<STR_LIT:\n>')<EOL>continue<EOL><DEDENT>if term_len(first) <= first_col - col_spacing:<EOL><INDENT>self.write('<STR_LIT:U+0020>' * (first_col - term_len(first)))<EOL><DEDENT>else:<EOL><INDENT>self.write('<STR_LIT:\n>')<EOL>self.write('<STR_LIT:U+0020>' * (first_col + self.current_indent))<EOL><DEDENT>text_width = max(self.width - first_col - <NUM_LIT:2>, <NUM_LIT:10>)<EOL>lines = iter(wrap_text(second, text_width).splitlines())<EOL>if lines:<EOL><INDENT>self.write(next(lines) + '<STR_LIT:\n>')<EOL>for line in lines:<EOL><INDENT>self.write('<STR_LIT>' % (<EOL>first_col + self.current_indent, '<STR_LIT>', line,<EOL>))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.write('<STR_LIT:\n>')<EOL><DEDENT><DEDENT>
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 second column. :param widths: optional pre-calculated line widths
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 command. For the toplevel script it's usually the name of the script, for commands below it it's the name of the script. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor.
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>self.greenlet.name = f'<STR_LIT>'<EOL><DEDENT>self.greenlet.start()<EOL>
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['<STR_LIT>'][<NUM_LIT:0>]<EOL>events = filter_by_type('<STR_LIT>', abi)<EOL>topic_to_event_abi = {<EOL>event_abi_to_log_topic(event_abi): event_abi<EOL>for event_abi in events<EOL>}<EOL>event_abi = topic_to_event_abi[event_id]<EOL>return get_event_data(event_abi, log)<EOL>
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(part for part in platform.architecture() if part),<EOL>platform.release(),<EOL>)<EOL><DEDENT>try:<EOL><INDENT>version = pkg_resources.require(raiden.__name__)[<NUM_LIT:0>].version<EOL><DEDENT>except (pkg_resources.VersionConflict, pkg_resources.DistributionNotFound):<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>system_spec = {<EOL>'<STR_LIT>': version,<EOL>'<STR_LIT>': platform.python_implementation(),<EOL>'<STR_LIT>': platform.python_version(),<EOL>'<STR_LIT>': system_info,<EOL>'<STR_LIT>': platform.machine(),<EOL>'<STR_LIT>': '<STR_LIT>' if getattr(sys, '<STR_LIT>', False) else '<STR_LIT:source>',<EOL>}<EOL>return system_spec<EOL>
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 = func()<EOL><DEDENT><DEDENT>return res<EOL>
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, None): the maximum time to wait, or None for an infinite loop sleep_for (float, integer): how much to gevent.sleep between calls Returns: func(): result of func, if truth value, or None
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):<EOL><INDENT>number = block<EOL><DEDENT>else:<EOL><INDENT>if __debug__:<EOL><INDENT>raise AssertionError(f'<STR_LIT>')<EOL><DEDENT><DEDENT>return BlockNumber(number)<EOL>
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>'<STR_LIT>',<EOL>)<EOL><DEDENT>if not result:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>return int(result[<NUM_LIT:0>])<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>self.host,<EOL>self.port,<EOL>context=ssl_context,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(f'<STR_LIT>')<EOL><DEDENT>self._send_request(conn)<EOL>response = conn.getresponse()<EOL>status = str(response.status)<EOL>if not self._validate_response(response):<EOL><INDENT>return False<EOL><DEDENT>if status == self.status or self.status_re.match(status):<EOL><INDENT>conn.close()<EOL>return True<EOL><DEDENT><DEDENT>except (HTTPException, socket.timeout, socket.error) as ex:<EOL><INDENT>log.debug('<STR_LIT>', command=self.command, error=ex)<EOL>time.sleep(<NUM_LIT>)<EOL>return False<EOL><DEDENT>return False<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:<EOL><INDENT>stdin = stdout = stderr = self.stdio<EOL><DEDENT>env = os.environ.copy()<EOL>env[ENV_UUID] = self._uuid<EOL>popen_kwargs = {<EOL>'<STR_LIT>': self._shell,<EOL>'<STR_LIT>': stdin,<EOL>'<STR_LIT>': stdout,<EOL>'<STR_LIT>': stderr,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': env,<EOL>'<STR_LIT>': self.cwd,<EOL>}<EOL>if platform.system() != '<STR_LIT>':<EOL><INDENT>popen_kwargs['<STR_LIT>'] = os.setsid<EOL><DEDENT>self.process = subprocess.Popen(<EOL>command,<EOL>**popen_kwargs,<EOL>)<EOL><DEDENT>self._set_timeout()<EOL>try:<EOL><INDENT>self.wait_for(self.check_subprocess)<EOL><DEDENT>except ProcessExitedWithError as e:<EOL><INDENT>if e.exit_code == <NUM_LIT>:<EOL><INDENT>raise FileNotFoundError(<EOL>f'<STR_LIT>',<EOL>) from e<EOL><DEDENT>else:<EOL><INDENT>output_file_names = {io.name for io in (stdout, stderr) if hasattr(io, '<STR_LIT:name>')}<EOL>if output_file_names:<EOL><INDENT>log.warning('<STR_LIT>', output_files=output_file_names)<EOL><DEDENT><DEDENT>raise<EOL><DEDENT>return self<EOL>
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, value))<EOL>for abi_type, value<EOL>in zip(abi_types, normalized_values)<EOL>))<EOL>
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_offset,<EOL>)<EOL>received_transfers = [<EOL>event<EOL>for event in received_transfers<EOL>if type(event) == EventPaymentReceivedSuccess<EOL>]<EOL>for event in received_transfers:<EOL><INDENT>transfer = copy.deepcopy(event)<EOL>self.received_transfers.put(transfer)<EOL><DEDENT>if received_transfers:<EOL><INDENT>self.last_poll_offset += len(received_transfers)<EOL><DEDENT>if not self.echo_worker_greenlet.started:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>dead=self.echo_worker_greenlet.dead,<EOL>successful=self.echo_worker_greenlet.successful(),<EOL>exception=self.echo_worker_greenlet.exception,<EOL>)<EOL>self.echo_worker_greenlet = gevent.spawn(self.echo_worker)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except Timeout:<EOL><INDENT>log.info('<STR_LIT>')<EOL><DEDENT>finally:<EOL><INDENT>if locked:<EOL><INDENT>self.lock.release()<EOL><DEDENT><DEDENT>
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.initiator),<EOL>amount=transfer.amount,<EOL>identifier=transfer.identifier,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.seen_transfers.append(transfer)<EOL>self.greenlets.add(gevent.spawn(self.on_transfer, transfer))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>gevent.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>
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:7>:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>initiator=pex(transfer.initiator),<EOL>amount=transfer.amount,<EOL>identifier=transfer.identifier,<EOL>poolsize=self.lottery_pool.qsize(),<EOL>)<EOL>pool = self.lottery_pool.copy()<EOL>tickets = [pool.get() for _ in range(pool.qsize())]<EOL>assert pool.empty()<EOL>del pool<EOL>if any(ticket.initiator == transfer.initiator for ticket in tickets):<EOL><INDENT>assert transfer not in tickets<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>initiator=pex(transfer.initiator),<EOL>identifier=transfer.identifier,<EOL>poolsize=len(tickets),<EOL>)<EOL>echo_amount = len(tickets)<EOL><DEDENT>elif len(tickets) == <NUM_LIT:6>:<EOL><INDENT>log.info('<STR_LIT>')<EOL>assert self.lottery_pool.qsize() == <NUM_LIT:6><EOL>self.lottery_pool = Queue()<EOL>tickets.append(transfer)<EOL>transfer = random.choice(tickets)<EOL>echo_amount = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>self.lottery_pool.put(transfer)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>initiator=pex(transfer.initiator),<EOL>amount=transfer.amount,<EOL>identifier=transfer.identifier,<EOL>)<EOL>echo_amount = transfer.amount<EOL><DEDENT>if echo_amount:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>target=pex(transfer.initiator),<EOL>amount=echo_amount,<EOL>orig_identifier=transfer.identifier,<EOL>echo_identifier=transfer.identifier + echo_amount,<EOL>token_address=pex(self.token_address),<EOL>num_handled_transfers=self.num_handled_transfers + <NUM_LIT:1>,<EOL>)<EOL>self.api.transfer(<EOL>self.api.raiden.default_registry.address,<EOL>self.token_address,<EOL>echo_amount,<EOL>transfer.initiator,<EOL>identifier=transfer.identifier + echo_amount,<EOL>)<EOL><DEDENT>self.num_handled_transfers += <NUM_LIT:1><EOL>
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" amount `amount == 7` it does not send anything back immediately -- after having received "lucky number transfers" from 7 different addresses it sends a transfer with `amount = 49` to one randomly chosen one (from the 7 lucky addresses) - consecutive entries to the lucky lottery will receive the current pool size as the `echo_amount` - for all other transfers it sends a transfer with the same `amount` back to the initiator
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: Tuple of a boolean denoting if the account has enough balance for the remaining lifecycle events and the estimate for the remaining lifecycle cost
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['<STR_LIT>']<EOL><DEDENT>hexbytes_to_str(new_event)<EOL>name = new_event['<STR_LIT>']<EOL>if name == '<STR_LIT>':<EOL><INDENT>new_event['<STR_LIT>'] = to_checksum_address(new_event['<STR_LIT>'])<EOL><DEDENT>if name in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>new_event['<STR_LIT:target>'] = to_checksum_address(new_event['<STR_LIT:target>'])<EOL><DEDENT>encode_byte_values(new_event)<EOL>encode_object_to_str(new_event)<EOL>new_list.append(new_event)<EOL><DEDENT>return new_list<EOL>
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_address(<EOL>views.state_from_raiden(self.raiden_api.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=token,<EOL>)<EOL>try:<EOL><INDENT>connection_manager = self.raiden_api.raiden.connection_manager_for_token_network(<EOL>token_network_identifier,<EOL>)<EOL><DEDENT>except InvalidAddress:<EOL><INDENT>connection_manager = None<EOL><DEDENT>open_channels = views.get_channelstate_open(<EOL>chain_state=views.state_from_raiden(self.raiden_api.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=token,<EOL>)<EOL>if connection_manager is not None and open_channels:<EOL><INDENT>connection_managers[to_checksum_address(connection_manager.token_address)] = {<EOL>'<STR_LIT>': connection_manager.funds,<EOL>'<STR_LIT>': views.get_our_capacity_for_token_network(<EOL>views.state_from_raiden(self.raiden_api.raiden),<EOL>registry_address,<EOL>token,<EOL>),<EOL>'<STR_LIT>': len(open_channels),<EOL>}<EOL><DEDENT><DEDENT>return connection_managers<EOL>
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, (EventPaymentSentFailed, EventPaymentSentSuccess)) and<EOL>(<EOL>partner_address is None or<EOL>event.target == partner_address<EOL>)<EOL>)<EOL>received_and_initiator_matches = (<EOL>isinstance(event, EventPaymentReceivedSuccess) and<EOL>(<EOL>partner_address is None or<EOL>event.initiator == partner_address<EOL>)<EOL>)<EOL>return sent_and_target_matches or received_and_initiator_matches<EOL>
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. If it's a payment received and the initiator matches then it's returned.
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>')<EOL><DEDENT>contracts_version = self.raiden.contract_manager.contracts_version<EOL>registry = self.raiden.chain.token_network_registry(registry_address)<EOL>try:<EOL><INDENT>if contracts_version == DEVELOPMENT_CONTRACT_VERSION:<EOL><INDENT>return registry.add_token_with_limits(<EOL>token_address=token_address,<EOL>channel_participant_deposit_limit=channel_participant_deposit_limit,<EOL>token_network_deposit_limit=token_network_deposit_limit,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return registry.add_token_without_limits(<EOL>token_address=token_address,<EOL>)<EOL><DEDENT><DEDENT>except RaidenRecoverableError as e:<EOL><INDENT>if '<STR_LIT>' in str(e):<EOL><INDENT>raise AlreadyRegisteredTokenAddress('<STR_LIT>')<EOL><DEDENT>raise<EOL><DEDENT>finally:<EOL><INDENT>next_block = self.raiden.get_block_number() + <NUM_LIT:1><EOL>waiting.wait_for_block(self.raiden, next_block, retry_timeout)<EOL><DEDENT>
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 a valid address. AlreadyRegisteredTokenAddress: If the token is already registered. TransactionThrew: If the register transaction failed, this may happen because the account has not enough balance to pay for the gas or this register call raced with another transaction and lost.
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(self.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>)<EOL>connection_manager = self.raiden.connection_manager_for_token_network(<EOL>token_network_identifier,<EOL>)<EOL>has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(<EOL>raiden=self.raiden,<EOL>channels_to_open=initial_channel_target,<EOL>)<EOL>if not has_enough_reserve:<EOL><INDENT>raise InsufficientGasReserve((<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>))<EOL><DEDENT>connection_manager.connect(<EOL>funds=funds,<EOL>initial_channel_target=initial_channel_target,<EOL>joinable_funds_target=joinable_funds_target,<EOL>)<EOL>
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. joinable_funds_target: fraction of the funds that will be used to join channels opened by other participants.
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><DEDENT>token_network_identifier = views.get_token_network_identifier_by_token_address(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>)<EOL>connection_manager = self.raiden.connection_manager_for_token_network(<EOL>token_network_identifier,<EOL>)<EOL>return connection_manager.leave(registry_address)<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('<STR_LIT>')<EOL><DEDENT>if not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not is_binary_address(partner_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>chain_state = views.state_from_raiden(self.raiden)<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=partner_address,<EOL>)<EOL>if channel_state:<EOL><INDENT>raise DuplicatedChannelError('<STR_LIT>')<EOL><DEDENT>registry = self.raiden.chain.token_network_registry(registry_address)<EOL>token_network_address = registry.get_token_network(token_address)<EOL>if token_network_address is None:<EOL><INDENT>raise TokenNotRegistered(<EOL>'<STR_LIT>' % to_checksum_address(token_address),<EOL>)<EOL><DEDENT>token_network = self.raiden.chain.token_network(<EOL>registry.get_token_network(token_address),<EOL>)<EOL>with self.raiden.gas_reserve_lock:<EOL><INDENT>has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(<EOL>self.raiden,<EOL>channels_to_open=<NUM_LIT:1>,<EOL>)<EOL>if not has_enough_reserve:<EOL><INDENT>raise InsufficientGasReserve((<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>))<EOL><DEDENT>try:<EOL><INDENT>token_network.new_netting_channel(<EOL>partner=partner_address,<EOL>settle_timeout=settle_timeout,<EOL>given_block_identifier=views.state_from_raiden(self.raiden).block_hash,<EOL>)<EOL><DEDENT>except DuplicatedChannelError:<EOL><INDENT>log.info('<STR_LIT>')<EOL><DEDENT><DEDENT>waiting.wait_for_newchannel(<EOL>raiden=self.raiden,<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>partner_address=partner_address,<EOL>retry_timeout=retry_timeout,<EOL>)<EOL>chain_state = views.state_from_raiden(self.raiden)<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=partner_address,<EOL>)<EOL>assert channel_state, f'<STR_LIT>'<EOL>return channel_state.identifier<EOL>
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=partner_address,<EOL>)<EOL>if not is_binary_address(token_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if not is_binary_address(partner_address):<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if token_address not in token_addresses:<EOL><INDENT>raise UnknownTokenAddress('<STR_LIT>')<EOL><DEDENT>if channel_state is None:<EOL><INDENT>raise InvalidAddress('<STR_LIT>')<EOL><DEDENT>if self.raiden.config['<STR_LIT>'] == Environment.PRODUCTION:<EOL><INDENT>per_token_network_deposit_limit = RED_EYES_PER_TOKEN_NETWORK_LIMIT<EOL><DEDENT>else:<EOL><INDENT>per_token_network_deposit_limit = UINT256_MAX<EOL><DEDENT>token = self.raiden.chain.token(token_address)<EOL>token_network_registry = self.raiden.chain.token_network_registry(registry_address)<EOL>token_network_address = token_network_registry.get_token_network(token_address)<EOL>token_network_proxy = self.raiden.chain.token_network(token_network_address)<EOL>channel_proxy = self.raiden.chain.payment_channel(<EOL>canonical_identifier=channel_state.canonical_identifier,<EOL>)<EOL>if total_deposit == <NUM_LIT:0>:<EOL><INDENT>raise DepositMismatch('<STR_LIT>')<EOL><DEDENT>addendum = total_deposit - channel_state.our_state.contract_balance<EOL>total_network_balance = token.balance_of(registry_address)<EOL>if total_network_balance + addendum > per_token_network_deposit_limit:<EOL><INDENT>raise DepositOverLimit(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT>balance = token.balance_of(self.raiden.address)<EOL>functions = token_network_proxy.proxy.contract.functions<EOL>deposit_limit = functions.channel_participant_deposit_limit().call()<EOL>if total_deposit > deposit_limit:<EOL><INDENT>raise DepositOverLimit(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT>if not balance >= addendum:<EOL><INDENT>msg = '<STR_LIT>'.format(<EOL>pex(token_address),<EOL>balance,<EOL>addendum,<EOL>)<EOL>raise InsufficientFunds(msg)<EOL><DEDENT>channel_proxy.set_total_deposit(<EOL>total_deposit=total_deposit,<EOL>block_identifier=views.state_from_raiden(self.raiden).block_hash,<EOL>)<EOL>target_address = self.raiden.address<EOL>waiting.wait_for_participant_newbalance(<EOL>raiden=self.raiden,<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>partner_address=partner_address,<EOL>target_address=target_address,<EOL>target_balance=total_deposit,<EOL>retry_timeout=retry_timeout,<EOL>)<EOL>
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 multiple reasons: - If the token approval fails, e.g. the token may validate if account has enough balance for the allowance. - The deposit failed, e.g. the allowance did not set the token aside for use and the user spent it before deposit was called. - The channel was closed/settled between the allowance call and the deposit call. AddressWithoutCode: The channel was settled during the deposit execution. DepositOverLimit: The total deposit amount is higher than the limit.
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>payment_network_id=registry_address,<EOL>)<EOL>if token_address not in valid_tokens:<EOL><INDENT>raise UnknownTokenAddress('<STR_LIT>')<EOL><DEDENT>chain_state = views.state_from_raiden(self.raiden)<EOL>channels_to_close = views.filter_channels_by_partneraddress(<EOL>chain_state=chain_state,<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>partner_addresses=partner_addresses,<EOL>)<EOL>greenlets: Set[Greenlet] = set()<EOL>for channel_state in channels_to_close:<EOL><INDENT>channel_close = ActionChannelClose(<EOL>canonical_identifier=channel_state.canonical_identifier,<EOL>)<EOL>greenlets.update(<EOL>self.raiden.handle_state_change(channel_close),<EOL>)<EOL><DEDENT>gevent.joinall(greenlets, raise_error=True)<EOL>channel_ids = [channel_state.identifier for channel_state in channels_to_close]<EOL>waiting.wait_for_close(<EOL>raiden=self.raiden,<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>channel_ids=channel_ids,<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: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><INDENT>raise InvalidAddress(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>if not token_address:<EOL><INDENT>raise UnknownTokenAddress('<STR_LIT>')<EOL><DEDENT><DEDENT>if token_address and partner_address:<EOL><INDENT>channel_state = views.get_channelstate_for(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>partner_address=partner_address,<EOL>)<EOL>if channel_state:<EOL><INDENT>result = [channel_state]<EOL><DEDENT>else:<EOL><INDENT>result = []<EOL><DEDENT><DEDENT>elif token_address:<EOL><INDENT>result = views.list_channelstate_for_tokennetwork(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=token_address,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>result = views.list_all_channelstate(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>)<EOL><DEDENT>return result<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 channels the node participates. Optionally filtered by a token address and/or partner address. Raises: KeyError: An error occurred when the token address is unknown to the node.
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_status<EOL>
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. - claim the `reward_amount` from the UDC.
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 important to only use this with sanitized or trusted input, otherwise arbitrary modules can be imported and potentially arbitrary code can be executed.
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: >>> def __init__(self, left, right): >>> self.left = left >>> self.right = right >>> def to_dict(self): >>> return { >>> 'left': left, >>> 'right': right, >>> } >>> class Node: >>> def to_dict(self): >>> return {'value': 'node'} >>> root = Root(left=None(), right=None()) >>> json.dumps(root, default=to_dict_hook) '{ "_type": "Root", "left": {"_type": "Node", "value": "node"}, "right": {"_type": "Node", "value": "node"} }'
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:<EOL><INDENT>state_change_identifier = result[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>state_change_identifier = <NUM_LIT:0><EOL><DEDENT><DEDENT>cursor = self.conn.execute(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>(state_change_identifier, ),<EOL>)<EOL>rows = cursor.fetchall()<EOL>if rows:<EOL><INDENT>assert len(rows) == <NUM_LIT:1>, '<STR_LIT>'<EOL>last_applied_state_change_id = rows[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>snapshot_state = rows[<NUM_LIT:0>][<NUM_LIT:1>]<EOL>result = (last_applied_state_change_id, snapshot_state)<EOL><DEDENT>else:<EOL><INDENT>result = (<NUM_LIT:0>, None)<EOL><DEDENT>return result<EOL>
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 result<EOL>
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