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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.connect
def connect( self, funds: typing.TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ): """Connect to the network. Subsequent calls to `connect` are allowed, but will only affect the spendable funds and the connection strategy parameters for the future. `connect` will not close any channels. Note: the ConnectionManager does not discriminate manually opened channels from automatically opened ones. If the user manually opened channels, those deposit amounts will affect the funding per channel and the number of new channels opened. Args: funds: Target amount of tokens spendable to join the network. initial_channel_target: Target number of channels to open. joinable_funds_target: Amount of funds not initially assigned. """ token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) if token_balance < funds: raise InvalidAmount( f'Insufficient balance for token {pex(self.token_address)}', ) if funds <= 0: raise InvalidAmount( 'The funds to use in the connection need to be a positive integer', ) if joinable_funds_target < 0 or joinable_funds_target > 1: raise InvalidAmount( f'joinable_funds_target should be between 0 and 1. Given: {joinable_funds_target}', ) with self.lock: self.funds = funds self.initial_channel_target = initial_channel_target self.joinable_funds_target = joinable_funds_target log_open_channels(self.raiden, self.registry_address, self.token_address, funds) qty_network_channels = views.count_token_network_channels( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) if not qty_network_channels: log.info( 'Bootstrapping token network.', node=pex(self.raiden.address), network_id=pex(self.registry_address), token_id=pex(self.token_address), ) self.api.channel_open( self.registry_address, self.token_address, self.BOOTSTRAP_ADDR, ) else: self._open_channels()
python
def connect( self, funds: typing.TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ): """Connect to the network. Subsequent calls to `connect` are allowed, but will only affect the spendable funds and the connection strategy parameters for the future. `connect` will not close any channels. Note: the ConnectionManager does not discriminate manually opened channels from automatically opened ones. If the user manually opened channels, those deposit amounts will affect the funding per channel and the number of new channels opened. Args: funds: Target amount of tokens spendable to join the network. initial_channel_target: Target number of channels to open. joinable_funds_target: Amount of funds not initially assigned. """ token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) if token_balance < funds: raise InvalidAmount( f'Insufficient balance for token {pex(self.token_address)}', ) if funds <= 0: raise InvalidAmount( 'The funds to use in the connection need to be a positive integer', ) if joinable_funds_target < 0 or joinable_funds_target > 1: raise InvalidAmount( f'joinable_funds_target should be between 0 and 1. Given: {joinable_funds_target}', ) with self.lock: self.funds = funds self.initial_channel_target = initial_channel_target self.joinable_funds_target = joinable_funds_target log_open_channels(self.raiden, self.registry_address, self.token_address, funds) qty_network_channels = views.count_token_network_channels( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) if not qty_network_channels: log.info( 'Bootstrapping token network.', node=pex(self.raiden.address), network_id=pex(self.registry_address), token_id=pex(self.token_address), ) self.api.channel_open( self.registry_address, self.token_address, self.BOOTSTRAP_ADDR, ) else: self._open_channels()
[ "def", "connect", "(", "self", ",", "funds", ":", "typing", ".", "TokenAmount", ",", "initial_channel_target", ":", "int", "=", "3", ",", "joinable_funds_target", ":", "float", "=", "0.4", ",", ")", ":", "token", "=", "self", ".", "raiden", ".", "chain",...
Connect to the network. Subsequent calls to `connect` are allowed, but will only affect the spendable funds and the connection strategy parameters for the future. `connect` will not close any channels. Note: the ConnectionManager does not discriminate manually opened channels from automatically opened ones. If the user manually opened channels, those deposit amounts will affect the funding per channel and the number of new channels opened. Args: funds: Target amount of tokens spendable to join the network. initial_channel_target: Target number of channels to open. joinable_funds_target: Amount of funds not initially assigned.
[ "Connect", "to", "the", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L101-L166
train
216,500
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.leave
def leave(self, registry_address): """ Leave the token network. This implies closing all channels and waiting for all channels to be settled. """ with self.lock: self.initial_channel_target = 0 channels_to_close = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=self.token_address, ) partner_addresses = [ channel_state.partner_state.address for channel_state in channels_to_close ] self.api.channel_batch_close( registry_address, self.token_address, partner_addresses, ) channel_ids = [ channel_state.identifier for channel_state in channels_to_close ] waiting.wait_for_settle( self.raiden, registry_address, self.token_address, channel_ids, self.raiden.alarm.sleep_time, ) return channels_to_close
python
def leave(self, registry_address): """ Leave the token network. This implies closing all channels and waiting for all channels to be settled. """ with self.lock: self.initial_channel_target = 0 channels_to_close = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=self.token_address, ) partner_addresses = [ channel_state.partner_state.address for channel_state in channels_to_close ] self.api.channel_batch_close( registry_address, self.token_address, partner_addresses, ) channel_ids = [ channel_state.identifier for channel_state in channels_to_close ] waiting.wait_for_settle( self.raiden, registry_address, self.token_address, channel_ids, self.raiden.alarm.sleep_time, ) return channels_to_close
[ "def", "leave", "(", "self", ",", "registry_address", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "initial_channel_target", "=", "0", "channels_to_close", "=", "views", ".", "get_channelstate_open", "(", "chain_state", "=", "views", ".", "state_fr...
Leave the token network. This implies closing all channels and waiting for all channels to be settled.
[ "Leave", "the", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L168-L206
train
216,501
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.join_channel
def join_channel(self, partner_address, partner_deposit): """Will be called, when we were selected as channel partner by another node. It will fund the channel with up to the partners deposit, but not more than remaining funds or the initial funding per channel. If the connection manager has no funds, this is a noop. """ # Consider this race condition: # # - Partner opens the channel and starts the deposit. # - This nodes learns about the new channel, starts ConnectionManager's # retry_connect, which will start a deposit for this half of the # channel. # - This node learns about the partner's deposit before its own. # join_channel is called which will try to deposit again. # # To fix this race, first the node must wait for the pending operations # to finish, because in them could be a deposit, and then deposit must # be called only if the channel is still not funded. token_network_proxy = self.raiden.chain.token_network(self.token_network_identifier) # Wait for any pending operation in the channel to complete, before # deciding on the deposit with self.lock, token_network_proxy.channel_operations_lock[partner_address]: channel_state = views.get_channelstate_for( views.state_from_raiden(self.raiden), self.token_network_identifier, self.token_address, partner_address, ) if not channel_state: return joining_funds = min( partner_deposit, self._funds_remaining, self._initial_funding_per_partner, ) if joining_funds <= 0 or self._leaving_state: return if joining_funds <= channel_state.our_state.contract_balance: return try: self.api.set_total_channel_deposit( self.registry_address, self.token_address, partner_address, joining_funds, ) except RaidenRecoverableError: log.info( 'Channel not in opened state', node=pex(self.raiden.address), ) except InvalidDBData: raise except RaidenUnrecoverableError as e: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( str(e), node=pex(self.raiden.address), ) else: log.info( 'Joined a channel', node=pex(self.raiden.address), partner=pex(partner_address), funds=joining_funds, )
python
def join_channel(self, partner_address, partner_deposit): """Will be called, when we were selected as channel partner by another node. It will fund the channel with up to the partners deposit, but not more than remaining funds or the initial funding per channel. If the connection manager has no funds, this is a noop. """ # Consider this race condition: # # - Partner opens the channel and starts the deposit. # - This nodes learns about the new channel, starts ConnectionManager's # retry_connect, which will start a deposit for this half of the # channel. # - This node learns about the partner's deposit before its own. # join_channel is called which will try to deposit again. # # To fix this race, first the node must wait for the pending operations # to finish, because in them could be a deposit, and then deposit must # be called only if the channel is still not funded. token_network_proxy = self.raiden.chain.token_network(self.token_network_identifier) # Wait for any pending operation in the channel to complete, before # deciding on the deposit with self.lock, token_network_proxy.channel_operations_lock[partner_address]: channel_state = views.get_channelstate_for( views.state_from_raiden(self.raiden), self.token_network_identifier, self.token_address, partner_address, ) if not channel_state: return joining_funds = min( partner_deposit, self._funds_remaining, self._initial_funding_per_partner, ) if joining_funds <= 0 or self._leaving_state: return if joining_funds <= channel_state.our_state.contract_balance: return try: self.api.set_total_channel_deposit( self.registry_address, self.token_address, partner_address, joining_funds, ) except RaidenRecoverableError: log.info( 'Channel not in opened state', node=pex(self.raiden.address), ) except InvalidDBData: raise except RaidenUnrecoverableError as e: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( str(e), node=pex(self.raiden.address), ) else: log.info( 'Joined a channel', node=pex(self.raiden.address), partner=pex(partner_address), funds=joining_funds, )
[ "def", "join_channel", "(", "self", ",", "partner_address", ",", "partner_deposit", ")", ":", "# Consider this race condition:", "#", "# - Partner opens the channel and starts the deposit.", "# - This nodes learns about the new channel, starts ConnectionManager's", "# retry_connect, wh...
Will be called, when we were selected as channel partner by another node. It will fund the channel with up to the partners deposit, but not more than remaining funds or the initial funding per channel. If the connection manager has no funds, this is a noop.
[ "Will", "be", "called", "when", "we", "were", "selected", "as", "channel", "partner", "by", "another", "node", ".", "It", "will", "fund", "the", "channel", "with", "up", "to", "the", "partners", "deposit", "but", "not", "more", "than", "remaining", "funds"...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L208-L286
train
216,502
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager.retry_connect
def retry_connect(self): """Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop. """ with self.lock: if self._funds_remaining > 0 and not self._leaving_state: self._open_channels()
python
def retry_connect(self): """Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop. """ with self.lock: if self._funds_remaining > 0 and not self._leaving_state: self._open_channels()
[ "def", "retry_connect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_funds_remaining", ">", "0", "and", "not", "self", ".", "_leaving_state", ":", "self", ".", "_open_channels", "(", ")" ]
Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop.
[ "Will", "be", "called", "when", "new", "channels", "in", "the", "token", "network", "are", "detected", ".", "If", "the", "minimum", "number", "of", "channels", "was", "not", "yet", "established", "it", "will", "try", "to", "open", "new", "channels", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L288-L297
train
216,503
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._find_new_partners
def _find_new_partners(self): """ Search the token network for potential channel partners. """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) known = set(channel_state.partner_state.address for channel_state in open_channels) known.add(self.BOOTSTRAP_ADDR) known.add(self.raiden.address) participants_addresses = views.get_participants_addresses( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) available = participants_addresses - known available = list(available) shuffle(available) new_partners = available log.debug( 'Found partners', node=pex(self.raiden.address), number_of_partners=len(available), ) return new_partners
python
def _find_new_partners(self): """ Search the token network for potential channel partners. """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) known = set(channel_state.partner_state.address for channel_state in open_channels) known.add(self.BOOTSTRAP_ADDR) known.add(self.raiden.address) participants_addresses = views.get_participants_addresses( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) available = participants_addresses - known available = list(available) shuffle(available) new_partners = available log.debug( 'Found partners', node=pex(self.raiden.address), number_of_partners=len(available), ) return new_partners
[ "def", "_find_new_partners", "(", "self", ")", ":", "open_channels", "=", "views", ".", "get_channelstate_open", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "payment_network_id", "=", "self", ".", "registry_a...
Search the token network for potential channel partners.
[ "Search", "the", "token", "network", "for", "potential", "channel", "partners", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L299-L327
train
216,504
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._join_partner
def _join_partner(self, partner: Address): """ Ensure a channel exists with partner and is funded in our side """ try: self.api.channel_open( self.registry_address, self.token_address, partner, ) except DuplicatedChannelError: # If channel already exists (either because partner created it, # or it's nonfunded channel), continue to ensure it's funded pass total_deposit = self._initial_funding_per_partner if total_deposit == 0: return try: self.api.set_total_channel_deposit( registry_address=self.registry_address, token_address=self.token_address, partner_address=partner, total_deposit=total_deposit, ) except InvalidDBData: raise except RECOVERABLE_ERRORS: log.info( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), ) except RaidenUnrecoverableError: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), )
python
def _join_partner(self, partner: Address): """ Ensure a channel exists with partner and is funded in our side """ try: self.api.channel_open( self.registry_address, self.token_address, partner, ) except DuplicatedChannelError: # If channel already exists (either because partner created it, # or it's nonfunded channel), continue to ensure it's funded pass total_deposit = self._initial_funding_per_partner if total_deposit == 0: return try: self.api.set_total_channel_deposit( registry_address=self.registry_address, token_address=self.token_address, partner_address=partner, total_deposit=total_deposit, ) except InvalidDBData: raise except RECOVERABLE_ERRORS: log.info( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), ) except RaidenUnrecoverableError: should_crash = ( self.raiden.config['environment_type'] != Environment.PRODUCTION or self.raiden.config['unrecoverable_error_should_crash'] ) if should_crash: raise log.critical( 'Deposit failed', node=pex(self.raiden.address), partner=pex(partner), )
[ "def", "_join_partner", "(", "self", ",", "partner", ":", "Address", ")", ":", "try", ":", "self", ".", "api", ".", "channel_open", "(", "self", ".", "registry_address", ",", "self", ".", "token_address", ",", "partner", ",", ")", "except", "DuplicatedChan...
Ensure a channel exists with partner and is funded in our side
[ "Ensure", "a", "channel", "exists", "with", "partner", "and", "is", "funded", "in", "our", "side" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L329-L373
train
216,505
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._open_channels
def _open_channels(self) -> bool: """ Open channels until there are `self.initial_channel_target` channels open. Do nothing if there are enough channels open already. Note: - This method must be called with the lock held. Return: - False if no channels could be opened """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) open_channels = [ channel_state for channel_state in open_channels if channel_state.partner_state.address != self.BOOTSTRAP_ADDR ] funded_channels = [ channel_state for channel_state in open_channels if channel_state.our_state.contract_balance >= self._initial_funding_per_partner ] nonfunded_channels = [ channel_state for channel_state in open_channels if channel_state not in funded_channels ] possible_new_partners = self._find_new_partners() if possible_new_partners == 0: return False # if we already met our target, break if len(funded_channels) >= self.initial_channel_target: return False # if we didn't, but there's no nonfunded channels and no available partners # it means the network is smaller than our target, so we should also break if not nonfunded_channels and possible_new_partners == 0: return False n_to_join = self.initial_channel_target - len(funded_channels) nonfunded_partners = [ channel_state.partner_state.address for channel_state in nonfunded_channels ] # first, fund nonfunded channels, then open and fund with possible_new_partners, # until initial_channel_target of funded channels is met join_partners = (nonfunded_partners + possible_new_partners)[:n_to_join] log.debug( 'Spawning greenlets to join partners', node=pex(self.raiden.address), num_greenlets=len(join_partners), ) greenlets = set( gevent.spawn(self._join_partner, partner) for partner in join_partners ) gevent.joinall(greenlets, raise_error=True) return True
python
def _open_channels(self) -> bool: """ Open channels until there are `self.initial_channel_target` channels open. Do nothing if there are enough channels open already. Note: - This method must be called with the lock held. Return: - False if no channels could be opened """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ) open_channels = [ channel_state for channel_state in open_channels if channel_state.partner_state.address != self.BOOTSTRAP_ADDR ] funded_channels = [ channel_state for channel_state in open_channels if channel_state.our_state.contract_balance >= self._initial_funding_per_partner ] nonfunded_channels = [ channel_state for channel_state in open_channels if channel_state not in funded_channels ] possible_new_partners = self._find_new_partners() if possible_new_partners == 0: return False # if we already met our target, break if len(funded_channels) >= self.initial_channel_target: return False # if we didn't, but there's no nonfunded channels and no available partners # it means the network is smaller than our target, so we should also break if not nonfunded_channels and possible_new_partners == 0: return False n_to_join = self.initial_channel_target - len(funded_channels) nonfunded_partners = [ channel_state.partner_state.address for channel_state in nonfunded_channels ] # first, fund nonfunded channels, then open and fund with possible_new_partners, # until initial_channel_target of funded channels is met join_partners = (nonfunded_partners + possible_new_partners)[:n_to_join] log.debug( 'Spawning greenlets to join partners', node=pex(self.raiden.address), num_greenlets=len(join_partners), ) greenlets = set( gevent.spawn(self._join_partner, partner) for partner in join_partners ) gevent.joinall(greenlets, raise_error=True) return True
[ "def", "_open_channels", "(", "self", ")", "->", "bool", ":", "open_channels", "=", "views", ".", "get_channelstate_open", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "payment_network_id", "=", "self", ".",...
Open channels until there are `self.initial_channel_target` channels open. Do nothing if there are enough channels open already. Note: - This method must be called with the lock held. Return: - False if no channels could be opened
[ "Open", "channels", "until", "there", "are", "self", ".", "initial_channel_target", "channels", "open", ".", "Do", "nothing", "if", "there", "are", "enough", "channels", "open", "already", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L375-L435
train
216,506
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._initial_funding_per_partner
def _initial_funding_per_partner(self) -> int: """The calculated funding per partner depending on configuration and overall funding of the ConnectionManager. Note: - This attribute must be accessed with the lock held. """ if self.initial_channel_target: return int( self.funds * (1 - self.joinable_funds_target) / self.initial_channel_target, ) return 0
python
def _initial_funding_per_partner(self) -> int: """The calculated funding per partner depending on configuration and overall funding of the ConnectionManager. Note: - This attribute must be accessed with the lock held. """ if self.initial_channel_target: return int( self.funds * (1 - self.joinable_funds_target) / self.initial_channel_target, ) return 0
[ "def", "_initial_funding_per_partner", "(", "self", ")", "->", "int", ":", "if", "self", ".", "initial_channel_target", ":", "return", "int", "(", "self", ".", "funds", "*", "(", "1", "-", "self", ".", "joinable_funds_target", ")", "/", "self", ".", "initi...
The calculated funding per partner depending on configuration and overall funding of the ConnectionManager. Note: - This attribute must be accessed with the lock held.
[ "The", "calculated", "funding", "per", "partner", "depending", "on", "configuration", "and", "overall", "funding", "of", "the", "ConnectionManager", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L438-L451
train
216,507
raiden-network/raiden
raiden/connection_manager.py
ConnectionManager._funds_remaining
def _funds_remaining(self) -> int: """The remaining funds after subtracting the already deposited amounts. Note: - This attribute must be accessed with the lock held. """ if self.funds > 0: token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) sum_deposits = views.get_our_capacity_for_token_network( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) return min(self.funds - sum_deposits, token_balance) return 0
python
def _funds_remaining(self) -> int: """The remaining funds after subtracting the already deposited amounts. Note: - This attribute must be accessed with the lock held. """ if self.funds > 0: token = self.raiden.chain.token(self.token_address) token_balance = token.balance_of(self.raiden.address) sum_deposits = views.get_our_capacity_for_token_network( views.state_from_raiden(self.raiden), self.registry_address, self.token_address, ) return min(self.funds - sum_deposits, token_balance) return 0
[ "def", "_funds_remaining", "(", "self", ")", "->", "int", ":", "if", "self", ".", "funds", ">", "0", ":", "token", "=", "self", ".", "raiden", ".", "chain", ".", "token", "(", "self", ".", "token_address", ")", "token_balance", "=", "token", ".", "ba...
The remaining funds after subtracting the already deposited amounts. Note: - This attribute must be accessed with the lock held.
[ "The", "remaining", "funds", "after", "subtracting", "the", "already", "deposited", "amounts", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L454-L471
train
216,508
raiden-network/raiden
tools/debugging/replay_wal.py
Translator._make_regex
def _make_regex(self): """ Compile rxp with all keys concatenated. """ rxp = "|".join( map(self._address_rxp, self.keys()), ) self._regex = re.compile( rxp, re.IGNORECASE, )
python
def _make_regex(self): """ Compile rxp with all keys concatenated. """ rxp = "|".join( map(self._address_rxp, self.keys()), ) self._regex = re.compile( rxp, re.IGNORECASE, )
[ "def", "_make_regex", "(", "self", ")", ":", "rxp", "=", "\"|\"", ".", "join", "(", "map", "(", "self", ".", "_address_rxp", ",", "self", ".", "keys", "(", ")", ")", ",", ")", "self", ".", "_regex", "=", "re", ".", "compile", "(", "rxp", ",", "...
Compile rxp with all keys concatenated.
[ "Compile", "rxp", "with", "all", "keys", "concatenated", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/debugging/replay_wal.py#L97-L105
train
216,509
raiden-network/raiden
raiden/api/v1/resources.py
TokensResource.get
def get(self): """ this translates to 'get all token addresses we have channels open for' """ return self.rest_api.get_tokens_list( self.rest_api.raiden_api.raiden.default_registry.address, )
python
def get(self): """ this translates to 'get all token addresses we have channels open for' """ return self.rest_api.get_tokens_list( self.rest_api.raiden_api.raiden.default_registry.address, )
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "rest_api", ".", "get_tokens_list", "(", "self", ".", "rest_api", ".", "raiden_api", ".", "raiden", ".", "default_registry", ".", "address", ",", ")" ]
this translates to 'get all token addresses we have channels open for'
[ "this", "translates", "to", "get", "all", "token", "addresses", "we", "have", "channels", "open", "for" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/v1/resources.py#L88-L94
train
216,510
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
is_safe_to_wait
def is_safe_to_wait( lock_expiration: BlockExpiration, reveal_timeout: BlockTimeout, block_number: BlockNumber, ) -> SuccessOrError: """ True if waiting is safe, i.e. there are more than enough blocks to safely unlock on chain. """ # reveal timeout will not ever be larger than the lock_expiration otherwise # the expected block_number is negative assert block_number > 0 assert reveal_timeout > 0 assert lock_expiration > reveal_timeout lock_timeout = lock_expiration - block_number # A node may wait for a new balance proof while there are reveal_timeout # blocks left, at that block and onwards it is not safe to wait. if lock_timeout > reveal_timeout: return True, None msg = ( f'lock timeout is unsafe.' f' timeout must be larger than {reveal_timeout}, but it is {lock_timeout}.' f' expiration: {lock_expiration} block_number: {block_number}' ) return False, msg
python
def is_safe_to_wait( lock_expiration: BlockExpiration, reveal_timeout: BlockTimeout, block_number: BlockNumber, ) -> SuccessOrError: """ True if waiting is safe, i.e. there are more than enough blocks to safely unlock on chain. """ # reveal timeout will not ever be larger than the lock_expiration otherwise # the expected block_number is negative assert block_number > 0 assert reveal_timeout > 0 assert lock_expiration > reveal_timeout lock_timeout = lock_expiration - block_number # A node may wait for a new balance proof while there are reveal_timeout # blocks left, at that block and onwards it is not safe to wait. if lock_timeout > reveal_timeout: return True, None msg = ( f'lock timeout is unsafe.' f' timeout must be larger than {reveal_timeout}, but it is {lock_timeout}.' f' expiration: {lock_expiration} block_number: {block_number}' ) return False, msg
[ "def", "is_safe_to_wait", "(", "lock_expiration", ":", "BlockExpiration", ",", "reveal_timeout", ":", "BlockTimeout", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "SuccessOrError", ":", "# reveal timeout will not ever be larger than the lock_expiration otherwise", ...
True if waiting is safe, i.e. there are more than enough blocks to safely unlock on chain.
[ "True", "if", "waiting", "is", "safe", "i", ".", "e", ".", "there", "are", "more", "than", "enough", "blocks", "to", "safely", "unlock", "on", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L103-L129
train
216,511
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
is_send_transfer_almost_equal
def is_send_transfer_almost_equal( send_channel: NettingChannelState, send: LockedTransferUnsignedState, received: LockedTransferSignedState, ) -> bool: """ True if both transfers are for the same mediated transfer. """ # The only thing that may change is the direction of the transfer return ( isinstance(send, LockedTransferUnsignedState) and isinstance(received, LockedTransferSignedState) and send.payment_identifier == received.payment_identifier and send.token == received.token and send.lock.amount == received.lock.amount - send_channel.mediation_fee and send.lock.expiration == received.lock.expiration and send.lock.secrethash == received.lock.secrethash and send.initiator == received.initiator and send.target == received.target )
python
def is_send_transfer_almost_equal( send_channel: NettingChannelState, send: LockedTransferUnsignedState, received: LockedTransferSignedState, ) -> bool: """ True if both transfers are for the same mediated transfer. """ # The only thing that may change is the direction of the transfer return ( isinstance(send, LockedTransferUnsignedState) and isinstance(received, LockedTransferSignedState) and send.payment_identifier == received.payment_identifier and send.token == received.token and send.lock.amount == received.lock.amount - send_channel.mediation_fee and send.lock.expiration == received.lock.expiration and send.lock.secrethash == received.lock.secrethash and send.initiator == received.initiator and send.target == received.target )
[ "def", "is_send_transfer_almost_equal", "(", "send_channel", ":", "NettingChannelState", ",", "send", ":", "LockedTransferUnsignedState", ",", "received", ":", "LockedTransferSignedState", ",", ")", "->", "bool", ":", "# The only thing that may change is the direction of the tr...
True if both transfers are for the same mediated transfer.
[ "True", "if", "both", "transfers", "are", "for", "the", "same", "mediated", "transfer", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L154-L171
train
216,512
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
filter_reachable_routes
def filter_reachable_routes( routes: List[RouteState], nodeaddresses_to_networkstates: NodeNetworkStateMap, ) -> List[RouteState]: """This function makes sure we use reachable routes only.""" reachable_routes = [] for route in routes: node_network_state = nodeaddresses_to_networkstates.get( route.node_address, NODE_NETWORK_UNREACHABLE, ) if node_network_state == NODE_NETWORK_REACHABLE: reachable_routes.append(route) return reachable_routes
python
def filter_reachable_routes( routes: List[RouteState], nodeaddresses_to_networkstates: NodeNetworkStateMap, ) -> List[RouteState]: """This function makes sure we use reachable routes only.""" reachable_routes = [] for route in routes: node_network_state = nodeaddresses_to_networkstates.get( route.node_address, NODE_NETWORK_UNREACHABLE, ) if node_network_state == NODE_NETWORK_REACHABLE: reachable_routes.append(route) return reachable_routes
[ "def", "filter_reachable_routes", "(", "routes", ":", "List", "[", "RouteState", "]", ",", "nodeaddresses_to_networkstates", ":", "NodeNetworkStateMap", ",", ")", "->", "List", "[", "RouteState", "]", ":", "reachable_routes", "=", "[", "]", "for", "route", "in",...
This function makes sure we use reachable routes only.
[ "This", "function", "makes", "sure", "we", "use", "reachable", "routes", "only", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L198-L214
train
216,513
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
filter_used_routes
def filter_used_routes( transfers_pair: List[MediationPairState], routes: List[RouteState], ) -> List[RouteState]: """This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through 3 will also try 5 before sending it backwards to 1 1 -> 2 -> 3 -> 4 v ^ 5 -> 6 -> 7 This function will return routes as provided in their original order. """ channelid_to_route = {r.channel_identifier: r for r in routes} routes_order = {route.node_address: index for index, route in enumerate(routes)} for pair in transfers_pair: channelid = pair.payer_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] channelid = pair.payee_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] return sorted( channelid_to_route.values(), key=lambda route: routes_order[route.node_address], )
python
def filter_used_routes( transfers_pair: List[MediationPairState], routes: List[RouteState], ) -> List[RouteState]: """This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through 3 will also try 5 before sending it backwards to 1 1 -> 2 -> 3 -> 4 v ^ 5 -> 6 -> 7 This function will return routes as provided in their original order. """ channelid_to_route = {r.channel_identifier: r for r in routes} routes_order = {route.node_address: index for index, route in enumerate(routes)} for pair in transfers_pair: channelid = pair.payer_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] channelid = pair.payee_transfer.balance_proof.channel_identifier if channelid in channelid_to_route: del channelid_to_route[channelid] return sorted( channelid_to_route.values(), key=lambda route: routes_order[route.node_address], )
[ "def", "filter_used_routes", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "routes", ":", "List", "[", "RouteState", "]", ",", ")", "->", "List", "[", "RouteState", "]", ":", "channelid_to_route", "=", "{", "r", ".", "channel_ident...
This function makes sure we filter routes that have already been used. So in a setup like this, we want to make sure that node 2, having tried to route the transfer through 3 will also try 5 before sending it backwards to 1 1 -> 2 -> 3 -> 4 v ^ 5 -> 6 -> 7 This function will return routes as provided in their original order.
[ "This", "function", "makes", "sure", "we", "filter", "routes", "that", "have", "already", "been", "used", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L217-L246
train
216,514
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_payee_channel
def get_payee_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: """ Returns the payee channel of a given transfer pair or None if it's not found """ payee_channel_identifier = transfer_pair.payee_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payee_channel_identifier)
python
def get_payee_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: """ Returns the payee channel of a given transfer pair or None if it's not found """ payee_channel_identifier = transfer_pair.payee_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payee_channel_identifier)
[ "def", "get_payee_channel", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfer_pair", ":", "MediationPairState", ",", ")", "->", "Optional", "[", "NettingChannelState", "]", ":", "payee_channel_identifier", "=", "transfer_pair", ".", "payee_transfer"...
Returns the payee channel of a given transfer pair or None if it's not found
[ "Returns", "the", "payee", "channel", "of", "a", "given", "transfer", "pair", "or", "None", "if", "it", "s", "not", "found" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L249-L255
train
216,515
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_payer_channel
def get_payer_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: """ Returns the payer channel of a given transfer pair or None if it's not found """ payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payer_channel_identifier)
python
def get_payer_channel( channelidentifiers_to_channels: ChannelMap, transfer_pair: MediationPairState, ) -> Optional[NettingChannelState]: """ Returns the payer channel of a given transfer pair or None if it's not found """ payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_identifier return channelidentifiers_to_channels.get(payer_channel_identifier)
[ "def", "get_payer_channel", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfer_pair", ":", "MediationPairState", ",", ")", "->", "Optional", "[", "NettingChannelState", "]", ":", "payer_channel_identifier", "=", "transfer_pair", ".", "payer_transfer"...
Returns the payer channel of a given transfer pair or None if it's not found
[ "Returns", "the", "payer", "channel", "of", "a", "given", "transfer", "pair", "or", "None", "if", "it", "s", "not", "found" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L258-L264
train
216,516
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_pending_transfer_pairs
def get_pending_transfer_pairs( transfers_pair: List[MediationPairState], ) -> List[MediationPairState]: """ Return the transfer pairs that are not at a final state. """ pending_pairs = list( pair for pair in transfers_pair if pair.payee_state not in STATE_TRANSFER_FINAL or pair.payer_state not in STATE_TRANSFER_FINAL ) return pending_pairs
python
def get_pending_transfer_pairs( transfers_pair: List[MediationPairState], ) -> List[MediationPairState]: """ Return the transfer pairs that are not at a final state. """ pending_pairs = list( pair for pair in transfers_pair if pair.payee_state not in STATE_TRANSFER_FINAL or pair.payer_state not in STATE_TRANSFER_FINAL ) return pending_pairs
[ "def", "get_pending_transfer_pairs", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", ")", "->", "List", "[", "MediationPairState", "]", ":", "pending_pairs", "=", "list", "(", "pair", "for", "pair", "in", "transfers_pair", "if", "pair", ...
Return the transfer pairs that are not at a final state.
[ "Return", "the", "transfer", "pairs", "that", "are", "not", "at", "a", "final", "state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L267-L277
train
216,517
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
get_lock_amount_after_fees
def get_lock_amount_after_fees( lock: HashTimeLockState, payee_channel: NettingChannelState, ) -> PaymentWithFeeAmount: """ Return the lock.amount after fees are taken. Fees are taken only for the outgoing channel, which is the one with collateral locked from this node. """ return PaymentWithFeeAmount(lock.amount - payee_channel.mediation_fee)
python
def get_lock_amount_after_fees( lock: HashTimeLockState, payee_channel: NettingChannelState, ) -> PaymentWithFeeAmount: """ Return the lock.amount after fees are taken. Fees are taken only for the outgoing channel, which is the one with collateral locked from this node. """ return PaymentWithFeeAmount(lock.amount - payee_channel.mediation_fee)
[ "def", "get_lock_amount_after_fees", "(", "lock", ":", "HashTimeLockState", ",", "payee_channel", ":", "NettingChannelState", ",", ")", "->", "PaymentWithFeeAmount", ":", "return", "PaymentWithFeeAmount", "(", "lock", ".", "amount", "-", "payee_channel", ".", "mediati...
Return the lock.amount after fees are taken. Fees are taken only for the outgoing channel, which is the one with collateral locked from this node.
[ "Return", "the", "lock", ".", "amount", "after", "fees", "are", "taken", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L280-L290
train
216,518
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
sanity_check
def sanity_check( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, ) -> None: """ Check invariants that must hold. """ # if a transfer is paid we must know the secret all_transfers_states = itertools.chain( (pair.payee_state for pair in state.transfers_pair), (pair.payer_state for pair in state.transfers_pair), ) if any(state in STATE_TRANSFER_PAID for state in all_transfers_states): assert state.secret is not None # the "transitivity" for these values is checked below as part of # almost_equal check if state.transfers_pair: first_pair = state.transfers_pair[0] assert state.secrethash == first_pair.payer_transfer.lock.secrethash for pair in state.transfers_pair: payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=pair, ) # Channel could have been removed if not payee_channel: continue assert is_send_transfer_almost_equal( send_channel=payee_channel, send=pair.payee_transfer, received=pair.payer_transfer, ) assert pair.payer_state in pair.valid_payer_states assert pair.payee_state in pair.valid_payee_states for original, refund in zip(state.transfers_pair[:-1], state.transfers_pair[1:]): assert original.payee_address == refund.payer_address payer_channel = get_payer_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=refund, ) # Channel could have been removed if not payer_channel: continue transfer_sent = original.payee_transfer transfer_received = refund.payer_transfer assert is_send_transfer_almost_equal( send_channel=payer_channel, send=transfer_sent, received=transfer_received, ) if state.waiting_transfer and state.transfers_pair: last_transfer_pair = state.transfers_pair[-1] payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=last_transfer_pair, ) # Channel could have been removed if payee_channel: transfer_sent = last_transfer_pair.payee_transfer transfer_received = state.waiting_transfer.transfer assert is_send_transfer_almost_equal( send_channel=payee_channel, send=transfer_sent, received=transfer_received, )
python
def sanity_check( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, ) -> None: """ Check invariants that must hold. """ # if a transfer is paid we must know the secret all_transfers_states = itertools.chain( (pair.payee_state for pair in state.transfers_pair), (pair.payer_state for pair in state.transfers_pair), ) if any(state in STATE_TRANSFER_PAID for state in all_transfers_states): assert state.secret is not None # the "transitivity" for these values is checked below as part of # almost_equal check if state.transfers_pair: first_pair = state.transfers_pair[0] assert state.secrethash == first_pair.payer_transfer.lock.secrethash for pair in state.transfers_pair: payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=pair, ) # Channel could have been removed if not payee_channel: continue assert is_send_transfer_almost_equal( send_channel=payee_channel, send=pair.payee_transfer, received=pair.payer_transfer, ) assert pair.payer_state in pair.valid_payer_states assert pair.payee_state in pair.valid_payee_states for original, refund in zip(state.transfers_pair[:-1], state.transfers_pair[1:]): assert original.payee_address == refund.payer_address payer_channel = get_payer_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=refund, ) # Channel could have been removed if not payer_channel: continue transfer_sent = original.payee_transfer transfer_received = refund.payer_transfer assert is_send_transfer_almost_equal( send_channel=payer_channel, send=transfer_sent, received=transfer_received, ) if state.waiting_transfer and state.transfers_pair: last_transfer_pair = state.transfers_pair[-1] payee_channel = get_payee_channel( channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_pair=last_transfer_pair, ) # Channel could have been removed if payee_channel: transfer_sent = last_transfer_pair.payee_transfer transfer_received = state.waiting_transfer.transfer assert is_send_transfer_almost_equal( send_channel=payee_channel, send=transfer_sent, received=transfer_received, )
[ "def", "sanity_check", "(", "state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "None", ":", "# if a transfer is paid we must know the secret", "all_transfers_states", "=", "itertools", ".", "chain", "(", "(", ...
Check invariants that must hold.
[ "Check", "invariants", "that", "must", "hold", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L293-L365
train
216,519
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
clear_if_finalized
def clear_if_finalized( iteration: TransitionResult, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: """Clear the mediator task if all the locks have been finalized. A lock is considered finalized if it has been removed from the merkle tree offchain, either because the transfer was unlocked or expired, or because the channel was settled on chain and therefore the channel is removed.""" state = cast(MediatorTransferState, iteration.new_state) if state is None: return iteration # Only clear the task if all channels have the lock cleared. secrethash = state.secrethash for pair in state.transfers_pair: payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) if payer_channel and channel.is_lock_pending(payer_channel.partner_state, secrethash): return iteration payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) if payee_channel and channel.is_lock_pending(payee_channel.our_state, secrethash): return iteration if state.waiting_transfer: waiting_transfer = state.waiting_transfer.transfer waiting_channel_identifier = waiting_transfer.balance_proof.channel_identifier waiting_channel = channelidentifiers_to_channels.get(waiting_channel_identifier) if waiting_channel and channel.is_lock_pending(waiting_channel.partner_state, secrethash): return iteration return TransitionResult(None, iteration.events)
python
def clear_if_finalized( iteration: TransitionResult, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: """Clear the mediator task if all the locks have been finalized. A lock is considered finalized if it has been removed from the merkle tree offchain, either because the transfer was unlocked or expired, or because the channel was settled on chain and therefore the channel is removed.""" state = cast(MediatorTransferState, iteration.new_state) if state is None: return iteration # Only clear the task if all channels have the lock cleared. secrethash = state.secrethash for pair in state.transfers_pair: payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) if payer_channel and channel.is_lock_pending(payer_channel.partner_state, secrethash): return iteration payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) if payee_channel and channel.is_lock_pending(payee_channel.our_state, secrethash): return iteration if state.waiting_transfer: waiting_transfer = state.waiting_transfer.transfer waiting_channel_identifier = waiting_transfer.balance_proof.channel_identifier waiting_channel = channelidentifiers_to_channels.get(waiting_channel_identifier) if waiting_channel and channel.is_lock_pending(waiting_channel.partner_state, secrethash): return iteration return TransitionResult(None, iteration.events)
[ "def", "clear_if_finalized", "(", "iteration", ":", "TransitionResult", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "TransitionResult", "[", "MediatorTransferState", "]", ":", "state", "=", "cast", "(", "MediatorTransferState", ",", "iter...
Clear the mediator task if all the locks have been finalized. A lock is considered finalized if it has been removed from the merkle tree offchain, either because the transfer was unlocked or expired, or because the channel was settled on chain and therefore the channel is removed.
[ "Clear", "the", "mediator", "task", "if", "all", "the", "locks", "have", "been", "finalized", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L368-L401
train
216,520
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
forward_transfer_pair
def forward_transfer_pair( payer_transfer: LockedTransferSignedState, available_routes: List['RouteState'], channelidentifiers_to_channels: Dict, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: """ Given a payer transfer tries a new route to proceed with the mediation. Args: payer_transfer: The transfer received from the payer_channel. available_routes: Current available routes that may be used, it's assumed that the routes list is ordered from best to worst. channelidentifiers_to_channels: All the channels available for this transfer. pseudo_random_generator: Number generator to generate a message id. block_number: The current block number. """ transfer_pair = None mediated_events: List[Event] = list() lock_timeout = BlockTimeout(payer_transfer.lock.expiration - block_number) payee_channel = next_channel_from_routes( available_routes=available_routes, channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_amount=payer_transfer.lock.amount, lock_timeout=lock_timeout, ) if payee_channel: assert payee_channel.settle_timeout >= lock_timeout assert payee_channel.token_address == payer_transfer.token message_identifier = message_identifier_from_prng(pseudo_random_generator) lock = payer_transfer.lock lockedtransfer_event = channel.send_lockedtransfer( channel_state=payee_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, payee_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) assert lockedtransfer_event transfer_pair = MediationPairState( payer_transfer, payee_channel.partner_state.address, lockedtransfer_event.transfer, ) mediated_events = [lockedtransfer_event] return ( transfer_pair, mediated_events, )
python
def forward_transfer_pair( payer_transfer: LockedTransferSignedState, available_routes: List['RouteState'], channelidentifiers_to_channels: Dict, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: """ Given a payer transfer tries a new route to proceed with the mediation. Args: payer_transfer: The transfer received from the payer_channel. available_routes: Current available routes that may be used, it's assumed that the routes list is ordered from best to worst. channelidentifiers_to_channels: All the channels available for this transfer. pseudo_random_generator: Number generator to generate a message id. block_number: The current block number. """ transfer_pair = None mediated_events: List[Event] = list() lock_timeout = BlockTimeout(payer_transfer.lock.expiration - block_number) payee_channel = next_channel_from_routes( available_routes=available_routes, channelidentifiers_to_channels=channelidentifiers_to_channels, transfer_amount=payer_transfer.lock.amount, lock_timeout=lock_timeout, ) if payee_channel: assert payee_channel.settle_timeout >= lock_timeout assert payee_channel.token_address == payer_transfer.token message_identifier = message_identifier_from_prng(pseudo_random_generator) lock = payer_transfer.lock lockedtransfer_event = channel.send_lockedtransfer( channel_state=payee_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, payee_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) assert lockedtransfer_event transfer_pair = MediationPairState( payer_transfer, payee_channel.partner_state.address, lockedtransfer_event.transfer, ) mediated_events = [lockedtransfer_event] return ( transfer_pair, mediated_events, )
[ "def", "forward_transfer_pair", "(", "payer_transfer", ":", "LockedTransferSignedState", ",", "available_routes", ":", "List", "[", "'RouteState'", "]", ",", "channelidentifiers_to_channels", ":", "Dict", ",", "pseudo_random_generator", ":", "random", ".", "Random", ","...
Given a payer transfer tries a new route to proceed with the mediation. Args: payer_transfer: The transfer received from the payer_channel. available_routes: Current available routes that may be used, it's assumed that the routes list is ordered from best to worst. channelidentifiers_to_channels: All the channels available for this transfer. pseudo_random_generator: Number generator to generate a message id. block_number: The current block number.
[ "Given", "a", "payer", "transfer", "tries", "a", "new", "route", "to", "proceed", "with", "the", "mediation", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L438-L496
train
216,521
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
backward_transfer_pair
def backward_transfer_pair( backward_channel: NettingChannelState, payer_transfer: LockedTransferSignedState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: """ Sends a transfer backwards, allowing the previous hop to try a new route. When all the routes available for this node failed, send a transfer backwards with the same amount and secrethash, allowing the previous hop to do a retry. Args: backward_channel: The original channel which sent the mediated transfer to this node. payer_transfer: The *latest* payer transfer which is backing the mediation. block_number: The current block number. Returns: The mediator pair and the correspoding refund event. """ transfer_pair = None events: List[Event] = list() lock = payer_transfer.lock lock_timeout = BlockTimeout(lock.expiration - block_number) # Ensure the refund transfer's lock has a safe expiration, otherwise don't # do anything and wait for the received lock to expire. if is_channel_usable(backward_channel, lock.amount, lock_timeout): message_identifier = message_identifier_from_prng(pseudo_random_generator) refund_transfer = channel.send_refundtransfer( channel_state=backward_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, backward_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) transfer_pair = MediationPairState( payer_transfer, backward_channel.partner_state.address, refund_transfer.transfer, ) events.append(refund_transfer) return (transfer_pair, events)
python
def backward_transfer_pair( backward_channel: NettingChannelState, payer_transfer: LockedTransferSignedState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> Tuple[Optional[MediationPairState], List[Event]]: """ Sends a transfer backwards, allowing the previous hop to try a new route. When all the routes available for this node failed, send a transfer backwards with the same amount and secrethash, allowing the previous hop to do a retry. Args: backward_channel: The original channel which sent the mediated transfer to this node. payer_transfer: The *latest* payer transfer which is backing the mediation. block_number: The current block number. Returns: The mediator pair and the correspoding refund event. """ transfer_pair = None events: List[Event] = list() lock = payer_transfer.lock lock_timeout = BlockTimeout(lock.expiration - block_number) # Ensure the refund transfer's lock has a safe expiration, otherwise don't # do anything and wait for the received lock to expire. if is_channel_usable(backward_channel, lock.amount, lock_timeout): message_identifier = message_identifier_from_prng(pseudo_random_generator) refund_transfer = channel.send_refundtransfer( channel_state=backward_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, backward_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash, ) transfer_pair = MediationPairState( payer_transfer, backward_channel.partner_state.address, refund_transfer.transfer, ) events.append(refund_transfer) return (transfer_pair, events)
[ "def", "backward_transfer_pair", "(", "backward_channel", ":", "NettingChannelState", ",", "payer_transfer", ":", "LockedTransferSignedState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "Tuple",...
Sends a transfer backwards, allowing the previous hop to try a new route. When all the routes available for this node failed, send a transfer backwards with the same amount and secrethash, allowing the previous hop to do a retry. Args: backward_channel: The original channel which sent the mediated transfer to this node. payer_transfer: The *latest* payer transfer which is backing the mediation. block_number: The current block number. Returns: The mediator pair and the correspoding refund event.
[ "Sends", "a", "transfer", "backwards", "allowing", "the", "previous", "hop", "to", "try", "a", "new", "route", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L499-L551
train
216,522
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_expired_pairs
def events_for_expired_pairs( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], waiting_transfer: Optional[WaitingTransferState], block_number: BlockNumber, ) -> List[Event]: """ Informational events for expired locks. """ pending_transfers_pairs = get_pending_transfer_pairs(transfers_pair) events: List[Event] = list() for pair in pending_transfers_pairs: payer_balance_proof = pair.payer_transfer.balance_proof payer_channel = channelidentifiers_to_channels.get(payer_balance_proof.channel_identifier) if not payer_channel: continue has_payer_transfer_expired = channel.is_transfer_expired( transfer=pair.payer_transfer, affected_channel=payer_channel, block_number=block_number, ) if has_payer_transfer_expired: # For safety, the correct behavior is: # # - If the payee has been paid, then the payer must pay too. # # And the corollary: # # - If the payer transfer has expired, then the payee transfer must # have expired too. # # The problem is that this corollary cannot be asserted. If a user # is running Raiden without a monitoring service, then it may go # offline after having paid a transfer to a payee, but without # getting a balance proof of the payer, and once it comes back # online the transfer may have expired. # # assert pair.payee_state == 'payee_expired' pair.payer_state = 'payer_expired' unlock_claim_failed = EventUnlockClaimFailed( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) if waiting_transfer and waiting_transfer.state != 'expired': waiting_transfer.state = 'expired' unlock_claim_failed = EventUnlockClaimFailed( waiting_transfer.transfer.payment_identifier, waiting_transfer.transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) return events
python
def events_for_expired_pairs( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], waiting_transfer: Optional[WaitingTransferState], block_number: BlockNumber, ) -> List[Event]: """ Informational events for expired locks. """ pending_transfers_pairs = get_pending_transfer_pairs(transfers_pair) events: List[Event] = list() for pair in pending_transfers_pairs: payer_balance_proof = pair.payer_transfer.balance_proof payer_channel = channelidentifiers_to_channels.get(payer_balance_proof.channel_identifier) if not payer_channel: continue has_payer_transfer_expired = channel.is_transfer_expired( transfer=pair.payer_transfer, affected_channel=payer_channel, block_number=block_number, ) if has_payer_transfer_expired: # For safety, the correct behavior is: # # - If the payee has been paid, then the payer must pay too. # # And the corollary: # # - If the payer transfer has expired, then the payee transfer must # have expired too. # # The problem is that this corollary cannot be asserted. If a user # is running Raiden without a monitoring service, then it may go # offline after having paid a transfer to a payee, but without # getting a balance proof of the payer, and once it comes back # online the transfer may have expired. # # assert pair.payee_state == 'payee_expired' pair.payer_state = 'payer_expired' unlock_claim_failed = EventUnlockClaimFailed( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) if waiting_transfer and waiting_transfer.state != 'expired': waiting_transfer.state = 'expired' unlock_claim_failed = EventUnlockClaimFailed( waiting_transfer.transfer.payment_identifier, waiting_transfer.transfer.lock.secrethash, 'lock expired', ) events.append(unlock_claim_failed) return events
[ "def", "events_for_expired_pairs", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "waiting_transfer", ":", "Optional", "[", "WaitingTransferState", "]", ",", "block_number", ":", "BlockN...
Informational events for expired locks.
[ "Informational", "events", "for", "expired", "locks", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L681-L738
train
216,523
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_secretreveal
def events_for_secretreveal( transfers_pair: List[MediationPairState], secret: Secret, pseudo_random_generator: random.Random, ) -> List[Event]: """ Reveal the secret off-chain. The secret is revealed off-chain even if there is a pending transaction to reveal it on-chain, this allows the unlock to happen off-chain, which is faster. This node is named N, suppose there is a mediated transfer with two refund transfers, one from B and one from C: A-N-B...B-N-C..C-N-D Under normal operation N will first learn the secret from D, then reveal to C, wait for C to inform the secret is known before revealing it to B, and again wait for B before revealing the secret to A. If B somehow sent a reveal secret before C and D, then the secret will be revealed to A, but not C and D, meaning the secret won't be propagated forward. Even if D sent a reveal secret at about the same time, the secret will only be revealed to B upon confirmation from C. If the proof doesn't arrive in time and the lock's expiration is at risk, N won't lose tokens since it knows the secret can go on-chain at any time. """ events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payer_knows_secret = pair.payer_state in STATE_SECRET_KNOWN is_transfer_pending = pair.payer_state == 'payer_pending' should_send_secret = ( payee_knows_secret and not payer_knows_secret and is_transfer_pending ) if should_send_secret: message_identifier = message_identifier_from_prng(pseudo_random_generator) pair.payer_state = 'payer_secret_revealed' payer_transfer = pair.payer_transfer revealsecret = SendSecretReveal( recipient=payer_transfer.balance_proof.sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=message_identifier, secret=secret, ) events.append(revealsecret) return events
python
def events_for_secretreveal( transfers_pair: List[MediationPairState], secret: Secret, pseudo_random_generator: random.Random, ) -> List[Event]: """ Reveal the secret off-chain. The secret is revealed off-chain even if there is a pending transaction to reveal it on-chain, this allows the unlock to happen off-chain, which is faster. This node is named N, suppose there is a mediated transfer with two refund transfers, one from B and one from C: A-N-B...B-N-C..C-N-D Under normal operation N will first learn the secret from D, then reveal to C, wait for C to inform the secret is known before revealing it to B, and again wait for B before revealing the secret to A. If B somehow sent a reveal secret before C and D, then the secret will be revealed to A, but not C and D, meaning the secret won't be propagated forward. Even if D sent a reveal secret at about the same time, the secret will only be revealed to B upon confirmation from C. If the proof doesn't arrive in time and the lock's expiration is at risk, N won't lose tokens since it knows the secret can go on-chain at any time. """ events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payer_knows_secret = pair.payer_state in STATE_SECRET_KNOWN is_transfer_pending = pair.payer_state == 'payer_pending' should_send_secret = ( payee_knows_secret and not payer_knows_secret and is_transfer_pending ) if should_send_secret: message_identifier = message_identifier_from_prng(pseudo_random_generator) pair.payer_state = 'payer_secret_revealed' payer_transfer = pair.payer_transfer revealsecret = SendSecretReveal( recipient=payer_transfer.balance_proof.sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=message_identifier, secret=secret, ) events.append(revealsecret) return events
[ "def", "events_for_secretreveal", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "secret", ":", "Secret", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", "List", "[", "Event", "]", ":", "events", ":", "...
Reveal the secret off-chain. The secret is revealed off-chain even if there is a pending transaction to reveal it on-chain, this allows the unlock to happen off-chain, which is faster. This node is named N, suppose there is a mediated transfer with two refund transfers, one from B and one from C: A-N-B...B-N-C..C-N-D Under normal operation N will first learn the secret from D, then reveal to C, wait for C to inform the secret is known before revealing it to B, and again wait for B before revealing the secret to A. If B somehow sent a reveal secret before C and D, then the secret will be revealed to A, but not C and D, meaning the secret won't be propagated forward. Even if D sent a reveal secret at about the same time, the secret will only be revealed to B upon confirmation from C. If the proof doesn't arrive in time and the lock's expiration is at risk, N won't lose tokens since it knows the secret can go on-chain at any time.
[ "Reveal", "the", "secret", "off", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L741-L794
train
216,524
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_balanceproof
def events_for_balanceproof( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], pseudo_random_generator: random.Random, block_number: BlockNumber, secret: Secret, secrethash: SecretHash, ) -> List[Event]: """ While it's safe do the off-chain unlock. """ events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payee_payed = pair.payee_state in STATE_TRANSFER_PAID payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) payee_channel_open = ( payee_channel and channel.get_status(payee_channel) == CHANNEL_STATE_OPENED ) payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) # The mediator must not send to the payee a balance proof if the lock # is in the danger zone, because the payer may not do the same and the # on-chain unlock may fail. If the lock is nearing it's expiration # block, then on-chain unlock should be done, and if successful it can # be unlocked off-chain. is_safe_to_send_balanceproof = False if payer_channel: is_safe_to_send_balanceproof, _ = is_safe_to_wait( pair.payer_transfer.lock.expiration, payer_channel.reveal_timeout, block_number, ) should_send_balanceproof_to_payee = ( payee_channel_open and payee_knows_secret and not payee_payed and is_safe_to_send_balanceproof ) if should_send_balanceproof_to_payee: # At this point we are sure that payee_channel exists due to the # payee_channel_open check above. So let mypy know about this assert payee_channel payee_channel = cast(NettingChannelState, payee_channel) pair.payee_state = 'payee_balance_proof' message_identifier = message_identifier_from_prng(pseudo_random_generator) unlock_lock = channel.send_unlock( channel_state=payee_channel, message_identifier=message_identifier, payment_identifier=pair.payee_transfer.payment_identifier, secret=secret, secrethash=secrethash, ) unlock_success = EventUnlockSuccess( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, ) events.append(unlock_lock) events.append(unlock_success) return events
python
def events_for_balanceproof( channelidentifiers_to_channels: ChannelMap, transfers_pair: List[MediationPairState], pseudo_random_generator: random.Random, block_number: BlockNumber, secret: Secret, secrethash: SecretHash, ) -> List[Event]: """ While it's safe do the off-chain unlock. """ events: List[Event] = list() for pair in reversed(transfers_pair): payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN payee_payed = pair.payee_state in STATE_TRANSFER_PAID payee_channel = get_payee_channel(channelidentifiers_to_channels, pair) payee_channel_open = ( payee_channel and channel.get_status(payee_channel) == CHANNEL_STATE_OPENED ) payer_channel = get_payer_channel(channelidentifiers_to_channels, pair) # The mediator must not send to the payee a balance proof if the lock # is in the danger zone, because the payer may not do the same and the # on-chain unlock may fail. If the lock is nearing it's expiration # block, then on-chain unlock should be done, and if successful it can # be unlocked off-chain. is_safe_to_send_balanceproof = False if payer_channel: is_safe_to_send_balanceproof, _ = is_safe_to_wait( pair.payer_transfer.lock.expiration, payer_channel.reveal_timeout, block_number, ) should_send_balanceproof_to_payee = ( payee_channel_open and payee_knows_secret and not payee_payed and is_safe_to_send_balanceproof ) if should_send_balanceproof_to_payee: # At this point we are sure that payee_channel exists due to the # payee_channel_open check above. So let mypy know about this assert payee_channel payee_channel = cast(NettingChannelState, payee_channel) pair.payee_state = 'payee_balance_proof' message_identifier = message_identifier_from_prng(pseudo_random_generator) unlock_lock = channel.send_unlock( channel_state=payee_channel, message_identifier=message_identifier, payment_identifier=pair.payee_transfer.payment_identifier, secret=secret, secrethash=secrethash, ) unlock_success = EventUnlockSuccess( pair.payer_transfer.payment_identifier, pair.payer_transfer.lock.secrethash, ) events.append(unlock_lock) events.append(unlock_success) return events
[ "def", "events_for_balanceproof", "(", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", "block_number", ":", "BlockNumber", ",", ...
While it's safe do the off-chain unlock.
[ "While", "it", "s", "safe", "do", "the", "off", "-", "chain", "unlock", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L797-L862
train
216,525
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_onchain_secretreveal_if_dangerzone
def events_for_onchain_secretreveal_if_dangerzone( channelmap: ChannelMap, secrethash: SecretHash, transfers_pair: List[MediationPairState], block_number: BlockNumber, block_hash: BlockHash, ) -> List[Event]: """ Reveal the secret on-chain if the lock enters the unsafe region and the secret is not yet on-chain. """ events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Only consider the transfers which have a pair. This means if we have a # waiting transfer and for some reason the node knows the secret, it will # not try to register it. Otherwise it would be possible for an attacker to # reveal the secret late, just to force the node to send an unecessary # transaction. for pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pair) if not payer_channel: continue lock = pair.payer_transfer.lock safe_to_wait, _ = is_safe_to_wait( lock.expiration, payer_channel.reveal_timeout, block_number, ) secret_known = channel.is_secret_known( payer_channel.partner_state, pair.payer_transfer.lock.secrethash, ) if not safe_to_wait and secret_known: pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: secret = channel.get_secret( payer_channel.partner_state, lock.secrethash, ) assert secret, 'the secret should be known at this point' reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
python
def events_for_onchain_secretreveal_if_dangerzone( channelmap: ChannelMap, secrethash: SecretHash, transfers_pair: List[MediationPairState], block_number: BlockNumber, block_hash: BlockHash, ) -> List[Event]: """ Reveal the secret on-chain if the lock enters the unsafe region and the secret is not yet on-chain. """ events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Only consider the transfers which have a pair. This means if we have a # waiting transfer and for some reason the node knows the secret, it will # not try to register it. Otherwise it would be possible for an attacker to # reveal the secret late, just to force the node to send an unecessary # transaction. for pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pair) if not payer_channel: continue lock = pair.payer_transfer.lock safe_to_wait, _ = is_safe_to_wait( lock.expiration, payer_channel.reveal_timeout, block_number, ) secret_known = channel.is_secret_known( payer_channel.partner_state, pair.payer_transfer.lock.secrethash, ) if not safe_to_wait and secret_known: pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: secret = channel.get_secret( payer_channel.partner_state, lock.secrethash, ) assert secret, 'the secret should be known at this point' reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
[ "def", "events_for_onchain_secretreveal_if_dangerzone", "(", "channelmap", ":", "ChannelMap", ",", "secrethash", ":", "SecretHash", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "block_number", ":", "BlockNumber", ",", "block_hash", ":", "Bl...
Reveal the secret on-chain if the lock enters the unsafe region and the secret is not yet on-chain.
[ "Reveal", "the", "secret", "on", "-", "chain", "if", "the", "lock", "enters", "the", "unsafe", "region", "and", "the", "secret", "is", "not", "yet", "on", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L865-L933
train
216,526
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_for_onchain_secretreveal_if_closed
def events_for_onchain_secretreveal_if_closed( channelmap: ChannelMap, transfers_pair: List[MediationPairState], secret: Secret, secrethash: SecretHash, block_hash: BlockHash, ) -> List[Event]: """ Register the secret on-chain if the payer channel is already closed and the mediator learned the secret off-chain. Balance proofs are not exchanged for closed channels, so there is no reason to wait for the unsafe region to register secret. Note: If the secret is learned before the channel is closed, then the channel will register the secrets in bulk, not the transfer. """ events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Just like the case for entering the danger zone, this will only consider # the transfers which have a pair. for pending_pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pending_pair) # Don't register the secret on-chain if the channel is open or settled if payer_channel and channel.get_status(payer_channel) == CHANNEL_STATE_CLOSED: pending_pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: partner_state = payer_channel.partner_state lock = channel.get_lock(partner_state, secrethash) # The mediator task lives as long as there are any pending # locks, it may be the case that some of the transfer_pairs got # resolved off-chain, but others didn't. For this reason we # must check if the lock is still part of the channel if lock: reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
python
def events_for_onchain_secretreveal_if_closed( channelmap: ChannelMap, transfers_pair: List[MediationPairState], secret: Secret, secrethash: SecretHash, block_hash: BlockHash, ) -> List[Event]: """ Register the secret on-chain if the payer channel is already closed and the mediator learned the secret off-chain. Balance proofs are not exchanged for closed channels, so there is no reason to wait for the unsafe region to register secret. Note: If the secret is learned before the channel is closed, then the channel will register the secrets in bulk, not the transfer. """ events: List[Event] = list() all_payer_channels = [] for pair in transfers_pair: channel_state = get_payer_channel(channelmap, pair) if channel_state: all_payer_channels.append(channel_state) transaction_sent = has_secret_registration_started( all_payer_channels, transfers_pair, secrethash, ) # Just like the case for entering the danger zone, this will only consider # the transfers which have a pair. for pending_pair in get_pending_transfer_pairs(transfers_pair): payer_channel = get_payer_channel(channelmap, pending_pair) # Don't register the secret on-chain if the channel is open or settled if payer_channel and channel.get_status(payer_channel) == CHANNEL_STATE_CLOSED: pending_pair.payer_state = 'payer_waiting_secret_reveal' if not transaction_sent: partner_state = payer_channel.partner_state lock = channel.get_lock(partner_state, secrethash) # The mediator task lives as long as there are any pending # locks, it may be the case that some of the transfer_pairs got # resolved off-chain, but others didn't. For this reason we # must check if the lock is still part of the channel if lock: reveal_events = secret_registry.events_for_onchain_secretreveal( channel_state=payer_channel, secret=secret, expiration=lock.expiration, block_hash=block_hash, ) events.extend(reveal_events) transaction_sent = True return events
[ "def", "events_for_onchain_secretreveal_if_closed", "(", "channelmap", ":", "ChannelMap", ",", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "block_hash", ":", "BlockHash", ","...
Register the secret on-chain if the payer channel is already closed and the mediator learned the secret off-chain. Balance proofs are not exchanged for closed channels, so there is no reason to wait for the unsafe region to register secret. Note: If the secret is learned before the channel is closed, then the channel will register the secrets in bulk, not the transfer.
[ "Register", "the", "secret", "on", "-", "chain", "if", "the", "payer", "channel", "is", "already", "closed", "and", "the", "mediator", "learned", "the", "secret", "off", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L936-L995
train
216,527
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
events_to_remove_expired_locks
def events_to_remove_expired_locks( mediator_state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, pseudo_random_generator: random.Random, ) -> List[Event]: """ Clear the channels which have expired locks. This only considers the *sent* transfers, received transfers can only be updated by the partner. """ events: List[Event] = list() for transfer_pair in mediator_state.transfers_pair: balance_proof = transfer_pair.payee_transfer.balance_proof channel_identifier = balance_proof.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue secrethash = mediator_state.secrethash lock: Union[None, LockType] = None if secrethash in channel_state.our_state.secrethashes_to_lockedlocks: assert secrethash not in channel_state.our_state.secrethashes_to_unlockedlocks lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) elif secrethash in channel_state.our_state.secrethashes_to_unlockedlocks: lock = channel_state.our_state.secrethashes_to_unlockedlocks.get(secrethash) if lock: lock_expiration_threshold = channel.get_sender_expiration_threshold(lock) has_lock_expired, _ = channel.is_lock_expired( end_state=channel_state.our_state, lock=lock, block_number=block_number, lock_expiration_threshold=lock_expiration_threshold, ) is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if has_lock_expired and is_channel_open: transfer_pair.payee_state = 'payee_expired' expired_lock_events = channel.events_for_expired_lock( channel_state=channel_state, locked_lock=lock, pseudo_random_generator=pseudo_random_generator, ) events.extend(expired_lock_events) unlock_failed = EventUnlockFailed( transfer_pair.payee_transfer.payment_identifier, transfer_pair.payee_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_failed) return events
python
def events_to_remove_expired_locks( mediator_state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, pseudo_random_generator: random.Random, ) -> List[Event]: """ Clear the channels which have expired locks. This only considers the *sent* transfers, received transfers can only be updated by the partner. """ events: List[Event] = list() for transfer_pair in mediator_state.transfers_pair: balance_proof = transfer_pair.payee_transfer.balance_proof channel_identifier = balance_proof.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: continue secrethash = mediator_state.secrethash lock: Union[None, LockType] = None if secrethash in channel_state.our_state.secrethashes_to_lockedlocks: assert secrethash not in channel_state.our_state.secrethashes_to_unlockedlocks lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) elif secrethash in channel_state.our_state.secrethashes_to_unlockedlocks: lock = channel_state.our_state.secrethashes_to_unlockedlocks.get(secrethash) if lock: lock_expiration_threshold = channel.get_sender_expiration_threshold(lock) has_lock_expired, _ = channel.is_lock_expired( end_state=channel_state.our_state, lock=lock, block_number=block_number, lock_expiration_threshold=lock_expiration_threshold, ) is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED if has_lock_expired and is_channel_open: transfer_pair.payee_state = 'payee_expired' expired_lock_events = channel.events_for_expired_lock( channel_state=channel_state, locked_lock=lock, pseudo_random_generator=pseudo_random_generator, ) events.extend(expired_lock_events) unlock_failed = EventUnlockFailed( transfer_pair.payee_transfer.payment_identifier, transfer_pair.payee_transfer.lock.secrethash, 'lock expired', ) events.append(unlock_failed) return events
[ "def", "events_to_remove_expired_locks", "(", "mediator_state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "block_number", ":", "BlockNumber", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", ...
Clear the channels which have expired locks. This only considers the *sent* transfers, received transfers can only be updated by the partner.
[ "Clear", "the", "channels", "which", "have", "expired", "locks", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L998-L1053
train
216,528
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
secret_learned
def secret_learned( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, block_hash: BlockHash, secret: Secret, secrethash: SecretHash, payee_address: Address, ) -> TransitionResult[MediatorTransferState]: """ Unlock the payee lock, reveal the lock to the payer, and if necessary register the secret on-chain. """ secret_reveal_events = set_offchain_secret( state, channelidentifiers_to_channels, secret, secrethash, ) set_offchain_reveal_state( state.transfers_pair, payee_address, ) onchain_secret_reveal = events_for_onchain_secretreveal_if_closed( channelmap=channelidentifiers_to_channels, transfers_pair=state.transfers_pair, secret=secret, secrethash=secrethash, block_hash=block_hash, ) offchain_secret_reveal = events_for_secretreveal( state.transfers_pair, secret, pseudo_random_generator, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels, state.transfers_pair, pseudo_random_generator, block_number, secret, secrethash, ) events = secret_reveal_events + offchain_secret_reveal + balance_proof + onchain_secret_reveal iteration = TransitionResult(state, events) return iteration
python
def secret_learned( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, block_hash: BlockHash, secret: Secret, secrethash: SecretHash, payee_address: Address, ) -> TransitionResult[MediatorTransferState]: """ Unlock the payee lock, reveal the lock to the payer, and if necessary register the secret on-chain. """ secret_reveal_events = set_offchain_secret( state, channelidentifiers_to_channels, secret, secrethash, ) set_offchain_reveal_state( state.transfers_pair, payee_address, ) onchain_secret_reveal = events_for_onchain_secretreveal_if_closed( channelmap=channelidentifiers_to_channels, transfers_pair=state.transfers_pair, secret=secret, secrethash=secrethash, block_hash=block_hash, ) offchain_secret_reveal = events_for_secretreveal( state.transfers_pair, secret, pseudo_random_generator, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels, state.transfers_pair, pseudo_random_generator, block_number, secret, secrethash, ) events = secret_reveal_events + offchain_secret_reveal + balance_proof + onchain_secret_reveal iteration = TransitionResult(state, events) return iteration
[ "def", "secret_learned", "(", "state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", "block_number", ":", "BlockNumber", ",", "block_hash", ":", "BlockHash", "...
Unlock the payee lock, reveal the lock to the payer, and if necessary register the secret on-chain.
[ "Unlock", "the", "payee", "lock", "reveal", "the", "lock", "to", "the", "payer", "and", "if", "necessary", "register", "the", "secret", "on", "-", "chain", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1056-L1107
train
216,529
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
mediate_transfer
def mediate_transfer( state: MediatorTransferState, possible_routes: List['RouteState'], payer_channel: NettingChannelState, channelidentifiers_to_channels: ChannelMap, nodeaddresses_to_networkstates: NodeNetworkStateMap, pseudo_random_generator: random.Random, payer_transfer: LockedTransferSignedState, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: """ Try a new route or fail back to a refund. The mediator can safely try a new route knowing that the tokens from payer_transfer will cover the expenses of the mediation. If there is no route available that may be used at the moment of the call the mediator may send a refund back to the payer, allowing the payer to try a different route. """ reachable_routes = filter_reachable_routes( possible_routes, nodeaddresses_to_networkstates, ) available_routes = filter_used_routes( state.transfers_pair, reachable_routes, ) assert payer_channel.partner_state.address == payer_transfer.balance_proof.sender transfer_pair, mediated_events = forward_transfer_pair( payer_transfer, available_routes, channelidentifiers_to_channels, pseudo_random_generator, block_number, ) if transfer_pair is None: assert not mediated_events if state.transfers_pair: original_pair = state.transfers_pair[0] original_channel = get_payer_channel( channelidentifiers_to_channels, original_pair, ) else: original_channel = payer_channel if original_channel: transfer_pair, mediated_events = backward_transfer_pair( original_channel, payer_transfer, pseudo_random_generator, block_number, ) else: transfer_pair = None mediated_events = list() if transfer_pair is None: assert not mediated_events mediated_events = list() state.waiting_transfer = WaitingTransferState(payer_transfer) else: # the list must be ordered from high to low expiration, expiration # handling depends on it state.transfers_pair.append(transfer_pair) return TransitionResult(state, mediated_events)
python
def mediate_transfer( state: MediatorTransferState, possible_routes: List['RouteState'], payer_channel: NettingChannelState, channelidentifiers_to_channels: ChannelMap, nodeaddresses_to_networkstates: NodeNetworkStateMap, pseudo_random_generator: random.Random, payer_transfer: LockedTransferSignedState, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: """ Try a new route or fail back to a refund. The mediator can safely try a new route knowing that the tokens from payer_transfer will cover the expenses of the mediation. If there is no route available that may be used at the moment of the call the mediator may send a refund back to the payer, allowing the payer to try a different route. """ reachable_routes = filter_reachable_routes( possible_routes, nodeaddresses_to_networkstates, ) available_routes = filter_used_routes( state.transfers_pair, reachable_routes, ) assert payer_channel.partner_state.address == payer_transfer.balance_proof.sender transfer_pair, mediated_events = forward_transfer_pair( payer_transfer, available_routes, channelidentifiers_to_channels, pseudo_random_generator, block_number, ) if transfer_pair is None: assert not mediated_events if state.transfers_pair: original_pair = state.transfers_pair[0] original_channel = get_payer_channel( channelidentifiers_to_channels, original_pair, ) else: original_channel = payer_channel if original_channel: transfer_pair, mediated_events = backward_transfer_pair( original_channel, payer_transfer, pseudo_random_generator, block_number, ) else: transfer_pair = None mediated_events = list() if transfer_pair is None: assert not mediated_events mediated_events = list() state.waiting_transfer = WaitingTransferState(payer_transfer) else: # the list must be ordered from high to low expiration, expiration # handling depends on it state.transfers_pair.append(transfer_pair) return TransitionResult(state, mediated_events)
[ "def", "mediate_transfer", "(", "state", ":", "MediatorTransferState", ",", "possible_routes", ":", "List", "[", "'RouteState'", "]", ",", "payer_channel", ":", "NettingChannelState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "nodeaddresses_to_network...
Try a new route or fail back to a refund. The mediator can safely try a new route knowing that the tokens from payer_transfer will cover the expenses of the mediation. If there is no route available that may be used at the moment of the call the mediator may send a refund back to the payer, allowing the payer to try a different route.
[ "Try", "a", "new", "route", "or", "fail", "back", "to", "a", "refund", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1110-L1180
train
216,530
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
handle_onchain_secretreveal
def handle_onchain_secretreveal( mediator_state: MediatorTransferState, onchain_secret_reveal: ContractReceiveSecretReveal, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: """ The secret was revealed on-chain, set the state of all transfers to secret known. """ secrethash = onchain_secret_reveal.secrethash is_valid_reveal = is_valid_secret_reveal( state_change=onchain_secret_reveal, transfer_secrethash=mediator_state.secrethash, secret=onchain_secret_reveal.secret, ) if is_valid_reveal: secret = onchain_secret_reveal.secret # Compare against the block number at which the event was emitted. block_number = onchain_secret_reveal.block_number secret_reveal = set_onchain_secret( state=mediator_state, channelidentifiers_to_channels=channelidentifiers_to_channels, secret=secret, secrethash=secrethash, block_number=block_number, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels=channelidentifiers_to_channels, transfers_pair=mediator_state.transfers_pair, pseudo_random_generator=pseudo_random_generator, block_number=block_number, secret=secret, secrethash=secrethash, ) iteration = TransitionResult(mediator_state, secret_reveal + balance_proof) else: iteration = TransitionResult(mediator_state, list()) return iteration
python
def handle_onchain_secretreveal( mediator_state: MediatorTransferState, onchain_secret_reveal: ContractReceiveSecretReveal, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[MediatorTransferState]: """ The secret was revealed on-chain, set the state of all transfers to secret known. """ secrethash = onchain_secret_reveal.secrethash is_valid_reveal = is_valid_secret_reveal( state_change=onchain_secret_reveal, transfer_secrethash=mediator_state.secrethash, secret=onchain_secret_reveal.secret, ) if is_valid_reveal: secret = onchain_secret_reveal.secret # Compare against the block number at which the event was emitted. block_number = onchain_secret_reveal.block_number secret_reveal = set_onchain_secret( state=mediator_state, channelidentifiers_to_channels=channelidentifiers_to_channels, secret=secret, secrethash=secrethash, block_number=block_number, ) balance_proof = events_for_balanceproof( channelidentifiers_to_channels=channelidentifiers_to_channels, transfers_pair=mediator_state.transfers_pair, pseudo_random_generator=pseudo_random_generator, block_number=block_number, secret=secret, secrethash=secrethash, ) iteration = TransitionResult(mediator_state, secret_reveal + balance_proof) else: iteration = TransitionResult(mediator_state, list()) return iteration
[ "def", "handle_onchain_secretreveal", "(", "mediator_state", ":", "MediatorTransferState", ",", "onchain_secret_reveal", ":", "ContractReceiveSecretReveal", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "pseudo_random_generator", ":", "random", ".", "Random", ...
The secret was revealed on-chain, set the state of all transfers to secret known.
[ "The", "secret", "was", "revealed", "on", "-", "chain", "set", "the", "state", "of", "all", "transfers", "to", "secret", "known", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1384-L1426
train
216,531
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
handle_unlock
def handle_unlock( mediator_state: MediatorTransferState, state_change: ReceiveUnlock, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: """ Handle a ReceiveUnlock state change. """ events = list() balance_proof_sender = state_change.balance_proof.sender channel_identifier = state_change.balance_proof.channel_identifier for pair in mediator_state.transfers_pair: if pair.payer_transfer.balance_proof.sender == balance_proof_sender: channel_state = channelidentifiers_to_channels.get(channel_identifier) if channel_state: is_valid, channel_events, _ = channel.handle_unlock( channel_state, state_change, ) events.extend(channel_events) if is_valid: unlock = EventUnlockClaimSuccess( pair.payee_transfer.payment_identifier, pair.payee_transfer.lock.secrethash, ) events.append(unlock) send_processed = SendProcessed( recipient=balance_proof_sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=state_change.message_identifier, ) events.append(send_processed) pair.payer_state = 'payer_balance_proof' iteration = TransitionResult(mediator_state, events) return iteration
python
def handle_unlock( mediator_state: MediatorTransferState, state_change: ReceiveUnlock, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: """ Handle a ReceiveUnlock state change. """ events = list() balance_proof_sender = state_change.balance_proof.sender channel_identifier = state_change.balance_proof.channel_identifier for pair in mediator_state.transfers_pair: if pair.payer_transfer.balance_proof.sender == balance_proof_sender: channel_state = channelidentifiers_to_channels.get(channel_identifier) if channel_state: is_valid, channel_events, _ = channel.handle_unlock( channel_state, state_change, ) events.extend(channel_events) if is_valid: unlock = EventUnlockClaimSuccess( pair.payee_transfer.payment_identifier, pair.payee_transfer.lock.secrethash, ) events.append(unlock) send_processed = SendProcessed( recipient=balance_proof_sender, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, message_identifier=state_change.message_identifier, ) events.append(send_processed) pair.payer_state = 'payer_balance_proof' iteration = TransitionResult(mediator_state, events) return iteration
[ "def", "handle_unlock", "(", "mediator_state", ":", "MediatorTransferState", ",", "state_change", ":", "ReceiveUnlock", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", ")", "->", "TransitionResult", "[", "MediatorTransferState", "]", ":", "events", "=", ...
Handle a ReceiveUnlock state change.
[ "Handle", "a", "ReceiveUnlock", "state", "change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L1429-L1467
train
216,532
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.service_count
def service_count(self, block_identifier: BlockSpecification) -> int: """Get the number of registered services""" result = self.proxy.contract.functions.serviceCount().call( block_identifier=block_identifier, ) return result
python
def service_count(self, block_identifier: BlockSpecification) -> int: """Get the number of registered services""" result = self.proxy.contract.functions.serviceCount().call( block_identifier=block_identifier, ) return result
[ "def", "service_count", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "int", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functions", ".", "serviceCount", "(", ")", ".", "call", "(", "block_identifier", "=", ...
Get the number of registered services
[ "Get", "the", "number", "of", "registered", "services" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L46-L51
train
216,533
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.get_service_address
def get_service_address( self, block_identifier: BlockSpecification, index: int, ) -> Optional[AddressHex]: """Gets the address of a service by index. If index is out of range return None""" try: result = self.proxy.contract.functions.service_addresses(index).call( block_identifier=block_identifier, ) except web3.exceptions.BadFunctionCallOutput: result = None return result
python
def get_service_address( self, block_identifier: BlockSpecification, index: int, ) -> Optional[AddressHex]: """Gets the address of a service by index. If index is out of range return None""" try: result = self.proxy.contract.functions.service_addresses(index).call( block_identifier=block_identifier, ) except web3.exceptions.BadFunctionCallOutput: result = None return result
[ "def", "get_service_address", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ",", "index", ":", "int", ",", ")", "->", "Optional", "[", "AddressHex", "]", ":", "try", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functi...
Gets the address of a service by index. If index is out of range return None
[ "Gets", "the", "address", "of", "a", "service", "by", "index", ".", "If", "index", "is", "out", "of", "range", "return", "None" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L53-L65
train
216,534
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.get_service_url
def get_service_url( self, block_identifier: BlockSpecification, service_hex_address: AddressHex, ) -> Optional[str]: """Gets the URL of a service by address. If does not exist return None""" result = self.proxy.contract.functions.urls(service_hex_address).call( block_identifier=block_identifier, ) if result == '': return None return result
python
def get_service_url( self, block_identifier: BlockSpecification, service_hex_address: AddressHex, ) -> Optional[str]: """Gets the URL of a service by address. If does not exist return None""" result = self.proxy.contract.functions.urls(service_hex_address).call( block_identifier=block_identifier, ) if result == '': return None return result
[ "def", "get_service_url", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ",", "service_hex_address", ":", "AddressHex", ",", ")", "->", "Optional", "[", "str", "]", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functions", ...
Gets the URL of a service by address. If does not exist return None
[ "Gets", "the", "URL", "of", "a", "service", "by", "address", ".", "If", "does", "not", "exist", "return", "None" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L67-L78
train
216,535
raiden-network/raiden
raiden/network/proxies/service_registry.py
ServiceRegistry.set_url
def set_url(self, url: str): """Sets the url needed to access the service via HTTP for the caller""" gas_limit = self.proxy.estimate_gas('latest', 'setURL', url) transaction_hash = self.proxy.transact('setURL', gas_limit, url) self.client.poll(transaction_hash) assert not check_transaction_threw(self.client, transaction_hash)
python
def set_url(self, url: str): """Sets the url needed to access the service via HTTP for the caller""" gas_limit = self.proxy.estimate_gas('latest', 'setURL', url) transaction_hash = self.proxy.transact('setURL', gas_limit, url) self.client.poll(transaction_hash) assert not check_transaction_threw(self.client, transaction_hash)
[ "def", "set_url", "(", "self", ",", "url", ":", "str", ")", ":", "gas_limit", "=", "self", ".", "proxy", ".", "estimate_gas", "(", "'latest'", ",", "'setURL'", ",", "url", ")", "transaction_hash", "=", "self", ".", "proxy", ".", "transact", "(", "'setU...
Sets the url needed to access the service via HTTP for the caller
[ "Sets", "the", "url", "needed", "to", "access", "the", "service", "via", "HTTP", "for", "the", "caller" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/service_registry.py#L80-L85
train
216,536
raiden-network/raiden
raiden/utils/signer.py
recover
def recover( data: bytes, signature: Signature, hasher: Callable[[bytes], bytes] = eth_sign_sha3, ) -> Address: """ eth_recover address from data hash and signature """ _hash = hasher(data) # ecdsa_recover accepts only standard [0,1] v's so we add support also for [27,28] here # anything else will raise BadSignature if signature[-1] >= 27: # support (0,1,27,28) v values signature = Signature(signature[:-1] + bytes([signature[-1] - 27])) try: sig = keys.Signature(signature_bytes=signature) public_key = keys.ecdsa_recover(message_hash=_hash, signature=sig) except BadSignature as e: raise InvalidSignature from e return public_key.to_canonical_address()
python
def recover( data: bytes, signature: Signature, hasher: Callable[[bytes], bytes] = eth_sign_sha3, ) -> Address: """ eth_recover address from data hash and signature """ _hash = hasher(data) # ecdsa_recover accepts only standard [0,1] v's so we add support also for [27,28] here # anything else will raise BadSignature if signature[-1] >= 27: # support (0,1,27,28) v values signature = Signature(signature[:-1] + bytes([signature[-1] - 27])) try: sig = keys.Signature(signature_bytes=signature) public_key = keys.ecdsa_recover(message_hash=_hash, signature=sig) except BadSignature as e: raise InvalidSignature from e return public_key.to_canonical_address()
[ "def", "recover", "(", "data", ":", "bytes", ",", "signature", ":", "Signature", ",", "hasher", ":", "Callable", "[", "[", "bytes", "]", ",", "bytes", "]", "=", "eth_sign_sha3", ",", ")", "->", "Address", ":", "_hash", "=", "hasher", "(", "data", ")"...
eth_recover address from data hash and signature
[ "eth_recover", "address", "from", "data", "hash", "and", "signature" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/signer.py#L23-L41
train
216,537
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: """ 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])
[ "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
train
216,538
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, ): """ 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)
[ "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
train
216,539
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 the balance of `address`. """ 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
train
216,540
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 the total supply of the token at the given block identifier. """ 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
train
216,541
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]: """ 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
[ "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
train
216,542
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]: """ 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)
[ "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
train
216,543
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
train
216,544
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]: """ 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)
[ "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
train
216,545
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 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)
[ "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
train
216,546
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, ): """ 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
[ "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
train
216,547
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]]: """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
[ "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
train
216,548
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]: """ 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), )
[ "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
train
216,549
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]]: """ 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()
[ "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
train
216,550
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, ): """ 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
[ "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
train
216,551
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): """ 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]
[ "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
train
216,552
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): """ 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)
[ "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
train
216,553
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: """ 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
[ "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
train
216,554
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: """ 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
[ "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
train
216,555
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, ): """ 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, )
[ "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
train
216,556
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: """ 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
[ "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
train
216,557
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): """ 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, )
[ "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
train
216,558
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): """ 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, )
[ "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
train
216,559
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): """ 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)
[ "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
train
216,560
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): """ 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, )
[ "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
train
216,561
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: """ 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()
[ "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
train
216,562
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', ): """ 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
[ "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
train
216,563
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]: """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
[ "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
train
216,564
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]: """ 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
[ "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
train
216,565
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): """ 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))
[ "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
train
216,566
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): """ 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)
[ "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
train
216,567
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): """ 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)
[ "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
train
216,568
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]: """ 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
[ "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
train
216,569
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: """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)
[ "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
train
216,570
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): """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)
[ "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
train
216,571
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): """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)
[ "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
train
216,572
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): """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
[ "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
train
216,573
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): """ 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(), )
[ "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
train
216,574
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): """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)
[ "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
train
216,575
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): """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)
[ "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
train
216,576
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): """ 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)
[ "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
train
216,577
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): """ Sign message inplace. """ 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
train
216,578
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: """ 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
[ "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
train
216,579
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): """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
[ "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
train
216,580
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): """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', )
[ "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
train
216,581
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): """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
[ "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
train
216,582
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: """ 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)
[ "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
train
216,583
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: """ 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)
[ "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
train
216,584
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: """ 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()
[ "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
train
216,585
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]: """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
[ "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
train
216,586
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: """ 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)
[ "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
train
216,587
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: """ 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)
[ "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
train
216,588
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: """ Returns the channel details. """ 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
train
216,589
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: """ 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']
[ "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
train
216,590
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: """ 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, )
[ "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
train
216,591
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: """ 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, )
[ "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
train
216,592
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: """ 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, )
[ "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
train
216,593
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]: """ 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, )
[ "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
train
216,594
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, ): """ 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, )
[ "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
train
216,595
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, ): """ 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, )
[ "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
train
216,596
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, ): """ 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, )
[ "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
train
216,597
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]: """ 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]
[ "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
train
216,598
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]: """ 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)
[ "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
train
216,599