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,500
raiden-network/raiden
raiden/utils/signer.py
LocalSigner.sign
def sign(self, data: bytes, v: int = 27) -> Signature: """ Sign data hash with local private key """ assert v in (0, 27), 'Raiden is only signing messages with v in (0, 27)' _hash = eth_sign_sha3(data) signature = self.private_key.sign_msg_hash(message_hash=_hash) sig_bytes = signature.to_bytes() # adjust last byte to v return sig_bytes[:-1] + bytes([sig_bytes[-1] + v])
python
def sign(self, data: bytes, v: int = 27) -> Signature: assert v in (0, 27), 'Raiden is only signing messages with v in (0, 27)' _hash = eth_sign_sha3(data) signature = self.private_key.sign_msg_hash(message_hash=_hash) sig_bytes = signature.to_bytes() # adjust last byte to v return sig_bytes[:-1] + bytes([sig_bytes[-1] + v])
[ "def", "sign", "(", "self", ",", "data", ":", "bytes", ",", "v", ":", "int", "=", "27", ")", "->", "Signature", ":", "assert", "v", "in", "(", "0", ",", "27", ")", ",", "'Raiden is only signing messages with v in (0, 27)'", "_hash", "=", "eth_sign_sha3", ...
Sign data hash with local private key
[ "Sign", "data", "hash", "with", "local", "private", "key" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/signer.py#L83-L90
235,501
raiden-network/raiden
raiden/network/proxies/token.py
Token.approve
def approve( self, allowed_address: Address, allowance: TokenAmount, ): """ Aprove `allowed_address` to transfer up to `deposit` amount of token. Note: For channel deposit please use the channel proxy, since it does additional validations. """ # Note that given_block_identifier is not used here as there # are no preconditions to check before sending the transaction log_details = { 'node': pex(self.node_address), 'contract': pex(self.address), 'allowed_address': pex(allowed_address), 'allowance': allowance, } checking_block = self.client.get_checking_block() error_prefix = 'Call to approve will fail' gas_limit = self.proxy.estimate_gas( checking_block, 'approve', to_checksum_address(allowed_address), allowance, ) if gas_limit: error_prefix = 'Call to approve failed' log.debug('approve called', **log_details) transaction_hash = self.proxy.transact( 'approve', safe_gas_limit(gas_limit), to_checksum_address(allowed_address), allowance, ) 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='approve', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_APPROVE, block_identifier=block, ) msg = self._check_why_approved_failed(allowance, block) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('approve successful', **log_details)
python
def approve( self, allowed_address: Address, allowance: TokenAmount, ): # Note that given_block_identifier is not used here as there # are no preconditions to check before sending the transaction log_details = { 'node': pex(self.node_address), 'contract': pex(self.address), 'allowed_address': pex(allowed_address), 'allowance': allowance, } checking_block = self.client.get_checking_block() error_prefix = 'Call to approve will fail' gas_limit = self.proxy.estimate_gas( checking_block, 'approve', to_checksum_address(allowed_address), allowance, ) if gas_limit: error_prefix = 'Call to approve failed' log.debug('approve called', **log_details) transaction_hash = self.proxy.transact( 'approve', safe_gas_limit(gas_limit), to_checksum_address(allowed_address), allowance, ) 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='approve', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_APPROVE, block_identifier=block, ) msg = self._check_why_approved_failed(allowance, block) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('approve successful', **log_details)
[ "def", "approve", "(", "self", ",", "allowed_address", ":", "Address", ",", "allowance", ":", "TokenAmount", ",", ")", ":", "# Note that given_block_identifier is not used here as there", "# are no preconditions to check before sending the transaction", "log_details", "=", "{",...
Aprove `allowed_address` to transfer up to `deposit` amount of token. Note: For channel deposit please use the channel proxy, since it does additional validations.
[ "Aprove", "allowed_address", "to", "transfer", "up", "to", "deposit", "amount", "of", "token", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token.py#L49-L112
235,502
raiden-network/raiden
raiden/network/proxies/token.py
Token.balance_of
def balance_of(self, address, block_identifier='latest'): """ Return the balance of `address`. """ return self.proxy.contract.functions.balanceOf( to_checksum_address(address), ).call(block_identifier=block_identifier)
python
def balance_of(self, address, block_identifier='latest'): return self.proxy.contract.functions.balanceOf( to_checksum_address(address), ).call(block_identifier=block_identifier)
[ "def", "balance_of", "(", "self", ",", "address", ",", "block_identifier", "=", "'latest'", ")", ":", "return", "self", ".", "proxy", ".", "contract", ".", "functions", ".", "balanceOf", "(", "to_checksum_address", "(", "address", ")", ",", ")", ".", "call...
Return the balance of `address`.
[ "Return", "the", "balance", "of", "address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token.py#L158-L162
235,503
raiden-network/raiden
raiden/network/proxies/token.py
Token.total_supply
def total_supply(self, block_identifier='latest'): """ Return the total supply of the token at the given block identifier. """ return self.proxy.contract.functions.totalSupply().call(block_identifier=block_identifier)
python
def total_supply(self, block_identifier='latest'): return self.proxy.contract.functions.totalSupply().call(block_identifier=block_identifier)
[ "def", "total_supply", "(", "self", ",", "block_identifier", "=", "'latest'", ")", ":", "return", "self", ".", "proxy", ".", "contract", ".", "functions", ".", "totalSupply", "(", ")", ".", "call", "(", "block_identifier", "=", "block_identifier", ")" ]
Return the total supply of the token at the given block identifier.
[ "Return", "the", "total", "supply", "of", "the", "token", "at", "the", "given", "block", "identifier", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token.py#L164-L166
235,504
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator_manager.py
clear_if_finalized
def clear_if_finalized( iteration: TransitionResult, ) -> TransitionResult[InitiatorPaymentState]: """ Clear the initiator payment task if all transfers have been finalized or expired. """ state = cast(InitiatorPaymentState, iteration.new_state) if state is None: return iteration if len(state.initiator_transfers) == 0: return TransitionResult(None, iteration.events) return iteration
python
def clear_if_finalized( iteration: TransitionResult, ) -> TransitionResult[InitiatorPaymentState]: state = cast(InitiatorPaymentState, iteration.new_state) if state is None: return iteration if len(state.initiator_transfers) == 0: return TransitionResult(None, iteration.events) return iteration
[ "def", "clear_if_finalized", "(", "iteration", ":", "TransitionResult", ",", ")", "->", "TransitionResult", "[", "InitiatorPaymentState", "]", ":", "state", "=", "cast", "(", "InitiatorPaymentState", ",", "iteration", ".", "new_state", ")", "if", "state", "is", ...
Clear the initiator payment task if all transfers have been finalized or expired.
[ "Clear", "the", "initiator", "payment", "task", "if", "all", "transfers", "have", "been", "finalized", "or", "expired", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator_manager.py#L34-L47
235,505
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator_manager.py
cancel_current_route
def cancel_current_route( payment_state: InitiatorPaymentState, initiator_state: InitiatorTransferState, ) -> List[Event]: """ Cancel current route. This allows a new route to be tried. """ assert can_cancel(initiator_state), 'Cannot cancel a route after the secret is revealed' transfer_description = initiator_state.transfer_description payment_state.cancelled_channels.append(initiator_state.channel_identifier) return events_for_cancel_current_route(transfer_description)
python
def cancel_current_route( payment_state: InitiatorPaymentState, initiator_state: InitiatorTransferState, ) -> List[Event]: assert can_cancel(initiator_state), 'Cannot cancel a route after the secret is revealed' transfer_description = initiator_state.transfer_description payment_state.cancelled_channels.append(initiator_state.channel_identifier) return events_for_cancel_current_route(transfer_description)
[ "def", "cancel_current_route", "(", "payment_state", ":", "InitiatorPaymentState", ",", "initiator_state", ":", "InitiatorTransferState", ",", ")", "->", "List", "[", "Event", "]", ":", "assert", "can_cancel", "(", "initiator_state", ")", ",", "'Cannot cancel a route ...
Cancel current route. This allows a new route to be tried.
[ "Cancel", "current", "route", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator_manager.py#L81-L95
235,506
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator_manager.py
subdispatch_to_all_initiatortransfer
def subdispatch_to_all_initiatortransfer( payment_state: InitiatorPaymentState, state_change: StateChange, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorPaymentState]: events = list() ''' Copy and iterate over the list of keys because this loop will alter the `initiator_transfers` list and this is not allowed if iterating over the original list. ''' for secrethash in list(payment_state.initiator_transfers.keys()): initiator_state = payment_state.initiator_transfers[secrethash] sub_iteration = subdispatch_to_initiatortransfer( payment_state=payment_state, initiator_state=initiator_state, state_change=state_change, channelidentifiers_to_channels=channelidentifiers_to_channels, pseudo_random_generator=pseudo_random_generator, ) events.extend(sub_iteration.events) return TransitionResult(payment_state, events)
python
def subdispatch_to_all_initiatortransfer( payment_state: InitiatorPaymentState, state_change: StateChange, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorPaymentState]: events = list() ''' Copy and iterate over the list of keys because this loop will alter the `initiator_transfers` list and this is not allowed if iterating over the original list. ''' for secrethash in list(payment_state.initiator_transfers.keys()): initiator_state = payment_state.initiator_transfers[secrethash] sub_iteration = subdispatch_to_initiatortransfer( payment_state=payment_state, initiator_state=initiator_state, state_change=state_change, channelidentifiers_to_channels=channelidentifiers_to_channels, pseudo_random_generator=pseudo_random_generator, ) events.extend(sub_iteration.events) return TransitionResult(payment_state, events)
[ "def", "subdispatch_to_all_initiatortransfer", "(", "payment_state", ":", "InitiatorPaymentState", ",", "state_change", ":", "StateChange", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "-...
Copy and iterate over the list of keys because this loop will alter the `initiator_transfers` list and this is not allowed if iterating over the original list.
[ "Copy", "and", "iterate", "over", "the", "list", "of", "keys", "because", "this", "loop", "will", "alter", "the", "initiator_transfers", "list", "and", "this", "is", "not", "allowed", "if", "iterating", "over", "the", "original", "list", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator_manager.py#L163-L184
235,507
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator_manager.py
handle_cancelpayment
def handle_cancelpayment( payment_state: InitiatorPaymentState, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[InitiatorPaymentState]: """ Cancel the payment and all related transfers. """ # Cannot cancel a transfer after the secret is revealed events = list() for initiator_state in payment_state.initiator_transfers.values(): channel_identifier = initiator_state.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue if can_cancel(initiator_state): transfer_description = initiator_state.transfer_description cancel_events = cancel_current_route(payment_state, initiator_state) initiator_state.transfer_state = 'transfer_cancelled' cancel = EventPaymentSentFailed( payment_network_identifier=channel_state.payment_network_identifier, token_network_identifier=TokenNetworkID(channel_state.token_network_identifier), identifier=transfer_description.payment_identifier, target=transfer_description.target, reason='user canceled payment', ) cancel_events.append(cancel) events.extend(cancel_events) return TransitionResult(payment_state, events)
python
def handle_cancelpayment( payment_state: InitiatorPaymentState, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[InitiatorPaymentState]: # Cannot cancel a transfer after the secret is revealed events = list() for initiator_state in payment_state.initiator_transfers.values(): channel_identifier = initiator_state.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue if can_cancel(initiator_state): transfer_description = initiator_state.transfer_description cancel_events = cancel_current_route(payment_state, initiator_state) initiator_state.transfer_state = 'transfer_cancelled' cancel = EventPaymentSentFailed( payment_network_identifier=channel_state.payment_network_identifier, token_network_identifier=TokenNetworkID(channel_state.token_network_identifier), identifier=transfer_description.payment_identifier, target=transfer_description.target, reason='user canceled payment', ) cancel_events.append(cancel) events.extend(cancel_events) return TransitionResult(payment_state, events)
[ "def", "handle_cancelpayment", "(", "payment_state", ":", "InitiatorPaymentState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "TransitionResult", "[", "InitiatorPaymentState", "]", ":", "# Cannot cancel a transfer after the secret is revealed", "e...
Cancel the payment and all related transfers.
[ "Cancel", "the", "payment", "and", "all", "related", "transfers", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator_manager.py#L232-L263
235,508
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator_manager.py
handle_lock_expired
def handle_lock_expired( payment_state: InitiatorPaymentState, state_change: ReceiveLockExpired, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, ) -> TransitionResult[InitiatorPaymentState]: """Initiator also needs to handle LockExpired messages when refund transfers are involved. A -> B -> C - A sends locked transfer to B - B attempted to forward to C but has not enough capacity - B sends a refund transfer with the same secrethash back to A - When the lock expires B will also send a LockExpired message to A - A needs to be able to properly process it Related issue: https://github.com/raiden-network/raiden/issues/3183 """ initiator_state = payment_state.initiator_transfers.get(state_change.secrethash) if not initiator_state: return TransitionResult(payment_state, list()) channel_identifier = initiator_state.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: return TransitionResult(payment_state, list()) secrethash = initiator_state.transfer.lock.secrethash result = channel.handle_receive_lock_expired( channel_state=channel_state, state_change=state_change, block_number=block_number, ) assert result.new_state, 'handle_receive_lock_expired should not delete the task' if not channel.get_lock(result.new_state.partner_state, secrethash): transfer = initiator_state.transfer unlock_failed = EventUnlockClaimFailed( identifier=transfer.payment_identifier, secrethash=transfer.lock.secrethash, reason='Lock expired', ) result.events.append(unlock_failed) return TransitionResult(payment_state, result.events)
python
def handle_lock_expired( payment_state: InitiatorPaymentState, state_change: ReceiveLockExpired, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, ) -> TransitionResult[InitiatorPaymentState]: initiator_state = payment_state.initiator_transfers.get(state_change.secrethash) if not initiator_state: return TransitionResult(payment_state, list()) channel_identifier = initiator_state.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: return TransitionResult(payment_state, list()) secrethash = initiator_state.transfer.lock.secrethash result = channel.handle_receive_lock_expired( channel_state=channel_state, state_change=state_change, block_number=block_number, ) assert result.new_state, 'handle_receive_lock_expired should not delete the task' if not channel.get_lock(result.new_state.partner_state, secrethash): transfer = initiator_state.transfer unlock_failed = EventUnlockClaimFailed( identifier=transfer.payment_identifier, secrethash=transfer.lock.secrethash, reason='Lock expired', ) result.events.append(unlock_failed) return TransitionResult(payment_state, result.events)
[ "def", "handle_lock_expired", "(", "payment_state", ":", "InitiatorPaymentState", ",", "state_change", ":", "ReceiveLockExpired", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "TransitionResult", "[", ...
Initiator also needs to handle LockExpired messages when refund transfers are involved. A -> B -> C - A sends locked transfer to B - B attempted to forward to C but has not enough capacity - B sends a refund transfer with the same secrethash back to A - When the lock expires B will also send a LockExpired message to A - A needs to be able to properly process it Related issue: https://github.com/raiden-network/raiden/issues/3183
[ "Initiator", "also", "needs", "to", "handle", "LockExpired", "messages", "when", "refund", "transfers", "are", "involved", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator_manager.py#L340-L385
235,509
raiden-network/raiden
raiden/network/rpc/middleware.py
http_retry_with_backoff_middleware
def http_retry_with_backoff_middleware( make_request, web3, # pylint: disable=unused-argument errors: Tuple = ( exceptions.ConnectionError, exceptions.HTTPError, exceptions.Timeout, exceptions.TooManyRedirects, ), retries: int = 10, first_backoff: float = 0.2, backoff_factor: float = 2, ): """ Retry requests with exponential backoff Creates middleware that retries failed HTTP requests and exponentially increases the backoff between retries. Meant to replace the default middleware `http_retry_request_middleware` for HTTPProvider. """ def middleware(method, params): backoff = first_backoff if check_if_retry_on_failure(method): for i in range(retries): try: return make_request(method, params) except errors: if i < retries - 1: gevent.sleep(backoff) backoff *= backoff_factor continue else: raise else: return make_request(method, params) return middleware
python
def http_retry_with_backoff_middleware( make_request, web3, # pylint: disable=unused-argument errors: Tuple = ( exceptions.ConnectionError, exceptions.HTTPError, exceptions.Timeout, exceptions.TooManyRedirects, ), retries: int = 10, first_backoff: float = 0.2, backoff_factor: float = 2, ): def middleware(method, params): backoff = first_backoff if check_if_retry_on_failure(method): for i in range(retries): try: return make_request(method, params) except errors: if i < retries - 1: gevent.sleep(backoff) backoff *= backoff_factor continue else: raise else: return make_request(method, params) return middleware
[ "def", "http_retry_with_backoff_middleware", "(", "make_request", ",", "web3", ",", "# pylint: disable=unused-argument", "errors", ":", "Tuple", "=", "(", "exceptions", ".", "ConnectionError", ",", "exceptions", ".", "HTTPError", ",", "exceptions", ".", "Timeout", ","...
Retry requests with exponential backoff Creates middleware that retries failed HTTP requests and exponentially increases the backoff between retries. Meant to replace the default middleware `http_retry_request_middleware` for HTTPProvider.
[ "Retry", "requests", "with", "exponential", "backoff", "Creates", "middleware", "that", "retries", "failed", "HTTP", "requests", "and", "exponentially", "increases", "the", "backoff", "between", "retries", ".", "Meant", "to", "replace", "the", "default", "middleware...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/middleware.py#L52-L86
235,510
raiden-network/raiden
raiden/network/pathfinding.py
get_random_service
def get_random_service( service_registry: ServiceRegistry, block_identifier: BlockSpecification, ) -> Tuple[Optional[str], Optional[str]]: """Selects a random PFS from service_registry. Returns a tuple of the chosen services url and eth address. If there are no PFS in the given registry, it returns (None, None). """ count = service_registry.service_count(block_identifier=block_identifier) if count == 0: return None, None index = random.SystemRandom().randint(0, count - 1) address = service_registry.get_service_address( block_identifier=block_identifier, index=index, ) # We are using the same blockhash for both blockchain queries so the address # should exist for this query. Additionally at the moment there is no way for # services to be removed from the registry. assert address, 'address should exist for this index' url = service_registry.get_service_url( block_identifier=block_identifier, service_hex_address=address, ) return url, address
python
def get_random_service( service_registry: ServiceRegistry, block_identifier: BlockSpecification, ) -> Tuple[Optional[str], Optional[str]]: count = service_registry.service_count(block_identifier=block_identifier) if count == 0: return None, None index = random.SystemRandom().randint(0, count - 1) address = service_registry.get_service_address( block_identifier=block_identifier, index=index, ) # We are using the same blockhash for both blockchain queries so the address # should exist for this query. Additionally at the moment there is no way for # services to be removed from the registry. assert address, 'address should exist for this index' url = service_registry.get_service_url( block_identifier=block_identifier, service_hex_address=address, ) return url, address
[ "def", "get_random_service", "(", "service_registry", ":", "ServiceRegistry", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "str", "]", "]", ":", "count", "=", "service_regi...
Selects a random PFS from service_registry. Returns a tuple of the chosen services url and eth address. If there are no PFS in the given registry, it returns (None, None).
[ "Selects", "a", "random", "PFS", "from", "service_registry", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/pathfinding.py#L81-L106
235,511
raiden-network/raiden
raiden/network/pathfinding.py
configure_pfs_or_exit
def configure_pfs_or_exit( pfs_address: Optional[str], pfs_eth_address: Optional[str], routing_mode: RoutingMode, service_registry, ) -> Optional[PFSConfiguration]: """ Take in the given pfs_address argument, the service registry and find out a pfs address to use. If pfs_address is None then basic routing must have been requested. If pfs_address is provided we use that. If pfs_address is 'auto' then we randomly choose a PFS address from the registry Returns a NamedTuple containing url, eth_address and fee (per paths request) of the selected PFS, or None if we use basic routing instead of a PFS. """ if routing_mode == RoutingMode.BASIC: msg = 'Not using path finding services, falling back to basic routing.' log.info(msg) click.secho(msg) return None msg = "With PFS routing mode we shouldn't get to configure pfs with pfs_address being None" assert pfs_address, msg if pfs_address == 'auto': assert service_registry, 'Should not get here without a service registry' block_hash = service_registry.client.get_confirmed_blockhash() pfs_address, pfs_eth_address = get_random_service( service_registry=service_registry, block_identifier=block_hash, ) if pfs_address is None: click.secho( "The service registry has no registered path finding service " "and we don't use basic routing.", ) sys.exit(1) assert pfs_eth_address, "At this point pfs_eth_address can't be none" pathfinding_service_info = get_pfs_info(pfs_address) if not pathfinding_service_info: click.secho( f'There is an error with the pathfinding service with address ' f'{pfs_address}. Raiden will shut down.', ) sys.exit(1) else: msg = configure_pfs_message( info=pathfinding_service_info, url=pfs_address, eth_address=pfs_eth_address, ) click.secho(msg) log.info('Using PFS', pfs_info=pathfinding_service_info) return PFSConfiguration( url=pfs_address, eth_address=pfs_eth_address, fee=pathfinding_service_info.get('price_info', 0), )
python
def configure_pfs_or_exit( pfs_address: Optional[str], pfs_eth_address: Optional[str], routing_mode: RoutingMode, service_registry, ) -> Optional[PFSConfiguration]: if routing_mode == RoutingMode.BASIC: msg = 'Not using path finding services, falling back to basic routing.' log.info(msg) click.secho(msg) return None msg = "With PFS routing mode we shouldn't get to configure pfs with pfs_address being None" assert pfs_address, msg if pfs_address == 'auto': assert service_registry, 'Should not get here without a service registry' block_hash = service_registry.client.get_confirmed_blockhash() pfs_address, pfs_eth_address = get_random_service( service_registry=service_registry, block_identifier=block_hash, ) if pfs_address is None: click.secho( "The service registry has no registered path finding service " "and we don't use basic routing.", ) sys.exit(1) assert pfs_eth_address, "At this point pfs_eth_address can't be none" pathfinding_service_info = get_pfs_info(pfs_address) if not pathfinding_service_info: click.secho( f'There is an error with the pathfinding service with address ' f'{pfs_address}. Raiden will shut down.', ) sys.exit(1) else: msg = configure_pfs_message( info=pathfinding_service_info, url=pfs_address, eth_address=pfs_eth_address, ) click.secho(msg) log.info('Using PFS', pfs_info=pathfinding_service_info) return PFSConfiguration( url=pfs_address, eth_address=pfs_eth_address, fee=pathfinding_service_info.get('price_info', 0), )
[ "def", "configure_pfs_or_exit", "(", "pfs_address", ":", "Optional", "[", "str", "]", ",", "pfs_eth_address", ":", "Optional", "[", "str", "]", ",", "routing_mode", ":", "RoutingMode", ",", "service_registry", ",", ")", "->", "Optional", "[", "PFSConfiguration",...
Take in the given pfs_address argument, the service registry and find out a pfs address to use. If pfs_address is None then basic routing must have been requested. If pfs_address is provided we use that. If pfs_address is 'auto' then we randomly choose a PFS address from the registry Returns a NamedTuple containing url, eth_address and fee (per paths request) of the selected PFS, or None if we use basic routing instead of a PFS.
[ "Take", "in", "the", "given", "pfs_address", "argument", "the", "service", "registry", "and", "find", "out", "a", "pfs", "address", "to", "use", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/pathfinding.py#L132-L192
235,512
raiden-network/raiden
raiden/network/pathfinding.py
query_paths
def query_paths( service_config: Dict[str, Any], our_address: Address, privkey: bytes, current_block_number: BlockNumber, token_network_address: Union[TokenNetworkAddress, TokenNetworkID], route_from: InitiatorAddress, route_to: TargetAddress, value: PaymentAmount, ) -> List[Dict[str, Any]]: """ Query paths from the PFS. Send a request to the /paths endpoint of the PFS specified in service_config, and retry in case of a failed request if it makes sense. """ max_paths = service_config['pathfinding_max_paths'] url = service_config['pathfinding_service_address'] payload = { 'from': to_checksum_address(route_from), 'to': to_checksum_address(route_to), 'value': value, 'max_paths': max_paths, } offered_fee = service_config.get('pathfinding_fee', service_config['pathfinding_max_fee']) scrap_existing_iou = False for retries in reversed(range(MAX_PATHS_QUERY_ATTEMPTS)): payload['iou'] = create_current_iou( config=service_config, token_network_address=token_network_address, our_address=our_address, privkey=privkey, block_number=current_block_number, offered_fee=offered_fee, scrap_existing_iou=scrap_existing_iou, ) try: return post_pfs_paths( url=url, token_network_address=token_network_address, payload=payload, ) except ServiceRequestIOURejected as error: code = error.error_code if retries == 0 or code in (PFSError.WRONG_IOU_RECIPIENT, PFSError.DEPOSIT_TOO_LOW): raise elif code in (PFSError.IOU_ALREADY_CLAIMED, PFSError.IOU_EXPIRED_TOO_EARLY): scrap_existing_iou = True elif code == PFSError.INSUFFICIENT_SERVICE_PAYMENT: if offered_fee < service_config['pathfinding_max_fee']: offered_fee = service_config['pathfinding_max_fee'] # TODO: Query the PFS for the fee here instead of using the max fee else: raise log.info(f'PFS rejected our IOU, reason: {error}. Attempting again.') # If we got no results after MAX_PATHS_QUERY_ATTEMPTS return empty list of paths return list()
python
def query_paths( service_config: Dict[str, Any], our_address: Address, privkey: bytes, current_block_number: BlockNumber, token_network_address: Union[TokenNetworkAddress, TokenNetworkID], route_from: InitiatorAddress, route_to: TargetAddress, value: PaymentAmount, ) -> List[Dict[str, Any]]: max_paths = service_config['pathfinding_max_paths'] url = service_config['pathfinding_service_address'] payload = { 'from': to_checksum_address(route_from), 'to': to_checksum_address(route_to), 'value': value, 'max_paths': max_paths, } offered_fee = service_config.get('pathfinding_fee', service_config['pathfinding_max_fee']) scrap_existing_iou = False for retries in reversed(range(MAX_PATHS_QUERY_ATTEMPTS)): payload['iou'] = create_current_iou( config=service_config, token_network_address=token_network_address, our_address=our_address, privkey=privkey, block_number=current_block_number, offered_fee=offered_fee, scrap_existing_iou=scrap_existing_iou, ) try: return post_pfs_paths( url=url, token_network_address=token_network_address, payload=payload, ) except ServiceRequestIOURejected as error: code = error.error_code if retries == 0 or code in (PFSError.WRONG_IOU_RECIPIENT, PFSError.DEPOSIT_TOO_LOW): raise elif code in (PFSError.IOU_ALREADY_CLAIMED, PFSError.IOU_EXPIRED_TOO_EARLY): scrap_existing_iou = True elif code == PFSError.INSUFFICIENT_SERVICE_PAYMENT: if offered_fee < service_config['pathfinding_max_fee']: offered_fee = service_config['pathfinding_max_fee'] # TODO: Query the PFS for the fee here instead of using the max fee else: raise log.info(f'PFS rejected our IOU, reason: {error}. Attempting again.') # If we got no results after MAX_PATHS_QUERY_ATTEMPTS return empty list of paths return list()
[ "def", "query_paths", "(", "service_config", ":", "Dict", "[", "str", ",", "Any", "]", ",", "our_address", ":", "Address", ",", "privkey", ":", "bytes", ",", "current_block_number", ":", "BlockNumber", ",", "token_network_address", ":", "Union", "[", "TokenNet...
Query paths from the PFS. Send a request to the /paths endpoint of the PFS specified in service_config, and retry in case of a failed request if it makes sense.
[ "Query", "paths", "from", "the", "PFS", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/pathfinding.py#L362-L421
235,513
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
single_queue_send
def single_queue_send( transport: 'UDPTransport', recipient: Address, queue: Queue_T, queue_identifier: QueueIdentifier, event_stop: Event, event_healthy: Event, event_unhealthy: Event, message_retries: int, message_retry_timeout: int, message_retry_max_timeout: int, ): """ Handles a single message queue for `recipient`. Notes: - This task must be the only consumer of queue. - This task can be killed at any time, but the intended usage is to stop it with the event_stop. - If there are many queues for the same recipient, it is the caller's responsibility to not start them together to avoid congestion. - This task assumes the endpoint is never cleared after it's first known. If this assumption changes the code must be updated to handle unknown addresses. """ # A NotifyingQueue is required to implement cancelability, otherwise the # task cannot be stopped while the greenlet waits for an element to be # inserted in the queue. if not isinstance(queue, NotifyingQueue): raise ValueError('queue must be a NotifyingQueue.') # Reusing the event, clear must be carefully done data_or_stop = event_first_of( queue, event_stop, ) # Wait for the endpoint registration or to quit transport.log.debug( 'queue: waiting for node to become healthy', queue_identifier=queue_identifier, queue_size=len(queue), ) event_first_of( event_healthy, event_stop, ).wait() transport.log.debug( 'queue: processing queue', queue_identifier=queue_identifier, queue_size=len(queue), ) while True: data_or_stop.wait() if event_stop.is_set(): transport.log.debug( 'queue: stopping', queue_identifier=queue_identifier, queue_size=len(queue), ) return # The queue is not empty at this point, so this won't raise Empty. # This task being the only consumer is a requirement. (messagedata, message_id) = queue.peek(block=False) transport.log.debug( 'queue: sending message', recipient=pex(recipient), msgid=message_id, queue_identifier=queue_identifier, queue_size=len(queue), ) backoff = timeout_exponential_backoff( message_retries, message_retry_timeout, message_retry_max_timeout, ) acknowledged = retry_with_recovery( transport, messagedata, message_id, recipient, event_stop, event_healthy, event_unhealthy, backoff, ) if acknowledged: queue.get() # Checking the length of the queue does not trigger a # context-switch, so it's safe to assume the length of the queue # won't change under our feet and when a new item will be added the # event will be set again. if not queue: data_or_stop.clear() if event_stop.is_set(): return
python
def single_queue_send( transport: 'UDPTransport', recipient: Address, queue: Queue_T, queue_identifier: QueueIdentifier, event_stop: Event, event_healthy: Event, event_unhealthy: Event, message_retries: int, message_retry_timeout: int, message_retry_max_timeout: int, ): # A NotifyingQueue is required to implement cancelability, otherwise the # task cannot be stopped while the greenlet waits for an element to be # inserted in the queue. if not isinstance(queue, NotifyingQueue): raise ValueError('queue must be a NotifyingQueue.') # Reusing the event, clear must be carefully done data_or_stop = event_first_of( queue, event_stop, ) # Wait for the endpoint registration or to quit transport.log.debug( 'queue: waiting for node to become healthy', queue_identifier=queue_identifier, queue_size=len(queue), ) event_first_of( event_healthy, event_stop, ).wait() transport.log.debug( 'queue: processing queue', queue_identifier=queue_identifier, queue_size=len(queue), ) while True: data_or_stop.wait() if event_stop.is_set(): transport.log.debug( 'queue: stopping', queue_identifier=queue_identifier, queue_size=len(queue), ) return # The queue is not empty at this point, so this won't raise Empty. # This task being the only consumer is a requirement. (messagedata, message_id) = queue.peek(block=False) transport.log.debug( 'queue: sending message', recipient=pex(recipient), msgid=message_id, queue_identifier=queue_identifier, queue_size=len(queue), ) backoff = timeout_exponential_backoff( message_retries, message_retry_timeout, message_retry_max_timeout, ) acknowledged = retry_with_recovery( transport, messagedata, message_id, recipient, event_stop, event_healthy, event_unhealthy, backoff, ) if acknowledged: queue.get() # Checking the length of the queue does not trigger a # context-switch, so it's safe to assume the length of the queue # won't change under our feet and when a new item will be added the # event will be set again. if not queue: data_or_stop.clear() if event_stop.is_set(): return
[ "def", "single_queue_send", "(", "transport", ":", "'UDPTransport'", ",", "recipient", ":", "Address", ",", "queue", ":", "Queue_T", ",", "queue_identifier", ":", "QueueIdentifier", ",", "event_stop", ":", "Event", ",", "event_healthy", ":", "Event", ",", "event...
Handles a single message queue for `recipient`. Notes: - This task must be the only consumer of queue. - This task can be killed at any time, but the intended usage is to stop it with the event_stop. - If there are many queues for the same recipient, it is the caller's responsibility to not start them together to avoid congestion. - This task assumes the endpoint is never cleared after it's first known. If this assumption changes the code must be updated to handle unknown addresses.
[ "Handles", "a", "single", "message", "queue", "for", "recipient", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L57-L163
235,514
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.get_health_events
def get_health_events(self, recipient): """ Starts a healthcheck task for `recipient` and returns a HealthEvents with locks to react on its current state. """ if recipient not in self.addresses_events: self.start_health_check(recipient) return self.addresses_events[recipient]
python
def get_health_events(self, recipient): if recipient not in self.addresses_events: self.start_health_check(recipient) return self.addresses_events[recipient]
[ "def", "get_health_events", "(", "self", ",", "recipient", ")", ":", "if", "recipient", "not", "in", "self", ".", "addresses_events", ":", "self", ".", "start_health_check", "(", "recipient", ")", "return", "self", ".", "addresses_events", "[", "recipient", "]...
Starts a healthcheck task for `recipient` and returns a HealthEvents with locks to react on its current state.
[ "Starts", "a", "healthcheck", "task", "for", "recipient", "and", "returns", "a", "HealthEvents", "with", "locks", "to", "react", "on", "its", "current", "state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L287-L294
235,515
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.start_health_check
def start_health_check(self, recipient): """ Starts a task for healthchecking `recipient` if there is not one yet. It also whitelists the address """ if recipient not in self.addresses_events: self.whitelist(recipient) # noop for now, for compatibility ping_nonce = self.nodeaddresses_to_nonces.setdefault( recipient, {'nonce': 0}, # HACK: Allows the task to mutate the object ) events = healthcheck.HealthEvents( event_healthy=Event(), event_unhealthy=Event(), ) self.addresses_events[recipient] = events greenlet_healthcheck = gevent.spawn( healthcheck.healthcheck, self, recipient, self.event_stop, events.event_healthy, events.event_unhealthy, self.nat_keepalive_retries, self.nat_keepalive_timeout, self.nat_invitation_timeout, ping_nonce, ) greenlet_healthcheck.name = f'Healthcheck for {pex(recipient)}' greenlet_healthcheck.link_exception(self.on_error) self.greenlets.append(greenlet_healthcheck)
python
def start_health_check(self, recipient): if recipient not in self.addresses_events: self.whitelist(recipient) # noop for now, for compatibility ping_nonce = self.nodeaddresses_to_nonces.setdefault( recipient, {'nonce': 0}, # HACK: Allows the task to mutate the object ) events = healthcheck.HealthEvents( event_healthy=Event(), event_unhealthy=Event(), ) self.addresses_events[recipient] = events greenlet_healthcheck = gevent.spawn( healthcheck.healthcheck, self, recipient, self.event_stop, events.event_healthy, events.event_unhealthy, self.nat_keepalive_retries, self.nat_keepalive_timeout, self.nat_invitation_timeout, ping_nonce, ) greenlet_healthcheck.name = f'Healthcheck for {pex(recipient)}' greenlet_healthcheck.link_exception(self.on_error) self.greenlets.append(greenlet_healthcheck)
[ "def", "start_health_check", "(", "self", ",", "recipient", ")", ":", "if", "recipient", "not", "in", "self", ".", "addresses_events", ":", "self", ".", "whitelist", "(", "recipient", ")", "# noop for now, for compatibility", "ping_nonce", "=", "self", ".", "nod...
Starts a task for healthchecking `recipient` if there is not one yet. It also whitelists the address
[ "Starts", "a", "task", "for", "healthchecking", "recipient", "if", "there", "is", "not", "one", "yet", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L305-L339
235,516
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.init_queue_for
def init_queue_for( self, queue_identifier: QueueIdentifier, items: List[QueueItem_T], ) -> NotifyingQueue: """ Create the queue identified by the queue_identifier and initialize it with `items`. """ recipient = queue_identifier.recipient queue = self.queueids_to_queues.get(queue_identifier) assert queue is None queue = NotifyingQueue(items=items) self.queueids_to_queues[queue_identifier] = queue events = self.get_health_events(recipient) greenlet_queue = gevent.spawn( single_queue_send, self, recipient, queue, queue_identifier, self.event_stop, events.event_healthy, events.event_unhealthy, self.retries_before_backoff, self.retry_interval, self.retry_interval * 10, ) if queue_identifier.channel_identifier == CHANNEL_IDENTIFIER_GLOBAL_QUEUE: greenlet_queue.name = f'Queue for {pex(recipient)} - global' else: greenlet_queue.name = ( f'Queue for {pex(recipient)} - {queue_identifier.channel_identifier}' ) greenlet_queue.link_exception(self.on_error) self.greenlets.append(greenlet_queue) self.log.debug( 'new queue created for', queue_identifier=queue_identifier, items_qty=len(items), ) return queue
python
def init_queue_for( self, queue_identifier: QueueIdentifier, items: List[QueueItem_T], ) -> NotifyingQueue: recipient = queue_identifier.recipient queue = self.queueids_to_queues.get(queue_identifier) assert queue is None queue = NotifyingQueue(items=items) self.queueids_to_queues[queue_identifier] = queue events = self.get_health_events(recipient) greenlet_queue = gevent.spawn( single_queue_send, self, recipient, queue, queue_identifier, self.event_stop, events.event_healthy, events.event_unhealthy, self.retries_before_backoff, self.retry_interval, self.retry_interval * 10, ) if queue_identifier.channel_identifier == CHANNEL_IDENTIFIER_GLOBAL_QUEUE: greenlet_queue.name = f'Queue for {pex(recipient)} - global' else: greenlet_queue.name = ( f'Queue for {pex(recipient)} - {queue_identifier.channel_identifier}' ) greenlet_queue.link_exception(self.on_error) self.greenlets.append(greenlet_queue) self.log.debug( 'new queue created for', queue_identifier=queue_identifier, items_qty=len(items), ) return queue
[ "def", "init_queue_for", "(", "self", ",", "queue_identifier", ":", "QueueIdentifier", ",", "items", ":", "List", "[", "QueueItem_T", "]", ",", ")", "->", "NotifyingQueue", ":", "recipient", "=", "queue_identifier", ".", "recipient", "queue", "=", "self", ".",...
Create the queue identified by the queue_identifier and initialize it with `items`.
[ "Create", "the", "queue", "identified", "by", "the", "queue_identifier", "and", "initialize", "it", "with", "items", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L341-L388
235,517
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.get_queue_for
def get_queue_for( self, queue_identifier: QueueIdentifier, ) -> NotifyingQueue: """ Return the queue identified by the given queue identifier. If the queue doesn't exist it will be instantiated. """ queue = self.queueids_to_queues.get(queue_identifier) if queue is None: items: List[QueueItem_T] = list() queue = self.init_queue_for(queue_identifier, items) return queue
python
def get_queue_for( self, queue_identifier: QueueIdentifier, ) -> NotifyingQueue: queue = self.queueids_to_queues.get(queue_identifier) if queue is None: items: List[QueueItem_T] = list() queue = self.init_queue_for(queue_identifier, items) return queue
[ "def", "get_queue_for", "(", "self", ",", "queue_identifier", ":", "QueueIdentifier", ",", ")", "->", "NotifyingQueue", ":", "queue", "=", "self", ".", "queueids_to_queues", ".", "get", "(", "queue_identifier", ")", "if", "queue", "is", "None", ":", "items", ...
Return the queue identified by the given queue identifier. If the queue doesn't exist it will be instantiated.
[ "Return", "the", "queue", "identified", "by", "the", "given", "queue", "identifier", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L390-L404
235,518
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.send_async
def send_async( self, queue_identifier: QueueIdentifier, message: Message, ): """ Send a new ordered message to recipient. Messages that use the same `queue_identifier` are ordered. """ recipient = queue_identifier.recipient if not is_binary_address(recipient): raise ValueError('Invalid address {}'.format(pex(recipient))) # These are not protocol messages, but transport specific messages if isinstance(message, (Delivered, Ping, Pong)): raise ValueError('Do not use send for {} messages'.format(message.__class__.__name__)) messagedata = message.encode() if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE: raise ValueError( 'message size exceeds the maximum {}'.format(self.UDP_MAX_MESSAGE_SIZE), ) # message identifiers must be unique message_id = message.message_identifier # ignore duplicates if message_id not in self.messageids_to_asyncresults: self.messageids_to_asyncresults[message_id] = AsyncResult() queue = self.get_queue_for(queue_identifier) queue.put((messagedata, message_id)) assert queue.is_set() self.log.debug( 'Message queued', queue_identifier=queue_identifier, queue_size=len(queue), message=message, )
python
def send_async( self, queue_identifier: QueueIdentifier, message: Message, ): recipient = queue_identifier.recipient if not is_binary_address(recipient): raise ValueError('Invalid address {}'.format(pex(recipient))) # These are not protocol messages, but transport specific messages if isinstance(message, (Delivered, Ping, Pong)): raise ValueError('Do not use send for {} messages'.format(message.__class__.__name__)) messagedata = message.encode() if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE: raise ValueError( 'message size exceeds the maximum {}'.format(self.UDP_MAX_MESSAGE_SIZE), ) # message identifiers must be unique message_id = message.message_identifier # ignore duplicates if message_id not in self.messageids_to_asyncresults: self.messageids_to_asyncresults[message_id] = AsyncResult() queue = self.get_queue_for(queue_identifier) queue.put((messagedata, message_id)) assert queue.is_set() self.log.debug( 'Message queued', queue_identifier=queue_identifier, queue_size=len(queue), message=message, )
[ "def", "send_async", "(", "self", ",", "queue_identifier", ":", "QueueIdentifier", ",", "message", ":", "Message", ",", ")", ":", "recipient", "=", "queue_identifier", ".", "recipient", "if", "not", "is_binary_address", "(", "recipient", ")", ":", "raise", "Va...
Send a new ordered message to recipient. Messages that use the same `queue_identifier` are ordered.
[ "Send", "a", "new", "ordered", "message", "to", "recipient", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L406-L445
235,519
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.receive
def receive( self, messagedata: bytes, host_port: Tuple[str, int], # pylint: disable=unused-argument ) -> bool: """ Handle an UDP packet. """ # pylint: disable=unidiomatic-typecheck if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE: self.log.warning( 'Invalid message: Packet larger than maximum size', message=encode_hex(messagedata), length=len(messagedata), ) return False try: message = decode(messagedata) except InvalidProtocolMessage as e: self.log.warning( 'Invalid protocol message', error=str(e), message=encode_hex(messagedata), ) return False if type(message) == Pong: assert isinstance(message, Pong), MYPY_ANNOTATION self.receive_pong(message) elif type(message) == Ping: assert isinstance(message, Ping), MYPY_ANNOTATION self.receive_ping(message) elif type(message) == Delivered: assert isinstance(message, Delivered), MYPY_ANNOTATION self.receive_delivered(message) elif message is not None: self.receive_message(message) else: self.log.warning( 'Invalid message: Unknown cmdid', message=encode_hex(messagedata), ) return False return True
python
def receive( self, messagedata: bytes, host_port: Tuple[str, int], # pylint: disable=unused-argument ) -> bool: # pylint: disable=unidiomatic-typecheck if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE: self.log.warning( 'Invalid message: Packet larger than maximum size', message=encode_hex(messagedata), length=len(messagedata), ) return False try: message = decode(messagedata) except InvalidProtocolMessage as e: self.log.warning( 'Invalid protocol message', error=str(e), message=encode_hex(messagedata), ) return False if type(message) == Pong: assert isinstance(message, Pong), MYPY_ANNOTATION self.receive_pong(message) elif type(message) == Ping: assert isinstance(message, Ping), MYPY_ANNOTATION self.receive_ping(message) elif type(message) == Delivered: assert isinstance(message, Delivered), MYPY_ANNOTATION self.receive_delivered(message) elif message is not None: self.receive_message(message) else: self.log.warning( 'Invalid message: Unknown cmdid', message=encode_hex(messagedata), ) return False return True
[ "def", "receive", "(", "self", ",", "messagedata", ":", "bytes", ",", "host_port", ":", "Tuple", "[", "str", ",", "int", "]", ",", "# pylint: disable=unused-argument", ")", "->", "bool", ":", "# pylint: disable=unidiomatic-typecheck", "if", "len", "(", "messaged...
Handle an UDP packet.
[ "Handle", "an", "UDP", "packet", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L506-L550
235,520
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.receive_message
def receive_message(self, message: Message): """ Handle a Raiden protocol message. The protocol requires durability of the messages. The UDP transport relies on the node's WAL for durability. The message will be converted to a state change, saved to the WAL, and *processed* before the durability is confirmed, which is a stronger property than what is required of any transport. """ self.raiden.on_message(message) # Sending Delivered after the message is decoded and *processed* # gives a stronger guarantee than what is required from a # transport. # # Alternatives are, from weakest to strongest options: # - Just save it on disk and asynchronously process the messages # - Decode it, save to the WAL, and asynchronously process the # state change # - Decode it, save to the WAL, and process it (the current # implementation) delivered_message = Delivered(delivered_message_identifier=message.message_identifier) self.raiden.sign(delivered_message) self.maybe_send( message.sender, delivered_message, )
python
def receive_message(self, message: Message): self.raiden.on_message(message) # Sending Delivered after the message is decoded and *processed* # gives a stronger guarantee than what is required from a # transport. # # Alternatives are, from weakest to strongest options: # - Just save it on disk and asynchronously process the messages # - Decode it, save to the WAL, and asynchronously process the # state change # - Decode it, save to the WAL, and process it (the current # implementation) delivered_message = Delivered(delivered_message_identifier=message.message_identifier) self.raiden.sign(delivered_message) self.maybe_send( message.sender, delivered_message, )
[ "def", "receive_message", "(", "self", ",", "message", ":", "Message", ")", ":", "self", ".", "raiden", ".", "on_message", "(", "message", ")", "# Sending Delivered after the message is decoded and *processed*", "# gives a stronger guarantee than what is required from a", "# ...
Handle a Raiden protocol message. The protocol requires durability of the messages. The UDP transport relies on the node's WAL for durability. The message will be converted to a state change, saved to the WAL, and *processed* before the durability is confirmed, which is a stronger property than what is required of any transport.
[ "Handle", "a", "Raiden", "protocol", "message", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L552-L579
235,521
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.receive_delivered
def receive_delivered(self, delivered: Delivered): """ Handle a Delivered message. The Delivered message is how the UDP transport guarantees persistence by the partner node. The message itself is not part of the raiden protocol, but it's required by this transport to provide the required properties. """ self.raiden.on_message(delivered) message_id = delivered.delivered_message_identifier async_result = self.raiden.transport.messageids_to_asyncresults.get(message_id) # clear the async result, otherwise we have a memory leak if async_result is not None: del self.messageids_to_asyncresults[message_id] async_result.set() else: self.log.warn( 'Unknown delivered message received', message_id=message_id, )
python
def receive_delivered(self, delivered: Delivered): self.raiden.on_message(delivered) message_id = delivered.delivered_message_identifier async_result = self.raiden.transport.messageids_to_asyncresults.get(message_id) # clear the async result, otherwise we have a memory leak if async_result is not None: del self.messageids_to_asyncresults[message_id] async_result.set() else: self.log.warn( 'Unknown delivered message received', message_id=message_id, )
[ "def", "receive_delivered", "(", "self", ",", "delivered", ":", "Delivered", ")", ":", "self", ".", "raiden", ".", "on_message", "(", "delivered", ")", "message_id", "=", "delivered", ".", "delivered_message_identifier", "async_result", "=", "self", ".", "raiden...
Handle a Delivered message. The Delivered message is how the UDP transport guarantees persistence by the partner node. The message itself is not part of the raiden protocol, but it's required by this transport to provide the required properties.
[ "Handle", "a", "Delivered", "message", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L581-L602
235,522
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.receive_ping
def receive_ping(self, ping: Ping): """ Handle a Ping message by answering with a Pong. """ self.log_healthcheck.debug( 'Ping received', message_id=ping.nonce, message=ping, sender=pex(ping.sender), ) pong = Pong(nonce=ping.nonce) self.raiden.sign(pong) try: self.maybe_send(ping.sender, pong) except (InvalidAddress, UnknownAddress) as e: self.log.debug("Couldn't send the `Delivered` message", e=e)
python
def receive_ping(self, ping: Ping): self.log_healthcheck.debug( 'Ping received', message_id=ping.nonce, message=ping, sender=pex(ping.sender), ) pong = Pong(nonce=ping.nonce) self.raiden.sign(pong) try: self.maybe_send(ping.sender, pong) except (InvalidAddress, UnknownAddress) as e: self.log.debug("Couldn't send the `Delivered` message", e=e)
[ "def", "receive_ping", "(", "self", ",", "ping", ":", "Ping", ")", ":", "self", ".", "log_healthcheck", ".", "debug", "(", "'Ping received'", ",", "message_id", "=", "ping", ".", "nonce", ",", "message", "=", "ping", ",", "sender", "=", "pex", "(", "pi...
Handle a Ping message by answering with a Pong.
[ "Handle", "a", "Ping", "message", "by", "answering", "with", "a", "Pong", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L607-L623
235,523
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.receive_pong
def receive_pong(self, pong: Pong): """ Handles a Pong message. """ message_id = ('ping', pong.nonce, pong.sender) async_result = self.messageids_to_asyncresults.get(message_id) if async_result is not None: self.log_healthcheck.debug( 'Pong received', sender=pex(pong.sender), message_id=pong.nonce, ) async_result.set(True) else: self.log_healthcheck.warn( 'Unknown pong received', message_id=message_id, )
python
def receive_pong(self, pong: Pong): message_id = ('ping', pong.nonce, pong.sender) async_result = self.messageids_to_asyncresults.get(message_id) if async_result is not None: self.log_healthcheck.debug( 'Pong received', sender=pex(pong.sender), message_id=pong.nonce, ) async_result.set(True) else: self.log_healthcheck.warn( 'Unknown pong received', message_id=message_id, )
[ "def", "receive_pong", "(", "self", ",", "pong", ":", "Pong", ")", ":", "message_id", "=", "(", "'ping'", ",", "pong", ".", "nonce", ",", "pong", ".", "sender", ")", "async_result", "=", "self", ".", "messageids_to_asyncresults", ".", "get", "(", "messag...
Handles a Pong message.
[ "Handles", "a", "Pong", "message", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L625-L644
235,524
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
UDPTransport.get_ping
def get_ping(self, nonce: Nonce) -> bytes: """ Returns a signed Ping message. Note: Ping messages don't have an enforced ordering, so a Ping message with a higher nonce may be acknowledged first. """ message = Ping( nonce=nonce, current_protocol_version=constants.PROTOCOL_VERSION, ) self.raiden.sign(message) return message.encode()
python
def get_ping(self, nonce: Nonce) -> bytes: message = Ping( nonce=nonce, current_protocol_version=constants.PROTOCOL_VERSION, ) self.raiden.sign(message) return message.encode()
[ "def", "get_ping", "(", "self", ",", "nonce", ":", "Nonce", ")", "->", "bytes", ":", "message", "=", "Ping", "(", "nonce", "=", "nonce", ",", "current_protocol_version", "=", "constants", ".", "PROTOCOL_VERSION", ",", ")", "self", ".", "raiden", ".", "si...
Returns a signed Ping message. Note: Ping messages don't have an enforced ordering, so a Ping message with a higher nonce may be acknowledged first.
[ "Returns", "a", "signed", "Ping", "message", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L646-L657
235,525
raiden-network/raiden
raiden/utils/cli.py
apply_config_file
def apply_config_file( command_function: Union[click.Command, click.Group], cli_params: Dict[str, Any], ctx, config_file_option_name='config_file', ): """ Applies all options set in the config file to `cli_params` """ paramname_to_param = {param.name: param for param in command_function.params} path_params = { param.name for param in command_function.params if isinstance(param.type, (click.Path, click.File)) } config_file_path = Path(cli_params[config_file_option_name]) config_file_values = dict() try: with config_file_path.open() as config_file: config_file_values = load(config_file) except OSError as ex: # Silently ignore if 'file not found' and the config file path is the default config_file_param = paramname_to_param[config_file_option_name] config_file_default_path = Path( config_file_param.type.expand_default(config_file_param.get_default(ctx), cli_params), ) default_config_missing = ( ex.errno == errno.ENOENT and config_file_path.resolve() == config_file_default_path.resolve() ) if default_config_missing: cli_params['config_file'] = None else: click.secho(f"Error opening config file: {ex}", fg='red') sys.exit(1) except TomlError as ex: click.secho(f'Error loading config file: {ex}', fg='red') sys.exit(1) for config_name, config_value in config_file_values.items(): config_name_int = config_name.replace('-', '_') if config_name_int not in paramname_to_param: click.secho( f"Unknown setting '{config_name}' found in config file - ignoring.", fg='yellow', ) continue if config_name_int in path_params: # Allow users to use `~` in paths in the config file config_value = os.path.expanduser(config_value) if config_name_int == LOG_CONFIG_OPTION_NAME: # Uppercase log level names config_value = {k: v.upper() for k, v in config_value.items()} else: # Pipe config file values through cli converter to ensure correct types # We exclude `log-config` because it already is a dict when loading from toml try: config_value = paramname_to_param[config_name_int].type.convert( config_value, paramname_to_param[config_name_int], ctx, ) except click.BadParameter as ex: click.secho(f"Invalid config file setting '{config_name}': {ex}", fg='red') sys.exit(1) # Use the config file value if the value from the command line is the default if cli_params[config_name_int] == paramname_to_param[config_name_int].get_default(ctx): cli_params[config_name_int] = config_value
python
def apply_config_file( command_function: Union[click.Command, click.Group], cli_params: Dict[str, Any], ctx, config_file_option_name='config_file', ): paramname_to_param = {param.name: param for param in command_function.params} path_params = { param.name for param in command_function.params if isinstance(param.type, (click.Path, click.File)) } config_file_path = Path(cli_params[config_file_option_name]) config_file_values = dict() try: with config_file_path.open() as config_file: config_file_values = load(config_file) except OSError as ex: # Silently ignore if 'file not found' and the config file path is the default config_file_param = paramname_to_param[config_file_option_name] config_file_default_path = Path( config_file_param.type.expand_default(config_file_param.get_default(ctx), cli_params), ) default_config_missing = ( ex.errno == errno.ENOENT and config_file_path.resolve() == config_file_default_path.resolve() ) if default_config_missing: cli_params['config_file'] = None else: click.secho(f"Error opening config file: {ex}", fg='red') sys.exit(1) except TomlError as ex: click.secho(f'Error loading config file: {ex}', fg='red') sys.exit(1) for config_name, config_value in config_file_values.items(): config_name_int = config_name.replace('-', '_') if config_name_int not in paramname_to_param: click.secho( f"Unknown setting '{config_name}' found in config file - ignoring.", fg='yellow', ) continue if config_name_int in path_params: # Allow users to use `~` in paths in the config file config_value = os.path.expanduser(config_value) if config_name_int == LOG_CONFIG_OPTION_NAME: # Uppercase log level names config_value = {k: v.upper() for k, v in config_value.items()} else: # Pipe config file values through cli converter to ensure correct types # We exclude `log-config` because it already is a dict when loading from toml try: config_value = paramname_to_param[config_name_int].type.convert( config_value, paramname_to_param[config_name_int], ctx, ) except click.BadParameter as ex: click.secho(f"Invalid config file setting '{config_name}': {ex}", fg='red') sys.exit(1) # Use the config file value if the value from the command line is the default if cli_params[config_name_int] == paramname_to_param[config_name_int].get_default(ctx): cli_params[config_name_int] = config_value
[ "def", "apply_config_file", "(", "command_function", ":", "Union", "[", "click", ".", "Command", ",", "click", ".", "Group", "]", ",", "cli_params", ":", "Dict", "[", "str", ",", "Any", "]", ",", "ctx", ",", "config_file_option_name", "=", "'config_file'", ...
Applies all options set in the config file to `cli_params`
[ "Applies", "all", "options", "set", "in", "the", "config", "file", "to", "cli_params" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/cli.py#L354-L424
235,526
raiden-network/raiden
raiden/utils/cli.py
get_matrix_servers
def get_matrix_servers(url: str) -> List[str]: """Fetch a list of matrix servers from a text url '-' prefixes (YAML list) are cleaned. Comment lines /^\\s*#/ are ignored url: url of a text file returns: list of urls, default schema is https """ try: response = requests.get(url) if response.status_code != 200: raise requests.RequestException('Response: {response!r}') except requests.RequestException as ex: raise RuntimeError(f'Could not fetch matrix servers list: {url!r} => {ex!r}') from ex available_servers = [] for line in response.text.splitlines(): line = line.strip(string.whitespace + '-') if line.startswith('#') or not line: continue if not line.startswith('http'): line = 'https://' + line # default schema available_servers.append(line) return available_servers
python
def get_matrix_servers(url: str) -> List[str]: try: response = requests.get(url) if response.status_code != 200: raise requests.RequestException('Response: {response!r}') except requests.RequestException as ex: raise RuntimeError(f'Could not fetch matrix servers list: {url!r} => {ex!r}') from ex available_servers = [] for line in response.text.splitlines(): line = line.strip(string.whitespace + '-') if line.startswith('#') or not line: continue if not line.startswith('http'): line = 'https://' + line # default schema available_servers.append(line) return available_servers
[ "def", "get_matrix_servers", "(", "url", ":", "str", ")", "->", "List", "[", "str", "]", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ")", "if", "response", ".", "status_code", "!=", "200", ":", "raise", "requests", ".", "Req...
Fetch a list of matrix servers from a text url '-' prefixes (YAML list) are cleaned. Comment lines /^\\s*#/ are ignored url: url of a text file returns: list of urls, default schema is https
[ "Fetch", "a", "list", "of", "matrix", "servers", "from", "a", "text", "url" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/cli.py#L427-L450
235,527
raiden-network/raiden
raiden/raiden_service.py
_redact_secret
def _redact_secret( data: Union[Dict, List], ) -> Union[Dict, List]: """ Modify `data` in-place and replace keys named `secret`. """ if isinstance(data, dict): stack = [data] else: stack = [] while stack: current = stack.pop() if 'secret' in current: current['secret'] = '<redacted>' else: stack.extend( value for value in current.values() if isinstance(value, dict) ) return data
python
def _redact_secret( data: Union[Dict, List], ) -> Union[Dict, List]: if isinstance(data, dict): stack = [data] else: stack = [] while stack: current = stack.pop() if 'secret' in current: current['secret'] = '<redacted>' else: stack.extend( value for value in current.values() if isinstance(value, dict) ) return data
[ "def", "_redact_secret", "(", "data", ":", "Union", "[", "Dict", ",", "List", "]", ",", ")", "->", "Union", "[", "Dict", ",", "List", "]", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "stack", "=", "[", "data", "]", "else", ":", ...
Modify `data` in-place and replace keys named `secret`.
[ "Modify", "data", "in", "-", "place", "and", "replace", "keys", "named", "secret", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L98-L120
235,528
raiden-network/raiden
raiden/raiden_service.py
RaidenService.stop
def stop(self): """ Stop the node gracefully. Raise if any stop-time error occurred on any subtask """ if self.stop_event.ready(): # not started return # Needs to come before any greenlets joining self.stop_event.set() # Filters must be uninstalled after the alarm task has stopped. Since # the events are polled by an alarm task callback, if the filters are # uninstalled before the alarm task is fully stopped the callback # `poll_blockchain_events` will fail. # # We need a timeout to prevent an endless loop from trying to # contact the disconnected client self.transport.stop() self.alarm.stop() self.transport.join() self.alarm.join() self.blockchain_events.uninstall_all_event_listeners() # Close storage DB to release internal DB lock self.wal.storage.conn.close() if self.db_lock is not None: self.db_lock.release() log.debug('Raiden Service stopped', node=pex(self.address))
python
def stop(self): if self.stop_event.ready(): # not started return # Needs to come before any greenlets joining self.stop_event.set() # Filters must be uninstalled after the alarm task has stopped. Since # the events are polled by an alarm task callback, if the filters are # uninstalled before the alarm task is fully stopped the callback # `poll_blockchain_events` will fail. # # We need a timeout to prevent an endless loop from trying to # contact the disconnected client self.transport.stop() self.alarm.stop() self.transport.join() self.alarm.join() self.blockchain_events.uninstall_all_event_listeners() # Close storage DB to release internal DB lock self.wal.storage.conn.close() if self.db_lock is not None: self.db_lock.release() log.debug('Raiden Service stopped', node=pex(self.address))
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "stop_event", ".", "ready", "(", ")", ":", "# not started", "return", "# Needs to come before any greenlets joining", "self", ".", "stop_event", ".", "set", "(", ")", "# Filters must be uninstalled after the a...
Stop the node gracefully. Raise if any stop-time error occurred on any subtask
[ "Stop", "the", "node", "gracefully", ".", "Raise", "if", "any", "stop", "-", "time", "error", "occurred", "on", "any", "subtask" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L576-L605
235,529
raiden-network/raiden
raiden/raiden_service.py
RaidenService._start_transport
def _start_transport(self, chain_state: ChainState): """ Initialize the transport and related facilities. Note: The transport must not be started before the node has caught up with the blockchain through `AlarmTask.first_run()`. This synchronization includes the on-chain channel state and is necessary to reject new messages for closed channels. """ assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' assert self.ready_to_process_events, f'Event procossing disable. node:{self!r}' self.transport.start( raiden_service=self, message_handler=self.message_handler, prev_auth_data=chain_state.last_transport_authdata, ) for neighbour in views.all_neighbour_nodes(chain_state): if neighbour != ConnectionManager.BOOTSTRAP_ADDR: self.start_health_check_for(neighbour)
python
def _start_transport(self, chain_state: ChainState): assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' assert self.ready_to_process_events, f'Event procossing disable. node:{self!r}' self.transport.start( raiden_service=self, message_handler=self.message_handler, prev_auth_data=chain_state.last_transport_authdata, ) for neighbour in views.all_neighbour_nodes(chain_state): if neighbour != ConnectionManager.BOOTSTRAP_ADDR: self.start_health_check_for(neighbour)
[ "def", "_start_transport", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "assert", "self", ".", "alarm", ".", "is_primed", "(", ")", ",", "f'AlarmTask not primed. node:{self!r}'", "assert", "self", ".", "ready_to_process_events", ",", "f'Event procos...
Initialize the transport and related facilities. Note: The transport must not be started before the node has caught up with the blockchain through `AlarmTask.first_run()`. This synchronization includes the on-chain channel state and is necessary to reject new messages for closed channels.
[ "Initialize", "the", "transport", "and", "related", "facilities", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L628-L648
235,530
raiden-network/raiden
raiden/raiden_service.py
RaidenService.handle_and_track_state_change
def handle_and_track_state_change(self, state_change: StateChange): """ Dispatch the state change and does not handle the exceptions. When the method is used the exceptions are tracked and re-raised in the raiden service thread. """ for greenlet in self.handle_state_change(state_change): self.add_pending_greenlet(greenlet)
python
def handle_and_track_state_change(self, state_change: StateChange): for greenlet in self.handle_state_change(state_change): self.add_pending_greenlet(greenlet)
[ "def", "handle_and_track_state_change", "(", "self", ",", "state_change", ":", "StateChange", ")", ":", "for", "greenlet", "in", "self", ".", "handle_state_change", "(", "state_change", ")", ":", "self", ".", "add_pending_greenlet", "(", "greenlet", ")" ]
Dispatch the state change and does not handle the exceptions. When the method is used the exceptions are tracked and re-raised in the raiden service thread.
[ "Dispatch", "the", "state", "change", "and", "does", "not", "handle", "the", "exceptions", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L675-L682
235,531
raiden-network/raiden
raiden/raiden_service.py
RaidenService.handle_state_change
def handle_state_change(self, state_change: StateChange) -> List[Greenlet]: """ Dispatch the state change and return the processing threads. Use this for error reporting, failures in the returned greenlets, should be re-raised using `gevent.joinall` with `raise_error=True`. """ assert self.wal, f'WAL not restored. node:{self!r}' log.debug( 'State change', node=pex(self.address), state_change=_redact_secret(serialize.JSONSerializer.serialize(state_change)), ) old_state = views.state_from_raiden(self) raiden_event_list = self.wal.log_and_dispatch(state_change) current_state = views.state_from_raiden(self) for changed_balance_proof in views.detect_balance_proof_change(old_state, current_state): update_services_from_balance_proof(self, current_state, changed_balance_proof) log.debug( 'Raiden events', node=pex(self.address), raiden_events=[ _redact_secret(serialize.JSONSerializer.serialize(event)) for event in raiden_event_list ], ) greenlets: List[Greenlet] = list() if self.ready_to_process_events: for raiden_event in raiden_event_list: greenlets.append( self.handle_event(raiden_event=raiden_event), ) state_changes_count = self.wal.storage.count_state_changes() new_snapshot_group = ( state_changes_count // SNAPSHOT_STATE_CHANGES_COUNT ) if new_snapshot_group > self.snapshot_group: log.debug('Storing snapshot', snapshot_id=new_snapshot_group) self.wal.snapshot() self.snapshot_group = new_snapshot_group return greenlets
python
def handle_state_change(self, state_change: StateChange) -> List[Greenlet]: assert self.wal, f'WAL not restored. node:{self!r}' log.debug( 'State change', node=pex(self.address), state_change=_redact_secret(serialize.JSONSerializer.serialize(state_change)), ) old_state = views.state_from_raiden(self) raiden_event_list = self.wal.log_and_dispatch(state_change) current_state = views.state_from_raiden(self) for changed_balance_proof in views.detect_balance_proof_change(old_state, current_state): update_services_from_balance_proof(self, current_state, changed_balance_proof) log.debug( 'Raiden events', node=pex(self.address), raiden_events=[ _redact_secret(serialize.JSONSerializer.serialize(event)) for event in raiden_event_list ], ) greenlets: List[Greenlet] = list() if self.ready_to_process_events: for raiden_event in raiden_event_list: greenlets.append( self.handle_event(raiden_event=raiden_event), ) state_changes_count = self.wal.storage.count_state_changes() new_snapshot_group = ( state_changes_count // SNAPSHOT_STATE_CHANGES_COUNT ) if new_snapshot_group > self.snapshot_group: log.debug('Storing snapshot', snapshot_id=new_snapshot_group) self.wal.snapshot() self.snapshot_group = new_snapshot_group return greenlets
[ "def", "handle_state_change", "(", "self", ",", "state_change", ":", "StateChange", ")", "->", "List", "[", "Greenlet", "]", ":", "assert", "self", ".", "wal", ",", "f'WAL not restored. node:{self!r}'", "log", ".", "debug", "(", "'State change'", ",", "node", ...
Dispatch the state change and return the processing threads. Use this for error reporting, failures in the returned greenlets, should be re-raised using `gevent.joinall` with `raise_error=True`.
[ "Dispatch", "the", "state", "change", "and", "return", "the", "processing", "threads", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L684-L730
235,532
raiden-network/raiden
raiden/raiden_service.py
RaidenService.handle_event
def handle_event(self, raiden_event: RaidenEvent) -> Greenlet: """Spawn a new thread to handle a Raiden event. This will spawn a new greenlet to handle each event, which is important for two reasons: - Blockchain transactions can be queued without interfering with each other. - The calling thread is free to do more work. This is specially important for the AlarmTask thread, which will eventually cause the node to send transactions when a given Block is reached (e.g. registering a secret or settling a channel). Important: This is spawing a new greenlet for /each/ transaction. It's therefore /required/ that there is *NO* order among these. """ return gevent.spawn(self._handle_event, raiden_event)
python
def handle_event(self, raiden_event: RaidenEvent) -> Greenlet: return gevent.spawn(self._handle_event, raiden_event)
[ "def", "handle_event", "(", "self", ",", "raiden_event", ":", "RaidenEvent", ")", "->", "Greenlet", ":", "return", "gevent", ".", "spawn", "(", "self", ".", "_handle_event", ",", "raiden_event", ")" ]
Spawn a new thread to handle a Raiden event. This will spawn a new greenlet to handle each event, which is important for two reasons: - Blockchain transactions can be queued without interfering with each other. - The calling thread is free to do more work. This is specially important for the AlarmTask thread, which will eventually cause the node to send transactions when a given Block is reached (e.g. registering a secret or settling a channel). Important: This is spawing a new greenlet for /each/ transaction. It's therefore /required/ that there is *NO* order among these.
[ "Spawn", "a", "new", "thread", "to", "handle", "a", "Raiden", "event", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L732-L750
235,533
raiden-network/raiden
raiden/raiden_service.py
RaidenService.start_health_check_for
def start_health_check_for(self, node_address: Address): """Start health checking `node_address`. This function is a noop during initialization, because health checking can be started as a side effect of some events (e.g. new channel). For these cases the healthcheck will be started by `start_neighbours_healthcheck`. """ if self.transport: self.transport.start_health_check(node_address)
python
def start_health_check_for(self, node_address: Address): if self.transport: self.transport.start_health_check(node_address)
[ "def", "start_health_check_for", "(", "self", ",", "node_address", ":", "Address", ")", ":", "if", "self", ".", "transport", ":", "self", ".", "transport", ".", "start_health_check", "(", "node_address", ")" ]
Start health checking `node_address`. This function is a noop during initialization, because health checking can be started as a side effect of some events (e.g. new channel). For these cases the healthcheck will be started by `start_neighbours_healthcheck`.
[ "Start", "health", "checking", "node_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L777-L786
235,534
raiden-network/raiden
raiden/raiden_service.py
RaidenService._callback_new_block
def _callback_new_block(self, latest_block: Dict): """Called once a new block is detected by the alarm task. Note: This should be called only once per block, otherwise there will be duplicated `Block` state changes in the log. Therefore this method should be called only once a new block is mined with the corresponding block data from the AlarmTask. """ # User facing APIs, which have on-chain side-effects, force polled the # blockchain to update the node's state. This force poll is used to # provide a consistent view to the user, e.g. a channel open call waits # for the transaction to be mined and force polled the event to update # the node's state. This pattern introduced a race with the alarm task # and the task which served the user request, because the events are # returned only once per filter. The lock below is to protect against # these races (introduced by the commit # 3686b3275ff7c0b669a6d5e2b34109c3bdf1921d) with self.event_poll_lock: latest_block_number = latest_block['number'] # Handle testing with private chains. The block number can be # smaller than confirmation_blocks confirmed_block_number = max( GENESIS_BLOCK_NUMBER, latest_block_number - self.config['blockchain']['confirmation_blocks'], ) confirmed_block = self.chain.client.web3.eth.getBlock(confirmed_block_number) # These state changes will be procesed with a block_number which is # /larger/ than the ChainState's block_number. for event in self.blockchain_events.poll_blockchain_events(confirmed_block_number): on_blockchain_event(self, event) # On restart the Raiden node will re-create the filters with the # ethereum node. These filters will have the from_block set to the # value of the latest Block state change. To avoid missing events # the Block state change is dispatched only after all of the events # have been processed. # # This means on some corner cases a few events may be applied # twice, this will happen if the node crashed and some events have # been processed but the Block state change has not been # dispatched. state_change = Block( block_number=confirmed_block_number, gas_limit=confirmed_block['gasLimit'], block_hash=BlockHash(bytes(confirmed_block['hash'])), ) # Note: It's important to /not/ block here, because this function # can be called from the alarm task greenlet, which should not # starve. self.handle_and_track_state_change(state_change)
python
def _callback_new_block(self, latest_block: Dict): # User facing APIs, which have on-chain side-effects, force polled the # blockchain to update the node's state. This force poll is used to # provide a consistent view to the user, e.g. a channel open call waits # for the transaction to be mined and force polled the event to update # the node's state. This pattern introduced a race with the alarm task # and the task which served the user request, because the events are # returned only once per filter. The lock below is to protect against # these races (introduced by the commit # 3686b3275ff7c0b669a6d5e2b34109c3bdf1921d) with self.event_poll_lock: latest_block_number = latest_block['number'] # Handle testing with private chains. The block number can be # smaller than confirmation_blocks confirmed_block_number = max( GENESIS_BLOCK_NUMBER, latest_block_number - self.config['blockchain']['confirmation_blocks'], ) confirmed_block = self.chain.client.web3.eth.getBlock(confirmed_block_number) # These state changes will be procesed with a block_number which is # /larger/ than the ChainState's block_number. for event in self.blockchain_events.poll_blockchain_events(confirmed_block_number): on_blockchain_event(self, event) # On restart the Raiden node will re-create the filters with the # ethereum node. These filters will have the from_block set to the # value of the latest Block state change. To avoid missing events # the Block state change is dispatched only after all of the events # have been processed. # # This means on some corner cases a few events may be applied # twice, this will happen if the node crashed and some events have # been processed but the Block state change has not been # dispatched. state_change = Block( block_number=confirmed_block_number, gas_limit=confirmed_block['gasLimit'], block_hash=BlockHash(bytes(confirmed_block['hash'])), ) # Note: It's important to /not/ block here, because this function # can be called from the alarm task greenlet, which should not # starve. self.handle_and_track_state_change(state_change)
[ "def", "_callback_new_block", "(", "self", ",", "latest_block", ":", "Dict", ")", ":", "# User facing APIs, which have on-chain side-effects, force polled the", "# blockchain to update the node's state. This force poll is used to", "# provide a consistent view to the user, e.g. a channel ope...
Called once a new block is detected by the alarm task. Note: This should be called only once per block, otherwise there will be duplicated `Block` state changes in the log. Therefore this method should be called only once a new block is mined with the corresponding block data from the AlarmTask.
[ "Called", "once", "a", "new", "block", "is", "detected", "by", "the", "alarm", "task", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L788-L842
235,535
raiden-network/raiden
raiden/raiden_service.py
RaidenService._initialize_transactions_queues
def _initialize_transactions_queues(self, chain_state: ChainState): """Initialize the pending transaction queue from the previous run. Note: This will only send the transactions which don't have their side-effects applied. Transactions which another node may have sent already will be detected by the alarm task's first run and cleared from the queue (e.g. A monitoring service update transfer). """ assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' pending_transactions = views.get_pending_transactions(chain_state) log.debug( 'Processing pending transactions', num_pending_transactions=len(pending_transactions), node=pex(self.address), ) for transaction in pending_transactions: try: self.raiden_event_handler.on_raiden_event(self, transaction) except RaidenRecoverableError as e: log.error(str(e)) except InvalidDBData: raise except RaidenUnrecoverableError as e: log_unrecoverable = ( self.config['environment_type'] == Environment.PRODUCTION and not self.config['unrecoverable_error_should_crash'] ) if log_unrecoverable: log.error(str(e)) else: raise
python
def _initialize_transactions_queues(self, chain_state: ChainState): assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' pending_transactions = views.get_pending_transactions(chain_state) log.debug( 'Processing pending transactions', num_pending_transactions=len(pending_transactions), node=pex(self.address), ) for transaction in pending_transactions: try: self.raiden_event_handler.on_raiden_event(self, transaction) except RaidenRecoverableError as e: log.error(str(e)) except InvalidDBData: raise except RaidenUnrecoverableError as e: log_unrecoverable = ( self.config['environment_type'] == Environment.PRODUCTION and not self.config['unrecoverable_error_should_crash'] ) if log_unrecoverable: log.error(str(e)) else: raise
[ "def", "_initialize_transactions_queues", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "assert", "self", ".", "alarm", ".", "is_primed", "(", ")", ",", "f'AlarmTask not primed. node:{self!r}'", "pending_transactions", "=", "views", ".", "get_pending_t...
Initialize the pending transaction queue from the previous run. Note: This will only send the transactions which don't have their side-effects applied. Transactions which another node may have sent already will be detected by the alarm task's first run and cleared from the queue (e.g. A monitoring service update transfer).
[ "Initialize", "the", "pending", "transaction", "queue", "from", "the", "previous", "run", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L844-L878
235,536
raiden-network/raiden
raiden/raiden_service.py
RaidenService._initialize_payment_statuses
def _initialize_payment_statuses(self, chain_state: ChainState): """ Re-initialize targets_to_identifiers_to_statuses. Restore the PaymentStatus for any pending payment. This is not tied to a specific protocol message but to the lifecycle of a payment, i.e. the status is re-created if a payment itself has not completed. """ with self.payment_identifier_lock: for task in chain_state.payment_mapping.secrethashes_to_task.values(): if not isinstance(task, InitiatorTask): continue # Every transfer in the transfers_list must have the same target # and payment_identifier, so using the first transfer is # sufficient. initiator = next(iter(task.manager_state.initiator_transfers.values())) transfer = initiator.transfer transfer_description = initiator.transfer_description target = transfer.target identifier = transfer.payment_identifier balance_proof = transfer.balance_proof self.targets_to_identifiers_to_statuses[target][identifier] = PaymentStatus( payment_identifier=identifier, amount=transfer_description.amount, token_network_identifier=TokenNetworkID( balance_proof.token_network_identifier, ), payment_done=AsyncResult(), )
python
def _initialize_payment_statuses(self, chain_state: ChainState): with self.payment_identifier_lock: for task in chain_state.payment_mapping.secrethashes_to_task.values(): if not isinstance(task, InitiatorTask): continue # Every transfer in the transfers_list must have the same target # and payment_identifier, so using the first transfer is # sufficient. initiator = next(iter(task.manager_state.initiator_transfers.values())) transfer = initiator.transfer transfer_description = initiator.transfer_description target = transfer.target identifier = transfer.payment_identifier balance_proof = transfer.balance_proof self.targets_to_identifiers_to_statuses[target][identifier] = PaymentStatus( payment_identifier=identifier, amount=transfer_description.amount, token_network_identifier=TokenNetworkID( balance_proof.token_network_identifier, ), payment_done=AsyncResult(), )
[ "def", "_initialize_payment_statuses", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "with", "self", ".", "payment_identifier_lock", ":", "for", "task", "in", "chain_state", ".", "payment_mapping", ".", "secrethashes_to_task", ".", "values", "(", "...
Re-initialize targets_to_identifiers_to_statuses. Restore the PaymentStatus for any pending payment. This is not tied to a specific protocol message but to the lifecycle of a payment, i.e. the status is re-created if a payment itself has not completed.
[ "Re", "-", "initialize", "targets_to_identifiers_to_statuses", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L880-L909
235,537
raiden-network/raiden
raiden/raiden_service.py
RaidenService._initialize_messages_queues
def _initialize_messages_queues(self, chain_state: ChainState): """Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transport processes network messages too quickly, queueing new messages before any of the previous messages, resulting in new messages being out-of-order. The Alarm task must be started before this method is called, otherwise queues for channel closed while the node was offline won't be properly cleared. It is not bad but it is suboptimal. """ assert not self.transport, f'Transport is running. node:{self!r}' assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' events_queues = views.get_all_messagequeues(chain_state) for queue_identifier, event_queue in events_queues.items(): self.start_health_check_for(queue_identifier.recipient) for event in event_queue: message = message_from_sendevent(event) self.sign(message) self.transport.send_async(queue_identifier, message)
python
def _initialize_messages_queues(self, chain_state: ChainState): assert not self.transport, f'Transport is running. node:{self!r}' assert self.alarm.is_primed(), f'AlarmTask not primed. node:{self!r}' events_queues = views.get_all_messagequeues(chain_state) for queue_identifier, event_queue in events_queues.items(): self.start_health_check_for(queue_identifier.recipient) for event in event_queue: message = message_from_sendevent(event) self.sign(message) self.transport.send_async(queue_identifier, message)
[ "def", "_initialize_messages_queues", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "assert", "not", "self", ".", "transport", ",", "f'Transport is running. node:{self!r}'", "assert", "self", ".", "alarm", ".", "is_primed", "(", ")", ",", "f'AlarmT...
Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transport processes network messages too quickly, queueing new messages before any of the previous messages, resulting in new messages being out-of-order. The Alarm task must be started before this method is called, otherwise queues for channel closed while the node was offline won't be properly cleared. It is not bad but it is suboptimal.
[ "Initialize", "all", "the", "message", "queues", "with", "the", "transport", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L911-L936
235,538
raiden-network/raiden
raiden/raiden_service.py
RaidenService._initialize_monitoring_services_queue
def _initialize_monitoring_services_queue(self, chain_state: ChainState): """Send the monitoring requests for all current balance proofs. Note: The node must always send the *received* balance proof to the monitoring service, *before* sending its own locked transfer forward. If the monitoring service is updated after, then the following can happen: For a transfer A-B-C where this node is B - B receives T1 from A and processes it - B forwards its T2 to C * B crashes (the monitoring service is not updated) For the above scenario, the monitoring service would not have the latest balance proof received by B from A available with the lock for T1, but C would. If the channel B-C is closed and B does not come back online in time, the funds for the lock L1 can be lost. During restarts the rationale from above has to be replicated. Because the initialization code *is not* the same as the event handler. This means the balance proof updates must be done prior to the processing of the message queues. """ msg = ( 'Transport was started before the monitoring service queue was updated. ' 'This can lead to safety issue. node:{self!r}' ) assert not self.transport, msg msg = ( 'The node state was not yet recovered, cant read balance proofs. node:{self!r}' ) assert self.wal, msg current_balance_proofs = views.detect_balance_proof_change( old_state=ChainState( pseudo_random_generator=chain_state.pseudo_random_generator, block_number=GENESIS_BLOCK_NUMBER, block_hash=constants.EMPTY_HASH, our_address=chain_state.our_address, chain_id=chain_state.chain_id, ), current_state=chain_state, ) for balance_proof in current_balance_proofs: update_services_from_balance_proof(self, chain_state, balance_proof)
python
def _initialize_monitoring_services_queue(self, chain_state: ChainState): msg = ( 'Transport was started before the monitoring service queue was updated. ' 'This can lead to safety issue. node:{self!r}' ) assert not self.transport, msg msg = ( 'The node state was not yet recovered, cant read balance proofs. node:{self!r}' ) assert self.wal, msg current_balance_proofs = views.detect_balance_proof_change( old_state=ChainState( pseudo_random_generator=chain_state.pseudo_random_generator, block_number=GENESIS_BLOCK_NUMBER, block_hash=constants.EMPTY_HASH, our_address=chain_state.our_address, chain_id=chain_state.chain_id, ), current_state=chain_state, ) for balance_proof in current_balance_proofs: update_services_from_balance_proof(self, chain_state, balance_proof)
[ "def", "_initialize_monitoring_services_queue", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "msg", "=", "(", "'Transport was started before the monitoring service queue was updated. '", "'This can lead to safety issue. node:{self!r}'", ")", "assert", "not", "sel...
Send the monitoring requests for all current balance proofs. Note: The node must always send the *received* balance proof to the monitoring service, *before* sending its own locked transfer forward. If the monitoring service is updated after, then the following can happen: For a transfer A-B-C where this node is B - B receives T1 from A and processes it - B forwards its T2 to C * B crashes (the monitoring service is not updated) For the above scenario, the monitoring service would not have the latest balance proof received by B from A available with the lock for T1, but C would. If the channel B-C is closed and B does not come back online in time, the funds for the lock L1 can be lost. During restarts the rationale from above has to be replicated. Because the initialization code *is not* the same as the event handler. This means the balance proof updates must be done prior to the processing of the message queues.
[ "Send", "the", "monitoring", "requests", "for", "all", "current", "balance", "proofs", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L938-L985
235,539
raiden-network/raiden
raiden/raiden_service.py
RaidenService._initialize_whitelists
def _initialize_whitelists(self, chain_state: ChainState): """ Whitelist neighbors and mediated transfer targets on transport """ for neighbour in views.all_neighbour_nodes(chain_state): if neighbour == ConnectionManager.BOOTSTRAP_ADDR: continue self.transport.whitelist(neighbour) events_queues = views.get_all_messagequeues(chain_state) for event_queue in events_queues.values(): for event in event_queue: if isinstance(event, SendLockedTransfer): transfer = event.transfer if transfer.initiator == self.address: self.transport.whitelist(address=transfer.target)
python
def _initialize_whitelists(self, chain_state: ChainState): for neighbour in views.all_neighbour_nodes(chain_state): if neighbour == ConnectionManager.BOOTSTRAP_ADDR: continue self.transport.whitelist(neighbour) events_queues = views.get_all_messagequeues(chain_state) for event_queue in events_queues.values(): for event in event_queue: if isinstance(event, SendLockedTransfer): transfer = event.transfer if transfer.initiator == self.address: self.transport.whitelist(address=transfer.target)
[ "def", "_initialize_whitelists", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "for", "neighbour", "in", "views", ".", "all_neighbour_nodes", "(", "chain_state", ")", ":", "if", "neighbour", "==", "ConnectionManager", ".", "BOOTSTRAP_ADDR", ":", ...
Whitelist neighbors and mediated transfer targets on transport
[ "Whitelist", "neighbors", "and", "mediated", "transfer", "targets", "on", "transport" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L987-L1002
235,540
raiden-network/raiden
raiden/raiden_service.py
RaidenService.sign
def sign(self, message: Message): """ Sign message inplace. """ if not isinstance(message, SignedMessage): raise ValueError('{} is not signable.'.format(repr(message))) message.sign(self.signer)
python
def sign(self, message: Message): if not isinstance(message, SignedMessage): raise ValueError('{} is not signable.'.format(repr(message))) message.sign(self.signer)
[ "def", "sign", "(", "self", ",", "message", ":", "Message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "SignedMessage", ")", ":", "raise", "ValueError", "(", "'{} is not signable.'", ".", "format", "(", "repr", "(", "message", ")", ")", ")...
Sign message inplace.
[ "Sign", "message", "inplace", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L1004-L1009
235,541
raiden-network/raiden
raiden/raiden_service.py
RaidenService.mediated_transfer_async
def mediated_transfer_async( self, token_network_identifier: TokenNetworkID, amount: PaymentAmount, target: TargetAddress, identifier: PaymentID, fee: FeeAmount = MEDIATION_FEE, secret: Secret = None, secret_hash: SecretHash = None, ) -> PaymentStatus: """ Transfer `amount` between this node and `target`. This method will start an asynchronous transfer, the transfer might fail or succeed depending on a couple of factors: - Existence of a path that can be used, through the usage of direct or intermediary channels. - Network speed, making the transfer sufficiently fast so it doesn't expire. """ if secret is None: if secret_hash is None: secret = random_secret() else: secret = EMPTY_SECRET payment_status = self.start_mediated_transfer_with_secret( token_network_identifier=token_network_identifier, amount=amount, fee=fee, target=target, identifier=identifier, secret=secret, secret_hash=secret_hash, ) return payment_status
python
def mediated_transfer_async( self, token_network_identifier: TokenNetworkID, amount: PaymentAmount, target: TargetAddress, identifier: PaymentID, fee: FeeAmount = MEDIATION_FEE, secret: Secret = None, secret_hash: SecretHash = None, ) -> PaymentStatus: if secret is None: if secret_hash is None: secret = random_secret() else: secret = EMPTY_SECRET payment_status = self.start_mediated_transfer_with_secret( token_network_identifier=token_network_identifier, amount=amount, fee=fee, target=target, identifier=identifier, secret=secret, secret_hash=secret_hash, ) return payment_status
[ "def", "mediated_transfer_async", "(", "self", ",", "token_network_identifier", ":", "TokenNetworkID", ",", "amount", ":", "PaymentAmount", ",", "target", ":", "TargetAddress", ",", "identifier", ":", "PaymentID", ",", "fee", ":", "FeeAmount", "=", "MEDIATION_FEE", ...
Transfer `amount` between this node and `target`. This method will start an asynchronous transfer, the transfer might fail or succeed depending on a couple of factors: - Existence of a path that can be used, through the usage of direct or intermediary channels. - Network speed, making the transfer sufficiently fast so it doesn't expire.
[ "Transfer", "amount", "between", "this", "node", "and", "target", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L1068-L1104
235,542
raiden-network/raiden
raiden/storage/serialize.py
from_dict_hook
def from_dict_hook(data): """Decode internal objects encoded using `to_dict_hook`. This automatically imports the class defined in the `_type` metadata field, and calls the `from_dict` method hook to instantiate an object of that class. Note: Because this function will do automatic module loading it's really important to only use this with sanitized or trusted input, otherwise arbitrary modules can be imported and potentially arbitrary code can be executed. """ type_ = data.get('_type', None) if type_ is not None: klass = _import_type(type_) msg = '_type must point to a class with `from_dict` static method' assert hasattr(klass, 'from_dict'), msg return klass.from_dict(data) return data
python
def from_dict_hook(data): type_ = data.get('_type', None) if type_ is not None: klass = _import_type(type_) msg = '_type must point to a class with `from_dict` static method' assert hasattr(klass, 'from_dict'), msg return klass.from_dict(data) return data
[ "def", "from_dict_hook", "(", "data", ")", ":", "type_", "=", "data", ".", "get", "(", "'_type'", ",", "None", ")", "if", "type_", "is", "not", "None", ":", "klass", "=", "_import_type", "(", "type_", ")", "msg", "=", "'_type must point to a class with `fr...
Decode internal objects encoded using `to_dict_hook`. This automatically imports the class defined in the `_type` metadata field, and calls the `from_dict` method hook to instantiate an object of that class. Note: Because this function will do automatic module loading it's really important to only use this with sanitized or trusted input, otherwise arbitrary modules can be imported and potentially arbitrary code can be executed.
[ "Decode", "internal", "objects", "encoded", "using", "to_dict_hook", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/serialize.py#L27-L48
235,543
raiden-network/raiden
raiden/storage/serialize.py
to_dict_hook
def to_dict_hook(obj): """Convert internal objects to a serializable representation. During serialization if the object has the hook method `to_dict` it will be automatically called and metadata for decoding will be added. This allows for the translation of objects trees of arbitrary depth. E.g.: >>> class Root: >>> def __init__(self, left, right): >>> self.left = left >>> self.right = right >>> def to_dict(self): >>> return { >>> 'left': left, >>> 'right': right, >>> } >>> class Node: >>> def to_dict(self): >>> return {'value': 'node'} >>> root = Root(left=None(), right=None()) >>> json.dumps(root, default=to_dict_hook) '{ "_type": "Root", "left": {"_type": "Node", "value": "node"}, "right": {"_type": "Node", "value": "node"} }' """ if hasattr(obj, 'to_dict'): result = obj.to_dict() assert isinstance(result, dict), 'to_dict must return a dictionary' result['_type'] = f'{obj.__module__}.{obj.__class__.__name__}' result['_version'] = 0 return result raise TypeError( f'Object of type {obj.__class__.__name__} is not JSON serializable', )
python
def to_dict_hook(obj): if hasattr(obj, 'to_dict'): result = obj.to_dict() assert isinstance(result, dict), 'to_dict must return a dictionary' result['_type'] = f'{obj.__module__}.{obj.__class__.__name__}' result['_version'] = 0 return result raise TypeError( f'Object of type {obj.__class__.__name__} is not JSON serializable', )
[ "def", "to_dict_hook", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'to_dict'", ")", ":", "result", "=", "obj", ".", "to_dict", "(", ")", "assert", "isinstance", "(", "result", ",", "dict", ")", ",", "'to_dict must return a dictionary'", "resul...
Convert internal objects to a serializable representation. During serialization if the object has the hook method `to_dict` it will be automatically called and metadata for decoding will be added. This allows for the translation of objects trees of arbitrary depth. E.g.: >>> class Root: >>> def __init__(self, left, right): >>> self.left = left >>> self.right = right >>> def to_dict(self): >>> return { >>> 'left': left, >>> 'right': right, >>> } >>> class Node: >>> def to_dict(self): >>> return {'value': 'node'} >>> root = Root(left=None(), right=None()) >>> json.dumps(root, default=to_dict_hook) '{ "_type": "Root", "left": {"_type": "Node", "value": "node"}, "right": {"_type": "Node", "value": "node"} }'
[ "Convert", "internal", "objects", "to", "a", "serializable", "representation", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/serialize.py#L51-L87
235,544
raiden-network/raiden
tools/debugging/json-log-to-html.py
rgb_color_picker
def rgb_color_picker(obj, min_luminance=None, max_luminance=None): """Modified version of colour.RGB_color_picker""" color_value = int.from_bytes( hashlib.md5(str(obj).encode('utf-8')).digest(), 'little', ) % 0xffffff color = Color(f'#{color_value:06x}') if min_luminance and color.get_luminance() < min_luminance: color.set_luminance(min_luminance) elif max_luminance and color.get_luminance() > max_luminance: color.set_luminance(max_luminance) return color
python
def rgb_color_picker(obj, min_luminance=None, max_luminance=None): color_value = int.from_bytes( hashlib.md5(str(obj).encode('utf-8')).digest(), 'little', ) % 0xffffff color = Color(f'#{color_value:06x}') if min_luminance and color.get_luminance() < min_luminance: color.set_luminance(min_luminance) elif max_luminance and color.get_luminance() > max_luminance: color.set_luminance(max_luminance) return color
[ "def", "rgb_color_picker", "(", "obj", ",", "min_luminance", "=", "None", ",", "max_luminance", "=", "None", ")", ":", "color_value", "=", "int", ".", "from_bytes", "(", "hashlib", ".", "md5", "(", "str", "(", "obj", ")", ".", "encode", "(", "'utf-8'", ...
Modified version of colour.RGB_color_picker
[ "Modified", "version", "of", "colour", ".", "RGB_color_picker" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/debugging/json-log-to-html.py#L100-L111
235,545
raiden-network/raiden
raiden/utils/__init__.py
random_secret
def random_secret() -> Secret: """ Return a random 32 byte secret except the 0 secret since it's not accepted in the contracts """ while True: secret = os.urandom(32) if secret != constants.EMPTY_HASH: return Secret(secret)
python
def random_secret() -> Secret: while True: secret = os.urandom(32) if secret != constants.EMPTY_HASH: return Secret(secret)
[ "def", "random_secret", "(", ")", "->", "Secret", ":", "while", "True", ":", "secret", "=", "os", ".", "urandom", "(", "32", ")", "if", "secret", "!=", "constants", ".", "EMPTY_HASH", ":", "return", "Secret", "(", "secret", ")" ]
Return a random 32 byte secret except the 0 secret since it's not accepted in the contracts
[ "Return", "a", "random", "32", "byte", "secret", "except", "the", "0", "secret", "since", "it", "s", "not", "accepted", "in", "the", "contracts" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/__init__.py#L46-L52
235,546
raiden-network/raiden
raiden/utils/__init__.py
address_checksum_and_decode
def address_checksum_and_decode(addr: str) -> Address: """ Accepts a string address and turns it into binary. Makes sure that the string address provided starts is 0x prefixed and checksummed according to EIP55 specification """ if not is_0x_prefixed(addr): raise InvalidAddress('Address must be 0x prefixed') if not is_checksum_address(addr): raise InvalidAddress('Address must be EIP55 checksummed') addr_bytes = decode_hex(addr) assert len(addr_bytes) in (20, 0) return Address(addr_bytes)
python
def address_checksum_and_decode(addr: str) -> Address: if not is_0x_prefixed(addr): raise InvalidAddress('Address must be 0x prefixed') if not is_checksum_address(addr): raise InvalidAddress('Address must be EIP55 checksummed') addr_bytes = decode_hex(addr) assert len(addr_bytes) in (20, 0) return Address(addr_bytes)
[ "def", "address_checksum_and_decode", "(", "addr", ":", "str", ")", "->", "Address", ":", "if", "not", "is_0x_prefixed", "(", "addr", ")", ":", "raise", "InvalidAddress", "(", "'Address must be 0x prefixed'", ")", "if", "not", "is_checksum_address", "(", "addr", ...
Accepts a string address and turns it into binary. Makes sure that the string address provided starts is 0x prefixed and checksummed according to EIP55 specification
[ "Accepts", "a", "string", "address", "and", "turns", "it", "into", "binary", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/__init__.py#L63-L77
235,547
raiden-network/raiden
raiden/utils/__init__.py
privatekey_to_publickey
def privatekey_to_publickey(private_key_bin: bytes) -> bytes: """ Returns public key in bitcoins 'bin' encoding. """ if not ishash(private_key_bin): raise ValueError('private_key_bin format mismatch. maybe hex encoded?') return keys.PrivateKey(private_key_bin).public_key.to_bytes()
python
def privatekey_to_publickey(private_key_bin: bytes) -> bytes: if not ishash(private_key_bin): raise ValueError('private_key_bin format mismatch. maybe hex encoded?') return keys.PrivateKey(private_key_bin).public_key.to_bytes()
[ "def", "privatekey_to_publickey", "(", "private_key_bin", ":", "bytes", ")", "->", "bytes", ":", "if", "not", "ishash", "(", "private_key_bin", ")", ":", "raise", "ValueError", "(", "'private_key_bin format mismatch. maybe hex encoded?'", ")", "return", "keys", ".", ...
Returns public key in bitcoins 'bin' encoding.
[ "Returns", "public", "key", "in", "bitcoins", "bin", "encoding", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/__init__.py#L120-L124
235,548
raiden-network/raiden
raiden/utils/__init__.py
get_system_spec
def get_system_spec() -> Dict[str, str]: """Collect information about the system and installation. """ import pkg_resources import platform if sys.platform == 'darwin': system_info = 'macOS {} {}'.format( platform.mac_ver()[0], platform.architecture()[0], ) else: system_info = '{} {} {}'.format( platform.system(), '_'.join(part for part in platform.architecture() if part), platform.release(), ) try: version = pkg_resources.require(raiden.__name__)[0].version except (pkg_resources.VersionConflict, pkg_resources.DistributionNotFound): raise RuntimeError( 'Cannot detect Raiden version. Did you do python setup.py? ' 'Refer to https://raiden-network.readthedocs.io/en/latest/' 'overview_and_guide.html#for-developers', ) system_spec = { 'raiden': version, 'python_implementation': platform.python_implementation(), 'python_version': platform.python_version(), 'system': system_info, 'architecture': platform.machine(), 'distribution': 'bundled' if getattr(sys, 'frozen', False) else 'source', } return system_spec
python
def get_system_spec() -> Dict[str, str]: import pkg_resources import platform if sys.platform == 'darwin': system_info = 'macOS {} {}'.format( platform.mac_ver()[0], platform.architecture()[0], ) else: system_info = '{} {} {}'.format( platform.system(), '_'.join(part for part in platform.architecture() if part), platform.release(), ) try: version = pkg_resources.require(raiden.__name__)[0].version except (pkg_resources.VersionConflict, pkg_resources.DistributionNotFound): raise RuntimeError( 'Cannot detect Raiden version. Did you do python setup.py? ' 'Refer to https://raiden-network.readthedocs.io/en/latest/' 'overview_and_guide.html#for-developers', ) system_spec = { 'raiden': version, 'python_implementation': platform.python_implementation(), 'python_version': platform.python_version(), 'system': system_info, 'architecture': platform.machine(), 'distribution': 'bundled' if getattr(sys, 'frozen', False) else 'source', } return system_spec
[ "def", "get_system_spec", "(", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "import", "pkg_resources", "import", "platform", "if", "sys", ".", "platform", "==", "'darwin'", ":", "system_info", "=", "'macOS {} {}'", ".", "format", "(", "platform", "...
Collect information about the system and installation.
[ "Collect", "information", "about", "the", "system", "and", "installation", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/__init__.py#L143-L178
235,549
raiden-network/raiden
raiden/utils/__init__.py
safe_gas_limit
def safe_gas_limit(*estimates: int) -> int: """ Calculates a safe gas limit for a number of gas estimates including a security margin """ assert None not in estimates, 'if estimateGas returned None it should not reach here' calculated_limit = max(estimates) return int(calculated_limit * constants.GAS_FACTOR)
python
def safe_gas_limit(*estimates: int) -> int: assert None not in estimates, 'if estimateGas returned None it should not reach here' calculated_limit = max(estimates) return int(calculated_limit * constants.GAS_FACTOR)
[ "def", "safe_gas_limit", "(", "*", "estimates", ":", "int", ")", "->", "int", ":", "assert", "None", "not", "in", "estimates", ",", "'if estimateGas returned None it should not reach here'", "calculated_limit", "=", "max", "(", "estimates", ")", "return", "int", "...
Calculates a safe gas limit for a number of gas estimates including a security margin
[ "Calculates", "a", "safe", "gas", "limit", "for", "a", "number", "of", "gas", "estimates", "including", "a", "security", "margin" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/__init__.py#L253-L259
235,550
raiden-network/raiden
raiden/utils/__init__.py
block_specification_to_number
def block_specification_to_number(block: BlockSpecification, web3: Web3) -> BlockNumber: """ Converts a block specification to an actual block number """ if isinstance(block, str): msg = f"string block specification can't contain {block}" assert block in ('latest', 'pending'), msg number = web3.eth.getBlock(block)['number'] elif isinstance(block, T_BlockHash): number = web3.eth.getBlock(block)['number'] elif isinstance(block, T_BlockNumber): number = block else: if __debug__: raise AssertionError(f'Unknown type {type(block)} given for block specification') return BlockNumber(number)
python
def block_specification_to_number(block: BlockSpecification, web3: Web3) -> BlockNumber: if isinstance(block, str): msg = f"string block specification can't contain {block}" assert block in ('latest', 'pending'), msg number = web3.eth.getBlock(block)['number'] elif isinstance(block, T_BlockHash): number = web3.eth.getBlock(block)['number'] elif isinstance(block, T_BlockNumber): number = block else: if __debug__: raise AssertionError(f'Unknown type {type(block)} given for block specification') return BlockNumber(number)
[ "def", "block_specification_to_number", "(", "block", ":", "BlockSpecification", ",", "web3", ":", "Web3", ")", "->", "BlockNumber", ":", "if", "isinstance", "(", "block", ",", "str", ")", ":", "msg", "=", "f\"string block specification can't contain {block}\"", "as...
Converts a block specification to an actual block number
[ "Converts", "a", "block", "specification", "to", "an", "actual", "block", "number" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/__init__.py#L267-L281
235,551
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.detail
def detail(self, block_identifier: BlockSpecification) -> ChannelDetails: """ Returns the channel details. """ return self.token_network.detail( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
python
def detail(self, block_identifier: BlockSpecification) -> ChannelDetails: return self.token_network.detail( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
[ "def", "detail", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "ChannelDetails", ":", "return", "self", ".", "token_network", ".", "detail", "(", "participant1", "=", "self", ".", "participant1", ",", "participant2", "=", "self", ...
Returns the channel details.
[ "Returns", "the", "channel", "details", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L71-L78
235,552
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.settle_timeout
def settle_timeout(self) -> int: """ Returns the channels settle_timeout. """ # There is no way to get the settle timeout after the channel has been closed as # we're saving gas. Therefore get the ChannelOpened event and get the timeout there. filter_args = get_filter_args_for_specific_event_from_channel( token_network_address=self.token_network.address, channel_identifier=self.channel_identifier, event_name=ChannelEvent.OPENED, contract_manager=self.contract_manager, ) events = self.token_network.proxy.contract.web3.eth.getLogs(filter_args) assert len(events) > 0, 'No matching ChannelOpen event found.' # we want the latest event here, there might have been multiple channels event = decode_event( self.contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK), events[-1], ) return event['args']['settle_timeout']
python
def settle_timeout(self) -> int: # There is no way to get the settle timeout after the channel has been closed as # we're saving gas. Therefore get the ChannelOpened event and get the timeout there. filter_args = get_filter_args_for_specific_event_from_channel( token_network_address=self.token_network.address, channel_identifier=self.channel_identifier, event_name=ChannelEvent.OPENED, contract_manager=self.contract_manager, ) events = self.token_network.proxy.contract.web3.eth.getLogs(filter_args) assert len(events) > 0, 'No matching ChannelOpen event found.' # we want the latest event here, there might have been multiple channels event = decode_event( self.contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK), events[-1], ) return event['args']['settle_timeout']
[ "def", "settle_timeout", "(", "self", ")", "->", "int", ":", "# There is no way to get the settle timeout after the channel has been closed as", "# we're saving gas. Therefore get the ChannelOpened event and get the timeout there.", "filter_args", "=", "get_filter_args_for_specific_event_fro...
Returns the channels settle_timeout.
[ "Returns", "the", "channels", "settle_timeout", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L80-L100
235,553
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.opened
def opened(self, block_identifier: BlockSpecification) -> bool: """ Returns if the channel is opened. """ return self.token_network.channel_is_opened( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
python
def opened(self, block_identifier: BlockSpecification) -> bool: return self.token_network.channel_is_opened( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
[ "def", "opened", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "bool", ":", "return", "self", ".", "token_network", ".", "channel_is_opened", "(", "participant1", "=", "self", ".", "participant1", ",", "participant2", "=", "self", ...
Returns if the channel is opened.
[ "Returns", "if", "the", "channel", "is", "opened", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L125-L132
235,554
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.closed
def closed(self, block_identifier: BlockSpecification) -> bool: """ Returns if the channel is closed. """ return self.token_network.channel_is_closed( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
python
def closed(self, block_identifier: BlockSpecification) -> bool: return self.token_network.channel_is_closed( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
[ "def", "closed", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "bool", ":", "return", "self", ".", "token_network", ".", "channel_is_closed", "(", "participant1", "=", "self", ".", "participant1", ",", "participant2", "=", "self", ...
Returns if the channel is closed.
[ "Returns", "if", "the", "channel", "is", "closed", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L134-L141
235,555
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.settled
def settled(self, block_identifier: BlockSpecification) -> bool: """ Returns if the channel is settled. """ return self.token_network.channel_is_settled( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
python
def settled(self, block_identifier: BlockSpecification) -> bool: return self.token_network.channel_is_settled( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
[ "def", "settled", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "bool", ":", "return", "self", ".", "token_network", ".", "channel_is_settled", "(", "participant1", "=", "self", ".", "participant1", ",", "participant2", "=", "self",...
Returns if the channel is settled.
[ "Returns", "if", "the", "channel", "is", "settled", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L143-L150
235,556
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.closing_address
def closing_address(self, block_identifier: BlockSpecification) -> Optional[Address]: """ Returns the address of the closer of the channel. """ return self.token_network.closing_address( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
python
def closing_address(self, block_identifier: BlockSpecification) -> Optional[Address]: return self.token_network.closing_address( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, )
[ "def", "closing_address", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "Optional", "[", "Address", "]", ":", "return", "self", ".", "token_network", ".", "closing_address", "(", "participant1", "=", "self", ".", "participant1", ","...
Returns the address of the closer of the channel.
[ "Returns", "the", "address", "of", "the", "closer", "of", "the", "channel", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L152-L159
235,557
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.close
def close( self, nonce: Nonce, balance_hash: BalanceHash, additional_hash: AdditionalHash, signature: Signature, block_identifier: BlockSpecification, ): """ Closes the channel using the provided balance proof. """ self.token_network.close( channel_identifier=self.channel_identifier, partner=self.participant2, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature, given_block_identifier=block_identifier, )
python
def close( self, nonce: Nonce, balance_hash: BalanceHash, additional_hash: AdditionalHash, signature: Signature, block_identifier: BlockSpecification, ): self.token_network.close( channel_identifier=self.channel_identifier, partner=self.participant2, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature, given_block_identifier=block_identifier, )
[ "def", "close", "(", "self", ",", "nonce", ":", "Nonce", ",", "balance_hash", ":", "BalanceHash", ",", "additional_hash", ":", "AdditionalHash", ",", "signature", ":", "Signature", ",", "block_identifier", ":", "BlockSpecification", ",", ")", ":", "self", ".",...
Closes the channel using the provided balance proof.
[ "Closes", "the", "channel", "using", "the", "provided", "balance", "proof", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L178-L195
235,558
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.update_transfer
def update_transfer( self, nonce: Nonce, balance_hash: BalanceHash, additional_hash: AdditionalHash, partner_signature: Signature, signature: Signature, block_identifier: BlockSpecification, ): """ Updates the channel using the provided balance proof. """ self.token_network.update_transfer( channel_identifier=self.channel_identifier, partner=self.participant2, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, closing_signature=partner_signature, non_closing_signature=signature, given_block_identifier=block_identifier, )
python
def update_transfer( self, nonce: Nonce, balance_hash: BalanceHash, additional_hash: AdditionalHash, partner_signature: Signature, signature: Signature, block_identifier: BlockSpecification, ): self.token_network.update_transfer( channel_identifier=self.channel_identifier, partner=self.participant2, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, closing_signature=partner_signature, non_closing_signature=signature, given_block_identifier=block_identifier, )
[ "def", "update_transfer", "(", "self", ",", "nonce", ":", "Nonce", ",", "balance_hash", ":", "BalanceHash", ",", "additional_hash", ":", "AdditionalHash", ",", "partner_signature", ":", "Signature", ",", "signature", ":", "Signature", ",", "block_identifier", ":",...
Updates the channel using the provided balance proof.
[ "Updates", "the", "channel", "using", "the", "provided", "balance", "proof", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L197-L216
235,559
raiden-network/raiden
raiden/network/proxies/payment_channel.py
PaymentChannel.settle
def settle( self, transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, partner_transferred_amount: TokenAmount, partner_locked_amount: TokenAmount, partner_locksroot: Locksroot, block_identifier: BlockSpecification, ): """ Settles the channel. """ self.token_network.settle( channel_identifier=self.channel_identifier, transferred_amount=transferred_amount, locked_amount=locked_amount, locksroot=locksroot, partner=self.participant2, partner_transferred_amount=partner_transferred_amount, partner_locked_amount=partner_locked_amount, partner_locksroot=partner_locksroot, given_block_identifier=block_identifier, )
python
def settle( self, transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, partner_transferred_amount: TokenAmount, partner_locked_amount: TokenAmount, partner_locksroot: Locksroot, block_identifier: BlockSpecification, ): self.token_network.settle( channel_identifier=self.channel_identifier, transferred_amount=transferred_amount, locked_amount=locked_amount, locksroot=locksroot, partner=self.participant2, partner_transferred_amount=partner_transferred_amount, partner_locked_amount=partner_locked_amount, partner_locksroot=partner_locksroot, given_block_identifier=block_identifier, )
[ "def", "settle", "(", "self", ",", "transferred_amount", ":", "TokenAmount", ",", "locked_amount", ":", "TokenAmount", ",", "locksroot", ":", "Locksroot", ",", "partner_transferred_amount", ":", "TokenAmount", ",", "partner_locked_amount", ":", "TokenAmount", ",", "...
Settles the channel.
[ "Settles", "the", "channel", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L231-L252
235,560
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator.py
events_for_unlock_lock
def events_for_unlock_lock( initiator_state: InitiatorTransferState, channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, pseudo_random_generator: random.Random, ) -> List[Event]: """ Unlocks the lock offchain, and emits the events for the successful payment. """ # next hop learned the secret, unlock the token locally and send the # lock claim message to next hop transfer_description = initiator_state.transfer_description message_identifier = message_identifier_from_prng(pseudo_random_generator) unlock_lock = channel.send_unlock( channel_state=channel_state, message_identifier=message_identifier, payment_identifier=transfer_description.payment_identifier, secret=secret, secrethash=secrethash, ) payment_sent_success = EventPaymentSentSuccess( payment_network_identifier=channel_state.payment_network_identifier, token_network_identifier=TokenNetworkID(channel_state.token_network_identifier), identifier=transfer_description.payment_identifier, amount=transfer_description.amount, target=transfer_description.target, secret=secret, ) unlock_success = EventUnlockSuccess( transfer_description.payment_identifier, transfer_description.secrethash, ) return [unlock_lock, payment_sent_success, unlock_success]
python
def events_for_unlock_lock( initiator_state: InitiatorTransferState, channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, pseudo_random_generator: random.Random, ) -> List[Event]: # next hop learned the secret, unlock the token locally and send the # lock claim message to next hop transfer_description = initiator_state.transfer_description message_identifier = message_identifier_from_prng(pseudo_random_generator) unlock_lock = channel.send_unlock( channel_state=channel_state, message_identifier=message_identifier, payment_identifier=transfer_description.payment_identifier, secret=secret, secrethash=secrethash, ) payment_sent_success = EventPaymentSentSuccess( payment_network_identifier=channel_state.payment_network_identifier, token_network_identifier=TokenNetworkID(channel_state.token_network_identifier), identifier=transfer_description.payment_identifier, amount=transfer_description.amount, target=transfer_description.target, secret=secret, ) unlock_success = EventUnlockSuccess( transfer_description.payment_identifier, transfer_description.secrethash, ) return [unlock_lock, payment_sent_success, unlock_success]
[ "def", "events_for_unlock_lock", "(", "initiator_state", ":", "InitiatorTransferState", ",", "channel_state", ":", "NettingChannelState", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "pseudo_random_generator", ":", "random", ".", "Random", ...
Unlocks the lock offchain, and emits the events for the successful payment.
[ "Unlocks", "the", "lock", "offchain", "and", "emits", "the", "events", "for", "the", "successful", "payment", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L49-L84
235,561
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator.py
handle_block
def handle_block( initiator_state: InitiatorTransferState, state_change: Block, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: """ Checks if the lock has expired, and if it has sends a remove expired lock and emits the failing events. """ secrethash = initiator_state.transfer.lock.secrethash locked_lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) if not locked_lock: if channel_state.partner_state.secrethashes_to_lockedlocks.get(secrethash): return TransitionResult(initiator_state, list()) else: # if lock is not in our or our partner's locked locks then the # task can go return TransitionResult(None, list()) lock_expiration_threshold = BlockNumber( locked_lock.expiration + DEFAULT_WAIT_BEFORE_LOCK_REMOVAL, ) lock_has_expired, _ = channel.is_lock_expired( end_state=channel_state.our_state, lock=locked_lock, block_number=state_change.block_number, lock_expiration_threshold=lock_expiration_threshold, ) events: List[Event] = list() if lock_has_expired: is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if is_channel_open: expired_lock_events = channel.events_for_expired_lock( channel_state=channel_state, locked_lock=locked_lock, pseudo_random_generator=pseudo_random_generator, ) events.extend(expired_lock_events) if initiator_state.received_secret_request: reason = 'bad secret request message from target' else: reason = 'lock expired' transfer_description = initiator_state.transfer_description payment_identifier = transfer_description.payment_identifier # TODO: When we introduce multiple transfers per payment this needs to be # reconsidered. As we would want to try other routes once a route # has failed, and a transfer failing does not mean the entire payment # would have to fail. # Related issue: https://github.com/raiden-network/raiden/issues/2329 payment_failed = EventPaymentSentFailed( payment_network_identifier=transfer_description.payment_network_identifier, token_network_identifier=transfer_description.token_network_identifier, identifier=payment_identifier, target=transfer_description.target, reason=reason, ) unlock_failed = EventUnlockFailed( identifier=payment_identifier, secrethash=initiator_state.transfer_description.secrethash, reason=reason, ) lock_exists = channel.lock_exists_in_either_channel_side( channel_state=channel_state, secrethash=secrethash, ) return TransitionResult( # If the lock is either in our state or partner state we keep the # task around to wait for the LockExpired messages to sync. # Check https://github.com/raiden-network/raiden/issues/3183 initiator_state if lock_exists else None, events + [payment_failed, unlock_failed], ) else: return TransitionResult(initiator_state, events)
python
def handle_block( initiator_state: InitiatorTransferState, state_change: Block, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: secrethash = initiator_state.transfer.lock.secrethash locked_lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) if not locked_lock: if channel_state.partner_state.secrethashes_to_lockedlocks.get(secrethash): return TransitionResult(initiator_state, list()) else: # if lock is not in our or our partner's locked locks then the # task can go return TransitionResult(None, list()) lock_expiration_threshold = BlockNumber( locked_lock.expiration + DEFAULT_WAIT_BEFORE_LOCK_REMOVAL, ) lock_has_expired, _ = channel.is_lock_expired( end_state=channel_state.our_state, lock=locked_lock, block_number=state_change.block_number, lock_expiration_threshold=lock_expiration_threshold, ) events: List[Event] = list() if lock_has_expired: is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if is_channel_open: expired_lock_events = channel.events_for_expired_lock( channel_state=channel_state, locked_lock=locked_lock, pseudo_random_generator=pseudo_random_generator, ) events.extend(expired_lock_events) if initiator_state.received_secret_request: reason = 'bad secret request message from target' else: reason = 'lock expired' transfer_description = initiator_state.transfer_description payment_identifier = transfer_description.payment_identifier # TODO: When we introduce multiple transfers per payment this needs to be # reconsidered. As we would want to try other routes once a route # has failed, and a transfer failing does not mean the entire payment # would have to fail. # Related issue: https://github.com/raiden-network/raiden/issues/2329 payment_failed = EventPaymentSentFailed( payment_network_identifier=transfer_description.payment_network_identifier, token_network_identifier=transfer_description.token_network_identifier, identifier=payment_identifier, target=transfer_description.target, reason=reason, ) unlock_failed = EventUnlockFailed( identifier=payment_identifier, secrethash=initiator_state.transfer_description.secrethash, reason=reason, ) lock_exists = channel.lock_exists_in_either_channel_side( channel_state=channel_state, secrethash=secrethash, ) return TransitionResult( # If the lock is either in our state or partner state we keep the # task around to wait for the LockExpired messages to sync. # Check https://github.com/raiden-network/raiden/issues/3183 initiator_state if lock_exists else None, events + [payment_failed, unlock_failed], ) else: return TransitionResult(initiator_state, events)
[ "def", "handle_block", "(", "initiator_state", ":", "InitiatorTransferState", ",", "state_change", ":", "Block", ",", "channel_state", ":", "NettingChannelState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", "TransitionResult", "[", ...
Checks if the lock has expired, and if it has sends a remove expired lock and emits the failing events.
[ "Checks", "if", "the", "lock", "has", "expired", "and", "if", "it", "has", "sends", "a", "remove", "expired", "lock", "and", "emits", "the", "failing", "events", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L87-L167
235,562
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator.py
next_channel_from_routes
def next_channel_from_routes( available_routes: List[RouteState], channelidentifiers_to_channels: ChannelMap, transfer_amount: PaymentAmount, ) -> Optional[NettingChannelState]: """ Returns the first channel that can be used to start the transfer. The routing service can race with local changes, so the recommended routes must be validated. """ for route in available_routes: channel_identifier = route.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue if channel.get_status(channel_state) != CHANNEL_STATE_OPENED: continue pending_transfers = channel.get_number_of_pending_transfers(channel_state.our_state) if pending_transfers >= MAXIMUM_PENDING_TRANSFERS: continue distributable = channel.get_distributable( channel_state.our_state, channel_state.partner_state, ) if transfer_amount > distributable: continue if channel.is_valid_amount(channel_state.our_state, transfer_amount): return channel_state return None
python
def next_channel_from_routes( available_routes: List[RouteState], channelidentifiers_to_channels: ChannelMap, transfer_amount: PaymentAmount, ) -> Optional[NettingChannelState]: for route in available_routes: channel_identifier = route.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue if channel.get_status(channel_state) != CHANNEL_STATE_OPENED: continue pending_transfers = channel.get_number_of_pending_transfers(channel_state.our_state) if pending_transfers >= MAXIMUM_PENDING_TRANSFERS: continue distributable = channel.get_distributable( channel_state.our_state, channel_state.partner_state, ) if transfer_amount > distributable: continue if channel.is_valid_amount(channel_state.our_state, transfer_amount): return channel_state return None
[ "def", "next_channel_from_routes", "(", "available_routes", ":", "List", "[", "RouteState", "]", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfer_amount", ":", "PaymentAmount", ",", ")", "->", "Optional", "[", "NettingChannelState", "]", ":", ...
Returns the first channel that can be used to start the transfer. The routing service can race with local changes, so the recommended routes must be validated.
[ "Returns", "the", "first", "channel", "that", "can", "be", "used", "to", "start", "the", "transfer", ".", "The", "routing", "service", "can", "race", "with", "local", "changes", "so", "the", "recommended", "routes", "must", "be", "validated", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L178-L211
235,563
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator.py
send_lockedtransfer
def send_lockedtransfer( transfer_description: TransferDescriptionWithSecretState, channel_state: NettingChannelState, message_identifier: MessageID, block_number: BlockNumber, ) -> SendLockedTransfer: """ Create a mediated transfer using channel. """ assert channel_state.token_network_identifier == transfer_description.token_network_identifier lock_expiration = get_initial_lock_expiration( block_number, channel_state.reveal_timeout, ) # The payment amount and the fee amount must be included in the locked # amount, as a guarantee to the mediator that the fee will be claimable # on-chain. total_amount = PaymentWithFeeAmount( transfer_description.amount + transfer_description.allocated_fee, ) lockedtransfer_event = channel.send_lockedtransfer( channel_state=channel_state, initiator=transfer_description.initiator, target=transfer_description.target, amount=total_amount, message_identifier=message_identifier, payment_identifier=transfer_description.payment_identifier, expiration=lock_expiration, secrethash=transfer_description.secrethash, ) return lockedtransfer_event
python
def send_lockedtransfer( transfer_description: TransferDescriptionWithSecretState, channel_state: NettingChannelState, message_identifier: MessageID, block_number: BlockNumber, ) -> SendLockedTransfer: assert channel_state.token_network_identifier == transfer_description.token_network_identifier lock_expiration = get_initial_lock_expiration( block_number, channel_state.reveal_timeout, ) # The payment amount and the fee amount must be included in the locked # amount, as a guarantee to the mediator that the fee will be claimable # on-chain. total_amount = PaymentWithFeeAmount( transfer_description.amount + transfer_description.allocated_fee, ) lockedtransfer_event = channel.send_lockedtransfer( channel_state=channel_state, initiator=transfer_description.initiator, target=transfer_description.target, amount=total_amount, message_identifier=message_identifier, payment_identifier=transfer_description.payment_identifier, expiration=lock_expiration, secrethash=transfer_description.secrethash, ) return lockedtransfer_event
[ "def", "send_lockedtransfer", "(", "transfer_description", ":", "TransferDescriptionWithSecretState", ",", "channel_state", ":", "NettingChannelState", ",", "message_identifier", ":", "MessageID", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "SendLockedTransfer"...
Create a mediated transfer using channel.
[ "Create", "a", "mediated", "transfer", "using", "channel", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L267-L298
235,564
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator.py
handle_offchain_secretreveal
def handle_offchain_secretreveal( initiator_state: InitiatorTransferState, state_change: ReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: """ Once the next hop proves it knows the secret, the initiator can unlock the mediated transfer. This will validate the secret, and if valid a new balance proof is sent to the next hop with the current lock removed from the merkle tree and the transferred amount updated. """ iteration: TransitionResult[InitiatorTransferState] valid_reveal = is_valid_secret_reveal( state_change=state_change, transfer_secrethash=initiator_state.transfer_description.secrethash, secret=state_change.secret, ) sent_by_partner = state_change.sender == channel_state.partner_state.address is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if valid_reveal and is_channel_open and sent_by_partner: events = events_for_unlock_lock( initiator_state=initiator_state, channel_state=channel_state, secret=state_change.secret, secrethash=state_change.secrethash, pseudo_random_generator=pseudo_random_generator, ) iteration = TransitionResult(None, events) else: events = list() iteration = TransitionResult(initiator_state, events) return iteration
python
def handle_offchain_secretreveal( initiator_state: InitiatorTransferState, state_change: ReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: iteration: TransitionResult[InitiatorTransferState] valid_reveal = is_valid_secret_reveal( state_change=state_change, transfer_secrethash=initiator_state.transfer_description.secrethash, secret=state_change.secret, ) sent_by_partner = state_change.sender == channel_state.partner_state.address is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if valid_reveal and is_channel_open and sent_by_partner: events = events_for_unlock_lock( initiator_state=initiator_state, channel_state=channel_state, secret=state_change.secret, secrethash=state_change.secrethash, pseudo_random_generator=pseudo_random_generator, ) iteration = TransitionResult(None, events) else: events = list() iteration = TransitionResult(initiator_state, events) return iteration
[ "def", "handle_offchain_secretreveal", "(", "initiator_state", ":", "InitiatorTransferState", ",", "state_change", ":", "ReceiveSecretReveal", ",", "channel_state", ":", "NettingChannelState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", ...
Once the next hop proves it knows the secret, the initiator can unlock the mediated transfer. This will validate the secret, and if valid a new balance proof is sent to the next hop with the current lock removed from the merkle tree and the transferred amount updated.
[ "Once", "the", "next", "hop", "proves", "it", "knows", "the", "secret", "the", "initiator", "can", "unlock", "the", "mediated", "transfer", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L371-L406
235,565
raiden-network/raiden
raiden/transfer/mediated_transfer/initiator.py
handle_onchain_secretreveal
def handle_onchain_secretreveal( initiator_state: InitiatorTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: """ When a secret is revealed on-chain all nodes learn the secret. This check the on-chain secret corresponds to the one used by the initiator, and if valid a new balance proof is sent to the next hop with the current lock removed from the merkle tree and the transferred amount updated. """ iteration: TransitionResult[InitiatorTransferState] secret = state_change.secret secrethash = initiator_state.transfer_description.secrethash is_valid_secret = is_valid_secret_reveal( state_change=state_change, transfer_secrethash=secrethash, secret=secret, ) is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED is_lock_expired = state_change.block_number > initiator_state.transfer.lock.expiration is_lock_unlocked = ( is_valid_secret and not is_lock_expired ) if is_lock_unlocked: channel.register_onchain_secret( channel_state=channel_state, secret=secret, secrethash=secrethash, secret_reveal_block_number=state_change.block_number, ) if is_lock_unlocked and is_channel_open: events = events_for_unlock_lock( initiator_state, channel_state, state_change.secret, state_change.secrethash, pseudo_random_generator, ) iteration = TransitionResult(None, events) else: events = list() iteration = TransitionResult(initiator_state, events) return iteration
python
def handle_onchain_secretreveal( initiator_state: InitiatorTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[InitiatorTransferState]: iteration: TransitionResult[InitiatorTransferState] secret = state_change.secret secrethash = initiator_state.transfer_description.secrethash is_valid_secret = is_valid_secret_reveal( state_change=state_change, transfer_secrethash=secrethash, secret=secret, ) is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED is_lock_expired = state_change.block_number > initiator_state.transfer.lock.expiration is_lock_unlocked = ( is_valid_secret and not is_lock_expired ) if is_lock_unlocked: channel.register_onchain_secret( channel_state=channel_state, secret=secret, secrethash=secrethash, secret_reveal_block_number=state_change.block_number, ) if is_lock_unlocked and is_channel_open: events = events_for_unlock_lock( initiator_state, channel_state, state_change.secret, state_change.secrethash, pseudo_random_generator, ) iteration = TransitionResult(None, events) else: events = list() iteration = TransitionResult(initiator_state, events) return iteration
[ "def", "handle_onchain_secretreveal", "(", "initiator_state", ":", "InitiatorTransferState", ",", "state_change", ":", "ContractReceiveSecretReveal", ",", "channel_state", ":", "NettingChannelState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", ...
When a secret is revealed on-chain all nodes learn the secret. This check the on-chain secret corresponds to the one used by the initiator, and if valid a new balance proof is sent to the next hop with the current lock removed from the merkle tree and the transferred amount updated.
[ "When", "a", "secret", "is", "revealed", "on", "-", "chain", "all", "nodes", "learn", "the", "secret", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L409-L459
235,566
raiden-network/raiden
raiden/transfer/channel.py
is_lock_pending
def is_lock_pending( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> bool: """True if the `secrethash` corresponds to a lock that is pending to be claimed and didn't expire. """ return ( secrethash in end_state.secrethashes_to_lockedlocks or secrethash in end_state.secrethashes_to_unlockedlocks or secrethash in end_state.secrethashes_to_onchain_unlockedlocks )
python
def is_lock_pending( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> bool: return ( secrethash in end_state.secrethashes_to_lockedlocks or secrethash in end_state.secrethashes_to_unlockedlocks or secrethash in end_state.secrethashes_to_onchain_unlockedlocks )
[ "def", "is_lock_pending", "(", "end_state", ":", "NettingChannelEndState", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "bool", ":", "return", "(", "secrethash", "in", "end_state", ".", "secrethashes_to_lockedlocks", "or", "secrethash", "in", "end_state", ...
True if the `secrethash` corresponds to a lock that is pending to be claimed and didn't expire.
[ "True", "if", "the", "secrethash", "corresponds", "to", "a", "lock", "that", "is", "pending", "to", "be", "claimed", "and", "didn", "t", "expire", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L156-L167
235,567
raiden-network/raiden
raiden/transfer/channel.py
is_deposit_confirmed
def is_deposit_confirmed( channel_state: NettingChannelState, block_number: BlockNumber, ) -> bool: """True if the block which mined the deposit transaction has been confirmed. """ if not channel_state.deposit_transaction_queue: return False return is_transaction_confirmed( channel_state.deposit_transaction_queue[0].block_number, block_number, )
python
def is_deposit_confirmed( channel_state: NettingChannelState, block_number: BlockNumber, ) -> bool: if not channel_state.deposit_transaction_queue: return False return is_transaction_confirmed( channel_state.deposit_transaction_queue[0].block_number, block_number, )
[ "def", "is_deposit_confirmed", "(", "channel_state", ":", "NettingChannelState", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "bool", ":", "if", "not", "channel_state", ".", "deposit_transaction_queue", ":", "return", "False", "return", "is_transaction_con...
True if the block which mined the deposit transaction has been confirmed.
[ "True", "if", "the", "block", "which", "mined", "the", "deposit", "transaction", "has", "been", "confirmed", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L170-L183
235,568
raiden-network/raiden
raiden/transfer/channel.py
is_lock_expired
def is_lock_expired( end_state: NettingChannelEndState, lock: LockType, block_number: BlockNumber, lock_expiration_threshold: BlockNumber, ) -> SuccessOrError: """ Determine whether a lock has expired. The lock has expired if both: - The secret was not registered on-chain in time. - The current block exceeds lock's expiration + confirmation blocks. """ secret_registered_on_chain = lock.secrethash in end_state.secrethashes_to_onchain_unlockedlocks if secret_registered_on_chain: return (False, 'lock has been unlocked on-chain') if block_number < lock_expiration_threshold: msg = ( f'current block number ({block_number}) is not larger than ' f'lock.expiration + confirmation blocks ({lock_expiration_threshold})' ) return (False, msg) return (True, None)
python
def is_lock_expired( end_state: NettingChannelEndState, lock: LockType, block_number: BlockNumber, lock_expiration_threshold: BlockNumber, ) -> SuccessOrError: secret_registered_on_chain = lock.secrethash in end_state.secrethashes_to_onchain_unlockedlocks if secret_registered_on_chain: return (False, 'lock has been unlocked on-chain') if block_number < lock_expiration_threshold: msg = ( f'current block number ({block_number}) is not larger than ' f'lock.expiration + confirmation blocks ({lock_expiration_threshold})' ) return (False, msg) return (True, None)
[ "def", "is_lock_expired", "(", "end_state", ":", "NettingChannelEndState", ",", "lock", ":", "LockType", ",", "block_number", ":", "BlockNumber", ",", "lock_expiration_threshold", ":", "BlockNumber", ",", ")", "->", "SuccessOrError", ":", "secret_registered_on_chain", ...
Determine whether a lock has expired. The lock has expired if both: - The secret was not registered on-chain in time. - The current block exceeds lock's expiration + confirmation blocks.
[ "Determine", "whether", "a", "lock", "has", "expired", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L194-L219
235,569
raiden-network/raiden
raiden/transfer/channel.py
is_secret_known
def is_secret_known( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> bool: """True if the `secrethash` is for a lock with a known secret.""" return ( secrethash in end_state.secrethashes_to_unlockedlocks or secrethash in end_state.secrethashes_to_onchain_unlockedlocks )
python
def is_secret_known( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> bool: return ( secrethash in end_state.secrethashes_to_unlockedlocks or secrethash in end_state.secrethashes_to_onchain_unlockedlocks )
[ "def", "is_secret_known", "(", "end_state", ":", "NettingChannelEndState", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "bool", ":", "return", "(", "secrethash", "in", "end_state", ".", "secrethashes_to_unlockedlocks", "or", "secrethash", "in", "end_state",...
True if the `secrethash` is for a lock with a known secret.
[ "True", "if", "the", "secrethash", "is", "for", "a", "lock", "with", "a", "known", "secret", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L237-L245
235,570
raiden-network/raiden
raiden/transfer/channel.py
get_secret
def get_secret( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> Optional[Secret]: """Returns `secret` if the `secrethash` is for a lock with a known secret.""" partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash) if partial_unlock_proof is None: partial_unlock_proof = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash) if partial_unlock_proof is not None: return partial_unlock_proof.secret return None
python
def get_secret( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> Optional[Secret]: partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash) if partial_unlock_proof is None: partial_unlock_proof = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash) if partial_unlock_proof is not None: return partial_unlock_proof.secret return None
[ "def", "get_secret", "(", "end_state", ":", "NettingChannelEndState", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "Optional", "[", "Secret", "]", ":", "partial_unlock_proof", "=", "end_state", ".", "secrethashes_to_unlockedlocks", ".", "get", "(", "secre...
Returns `secret` if the `secrethash` is for a lock with a known secret.
[ "Returns", "secret", "if", "the", "secrethash", "is", "for", "a", "lock", "with", "a", "known", "secret", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L264-L277
235,571
raiden-network/raiden
raiden/transfer/channel.py
is_balance_proof_safe_for_onchain_operations
def is_balance_proof_safe_for_onchain_operations( balance_proof: BalanceProofSignedState, ) -> bool: """ Check if the balance proof would overflow onchain. """ total_amount = balance_proof.transferred_amount + balance_proof.locked_amount return total_amount <= UINT256_MAX
python
def is_balance_proof_safe_for_onchain_operations( balance_proof: BalanceProofSignedState, ) -> bool: total_amount = balance_proof.transferred_amount + balance_proof.locked_amount return total_amount <= UINT256_MAX
[ "def", "is_balance_proof_safe_for_onchain_operations", "(", "balance_proof", ":", "BalanceProofSignedState", ",", ")", "->", "bool", ":", "total_amount", "=", "balance_proof", ".", "transferred_amount", "+", "balance_proof", ".", "locked_amount", "return", "total_amount", ...
Check if the balance proof would overflow onchain.
[ "Check", "if", "the", "balance", "proof", "would", "overflow", "onchain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L288-L293
235,572
raiden-network/raiden
raiden/transfer/channel.py
is_balance_proof_usable_onchain
def is_balance_proof_usable_onchain( received_balance_proof: BalanceProofSignedState, channel_state: NettingChannelState, sender_state: NettingChannelEndState, ) -> SuccessOrError: """ Checks the balance proof can be used on-chain. For a balance proof to be valid it must be newer than the previous one, i.e. the nonce must increase, the signature must tie the balance proof to the correct channel, and the values must not result in an under/overflow onchain. Important: This predicate does not validate all the message fields. The fields locksroot, transferred_amount, and locked_amount **MUST** be validated elsewhere based on the message type. """ expected_nonce = get_next_nonce(sender_state) is_valid_signature_, signature_msg = is_valid_signature( received_balance_proof, sender_state.address, ) result: SuccessOrError # TODO: Accept unlock messages if the node has not yet sent a transaction # with the balance proof to the blockchain, this will save one call to # unlock on-chain for the non-closing party. if get_status(channel_state) != CHANNEL_STATE_OPENED: # The channel must be opened, otherwise if receiver is the closer, the # balance proof cannot be used onchain. msg = f'The channel is already closed.' result = (False, msg) elif received_balance_proof.channel_identifier != channel_state.identifier: # Informational message, the channel_identifier **validated by the # signature** must match for the balance_proof to be valid. msg = ( f"channel_identifier does not match. " f"expected: {channel_state.identifier} " f"got: {received_balance_proof.channel_identifier}." ) result = (False, msg) elif received_balance_proof.token_network_identifier != channel_state.token_network_identifier: # Informational message, the token_network_identifier **validated by # the signature** must match for the balance_proof to be valid. msg = ( f"token_network_identifier does not match. " f"expected: {channel_state.token_network_identifier} " f"got: {received_balance_proof.token_network_identifier}." ) result = (False, msg) elif received_balance_proof.chain_id != channel_state.chain_id: # Informational message, the chain_id **validated by the signature** # must match for the balance_proof to be valid. msg = ( f"chain_id does not match channel's " f"chain_id. expected: {channel_state.chain_id} " f"got: {received_balance_proof.chain_id}." ) result = (False, msg) elif not is_balance_proof_safe_for_onchain_operations(received_balance_proof): transferred_amount_after_unlock = ( received_balance_proof.transferred_amount + received_balance_proof.locked_amount ) msg = ( f"Balance proof total transferred amount would overflow onchain. " f"max: {UINT256_MAX} result would be: {transferred_amount_after_unlock}" ) result = (False, msg) elif received_balance_proof.nonce != expected_nonce: # The nonces must increase sequentially, otherwise there is a # synchronization problem. msg = ( f'Nonce did not change sequentially, expected: {expected_nonce} ' f'got: {received_balance_proof.nonce}.' ) result = (False, msg) elif not is_valid_signature_: # The signature must be valid, otherwise the balance proof cannot be # used onchain. result = (False, signature_msg) else: result = (True, None) return result
python
def is_balance_proof_usable_onchain( received_balance_proof: BalanceProofSignedState, channel_state: NettingChannelState, sender_state: NettingChannelEndState, ) -> SuccessOrError: expected_nonce = get_next_nonce(sender_state) is_valid_signature_, signature_msg = is_valid_signature( received_balance_proof, sender_state.address, ) result: SuccessOrError # TODO: Accept unlock messages if the node has not yet sent a transaction # with the balance proof to the blockchain, this will save one call to # unlock on-chain for the non-closing party. if get_status(channel_state) != CHANNEL_STATE_OPENED: # The channel must be opened, otherwise if receiver is the closer, the # balance proof cannot be used onchain. msg = f'The channel is already closed.' result = (False, msg) elif received_balance_proof.channel_identifier != channel_state.identifier: # Informational message, the channel_identifier **validated by the # signature** must match for the balance_proof to be valid. msg = ( f"channel_identifier does not match. " f"expected: {channel_state.identifier} " f"got: {received_balance_proof.channel_identifier}." ) result = (False, msg) elif received_balance_proof.token_network_identifier != channel_state.token_network_identifier: # Informational message, the token_network_identifier **validated by # the signature** must match for the balance_proof to be valid. msg = ( f"token_network_identifier does not match. " f"expected: {channel_state.token_network_identifier} " f"got: {received_balance_proof.token_network_identifier}." ) result = (False, msg) elif received_balance_proof.chain_id != channel_state.chain_id: # Informational message, the chain_id **validated by the signature** # must match for the balance_proof to be valid. msg = ( f"chain_id does not match channel's " f"chain_id. expected: {channel_state.chain_id} " f"got: {received_balance_proof.chain_id}." ) result = (False, msg) elif not is_balance_proof_safe_for_onchain_operations(received_balance_proof): transferred_amount_after_unlock = ( received_balance_proof.transferred_amount + received_balance_proof.locked_amount ) msg = ( f"Balance proof total transferred amount would overflow onchain. " f"max: {UINT256_MAX} result would be: {transferred_amount_after_unlock}" ) result = (False, msg) elif received_balance_proof.nonce != expected_nonce: # The nonces must increase sequentially, otherwise there is a # synchronization problem. msg = ( f'Nonce did not change sequentially, expected: {expected_nonce} ' f'got: {received_balance_proof.nonce}.' ) result = (False, msg) elif not is_valid_signature_: # The signature must be valid, otherwise the balance proof cannot be # used onchain. result = (False, signature_msg) else: result = (True, None) return result
[ "def", "is_balance_proof_usable_onchain", "(", "received_balance_proof", ":", "BalanceProofSignedState", ",", "channel_state", ":", "NettingChannelState", ",", "sender_state", ":", "NettingChannelEndState", ",", ")", "->", "SuccessOrError", ":", "expected_nonce", "=", "get_...
Checks the balance proof can be used on-chain. For a balance proof to be valid it must be newer than the previous one, i.e. the nonce must increase, the signature must tie the balance proof to the correct channel, and the values must not result in an under/overflow onchain. Important: This predicate does not validate all the message fields. The fields locksroot, transferred_amount, and locked_amount **MUST** be validated elsewhere based on the message type.
[ "Checks", "the", "balance", "proof", "can", "be", "used", "on", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L368-L462
235,573
raiden-network/raiden
raiden/transfer/channel.py
get_distributable
def get_distributable( sender: NettingChannelEndState, receiver: NettingChannelEndState, ) -> TokenAmount: """Return the amount of tokens that can be used by the `sender`. The returned value is limited to a UINT256, since that is the representation used in the smart contracts and we cannot use a larger value. The limit is enforced on transferred_amount + locked_amount to avoid overflows. This is an additional security check. """ _, _, transferred_amount, locked_amount = get_current_balanceproof(sender) distributable = get_balance(sender, receiver) - get_amount_locked(sender) overflow_limit = max( UINT256_MAX - transferred_amount - locked_amount, 0, ) return TokenAmount(min(overflow_limit, distributable))
python
def get_distributable( sender: NettingChannelEndState, receiver: NettingChannelEndState, ) -> TokenAmount: _, _, transferred_amount, locked_amount = get_current_balanceproof(sender) distributable = get_balance(sender, receiver) - get_amount_locked(sender) overflow_limit = max( UINT256_MAX - transferred_amount - locked_amount, 0, ) return TokenAmount(min(overflow_limit, distributable))
[ "def", "get_distributable", "(", "sender", ":", "NettingChannelEndState", ",", "receiver", ":", "NettingChannelEndState", ",", ")", "->", "TokenAmount", ":", "_", ",", "_", ",", "transferred_amount", ",", "locked_amount", "=", "get_current_balanceproof", "(", "sende...
Return the amount of tokens that can be used by the `sender`. The returned value is limited to a UINT256, since that is the representation used in the smart contracts and we cannot use a larger value. The limit is enforced on transferred_amount + locked_amount to avoid overflows. This is an additional security check.
[ "Return", "the", "amount", "of", "tokens", "that", "can", "be", "used", "by", "the", "sender", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L950-L970
235,574
raiden-network/raiden
raiden/transfer/channel.py
get_batch_unlock
def get_batch_unlock( end_state: NettingChannelEndState, ) -> Optional[MerkleTreeLeaves]: """ Unlock proof for an entire merkle tree of pending locks The unlock proof contains all the merkle tree data, tightly packed, needed by the token network contract to verify the secret expiry and calculate the token amounts to transfer. """ if len(end_state.merkletree.layers[LEAVES]) == 0: # pylint: disable=len-as-condition return None lockhashes_to_locks = dict() lockhashes_to_locks.update({ lock.lockhash: lock for secrethash, lock in end_state.secrethashes_to_lockedlocks.items() }) lockhashes_to_locks.update({ proof.lock.lockhash: proof.lock for secrethash, proof in end_state.secrethashes_to_unlockedlocks.items() }) lockhashes_to_locks.update({ proof.lock.lockhash: proof.lock for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items() }) ordered_locks = [ lockhashes_to_locks[LockHash(lockhash)] for lockhash in end_state.merkletree.layers[LEAVES] ] # Not sure why the cast is needed here. The error was: # Incompatible return value type # (got "List[HashTimeLockState]", expected "Optional[MerkleTreeLeaves]") return cast(MerkleTreeLeaves, ordered_locks)
python
def get_batch_unlock( end_state: NettingChannelEndState, ) -> Optional[MerkleTreeLeaves]: if len(end_state.merkletree.layers[LEAVES]) == 0: # pylint: disable=len-as-condition return None lockhashes_to_locks = dict() lockhashes_to_locks.update({ lock.lockhash: lock for secrethash, lock in end_state.secrethashes_to_lockedlocks.items() }) lockhashes_to_locks.update({ proof.lock.lockhash: proof.lock for secrethash, proof in end_state.secrethashes_to_unlockedlocks.items() }) lockhashes_to_locks.update({ proof.lock.lockhash: proof.lock for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items() }) ordered_locks = [ lockhashes_to_locks[LockHash(lockhash)] for lockhash in end_state.merkletree.layers[LEAVES] ] # Not sure why the cast is needed here. The error was: # Incompatible return value type # (got "List[HashTimeLockState]", expected "Optional[MerkleTreeLeaves]") return cast(MerkleTreeLeaves, ordered_locks)
[ "def", "get_batch_unlock", "(", "end_state", ":", "NettingChannelEndState", ",", ")", "->", "Optional", "[", "MerkleTreeLeaves", "]", ":", "if", "len", "(", "end_state", ".", "merkletree", ".", "layers", "[", "LEAVES", "]", ")", "==", "0", ":", "# pylint: di...
Unlock proof for an entire merkle tree of pending locks The unlock proof contains all the merkle tree data, tightly packed, needed by the token network contract to verify the secret expiry and calculate the token amounts to transfer.
[ "Unlock", "proof", "for", "an", "entire", "merkle", "tree", "of", "pending", "locks" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L973-L1007
235,575
raiden-network/raiden
raiden/transfer/channel.py
get_lock
def get_lock( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> Optional[HashTimeLockState]: """Return the lock correspoding to `secrethash` or None if the lock is unknown. """ lock = end_state.secrethashes_to_lockedlocks.get(secrethash) if not lock: partial_unlock = end_state.secrethashes_to_unlockedlocks.get(secrethash) if not partial_unlock: partial_unlock = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash) if partial_unlock: lock = partial_unlock.lock assert isinstance(lock, HashTimeLockState) or lock is None return lock
python
def get_lock( end_state: NettingChannelEndState, secrethash: SecretHash, ) -> Optional[HashTimeLockState]: lock = end_state.secrethashes_to_lockedlocks.get(secrethash) if not lock: partial_unlock = end_state.secrethashes_to_unlockedlocks.get(secrethash) if not partial_unlock: partial_unlock = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash) if partial_unlock: lock = partial_unlock.lock assert isinstance(lock, HashTimeLockState) or lock is None return lock
[ "def", "get_lock", "(", "end_state", ":", "NettingChannelEndState", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "Optional", "[", "HashTimeLockState", "]", ":", "lock", "=", "end_state", ".", "secrethashes_to_lockedlocks", ".", "get", "(", "secrethash", ...
Return the lock correspoding to `secrethash` or None if the lock is unknown.
[ "Return", "the", "lock", "correspoding", "to", "secrethash", "or", "None", "if", "the", "lock", "is", "unknown", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1010-L1029
235,576
raiden-network/raiden
raiden/transfer/channel.py
lock_exists_in_either_channel_side
def lock_exists_in_either_channel_side( channel_state: NettingChannelState, secrethash: SecretHash, ) -> bool: """Check if the lock with `secrethash` exists in either our state or the partner's state""" lock = get_lock(channel_state.our_state, secrethash) if not lock: lock = get_lock(channel_state.partner_state, secrethash) return lock is not None
python
def lock_exists_in_either_channel_side( channel_state: NettingChannelState, secrethash: SecretHash, ) -> bool: lock = get_lock(channel_state.our_state, secrethash) if not lock: lock = get_lock(channel_state.partner_state, secrethash) return lock is not None
[ "def", "lock_exists_in_either_channel_side", "(", "channel_state", ":", "NettingChannelState", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "bool", ":", "lock", "=", "get_lock", "(", "channel_state", ".", "our_state", ",", "secrethash", ")", "if", "not", ...
Check if the lock with `secrethash` exists in either our state or the partner's state
[ "Check", "if", "the", "lock", "with", "secrethash", "exists", "in", "either", "our", "state", "or", "the", "partner", "s", "state" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1032-L1040
235,577
raiden-network/raiden
raiden/transfer/channel.py
_del_lock
def _del_lock(end_state: NettingChannelEndState, secrethash: SecretHash) -> None: """Removes the lock from the indexing structures. Note: This won't change the merkletree! """ assert is_lock_pending(end_state, secrethash) _del_unclaimed_lock(end_state, secrethash) if secrethash in end_state.secrethashes_to_onchain_unlockedlocks: del end_state.secrethashes_to_onchain_unlockedlocks[secrethash]
python
def _del_lock(end_state: NettingChannelEndState, secrethash: SecretHash) -> None: assert is_lock_pending(end_state, secrethash) _del_unclaimed_lock(end_state, secrethash) if secrethash in end_state.secrethashes_to_onchain_unlockedlocks: del end_state.secrethashes_to_onchain_unlockedlocks[secrethash]
[ "def", "_del_lock", "(", "end_state", ":", "NettingChannelEndState", ",", "secrethash", ":", "SecretHash", ")", "->", "None", ":", "assert", "is_lock_pending", "(", "end_state", ",", "secrethash", ")", "_del_unclaimed_lock", "(", "end_state", ",", "secrethash", ")...
Removes the lock from the indexing structures. Note: This won't change the merkletree!
[ "Removes", "the", "lock", "from", "the", "indexing", "structures", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1103-L1114
235,578
raiden-network/raiden
raiden/transfer/channel.py
compute_merkletree_with
def compute_merkletree_with( merkletree: MerkleTreeState, lockhash: LockHash, ) -> Optional[MerkleTreeState]: """Register the given lockhash with the existing merkle tree.""" # Use None to inform the caller the lockshash is already known result = None leaves = merkletree.layers[LEAVES] if lockhash not in leaves: leaves = list(leaves) leaves.append(Keccak256(lockhash)) result = MerkleTreeState(compute_layers(leaves)) return result
python
def compute_merkletree_with( merkletree: MerkleTreeState, lockhash: LockHash, ) -> Optional[MerkleTreeState]: # Use None to inform the caller the lockshash is already known result = None leaves = merkletree.layers[LEAVES] if lockhash not in leaves: leaves = list(leaves) leaves.append(Keccak256(lockhash)) result = MerkleTreeState(compute_layers(leaves)) return result
[ "def", "compute_merkletree_with", "(", "merkletree", ":", "MerkleTreeState", ",", "lockhash", ":", "LockHash", ",", ")", "->", "Optional", "[", "MerkleTreeState", "]", ":", "# Use None to inform the caller the lockshash is already known", "result", "=", "None", "leaves", ...
Register the given lockhash with the existing merkle tree.
[ "Register", "the", "given", "lockhash", "with", "the", "existing", "merkle", "tree", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1172-L1186
235,579
raiden-network/raiden
raiden/transfer/channel.py
register_offchain_secret
def register_offchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, ) -> None: """This will register the secret and set the lock to the unlocked stated. Even though the lock is unlock it is *not* claimed. The capacity will increase once the next balance proof is received. """ our_state = channel_state.our_state partner_state = channel_state.partner_state register_secret_endstate(our_state, secret, secrethash) register_secret_endstate(partner_state, secret, secrethash)
python
def register_offchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, ) -> None: our_state = channel_state.our_state partner_state = channel_state.partner_state register_secret_endstate(our_state, secret, secrethash) register_secret_endstate(partner_state, secret, secrethash)
[ "def", "register_offchain_secret", "(", "channel_state", ":", "NettingChannelState", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "None", ":", "our_state", "=", "channel_state", ".", "our_state", "partner_state", "=", "channe...
This will register the secret and set the lock to the unlocked stated. Even though the lock is unlock it is *not* claimed. The capacity will increase once the next balance proof is received.
[ "This", "will", "register", "the", "secret", "and", "set", "the", "lock", "to", "the", "unlocked", "stated", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1590-L1604
235,580
raiden-network/raiden
raiden/transfer/channel.py
register_onchain_secret
def register_onchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, secret_reveal_block_number: BlockNumber, delete_lock: bool = True, ) -> None: """This will register the onchain secret and set the lock to the unlocked stated. Even though the lock is unlocked it is *not* claimed. The capacity will increase once the next balance proof is received. """ our_state = channel_state.our_state partner_state = channel_state.partner_state register_onchain_secret_endstate( our_state, secret, secrethash, secret_reveal_block_number, delete_lock, ) register_onchain_secret_endstate( partner_state, secret, secrethash, secret_reveal_block_number, delete_lock, )
python
def register_onchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, secret_reveal_block_number: BlockNumber, delete_lock: bool = True, ) -> None: our_state = channel_state.our_state partner_state = channel_state.partner_state register_onchain_secret_endstate( our_state, secret, secrethash, secret_reveal_block_number, delete_lock, ) register_onchain_secret_endstate( partner_state, secret, secrethash, secret_reveal_block_number, delete_lock, )
[ "def", "register_onchain_secret", "(", "channel_state", ":", "NettingChannelState", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "secret_reveal_block_number", ":", "BlockNumber", ",", "delete_lock", ":", "bool", "=", "True", ",", ")", "...
This will register the onchain secret and set the lock to the unlocked stated. Even though the lock is unlocked it is *not* claimed. The capacity will increase once the next balance proof is received.
[ "This", "will", "register", "the", "onchain", "secret", "and", "set", "the", "lock", "to", "the", "unlocked", "stated", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1607-L1635
235,581
raiden-network/raiden
raiden/transfer/channel.py
handle_receive_lockedtransfer
def handle_receive_lockedtransfer( channel_state: NettingChannelState, mediated_transfer: LockedTransferSignedState, ) -> EventsOrError: """Register the latest known transfer. The receiver needs to use this method to update the container with a _valid_ transfer, otherwise the locksroot will not contain the pending transfer. The receiver needs to ensure that the merkle root has the secrethash included, otherwise it won't be able to claim it. """ events: List[Event] is_valid, msg, merkletree = is_valid_lockedtransfer( mediated_transfer, channel_state, channel_state.partner_state, channel_state.our_state, ) if is_valid: assert merkletree, 'is_valid_lock_expired should return merkletree if valid' channel_state.partner_state.balance_proof = mediated_transfer.balance_proof channel_state.partner_state.merkletree = merkletree lock = mediated_transfer.lock channel_state.partner_state.secrethashes_to_lockedlocks[lock.secrethash] = lock send_processed = SendProcessed( recipient=mediated_transfer.balance_proof.sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=mediated_transfer.message_identifier, ) events = [send_processed] else: assert msg, 'is_valid_lock_expired should return error msg if not valid' invalid_locked = EventInvalidReceivedLockedTransfer( payment_identifier=mediated_transfer.payment_identifier, reason=msg, ) events = [invalid_locked] return is_valid, events, msg
python
def handle_receive_lockedtransfer( channel_state: NettingChannelState, mediated_transfer: LockedTransferSignedState, ) -> EventsOrError: events: List[Event] is_valid, msg, merkletree = is_valid_lockedtransfer( mediated_transfer, channel_state, channel_state.partner_state, channel_state.our_state, ) if is_valid: assert merkletree, 'is_valid_lock_expired should return merkletree if valid' channel_state.partner_state.balance_proof = mediated_transfer.balance_proof channel_state.partner_state.merkletree = merkletree lock = mediated_transfer.lock channel_state.partner_state.secrethashes_to_lockedlocks[lock.secrethash] = lock send_processed = SendProcessed( recipient=mediated_transfer.balance_proof.sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=mediated_transfer.message_identifier, ) events = [send_processed] else: assert msg, 'is_valid_lock_expired should return error msg if not valid' invalid_locked = EventInvalidReceivedLockedTransfer( payment_identifier=mediated_transfer.payment_identifier, reason=msg, ) events = [invalid_locked] return is_valid, events, msg
[ "def", "handle_receive_lockedtransfer", "(", "channel_state", ":", "NettingChannelState", ",", "mediated_transfer", ":", "LockedTransferSignedState", ",", ")", "->", "EventsOrError", ":", "events", ":", "List", "[", "Event", "]", "is_valid", ",", "msg", ",", "merkle...
Register the latest known transfer. The receiver needs to use this method to update the container with a _valid_ transfer, otherwise the locksroot will not contain the pending transfer. The receiver needs to ensure that the merkle root has the secrethash included, otherwise it won't be able to claim it.
[ "Register", "the", "latest", "known", "transfer", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1742-L1783
235,582
raiden-network/raiden
raiden/utils/notifying_queue.py
NotifyingQueue.get
def get(self, block=True, timeout=None): """ Removes and returns an item from the queue. """ value = self._queue.get(block, timeout) if self._queue.empty(): self.clear() return value
python
def get(self, block=True, timeout=None): value = self._queue.get(block, timeout) if self._queue.empty(): self.clear() return value
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "value", "=", "self", ".", "_queue", ".", "get", "(", "block", ",", "timeout", ")", "if", "self", ".", "_queue", ".", "empty", "(", ")", ":", "self", "...
Removes and returns an item from the queue.
[ "Removes", "and", "returns", "an", "item", "from", "the", "queue", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/notifying_queue.py#L18-L23
235,583
raiden-network/raiden
raiden/utils/notifying_queue.py
NotifyingQueue.copy
def copy(self): """ Copies the current queue items. """ copy = self._queue.copy() result = list() while not copy.empty(): result.append(copy.get_nowait()) return result
python
def copy(self): copy = self._queue.copy() result = list() while not copy.empty(): result.append(copy.get_nowait()) return result
[ "def", "copy", "(", "self", ")", ":", "copy", "=", "self", ".", "_queue", ".", "copy", "(", ")", "result", "=", "list", "(", ")", "while", "not", "copy", ".", "empty", "(", ")", ":", "result", ".", "append", "(", "copy", ".", "get_nowait", "(", ...
Copies the current queue items.
[ "Copies", "the", "current", "queue", "items", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/notifying_queue.py#L31-L38
235,584
raiden-network/raiden
raiden/routing.py
get_best_routes_internal
def get_best_routes_internal( chain_state: ChainState, token_network_id: TokenNetworkID, from_address: InitiatorAddress, to_address: TargetAddress, amount: int, previous_address: Optional[Address], ) -> List[RouteState]: """ Returns a list of channels that can be used to make a transfer. This will filter out channels that are not open and don't have enough capacity. """ # TODO: Route ranking. # Rate each route to optimize the fee price/quality of each route and add a # rate from in the range [0.0,1.0]. available_routes = list() token_network = views.get_token_network_by_identifier( chain_state, token_network_id, ) if not token_network: return list() neighbors_heap: List[Neighbour] = list() try: all_neighbors = networkx.all_neighbors(token_network.network_graph.network, from_address) except networkx.NetworkXError: # If `our_address` is not in the graph, no channels opened with the # address return list() for partner_address in all_neighbors: # don't send the message backwards if partner_address == previous_address: continue channel_state = views.get_channelstate_by_token_network_and_partner( chain_state, token_network_id, partner_address, ) if not channel_state: continue if channel.get_status(channel_state) != CHANNEL_STATE_OPENED: log.info( 'Channel is not opened, ignoring', from_address=pex(from_address), partner_address=pex(partner_address), routing_source='Internal Routing', ) continue nonrefundable = amount > channel.get_distributable( channel_state.partner_state, channel_state.our_state, ) try: length = networkx.shortest_path_length( token_network.network_graph.network, partner_address, to_address, ) neighbour = Neighbour( length=length, nonrefundable=nonrefundable, partner_address=partner_address, channelid=channel_state.identifier, ) heappush(neighbors_heap, neighbour) except (networkx.NetworkXNoPath, networkx.NodeNotFound): pass if not neighbors_heap: log.warning( 'No routes available', from_address=pex(from_address), to_address=pex(to_address), ) return list() while neighbors_heap: neighbour = heappop(neighbors_heap) route_state = RouteState( node_address=neighbour.partner_address, channel_identifier=neighbour.channelid, ) available_routes.append(route_state) return available_routes
python
def get_best_routes_internal( chain_state: ChainState, token_network_id: TokenNetworkID, from_address: InitiatorAddress, to_address: TargetAddress, amount: int, previous_address: Optional[Address], ) -> List[RouteState]: # TODO: Route ranking. # Rate each route to optimize the fee price/quality of each route and add a # rate from in the range [0.0,1.0]. available_routes = list() token_network = views.get_token_network_by_identifier( chain_state, token_network_id, ) if not token_network: return list() neighbors_heap: List[Neighbour] = list() try: all_neighbors = networkx.all_neighbors(token_network.network_graph.network, from_address) except networkx.NetworkXError: # If `our_address` is not in the graph, no channels opened with the # address return list() for partner_address in all_neighbors: # don't send the message backwards if partner_address == previous_address: continue channel_state = views.get_channelstate_by_token_network_and_partner( chain_state, token_network_id, partner_address, ) if not channel_state: continue if channel.get_status(channel_state) != CHANNEL_STATE_OPENED: log.info( 'Channel is not opened, ignoring', from_address=pex(from_address), partner_address=pex(partner_address), routing_source='Internal Routing', ) continue nonrefundable = amount > channel.get_distributable( channel_state.partner_state, channel_state.our_state, ) try: length = networkx.shortest_path_length( token_network.network_graph.network, partner_address, to_address, ) neighbour = Neighbour( length=length, nonrefundable=nonrefundable, partner_address=partner_address, channelid=channel_state.identifier, ) heappush(neighbors_heap, neighbour) except (networkx.NetworkXNoPath, networkx.NodeNotFound): pass if not neighbors_heap: log.warning( 'No routes available', from_address=pex(from_address), to_address=pex(to_address), ) return list() while neighbors_heap: neighbour = heappop(neighbors_heap) route_state = RouteState( node_address=neighbour.partner_address, channel_identifier=neighbour.channelid, ) available_routes.append(route_state) return available_routes
[ "def", "get_best_routes_internal", "(", "chain_state", ":", "ChainState", ",", "token_network_id", ":", "TokenNetworkID", ",", "from_address", ":", "InitiatorAddress", ",", "to_address", ":", "TargetAddress", ",", "amount", ":", "int", ",", "previous_address", ":", ...
Returns a list of channels that can be used to make a transfer. This will filter out channels that are not open and don't have enough capacity.
[ "Returns", "a", "list", "of", "channels", "that", "can", "be", "used", "to", "make", "a", "transfer", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/routing.py#L80-L174
235,585
raiden-network/raiden
raiden/network/transport/matrix/client.py
Room.get_joined_members
def get_joined_members(self, force_resync=False) -> List[User]: """ Return a list of members of this room. """ if force_resync: response = self.client.api.get_room_members(self.room_id) for event in response['chunk']: if event['content']['membership'] == 'join': user_id = event["state_key"] if user_id not in self._members: self._mkmembers( User( self.client.api, user_id, event['content'].get('displayname'), ), ) return list(self._members.values())
python
def get_joined_members(self, force_resync=False) -> List[User]: if force_resync: response = self.client.api.get_room_members(self.room_id) for event in response['chunk']: if event['content']['membership'] == 'join': user_id = event["state_key"] if user_id not in self._members: self._mkmembers( User( self.client.api, user_id, event['content'].get('displayname'), ), ) return list(self._members.values())
[ "def", "get_joined_members", "(", "self", ",", "force_resync", "=", "False", ")", "->", "List", "[", "User", "]", ":", "if", "force_resync", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_members", "(", "self", ".", "room_id", ")...
Return a list of members of this room.
[ "Return", "a", "list", "of", "members", "of", "this", "room", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L31-L46
235,586
raiden-network/raiden
raiden/network/transport/matrix/client.py
Room.update_aliases
def update_aliases(self): """ Get aliases information from room state Returns: boolean: True if the aliases changed, False if not """ changed = False try: response = self.client.api.get_room_state(self.room_id) except MatrixRequestError: return False for chunk in response: content = chunk.get('content') if content: if 'aliases' in content: aliases = content['aliases'] if aliases != self.aliases: self.aliases = aliases changed = True if chunk.get('type') == 'm.room.canonical_alias': canonical_alias = content['alias'] if self.canonical_alias != canonical_alias: self.canonical_alias = canonical_alias changed = True if changed and self.aliases and not self.canonical_alias: self.canonical_alias = self.aliases[0] return changed
python
def update_aliases(self): changed = False try: response = self.client.api.get_room_state(self.room_id) except MatrixRequestError: return False for chunk in response: content = chunk.get('content') if content: if 'aliases' in content: aliases = content['aliases'] if aliases != self.aliases: self.aliases = aliases changed = True if chunk.get('type') == 'm.room.canonical_alias': canonical_alias = content['alias'] if self.canonical_alias != canonical_alias: self.canonical_alias = canonical_alias changed = True if changed and self.aliases and not self.canonical_alias: self.canonical_alias = self.aliases[0] return changed
[ "def", "update_aliases", "(", "self", ")", ":", "changed", "=", "False", "try", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_state", "(", "self", ".", "room_id", ")", "except", "MatrixRequestError", ":", "return", "False", "for",...
Get aliases information from room state Returns: boolean: True if the aliases changed, False if not
[ "Get", "aliases", "information", "from", "room", "state" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L60-L86
235,587
raiden-network/raiden
raiden/network/transport/matrix/client.py
GMatrixClient.stop_listener_thread
def stop_listener_thread(self): """ Kills sync_thread greenlet before joining it """ # when stopping, `kill` will cause the `self.api.sync` call in _sync # to raise a connection error. This flag will ensure it exits gracefully then self.should_listen = False if self.sync_thread: self.sync_thread.kill() self.sync_thread.get() if self._handle_thread is not None: self._handle_thread.get() self.sync_thread = None self._handle_thread = None
python
def stop_listener_thread(self): # when stopping, `kill` will cause the `self.api.sync` call in _sync # to raise a connection error. This flag will ensure it exits gracefully then self.should_listen = False if self.sync_thread: self.sync_thread.kill() self.sync_thread.get() if self._handle_thread is not None: self._handle_thread.get() self.sync_thread = None self._handle_thread = None
[ "def", "stop_listener_thread", "(", "self", ")", ":", "# when stopping, `kill` will cause the `self.api.sync` call in _sync", "# to raise a connection error. This flag will ensure it exits gracefully then", "self", ".", "should_listen", "=", "False", "if", "self", ".", "sync_thread",...
Kills sync_thread greenlet before joining it
[ "Kills", "sync_thread", "greenlet", "before", "joining", "it" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L267-L278
235,588
raiden-network/raiden
raiden/network/transport/matrix/client.py
GMatrixClient.typing
def typing(self, room: Room, timeout: int = 5000): """ Send typing event directly to api Args: room: room to send typing event to timeout: timeout for the event, in ms """ path = f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}' return self.api._send('PUT', path, {'typing': True, 'timeout': timeout})
python
def typing(self, room: Room, timeout: int = 5000): path = f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}' return self.api._send('PUT', path, {'typing': True, 'timeout': timeout})
[ "def", "typing", "(", "self", ",", "room", ":", "Room", ",", "timeout", ":", "int", "=", "5000", ")", ":", "path", "=", "f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}'", "return", "self", ".", "api", ".", "_send", "(", "'PUT'", ",", "path", ","...
Send typing event directly to api Args: room: room to send typing event to timeout: timeout for the event, in ms
[ "Send", "typing", "event", "directly", "to", "api" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L362-L371
235,589
raiden-network/raiden
raiden/network/transport/matrix/client.py
GMatrixClient._mkroom
def _mkroom(self, room_id: str) -> Room: """ Uses a geventified Room subclass """ if room_id not in self.rooms: self.rooms[room_id] = Room(self, room_id) room = self.rooms[room_id] if not room.canonical_alias: room.update_aliases() return room
python
def _mkroom(self, room_id: str) -> Room: if room_id not in self.rooms: self.rooms[room_id] = Room(self, room_id) room = self.rooms[room_id] if not room.canonical_alias: room.update_aliases() return room
[ "def", "_mkroom", "(", "self", ",", "room_id", ":", "str", ")", "->", "Room", ":", "if", "room_id", "not", "in", "self", ".", "rooms", ":", "self", ".", "rooms", "[", "room_id", "]", "=", "Room", "(", "self", ",", "room_id", ")", "room", "=", "se...
Uses a geventified Room subclass
[ "Uses", "a", "geventified", "Room", "subclass" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L373-L380
235,590
raiden-network/raiden
raiden/network/transport/matrix/client.py
GMatrixClient.set_sync_limit
def set_sync_limit(self, limit: int) -> Optional[int]: """ Sets the events limit per room for sync and return previous limit """ try: prev_limit = json.loads(self.sync_filter)['room']['timeline']['limit'] except (json.JSONDecodeError, KeyError): prev_limit = None self.sync_filter = json.dumps({'room': {'timeline': {'limit': limit}}}) return prev_limit
python
def set_sync_limit(self, limit: int) -> Optional[int]: try: prev_limit = json.loads(self.sync_filter)['room']['timeline']['limit'] except (json.JSONDecodeError, KeyError): prev_limit = None self.sync_filter = json.dumps({'room': {'timeline': {'limit': limit}}}) return prev_limit
[ "def", "set_sync_limit", "(", "self", ",", "limit", ":", "int", ")", "->", "Optional", "[", "int", "]", ":", "try", ":", "prev_limit", "=", "json", ".", "loads", "(", "self", ".", "sync_filter", ")", "[", "'room'", "]", "[", "'timeline'", "]", "[", ...
Sets the events limit per room for sync and return previous limit
[ "Sets", "the", "events", "limit", "per", "room", "for", "sync", "and", "return", "previous", "limit" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L491-L498
235,591
raiden-network/raiden
raiden/api/rest.py
handle_request_parsing_error
def handle_request_parsing_error( err, _req, _schema, _err_status_code, _err_headers, ): """ This handles request parsing errors generated for example by schema field validation failing.""" abort(HTTPStatus.BAD_REQUEST, errors=err.messages)
python
def handle_request_parsing_error( err, _req, _schema, _err_status_code, _err_headers, ): abort(HTTPStatus.BAD_REQUEST, errors=err.messages)
[ "def", "handle_request_parsing_error", "(", "err", ",", "_req", ",", "_schema", ",", "_err_status_code", ",", "_err_headers", ",", ")", ":", "abort", "(", "HTTPStatus", ".", "BAD_REQUEST", ",", "errors", "=", "err", ".", "messages", ")" ]
This handles request parsing errors generated for example by schema field validation failing.
[ "This", "handles", "request", "parsing", "errors", "generated", "for", "example", "by", "schema", "field", "validation", "failing", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L230-L239
235,592
raiden-network/raiden
raiden/api/rest.py
hexbytes_to_str
def hexbytes_to_str(map_: Dict): """ Converts values that are of type `HexBytes` to strings. """ for k, v in map_.items(): if isinstance(v, HexBytes): map_[k] = encode_hex(v)
python
def hexbytes_to_str(map_: Dict): for k, v in map_.items(): if isinstance(v, HexBytes): map_[k] = encode_hex(v)
[ "def", "hexbytes_to_str", "(", "map_", ":", "Dict", ")", ":", "for", "k", ",", "v", "in", "map_", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "HexBytes", ")", ":", "map_", "[", "k", "]", "=", "encode_hex", "(", "v", ")" ]
Converts values that are of type `HexBytes` to strings.
[ "Converts", "values", "that", "are", "of", "type", "HexBytes", "to", "strings", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L249-L253
235,593
raiden-network/raiden
raiden/api/rest.py
encode_byte_values
def encode_byte_values(map_: Dict): """ Converts values that are of type `bytes` to strings. """ for k, v in map_.items(): if isinstance(v, bytes): map_[k] = encode_hex(v)
python
def encode_byte_values(map_: Dict): for k, v in map_.items(): if isinstance(v, bytes): map_[k] = encode_hex(v)
[ "def", "encode_byte_values", "(", "map_", ":", "Dict", ")", ":", "for", "k", ",", "v", "in", "map_", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "bytes", ")", ":", "map_", "[", "k", "]", "=", "encode_hex", "(", "v", ")" ]
Converts values that are of type `bytes` to strings.
[ "Converts", "values", "that", "are", "of", "type", "bytes", "to", "strings", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L256-L260
235,594
raiden-network/raiden
raiden/api/rest.py
normalize_events_list
def normalize_events_list(old_list): """Internally the `event_type` key is prefixed with underscore but the API returns an object without that prefix""" new_list = [] for _event in old_list: new_event = dict(_event) if new_event.get('args'): new_event['args'] = dict(new_event['args']) encode_byte_values(new_event['args']) # remove the queue identifier if new_event.get('queue_identifier'): del new_event['queue_identifier'] # the events contain HexBytes values, convert those to strings hexbytes_to_str(new_event) # Some of the raiden events contain accounts and as such need to # be exported in hex to the outside world name = new_event['event'] if name == 'EventPaymentReceivedSuccess': new_event['initiator'] = to_checksum_address(new_event['initiator']) if name in ('EventPaymentSentSuccess', 'EventPaymentSentFailed'): new_event['target'] = to_checksum_address(new_event['target']) encode_byte_values(new_event) # encode unserializable objects encode_object_to_str(new_event) new_list.append(new_event) return new_list
python
def normalize_events_list(old_list): new_list = [] for _event in old_list: new_event = dict(_event) if new_event.get('args'): new_event['args'] = dict(new_event['args']) encode_byte_values(new_event['args']) # remove the queue identifier if new_event.get('queue_identifier'): del new_event['queue_identifier'] # the events contain HexBytes values, convert those to strings hexbytes_to_str(new_event) # Some of the raiden events contain accounts and as such need to # be exported in hex to the outside world name = new_event['event'] if name == 'EventPaymentReceivedSuccess': new_event['initiator'] = to_checksum_address(new_event['initiator']) if name in ('EventPaymentSentSuccess', 'EventPaymentSentFailed'): new_event['target'] = to_checksum_address(new_event['target']) encode_byte_values(new_event) # encode unserializable objects encode_object_to_str(new_event) new_list.append(new_event) return new_list
[ "def", "normalize_events_list", "(", "old_list", ")", ":", "new_list", "=", "[", "]", "for", "_event", "in", "old_list", ":", "new_event", "=", "dict", "(", "_event", ")", "if", "new_event", ".", "get", "(", "'args'", ")", ":", "new_event", "[", "'args'"...
Internally the `event_type` key is prefixed with underscore but the API returns an object without that prefix
[ "Internally", "the", "event_type", "key", "is", "prefixed", "with", "underscore", "but", "the", "API", "returns", "an", "object", "without", "that", "prefix" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L271-L296
235,595
raiden-network/raiden
raiden/api/rest.py
APIServer.unhandled_exception
def unhandled_exception(self, exception: Exception): """ Flask.errorhandler when an exception wasn't correctly handled """ log.critical( 'Unhandled exception when processing endpoint request', exc_info=True, node=pex(self.rest_api.raiden_api.address), ) self.greenlet.kill(exception) return api_error([str(exception)], HTTPStatus.INTERNAL_SERVER_ERROR)
python
def unhandled_exception(self, exception: Exception): log.critical( 'Unhandled exception when processing endpoint request', exc_info=True, node=pex(self.rest_api.raiden_api.address), ) self.greenlet.kill(exception) return api_error([str(exception)], HTTPStatus.INTERNAL_SERVER_ERROR)
[ "def", "unhandled_exception", "(", "self", ",", "exception", ":", "Exception", ")", ":", "log", ".", "critical", "(", "'Unhandled exception when processing endpoint request'", ",", "exc_info", "=", "True", ",", "node", "=", "pex", "(", "self", ".", "rest_api", "...
Flask.errorhandler when an exception wasn't correctly handled
[ "Flask", ".", "errorhandler", "when", "an", "exception", "wasn", "t", "correctly", "handled" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L540-L548
235,596
raiden-network/raiden
raiden/api/rest.py
RestAPI.get_connection_managers_info
def get_connection_managers_info(self, registry_address: typing.PaymentNetworkID): """Get a dict whose keys are token addresses and whose values are open channels, funds of last request, sum of deposits and number of channels""" log.debug( 'Getting connection managers info', node=pex(self.raiden_api.address), registry_address=to_checksum_address(registry_address), ) connection_managers = dict() for token in self.raiden_api.get_tokens_list(registry_address): token_network_identifier = views.get_token_network_identifier_by_token_address( views.state_from_raiden(self.raiden_api.raiden), payment_network_id=registry_address, token_address=token, ) try: connection_manager = self.raiden_api.raiden.connection_manager_for_token_network( token_network_identifier, ) except InvalidAddress: connection_manager = None open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden_api.raiden), payment_network_id=registry_address, token_address=token, ) if connection_manager is not None and open_channels: connection_managers[to_checksum_address(connection_manager.token_address)] = { 'funds': connection_manager.funds, 'sum_deposits': views.get_our_capacity_for_token_network( views.state_from_raiden(self.raiden_api.raiden), registry_address, token, ), 'channels': len(open_channels), } return connection_managers
python
def get_connection_managers_info(self, registry_address: typing.PaymentNetworkID): log.debug( 'Getting connection managers info', node=pex(self.raiden_api.address), registry_address=to_checksum_address(registry_address), ) connection_managers = dict() for token in self.raiden_api.get_tokens_list(registry_address): token_network_identifier = views.get_token_network_identifier_by_token_address( views.state_from_raiden(self.raiden_api.raiden), payment_network_id=registry_address, token_address=token, ) try: connection_manager = self.raiden_api.raiden.connection_manager_for_token_network( token_network_identifier, ) except InvalidAddress: connection_manager = None open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden_api.raiden), payment_network_id=registry_address, token_address=token, ) if connection_manager is not None and open_channels: connection_managers[to_checksum_address(connection_manager.token_address)] = { 'funds': connection_manager.funds, 'sum_deposits': views.get_our_capacity_for_token_network( views.state_from_raiden(self.raiden_api.raiden), registry_address, token, ), 'channels': len(open_channels), } return connection_managers
[ "def", "get_connection_managers_info", "(", "self", ",", "registry_address", ":", "typing", ".", "PaymentNetworkID", ")", ":", "log", ".", "debug", "(", "'Getting connection managers info'", ",", "node", "=", "pex", "(", "self", ".", "raiden_api", ".", "address", ...
Get a dict whose keys are token addresses and whose values are open channels, funds of last request, sum of deposits and number of channels
[ "Get", "a", "dict", "whose", "keys", "are", "token", "addresses", "and", "whose", "values", "are", "open", "channels", "funds", "of", "last", "request", "sum", "of", "deposits", "and", "number", "of", "channels" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L788-L828
235,597
raiden-network/raiden
raiden/ui/startup.py
setup_network_id_or_exit
def setup_network_id_or_exit( config: Dict[str, Any], given_network_id: int, web3: Web3, ) -> Tuple[int, bool]: """ Takes the given network id and checks it against the connected network If they don't match, exits the program with an error. If they do adds it to the configuration and then returns it and whether it is a known network """ node_network_id = int(web3.version.network) # pylint: disable=no-member known_given_network_id = given_network_id in ID_TO_NETWORKNAME known_node_network_id = node_network_id in ID_TO_NETWORKNAME if node_network_id != given_network_id: if known_given_network_id and known_node_network_id: click.secho( f"The chosen ethereum network '{ID_TO_NETWORKNAME[given_network_id]}' " f"differs from the ethereum client '{ID_TO_NETWORKNAME[node_network_id]}'. " "Please update your settings.", fg='red', ) else: click.secho( f"The chosen ethereum network id '{given_network_id}' differs " f"from the ethereum client '{node_network_id}'. " "Please update your settings.", fg='red', ) sys.exit(1) config['chain_id'] = given_network_id return given_network_id, known_node_network_id
python
def setup_network_id_or_exit( config: Dict[str, Any], given_network_id: int, web3: Web3, ) -> Tuple[int, bool]: node_network_id = int(web3.version.network) # pylint: disable=no-member known_given_network_id = given_network_id in ID_TO_NETWORKNAME known_node_network_id = node_network_id in ID_TO_NETWORKNAME if node_network_id != given_network_id: if known_given_network_id and known_node_network_id: click.secho( f"The chosen ethereum network '{ID_TO_NETWORKNAME[given_network_id]}' " f"differs from the ethereum client '{ID_TO_NETWORKNAME[node_network_id]}'. " "Please update your settings.", fg='red', ) else: click.secho( f"The chosen ethereum network id '{given_network_id}' differs " f"from the ethereum client '{node_network_id}'. " "Please update your settings.", fg='red', ) sys.exit(1) config['chain_id'] = given_network_id return given_network_id, known_node_network_id
[ "def", "setup_network_id_or_exit", "(", "config", ":", "Dict", "[", "str", ",", "Any", "]", ",", "given_network_id", ":", "int", ",", "web3", ":", "Web3", ",", ")", "->", "Tuple", "[", "int", ",", "bool", "]", ":", "node_network_id", "=", "int", "(", ...
Takes the given network id and checks it against the connected network If they don't match, exits the program with an error. If they do adds it to the configuration and then returns it and whether it is a known network
[ "Takes", "the", "given", "network", "id", "and", "checks", "it", "against", "the", "connected", "network" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/startup.py#L46-L79
235,598
raiden-network/raiden
raiden/ui/startup.py
setup_environment
def setup_environment(config: Dict[str, Any], environment_type: Environment) -> None: """Sets the config depending on the environment type""" # interpret the provided string argument if environment_type == Environment.PRODUCTION: # Safe configuration: restrictions for mainnet apply and matrix rooms have to be private config['transport']['matrix']['private_rooms'] = True config['environment_type'] = environment_type print(f'Raiden is running in {environment_type.value.lower()} mode')
python
def setup_environment(config: Dict[str, Any], environment_type: Environment) -> None: # interpret the provided string argument if environment_type == Environment.PRODUCTION: # Safe configuration: restrictions for mainnet apply and matrix rooms have to be private config['transport']['matrix']['private_rooms'] = True config['environment_type'] = environment_type print(f'Raiden is running in {environment_type.value.lower()} mode')
[ "def", "setup_environment", "(", "config", ":", "Dict", "[", "str", ",", "Any", "]", ",", "environment_type", ":", "Environment", ")", "->", "None", ":", "# interpret the provided string argument", "if", "environment_type", "==", "Environment", ".", "PRODUCTION", ...
Sets the config depending on the environment type
[ "Sets", "the", "config", "depending", "on", "the", "environment", "type" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/startup.py#L82-L91
235,599
raiden-network/raiden
raiden/ui/startup.py
setup_contracts_or_exit
def setup_contracts_or_exit( config: Dict[str, Any], network_id: int, ) -> Dict[str, Any]: """Sets the contract deployment data depending on the network id and environment type If an invalid combination of network id and environment type is provided, exits the program with an error """ environment_type = config['environment_type'] not_allowed = ( # for now we only disallow mainnet with test configuration network_id == 1 and environment_type == Environment.DEVELOPMENT ) if not_allowed: click.secho( f'The chosen network ({ID_TO_NETWORKNAME[network_id]}) is not a testnet, ' f'but the "development" environment was selected.\n' f'This is not allowed. Please start again with a safe environment setting ' f'(--environment production).', fg='red', ) sys.exit(1) contracts = dict() contracts_version = environment_type_to_contracts_version(environment_type) config['contracts_path'] = contracts_precompiled_path(contracts_version) if network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[network_id] != 'smoketest': try: deployment_data = get_contracts_deployment_info( chain_id=network_id, version=contracts_version, ) except ValueError: return contracts, False contracts = deployment_data['contracts'] return contracts
python
def setup_contracts_or_exit( config: Dict[str, Any], network_id: int, ) -> Dict[str, Any]: environment_type = config['environment_type'] not_allowed = ( # for now we only disallow mainnet with test configuration network_id == 1 and environment_type == Environment.DEVELOPMENT ) if not_allowed: click.secho( f'The chosen network ({ID_TO_NETWORKNAME[network_id]}) is not a testnet, ' f'but the "development" environment was selected.\n' f'This is not allowed. Please start again with a safe environment setting ' f'(--environment production).', fg='red', ) sys.exit(1) contracts = dict() contracts_version = environment_type_to_contracts_version(environment_type) config['contracts_path'] = contracts_precompiled_path(contracts_version) if network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[network_id] != 'smoketest': try: deployment_data = get_contracts_deployment_info( chain_id=network_id, version=contracts_version, ) except ValueError: return contracts, False contracts = deployment_data['contracts'] return contracts
[ "def", "setup_contracts_or_exit", "(", "config", ":", "Dict", "[", "str", ",", "Any", "]", ",", "network_id", ":", "int", ",", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "environment_type", "=", "config", "[", "'environment_type'", "]", "not_al...
Sets the contract deployment data depending on the network id and environment type If an invalid combination of network id and environment type is provided, exits the program with an error
[ "Sets", "the", "contract", "deployment", "data", "depending", "on", "the", "network", "id", "and", "environment", "type" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/startup.py#L94-L135