id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
235,400
raiden-network/raiden
raiden/transfer/views.py
get_token_identifiers
def get_token_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenAddress]: """ Return the list of tokens registered with the given payment network. """ payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_network is not None: return [ token_address for token_address in payment_network.tokenaddresses_to_tokenidentifiers.keys() ] return list()
python
def get_token_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenAddress]: payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_network is not None: return [ token_address for token_address in payment_network.tokenaddresses_to_tokenidentifiers.keys() ] return list()
[ "def", "get_token_identifiers", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", ")", "->", "List", "[", "TokenAddress", "]", ":", "payment_network", "=", "chain_state", ".", "identifiers_to_paymentnetworks", ".", "get", ...
Return the list of tokens registered with the given payment network.
[ "Return", "the", "list", "of", "tokens", "registered", "with", "the", "given", "payment", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L203-L216
235,401
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_filter
def get_channelstate_filter( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, filter_fn: Callable, ) -> List[NettingChannelState]: """ Return the state of channels that match the condition in `filter_fn` """ token_network = get_token_network_by_token_address( chain_state, payment_network_id, token_address, ) result: List[NettingChannelState] = [] if not token_network: return result for channel_state in token_network.channelidentifiers_to_channels.values(): if filter_fn(channel_state): result.append(channel_state) return result
python
def get_channelstate_filter( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, filter_fn: Callable, ) -> List[NettingChannelState]: token_network = get_token_network_by_token_address( chain_state, payment_network_id, token_address, ) result: List[NettingChannelState] = [] if not token_network: return result for channel_state in token_network.channelidentifiers_to_channels.values(): if filter_fn(channel_state): result.append(channel_state) return result
[ "def", "get_channelstate_filter", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "filter_fn", ":", "Callable", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", ...
Return the state of channels that match the condition in `filter_fn`
[ "Return", "the", "state", "of", "channels", "that", "match", "the", "condition", "in", "filter_fn" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L347-L368
235,402
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_open
def get_channelstate_open( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of open channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_OPENED, )
python
def get_channelstate_open( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_OPENED, )
[ "def", "get_channelstate_open", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", "("...
Return the state of open channels in a token network.
[ "Return", "the", "state", "of", "open", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L371-L382
235,403
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_closing
def get_channelstate_closing( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closing channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSING, )
python
def get_channelstate_closing( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSING, )
[ "def", "get_channelstate_closing", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of closing channels in a token network.
[ "Return", "the", "state", "of", "closing", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L385-L396
235,404
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_closed
def get_channelstate_closed( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closed channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSED, )
python
def get_channelstate_closed( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSED, )
[ "def", "get_channelstate_closed", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", "...
Return the state of closed channels in a token network.
[ "Return", "the", "state", "of", "closed", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L399-L410
235,405
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_settling
def get_channelstate_settling( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settling channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLING, )
python
def get_channelstate_settling( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLING, )
[ "def", "get_channelstate_settling", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of settling channels in a token network.
[ "Return", "the", "state", "of", "settling", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L413-L424
235,406
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_settled
def get_channelstate_settled( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settled channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLED, )
python
def get_channelstate_settled( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLED, )
[ "def", "get_channelstate_settled", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of settled channels in a token network.
[ "Return", "the", "state", "of", "settled", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L427-L438
235,407
raiden-network/raiden
raiden/transfer/views.py
role_from_transfer_task
def role_from_transfer_task(transfer_task: TransferTask) -> str: """Return the role and type for the transfer. Throws an exception on error""" if isinstance(transfer_task, InitiatorTask): return 'initiator' if isinstance(transfer_task, MediatorTask): return 'mediator' if isinstance(transfer_task, TargetTask): return 'target' raise ValueError('Argument to role_from_transfer_task is not a TransferTask')
python
def role_from_transfer_task(transfer_task: TransferTask) -> str: if isinstance(transfer_task, InitiatorTask): return 'initiator' if isinstance(transfer_task, MediatorTask): return 'mediator' if isinstance(transfer_task, TargetTask): return 'target' raise ValueError('Argument to role_from_transfer_task is not a TransferTask')
[ "def", "role_from_transfer_task", "(", "transfer_task", ":", "TransferTask", ")", "->", "str", ":", "if", "isinstance", "(", "transfer_task", ",", "InitiatorTask", ")", ":", "return", "'initiator'", "if", "isinstance", "(", "transfer_task", ",", "MediatorTask", ")...
Return the role and type for the transfer. Throws an exception on error
[ "Return", "the", "role", "and", "type", "for", "the", "transfer", ".", "Throws", "an", "exception", "on", "error" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L441-L450
235,408
raiden-network/raiden
raiden/transfer/views.py
secret_from_transfer_task
def secret_from_transfer_task( transfer_task: Optional[TransferTask], secrethash: SecretHash, ) -> Optional[Secret]: """Return the secret for the transfer, None on EMPTY_SECRET.""" assert isinstance(transfer_task, InitiatorTask) transfer_state = transfer_task.manager_state.initiator_transfers[secrethash] if transfer_state is None: return None return transfer_state.transfer_description.secret
python
def secret_from_transfer_task( transfer_task: Optional[TransferTask], secrethash: SecretHash, ) -> Optional[Secret]: assert isinstance(transfer_task, InitiatorTask) transfer_state = transfer_task.manager_state.initiator_transfers[secrethash] if transfer_state is None: return None return transfer_state.transfer_description.secret
[ "def", "secret_from_transfer_task", "(", "transfer_task", ":", "Optional", "[", "TransferTask", "]", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "Optional", "[", "Secret", "]", ":", "assert", "isinstance", "(", "transfer_task", ",", "InitiatorTask", ")...
Return the secret for the transfer, None on EMPTY_SECRET.
[ "Return", "the", "secret", "for", "the", "transfer", "None", "on", "EMPTY_SECRET", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L453-L465
235,409
raiden-network/raiden
raiden/transfer/views.py
get_transfer_role
def get_transfer_role(chain_state: ChainState, secrethash: SecretHash) -> Optional[str]: """ Returns 'initiator', 'mediator' or 'target' to signify the role the node has in a transfer. If a transfer task is not found for the secrethash then the function returns None """ task = chain_state.payment_mapping.secrethashes_to_task.get(secrethash) if not task: return None return role_from_transfer_task(task)
python
def get_transfer_role(chain_state: ChainState, secrethash: SecretHash) -> Optional[str]: task = chain_state.payment_mapping.secrethashes_to_task.get(secrethash) if not task: return None return role_from_transfer_task(task)
[ "def", "get_transfer_role", "(", "chain_state", ":", "ChainState", ",", "secrethash", ":", "SecretHash", ")", "->", "Optional", "[", "str", "]", ":", "task", "=", "chain_state", ".", "payment_mapping", ".", "secrethashes_to_task", ".", "get", "(", "secrethash", ...
Returns 'initiator', 'mediator' or 'target' to signify the role the node has in a transfer. If a transfer task is not found for the secrethash then the function returns None
[ "Returns", "initiator", "mediator", "or", "target", "to", "signify", "the", "role", "the", "node", "has", "in", "a", "transfer", ".", "If", "a", "transfer", "task", "is", "not", "found", "for", "the", "secrethash", "then", "the", "function", "returns", "No...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L468-L477
235,410
raiden-network/raiden
raiden/transfer/views.py
filter_channels_by_status
def filter_channels_by_status( channel_states: List[NettingChannelState], exclude_states: Optional[List[str]] = None, ) -> List[NettingChannelState]: """ Filter the list of channels by excluding ones for which the state exists in `exclude_states`. """ if exclude_states is None: exclude_states = [] states = [] for channel_state in channel_states: if channel.get_status(channel_state) not in exclude_states: states.append(channel_state) return states
python
def filter_channels_by_status( channel_states: List[NettingChannelState], exclude_states: Optional[List[str]] = None, ) -> List[NettingChannelState]: if exclude_states is None: exclude_states = [] states = [] for channel_state in channel_states: if channel.get_status(channel_state) not in exclude_states: states.append(channel_state) return states
[ "def", "filter_channels_by_status", "(", "channel_states", ":", "List", "[", "NettingChannelState", "]", ",", "exclude_states", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "if...
Filter the list of channels by excluding ones for which the state exists in `exclude_states`.
[ "Filter", "the", "list", "of", "channels", "by", "excluding", "ones", "for", "which", "the", "state", "exists", "in", "exclude_states", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L558-L573
235,411
raiden-network/raiden
raiden/transfer/views.py
detect_balance_proof_change
def detect_balance_proof_change( old_state: ChainState, current_state: ChainState, ) -> Iterator[Union[BalanceProofSignedState, BalanceProofUnsignedState]]: """ Compare two states for any received balance_proofs that are not in `old_state`. """ if old_state == current_state: return for payment_network_identifier in current_state.identifiers_to_paymentnetworks: try: old_payment_network = old_state.identifiers_to_paymentnetworks.get( payment_network_identifier, ) except AttributeError: old_payment_network = None current_payment_network = current_state.identifiers_to_paymentnetworks[ payment_network_identifier ] if old_payment_network == current_payment_network: continue for token_network_identifier in current_payment_network.tokenidentifiers_to_tokennetworks: if old_payment_network: old_token_network = old_payment_network.tokenidentifiers_to_tokennetworks.get( token_network_identifier, ) else: old_token_network = None current_token_network = current_payment_network.tokenidentifiers_to_tokennetworks[ token_network_identifier ] if old_token_network == current_token_network: continue for channel_identifier in current_token_network.channelidentifiers_to_channels: if old_token_network: old_channel = old_token_network.channelidentifiers_to_channels.get( channel_identifier, ) else: old_channel = None current_channel = current_token_network.channelidentifiers_to_channels[ channel_identifier ] if current_channel == old_channel: continue else: partner_state_updated = ( current_channel.partner_state.balance_proof is not None and ( old_channel is None or old_channel.partner_state.balance_proof != current_channel.partner_state.balance_proof ) ) if partner_state_updated: assert current_channel.partner_state.balance_proof, MYPY_ANNOTATION yield current_channel.partner_state.balance_proof our_state_updated = ( current_channel.our_state.balance_proof is not None and ( old_channel is None or old_channel.our_state.balance_proof != current_channel.our_state.balance_proof ) ) if our_state_updated: assert current_channel.our_state.balance_proof, MYPY_ANNOTATION yield current_channel.our_state.balance_proof
python
def detect_balance_proof_change( old_state: ChainState, current_state: ChainState, ) -> Iterator[Union[BalanceProofSignedState, BalanceProofUnsignedState]]: if old_state == current_state: return for payment_network_identifier in current_state.identifiers_to_paymentnetworks: try: old_payment_network = old_state.identifiers_to_paymentnetworks.get( payment_network_identifier, ) except AttributeError: old_payment_network = None current_payment_network = current_state.identifiers_to_paymentnetworks[ payment_network_identifier ] if old_payment_network == current_payment_network: continue for token_network_identifier in current_payment_network.tokenidentifiers_to_tokennetworks: if old_payment_network: old_token_network = old_payment_network.tokenidentifiers_to_tokennetworks.get( token_network_identifier, ) else: old_token_network = None current_token_network = current_payment_network.tokenidentifiers_to_tokennetworks[ token_network_identifier ] if old_token_network == current_token_network: continue for channel_identifier in current_token_network.channelidentifiers_to_channels: if old_token_network: old_channel = old_token_network.channelidentifiers_to_channels.get( channel_identifier, ) else: old_channel = None current_channel = current_token_network.channelidentifiers_to_channels[ channel_identifier ] if current_channel == old_channel: continue else: partner_state_updated = ( current_channel.partner_state.balance_proof is not None and ( old_channel is None or old_channel.partner_state.balance_proof != current_channel.partner_state.balance_proof ) ) if partner_state_updated: assert current_channel.partner_state.balance_proof, MYPY_ANNOTATION yield current_channel.partner_state.balance_proof our_state_updated = ( current_channel.our_state.balance_proof is not None and ( old_channel is None or old_channel.our_state.balance_proof != current_channel.our_state.balance_proof ) ) if our_state_updated: assert current_channel.our_state.balance_proof, MYPY_ANNOTATION yield current_channel.our_state.balance_proof
[ "def", "detect_balance_proof_change", "(", "old_state", ":", "ChainState", ",", "current_state", ":", "ChainState", ",", ")", "->", "Iterator", "[", "Union", "[", "BalanceProofSignedState", ",", "BalanceProofUnsignedState", "]", "]", ":", "if", "old_state", "==", ...
Compare two states for any received balance_proofs that are not in `old_state`.
[ "Compare", "two", "states", "for", "any", "received", "balance_proofs", "that", "are", "not", "in", "old_state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L576-L650
235,412
raiden-network/raiden
raiden/network/upnpsock.py
connect
def connect(): """Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information """ upnp = miniupnpc.UPnP() upnp.discoverdelay = 200 providers = upnp.discover() if providers > 1: log.debug('multiple upnp providers found', num_providers=providers) elif providers < 1: log.error('no upnp providers found') return None try: location = upnp.selectigd() log.debug('connected', upnp=upnp) except Exception as e: log.error('Error when connecting to uPnP provider', exception_info=e) return None if not valid_mappable_ipv4(upnp.lanaddr): log.error('could not query your lanaddr', reported=upnp.lanaddr) return None try: # this can fail if router advertises uPnP incorrectly if not valid_mappable_ipv4(upnp.externalipaddress()): log.error('could not query your externalipaddress', reported=upnp.externalipaddress()) return None return upnp, location except Exception: log.error('error when connecting with uPnP provider', location=location) return None
python
def connect(): upnp = miniupnpc.UPnP() upnp.discoverdelay = 200 providers = upnp.discover() if providers > 1: log.debug('multiple upnp providers found', num_providers=providers) elif providers < 1: log.error('no upnp providers found') return None try: location = upnp.selectigd() log.debug('connected', upnp=upnp) except Exception as e: log.error('Error when connecting to uPnP provider', exception_info=e) return None if not valid_mappable_ipv4(upnp.lanaddr): log.error('could not query your lanaddr', reported=upnp.lanaddr) return None try: # this can fail if router advertises uPnP incorrectly if not valid_mappable_ipv4(upnp.externalipaddress()): log.error('could not query your externalipaddress', reported=upnp.externalipaddress()) return None return upnp, location except Exception: log.error('error when connecting with uPnP provider', location=location) return None
[ "def", "connect", "(", ")", ":", "upnp", "=", "miniupnpc", ".", "UPnP", "(", ")", "upnp", ".", "discoverdelay", "=", "200", "providers", "=", "upnp", ".", "discover", "(", ")", "if", "providers", ">", "1", ":", "log", ".", "debug", "(", "'multiple up...
Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information
[ "Try", "to", "connect", "to", "the", "router", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/upnpsock.py#L37-L70
235,413
raiden-network/raiden
raiden/network/upnpsock.py
release_port
def release_port(upnp, external_port): """Try to release the port mapping for `external_port`. Args: external_port (int): the port that was previously forwarded to. Returns: success (boolean): if the release was successful. """ mapping = upnp.getspecificportmapping(external_port, 'UDP') if mapping is None: log.error('could not find a port mapping', external=external_port) return False else: log.debug('found existing port mapping', mapping=mapping) if upnp.deleteportmapping(external_port, 'UDP'): log.info('successfully released port mapping', external=external_port) return True log.warning( 'could not release port mapping, check your router for stale mappings', ) return False
python
def release_port(upnp, external_port): mapping = upnp.getspecificportmapping(external_port, 'UDP') if mapping is None: log.error('could not find a port mapping', external=external_port) return False else: log.debug('found existing port mapping', mapping=mapping) if upnp.deleteportmapping(external_port, 'UDP'): log.info('successfully released port mapping', external=external_port) return True log.warning( 'could not release port mapping, check your router for stale mappings', ) return False
[ "def", "release_port", "(", "upnp", ",", "external_port", ")", ":", "mapping", "=", "upnp", ".", "getspecificportmapping", "(", "external_port", ",", "'UDP'", ")", "if", "mapping", "is", "None", ":", "log", ".", "error", "(", "'could not find a port mapping'", ...
Try to release the port mapping for `external_port`. Args: external_port (int): the port that was previously forwarded to. Returns: success (boolean): if the release was successful.
[ "Try", "to", "release", "the", "port", "mapping", "for", "external_port", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/upnpsock.py#L170-L194
235,414
raiden-network/raiden
raiden/network/blockchain_service.py
BlockChainService.token
def token(self, token_address: Address) -> Token: """ Return a proxy to interact with a token. """ if not is_binary_address(token_address): raise ValueError('token_address must be a valid address') with self._token_creation_lock: if token_address not in self.address_to_token: self.address_to_token[token_address] = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) return self.address_to_token[token_address]
python
def token(self, token_address: Address) -> Token: if not is_binary_address(token_address): raise ValueError('token_address must be a valid address') with self._token_creation_lock: if token_address not in self.address_to_token: self.address_to_token[token_address] = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) return self.address_to_token[token_address]
[ "def", "token", "(", "self", ",", "token_address", ":", "Address", ")", "->", "Token", ":", "if", "not", "is_binary_address", "(", "token_address", ")", ":", "raise", "ValueError", "(", "'token_address must be a valid address'", ")", "with", "self", ".", "_token...
Return a proxy to interact with a token.
[ "Return", "a", "proxy", "to", "interact", "with", "a", "token", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/blockchain_service.py#L132-L145
235,415
raiden-network/raiden
raiden/network/blockchain_service.py
BlockChainService.discovery
def discovery(self, discovery_address: Address) -> Discovery: """ Return a proxy to interact with the discovery. """ if not is_binary_address(discovery_address): raise ValueError('discovery_address must be a valid address') with self._discovery_creation_lock: if discovery_address not in self.address_to_discovery: self.address_to_discovery[discovery_address] = Discovery( jsonrpc_client=self.client, discovery_address=discovery_address, contract_manager=self.contract_manager, ) return self.address_to_discovery[discovery_address]
python
def discovery(self, discovery_address: Address) -> Discovery: if not is_binary_address(discovery_address): raise ValueError('discovery_address must be a valid address') with self._discovery_creation_lock: if discovery_address not in self.address_to_discovery: self.address_to_discovery[discovery_address] = Discovery( jsonrpc_client=self.client, discovery_address=discovery_address, contract_manager=self.contract_manager, ) return self.address_to_discovery[discovery_address]
[ "def", "discovery", "(", "self", ",", "discovery_address", ":", "Address", ")", "->", "Discovery", ":", "if", "not", "is_binary_address", "(", "discovery_address", ")", ":", "raise", "ValueError", "(", "'discovery_address must be a valid address'", ")", "with", "sel...
Return a proxy to interact with the discovery.
[ "Return", "a", "proxy", "to", "interact", "with", "the", "discovery", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/blockchain_service.py#L147-L160
235,416
raiden-network/raiden
raiden/network/rpc/client.py
check_address_has_code
def check_address_has_code( client: 'JSONRPCClient', address: Address, contract_name: str = '', ): """ Checks that the given address contains code. """ result = client.web3.eth.getCode(to_checksum_address(address), 'latest') if not result: if contract_name: formated_contract_name = '[{}]: '.format(contract_name) else: formated_contract_name = '' raise AddressWithoutCode( '{}Address {} does not contain code'.format( formated_contract_name, to_checksum_address(address), ), )
python
def check_address_has_code( client: 'JSONRPCClient', address: Address, contract_name: str = '', ): result = client.web3.eth.getCode(to_checksum_address(address), 'latest') if not result: if contract_name: formated_contract_name = '[{}]: '.format(contract_name) else: formated_contract_name = '' raise AddressWithoutCode( '{}Address {} does not contain code'.format( formated_contract_name, to_checksum_address(address), ), )
[ "def", "check_address_has_code", "(", "client", ":", "'JSONRPCClient'", ",", "address", ":", "Address", ",", "contract_name", ":", "str", "=", "''", ",", ")", ":", "result", "=", "client", ".", "web3", ".", "eth", ".", "getCode", "(", "to_checksum_address", ...
Checks that the given address contains code.
[ "Checks", "that", "the", "given", "address", "contains", "code", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L188-L207
235,417
raiden-network/raiden
raiden/network/rpc/client.py
dependencies_order_of_build
def dependencies_order_of_build(target_contract, dependencies_map): """ Return an ordered list of contracts that is sufficient to successfully deploy the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph. """ if not dependencies_map: return [target_contract] if target_contract not in dependencies_map: raise ValueError('no dependencies defined for {}'.format(target_contract)) order = [target_contract] todo = list(dependencies_map[target_contract]) while todo: target_contract = todo.pop(0) target_pos = len(order) for dependency in dependencies_map[target_contract]: # we need to add the current contract before all its depedencies if dependency in order: target_pos = order.index(dependency) else: todo.append(dependency) order.insert(target_pos, target_contract) order.reverse() return order
python
def dependencies_order_of_build(target_contract, dependencies_map): if not dependencies_map: return [target_contract] if target_contract not in dependencies_map: raise ValueError('no dependencies defined for {}'.format(target_contract)) order = [target_contract] todo = list(dependencies_map[target_contract]) while todo: target_contract = todo.pop(0) target_pos = len(order) for dependency in dependencies_map[target_contract]: # we need to add the current contract before all its depedencies if dependency in order: target_pos = order.index(dependency) else: todo.append(dependency) order.insert(target_pos, target_contract) order.reverse() return order
[ "def", "dependencies_order_of_build", "(", "target_contract", ",", "dependencies_map", ")", ":", "if", "not", "dependencies_map", ":", "return", "[", "target_contract", "]", "if", "target_contract", "not", "in", "dependencies_map", ":", "raise", "ValueError", "(", "...
Return an ordered list of contracts that is sufficient to successfully deploy the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph.
[ "Return", "an", "ordered", "list", "of", "contracts", "that", "is", "sufficient", "to", "successfully", "deploy", "the", "target", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L232-L262
235,418
raiden-network/raiden
raiden/network/rpc/client.py
check_value_error_for_parity
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool: """ For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception. This function checks the thrown exception to see if it's the correct one and if yes returns True, if not returns False """ try: error_data = json.loads(str(value_error).replace("'", '"')) except json.JSONDecodeError: return False if call_type == ParityCallType.ESTIMATE_GAS: code_checks_out = error_data['code'] == -32016 message_checks_out = 'The execution failed due to an exception' in error_data['message'] elif call_type == ParityCallType.CALL: code_checks_out = error_data['code'] == -32015 message_checks_out = 'VM execution error' in error_data['message'] else: raise ValueError('Called check_value_error_for_parity() with illegal call type') if code_checks_out and message_checks_out: return True return False
python
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool: try: error_data = json.loads(str(value_error).replace("'", '"')) except json.JSONDecodeError: return False if call_type == ParityCallType.ESTIMATE_GAS: code_checks_out = error_data['code'] == -32016 message_checks_out = 'The execution failed due to an exception' in error_data['message'] elif call_type == ParityCallType.CALL: code_checks_out = error_data['code'] == -32015 message_checks_out = 'VM execution error' in error_data['message'] else: raise ValueError('Called check_value_error_for_parity() with illegal call type') if code_checks_out and message_checks_out: return True return False
[ "def", "check_value_error_for_parity", "(", "value_error", ":", "ValueError", ",", "call_type", ":", "ParityCallType", ")", "->", "bool", ":", "try", ":", "error_data", "=", "json", ".", "loads", "(", "str", "(", "value_error", ")", ".", "replace", "(", "\"'...
For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception. This function checks the thrown exception to see if it's the correct one and if yes returns True, if not returns False
[ "For", "parity", "failing", "calls", "and", "functions", "do", "not", "return", "None", "if", "the", "transaction", "will", "fail", "but", "instead", "throw", "a", "ValueError", "exception", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L270-L295
235,419
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.get_confirmed_blockhash
def get_confirmed_blockhash(self): """ Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash """ confirmed_block_number = self.web3.eth.blockNumber - self.default_block_num_confirmations if confirmed_block_number < 0: confirmed_block_number = 0 return self.blockhash_from_blocknumber(confirmed_block_number)
python
def get_confirmed_blockhash(self): confirmed_block_number = self.web3.eth.blockNumber - self.default_block_num_confirmations if confirmed_block_number < 0: confirmed_block_number = 0 return self.blockhash_from_blocknumber(confirmed_block_number)
[ "def", "get_confirmed_blockhash", "(", "self", ")", ":", "confirmed_block_number", "=", "self", ".", "web3", ".", "eth", ".", "blockNumber", "-", "self", ".", "default_block_num_confirmations", "if", "confirmed_block_number", "<", "0", ":", "confirmed_block_number", ...
Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash
[ "Gets", "the", "block", "CONFIRMATION_BLOCKS", "in", "the", "past", "and", "returns", "its", "block", "hash" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L559-L565
235,420
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.balance
def balance(self, account: Address): """ Return the balance of the account of the given address. """ return self.web3.eth.getBalance(to_checksum_address(account), 'pending')
python
def balance(self, account: Address): return self.web3.eth.getBalance(to_checksum_address(account), 'pending')
[ "def", "balance", "(", "self", ",", "account", ":", "Address", ")", ":", "return", "self", ".", "web3", ".", "eth", ".", "getBalance", "(", "to_checksum_address", "(", "account", ")", ",", "'pending'", ")" ]
Return the balance of the account of the given address.
[ "Return", "the", "balance", "of", "the", "account", "of", "the", "given", "address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L585-L587
235,421
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.parity_get_pending_transaction_hash_by_nonce
def parity_get_pending_transaction_hash_by_nonce( self, address: AddressHex, nonce: Nonce, ) -> Optional[TransactionHash]: """Queries the local parity transaction pool and searches for a transaction. Checks the local tx pool for a transaction from a particular address and for a given nonce. If it exists it returns the transaction hash. """ assert self.eth_node is constants.EthClient.PARITY # https://wiki.parity.io/JSONRPC-parity-module.html?q=traceTransaction#parity_alltransactions transactions = self.web3.manager.request_blocking('parity_allTransactions', []) log.debug('RETURNED TRANSACTIONS', transactions=transactions) for tx in transactions: address_match = to_checksum_address(tx['from']) == address if address_match and int(tx['nonce'], 16) == nonce: return tx['hash'] return None
python
def parity_get_pending_transaction_hash_by_nonce( self, address: AddressHex, nonce: Nonce, ) -> Optional[TransactionHash]: assert self.eth_node is constants.EthClient.PARITY # https://wiki.parity.io/JSONRPC-parity-module.html?q=traceTransaction#parity_alltransactions transactions = self.web3.manager.request_blocking('parity_allTransactions', []) log.debug('RETURNED TRANSACTIONS', transactions=transactions) for tx in transactions: address_match = to_checksum_address(tx['from']) == address if address_match and int(tx['nonce'], 16) == nonce: return tx['hash'] return None
[ "def", "parity_get_pending_transaction_hash_by_nonce", "(", "self", ",", "address", ":", "AddressHex", ",", "nonce", ":", "Nonce", ",", ")", "->", "Optional", "[", "TransactionHash", "]", ":", "assert", "self", ".", "eth_node", "is", "constants", ".", "EthClient...
Queries the local parity transaction pool and searches for a transaction. Checks the local tx pool for a transaction from a particular address and for a given nonce. If it exists it returns the transaction hash.
[ "Queries", "the", "local", "parity", "transaction", "pool", "and", "searches", "for", "a", "transaction", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L589-L607
235,422
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.new_contract_proxy
def new_contract_proxy(self, contract_interface, contract_address: Address): """ Return a proxy for interacting with a smart contract. Args: contract_interface: The contract interface as defined by the json. address: The contract's address. """ return ContractProxy( self, contract=self.new_contract(contract_interface, contract_address), )
python
def new_contract_proxy(self, contract_interface, contract_address: Address): return ContractProxy( self, contract=self.new_contract(contract_interface, contract_address), )
[ "def", "new_contract_proxy", "(", "self", ",", "contract_interface", ",", "contract_address", ":", "Address", ")", ":", "return", "ContractProxy", "(", "self", ",", "contract", "=", "self", ".", "new_contract", "(", "contract_interface", ",", "contract_address", "...
Return a proxy for interacting with a smart contract. Args: contract_interface: The contract interface as defined by the json. address: The contract's address.
[ "Return", "a", "proxy", "for", "interacting", "with", "a", "smart", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L628-L638
235,423
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.send_transaction
def send_transaction( self, to: Address, startgas: int, value: int = 0, data: bytes = b'', ) -> bytes: """ Helper to send signed messages. This method will use the `privkey` provided in the constructor to locally sign the transaction. This requires an extended server implementation that accepts the variables v, r, and s. """ if to == to_canonical_address(constants.NULL_ADDRESS): warnings.warn('For contract creation the empty string must be used.') with self._nonce_lock: nonce = self._available_nonce gas_price = self.gas_price() transaction = { 'data': data, 'gas': startgas, 'nonce': nonce, 'value': value, 'gasPrice': gas_price, } node_gas_price = self.web3.eth.gasPrice log.debug( 'Calculated gas price for transaction', node=pex(self.address), calculated_gas_price=gas_price, node_gas_price=node_gas_price, ) # add the to address if not deploying a contract if to != b'': transaction['to'] = to_checksum_address(to) signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey) log_details = { 'node': pex(self.address), 'nonce': transaction['nonce'], 'gasLimit': transaction['gas'], 'gasPrice': transaction['gasPrice'], } log.debug('send_raw_transaction called', **log_details) tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction) self._available_nonce += 1 log.debug('send_raw_transaction returned', tx_hash=encode_hex(tx_hash), **log_details) return tx_hash
python
def send_transaction( self, to: Address, startgas: int, value: int = 0, data: bytes = b'', ) -> bytes: if to == to_canonical_address(constants.NULL_ADDRESS): warnings.warn('For contract creation the empty string must be used.') with self._nonce_lock: nonce = self._available_nonce gas_price = self.gas_price() transaction = { 'data': data, 'gas': startgas, 'nonce': nonce, 'value': value, 'gasPrice': gas_price, } node_gas_price = self.web3.eth.gasPrice log.debug( 'Calculated gas price for transaction', node=pex(self.address), calculated_gas_price=gas_price, node_gas_price=node_gas_price, ) # add the to address if not deploying a contract if to != b'': transaction['to'] = to_checksum_address(to) signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey) log_details = { 'node': pex(self.address), 'nonce': transaction['nonce'], 'gasLimit': transaction['gas'], 'gasPrice': transaction['gasPrice'], } log.debug('send_raw_transaction called', **log_details) tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction) self._available_nonce += 1 log.debug('send_raw_transaction returned', tx_hash=encode_hex(tx_hash), **log_details) return tx_hash
[ "def", "send_transaction", "(", "self", ",", "to", ":", "Address", ",", "startgas", ":", "int", ",", "value", ":", "int", "=", "0", ",", "data", ":", "bytes", "=", "b''", ",", ")", "->", "bytes", ":", "if", "to", "==", "to_canonical_address", "(", ...
Helper to send signed messages. This method will use the `privkey` provided in the constructor to locally sign the transaction. This requires an extended server implementation that accepts the variables v, r, and s.
[ "Helper", "to", "send", "signed", "messages", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L775-L828
235,424
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.poll
def poll( self, transaction_hash: bytes, ): """ Wait until the `transaction_hash` is applied or rejected. Args: transaction_hash: Transaction hash that we are waiting for. """ if len(transaction_hash) != 32: raise ValueError( 'transaction_hash must be a 32 byte hash', ) transaction_hash = encode_hex(transaction_hash) # used to check if the transaction was removed, this could happen # if gas price is too low: # # > Transaction (acbca3d6) below gas price (tx=1 Wei ask=18 # > Shannon). All sequential txs from this address(7d0eae79) # > will be ignored # last_result = None while True: # Could return None for a short period of time, until the # transaction is added to the pool transaction = self.web3.eth.getTransaction(transaction_hash) # if the transaction was added to the pool and then removed if transaction is None and last_result is not None: raise Exception('invalid transaction, check gas price') # the transaction was added to the pool and mined if transaction and transaction['blockNumber'] is not None: last_result = transaction # this will wait for both APPLIED and REVERTED transactions transaction_block = transaction['blockNumber'] confirmation_block = transaction_block + self.default_block_num_confirmations block_number = self.block_number() if block_number >= confirmation_block: return transaction gevent.sleep(1.0)
python
def poll( self, transaction_hash: bytes, ): if len(transaction_hash) != 32: raise ValueError( 'transaction_hash must be a 32 byte hash', ) transaction_hash = encode_hex(transaction_hash) # used to check if the transaction was removed, this could happen # if gas price is too low: # # > Transaction (acbca3d6) below gas price (tx=1 Wei ask=18 # > Shannon). All sequential txs from this address(7d0eae79) # > will be ignored # last_result = None while True: # Could return None for a short period of time, until the # transaction is added to the pool transaction = self.web3.eth.getTransaction(transaction_hash) # if the transaction was added to the pool and then removed if transaction is None and last_result is not None: raise Exception('invalid transaction, check gas price') # the transaction was added to the pool and mined if transaction and transaction['blockNumber'] is not None: last_result = transaction # this will wait for both APPLIED and REVERTED transactions transaction_block = transaction['blockNumber'] confirmation_block = transaction_block + self.default_block_num_confirmations block_number = self.block_number() if block_number >= confirmation_block: return transaction gevent.sleep(1.0)
[ "def", "poll", "(", "self", ",", "transaction_hash", ":", "bytes", ",", ")", ":", "if", "len", "(", "transaction_hash", ")", "!=", "32", ":", "raise", "ValueError", "(", "'transaction_hash must be a 32 byte hash'", ",", ")", "transaction_hash", "=", "encode_hex"...
Wait until the `transaction_hash` is applied or rejected. Args: transaction_hash: Transaction hash that we are waiting for.
[ "Wait", "until", "the", "transaction_hash", "is", "applied", "or", "rejected", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L830-L877
235,425
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.new_filter
def new_filter( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> StatelessFilter: """ Create a filter in the ethereum node. """ logs_blocks_sanity_check(from_block, to_block) return StatelessFilter( self.web3, { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, }, )
python
def new_filter( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> StatelessFilter: logs_blocks_sanity_check(from_block, to_block) return StatelessFilter( self.web3, { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, }, )
[ "def", "new_filter", "(", "self", ",", "contract_address", ":", "Address", ",", "topics", ":", "List", "[", "str", "]", "=", "None", ",", "from_block", ":", "BlockSpecification", "=", "0", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", ",", "...
Create a filter in the ethereum node.
[ "Create", "a", "filter", "in", "the", "ethereum", "node", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L879-L896
235,426
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.get_filter_events
def get_filter_events( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> List[Dict]: """ Get events for the given query. """ logs_blocks_sanity_check(from_block, to_block) return self.web3.eth.getLogs({ 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, })
python
def get_filter_events( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> List[Dict]: logs_blocks_sanity_check(from_block, to_block) return self.web3.eth.getLogs({ 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, })
[ "def", "get_filter_events", "(", "self", ",", "contract_address", ":", "Address", ",", "topics", ":", "List", "[", "str", "]", "=", "None", ",", "from_block", ":", "BlockSpecification", "=", "0", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", "...
Get events for the given query.
[ "Get", "events", "for", "the", "given", "query", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L898-L912
235,427
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.check_for_insufficient_eth
def check_for_insufficient_eth( self, transaction_name: str, transaction_executed: bool, required_gas: int, block_identifier: BlockSpecification, ): """ After estimate gas failure checks if our address has enough balance. If the account did not have enough ETH balance to execute the, transaction then it raises an `InsufficientFunds` error """ if transaction_executed: return our_address = to_checksum_address(self.address) balance = self.web3.eth.getBalance(our_address, block_identifier) required_balance = required_gas * self.gas_price() if balance < required_balance: msg = f'Failed to execute {transaction_name} due to insufficient ETH' log.critical(msg, required_wei=required_balance, actual_wei=balance) raise InsufficientFunds(msg)
python
def check_for_insufficient_eth( self, transaction_name: str, transaction_executed: bool, required_gas: int, block_identifier: BlockSpecification, ): if transaction_executed: return our_address = to_checksum_address(self.address) balance = self.web3.eth.getBalance(our_address, block_identifier) required_balance = required_gas * self.gas_price() if balance < required_balance: msg = f'Failed to execute {transaction_name} due to insufficient ETH' log.critical(msg, required_wei=required_balance, actual_wei=balance) raise InsufficientFunds(msg)
[ "def", "check_for_insufficient_eth", "(", "self", ",", "transaction_name", ":", "str", ",", "transaction_executed", ":", "bool", ",", "required_gas", ":", "int", ",", "block_identifier", ":", "BlockSpecification", ",", ")", ":", "if", "transaction_executed", ":", ...
After estimate gas failure checks if our address has enough balance. If the account did not have enough ETH balance to execute the, transaction then it raises an `InsufficientFunds` error
[ "After", "estimate", "gas", "failure", "checks", "if", "our", "address", "has", "enough", "balance", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L914-L935
235,428
raiden-network/raiden
raiden/utils/upgrades.py
get_db_version
def get_db_version(db_filename: Path) -> int: """Return the version value stored in the db""" assert os.path.exists(db_filename) # Perform a query directly through SQL rather than using # storage.get_version() # as get_version will return the latest version if it doesn't # find a record in the database. conn = sqlite3.connect( str(db_filename), detect_types=sqlite3.PARSE_DECLTYPES, ) cursor = conn.cursor() try: cursor.execute('SELECT value FROM settings WHERE name="version";') result = cursor.fetchone() except sqlite3.OperationalError: raise RuntimeError( 'Corrupted database. Database does not the settings table.', ) if not result: raise RuntimeError( 'Corrupted database. Settings table does not contain an entry the db version.', ) return int(result[0])
python
def get_db_version(db_filename: Path) -> int: assert os.path.exists(db_filename) # Perform a query directly through SQL rather than using # storage.get_version() # as get_version will return the latest version if it doesn't # find a record in the database. conn = sqlite3.connect( str(db_filename), detect_types=sqlite3.PARSE_DECLTYPES, ) cursor = conn.cursor() try: cursor.execute('SELECT value FROM settings WHERE name="version";') result = cursor.fetchone() except sqlite3.OperationalError: raise RuntimeError( 'Corrupted database. Database does not the settings table.', ) if not result: raise RuntimeError( 'Corrupted database. Settings table does not contain an entry the db version.', ) return int(result[0])
[ "def", "get_db_version", "(", "db_filename", ":", "Path", ")", "->", "int", ":", "assert", "os", ".", "path", ".", "exists", "(", "db_filename", ")", "# Perform a query directly through SQL rather than using", "# storage.get_version()", "# as get_version will return the lat...
Return the version value stored in the db
[ "Return", "the", "version", "value", "stored", "in", "the", "db" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/upgrades.py#L73-L101
235,429
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
get_or_deploy_token
def get_or_deploy_token(runner) -> Tuple[ContractProxy, int]: """ Deploy or reuse """ token_contract = runner.contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN) token_config = runner.scenario.get('token', {}) if not token_config: token_config = {} address = token_config.get('address') block = token_config.get('block', 0) reuse = token_config.get('reuse', False) token_address_file = runner.data_path.joinpath('token.infos') if reuse: if address: raise ScenarioError('Token settings "address" and "reuse" are mutually exclusive.') if token_address_file.exists(): token_data = json.loads(token_address_file.read_text()) address = token_data['address'] block = token_data['block'] if address: check_address_has_code(runner.client, address, 'Token') token_ctr = runner.client.new_contract_proxy(token_contract['abi'], address) log.debug( "Reusing token", address=to_checksum_address(address), name=token_ctr.contract.functions.name().call(), symbol=token_ctr.contract.functions.symbol().call(), ) return token_ctr, block token_id = uuid.uuid4() now = datetime.now() name = token_config.get('name', f"Scenario Test Token {token_id!s} {now:%Y-%m-%dT%H:%M}") symbol = token_config.get('symbol', f"T{token_id!s:.3}") decimals = token_config.get('decimals', 0) log.debug("Deploying token", name=name, symbol=symbol, decimals=decimals) token_ctr, receipt = runner.client.deploy_solidity_contract( 'CustomToken', runner.contract_manager.contracts, constructor_parameters=(0, decimals, name, symbol), ) contract_deployment_block = receipt['blockNumber'] contract_checksum_address = to_checksum_address(token_ctr.contract_address) if reuse: token_address_file.write_text(json.dumps({ 'address': contract_checksum_address, 'block': contract_deployment_block, })) log.info( "Deployed token", address=contract_checksum_address, name=name, symbol=symbol, ) return token_ctr, contract_deployment_block
python
def get_or_deploy_token(runner) -> Tuple[ContractProxy, int]: token_contract = runner.contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN) token_config = runner.scenario.get('token', {}) if not token_config: token_config = {} address = token_config.get('address') block = token_config.get('block', 0) reuse = token_config.get('reuse', False) token_address_file = runner.data_path.joinpath('token.infos') if reuse: if address: raise ScenarioError('Token settings "address" and "reuse" are mutually exclusive.') if token_address_file.exists(): token_data = json.loads(token_address_file.read_text()) address = token_data['address'] block = token_data['block'] if address: check_address_has_code(runner.client, address, 'Token') token_ctr = runner.client.new_contract_proxy(token_contract['abi'], address) log.debug( "Reusing token", address=to_checksum_address(address), name=token_ctr.contract.functions.name().call(), symbol=token_ctr.contract.functions.symbol().call(), ) return token_ctr, block token_id = uuid.uuid4() now = datetime.now() name = token_config.get('name', f"Scenario Test Token {token_id!s} {now:%Y-%m-%dT%H:%M}") symbol = token_config.get('symbol', f"T{token_id!s:.3}") decimals = token_config.get('decimals', 0) log.debug("Deploying token", name=name, symbol=symbol, decimals=decimals) token_ctr, receipt = runner.client.deploy_solidity_contract( 'CustomToken', runner.contract_manager.contracts, constructor_parameters=(0, decimals, name, symbol), ) contract_deployment_block = receipt['blockNumber'] contract_checksum_address = to_checksum_address(token_ctr.contract_address) if reuse: token_address_file.write_text(json.dumps({ 'address': contract_checksum_address, 'block': contract_deployment_block, })) log.info( "Deployed token", address=contract_checksum_address, name=name, symbol=symbol, ) return token_ctr, contract_deployment_block
[ "def", "get_or_deploy_token", "(", "runner", ")", "->", "Tuple", "[", "ContractProxy", ",", "int", "]", ":", "token_contract", "=", "runner", ".", "contract_manager", ".", "get_contract", "(", "CONTRACT_CUSTOM_TOKEN", ")", "token_config", "=", "runner", ".", "sc...
Deploy or reuse
[ "Deploy", "or", "reuse" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L199-L257
235,430
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
get_udc_and_token
def get_udc_and_token(runner) -> Tuple[Optional[ContractProxy], Optional[ContractProxy]]: """ Return contract proxies for the UserDepositContract and associated token """ from scenario_player.runner import ScenarioRunner assert isinstance(runner, ScenarioRunner) udc_config = runner.scenario.services.get('udc', {}) if not udc_config.get('enable', False): return None, None udc_address = udc_config.get('address') if udc_address is None: contracts = get_contracts_deployment_info( chain_id=runner.chain_id, version=DEVELOPMENT_CONTRACT_VERSION, ) udc_address = contracts['contracts'][CONTRACT_USER_DEPOSIT]['address'] udc_abi = runner.contract_manager.get_contract_abi(CONTRACT_USER_DEPOSIT) udc_proxy = runner.client.new_contract_proxy(udc_abi, udc_address) ud_token_address = udc_proxy.contract.functions.token().call() # FIXME: We assume the UD token is a CustomToken (supporting the `mint()` function) custom_token_abi = runner.contract_manager.get_contract_abi(CONTRACT_CUSTOM_TOKEN) ud_token_proxy = runner.client.new_contract_proxy(custom_token_abi, ud_token_address) return udc_proxy, ud_token_proxy
python
def get_udc_and_token(runner) -> Tuple[Optional[ContractProxy], Optional[ContractProxy]]: from scenario_player.runner import ScenarioRunner assert isinstance(runner, ScenarioRunner) udc_config = runner.scenario.services.get('udc', {}) if not udc_config.get('enable', False): return None, None udc_address = udc_config.get('address') if udc_address is None: contracts = get_contracts_deployment_info( chain_id=runner.chain_id, version=DEVELOPMENT_CONTRACT_VERSION, ) udc_address = contracts['contracts'][CONTRACT_USER_DEPOSIT]['address'] udc_abi = runner.contract_manager.get_contract_abi(CONTRACT_USER_DEPOSIT) udc_proxy = runner.client.new_contract_proxy(udc_abi, udc_address) ud_token_address = udc_proxy.contract.functions.token().call() # FIXME: We assume the UD token is a CustomToken (supporting the `mint()` function) custom_token_abi = runner.contract_manager.get_contract_abi(CONTRACT_CUSTOM_TOKEN) ud_token_proxy = runner.client.new_contract_proxy(custom_token_abi, ud_token_address) return udc_proxy, ud_token_proxy
[ "def", "get_udc_and_token", "(", "runner", ")", "->", "Tuple", "[", "Optional", "[", "ContractProxy", "]", ",", "Optional", "[", "ContractProxy", "]", "]", ":", "from", "scenario_player", ".", "runner", "import", "ScenarioRunner", "assert", "isinstance", "(", ...
Return contract proxies for the UserDepositContract and associated token
[ "Return", "contract", "proxies", "for", "the", "UserDepositContract", "and", "associated", "token" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L260-L285
235,431
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
mint_token_if_balance_low
def mint_token_if_balance_low( token_contract: ContractProxy, target_address: str, min_balance: int, fund_amount: int, gas_limit: int, mint_msg: str, no_action_msg: str = None, ) -> Optional[TransactionHash]: """ Check token balance and mint if below minimum """ balance = token_contract.contract.functions.balanceOf(target_address).call() if balance < min_balance: mint_amount = fund_amount - balance log.debug(mint_msg, address=target_address, amount=mint_amount) return token_contract.transact('mintFor', gas_limit, mint_amount, target_address) else: if no_action_msg: log.debug(no_action_msg, balance=balance) return None
python
def mint_token_if_balance_low( token_contract: ContractProxy, target_address: str, min_balance: int, fund_amount: int, gas_limit: int, mint_msg: str, no_action_msg: str = None, ) -> Optional[TransactionHash]: balance = token_contract.contract.functions.balanceOf(target_address).call() if balance < min_balance: mint_amount = fund_amount - balance log.debug(mint_msg, address=target_address, amount=mint_amount) return token_contract.transact('mintFor', gas_limit, mint_amount, target_address) else: if no_action_msg: log.debug(no_action_msg, balance=balance) return None
[ "def", "mint_token_if_balance_low", "(", "token_contract", ":", "ContractProxy", ",", "target_address", ":", "str", ",", "min_balance", ":", "int", ",", "fund_amount", ":", "int", ",", "gas_limit", ":", "int", ",", "mint_msg", ":", "str", ",", "no_action_msg", ...
Check token balance and mint if below minimum
[ "Check", "token", "balance", "and", "mint", "if", "below", "minimum" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L288-L307
235,432
raiden-network/raiden
raiden/storage/wal.py
WriteAheadLog.log_and_dispatch
def log_and_dispatch(self, state_change): """ Log and apply a state change. This function will first write the state change to the write-ahead-log, in case of a node crash the state change can be recovered and replayed to restore the node state. Events produced by applying state change are also saved. """ with self._lock: timestamp = datetime.utcnow().isoformat(timespec='milliseconds') state_change_id = self.storage.write_state_change(state_change, timestamp) self.state_change_id = state_change_id events = self.state_manager.dispatch(state_change) self.storage.write_events(state_change_id, events, timestamp) return events
python
def log_and_dispatch(self, state_change): with self._lock: timestamp = datetime.utcnow().isoformat(timespec='milliseconds') state_change_id = self.storage.write_state_change(state_change, timestamp) self.state_change_id = state_change_id events = self.state_manager.dispatch(state_change) self.storage.write_events(state_change_id, events, timestamp) return events
[ "def", "log_and_dispatch", "(", "self", ",", "state_change", ")", ":", "with", "self", ".", "_lock", ":", "timestamp", "=", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", "timespec", "=", "'milliseconds'", ")", "state_change_id", "=", "self", ...
Log and apply a state change. This function will first write the state change to the write-ahead-log, in case of a node crash the state change can be recovered and replayed to restore the node state. Events produced by applying state change are also saved.
[ "Log", "and", "apply", "a", "state", "change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/wal.py#L64-L83
235,433
raiden-network/raiden
raiden/storage/wal.py
WriteAheadLog.snapshot
def snapshot(self): """ Snapshot the application state. Snapshots are used to restore the application state, either after a restart or a crash. """ with self._lock: current_state = self.state_manager.current_state state_change_id = self.state_change_id # otherwise no state change was dispatched if state_change_id: self.storage.write_state_snapshot(state_change_id, current_state)
python
def snapshot(self): with self._lock: current_state = self.state_manager.current_state state_change_id = self.state_change_id # otherwise no state change was dispatched if state_change_id: self.storage.write_state_snapshot(state_change_id, current_state)
[ "def", "snapshot", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "current_state", "=", "self", ".", "state_manager", ".", "current_state", "state_change_id", "=", "self", ".", "state_change_id", "# otherwise no state change was dispatched", "if", "state_...
Snapshot the application state. Snapshots are used to restore the application state, either after a restart or a crash.
[ "Snapshot", "the", "application", "state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/wal.py#L85-L97
235,434
raiden-network/raiden
raiden/blockchain_events_handler.py
handle_tokennetwork_new
def handle_tokennetwork_new(raiden: 'RaidenService', event: Event): """ Handles a `TokenNetworkCreated` event. """ data = event.event_data args = data['args'] block_number = data['block_number'] token_network_address = args['token_network_address'] token_address = typing.TokenAddress(args['token_address']) block_hash = data['block_hash'] token_network_proxy = raiden.chain.token_network(token_network_address) raiden.blockchain_events.add_token_network_listener( token_network_proxy=token_network_proxy, contract_manager=raiden.contract_manager, from_block=block_number, ) token_network_state = TokenNetworkState( token_network_address, token_address, ) transaction_hash = event.event_data['transaction_hash'] new_token_network = ContractReceiveNewTokenNetwork( transaction_hash=transaction_hash, payment_network_identifier=event.originating_contract, token_network=token_network_state, block_number=block_number, block_hash=block_hash, ) raiden.handle_and_track_state_change(new_token_network)
python
def handle_tokennetwork_new(raiden: 'RaidenService', event: Event): data = event.event_data args = data['args'] block_number = data['block_number'] token_network_address = args['token_network_address'] token_address = typing.TokenAddress(args['token_address']) block_hash = data['block_hash'] token_network_proxy = raiden.chain.token_network(token_network_address) raiden.blockchain_events.add_token_network_listener( token_network_proxy=token_network_proxy, contract_manager=raiden.contract_manager, from_block=block_number, ) token_network_state = TokenNetworkState( token_network_address, token_address, ) transaction_hash = event.event_data['transaction_hash'] new_token_network = ContractReceiveNewTokenNetwork( transaction_hash=transaction_hash, payment_network_identifier=event.originating_contract, token_network=token_network_state, block_number=block_number, block_hash=block_hash, ) raiden.handle_and_track_state_change(new_token_network)
[ "def", "handle_tokennetwork_new", "(", "raiden", ":", "'RaidenService'", ",", "event", ":", "Event", ")", ":", "data", "=", "event", ".", "event_data", "args", "=", "data", "[", "'args'", "]", "block_number", "=", "data", "[", "'block_number'", "]", "token_n...
Handles a `TokenNetworkCreated` event.
[ "Handles", "a", "TokenNetworkCreated", "event", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain_events_handler.py#L45-L75
235,435
raiden-network/raiden
tools/scenario-player/scenario_player/tasks/blockchain.py
query_blockchain_events
def query_blockchain_events( web3: Web3, contract_manager: ContractManager, contract_address: Address, contract_name: str, topics: List, from_block: BlockNumber, to_block: BlockNumber, ) -> List[Dict]: """Returns events emmitted by a contract for a given event name, within a certain range. Args: web3: A Web3 instance contract_manager: A contract manager contract_address: The address of the contract to be filtered, can be `None` contract_name: The name of the contract topics: The topics to filter for from_block: The block to start search events to_block: The block to stop searching for events Returns: All matching events """ filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, } events = web3.eth.getLogs(filter_params) contract_abi = contract_manager.get_contract_abi(contract_name) return [ decode_event( abi=contract_abi, log_=raw_event, ) for raw_event in events ]
python
def query_blockchain_events( web3: Web3, contract_manager: ContractManager, contract_address: Address, contract_name: str, topics: List, from_block: BlockNumber, to_block: BlockNumber, ) -> List[Dict]: filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, } events = web3.eth.getLogs(filter_params) contract_abi = contract_manager.get_contract_abi(contract_name) return [ decode_event( abi=contract_abi, log_=raw_event, ) for raw_event in events ]
[ "def", "query_blockchain_events", "(", "web3", ":", "Web3", ",", "contract_manager", ":", "ContractManager", ",", "contract_address", ":", "Address", ",", "contract_name", ":", "str", ",", "topics", ":", "List", ",", "from_block", ":", "BlockNumber", ",", "to_bl...
Returns events emmitted by a contract for a given event name, within a certain range. Args: web3: A Web3 instance contract_manager: A contract manager contract_address: The address of the contract to be filtered, can be `None` contract_name: The name of the contract topics: The topics to filter for from_block: The block to start search events to_block: The block to stop searching for events Returns: All matching events
[ "Returns", "events", "emmitted", "by", "a", "contract", "for", "a", "given", "event", "name", "within", "a", "certain", "range", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/tasks/blockchain.py#L50-L89
235,436
raiden-network/raiden
raiden/storage/migrations/v16_to_v17.py
upgrade_v16_to_v17
def upgrade_v16_to_v17(storage: SQLiteStorage, old_version: int, current_version: int, **kwargs): """ InitiatorPaymentState was changed so that the "initiator" attribute is renamed to "initiator_transfers" and converted to a list. """ if old_version == SOURCE_VERSION: _transform_snapshots(storage) return TARGET_VERSION
python
def upgrade_v16_to_v17(storage: SQLiteStorage, old_version: int, current_version: int, **kwargs): if old_version == SOURCE_VERSION: _transform_snapshots(storage) return TARGET_VERSION
[ "def", "upgrade_v16_to_v17", "(", "storage", ":", "SQLiteStorage", ",", "old_version", ":", "int", ",", "current_version", ":", "int", ",", "*", "*", "kwargs", ")", ":", "if", "old_version", "==", "SOURCE_VERSION", ":", "_transform_snapshots", "(", "storage", ...
InitiatorPaymentState was changed so that the "initiator" attribute is renamed to "initiator_transfers" and converted to a list.
[ "InitiatorPaymentState", "was", "changed", "so", "that", "the", "initiator", "attribute", "is", "renamed", "to", "initiator_transfers", "and", "converted", "to", "a", "list", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v16_to_v17.py#L52-L59
235,437
raiden-network/raiden
raiden/storage/versions.py
filter_db_names
def filter_db_names(paths: List[str]) -> List[str]: """Returns a filtered list of `paths`, where every name matches our format. Args: paths: A list of file names. """ return [ db_path for db_path in paths if VERSION_RE.match(os.path.basename(db_path)) ]
python
def filter_db_names(paths: List[str]) -> List[str]: return [ db_path for db_path in paths if VERSION_RE.match(os.path.basename(db_path)) ]
[ "def", "filter_db_names", "(", "paths", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "[", "db_path", "for", "db_path", "in", "paths", "if", "VERSION_RE", ".", "match", "(", "os", ".", "path", ".", "basename", "(", ...
Returns a filtered list of `paths`, where every name matches our format. Args: paths: A list of file names.
[ "Returns", "a", "filtered", "list", "of", "paths", "where", "every", "name", "matches", "our", "format", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/versions.py#L37-L47
235,438
raiden-network/raiden
raiden/network/proxies/utils.py
compare_contract_versions
def compare_contract_versions( proxy: ContractProxy, expected_version: str, contract_name: str, address: Address, ) -> None: """Compare version strings of a contract. If not matching raise ContractVersionMismatch. Also may raise AddressWrongContract if the contract contains no code.""" assert isinstance(expected_version, str) try: deployed_version = proxy.contract.functions.contract_version().call() except BadFunctionCallOutput: raise AddressWrongContract('') deployed_version = deployed_version.replace('_', '0') expected_version = expected_version.replace('_', '0') deployed = [int(x) for x in deployed_version.split('.')] expected = [int(x) for x in expected_version.split('.')] if deployed != expected: raise ContractVersionMismatch( f'Provided {contract_name} contract ({to_normalized_address(address)}) ' f'version mismatch. Expected: {expected_version} Got: {deployed_version}', )
python
def compare_contract_versions( proxy: ContractProxy, expected_version: str, contract_name: str, address: Address, ) -> None: assert isinstance(expected_version, str) try: deployed_version = proxy.contract.functions.contract_version().call() except BadFunctionCallOutput: raise AddressWrongContract('') deployed_version = deployed_version.replace('_', '0') expected_version = expected_version.replace('_', '0') deployed = [int(x) for x in deployed_version.split('.')] expected = [int(x) for x in expected_version.split('.')] if deployed != expected: raise ContractVersionMismatch( f'Provided {contract_name} contract ({to_normalized_address(address)}) ' f'version mismatch. Expected: {expected_version} Got: {deployed_version}', )
[ "def", "compare_contract_versions", "(", "proxy", ":", "ContractProxy", ",", "expected_version", ":", "str", ",", "contract_name", ":", "str", ",", "address", ":", "Address", ",", ")", "->", "None", ":", "assert", "isinstance", "(", "expected_version", ",", "s...
Compare version strings of a contract. If not matching raise ContractVersionMismatch. Also may raise AddressWrongContract if the contract contains no code.
[ "Compare", "version", "strings", "of", "a", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/utils.py#L16-L42
235,439
raiden-network/raiden
raiden/network/proxies/utils.py
get_onchain_locksroots
def get_onchain_locksroots( chain: 'BlockChainService', canonical_identifier: CanonicalIdentifier, participant1: Address, participant2: Address, block_identifier: BlockSpecification, ) -> Tuple[Locksroot, Locksroot]: """Return the locksroot for `participant1` and `participant2` at `block_identifier`.""" payment_channel = chain.payment_channel(canonical_identifier=canonical_identifier) token_network = payment_channel.token_network # This will not raise RaidenRecoverableError because we are providing the channel_identifier participants_details = token_network.detail_participants( participant1=participant1, participant2=participant2, channel_identifier=canonical_identifier.channel_identifier, block_identifier=block_identifier, ) our_details = participants_details.our_details our_locksroot = our_details.locksroot partner_details = participants_details.partner_details partner_locksroot = partner_details.locksroot return our_locksroot, partner_locksroot
python
def get_onchain_locksroots( chain: 'BlockChainService', canonical_identifier: CanonicalIdentifier, participant1: Address, participant2: Address, block_identifier: BlockSpecification, ) -> Tuple[Locksroot, Locksroot]: payment_channel = chain.payment_channel(canonical_identifier=canonical_identifier) token_network = payment_channel.token_network # This will not raise RaidenRecoverableError because we are providing the channel_identifier participants_details = token_network.detail_participants( participant1=participant1, participant2=participant2, channel_identifier=canonical_identifier.channel_identifier, block_identifier=block_identifier, ) our_details = participants_details.our_details our_locksroot = our_details.locksroot partner_details = participants_details.partner_details partner_locksroot = partner_details.locksroot return our_locksroot, partner_locksroot
[ "def", "get_onchain_locksroots", "(", "chain", ":", "'BlockChainService'", ",", "canonical_identifier", ":", "CanonicalIdentifier", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", ")", ...
Return the locksroot for `participant1` and `participant2` at `block_identifier`.
[ "Return", "the", "locksroot", "for", "participant1", "and", "participant2", "at", "block_identifier", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/utils.py#L45-L70
235,440
raiden-network/raiden
raiden/transfer/node.py
inplace_delete_message_queue
def inplace_delete_message_queue( chain_state: ChainState, state_change: Union[ReceiveDelivered, ReceiveProcessed], queueid: QueueIdentifier, ) -> None: """ Filter messages from queue, if the queue becomes empty, cleanup the queue itself. """ queue = chain_state.queueids_to_queues.get(queueid) if not queue: return inplace_delete_message( message_queue=queue, state_change=state_change, ) if len(queue) == 0: del chain_state.queueids_to_queues[queueid] else: chain_state.queueids_to_queues[queueid] = queue
python
def inplace_delete_message_queue( chain_state: ChainState, state_change: Union[ReceiveDelivered, ReceiveProcessed], queueid: QueueIdentifier, ) -> None: queue = chain_state.queueids_to_queues.get(queueid) if not queue: return inplace_delete_message( message_queue=queue, state_change=state_change, ) if len(queue) == 0: del chain_state.queueids_to_queues[queueid] else: chain_state.queueids_to_queues[queueid] = queue
[ "def", "inplace_delete_message_queue", "(", "chain_state", ":", "ChainState", ",", "state_change", ":", "Union", "[", "ReceiveDelivered", ",", "ReceiveProcessed", "]", ",", "queueid", ":", "QueueIdentifier", ",", ")", "->", "None", ":", "queue", "=", "chain_state"...
Filter messages from queue, if the queue becomes empty, cleanup the queue itself.
[ "Filter", "messages", "from", "queue", "if", "the", "queue", "becomes", "empty", "cleanup", "the", "queue", "itself", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L498-L516
235,441
raiden-network/raiden
raiden/transfer/node.py
inplace_delete_message
def inplace_delete_message( message_queue: List[SendMessageEvent], state_change: Union[ReceiveDelivered, ReceiveProcessed], ) -> None: """ Check if the message exists in queue with ID `queueid` and exclude if found.""" for message in list(message_queue): message_found = ( message.message_identifier == state_change.message_identifier and message.recipient == state_change.sender ) if message_found: message_queue.remove(message)
python
def inplace_delete_message( message_queue: List[SendMessageEvent], state_change: Union[ReceiveDelivered, ReceiveProcessed], ) -> None: for message in list(message_queue): message_found = ( message.message_identifier == state_change.message_identifier and message.recipient == state_change.sender ) if message_found: message_queue.remove(message)
[ "def", "inplace_delete_message", "(", "message_queue", ":", "List", "[", "SendMessageEvent", "]", ",", "state_change", ":", "Union", "[", "ReceiveDelivered", ",", "ReceiveProcessed", "]", ",", ")", "->", "None", ":", "for", "message", "in", "list", "(", "messa...
Check if the message exists in queue with ID `queueid` and exclude if found.
[ "Check", "if", "the", "message", "exists", "in", "queue", "with", "ID", "queueid", "and", "exclude", "if", "found", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L519-L530
235,442
raiden-network/raiden
raiden/transfer/node.py
handle_delivered
def handle_delivered( chain_state: ChainState, state_change: ReceiveDelivered, ) -> TransitionResult[ChainState]: """ Check if the "Delivered" message exists in the global queue and delete if found.""" queueid = QueueIdentifier(state_change.sender, CHANNEL_IDENTIFIER_GLOBAL_QUEUE) inplace_delete_message_queue(chain_state, state_change, queueid) return TransitionResult(chain_state, [])
python
def handle_delivered( chain_state: ChainState, state_change: ReceiveDelivered, ) -> TransitionResult[ChainState]: queueid = QueueIdentifier(state_change.sender, CHANNEL_IDENTIFIER_GLOBAL_QUEUE) inplace_delete_message_queue(chain_state, state_change, queueid) return TransitionResult(chain_state, [])
[ "def", "handle_delivered", "(", "chain_state", ":", "ChainState", ",", "state_change", ":", "ReceiveDelivered", ",", ")", "->", "TransitionResult", "[", "ChainState", "]", ":", "queueid", "=", "QueueIdentifier", "(", "state_change", ".", "sender", ",", "CHANNEL_ID...
Check if the "Delivered" message exists in the global queue and delete if found.
[ "Check", "if", "the", "Delivered", "message", "exists", "in", "the", "global", "queue", "and", "delete", "if", "found", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L620-L627
235,443
raiden-network/raiden
raiden/transfer/node.py
is_transaction_effect_satisfied
def is_transaction_effect_satisfied( chain_state: ChainState, transaction: ContractSendEvent, state_change: StateChange, ) -> bool: """ True if the side-effect of `transaction` is satisfied by `state_change`. This predicate is used to clear the transaction queue. This should only be done once the expected side effect of a transaction is achieved. This doesn't necessarily mean that the transaction sent by *this* node was mined, but only that *some* transaction which achieves the same side-effect was successfully executed and mined. This distinction is important for restarts and to reduce the number of state changes. On restarts: The state of the on-chain channel could have changed while the node was offline. Once the node learns about the change (e.g. the channel was settled), new transactions can be dispatched by Raiden as a side effect for the on-chain *event* (e.g. do the batch unlock with the latest merkle tree), but the dispatched transaction could have been completed by another agent (e.g. the partner node). For these cases, the transaction from a different address which achieves the same side-effect is sufficient, otherwise unnecessary transactions would be sent by the node. NOTE: The above is not important for transactions sent as a side-effect for a new *block*. On restart the node first synchronizes its state by querying for new events, only after the off-chain state is up-to-date, a Block state change is dispatched. At this point some transactions are not required anymore and therefore are not dispatched. On the number of state changes: Accepting a transaction from another address removes the need for clearing state changes, e.g. when our node's close transaction fails but its partner's close transaction succeeds. """ # These transactions are not made atomic through the WAL. They are sent # exclusively through the external APIs. # # - ContractReceiveChannelNew # - ContractReceiveChannelNewBalance # - ContractReceiveNewPaymentNetwork # - ContractReceiveNewTokenNetwork # - ContractReceiveRouteNew # # Note: Deposits and Withdraws must consider a transaction with a higher # value as sufficient, because the values are monotonically increasing and # the transaction with a lower value will never be executed. # Transactions are used to change the on-chain state of a channel. It # doesn't matter if the sender of the transaction is the local node or # another node authorized to perform the operation. So, for the following # transactions, as long as the side-effects are the same, the local # transaction can be removed from the queue. # # - An update transfer can be done by a trusted third party (i.e. monitoring service) # - A close transaction can be sent by our partner # - A settle transaction can be sent by anyone # - A secret reveal can be done by anyone # - A lower nonce is not a valid replacement, since that is an older balance # proof # - A larger raiden state change nonce is impossible. # That would require the partner node to produce an invalid balance proof, # and this node to accept the invalid balance proof and sign it is_valid_update_transfer = ( isinstance(state_change, ContractReceiveUpdateTransfer) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier and state_change.nonce == transaction.balance_proof.nonce ) if is_valid_update_transfer: return True # The balance proof data cannot be verified, the local close could have # lost a race against a remote close, and the balance proof data would be # the one provided by this node's partner is_valid_close = ( isinstance(state_change, ContractReceiveChannelClosed) and isinstance(transaction, ContractSendChannelClose) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_close: return True is_valid_settle = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelSettle) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_settle: return True is_valid_secret_reveal = ( isinstance(state_change, ContractReceiveSecretReveal) and isinstance(transaction, ContractSendSecretReveal) and state_change.secret == transaction.secret ) if is_valid_secret_reveal: return True is_batch_unlock = ( isinstance(state_change, ContractReceiveChannelBatchUnlock) and isinstance(transaction, ContractSendChannelBatchUnlock) ) if is_batch_unlock: assert isinstance(state_change, ContractReceiveChannelBatchUnlock), MYPY_ANNOTATION assert isinstance(transaction, ContractSendChannelBatchUnlock), MYPY_ANNOTATION our_address = chain_state.our_address # Don't assume that because we sent the transaction, we are a # participant partner_address = None if state_change.participant == our_address: partner_address = state_change.partner elif state_change.partner == our_address: partner_address = state_change.participant # Use the second address as the partner address, but check that a # channel exists for our_address and partner_address if partner_address: channel_state = views.get_channelstate_by_token_network_and_partner( chain_state, TokenNetworkID(state_change.token_network_identifier), partner_address, ) # If the channel was cleared, that means that both # sides of the channel were successfully unlocked. # In this case, we clear the batch unlock # transaction from the queue only in case there # were no more locked funds to unlock. if channel_state is None: return True return False
python
def is_transaction_effect_satisfied( chain_state: ChainState, transaction: ContractSendEvent, state_change: StateChange, ) -> bool: # These transactions are not made atomic through the WAL. They are sent # exclusively through the external APIs. # # - ContractReceiveChannelNew # - ContractReceiveChannelNewBalance # - ContractReceiveNewPaymentNetwork # - ContractReceiveNewTokenNetwork # - ContractReceiveRouteNew # # Note: Deposits and Withdraws must consider a transaction with a higher # value as sufficient, because the values are monotonically increasing and # the transaction with a lower value will never be executed. # Transactions are used to change the on-chain state of a channel. It # doesn't matter if the sender of the transaction is the local node or # another node authorized to perform the operation. So, for the following # transactions, as long as the side-effects are the same, the local # transaction can be removed from the queue. # # - An update transfer can be done by a trusted third party (i.e. monitoring service) # - A close transaction can be sent by our partner # - A settle transaction can be sent by anyone # - A secret reveal can be done by anyone # - A lower nonce is not a valid replacement, since that is an older balance # proof # - A larger raiden state change nonce is impossible. # That would require the partner node to produce an invalid balance proof, # and this node to accept the invalid balance proof and sign it is_valid_update_transfer = ( isinstance(state_change, ContractReceiveUpdateTransfer) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier and state_change.nonce == transaction.balance_proof.nonce ) if is_valid_update_transfer: return True # The balance proof data cannot be verified, the local close could have # lost a race against a remote close, and the balance proof data would be # the one provided by this node's partner is_valid_close = ( isinstance(state_change, ContractReceiveChannelClosed) and isinstance(transaction, ContractSendChannelClose) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_close: return True is_valid_settle = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelSettle) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_settle: return True is_valid_secret_reveal = ( isinstance(state_change, ContractReceiveSecretReveal) and isinstance(transaction, ContractSendSecretReveal) and state_change.secret == transaction.secret ) if is_valid_secret_reveal: return True is_batch_unlock = ( isinstance(state_change, ContractReceiveChannelBatchUnlock) and isinstance(transaction, ContractSendChannelBatchUnlock) ) if is_batch_unlock: assert isinstance(state_change, ContractReceiveChannelBatchUnlock), MYPY_ANNOTATION assert isinstance(transaction, ContractSendChannelBatchUnlock), MYPY_ANNOTATION our_address = chain_state.our_address # Don't assume that because we sent the transaction, we are a # participant partner_address = None if state_change.participant == our_address: partner_address = state_change.partner elif state_change.partner == our_address: partner_address = state_change.participant # Use the second address as the partner address, but check that a # channel exists for our_address and partner_address if partner_address: channel_state = views.get_channelstate_by_token_network_and_partner( chain_state, TokenNetworkID(state_change.token_network_identifier), partner_address, ) # If the channel was cleared, that means that both # sides of the channel were successfully unlocked. # In this case, we clear the batch unlock # transaction from the queue only in case there # were no more locked funds to unlock. if channel_state is None: return True return False
[ "def", "is_transaction_effect_satisfied", "(", "chain_state", ":", "ChainState", ",", "transaction", ":", "ContractSendEvent", ",", "state_change", ":", "StateChange", ",", ")", "->", "bool", ":", "# These transactions are not made atomic through the WAL. They are sent", "# e...
True if the side-effect of `transaction` is satisfied by `state_change`. This predicate is used to clear the transaction queue. This should only be done once the expected side effect of a transaction is achieved. This doesn't necessarily mean that the transaction sent by *this* node was mined, but only that *some* transaction which achieves the same side-effect was successfully executed and mined. This distinction is important for restarts and to reduce the number of state changes. On restarts: The state of the on-chain channel could have changed while the node was offline. Once the node learns about the change (e.g. the channel was settled), new transactions can be dispatched by Raiden as a side effect for the on-chain *event* (e.g. do the batch unlock with the latest merkle tree), but the dispatched transaction could have been completed by another agent (e.g. the partner node). For these cases, the transaction from a different address which achieves the same side-effect is sufficient, otherwise unnecessary transactions would be sent by the node. NOTE: The above is not important for transactions sent as a side-effect for a new *block*. On restart the node first synchronizes its state by querying for new events, only after the off-chain state is up-to-date, a Block state change is dispatched. At this point some transactions are not required anymore and therefore are not dispatched. On the number of state changes: Accepting a transaction from another address removes the need for clearing state changes, e.g. when our node's close transaction fails but its partner's close transaction succeeds.
[ "True", "if", "the", "side", "-", "effect", "of", "transaction", "is", "satisfied", "by", "state_change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1043-L1180
235,444
raiden-network/raiden
raiden/transfer/node.py
is_transaction_invalidated
def is_transaction_invalidated(transaction, state_change): """ True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local transaction is executed before it. The first case is handled by the predicate `is_transaction_effect_satisfied`, where a transaction from a different source which does the same thing is considered. This predicate handles the second scenario. A transaction can **only** invalidate another iff both share a valid initial state but a different end state. Valid example: A close can invalidate a deposit, because both a close and a deposit can be executed from an opened state (same initial state), but a close transaction will transition the channel to a closed state which doesn't allow for deposits (different end state). Invalid example: A settle transaction cannot invalidate a deposit because a settle is only allowed for the closed state and deposits are only allowed for the open state. In such a case a deposit should never have been sent. The deposit transaction for an invalid state is a bug and not a transaction which was invalidated. """ # Most transactions cannot be invalidated by others. These are: # # - close transactions # - settle transactions # - batch unlocks # # Deposits and withdraws are invalidated by the close, but these are not # made atomic through the WAL. is_our_failed_update_transfer = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_our_failed_update_transfer: return True return False
python
def is_transaction_invalidated(transaction, state_change): # Most transactions cannot be invalidated by others. These are: # # - close transactions # - settle transactions # - batch unlocks # # Deposits and withdraws are invalidated by the close, but these are not # made atomic through the WAL. is_our_failed_update_transfer = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_our_failed_update_transfer: return True return False
[ "def", "is_transaction_invalidated", "(", "transaction", ",", "state_change", ")", ":", "# Most transactions cannot be invalidated by others. These are:", "#", "# - close transactions", "# - settle transactions", "# - batch unlocks", "#", "# Deposits and withdraws are invalidated by the ...
True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local transaction is executed before it. The first case is handled by the predicate `is_transaction_effect_satisfied`, where a transaction from a different source which does the same thing is considered. This predicate handles the second scenario. A transaction can **only** invalidate another iff both share a valid initial state but a different end state. Valid example: A close can invalidate a deposit, because both a close and a deposit can be executed from an opened state (same initial state), but a close transaction will transition the channel to a closed state which doesn't allow for deposits (different end state). Invalid example: A settle transaction cannot invalidate a deposit because a settle is only allowed for the closed state and deposits are only allowed for the open state. In such a case a deposit should never have been sent. The deposit transaction for an invalid state is a bug and not a transaction which was invalidated.
[ "True", "if", "the", "transaction", "is", "made", "invalid", "by", "state_change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1183-L1232
235,445
raiden-network/raiden
raiden/transfer/node.py
is_transaction_expired
def is_transaction_expired(transaction, block_number): """ True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. If the current block is higher than any of these expirations blocks, the transaction is expired and cannot be successfully executed. """ is_update_expired = ( isinstance(transaction, ContractSendChannelUpdateTransfer) and transaction.expiration < block_number ) if is_update_expired: return True is_secret_register_expired = ( isinstance(transaction, ContractSendSecretReveal) and transaction.expiration < block_number ) if is_secret_register_expired: return True return False
python
def is_transaction_expired(transaction, block_number): is_update_expired = ( isinstance(transaction, ContractSendChannelUpdateTransfer) and transaction.expiration < block_number ) if is_update_expired: return True is_secret_register_expired = ( isinstance(transaction, ContractSendSecretReveal) and transaction.expiration < block_number ) if is_secret_register_expired: return True return False
[ "def", "is_transaction_expired", "(", "transaction", ",", "block_number", ")", ":", "is_update_expired", "=", "(", "isinstance", "(", "transaction", ",", "ContractSendChannelUpdateTransfer", ")", "and", "transaction", ".", "expiration", "<", "block_number", ")", "if",...
True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. If the current block is higher than any of these expirations blocks, the transaction is expired and cannot be successfully executed.
[ "True", "if", "transaction", "cannot", "be", "mined", "because", "it", "has", "expired", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1235-L1259
235,446
raiden-network/raiden
raiden/network/proxies/user_deposit.py
UserDeposit.deposit
def deposit( self, beneficiary: Address, total_deposit: TokenAmount, block_identifier: BlockSpecification, ) -> None: """ Deposit provided amount into the user-deposit contract to the beneficiary's account. """ token_address = self.token_address(block_identifier) token = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) log_details = { 'beneficiary': pex(beneficiary), 'contract': pex(self.address), 'total_deposit': total_deposit, } checking_block = self.client.get_checking_block() error_prefix = 'Call to deposit will fail' with self.deposit_lock: amount_to_deposit, log_details = self._deposit_preconditions( total_deposit=total_deposit, beneficiary=beneficiary, token=token, block_identifier=block_identifier, ) gas_limit = self.proxy.estimate_gas( checking_block, 'deposit', to_checksum_address(beneficiary), total_deposit, ) if gas_limit: error_prefix = 'Call to deposit failed' log.debug('deposit called', **log_details) transaction_hash = self.proxy.transact( 'deposit', safe_gas_limit(gas_limit), to_checksum_address(beneficiary), total_deposit, ) self.client.poll(transaction_hash) receipt_or_none = check_transaction_threw(self.client, transaction_hash) transaction_executed = gas_limit is not None if not transaction_executed or receipt_or_none: if transaction_executed: block = receipt_or_none['blockNumber'] else: block = checking_block self.proxy.jsonrpc_client.check_for_insufficient_eth( transaction_name='deposit', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_UDC_DEPOSIT, block_identifier=block, ) msg = self._check_why_deposit_failed( token=token, amount_to_deposit=amount_to_deposit, total_deposit=total_deposit, block_identifier=block, ) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('deposit successful', **log_details)
python
def deposit( self, beneficiary: Address, total_deposit: TokenAmount, block_identifier: BlockSpecification, ) -> None: token_address = self.token_address(block_identifier) token = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) log_details = { 'beneficiary': pex(beneficiary), 'contract': pex(self.address), 'total_deposit': total_deposit, } checking_block = self.client.get_checking_block() error_prefix = 'Call to deposit will fail' with self.deposit_lock: amount_to_deposit, log_details = self._deposit_preconditions( total_deposit=total_deposit, beneficiary=beneficiary, token=token, block_identifier=block_identifier, ) gas_limit = self.proxy.estimate_gas( checking_block, 'deposit', to_checksum_address(beneficiary), total_deposit, ) if gas_limit: error_prefix = 'Call to deposit failed' log.debug('deposit called', **log_details) transaction_hash = self.proxy.transact( 'deposit', safe_gas_limit(gas_limit), to_checksum_address(beneficiary), total_deposit, ) self.client.poll(transaction_hash) receipt_or_none = check_transaction_threw(self.client, transaction_hash) transaction_executed = gas_limit is not None if not transaction_executed or receipt_or_none: if transaction_executed: block = receipt_or_none['blockNumber'] else: block = checking_block self.proxy.jsonrpc_client.check_for_insufficient_eth( transaction_name='deposit', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_UDC_DEPOSIT, block_identifier=block, ) msg = self._check_why_deposit_failed( token=token, amount_to_deposit=amount_to_deposit, total_deposit=total_deposit, block_identifier=block, ) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('deposit successful', **log_details)
[ "def", "deposit", "(", "self", ",", "beneficiary", ":", "Address", ",", "total_deposit", ":", "TokenAmount", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "None", ":", "token_address", "=", "self", ".", "token_address", "(", "block_identifi...
Deposit provided amount into the user-deposit contract to the beneficiary's account.
[ "Deposit", "provided", "amount", "into", "the", "user", "-", "deposit", "contract", "to", "the", "beneficiary", "s", "account", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/user_deposit.py#L68-L144
235,447
raiden-network/raiden
raiden/network/proxies/user_deposit.py
UserDeposit.effective_balance
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance: """ The user's balance with planned withdrawals deducted. """ fn = getattr(self.proxy.contract.functions, 'effectiveBalance') balance = fn(address).call(block_identifier=block_identifier) if balance == b'': raise RuntimeError(f"Call to 'effectiveBalance' returned nothing") return balance
python
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance: fn = getattr(self.proxy.contract.functions, 'effectiveBalance') balance = fn(address).call(block_identifier=block_identifier) if balance == b'': raise RuntimeError(f"Call to 'effectiveBalance' returned nothing") return balance
[ "def", "effective_balance", "(", "self", ",", "address", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "Balance", ":", "fn", "=", "getattr", "(", "self", ".", "proxy", ".", "contract", ".", "functions", ",", "'effectiveBalance'...
The user's balance with planned withdrawals deducted.
[ "The", "user", "s", "balance", "with", "planned", "withdrawals", "deducted", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/user_deposit.py#L146-L154
235,448
raiden-network/raiden
raiden/encoding/encoders.py
integer.validate
def validate(self, value: int): ''' Validates the integer is in the value range. ''' if not isinstance(value, int): raise ValueError('value is not an integer') if self.minimum > value or self.maximum < value: msg = ( '{} is outside the valide range [{},{}]' ).format(value, self.minimum, self.maximum) raise ValueError(msg)
python
def validate(self, value: int): ''' Validates the integer is in the value range. ''' if not isinstance(value, int): raise ValueError('value is not an integer') if self.minimum > value or self.maximum < value: msg = ( '{} is outside the valide range [{},{}]' ).format(value, self.minimum, self.maximum) raise ValueError(msg)
[ "def", "validate", "(", "self", ",", "value", ":", "int", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "ValueError", "(", "'value is not an integer'", ")", "if", "self", ".", "minimum", ">", "value", "or", "self", "...
Validates the integer is in the value range.
[ "Validates", "the", "integer", "is", "in", "the", "value", "range", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/encoding/encoders.py#L11-L20
235,449
raiden-network/raiden
raiden/api/python.py
event_filter_for_payments
def event_filter_for_payments( event: architecture.Event, token_network_identifier: TokenNetworkID = None, partner_address: Address = None, ) -> bool: """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. """ is_matching_event = ( isinstance(event, EVENTS_PAYMENT_HISTORY_RELATED) and ( token_network_identifier is None or token_network_identifier == event.token_network_identifier ) ) if not is_matching_event: return False sent_and_target_matches = ( isinstance(event, (EventPaymentSentFailed, EventPaymentSentSuccess)) and ( partner_address is None or event.target == partner_address ) ) received_and_initiator_matches = ( isinstance(event, EventPaymentReceivedSuccess) and ( partner_address is None or event.initiator == partner_address ) ) return sent_and_target_matches or received_and_initiator_matches
python
def event_filter_for_payments( event: architecture.Event, token_network_identifier: TokenNetworkID = None, partner_address: Address = None, ) -> bool: is_matching_event = ( isinstance(event, EVENTS_PAYMENT_HISTORY_RELATED) and ( token_network_identifier is None or token_network_identifier == event.token_network_identifier ) ) if not is_matching_event: return False sent_and_target_matches = ( isinstance(event, (EventPaymentSentFailed, EventPaymentSentSuccess)) and ( partner_address is None or event.target == partner_address ) ) received_and_initiator_matches = ( isinstance(event, EventPaymentReceivedSuccess) and ( partner_address is None or event.initiator == partner_address ) ) return sent_and_target_matches or received_and_initiator_matches
[ "def", "event_filter_for_payments", "(", "event", ":", "architecture", ".", "Event", ",", "token_network_identifier", ":", "TokenNetworkID", "=", "None", ",", "partner_address", ":", "Address", "=", "None", ",", ")", "->", "bool", ":", "is_matching_event", "=", ...
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.
[ "Filters", "out", "non", "payment", "history", "related", "events" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L83-L120
235,450
raiden-network/raiden
raiden/api/python.py
RaidenAPI.token_network_register
def token_network_register( self, registry_address: PaymentNetworkID, token_address: TokenAddress, channel_participant_deposit_limit: TokenAmount, token_network_deposit_limit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetworkAddress: """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. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address in self.get_tokens_list(registry_address): raise AlreadyRegisteredTokenAddress('Token already registered') contracts_version = self.raiden.contract_manager.contracts_version registry = self.raiden.chain.token_network_registry(registry_address) try: if contracts_version == DEVELOPMENT_CONTRACT_VERSION: return registry.add_token_with_limits( token_address=token_address, channel_participant_deposit_limit=channel_participant_deposit_limit, token_network_deposit_limit=token_network_deposit_limit, ) else: return registry.add_token_without_limits( token_address=token_address, ) except RaidenRecoverableError as e: if 'Token already registered' in str(e): raise AlreadyRegisteredTokenAddress('Token already registered') # else raise finally: # Assume the transaction failed because the token is already # registered with the smart contract and this node has not yet # polled for the event (otherwise the check above would have # failed). # # To provide a consistent view to the user, wait one block, this # will guarantee that the events have been processed. next_block = self.raiden.get_block_number() + 1 waiting.wait_for_block(self.raiden, next_block, retry_timeout)
python
def token_network_register( self, registry_address: PaymentNetworkID, token_address: TokenAddress, channel_participant_deposit_limit: TokenAmount, token_network_deposit_limit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetworkAddress: if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address in self.get_tokens_list(registry_address): raise AlreadyRegisteredTokenAddress('Token already registered') contracts_version = self.raiden.contract_manager.contracts_version registry = self.raiden.chain.token_network_registry(registry_address) try: if contracts_version == DEVELOPMENT_CONTRACT_VERSION: return registry.add_token_with_limits( token_address=token_address, channel_participant_deposit_limit=channel_participant_deposit_limit, token_network_deposit_limit=token_network_deposit_limit, ) else: return registry.add_token_without_limits( token_address=token_address, ) except RaidenRecoverableError as e: if 'Token already registered' in str(e): raise AlreadyRegisteredTokenAddress('Token already registered') # else raise finally: # Assume the transaction failed because the token is already # registered with the smart contract and this node has not yet # polled for the event (otherwise the check above would have # failed). # # To provide a consistent view to the user, wait one block, this # will guarantee that the events have been processed. next_block = self.raiden.get_block_number() + 1 waiting.wait_for_block(self.raiden, next_block, retry_timeout)
[ "def", "token_network_register", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "channel_participant_deposit_limit", ":", "TokenAmount", ",", "token_network_deposit_limit", ":", "TokenAmount", ",", "retry_timeo...
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.
[ "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", "...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L220-L279
235,451
raiden-network/raiden
raiden/api/python.py
RaidenAPI.token_network_connect
def token_network_connect( self, registry_address: PaymentNetworkID, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: """ 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. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( raiden=self.raiden, channels_to_open=initial_channel_target, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) connection_manager.connect( funds=funds, initial_channel_target=initial_channel_target, joinable_funds_target=joinable_funds_target, )
python
def token_network_connect( self, registry_address: PaymentNetworkID, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( raiden=self.raiden, channels_to_open=initial_channel_target, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) connection_manager.connect( funds=funds, initial_channel_target=initial_channel_target, joinable_funds_target=joinable_funds_target, )
[ "def", "token_network_connect", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "funds", ":", "TokenAmount", ",", "initial_channel_target", ":", "int", "=", "3", ",", "joinable_funds_target", ":", "float...
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.
[ "Automatically", "maintain", "channels", "open", "for", "the", "given", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L281-L329
235,452
raiden-network/raiden
raiden/api/python.py
RaidenAPI.token_network_leave
def token_network_leave( self, registry_address: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """ Close all channels and wait for settlement. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address not in self.get_tokens_list(registry_address): raise UnknownTokenAddress('token_address unknown') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) return connection_manager.leave(registry_address)
python
def token_network_leave( self, registry_address: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address not in self.get_tokens_list(registry_address): raise UnknownTokenAddress('token_address unknown') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) return connection_manager.leave(registry_address)
[ "def", "token_network_leave", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "if", "not", "is_binary_address", "(", "registry_address", ")", ":...
Close all channels and wait for settlement.
[ "Close", "all", "channels", "and", "wait", "for", "settlement", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L331-L355
235,453
raiden-network/raiden
raiden/api/python.py
RaidenAPI.channel_open
def channel_open( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: """ Open a channel with the peer at `partner_address` with the given `token_address`. """ if settle_timeout is None: settle_timeout = self.raiden.config['settle_timeout'] if settle_timeout < self.raiden.config['reveal_timeout'] * 2: raise InvalidSettleTimeout( 'settle_timeout can not be smaller than double the reveal_timeout', ) if not is_binary_address(registry_address): raise InvalidAddress('Expected binary address format for registry in channel open') if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel open') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel open') chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: raise DuplicatedChannelError('Channel with given partner address already exists') registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = registry.get_token_network(token_address) if token_network_address is None: raise TokenNotRegistered( 'Token network for token %s does not exist' % to_checksum_address(token_address), ) token_network = self.raiden.chain.token_network( registry.get_token_network(token_address), ) with self.raiden.gas_reserve_lock: has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=views.state_from_raiden(self.raiden).block_hash, ) except DuplicatedChannelError: log.info('partner opened channel first') waiting.wait_for_newchannel( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f'channel {channel_state} is gone' return channel_state.identifier
python
def channel_open( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: if settle_timeout is None: settle_timeout = self.raiden.config['settle_timeout'] if settle_timeout < self.raiden.config['reveal_timeout'] * 2: raise InvalidSettleTimeout( 'settle_timeout can not be smaller than double the reveal_timeout', ) if not is_binary_address(registry_address): raise InvalidAddress('Expected binary address format for registry in channel open') if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel open') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel open') chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: raise DuplicatedChannelError('Channel with given partner address already exists') registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = registry.get_token_network(token_address) if token_network_address is None: raise TokenNotRegistered( 'Token network for token %s does not exist' % to_checksum_address(token_address), ) token_network = self.raiden.chain.token_network( registry.get_token_network(token_address), ) with self.raiden.gas_reserve_lock: has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=views.state_from_raiden(self.raiden).block_hash, ) except DuplicatedChannelError: log.info('partner opened channel first') waiting.wait_for_newchannel( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f'channel {channel_state} is gone' return channel_state.identifier
[ "def", "channel_open", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "settle_timeout", ":", "BlockTimeout", "=", "None", ",", "retry_timeout", ":", "NetworkTimeo...
Open a channel with the peer at `partner_address` with the given `token_address`.
[ "Open", "a", "channel", "with", "the", "peer", "at", "partner_address", "with", "the", "given", "token_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L357-L447
235,454
raiden-network/raiden
raiden/api/python.py
RaidenAPI.set_total_channel_deposit
def set_total_channel_deposit( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, total_deposit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ): """ 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. """ chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers( chain_state, registry_address, ) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel deposit') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel deposit') if token_address not in token_addresses: raise UnknownTokenAddress('Unknown token address') if channel_state is None: raise InvalidAddress('No channel with partner_address for the given token') if self.raiden.config['environment_type'] == Environment.PRODUCTION: per_token_network_deposit_limit = RED_EYES_PER_TOKEN_NETWORK_LIMIT else: per_token_network_deposit_limit = UINT256_MAX token = self.raiden.chain.token(token_address) token_network_registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = token_network_registry.get_token_network(token_address) token_network_proxy = self.raiden.chain.token_network(token_network_address) channel_proxy = self.raiden.chain.payment_channel( canonical_identifier=channel_state.canonical_identifier, ) if total_deposit == 0: raise DepositMismatch('Attempted to deposit with total deposit being 0') addendum = total_deposit - channel_state.our_state.contract_balance total_network_balance = token.balance_of(registry_address) if total_network_balance + addendum > per_token_network_deposit_limit: raise DepositOverLimit( f'The deposit of {addendum} will exceed the ' f'token network limit of {per_token_network_deposit_limit}', ) balance = token.balance_of(self.raiden.address) functions = token_network_proxy.proxy.contract.functions deposit_limit = functions.channel_participant_deposit_limit().call() if total_deposit > deposit_limit: raise DepositOverLimit( f'The additional deposit of {addendum} will exceed the ' f'channel participant limit of {deposit_limit}', ) # If this check succeeds it does not imply the the `deposit` will # succeed, since the `deposit` transaction may race with another # transaction. if not balance >= addendum: msg = 'Not enough balance to deposit. {} Available={} Needed={}'.format( pex(token_address), balance, addendum, ) raise InsufficientFunds(msg) # set_total_deposit calls approve # token.approve(netcontract_address, addendum) channel_proxy.set_total_deposit( total_deposit=total_deposit, block_identifier=views.state_from_raiden(self.raiden).block_hash, ) target_address = self.raiden.address waiting.wait_for_participant_newbalance( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, target_address=target_address, target_balance=total_deposit, retry_timeout=retry_timeout, )
python
def set_total_channel_deposit( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, total_deposit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ): chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers( chain_state, registry_address, ) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel deposit') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel deposit') if token_address not in token_addresses: raise UnknownTokenAddress('Unknown token address') if channel_state is None: raise InvalidAddress('No channel with partner_address for the given token') if self.raiden.config['environment_type'] == Environment.PRODUCTION: per_token_network_deposit_limit = RED_EYES_PER_TOKEN_NETWORK_LIMIT else: per_token_network_deposit_limit = UINT256_MAX token = self.raiden.chain.token(token_address) token_network_registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = token_network_registry.get_token_network(token_address) token_network_proxy = self.raiden.chain.token_network(token_network_address) channel_proxy = self.raiden.chain.payment_channel( canonical_identifier=channel_state.canonical_identifier, ) if total_deposit == 0: raise DepositMismatch('Attempted to deposit with total deposit being 0') addendum = total_deposit - channel_state.our_state.contract_balance total_network_balance = token.balance_of(registry_address) if total_network_balance + addendum > per_token_network_deposit_limit: raise DepositOverLimit( f'The deposit of {addendum} will exceed the ' f'token network limit of {per_token_network_deposit_limit}', ) balance = token.balance_of(self.raiden.address) functions = token_network_proxy.proxy.contract.functions deposit_limit = functions.channel_participant_deposit_limit().call() if total_deposit > deposit_limit: raise DepositOverLimit( f'The additional deposit of {addendum} will exceed the ' f'channel participant limit of {deposit_limit}', ) # If this check succeeds it does not imply the the `deposit` will # succeed, since the `deposit` transaction may race with another # transaction. if not balance >= addendum: msg = 'Not enough balance to deposit. {} Available={} Needed={}'.format( pex(token_address), balance, addendum, ) raise InsufficientFunds(msg) # set_total_deposit calls approve # token.approve(netcontract_address, addendum) channel_proxy.set_total_deposit( total_deposit=total_deposit, block_identifier=views.state_from_raiden(self.raiden).block_hash, ) target_address = self.raiden.address waiting.wait_for_participant_newbalance( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, target_address=target_address, target_balance=total_deposit, retry_timeout=retry_timeout, )
[ "def", "set_total_channel_deposit", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "total_deposit", ":", "TokenAmount", ",", "retry_timeout", ":", "NetworkTimeout", ...
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.
[ "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", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L449-L563
235,455
raiden-network/raiden
raiden/api/python.py
RaidenAPI.get_node_network_state
def get_node_network_state(self, node_address: Address): """ Returns the currently network status of `node_address`. """ return views.get_node_network_status( chain_state=views.state_from_raiden(self.raiden), node_address=node_address, )
python
def get_node_network_state(self, node_address: Address): return views.get_node_network_status( chain_state=views.state_from_raiden(self.raiden), node_address=node_address, )
[ "def", "get_node_network_state", "(", "self", ",", "node_address", ":", "Address", ")", ":", "return", "views", ".", "get_node_network_status", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "node_address", "=",...
Returns the currently network status of `node_address`.
[ "Returns", "the", "currently", "network", "status", "of", "node_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L701-L706
235,456
raiden-network/raiden
raiden/api/python.py
RaidenAPI.get_tokens_list
def get_tokens_list(self, registry_address: PaymentNetworkID): """Returns a list of tokens the node knows about""" tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_list
python
def get_tokens_list(self, registry_address: PaymentNetworkID): tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_list
[ "def", "get_tokens_list", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ")", ":", "tokens_list", "=", "views", ".", "get_token_identifiers", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "payme...
Returns a list of tokens the node knows about
[ "Returns", "a", "list", "of", "tokens", "the", "node", "knows", "about" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L712-L718
235,457
raiden-network/raiden
raiden/api/python.py
RaidenAPI.transfer_and_wait
def transfer_and_wait( self, registry_address: PaymentNetworkID, token_address: TokenAddress, amount: TokenAmount, target: Address, identifier: PaymentID = None, transfer_timeout: int = None, secret: Secret = None, secret_hash: SecretHash = None, ): """ Do a transfer with `target` with the given `amount` of `token_address`. """ # pylint: disable=too-many-arguments payment_status = self.transfer_async( registry_address=registry_address, token_address=token_address, amount=amount, target=target, identifier=identifier, secret=secret, secret_hash=secret_hash, ) payment_status.payment_done.wait(timeout=transfer_timeout) return payment_status
python
def transfer_and_wait( self, registry_address: PaymentNetworkID, token_address: TokenAddress, amount: TokenAmount, target: Address, identifier: PaymentID = None, transfer_timeout: int = None, secret: Secret = None, secret_hash: SecretHash = None, ): # pylint: disable=too-many-arguments payment_status = self.transfer_async( registry_address=registry_address, token_address=token_address, amount=amount, target=target, identifier=identifier, secret=secret, secret_hash=secret_hash, ) payment_status.payment_done.wait(timeout=transfer_timeout) return payment_status
[ "def", "transfer_and_wait", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "amount", ":", "TokenAmount", ",", "target", ":", "Address", ",", "identifier", ":", "PaymentID", "=", "None", ",", "transf...
Do a transfer with `target` with the given `amount` of `token_address`.
[ "Do", "a", "transfer", "with", "target", "with", "the", "given", "amount", "of", "token_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L731-L755
235,458
raiden-network/raiden
raiden/api/python.py
RaidenAPI.get_blockchain_events_token_network
def get_blockchain_events_token_network( self, token_address: TokenAddress, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ): """Returns a list of blockchain events coresponding to the token_address.""" if not is_binary_address(token_address): raise InvalidAddress( 'Expected binary address format for token in get_blockchain_events_token_network', ) token_network_address = self.raiden.default_registry.get_token_network( token_address, ) if token_network_address is None: raise UnknownTokenAddress('Token address is not known.') returned_events = blockchain_events.get_token_network_events( chain=self.raiden.chain, token_network_address=token_network_address, contract_manager=self.raiden.contract_manager, events=blockchain_events.ALL_EVENTS, from_block=from_block, to_block=to_block, ) for event in returned_events: if event.get('args'): event['args'] = dict(event['args']) returned_events.sort(key=lambda evt: evt.get('block_number'), reverse=True) return returned_events
python
def get_blockchain_events_token_network( self, token_address: TokenAddress, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ): if not is_binary_address(token_address): raise InvalidAddress( 'Expected binary address format for token in get_blockchain_events_token_network', ) token_network_address = self.raiden.default_registry.get_token_network( token_address, ) if token_network_address is None: raise UnknownTokenAddress('Token address is not known.') returned_events = blockchain_events.get_token_network_events( chain=self.raiden.chain, token_network_address=token_network_address, contract_manager=self.raiden.contract_manager, events=blockchain_events.ALL_EVENTS, from_block=from_block, to_block=to_block, ) for event in returned_events: if event.get('args'): event['args'] = dict(event['args']) returned_events.sort(key=lambda evt: evt.get('block_number'), reverse=True) return returned_events
[ "def", "get_blockchain_events_token_network", "(", "self", ",", "token_address", ":", "TokenAddress", ",", "from_block", ":", "BlockSpecification", "=", "GENESIS_BLOCK_NUMBER", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", ",", ")", ":", "if", "not", ...
Returns a list of blockchain events coresponding to the token_address.
[ "Returns", "a", "list", "of", "blockchain", "events", "coresponding", "to", "the", "token_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L922-L956
235,459
raiden-network/raiden
raiden/api/python.py
RaidenAPI.create_monitoring_request
def create_monitoring_request( self, balance_proof: BalanceProofSignedState, reward_amount: TokenAmount, ) -> Optional[RequestMonitoring]: """ 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. """ # create RequestMonitoring message from the above + `reward_amount` monitor_request = RequestMonitoring.from_balance_proof_signed_state( balance_proof=balance_proof, reward_amount=reward_amount, ) # sign RequestMonitoring and return monitor_request.sign(self.raiden.signer) return monitor_request
python
def create_monitoring_request( self, balance_proof: BalanceProofSignedState, reward_amount: TokenAmount, ) -> Optional[RequestMonitoring]: # create RequestMonitoring message from the above + `reward_amount` monitor_request = RequestMonitoring.from_balance_proof_signed_state( balance_proof=balance_proof, reward_amount=reward_amount, ) # sign RequestMonitoring and return monitor_request.sign(self.raiden.signer) return monitor_request
[ "def", "create_monitoring_request", "(", "self", ",", "balance_proof", ":", "BalanceProofSignedState", ",", "reward_amount", ":", "TokenAmount", ",", ")", "->", "Optional", "[", "RequestMonitoring", "]", ":", "# create RequestMonitoring message from the above + `reward_amount...
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.
[ "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", "tran...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L995-L1013
235,460
raiden-network/raiden
raiden/transfer/mediated_transfer/state.py
lockedtransfersigned_from_message
def lockedtransfersigned_from_message(message: 'LockedTransfer') -> 'LockedTransferSignedState': """ Create LockedTransferSignedState from a LockedTransfer message. """ balance_proof = balanceproof_from_envelope(message) lock = HashTimeLockState( message.lock.amount, message.lock.expiration, message.lock.secrethash, ) transfer_state = LockedTransferSignedState( message.message_identifier, message.payment_identifier, message.token, balance_proof, lock, message.initiator, message.target, ) return transfer_state
python
def lockedtransfersigned_from_message(message: 'LockedTransfer') -> 'LockedTransferSignedState': balance_proof = balanceproof_from_envelope(message) lock = HashTimeLockState( message.lock.amount, message.lock.expiration, message.lock.secrethash, ) transfer_state = LockedTransferSignedState( message.message_identifier, message.payment_identifier, message.token, balance_proof, lock, message.initiator, message.target, ) return transfer_state
[ "def", "lockedtransfersigned_from_message", "(", "message", ":", "'LockedTransfer'", ")", "->", "'LockedTransferSignedState'", ":", "balance_proof", "=", "balanceproof_from_envelope", "(", "message", ")", "lock", "=", "HashTimeLockState", "(", "message", ".", "lock", "....
Create LockedTransferSignedState from a LockedTransfer message.
[ "Create", "LockedTransferSignedState", "from", "a", "LockedTransfer", "message", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/state.py#L51-L71
235,461
raiden-network/raiden
raiden/ui/cli.py
version
def version(short): """Print version information and exit. """ if short: print(get_system_spec()['raiden']) else: print(json.dumps( get_system_spec(), indent=2, ))
python
def version(short): if short: print(get_system_spec()['raiden']) else: print(json.dumps( get_system_spec(), indent=2, ))
[ "def", "version", "(", "short", ")", ":", "if", "short", ":", "print", "(", "get_system_spec", "(", ")", "[", "'raiden'", "]", ")", "else", ":", "print", "(", "json", ".", "dumps", "(", "get_system_spec", "(", ")", ",", "indent", "=", "2", ",", ")"...
Print version information and exit.
[ "Print", "version", "information", "and", "exit", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/cli.py#L553-L561
235,462
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.connect
def connect( self, funds: typing.TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ): """Connect to the network. Subsequent calls to `connect` are allowed, but will only affect the spendable funds and the connection strategy parameters for the future. `connect` will not close any channels. Note: the ConnectionManager does not discriminate manually opened channels from automatically opened ones. If the user manually opened channels, those deposit amounts will affect the funding per channel and the number of new channels opened. Args: funds: Target amount of tokens spendable to join the network. initial_channel_target: Target number of channels to open. joinable_funds_target: Amount of funds not initially assigned. """ token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) if token_balance < funds: raise InvalidAmount( f'Insufficient balance for token {pex(self.token_address)}', ) if funds <= 0: raise InvalidAmount( 'The funds to use in the connection need to be a positive integer', ) if joinable_funds_target < 0 or joinable_funds_target > 1: raise InvalidAmount( f'joinable_funds_target should be between 0 and 1. Given: {joinable_funds_target}', ) with self.lock: self.funds = funds self.initial_channel_target = initial_channel_target self.joinable_funds_target = joinable_funds_target log_open_channels(self.raiden, self.registry_address, self.token_address, funds) qty_network_channels = views.count_token_network_channels( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) if not qty_network_channels: log.info( 'Bootstrapping token network.', node=pex(self.raiden.address), network_id=pex(self.registry_address), token_id=pex(self.token_address), ) self.api.channel_open( self.registry_address, self.token_address, self.BOOTSTRAP_ADDR, ) else: self._open_channels()
python
def connect( self, funds: typing.TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ): token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) if token_balance < funds: raise InvalidAmount( f'Insufficient balance for token {pex(self.token_address)}', ) if funds <= 0: raise InvalidAmount( 'The funds to use in the connection need to be a positive integer', ) if joinable_funds_target < 0 or joinable_funds_target > 1: raise InvalidAmount( f'joinable_funds_target should be between 0 and 1. Given: {joinable_funds_target}', ) with self.lock: self.funds = funds self.initial_channel_target = initial_channel_target self.joinable_funds_target = joinable_funds_target log_open_channels(self.raiden, self.registry_address, self.token_address, funds) qty_network_channels = views.count_token_network_channels( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) if not qty_network_channels: log.info( 'Bootstrapping token network.', node=pex(self.raiden.address), network_id=pex(self.registry_address), token_id=pex(self.token_address), ) self.api.channel_open( self.registry_address, self.token_address, self.BOOTSTRAP_ADDR, ) else: self._open_channels()
[ "def", "connect", "(", "self", ",", "funds", ":", "typing", ".", "TokenAmount", ",", "initial_channel_target", ":", "int", "=", "3", ",", "joinable_funds_target", ":", "float", "=", "0.4", ",", ")", ":", "token", "=", "self", ".", "raiden", ".", "chain",...
Connect to the network. Subsequent calls to `connect` are allowed, but will only affect the spendable funds and the connection strategy parameters for the future. `connect` will not close any channels. Note: the ConnectionManager does not discriminate manually opened channels from automatically opened ones. If the user manually opened channels, those deposit amounts will affect the funding per channel and the number of new channels opened. Args: funds: Target amount of tokens spendable to join the network. initial_channel_target: Target number of channels to open. joinable_funds_target: Amount of funds not initially assigned.
[ "Connect", "to", "the", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L101-L166
235,463
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.leave
def leave(self, registry_address): """ Leave the token network. This implies closing all channels and waiting for all channels to be settled. """ with self.lock: self.initial_channel_target = 0 channels_to_close = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=self.token_address, ) partner_addresses = [ channel_state.partner_state.address for channel_state in channels_to_close ] self.api.channel_batch_close( registry_address, self.token_address, partner_addresses, ) channel_ids = [ channel_state.identifier for channel_state in channels_to_close ] waiting.wait_for_settle( self.raiden, registry_address, self.token_address, channel_ids, self.raiden.alarm.sleep_time, ) return channels_to_close
python
def leave(self, registry_address): with self.lock: self.initial_channel_target = 0 channels_to_close = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=self.token_address, ) partner_addresses = [ channel_state.partner_state.address for channel_state in channels_to_close ] self.api.channel_batch_close( registry_address, self.token_address, partner_addresses, ) channel_ids = [ channel_state.identifier for channel_state in channels_to_close ] waiting.wait_for_settle( self.raiden, registry_address, self.token_address, channel_ids, self.raiden.alarm.sleep_time, ) return channels_to_close
[ "def", "leave", "(", "self", ",", "registry_address", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "initial_channel_target", "=", "0", "channels_to_close", "=", "views", ".", "get_channelstate_open", "(", "chain_state", "=", "views", ".", "state_fr...
Leave the token network. This implies closing all channels and waiting for all channels to be settled.
[ "Leave", "the", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L168-L206
235,464
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.join_channel
def join_channel(self, partner_address, partner_deposit): """Will be called, when we were selected as channel partner by another node. It will fund the channel with up to the partners deposit, but not more than remaining funds or the initial funding per channel. If the connection manager has no funds, this is a noop. """ # Consider this race condition: # # - Partner opens the channel and starts the deposit. # - This nodes learns about the new channel, starts ConnectionManager's # retry_connect, which will start a deposit for this half of the # channel. # - This node learns about the partner's deposit before its own. # join_channel is called which will try to deposit again. # # To fix this race, first the node must wait for the pending operations # to finish, because in them could be a deposit, and then deposit must # be called only if the channel is still not funded. token_network_proxy = self.raiden.chain.token_network(self.token_network_identifier) # Wait for any pending operation in the channel to complete, before # deciding on the deposit with self.lock, token_network_proxy.channel_operations_lock[partner_address]: channel_state = views.get_channelstate_for( views.state_from_raiden(self.raiden), self.token_network_identifier, self.token_address, partner_address, ) if not channel_state: return joining_funds = min( partner_deposit, self._funds_remaining, self._initial_funding_per_partner, ) if joining_funds <= 0 or self._leaving_state: return if joining_funds <= channel_state.our_state.contract_balance: return try: self.api.set_total_channel_deposit( self.registry_address, self.token_address, partner_address, joining_funds, ) except RaidenRecoverableError: log.info( 'Channel not in opened state', node=pex(self.raiden.address), ) except InvalidDBData: raise except RaidenUnrecoverableError as e: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( str(e), node=pex(self.raiden.address), ) else: log.info( 'Joined a channel', node=pex(self.raiden.address), partner=pex(partner_address), funds=joining_funds, )
python
def join_channel(self, partner_address, partner_deposit): # Consider this race condition: # # - Partner opens the channel and starts the deposit. # - This nodes learns about the new channel, starts ConnectionManager's # retry_connect, which will start a deposit for this half of the # channel. # - This node learns about the partner's deposit before its own. # join_channel is called which will try to deposit again. # # To fix this race, first the node must wait for the pending operations # to finish, because in them could be a deposit, and then deposit must # be called only if the channel is still not funded. token_network_proxy = self.raiden.chain.token_network(self.token_network_identifier) # Wait for any pending operation in the channel to complete, before # deciding on the deposit with self.lock, token_network_proxy.channel_operations_lock[partner_address]: channel_state = views.get_channelstate_for( views.state_from_raiden(self.raiden), self.token_network_identifier, self.token_address, partner_address, ) if not channel_state: return joining_funds = min( partner_deposit, self._funds_remaining, self._initial_funding_per_partner, ) if joining_funds <= 0 or self._leaving_state: return if joining_funds <= channel_state.our_state.contract_balance: return try: self.api.set_total_channel_deposit( self.registry_address, self.token_address, partner_address, joining_funds, ) except RaidenRecoverableError: log.info( 'Channel not in opened state', node=pex(self.raiden.address), ) except InvalidDBData: raise except RaidenUnrecoverableError as e: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( str(e), node=pex(self.raiden.address), ) else: log.info( 'Joined a channel', node=pex(self.raiden.address), partner=pex(partner_address), funds=joining_funds, )
[ "def", "join_channel", "(", "self", ",", "partner_address", ",", "partner_deposit", ")", ":", "# Consider this race condition:", "#", "# - Partner opens the channel and starts the deposit.", "# - This nodes learns about the new channel, starts ConnectionManager's", "# retry_connect, wh...
Will be called, when we were selected as channel partner by another node. It will fund the channel with up to the partners deposit, but not more than remaining funds or the initial funding per channel. If the connection manager has no funds, this is a noop.
[ "Will", "be", "called", "when", "we", "were", "selected", "as", "channel", "partner", "by", "another", "node", ".", "It", "will", "fund", "the", "channel", "with", "up", "to", "the", "partners", "deposit", "but", "not", "more", "than", "remaining", "funds"...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L208-L286
235,465
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.retry_connect
def retry_connect(self): """Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop. """ with self.lock: if self._funds_remaining > 0 and not self._leaving_state: self._open_channels()
python
def retry_connect(self): with self.lock: if self._funds_remaining > 0 and not self._leaving_state: self._open_channels()
[ "def", "retry_connect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_funds_remaining", ">", "0", "and", "not", "self", ".", "_leaving_state", ":", "self", ".", "_open_channels", "(", ")" ]
Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop.
[ "Will", "be", "called", "when", "new", "channels", "in", "the", "token", "network", "are", "detected", ".", "If", "the", "minimum", "number", "of", "channels", "was", "not", "yet", "established", "it", "will", "try", "to", "open", "new", "channels", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L288-L297
235,466
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._find_new_partners
def _find_new_partners(self): """ Search the token network for potential channel partners. """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) known = set(channel_state.partner_state.address for channel_state in open_channels) known.add(self.BOOTSTRAP_ADDR) known.add(self.raiden.address) participants_addresses = views.get_participants_addresses( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) available = participants_addresses - known available = list(available) shuffle(available) new_partners = available log.debug( 'Found partners', node=pex(self.raiden.address), number_of_partners=len(available), ) return new_partners
python
def _find_new_partners(self): open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) known = set(channel_state.partner_state.address for channel_state in open_channels) known.add(self.BOOTSTRAP_ADDR) known.add(self.raiden.address) participants_addresses = views.get_participants_addresses( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) available = participants_addresses - known available = list(available) shuffle(available) new_partners = available log.debug( 'Found partners', node=pex(self.raiden.address), number_of_partners=len(available), ) return new_partners
[ "def", "_find_new_partners", "(", "self", ")", ":", "open_channels", "=", "views", ".", "get_channelstate_open", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "payment_network_id", "=", "self", ".", "registry_a...
Search the token network for potential channel partners.
[ "Search", "the", "token", "network", "for", "potential", "channel", "partners", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L299-L327
235,467
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._join_partner
def _join_partner(self, partner: Address): """ Ensure a channel exists with partner and is funded in our side """ try: self.api.channel_open( self.registry_address, self.token_address, partner, ) except DuplicatedChannelError: # If channel already exists (either because partner created it, # or it's nonfunded channel), continue to ensure it's funded pass total_deposit = self._initial_funding_per_partner if total_deposit == 0: return try: self.api.set_total_channel_deposit( registry_address=self.registry_address, token_address=self.token_address, partner_address=partner, total_deposit=total_deposit, ) except InvalidDBData: raise except RECOVERABLE_ERRORS: log.info( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), ) except RaidenUnrecoverableError: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), )
python
def _join_partner(self, partner: Address): try: self.api.channel_open( self.registry_address, self.token_address, partner, ) except DuplicatedChannelError: # If channel already exists (either because partner created it, # or it's nonfunded channel), continue to ensure it's funded pass total_deposit = self._initial_funding_per_partner if total_deposit == 0: return try: self.api.set_total_channel_deposit( registry_address=self.registry_address, token_address=self.token_address, partner_address=partner, total_deposit=total_deposit, ) except InvalidDBData: raise except RECOVERABLE_ERRORS: log.info( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), ) except RaidenUnrecoverableError: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), )
[ "def", "_join_partner", "(", "self", ",", "partner", ":", "Address", ")", ":", "try", ":", "self", ".", "api", ".", "channel_open", "(", "self", ".", "registry_address", ",", "self", ".", "token_address", ",", "partner", ",", ")", "except", "DuplicatedChan...
Ensure a channel exists with partner and is funded in our side
[ "Ensure", "a", "channel", "exists", "with", "partner", "and", "is", "funded", "in", "our", "side" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L329-L373
235,468
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._open_channels
def _open_channels(self) -> bool: """ Open channels until there are `self.initial_channel_target` channels open. Do nothing if there are enough channels open already. Note: - This method must be called with the lock held. Return: - False if no channels could be opened """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) open_channels = [ channel_state for channel_state in open_channels if channel_state.partner_state.address != self.BOOTSTRAP_ADDR ] funded_channels = [ channel_state for channel_state in open_channels if channel_state.our_state.contract_balance >= self._initial_funding_per_partner ] nonfunded_channels = [ channel_state for channel_state in open_channels if channel_state not in funded_channels ] possible_new_partners = self._find_new_partners() if possible_new_partners == 0: return False # if we already met our target, break if len(funded_channels) >= self.initial_channel_target: return False # if we didn't, but there's no nonfunded channels and no available partners # it means the network is smaller than our target, so we should also break if not nonfunded_channels and possible_new_partners == 0: return False n_to_join = self.initial_channel_target - len(funded_channels) nonfunded_partners = [ channel_state.partner_state.address for channel_state in nonfunded_channels ] # first, fund nonfunded channels, then open and fund with possible_new_partners, # until initial_channel_target of funded channels is met join_partners = (nonfunded_partners + possible_new_partners)[:n_to_join] log.debug( 'Spawning greenlets to join partners', node=pex(self.raiden.address), num_greenlets=len(join_partners), ) greenlets = set( gevent.spawn(self._join_partner, partner) for partner in join_partners ) gevent.joinall(greenlets, raise_error=True) return True
python
def _open_channels(self) -> bool: open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) open_channels = [ channel_state for channel_state in open_channels if channel_state.partner_state.address != self.BOOTSTRAP_ADDR ] funded_channels = [ channel_state for channel_state in open_channels if channel_state.our_state.contract_balance >= self._initial_funding_per_partner ] nonfunded_channels = [ channel_state for channel_state in open_channels if channel_state not in funded_channels ] possible_new_partners = self._find_new_partners() if possible_new_partners == 0: return False # if we already met our target, break if len(funded_channels) >= self.initial_channel_target: return False # if we didn't, but there's no nonfunded channels and no available partners # it means the network is smaller than our target, so we should also break if not nonfunded_channels and possible_new_partners == 0: return False n_to_join = self.initial_channel_target - len(funded_channels) nonfunded_partners = [ channel_state.partner_state.address for channel_state in nonfunded_channels ] # first, fund nonfunded channels, then open and fund with possible_new_partners, # until initial_channel_target of funded channels is met join_partners = (nonfunded_partners + possible_new_partners)[:n_to_join] log.debug( 'Spawning greenlets to join partners', node=pex(self.raiden.address), num_greenlets=len(join_partners), ) greenlets = set( gevent.spawn(self._join_partner, partner) for partner in join_partners ) gevent.joinall(greenlets, raise_error=True) return True
[ "def", "_open_channels", "(", "self", ")", "->", "bool", ":", "open_channels", "=", "views", ".", "get_channelstate_open", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "payment_network_id", "=", "self", ".",...
Open channels until there are `self.initial_channel_target` channels open. Do nothing if there are enough channels open already. Note: - This method must be called with the lock held. Return: - False if no channels could be opened
[ "Open", "channels", "until", "there", "are", "self", ".", "initial_channel_target", "channels", "open", ".", "Do", "nothing", "if", "there", "are", "enough", "channels", "open", "already", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L375-L435
235,469
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._initial_funding_per_partner
def _initial_funding_per_partner(self) -> int: """The calculated funding per partner depending on configuration and overall funding of the ConnectionManager. Note: - This attribute must be accessed with the lock held. """ if self.initial_channel_target: return int( self.funds * (1 - self.joinable_funds_target) / self.initial_channel_target, ) return 0
python
def _initial_funding_per_partner(self) -> int: if self.initial_channel_target: return int( self.funds * (1 - self.joinable_funds_target) / self.initial_channel_target, ) return 0
[ "def", "_initial_funding_per_partner", "(", "self", ")", "->", "int", ":", "if", "self", ".", "initial_channel_target", ":", "return", "int", "(", "self", ".", "funds", "*", "(", "1", "-", "self", ".", "joinable_funds_target", ")", "/", "self", ".", "initi...
The calculated funding per partner depending on configuration and overall funding of the ConnectionManager. Note: - This attribute must be accessed with the lock held.
[ "The", "calculated", "funding", "per", "partner", "depending", "on", "configuration", "and", "overall", "funding", "of", "the", "ConnectionManager", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L438-L451
235,470
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._funds_remaining
def _funds_remaining(self) -> int: """The remaining funds after subtracting the already deposited amounts. Note: - This attribute must be accessed with the lock held. """ if self.funds > 0: token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) sum_deposits = views.get_our_capacity_for_token_network( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) return min(self.funds - sum_deposits, token_balance) return 0
python
def _funds_remaining(self) -> int: if self.funds > 0: token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) sum_deposits = views.get_our_capacity_for_token_network( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) return min(self.funds - sum_deposits, token_balance) return 0
[ "def", "_funds_remaining", "(", "self", ")", "->", "int", ":", "if", "self", ".", "funds", ">", "0", ":", "token", "=", "self", ".", "raiden", ".", "chain", ".", "token", "(", "self", ".", "token_address", ")", "token_balance", "=", "token", ".", "ba...
The remaining funds after subtracting the already deposited amounts. Note: - This attribute must be accessed with the lock held.
[ "The", "remaining", "funds", "after", "subtracting", "the", "already", "deposited", "amounts", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L454-L471
235,471
raiden-network/raiden
tools/debugging/replay_wal.py
Translator._make_regex
def _make_regex(self): """ Compile rxp with all keys concatenated. """ rxp = "|".join( map(self._address_rxp, self.keys()), ) self._regex = re.compile( rxp, re.IGNORECASE, )
python
def _make_regex(self): rxp = "|".join( map(self._address_rxp, self.keys()), ) self._regex = re.compile( rxp, re.IGNORECASE, )
[ "def", "_make_regex", "(", "self", ")", ":", "rxp", "=", "\"|\"", ".", "join", "(", "map", "(", "self", ".", "_address_rxp", ",", "self", ".", "keys", "(", ")", ")", ",", ")", "self", ".", "_regex", "=", "re", ".", "compile", "(", "rxp", ",", "...
Compile rxp with all keys concatenated.
[ "Compile", "rxp", "with", "all", "keys", "concatenated", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/debugging/replay_wal.py#L97-L105
235,472
raiden-network/raiden
raiden/api/v1/resources.py
TokensResource.get
def get(self): """ this translates to 'get all token addresses we have channels open for' """ return self.rest_api.get_tokens_list( self.rest_api.raiden_api.raiden.default_registry.address, )
python
def get(self): return self.rest_api.get_tokens_list( self.rest_api.raiden_api.raiden.default_registry.address, )
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "rest_api", ".", "get_tokens_list", "(", "self", ".", "rest_api", ".", "raiden_api", ".", "raiden", ".", "default_registry", ".", "address", ",", ")" ]
this translates to 'get all token addresses we have channels open for'
[ "this", "translates", "to", "get", "all", "token", "addresses", "we", "have", "channels", "open", "for" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/v1/resources.py#L88-L94
235,473
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
is_safe_to_wait
def is_safe_to_wait( lock_expiration: BlockExpiration, reveal_timeout: BlockTimeout, block_number: BlockNumber, ) -> SuccessOrError: """ True if waiting is safe, i.e. there are more than enough blocks to safely unlock on chain. """ # reveal timeout will not ever be larger than the lock_expiration otherwise # the expected block_number is negative assert block_number > 0 assert reveal_timeout > 0 assert lock_expiration > reveal_timeout lock_timeout = lock_expiration - block_number # A node may wait for a new balance proof while there are reveal_timeout # blocks left, at that block and onwards it is not safe to wait. if lock_timeout > reveal_timeout: return True, None msg = ( f'lock timeout is unsafe.' f' timeout must be larger than {reveal_timeout}, but it is {lock_timeout}.' f' expiration: {lock_expiration} block_number: {block_number}' ) return False, msg
python
def is_safe_to_wait( lock_expiration: BlockExpiration, reveal_timeout: BlockTimeout, block_number: BlockNumber, ) -> SuccessOrError: # reveal timeout will not ever be larger than the lock_expiration otherwise # the expected block_number is negative assert block_number > 0 assert reveal_timeout > 0 assert lock_expiration > reveal_timeout lock_timeout = lock_expiration - block_number # A node may wait for a new balance proof while there are reveal_timeout # blocks left, at that block and onwards it is not safe to wait. if lock_timeout > reveal_timeout: return True, None msg = ( f'lock timeout is unsafe.' f' timeout must be larger than {reveal_timeout}, but it is {lock_timeout}.' f' expiration: {lock_expiration} block_number: {block_number}' ) return False, msg
[ "def", "is_safe_to_wait", "(", "lock_expiration", ":", "BlockExpiration", ",", "reveal_timeout", ":", "BlockTimeout", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "SuccessOrError", ":", "# reveal timeout will not ever be larger than the lock_expiration otherwise", ...
True if waiting is safe, i.e. there are more than enough blocks to safely unlock on chain.
[ "True", "if", "waiting", "is", "safe", "i", ".", "e", ".", "there", "are", "more", "than", "enough", "blocks", "to", "safely", "unlock", "on", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L103-L129
235,474
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
is_send_transfer_almost_equal
def is_send_transfer_almost_equal( send_channel: NettingChannelState, send: LockedTransferUnsignedState, received: LockedTransferSignedState, ) -> bool: """ True if both transfers are for the same mediated transfer. """ # The only thing that may change is the direction of the transfer return ( isinstance(send, LockedTransferUnsignedState) and isinstance(received, LockedTransferSignedState) and send.payment_identifier == received.payment_identifier and send.token == received.token and send.lock.amount == received.lock.amount - send_channel.mediation_fee and send.lock.expiration == received.lock.expiration and send.lock.secrethash == received.lock.secrethash and send.initiator == received.initiator and send.target == received.target )
python
def is_send_transfer_almost_equal( send_channel: NettingChannelState, send: LockedTransferUnsignedState, received: LockedTransferSignedState, ) -> bool: # The only thing that may change is the direction of the transfer return ( isinstance(send, LockedTransferUnsignedState) and isinstance(received, LockedTransferSignedState) and send.payment_identifier == received.payment_identifier and send.token == received.token and send.lock.amount == received.lock.amount - send_channel.mediation_fee and send.lock.expiration == received.lock.expiration and send.lock.secrethash == received.lock.secrethash and send.initiator == received.initiator and send.target == received.target )
[ "def", "is_send_transfer_almost_equal", "(", "send_channel", ":", "NettingChannelState", ",", "send", ":", "LockedTransferUnsignedState", ",", "received", ":", "LockedTransferSignedState", ",", ")", "->", "bool", ":", "# The only thing that may change is the direction of the tr...
True if both transfers are for the same mediated transfer.
[ "True", "if", "both", "transfers", "are", "for", "the", "same", "mediated", "transfer", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L154-L171
235,475
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
filter_reachable_routes
def filter_reachable_routes( routes: List[RouteState], nodeaddresses_to_networkstates: NodeNetworkStateMap, ) -> List[RouteState]: """This function makes sure we use reachable routes only.""" reachable_routes = [] for route in routes: node_network_state = nodeaddresses_to_networkstates.get( route.node_address, NODE_NETWORK_UNREACHABLE, ) if node_network_state == NODE_NETWORK_REACHABLE: reachable_routes.append(route) return reachable_routes
python
def filter_reachable_routes( routes: List[RouteState], nodeaddresses_to_networkstates: NodeNetworkStateMap, ) -> List[RouteState]: reachable_routes = [] for route in routes: node_network_state = nodeaddresses_to_networkstates.get( route.node_address, NODE_NETWORK_UNREACHABLE, ) if node_network_state == NODE_NETWORK_REACHABLE: reachable_routes.append(route) return reachable_routes
[ "def", "filter_reachable_routes", "(", "routes", ":", "List", "[", "RouteState", "]", ",", "nodeaddresses_to_networkstates", ":", "NodeNetworkStateMap", ",", ")", "->", "List", "[", "RouteState", "]", ":", "reachable_routes", "=", "[", "]", "for", "route", "in",...
This function makes sure we use reachable routes only.
[ "This", "function", "makes", "sure", "we", "use", "reachable", "routes", "only", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L198-L214
235,476
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
filter_used_routes
def filter_used_routes( transfers_pair: List[MediationPairState], routes: List[RouteState], ) -> List[RouteState]: """This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through 3 will also try 5 before sending it backwards to 1 1 -> 2 -> 3 -> 4 v ^ 5 -> 6 -> 7 This function will return routes as provided in their original order. """ channelid_to_route = {r.channel_identifier: r for r in routes} routes_order = {route.node_address: index for index, route in enumerate(routes)} for pair in transfers_pair: channelid = pair.payer_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] channelid = pair.payee_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] return sorted( channelid_to_route.values(), key=lambda route: routes_order[route.node_address], )
python
def filter_used_routes( transfers_pair: List[MediationPairState], routes: List[RouteState], ) -> List[RouteState]: channelid_to_route = {r.channel_identifier: r for r in routes} routes_order = {route.node_address: index for index, route in enumerate(routes)} for pair in transfers_pair: channelid = pair.payer_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] channelid = pair.payee_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] return sorted( channelid_to_route.values(), key=lambda route: routes_order[route.node_address], )
[ "def", "filter_used_routes", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "routes", ":", "List", "[", "RouteState", "]", ",", ")", "->", "List", "[", "RouteState", "]", ":", "channelid_to_route", "=", "{", "r", ".", "channel_ident...
This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through 3 will also try 5 before sending it backwards to 1 1 -> 2 -> 3 -> 4 v ^ 5 -> 6 -> 7 This function will return routes as provided in their original order.
[ "This", "function", "makes", "sure", "we", "filter", "routes", "that", "have", "already", "been", "used", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L217-L246
235,477
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_payee_channel
def get_payee_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: """ Returns the payee channel of a given transfer pair or None if it's not found """ payee_channel_identifier = transfer_pair.payee_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payee_channel_identifier)
python
def get_payee_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: payee_channel_identifier = transfer_pair.payee_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payee_channel_identifier)
[ "def", "get_payee_channel", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfer_pair", ":", "MediationPairState", ",", ")", "->", "Optional", "[", "NettingChannelState", "]", ":", "payee_channel_identifier", "=", "transfer_pair", ".", "payee_transfer"...
Returns the payee channel of a given transfer pair or None if it's not found
[ "Returns", "the", "payee", "channel", "of", "a", "given", "transfer", "pair", "or", "None", "if", "it", "s", "not", "found" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L249-L255
235,478
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_payer_channel
def get_payer_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: """ Returns the payer channel of a given transfer pair or None if it's not found """ payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payer_channel_identifier)
python
def get_payer_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payer_channel_identifier)
[ "def", "get_payer_channel", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfer_pair", ":", "MediationPairState", ",", ")", "->", "Optional", "[", "NettingChannelState", "]", ":", "payer_channel_identifier", "=", "transfer_pair", ".", "payer_transfer"...
Returns the payer channel of a given transfer pair or None if it's not found
[ "Returns", "the", "payer", "channel", "of", "a", "given", "transfer", "pair", "or", "None", "if", "it", "s", "not", "found" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L258-L264
235,479
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_pending_transfer_pairs
def get_pending_transfer_pairs( transfers_pair: List[MediationPairState], ) -> List[MediationPairState]: """ Return the transfer pairs that are not at a final state. """ pending_pairs = list( pair for pair in transfers_pair if pair.payee_state not in STATE_TRANSFER_FINAL or pair.payer_state not in STATE_TRANSFER_FINAL ) return pending_pairs
python
def get_pending_transfer_pairs( transfers_pair: List[MediationPairState], ) -> List[MediationPairState]: pending_pairs = list( pair for pair in transfers_pair if pair.payee_state not in STATE_TRANSFER_FINAL or pair.payer_state not in STATE_TRANSFER_FINAL ) return pending_pairs
[ "def", "get_pending_transfer_pairs", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", ")", "->", "List", "[", "MediationPairState", "]", ":", "pending_pairs", "=", "list", "(", "pair", "for", "pair", "in", "transfers_pair", "if", "pair", ...
Return the transfer pairs that are not at a final state.
[ "Return", "the", "transfer", "pairs", "that", "are", "not", "at", "a", "final", "state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L267-L277
235,480
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_lock_amount_after_fees
def get_lock_amount_after_fees( lock: HashTimeLockState, payee_channel: NettingChannelState, ) -> PaymentWithFeeAmount: """ Return the lock.amount after fees are taken. Fees are taken only for the outgoing channel, which is the one with collateral locked from this node. """ return PaymentWithFeeAmount(lock.amount - payee_channel.mediation_fee)
python
def get_lock_amount_after_fees( lock: HashTimeLockState, payee_channel: NettingChannelState, ) -> PaymentWithFeeAmount: return PaymentWithFeeAmount(lock.amount - payee_channel.mediation_fee)
[ "def", "get_lock_amount_after_fees", "(", "lock", ":", "HashTimeLockState", ",", "payee_channel", ":", "NettingChannelState", ",", ")", "->", "PaymentWithFeeAmount", ":", "return", "PaymentWithFeeAmount", "(", "lock", ".", "amount", "-", "payee_channel", ".", "mediati...
Return the lock.amount after fees are taken. Fees are taken only for the outgoing channel, which is the one with collateral locked from this node.
[ "Return", "the", "lock", ".", "amount", "after", "fees", "are", "taken", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L280-L290
235,481
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
sanity_check
def sanity_check( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, ) -> None: """ Check invariants that must hold. """ # if a transfer is paid we must know the secret all_transfers_states = itertools.chain( (pair.payee_state for pair in state.transfers_pair), (pair.payer_state for pair in state.transfers_pair), ) if any(state in STATE_TRANSFER_PAID for state in all_transfers_states): assert state.secret is not None # the "transitivity" for these values is checked below as part of # almost_equal check if state.transfers_pair: first_pair = state.transfers_pair[0] assert state.secrethash == first_pair.payer_transfer.lock.secrethash for pair in state.transfers_pair: payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=pair, ) # Channel could have been removed if not payee_channel: continue assert is_send_transfer_almost_equal( send_channel=payee_channel, send=pair.payee_transfer, received=pair.payer_transfer, ) assert pair.payer_state in pair.valid_payer_states assert pair.payee_state in pair.valid_payee_states for original, refund in zip(state.transfers_pair[:-1], state.transfers_pair[1:]): assert original.payee_address == refund.payer_address payer_channel = get_payer_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=refund, ) # Channel could have been removed if not payer_channel: continue transfer_sent = original.payee_transfer transfer_received = refund.payer_transfer assert is_send_transfer_almost_equal( send_channel=payer_channel, send=transfer_sent, received=transfer_received, ) if state.waiting_transfer and state.transfers_pair: last_transfer_pair = state.transfers_pair[-1] payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=last_transfer_pair, ) # Channel could have been removed if payee_channel: transfer_sent = last_transfer_pair.payee_transfer transfer_received = state.waiting_transfer.transfer assert is_send_transfer_almost_equal( send_channel=payee_channel, send=transfer_sent, received=transfer_received, )
python
def sanity_check( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, ) -> None: # if a transfer is paid we must know the secret all_transfers_states = itertools.chain( (pair.payee_state for pair in state.transfers_pair), (pair.payer_state for pair in state.transfers_pair), ) if any(state in STATE_TRANSFER_PAID for state in all_transfers_states): assert state.secret is not None # the "transitivity" for these values is checked below as part of # almost_equal check if state.transfers_pair: first_pair = state.transfers_pair[0] assert state.secrethash == first_pair.payer_transfer.lock.secrethash for pair in state.transfers_pair: payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=pair, ) # Channel could have been removed if not payee_channel: continue assert is_send_transfer_almost_equal( send_channel=payee_channel, send=pair.payee_transfer, received=pair.payer_transfer, ) assert pair.payer_state in pair.valid_payer_states assert pair.payee_state in pair.valid_payee_states for original, refund in zip(state.transfers_pair[:-1], state.transfers_pair[1:]): assert original.payee_address == refund.payer_address payer_channel = get_payer_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=refund, ) # Channel could have been removed if not payer_channel: continue transfer_sent = original.payee_transfer transfer_received = refund.payer_transfer assert is_send_transfer_almost_equal( send_channel=payer_channel, send=transfer_sent, received=transfer_received, ) if state.waiting_transfer and state.transfers_pair: last_transfer_pair = state.transfers_pair[-1] payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=last_transfer_pair, ) # Channel could have been removed if payee_channel: transfer_sent = last_transfer_pair.payee_transfer transfer_received = state.waiting_transfer.transfer assert is_send_transfer_almost_equal( send_channel=payee_channel, send=transfer_sent, received=transfer_received, )
[ "def", "sanity_check", "(", "state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "None", ":", "# if a transfer is paid we must know the secret", "all_transfers_states", "=", "itertools", ".", "chain", "(", "(", ...
Check invariants that must hold.
[ "Check", "invariants", "that", "must", "hold", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L293-L365
235,482
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
clear_if_finalized
def clear_if_finalized( iteration: TransitionResult, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: """Clear the mediator task if all the locks have been finalized. A lock is considered finalized if it has been removed from the merkle tree offchain, either because the transfer was unlocked or expired, or because the channel was settled on chain and therefore the channel is removed.""" state = cast(MediatorTransferState, iteration.new_state) if state is None: return iteration # Only clear the task if all channels have the lock cleared. secrethash = state.secrethash for pair in state.transfers_pair: payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) if payer_channel and channel.is_lock_pending(payer_channel.partner_state, secrethash): return iteration payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) if payee_channel and channel.is_lock_pending(payee_channel.our_state, secrethash): return iteration if state.waiting_transfer: waiting_transfer = state.waiting_transfer.transfer waiting_channel_identifier = waiting_transfer.balance_proof.channel_identifier waiting_channel = channelidentifiers_to_channels.get(waiting_channel_identifier) if waiting_channel and channel.is_lock_pending(waiting_channel.partner_state, secrethash): return iteration return TransitionResult(None, iteration.events)
python
def clear_if_finalized( iteration: TransitionResult, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: state = cast(MediatorTransferState, iteration.new_state) if state is None: return iteration # Only clear the task if all channels have the lock cleared. secrethash = state.secrethash for pair in state.transfers_pair: payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) if payer_channel and channel.is_lock_pending(payer_channel.partner_state, secrethash): return iteration payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) if payee_channel and channel.is_lock_pending(payee_channel.our_state, secrethash): return iteration if state.waiting_transfer: waiting_transfer = state.waiting_transfer.transfer waiting_channel_identifier = waiting_transfer.balance_proof.channel_identifier waiting_channel = channelidentifiers_to_channels.get(waiting_channel_identifier) if waiting_channel and channel.is_lock_pending(waiting_channel.partner_state, secrethash): return iteration return TransitionResult(None, iteration.events)
[ "def", "clear_if_finalized", "(", "iteration", ":", "TransitionResult", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "TransitionResult", "[", "MediatorTransferState", "]", ":", "state", "=", "cast", "(", "MediatorTransferState", ",", "iter...
Clear the mediator task if all the locks have been finalized. A lock is considered finalized if it has been removed from the merkle tree offchain, either because the transfer was unlocked or expired, or because the channel was settled on chain and therefore the channel is removed.
[ "Clear", "the", "mediator", "task", "if", "all", "the", "locks", "have", "been", "finalized", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L368-L401
235,483
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
forward_transfer_pair
def forward_transfer_pair( payer_transfer: LockedTransferSignedState, available_routes: List['RouteState'], channelidentifiers_to_channels: Dict, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: """ Given a payer transfer tries a new route to proceed with the mediation. Args: payer_transfer: The transfer received from the payer_channel. available_routes: Current available routes that may be used, it's assumed that the routes list is ordered from best to worst. channelidentifiers_to_channels: All the channels available for this transfer. pseudo_random_generator: Number generator to generate a message id. block_number: The current block number. """ transfer_pair = None mediated_events: List[Event] = list() lock_timeout = BlockTimeout(payer_transfer.lock.expiration - block_number) payee_channel = next_channel_from_routes( available_routes=available_routes, channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_amount=payer_transfer.lock.amount, lock_timeout=lock_timeout, ) if payee_channel: assert payee_channel.settle_timeout >= lock_timeout assert payee_channel.token_address == payer_transfer.token message_identifier = message_identifier_from_prng(pseudo_random_generator) lock = payer_transfer.lock lockedtransfer_event = channel.send_lockedtransfer( channel_state=payee_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, payee_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) assert lockedtransfer_event transfer_pair = MediationPairState( payer_transfer, payee_channel.partner_state.address, lockedtransfer_event.transfer, ) mediated_events = [lockedtransfer_event] return ( transfer_pair, mediated_events, )
python
def forward_transfer_pair( payer_transfer: LockedTransferSignedState, available_routes: List['RouteState'], channelidentifiers_to_channels: Dict, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: transfer_pair = None mediated_events: List[Event] = list() lock_timeout = BlockTimeout(payer_transfer.lock.expiration - block_number) payee_channel = next_channel_from_routes( available_routes=available_routes, channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_amount=payer_transfer.lock.amount, lock_timeout=lock_timeout, ) if payee_channel: assert payee_channel.settle_timeout >= lock_timeout assert payee_channel.token_address == payer_transfer.token message_identifier = message_identifier_from_prng(pseudo_random_generator) lock = payer_transfer.lock lockedtransfer_event = channel.send_lockedtransfer( channel_state=payee_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, payee_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) assert lockedtransfer_event transfer_pair = MediationPairState( payer_transfer, payee_channel.partner_state.address, lockedtransfer_event.transfer, ) mediated_events = [lockedtransfer_event] return ( transfer_pair, mediated_events, )
[ "def", "forward_transfer_pair", "(", "payer_transfer", ":", "LockedTransferSignedState", ",", "available_routes", ":", "List", "[", "'RouteState'", "]", ",", "channelidentifiers_to_channels", ":", "Dict", ",", "pseudo_random_generator", ":", "random", ".", "Random", ","...
Given a payer transfer tries a new route to proceed with the mediation. Args: payer_transfer: The transfer received from the payer_channel. available_routes: Current available routes that may be used, it's assumed that the routes list is ordered from best to worst. channelidentifiers_to_channels: All the channels available for this transfer. pseudo_random_generator: Number generator to generate a message id. block_number: The current block number.
[ "Given", "a", "payer", "transfer", "tries", "a", "new", "route", "to", "proceed", "with", "the", "mediation", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L438-L496
235,484
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
backward_transfer_pair
def backward_transfer_pair( backward_channel: NettingChannelState, payer_transfer: LockedTransferSignedState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: """ Sends a transfer backwards, allowing the previous hop to try a new route. When all the routes available for this node failed, send a transfer backwards with the same amount and secrethash, allowing the previous hop to do a retry. Args: backward_channel: The original channel which sent the mediated transfer to this node. payer_transfer: The *latest* payer transfer which is backing the mediation. block_number: The current block number. Returns: The mediator pair and the correspoding refund event. """ transfer_pair = None events: List[Event] = list() lock = payer_transfer.lock lock_timeout = BlockTimeout(lock.expiration - block_number) # Ensure the refund transfer's lock has a safe expiration, otherwise don't # do anything and wait for the received lock to expire. if is_channel_usable(backward_channel, lock.amount, lock_timeout): message_identifier = message_identifier_from_prng(pseudo_random_generator) refund_transfer = channel.send_refundtransfer( channel_state=backward_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, backward_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) transfer_pair = MediationPairState( payer_transfer, backward_channel.partner_state.address, refund_transfer.transfer, ) events.append(refund_transfer) return (transfer_pair, events)
python
def backward_transfer_pair( backward_channel: NettingChannelState, payer_transfer: LockedTransferSignedState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: transfer_pair = None events: List[Event] = list() lock = payer_transfer.lock lock_timeout = BlockTimeout(lock.expiration - block_number) # Ensure the refund transfer's lock has a safe expiration, otherwise don't # do anything and wait for the received lock to expire. if is_channel_usable(backward_channel, lock.amount, lock_timeout): message_identifier = message_identifier_from_prng(pseudo_random_generator) refund_transfer = channel.send_refundtransfer( channel_state=backward_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, backward_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) transfer_pair = MediationPairState( payer_transfer, backward_channel.partner_state.address, refund_transfer.transfer, ) events.append(refund_transfer) return (transfer_pair, events)
[ "def", "backward_transfer_pair", "(", "backward_channel", ":", "NettingChannelState", ",", "payer_transfer", ":", "LockedTransferSignedState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "Tuple",...
Sends a transfer backwards, allowing the previous hop to try a new route. When all the routes available for this node failed, send a transfer backwards with the same amount and secrethash, allowing the previous hop to do a retry. Args: backward_channel: The original channel which sent the mediated transfer to this node. payer_transfer: The *latest* payer transfer which is backing the mediation. block_number: The current block number. Returns: The mediator pair and the correspoding refund event.
[ "Sends", "a", "transfer", "backwards", "allowing", "the", "previous", "hop", "to", "try", "a", "new", "route", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L499-L551
235,485
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_expired_pairs
def events_for_expired_pairs( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], waiting_transfer: Optional[WaitingTransferState], block_number: BlockNumber, ) -> List[Event]: """ Informational events for expired locks. """ pending_transfers_pairs = get_pending_transfer_pairs(transfers_pair) events: List[Event] = list() for pair in pending_transfers_pairs: payer_balance_proof = pair.payer_transfer.balance_proof payer_channel = channelidentifiers_to_channels.get(payer_balance_proof.channel_identifier) if not payer_channel: continue has_payer_transfer_expired = channel.is_transfer_expired( transfer=pair.payer_transfer, affected_channel=payer_channel, block_number=block_number, ) if has_payer_transfer_expired: # For safety, the correct behavior is: # # - If the payee has been paid, then the payer must pay too. # # And the corollary: # # - If the payer transfer has expired, then the payee transfer must # have expired too. # # The problem is that this corollary cannot be asserted. If a user # is running Raiden without a monitoring service, then it may go # offline after having paid a transfer to a payee, but without # getting a balance proof of the payer, and once it comes back # online the transfer may have expired. # # assert pair.payee_state == 'payee_expired' pair.payer_state = 'payer_expired' unlock_claim_failed = EventUnlockClaimFailed( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) if waiting_transfer and waiting_transfer.state != 'expired': waiting_transfer.state = 'expired' unlock_claim_failed = EventUnlockClaimFailed( waiting_transfer.transfer.payment_identifier, waiting_transfer.transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) return events
python
def events_for_expired_pairs( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], waiting_transfer: Optional[WaitingTransferState], block_number: BlockNumber, ) -> List[Event]: pending_transfers_pairs = get_pending_transfer_pairs(transfers_pair) events: List[Event] = list() for pair in pending_transfers_pairs: payer_balance_proof = pair.payer_transfer.balance_proof payer_channel = channelidentifiers_to_channels.get(payer_balance_proof.channel_identifier) if not payer_channel: continue has_payer_transfer_expired = channel.is_transfer_expired( transfer=pair.payer_transfer, affected_channel=payer_channel, block_number=block_number, ) if has_payer_transfer_expired: # For safety, the correct behavior is: # # - If the payee has been paid, then the payer must pay too. # # And the corollary: # # - If the payer transfer has expired, then the payee transfer must # have expired too. # # The problem is that this corollary cannot be asserted. If a user # is running Raiden without a monitoring service, then it may go # offline after having paid a transfer to a payee, but without # getting a balance proof of the payer, and once it comes back # online the transfer may have expired. # # assert pair.payee_state == 'payee_expired' pair.payer_state = 'payer_expired' unlock_claim_failed = EventUnlockClaimFailed( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) if waiting_transfer and waiting_transfer.state != 'expired': waiting_transfer.state = 'expired' unlock_claim_failed = EventUnlockClaimFailed( waiting_transfer.transfer.payment_identifier, waiting_transfer.transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) return events
[ "def", "events_for_expired_pairs", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "waiting_transfer", ":", "Optional", "[", "WaitingTransferState", "]", ",", "block_number", ":", "BlockN...
Informational events for expired locks.
[ "Informational", "events", "for", "expired", "locks", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L681-L738
235,486
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_secretreveal
def events_for_secretreveal( transfers_pair: List[MediationPairState], secret: Secret, pseudo_random_generator: random.Random, ) -> List[Event]: """ Reveal the secret off-chain. The secret is revealed off-chain even if there is a pending transaction to reveal it on-chain, this allows the unlock to happen off-chain, which is faster. This node is named N, suppose there is a mediated transfer with two refund transfers, one from B and one from C: A-N-B...B-N-C..C-N-D Under normal operation N will first learn the secret from D, then reveal to C, wait for C to inform the secret is known before revealing it to B, and again wait for B before revealing the secret to A. If B somehow sent a reveal secret before C and D, then the secret will be revealed to A, but not C and D, meaning the secret won't be propagated forward. Even if D sent a reveal secret at about the same time, the secret will only be revealed to B upon confirmation from C. If the proof doesn't arrive in time and the lock's expiration is at risk, N won't lose tokens since it knows the secret can go on-chain at any time. """ events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payer_knows_secret = pair.payer_state in STATE_SECRET_KNOWN is_transfer_pending = pair.payer_state == 'payer_pending' should_send_secret = ( payee_knows_secret and not payer_knows_secret and is_transfer_pending ) if should_send_secret: message_identifier = message_identifier_from_prng(pseudo_random_generator) pair.payer_state = 'payer_secret_revealed' payer_transfer = pair.payer_transfer revealsecret = SendSecretReveal( recipient=payer_transfer.balance_proof.sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=message_identifier, secret=secret, ) events.append(revealsecret) return events
python
def events_for_secretreveal( transfers_pair: List[MediationPairState], secret: Secret, pseudo_random_generator: random.Random, ) -> List[Event]: events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payer_knows_secret = pair.payer_state in STATE_SECRET_KNOWN is_transfer_pending = pair.payer_state == 'payer_pending' should_send_secret = ( payee_knows_secret and not payer_knows_secret and is_transfer_pending ) if should_send_secret: message_identifier = message_identifier_from_prng(pseudo_random_generator) pair.payer_state = 'payer_secret_revealed' payer_transfer = pair.payer_transfer revealsecret = SendSecretReveal( recipient=payer_transfer.balance_proof.sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=message_identifier, secret=secret, ) events.append(revealsecret) return events
[ "def", "events_for_secretreveal", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "secret", ":", "Secret", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", "List", "[", "Event", "]", ":", "events", ":", "...
Reveal the secret off-chain. The secret is revealed off-chain even if there is a pending transaction to reveal it on-chain, this allows the unlock to happen off-chain, which is faster. This node is named N, suppose there is a mediated transfer with two refund transfers, one from B and one from C: A-N-B...B-N-C..C-N-D Under normal operation N will first learn the secret from D, then reveal to C, wait for C to inform the secret is known before revealing it to B, and again wait for B before revealing the secret to A. If B somehow sent a reveal secret before C and D, then the secret will be revealed to A, but not C and D, meaning the secret won't be propagated forward. Even if D sent a reveal secret at about the same time, the secret will only be revealed to B upon confirmation from C. If the proof doesn't arrive in time and the lock's expiration is at risk, N won't lose tokens since it knows the secret can go on-chain at any time.
[ "Reveal", "the", "secret", "off", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L741-L794
235,487
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_balanceproof
def events_for_balanceproof( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], pseudo_random_generator: random.Random, block_number: BlockNumber, secret: Secret, secrethash: SecretHash, ) -> List[Event]: """ While it's safe do the off-chain unlock. """ events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payee_payed = pair.payee_state in STATE_TRANSFER_PAID payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) payee_channel_open = ( payee_channel and channel.get_status(payee_channel) == CHANNEL_STATE_OPENED ) payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) # The mediator must not send to the payee a balance proof if the lock # is in the danger zone, because the payer may not do the same and the # on-chain unlock may fail. If the lock is nearing it's expiration # block, then on-chain unlock should be done, and if successful it can # be unlocked off-chain. is_safe_to_send_balanceproof = False if payer_channel: is_safe_to_send_balanceproof, _ = is_safe_to_wait( pair.payer_transfer.lock.expiration, payer_channel.reveal_timeout, block_number, ) should_send_balanceproof_to_payee = ( payee_channel_open and payee_knows_secret and not payee_payed and is_safe_to_send_balanceproof ) if should_send_balanceproof_to_payee: # At this point we are sure that payee_channel exists due to the # payee_channel_open check above. So let mypy know about this assert payee_channel payee_channel = cast(NettingChannelState, payee_channel) pair.payee_state = 'payee_balance_proof' message_identifier = message_identifier_from_prng(pseudo_random_generator) unlock_lock = channel.send_unlock( channel_state=payee_channel, message_identifier=message_identifier, payment_identifier=pair.payee_transfer.payment_identifier, secret=secret, secrethash=secrethash, ) unlock_success = EventUnlockSuccess( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, ) events.append(unlock_lock) events.append(unlock_success) return events
python
def events_for_balanceproof( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], pseudo_random_generator: random.Random, block_number: BlockNumber, secret: Secret, secrethash: SecretHash, ) -> List[Event]: events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payee_payed = pair.payee_state in STATE_TRANSFER_PAID payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) payee_channel_open = ( payee_channel and channel.get_status(payee_channel) == CHANNEL_STATE_OPENED ) payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) # The mediator must not send to the payee a balance proof if the lock # is in the danger zone, because the payer may not do the same and the # on-chain unlock may fail. If the lock is nearing it's expiration # block, then on-chain unlock should be done, and if successful it can # be unlocked off-chain. is_safe_to_send_balanceproof = False if payer_channel: is_safe_to_send_balanceproof, _ = is_safe_to_wait( pair.payer_transfer.lock.expiration, payer_channel.reveal_timeout, block_number, ) should_send_balanceproof_to_payee = ( payee_channel_open and payee_knows_secret and not payee_payed and is_safe_to_send_balanceproof ) if should_send_balanceproof_to_payee: # At this point we are sure that payee_channel exists due to the # payee_channel_open check above. So let mypy know about this assert payee_channel payee_channel = cast(NettingChannelState, payee_channel) pair.payee_state = 'payee_balance_proof' message_identifier = message_identifier_from_prng(pseudo_random_generator) unlock_lock = channel.send_unlock( channel_state=payee_channel, message_identifier=message_identifier, payment_identifier=pair.payee_transfer.payment_identifier, secret=secret, secrethash=secrethash, ) unlock_success = EventUnlockSuccess( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, ) events.append(unlock_lock) events.append(unlock_success) return events
[ "def", "events_for_balanceproof", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", "block_number", ":", "BlockNumber", ",", ...
While it's safe do the off-chain unlock.
[ "While", "it", "s", "safe", "do", "the", "off", "-", "chain", "unlock", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L797-L862
235,488
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_onchain_secretreveal_if_dangerzone
def events_for_onchain_secretreveal_if_dangerzone( channelmap: ChannelMap, secrethash: SecretHash, transfers_pair: List[MediationPairState], block_number: BlockNumber, block_hash: BlockHash, ) -> List[Event]: """ Reveal the secret on-chain if the lock enters the unsafe region and the secret is not yet on-chain. """ events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Only consider the transfers which have a pair. This means if we have a # waiting transfer and for some reason the node knows the secret, it will # not try to register it. Otherwise it would be possible for an attacker to # reveal the secret late, just to force the node to send an unecessary # transaction. for pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pair) if not payer_channel: continue lock = pair.payer_transfer.lock safe_to_wait, _ = is_safe_to_wait( lock.expiration, payer_channel.reveal_timeout, block_number, ) secret_known = channel.is_secret_known( payer_channel.partner_state, pair.payer_transfer.lock.secrethash, ) if not safe_to_wait and secret_known: pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: secret = channel.get_secret( payer_channel.partner_state, lock.secrethash, ) assert secret, 'the secret should be known at this point' reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
python
def events_for_onchain_secretreveal_if_dangerzone( channelmap: ChannelMap, secrethash: SecretHash, transfers_pair: List[MediationPairState], block_number: BlockNumber, block_hash: BlockHash, ) -> List[Event]: events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Only consider the transfers which have a pair. This means if we have a # waiting transfer and for some reason the node knows the secret, it will # not try to register it. Otherwise it would be possible for an attacker to # reveal the secret late, just to force the node to send an unecessary # transaction. for pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pair) if not payer_channel: continue lock = pair.payer_transfer.lock safe_to_wait, _ = is_safe_to_wait( lock.expiration, payer_channel.reveal_timeout, block_number, ) secret_known = channel.is_secret_known( payer_channel.partner_state, pair.payer_transfer.lock.secrethash, ) if not safe_to_wait and secret_known: pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: secret = channel.get_secret( payer_channel.partner_state, lock.secrethash, ) assert secret, 'the secret should be known at this point' reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
[ "def", "events_for_onchain_secretreveal_if_dangerzone", "(", "channelmap", ":", "ChannelMap", ",", "secrethash", ":", "SecretHash", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "block_number", ":", "BlockNumber", ",", "block_hash", ":", "Bl...
Reveal the secret on-chain if the lock enters the unsafe region and the secret is not yet on-chain.
[ "Reveal", "the", "secret", "on", "-", "chain", "if", "the", "lock", "enters", "the", "unsafe", "region", "and", "the", "secret", "is", "not", "yet", "on", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L865-L933
235,489
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_onchain_secretreveal_if_closed
def events_for_onchain_secretreveal_if_closed( channelmap: ChannelMap, transfers_pair: List[MediationPairState], secret: Secret, secrethash: SecretHash, block_hash: BlockHash, ) -> List[Event]: """ Register the secret on-chain if the payer channel is already closed and the mediator learned the secret off-chain. Balance proofs are not exchanged for closed channels, so there is no reason to wait for the unsafe region to register secret. Note: If the secret is learned before the channel is closed, then the channel will register the secrets in bulk, not the transfer. """ events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Just like the case for entering the danger zone, this will only consider # the transfers which have a pair. for pending_pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pending_pair) # Don't register the secret on-chain if the channel is open or settled if payer_channel and channel.get_status(payer_channel) == CHANNEL_STATE_CLOSED: pending_pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: partner_state = payer_channel.partner_state lock = channel.get_lock(partner_state, secrethash) # The mediator task lives as long as there are any pending # locks, it may be the case that some of the transfer_pairs got # resolved off-chain, but others didn't. For this reason we # must check if the lock is still part of the channel if lock: reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
python
def events_for_onchain_secretreveal_if_closed( channelmap: ChannelMap, transfers_pair: List[MediationPairState], secret: Secret, secrethash: SecretHash, block_hash: BlockHash, ) -> List[Event]: events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Just like the case for entering the danger zone, this will only consider # the transfers which have a pair. for pending_pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pending_pair) # Don't register the secret on-chain if the channel is open or settled if payer_channel and channel.get_status(payer_channel) == CHANNEL_STATE_CLOSED: pending_pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: partner_state = payer_channel.partner_state lock = channel.get_lock(partner_state, secrethash) # The mediator task lives as long as there are any pending # locks, it may be the case that some of the transfer_pairs got # resolved off-chain, but others didn't. For this reason we # must check if the lock is still part of the channel if lock: reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
[ "def", "events_for_onchain_secretreveal_if_closed", "(", "channelmap", ":", "ChannelMap", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "block_hash", ":", "BlockHash", ","...
Register the secret on-chain if the payer channel is already closed and the mediator learned the secret off-chain. Balance proofs are not exchanged for closed channels, so there is no reason to wait for the unsafe region to register secret. Note: If the secret is learned before the channel is closed, then the channel will register the secrets in bulk, not the transfer.
[ "Register", "the", "secret", "on", "-", "chain", "if", "the", "payer", "channel", "is", "already", "closed", "and", "the", "mediator", "learned", "the", "secret", "off", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L936-L995
235,490
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_to_remove_expired_locks
def events_to_remove_expired_locks( mediator_state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, pseudo_random_generator: random.Random, ) -> List[Event]: """ Clear the channels which have expired locks. This only considers the *sent* transfers, received transfers can only be updated by the partner. """ events: List[Event] = list() for transfer_pair in mediator_state.transfers_pair: balance_proof = transfer_pair.payee_transfer.balance_proof channel_identifier = balance_proof.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue secrethash = mediator_state.secrethash lock: Union[None, LockType] = None if secrethash in channel_state.our_state.secrethashes_to_lockedlocks: assert secrethash not in channel_state.our_state.secrethashes_to_unlockedlocks lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) elif secrethash in channel_state.our_state.secrethashes_to_unlockedlocks: lock = channel_state.our_state.secrethashes_to_unlockedlocks.get(secrethash) if lock: lock_expiration_threshold = channel.get_sender_expiration_threshold(lock) has_lock_expired, _ = channel.is_lock_expired( end_state=channel_state.our_state, lock=lock, block_number=block_number, lock_expiration_threshold=lock_expiration_threshold, ) is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if has_lock_expired and is_channel_open: transfer_pair.payee_state = 'payee_expired' expired_lock_events = channel.events_for_expired_lock( channel_state=channel_state, locked_lock=lock, pseudo_random_generator=pseudo_random_generator, ) events.extend(expired_lock_events) unlock_failed = EventUnlockFailed( transfer_pair.payee_transfer.payment_identifier, transfer_pair.payee_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_failed) return events
python
def events_to_remove_expired_locks( mediator_state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, pseudo_random_generator: random.Random, ) -> List[Event]: events: List[Event] = list() for transfer_pair in mediator_state.transfers_pair: balance_proof = transfer_pair.payee_transfer.balance_proof channel_identifier = balance_proof.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue secrethash = mediator_state.secrethash lock: Union[None, LockType] = None if secrethash in channel_state.our_state.secrethashes_to_lockedlocks: assert secrethash not in channel_state.our_state.secrethashes_to_unlockedlocks lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) elif secrethash in channel_state.our_state.secrethashes_to_unlockedlocks: lock = channel_state.our_state.secrethashes_to_unlockedlocks.get(secrethash) if lock: lock_expiration_threshold = channel.get_sender_expiration_threshold(lock) has_lock_expired, _ = channel.is_lock_expired( end_state=channel_state.our_state, lock=lock, block_number=block_number, lock_expiration_threshold=lock_expiration_threshold, ) is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if has_lock_expired and is_channel_open: transfer_pair.payee_state = 'payee_expired' expired_lock_events = channel.events_for_expired_lock( channel_state=channel_state, locked_lock=lock, pseudo_random_generator=pseudo_random_generator, ) events.extend(expired_lock_events) unlock_failed = EventUnlockFailed( transfer_pair.payee_transfer.payment_identifier, transfer_pair.payee_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_failed) return events
[ "def", "events_to_remove_expired_locks", "(", "mediator_state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "block_number", ":", "BlockNumber", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", ...
Clear the channels which have expired locks. This only considers the *sent* transfers, received transfers can only be updated by the partner.
[ "Clear", "the", "channels", "which", "have", "expired", "locks", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L998-L1053
235,491
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
secret_learned
def secret_learned( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, block_hash: BlockHash, secret: Secret, secrethash: SecretHash, payee_address: Address, ) -> TransitionResult[MediatorTransferState]: """ Unlock the payee lock, reveal the lock to the payer, and if necessary register the secret on-chain. """ secret_reveal_events = set_offchain_secret( state, channelidentifiers_to_channels, secret, secrethash, ) set_offchain_reveal_state( state.transfers_pair, payee_address, ) onchain_secret_reveal = events_for_onchain_secretreveal_if_closed( channelmap=channelidentifiers_to_channels, transfers_pair=state.transfers_pair, secret=secret, secrethash=secrethash, block_hash=block_hash, ) offchain_secret_reveal = events_for_secretreveal( state.transfers_pair, secret, pseudo_random_generator, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels, state.transfers_pair, pseudo_random_generator, block_number, secret, secrethash, ) events = secret_reveal_events + offchain_secret_reveal + balance_proof + onchain_secret_reveal iteration = TransitionResult(state, events) return iteration
python
def secret_learned( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, block_hash: BlockHash, secret: Secret, secrethash: SecretHash, payee_address: Address, ) -> TransitionResult[MediatorTransferState]: secret_reveal_events = set_offchain_secret( state, channelidentifiers_to_channels, secret, secrethash, ) set_offchain_reveal_state( state.transfers_pair, payee_address, ) onchain_secret_reveal = events_for_onchain_secretreveal_if_closed( channelmap=channelidentifiers_to_channels, transfers_pair=state.transfers_pair, secret=secret, secrethash=secrethash, block_hash=block_hash, ) offchain_secret_reveal = events_for_secretreveal( state.transfers_pair, secret, pseudo_random_generator, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels, state.transfers_pair, pseudo_random_generator, block_number, secret, secrethash, ) events = secret_reveal_events + offchain_secret_reveal + balance_proof + onchain_secret_reveal iteration = TransitionResult(state, events) return iteration
[ "def", "secret_learned", "(", "state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", "block_number", ":", "BlockNumber", ",", "block_hash", ":", "BlockHash", "...
Unlock the payee lock, reveal the lock to the payer, and if necessary register the secret on-chain.
[ "Unlock", "the", "payee", "lock", "reveal", "the", "lock", "to", "the", "payer", "and", "if", "necessary", "register", "the", "secret", "on", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1056-L1107
235,492
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
mediate_transfer
def mediate_transfer( state: MediatorTransferState, possible_routes: List['RouteState'], payer_channel: NettingChannelState, channelidentifiers_to_channels: ChannelMap, nodeaddresses_to_networkstates: NodeNetworkStateMap, pseudo_random_generator: random.Random, payer_transfer: LockedTransferSignedState, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: """ Try a new route or fail back to a refund. The mediator can safely try a new route knowing that the tokens from payer_transfer will cover the expenses of the mediation. If there is no route available that may be used at the moment of the call the mediator may send a refund back to the payer, allowing the payer to try a different route. """ reachable_routes = filter_reachable_routes( possible_routes, nodeaddresses_to_networkstates, ) available_routes = filter_used_routes( state.transfers_pair, reachable_routes, ) assert payer_channel.partner_state.address == payer_transfer.balance_proof.sender transfer_pair, mediated_events = forward_transfer_pair( payer_transfer, available_routes, channelidentifiers_to_channels, pseudo_random_generator, block_number, ) if transfer_pair is None: assert not mediated_events if state.transfers_pair: original_pair = state.transfers_pair[0] original_channel = get_payer_channel( channelidentifiers_to_channels, original_pair, ) else: original_channel = payer_channel if original_channel: transfer_pair, mediated_events = backward_transfer_pair( original_channel, payer_transfer, pseudo_random_generator, block_number, ) else: transfer_pair = None mediated_events = list() if transfer_pair is None: assert not mediated_events mediated_events = list() state.waiting_transfer = WaitingTransferState(payer_transfer) else: # the list must be ordered from high to low expiration, expiration # handling depends on it state.transfers_pair.append(transfer_pair) return TransitionResult(state, mediated_events)
python
def mediate_transfer( state: MediatorTransferState, possible_routes: List['RouteState'], payer_channel: NettingChannelState, channelidentifiers_to_channels: ChannelMap, nodeaddresses_to_networkstates: NodeNetworkStateMap, pseudo_random_generator: random.Random, payer_transfer: LockedTransferSignedState, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: reachable_routes = filter_reachable_routes( possible_routes, nodeaddresses_to_networkstates, ) available_routes = filter_used_routes( state.transfers_pair, reachable_routes, ) assert payer_channel.partner_state.address == payer_transfer.balance_proof.sender transfer_pair, mediated_events = forward_transfer_pair( payer_transfer, available_routes, channelidentifiers_to_channels, pseudo_random_generator, block_number, ) if transfer_pair is None: assert not mediated_events if state.transfers_pair: original_pair = state.transfers_pair[0] original_channel = get_payer_channel( channelidentifiers_to_channels, original_pair, ) else: original_channel = payer_channel if original_channel: transfer_pair, mediated_events = backward_transfer_pair( original_channel, payer_transfer, pseudo_random_generator, block_number, ) else: transfer_pair = None mediated_events = list() if transfer_pair is None: assert not mediated_events mediated_events = list() state.waiting_transfer = WaitingTransferState(payer_transfer) else: # the list must be ordered from high to low expiration, expiration # handling depends on it state.transfers_pair.append(transfer_pair) return TransitionResult(state, mediated_events)
[ "def", "mediate_transfer", "(", "state", ":", "MediatorTransferState", ",", "possible_routes", ":", "List", "[", "'RouteState'", "]", ",", "payer_channel", ":", "NettingChannelState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "nodeaddresses_to_network...
Try a new route or fail back to a refund. The mediator can safely try a new route knowing that the tokens from payer_transfer will cover the expenses of the mediation. If there is no route available that may be used at the moment of the call the mediator may send a refund back to the payer, allowing the payer to try a different route.
[ "Try", "a", "new", "route", "or", "fail", "back", "to", "a", "refund", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1110-L1180
235,493
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
handle_onchain_secretreveal
def handle_onchain_secretreveal( mediator_state: MediatorTransferState, onchain_secret_reveal: ContractReceiveSecretReveal, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: """ The secret was revealed on-chain, set the state of all transfers to secret known. """ secrethash = onchain_secret_reveal.secrethash is_valid_reveal = is_valid_secret_reveal( state_change=onchain_secret_reveal, transfer_secrethash=mediator_state.secrethash, secret=onchain_secret_reveal.secret, ) if is_valid_reveal: secret = onchain_secret_reveal.secret # Compare against the block number at which the event was emitted. block_number = onchain_secret_reveal.block_number secret_reveal = set_onchain_secret( state=mediator_state, channelidentifiers_to_channels=channelidentifiers_to_channels, secret=secret, secrethash=secrethash, block_number=block_number, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels=channelidentifiers_to_channels, transfers_pair=mediator_state.transfers_pair, pseudo_random_generator=pseudo_random_generator, block_number=block_number, secret=secret, secrethash=secrethash, ) iteration = TransitionResult(mediator_state, secret_reveal + balance_proof) else: iteration = TransitionResult(mediator_state, list()) return iteration
python
def handle_onchain_secretreveal( mediator_state: MediatorTransferState, onchain_secret_reveal: ContractReceiveSecretReveal, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: secrethash = onchain_secret_reveal.secrethash is_valid_reveal = is_valid_secret_reveal( state_change=onchain_secret_reveal, transfer_secrethash=mediator_state.secrethash, secret=onchain_secret_reveal.secret, ) if is_valid_reveal: secret = onchain_secret_reveal.secret # Compare against the block number at which the event was emitted. block_number = onchain_secret_reveal.block_number secret_reveal = set_onchain_secret( state=mediator_state, channelidentifiers_to_channels=channelidentifiers_to_channels, secret=secret, secrethash=secrethash, block_number=block_number, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels=channelidentifiers_to_channels, transfers_pair=mediator_state.transfers_pair, pseudo_random_generator=pseudo_random_generator, block_number=block_number, secret=secret, secrethash=secrethash, ) iteration = TransitionResult(mediator_state, secret_reveal + balance_proof) else: iteration = TransitionResult(mediator_state, list()) return iteration
[ "def", "handle_onchain_secretreveal", "(", "mediator_state", ":", "MediatorTransferState", ",", "onchain_secret_reveal", ":", "ContractReceiveSecretReveal", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "pseudo_random_generator", ":", "random", ".", "Random", ...
The secret was revealed on-chain, set the state of all transfers to secret known.
[ "The", "secret", "was", "revealed", "on", "-", "chain", "set", "the", "state", "of", "all", "transfers", "to", "secret", "known", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1384-L1426
235,494
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
handle_unlock
def handle_unlock( mediator_state: MediatorTransferState, state_change: ReceiveUnlock, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: """ Handle a ReceiveUnlock state change. """ events = list() balance_proof_sender = state_change.balance_proof.sender channel_identifier = state_change.balance_proof.channel_identifier for pair in mediator_state.transfers_pair: if pair.payer_transfer.balance_proof.sender == balance_proof_sender: channel_state = channelidentifiers_to_channels.get(channel_identifier) if channel_state: is_valid, channel_events, _ = channel.handle_unlock( channel_state, state_change, ) events.extend(channel_events) if is_valid: unlock = EventUnlockClaimSuccess( pair.payee_transfer.payment_identifier, pair.payee_transfer.lock.secrethash, ) events.append(unlock) send_processed = SendProcessed( recipient=balance_proof_sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=state_change.message_identifier, ) events.append(send_processed) pair.payer_state = 'payer_balance_proof' iteration = TransitionResult(mediator_state, events) return iteration
python
def handle_unlock( mediator_state: MediatorTransferState, state_change: ReceiveUnlock, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: events = list() balance_proof_sender = state_change.balance_proof.sender channel_identifier = state_change.balance_proof.channel_identifier for pair in mediator_state.transfers_pair: if pair.payer_transfer.balance_proof.sender == balance_proof_sender: channel_state = channelidentifiers_to_channels.get(channel_identifier) if channel_state: is_valid, channel_events, _ = channel.handle_unlock( channel_state, state_change, ) events.extend(channel_events) if is_valid: unlock = EventUnlockClaimSuccess( pair.payee_transfer.payment_identifier, pair.payee_transfer.lock.secrethash, ) events.append(unlock) send_processed = SendProcessed( recipient=balance_proof_sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=state_change.message_identifier, ) events.append(send_processed) pair.payer_state = 'payer_balance_proof' iteration = TransitionResult(mediator_state, events) return iteration
[ "def", "handle_unlock", "(", "mediator_state", ":", "MediatorTransferState", ",", "state_change", ":", "ReceiveUnlock", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "TransitionResult", "[", "MediatorTransferState", "]", ":", "events", "=", ...
Handle a ReceiveUnlock state change.
[ "Handle", "a", "ReceiveUnlock", "state", "change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1429-L1467
235,495
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.service_count
def service_count(self, block_identifier: BlockSpecification) -> int: """Get the number of registered services""" result = self.proxy.contract.functions.serviceCount().call( block_identifier=block_identifier, ) return result
python
def service_count(self, block_identifier: BlockSpecification) -> int: result = self.proxy.contract.functions.serviceCount().call( block_identifier=block_identifier, ) return result
[ "def", "service_count", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "int", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functions", ".", "serviceCount", "(", ")", ".", "call", "(", "block_identifier", "=", ...
Get the number of registered services
[ "Get", "the", "number", "of", "registered", "services" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L46-L51
235,496
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.get_service_address
def get_service_address( self, block_identifier: BlockSpecification, index: int, ) -> Optional[AddressHex]: """Gets the address of a service by index. If index is out of range return None""" try: result = self.proxy.contract.functions.service_addresses(index).call( block_identifier=block_identifier, ) except web3.exceptions.BadFunctionCallOutput: result = None return result
python
def get_service_address( self, block_identifier: BlockSpecification, index: int, ) -> Optional[AddressHex]: try: result = self.proxy.contract.functions.service_addresses(index).call( block_identifier=block_identifier, ) except web3.exceptions.BadFunctionCallOutput: result = None return result
[ "def", "get_service_address", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ",", "index", ":", "int", ",", ")", "->", "Optional", "[", "AddressHex", "]", ":", "try", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functi...
Gets the address of a service by index. If index is out of range return None
[ "Gets", "the", "address", "of", "a", "service", "by", "index", ".", "If", "index", "is", "out", "of", "range", "return", "None" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L53-L65
235,497
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.get_service_url
def get_service_url( self, block_identifier: BlockSpecification, service_hex_address: AddressHex, ) -> Optional[str]: """Gets the URL of a service by address. If does not exist return None""" result = self.proxy.contract.functions.urls(service_hex_address).call( block_identifier=block_identifier, ) if result == '': return None return result
python
def get_service_url( self, block_identifier: BlockSpecification, service_hex_address: AddressHex, ) -> Optional[str]: result = self.proxy.contract.functions.urls(service_hex_address).call( block_identifier=block_identifier, ) if result == '': return None return result
[ "def", "get_service_url", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ",", "service_hex_address", ":", "AddressHex", ",", ")", "->", "Optional", "[", "str", "]", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functions", ...
Gets the URL of a service by address. If does not exist return None
[ "Gets", "the", "URL", "of", "a", "service", "by", "address", ".", "If", "does", "not", "exist", "return", "None" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L67-L78
235,498
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.set_url
def set_url(self, url: str): """Sets the url needed to access the service via HTTP for the caller""" gas_limit = self.proxy.estimate_gas('latest', 'setURL', url) transaction_hash = self.proxy.transact('setURL', gas_limit, url) self.client.poll(transaction_hash) assert not check_transaction_threw(self.client, transaction_hash)
python
def set_url(self, url: str): gas_limit = self.proxy.estimate_gas('latest', 'setURL', url) transaction_hash = self.proxy.transact('setURL', gas_limit, url) self.client.poll(transaction_hash) assert not check_transaction_threw(self.client, transaction_hash)
[ "def", "set_url", "(", "self", ",", "url", ":", "str", ")", ":", "gas_limit", "=", "self", ".", "proxy", ".", "estimate_gas", "(", "'latest'", ",", "'setURL'", ",", "url", ")", "transaction_hash", "=", "self", ".", "proxy", ".", "transact", "(", "'setU...
Sets the url needed to access the service via HTTP for the caller
[ "Sets", "the", "url", "needed", "to", "access", "the", "service", "via", "HTTP", "for", "the", "caller" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L80-L85
235,499
raiden-network/raiden
raiden/utils/signer.py
recover
def recover( data: bytes, signature: Signature, hasher: Callable[[bytes], bytes] = eth_sign_sha3, ) -> Address: """ eth_recover address from data hash and signature """ _hash = hasher(data) # ecdsa_recover accepts only standard [0,1] v's so we add support also for [27,28] here # anything else will raise BadSignature if signature[-1] >= 27: # support (0,1,27,28) v values signature = Signature(signature[:-1] + bytes([signature[-1] - 27])) try: sig = keys.Signature(signature_bytes=signature) public_key = keys.ecdsa_recover(message_hash=_hash, signature=sig) except BadSignature as e: raise InvalidSignature from e return public_key.to_canonical_address()
python
def recover( data: bytes, signature: Signature, hasher: Callable[[bytes], bytes] = eth_sign_sha3, ) -> Address: _hash = hasher(data) # ecdsa_recover accepts only standard [0,1] v's so we add support also for [27,28] here # anything else will raise BadSignature if signature[-1] >= 27: # support (0,1,27,28) v values signature = Signature(signature[:-1] + bytes([signature[-1] - 27])) try: sig = keys.Signature(signature_bytes=signature) public_key = keys.ecdsa_recover(message_hash=_hash, signature=sig) except BadSignature as e: raise InvalidSignature from e return public_key.to_canonical_address()
[ "def", "recover", "(", "data", ":", "bytes", ",", "signature", ":", "Signature", ",", "hasher", ":", "Callable", "[", "[", "bytes", "]", ",", "bytes", "]", "=", "eth_sign_sha3", ",", ")", "->", "Address", ":", "_hash", "=", "hasher", "(", "data", ")"...
eth_recover address from data hash and signature
[ "eth_recover", "address", "from", "data", "hash", "and", "signature" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/signer.py#L23-L41