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
tools/genesis_builder.py
mk_genesis
def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000): """ Create a genesis-block dict with allocation for all `accounts`. :param accounts: list of account addresses (hex) :param initial_alloc: the amount to allocate for the `accounts` :return: genesis dict """ genesis = GENESIS_STUB.copy() genesis['extraData'] = encode_hex(CLUSTER_NAME) genesis['alloc'].update({ account: { 'balance': str(initial_alloc), } for account in accounts }) # add the one-privatekey account ("1" * 64) for convenience genesis['alloc']['19e7e376e7c213b7e7e7e46cc70a5dd086daff2a'] = dict(balance=str(initial_alloc)) return genesis
python
def mk_genesis(accounts, initial_alloc=denoms.ether * 100000000): """ Create a genesis-block dict with allocation for all `accounts`. :param accounts: list of account addresses (hex) :param initial_alloc: the amount to allocate for the `accounts` :return: genesis dict """ genesis = GENESIS_STUB.copy() genesis['extraData'] = encode_hex(CLUSTER_NAME) genesis['alloc'].update({ account: { 'balance': str(initial_alloc), } for account in accounts }) # add the one-privatekey account ("1" * 64) for convenience genesis['alloc']['19e7e376e7c213b7e7e7e46cc70a5dd086daff2a'] = dict(balance=str(initial_alloc)) return genesis
[ "def", "mk_genesis", "(", "accounts", ",", "initial_alloc", "=", "denoms", ".", "ether", "*", "100000000", ")", ":", "genesis", "=", "GENESIS_STUB", ".", "copy", "(", ")", "genesis", "[", "'extraData'", "]", "=", "encode_hex", "(", "CLUSTER_NAME", ")", "ge...
Create a genesis-block dict with allocation for all `accounts`. :param accounts: list of account addresses (hex) :param initial_alloc: the amount to allocate for the `accounts` :return: genesis dict
[ "Create", "a", "genesis", "-", "block", "dict", "with", "allocation", "for", "all", "accounts", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/genesis_builder.py#L21-L39
train
216,400
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.token_address
def token_address(self) -> Address: """ Return the token of this manager. """ return to_canonical_address(self.proxy.contract.functions.token().call())
python
def token_address(self) -> Address: """ Return the token of this manager. """ return to_canonical_address(self.proxy.contract.functions.token().call())
[ "def", "token_address", "(", "self", ")", "->", "Address", ":", "return", "to_canonical_address", "(", "self", ".", "proxy", ".", "contract", ".", "functions", ".", "token", "(", ")", ".", "call", "(", ")", ")" ]
Return the token of this manager.
[ "Return", "the", "token", "of", "this", "manager", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L155-L157
train
216,401
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.new_netting_channel
def new_netting_channel( self, partner: Address, settle_timeout: int, given_block_identifier: BlockSpecification, ) -> ChannelID: """ Creates a new channel in the TokenNetwork contract. Args: partner: The peer to open the channel with. settle_timeout: The settle timeout to use for this channel. given_block_identifier: The block identifier of the state change that prompted this proxy action Returns: The ChannelID of the new netting channel. """ checking_block = self.client.get_checking_block() self._new_channel_preconditions( partner=partner, settle_timeout=settle_timeout, block_identifier=given_block_identifier, ) log_details = { 'peer1': pex(self.node_address), 'peer2': pex(partner), } gas_limit = self.proxy.estimate_gas( checking_block, 'openChannel', participant1=self.node_address, participant2=partner, settle_timeout=settle_timeout, ) if not gas_limit: self.proxy.jsonrpc_client.check_for_insufficient_eth( transaction_name='openChannel', transaction_executed=False, required_gas=GAS_REQUIRED_FOR_OPEN_CHANNEL, block_identifier=checking_block, ) self._new_channel_postconditions( partner=partner, block=checking_block, ) log.critical('new_netting_channel call will fail', **log_details) raise RaidenUnrecoverableError('Creating a new channel will fail') log.debug('new_netting_channel called', **log_details) # Prevent concurrent attempts to open a channel with the same token and # partner address. if gas_limit and partner not in self.open_channel_transactions: new_open_channel_transaction = AsyncResult() self.open_channel_transactions[partner] = new_open_channel_transaction gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_OPEN_CHANNEL) try: transaction_hash = self.proxy.transact( 'openChannel', gas_limit, participant1=self.node_address, participant2=partner, settle_timeout=settle_timeout, ) self.client.poll(transaction_hash) receipt_or_none = check_transaction_threw(self.client, transaction_hash) if receipt_or_none: self._new_channel_postconditions( partner=partner, block=receipt_or_none['blockNumber'], ) log.critical('new_netting_channel failed', **log_details) raise RaidenUnrecoverableError('creating new channel failed') except Exception as e: log.critical('new_netting_channel failed', **log_details) new_open_channel_transaction.set_exception(e) raise else: new_open_channel_transaction.set(transaction_hash) finally: self.open_channel_transactions.pop(partner, None) else: # All other concurrent threads should block on the result of opening this channel self.open_channel_transactions[partner].get() channel_identifier: ChannelID = self._detail_channel( participant1=self.node_address, participant2=partner, block_identifier='latest', ).channel_identifier log_details['channel_identifier'] = str(channel_identifier) log.info('new_netting_channel successful', **log_details) return channel_identifier
python
def new_netting_channel( self, partner: Address, settle_timeout: int, given_block_identifier: BlockSpecification, ) -> ChannelID: """ Creates a new channel in the TokenNetwork contract. Args: partner: The peer to open the channel with. settle_timeout: The settle timeout to use for this channel. given_block_identifier: The block identifier of the state change that prompted this proxy action Returns: The ChannelID of the new netting channel. """ checking_block = self.client.get_checking_block() self._new_channel_preconditions( partner=partner, settle_timeout=settle_timeout, block_identifier=given_block_identifier, ) log_details = { 'peer1': pex(self.node_address), 'peer2': pex(partner), } gas_limit = self.proxy.estimate_gas( checking_block, 'openChannel', participant1=self.node_address, participant2=partner, settle_timeout=settle_timeout, ) if not gas_limit: self.proxy.jsonrpc_client.check_for_insufficient_eth( transaction_name='openChannel', transaction_executed=False, required_gas=GAS_REQUIRED_FOR_OPEN_CHANNEL, block_identifier=checking_block, ) self._new_channel_postconditions( partner=partner, block=checking_block, ) log.critical('new_netting_channel call will fail', **log_details) raise RaidenUnrecoverableError('Creating a new channel will fail') log.debug('new_netting_channel called', **log_details) # Prevent concurrent attempts to open a channel with the same token and # partner address. if gas_limit and partner not in self.open_channel_transactions: new_open_channel_transaction = AsyncResult() self.open_channel_transactions[partner] = new_open_channel_transaction gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_OPEN_CHANNEL) try: transaction_hash = self.proxy.transact( 'openChannel', gas_limit, participant1=self.node_address, participant2=partner, settle_timeout=settle_timeout, ) self.client.poll(transaction_hash) receipt_or_none = check_transaction_threw(self.client, transaction_hash) if receipt_or_none: self._new_channel_postconditions( partner=partner, block=receipt_or_none['blockNumber'], ) log.critical('new_netting_channel failed', **log_details) raise RaidenUnrecoverableError('creating new channel failed') except Exception as e: log.critical('new_netting_channel failed', **log_details) new_open_channel_transaction.set_exception(e) raise else: new_open_channel_transaction.set(transaction_hash) finally: self.open_channel_transactions.pop(partner, None) else: # All other concurrent threads should block on the result of opening this channel self.open_channel_transactions[partner].get() channel_identifier: ChannelID = self._detail_channel( participant1=self.node_address, participant2=partner, block_identifier='latest', ).channel_identifier log_details['channel_identifier'] = str(channel_identifier) log.info('new_netting_channel successful', **log_details) return channel_identifier
[ "def", "new_netting_channel", "(", "self", ",", "partner", ":", "Address", ",", "settle_timeout", ":", "int", ",", "given_block_identifier", ":", "BlockSpecification", ",", ")", "->", "ChannelID", ":", "checking_block", "=", "self", ".", "client", ".", "get_chec...
Creates a new channel in the TokenNetwork contract. Args: partner: The peer to open the channel with. settle_timeout: The settle timeout to use for this channel. given_block_identifier: The block identifier of the state change that prompted this proxy action Returns: The ChannelID of the new netting channel.
[ "Creates", "a", "new", "channel", "in", "the", "TokenNetwork", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L209-L303
train
216,402
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork._channel_exists_and_not_settled
def _channel_exists_and_not_settled( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> bool: """Returns if the channel exists and is in a non-settled state""" try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False exists_and_not_settled = ( channel_state > ChannelState.NONEXISTENT and channel_state < ChannelState.SETTLED ) return exists_and_not_settled
python
def _channel_exists_and_not_settled( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> bool: """Returns if the channel exists and is in a non-settled state""" try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False exists_and_not_settled = ( channel_state > ChannelState.NONEXISTENT and channel_state < ChannelState.SETTLED ) return exists_and_not_settled
[ "def", "_channel_exists_and_not_settled", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", "=", "None", ",", ")", "->", "bool", "...
Returns if the channel exists and is in a non-settled state
[ "Returns", "if", "the", "channel", "exists", "and", "is", "in", "a", "non", "-", "settled", "state" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L332-L353
train
216,403
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork._detail_participant
def _detail_participant( self, channel_identifier: ChannelID, participant: Address, partner: Address, block_identifier: BlockSpecification, ) -> ParticipantDetails: """ Returns a dictionary with the channel participant information. """ data = self._call_and_check_result( block_identifier, 'getChannelParticipantInfo', channel_identifier=channel_identifier, participant=to_checksum_address(participant), partner=to_checksum_address(partner), ) return ParticipantDetails( address=participant, deposit=data[ParticipantInfoIndex.DEPOSIT], withdrawn=data[ParticipantInfoIndex.WITHDRAWN], is_closer=data[ParticipantInfoIndex.IS_CLOSER], balance_hash=data[ParticipantInfoIndex.BALANCE_HASH], nonce=data[ParticipantInfoIndex.NONCE], locksroot=data[ParticipantInfoIndex.LOCKSROOT], locked_amount=data[ParticipantInfoIndex.LOCKED_AMOUNT], )
python
def _detail_participant( self, channel_identifier: ChannelID, participant: Address, partner: Address, block_identifier: BlockSpecification, ) -> ParticipantDetails: """ Returns a dictionary with the channel participant information. """ data = self._call_and_check_result( block_identifier, 'getChannelParticipantInfo', channel_identifier=channel_identifier, participant=to_checksum_address(participant), partner=to_checksum_address(partner), ) return ParticipantDetails( address=participant, deposit=data[ParticipantInfoIndex.DEPOSIT], withdrawn=data[ParticipantInfoIndex.WITHDRAWN], is_closer=data[ParticipantInfoIndex.IS_CLOSER], balance_hash=data[ParticipantInfoIndex.BALANCE_HASH], nonce=data[ParticipantInfoIndex.NONCE], locksroot=data[ParticipantInfoIndex.LOCKSROOT], locked_amount=data[ParticipantInfoIndex.LOCKED_AMOUNT], )
[ "def", "_detail_participant", "(", "self", ",", "channel_identifier", ":", "ChannelID", ",", "participant", ":", "Address", ",", "partner", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "ParticipantDetails", ":", "data", "=", ...
Returns a dictionary with the channel participant information.
[ "Returns", "a", "dictionary", "with", "the", "channel", "participant", "information", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L355-L380
train
216,404
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork._detail_channel
def _detail_channel( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ChannelData: """ Returns a ChannelData instance with the channel specific information. If no specific channel_identifier is given then it tries to see if there is a currently open channel and uses that identifier. """ channel_identifier = self._inspect_channel_identifier( participant1=participant1, participant2=participant2, called_by_fn='_detail_channel(', block_identifier=block_identifier, channel_identifier=channel_identifier, ) channel_data = self._call_and_check_result( block_identifier, 'getChannelInfo', channel_identifier=channel_identifier, participant1=to_checksum_address(participant1), participant2=to_checksum_address(participant2), ) return ChannelData( channel_identifier=channel_identifier, settle_block_number=channel_data[ChannelInfoIndex.SETTLE_BLOCK], state=channel_data[ChannelInfoIndex.STATE], )
python
def _detail_channel( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ChannelData: """ Returns a ChannelData instance with the channel specific information. If no specific channel_identifier is given then it tries to see if there is a currently open channel and uses that identifier. """ channel_identifier = self._inspect_channel_identifier( participant1=participant1, participant2=participant2, called_by_fn='_detail_channel(', block_identifier=block_identifier, channel_identifier=channel_identifier, ) channel_data = self._call_and_check_result( block_identifier, 'getChannelInfo', channel_identifier=channel_identifier, participant1=to_checksum_address(participant1), participant2=to_checksum_address(participant2), ) return ChannelData( channel_identifier=channel_identifier, settle_block_number=channel_data[ChannelInfoIndex.SETTLE_BLOCK], state=channel_data[ChannelInfoIndex.STATE], )
[ "def", "_detail_channel", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", "=", "None", ",", ")", "->", "ChannelData", ":", "ch...
Returns a ChannelData instance with the channel specific information. If no specific channel_identifier is given then it tries to see if there is a currently open channel and uses that identifier.
[ "Returns", "a", "ChannelData", "instance", "with", "the", "channel", "specific", "information", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L382-L415
train
216,405
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.detail_participants
def detail_participants( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ParticipantsDetails: """ Returns a ParticipantsDetails instance with the participants' channel information. Note: For now one of the participants has to be the node_address """ if self.node_address not in (participant1, participant2): raise ValueError('One participant must be the node address') if self.node_address == participant2: participant1, participant2 = participant2, participant1 channel_identifier = self._inspect_channel_identifier( participant1=participant1, participant2=participant2, called_by_fn='details_participants', block_identifier=block_identifier, channel_identifier=channel_identifier, ) our_data = self._detail_participant( channel_identifier=channel_identifier, participant=participant1, partner=participant2, block_identifier=block_identifier, ) partner_data = self._detail_participant( channel_identifier=channel_identifier, participant=participant2, partner=participant1, block_identifier=block_identifier, ) return ParticipantsDetails(our_details=our_data, partner_details=partner_data)
python
def detail_participants( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ParticipantsDetails: """ Returns a ParticipantsDetails instance with the participants' channel information. Note: For now one of the participants has to be the node_address """ if self.node_address not in (participant1, participant2): raise ValueError('One participant must be the node address') if self.node_address == participant2: participant1, participant2 = participant2, participant1 channel_identifier = self._inspect_channel_identifier( participant1=participant1, participant2=participant2, called_by_fn='details_participants', block_identifier=block_identifier, channel_identifier=channel_identifier, ) our_data = self._detail_participant( channel_identifier=channel_identifier, participant=participant1, partner=participant2, block_identifier=block_identifier, ) partner_data = self._detail_participant( channel_identifier=channel_identifier, participant=participant2, partner=participant1, block_identifier=block_identifier, ) return ParticipantsDetails(our_details=our_data, partner_details=partner_data)
[ "def", "detail_participants", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", "=", "None", ",", ")", "->", "ParticipantsDetails", ...
Returns a ParticipantsDetails instance with the participants' channel information. Note: For now one of the participants has to be the node_address
[ "Returns", "a", "ParticipantsDetails", "instance", "with", "the", "participants", "channel", "information", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L417-L456
train
216,406
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.detail
def detail( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ChannelDetails: """ Returns a ChannelDetails instance with all the details of the channel and the channel participants. Note: For now one of the participants has to be the node_address """ if self.node_address not in (participant1, participant2): raise ValueError('One participant must be the node address') if self.node_address == participant2: participant1, participant2 = participant2, participant1 channel_data = self._detail_channel( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) participants_data = self.detail_participants( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_data.channel_identifier, ) chain_id = self.proxy.contract.functions.chain_id().call() return ChannelDetails( chain_id=chain_id, channel_data=channel_data, participants_data=participants_data, )
python
def detail( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ChannelDetails: """ Returns a ChannelDetails instance with all the details of the channel and the channel participants. Note: For now one of the participants has to be the node_address """ if self.node_address not in (participant1, participant2): raise ValueError('One participant must be the node address') if self.node_address == participant2: participant1, participant2 = participant2, participant1 channel_data = self._detail_channel( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) participants_data = self.detail_participants( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_data.channel_identifier, ) chain_id = self.proxy.contract.functions.chain_id().call() return ChannelDetails( chain_id=chain_id, channel_data=channel_data, participants_data=participants_data, )
[ "def", "detail", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", "=", "None", ",", ")", "->", "ChannelDetails", ":", "if", "...
Returns a ChannelDetails instance with all the details of the channel and the channel participants. Note: For now one of the participants has to be the node_address
[ "Returns", "a", "ChannelDetails", "instance", "with", "all", "the", "details", "of", "the", "channel", "and", "the", "channel", "participants", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L458-L495
train
216,407
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.channel_is_opened
def channel_is_opened( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in an open state, false otherwise. """ try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False return channel_state == ChannelState.OPENED
python
def channel_is_opened( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in an open state, false otherwise. """ try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False return channel_state == ChannelState.OPENED
[ "def", "channel_is_opened", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", ",", ")", "->", "bool", ":", "try", ":", "channel_...
Returns true if the channel is in an open state, false otherwise.
[ "Returns", "true", "if", "the", "channel", "is", "in", "an", "open", "state", "false", "otherwise", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L505-L522
train
216,408
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.channel_is_closed
def channel_is_closed( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in a closed state, false otherwise. """ try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False return channel_state == ChannelState.CLOSED
python
def channel_is_closed( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in a closed state, false otherwise. """ try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False return channel_state == ChannelState.CLOSED
[ "def", "channel_is_closed", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", ",", ")", "->", "bool", ":", "try", ":", "channel_...
Returns true if the channel is in a closed state, false otherwise.
[ "Returns", "true", "if", "the", "channel", "is", "in", "a", "closed", "state", "false", "otherwise", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L524-L541
train
216,409
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.channel_is_settled
def channel_is_settled( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in a settled state, false otherwise. """ try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False return channel_state >= ChannelState.SETTLED
python
def channel_is_settled( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in a settled state, false otherwise. """ try: channel_state = self._get_channel_state( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return False return channel_state >= ChannelState.SETTLED
[ "def", "channel_is_settled", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", ",", ")", "->", "bool", ":", "try", ":", "channel...
Returns true if the channel is in a settled state, false otherwise.
[ "Returns", "true", "if", "the", "channel", "is", "in", "a", "settled", "state", "false", "otherwise", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L543-L560
train
216,410
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.closing_address
def closing_address( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> Optional[Address]: """ Returns the address of the closer, if the channel is closed and not settled. None otherwise. """ try: channel_data = self._detail_channel( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return None if channel_data.state >= ChannelState.SETTLED: return None participants_data = self.detail_participants( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_data.channel_identifier, ) if participants_data.our_details.is_closer: return participants_data.our_details.address elif participants_data.partner_details.is_closer: return participants_data.partner_details.address return None
python
def closing_address( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> Optional[Address]: """ Returns the address of the closer, if the channel is closed and not settled. None otherwise. """ try: channel_data = self._detail_channel( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_identifier, ) except RaidenRecoverableError: return None if channel_data.state >= ChannelState.SETTLED: return None participants_data = self.detail_participants( participant1=participant1, participant2=participant2, block_identifier=block_identifier, channel_identifier=channel_data.channel_identifier, ) if participants_data.our_details.is_closer: return participants_data.our_details.address elif participants_data.partner_details.is_closer: return participants_data.partner_details.address return None
[ "def", "closing_address", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", "=", "None", ",", ")", "->", "Optional", "[", "Addre...
Returns the address of the closer, if the channel is closed and not settled. None otherwise.
[ "Returns", "the", "address", "of", "the", "closer", "if", "the", "channel", "is", "closed", "and", "not", "settled", ".", "None", "otherwise", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L562-L597
train
216,411
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.set_total_deposit
def set_total_deposit( self, given_block_identifier: BlockSpecification, channel_identifier: ChannelID, total_deposit: TokenAmount, partner: Address, ): """ Set channel's total deposit. `total_deposit` has to be monotonically increasing, this is enforced by the `TokenNetwork` smart contract. This is done for the same reason why the balance proofs have a monotonically increasing transferred amount, it simplifies the analysis of bad behavior and the handling code of out-dated balance proofs. Races to `set_total_deposit` are handled by the smart contract, where largest total deposit wins. The end balance of the funding accounts is undefined. E.g. - Acc1 calls set_total_deposit with 10 tokens - Acc2 calls set_total_deposit with 13 tokens - If Acc2's transaction is mined first, then Acc1 token supply is left intact. - If Acc1's transaction is mined first, then Acc2 will only move 3 tokens. Races for the same account don't have any unexpeted side-effect. Raises: DepositMismatch: If the new request total deposit is lower than the existing total deposit on-chain for the `given_block_identifier`. RaidenRecoverableError: If the channel was closed meanwhile the deposit was in transit. RaidenUnrecoverableError: If the transaction was sucessful and the deposit_amount is not as large as the requested value. RuntimeError: If the token address is empty. ValueError: If an argument is of the invalid type. """ if not isinstance(total_deposit, int): raise ValueError('total_deposit needs to be an integer number.') token_address = self.token_address() token = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) checking_block = self.client.get_checking_block() error_prefix = 'setTotalDeposit call will fail' with self.channel_operations_lock[partner], self.deposit_lock: previous_total_deposit = self._detail_participant( channel_identifier=channel_identifier, participant=self.node_address, partner=partner, block_identifier=given_block_identifier, ).deposit amount_to_deposit = TokenAmount(total_deposit - previous_total_deposit) log_details = { 'token_network': pex(self.address), 'channel_identifier': channel_identifier, 'node': pex(self.node_address), 'partner': pex(partner), 'new_total_deposit': total_deposit, 'previous_total_deposit': previous_total_deposit, } try: self._deposit_preconditions( channel_identifier=channel_identifier, total_deposit=total_deposit, partner=partner, token=token, previous_total_deposit=previous_total_deposit, log_details=log_details, block_identifier=given_block_identifier, ) except NoStateForBlockIdentifier: # If preconditions end up being on pruned state skip them. Estimate # gas will stop us from sending a transaction that will fail pass # If there are channels being set up concurrenlty either the # allowance must be accumulated *or* the calls to `approve` and # `setTotalDeposit` must be serialized. This is necessary otherwise # the deposit will fail. # # Calls to approve and setTotalDeposit are serialized with the # deposit_lock to avoid transaction failure, because with two # concurrent deposits, we may have the transactions executed in the # following order # # - approve # - approve # - setTotalDeposit # - setTotalDeposit # # in which case the second `approve` will overwrite the first, # and the first `setTotalDeposit` will consume the allowance, # making the second deposit fail. token.approve( allowed_address=Address(self.address), allowance=amount_to_deposit, ) gas_limit = self.proxy.estimate_gas( checking_block, 'setTotalDeposit', channel_identifier=channel_identifier, participant=self.node_address, total_deposit=total_deposit, partner=partner, ) if gas_limit: gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT) error_prefix = 'setTotalDeposit call failed' log.debug('setTotalDeposit called', **log_details) transaction_hash = self.proxy.transact( 'setTotalDeposit', gas_limit, channel_identifier=channel_identifier, participant=self.node_address, total_deposit=total_deposit, partner=partner, ) 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='setTotalDeposit', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT, block_identifier=block, ) error_type, msg = self._check_why_deposit_failed( channel_identifier=channel_identifier, partner=partner, token=token, amount_to_deposit=amount_to_deposit, total_deposit=total_deposit, transaction_executed=transaction_executed, block_identifier=block, ) error_msg = f'{error_prefix}. {msg}' if error_type == RaidenRecoverableError: log.warning(error_msg, **log_details) else: log.critical(error_msg, **log_details) raise error_type(error_msg) log.info('setTotalDeposit successful', **log_details)
python
def set_total_deposit( self, given_block_identifier: BlockSpecification, channel_identifier: ChannelID, total_deposit: TokenAmount, partner: Address, ): """ Set channel's total deposit. `total_deposit` has to be monotonically increasing, this is enforced by the `TokenNetwork` smart contract. This is done for the same reason why the balance proofs have a monotonically increasing transferred amount, it simplifies the analysis of bad behavior and the handling code of out-dated balance proofs. Races to `set_total_deposit` are handled by the smart contract, where largest total deposit wins. The end balance of the funding accounts is undefined. E.g. - Acc1 calls set_total_deposit with 10 tokens - Acc2 calls set_total_deposit with 13 tokens - If Acc2's transaction is mined first, then Acc1 token supply is left intact. - If Acc1's transaction is mined first, then Acc2 will only move 3 tokens. Races for the same account don't have any unexpeted side-effect. Raises: DepositMismatch: If the new request total deposit is lower than the existing total deposit on-chain for the `given_block_identifier`. RaidenRecoverableError: If the channel was closed meanwhile the deposit was in transit. RaidenUnrecoverableError: If the transaction was sucessful and the deposit_amount is not as large as the requested value. RuntimeError: If the token address is empty. ValueError: If an argument is of the invalid type. """ if not isinstance(total_deposit, int): raise ValueError('total_deposit needs to be an integer number.') token_address = self.token_address() token = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) checking_block = self.client.get_checking_block() error_prefix = 'setTotalDeposit call will fail' with self.channel_operations_lock[partner], self.deposit_lock: previous_total_deposit = self._detail_participant( channel_identifier=channel_identifier, participant=self.node_address, partner=partner, block_identifier=given_block_identifier, ).deposit amount_to_deposit = TokenAmount(total_deposit - previous_total_deposit) log_details = { 'token_network': pex(self.address), 'channel_identifier': channel_identifier, 'node': pex(self.node_address), 'partner': pex(partner), 'new_total_deposit': total_deposit, 'previous_total_deposit': previous_total_deposit, } try: self._deposit_preconditions( channel_identifier=channel_identifier, total_deposit=total_deposit, partner=partner, token=token, previous_total_deposit=previous_total_deposit, log_details=log_details, block_identifier=given_block_identifier, ) except NoStateForBlockIdentifier: # If preconditions end up being on pruned state skip them. Estimate # gas will stop us from sending a transaction that will fail pass # If there are channels being set up concurrenlty either the # allowance must be accumulated *or* the calls to `approve` and # `setTotalDeposit` must be serialized. This is necessary otherwise # the deposit will fail. # # Calls to approve and setTotalDeposit are serialized with the # deposit_lock to avoid transaction failure, because with two # concurrent deposits, we may have the transactions executed in the # following order # # - approve # - approve # - setTotalDeposit # - setTotalDeposit # # in which case the second `approve` will overwrite the first, # and the first `setTotalDeposit` will consume the allowance, # making the second deposit fail. token.approve( allowed_address=Address(self.address), allowance=amount_to_deposit, ) gas_limit = self.proxy.estimate_gas( checking_block, 'setTotalDeposit', channel_identifier=channel_identifier, participant=self.node_address, total_deposit=total_deposit, partner=partner, ) if gas_limit: gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT) error_prefix = 'setTotalDeposit call failed' log.debug('setTotalDeposit called', **log_details) transaction_hash = self.proxy.transact( 'setTotalDeposit', gas_limit, channel_identifier=channel_identifier, participant=self.node_address, total_deposit=total_deposit, partner=partner, ) 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='setTotalDeposit', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT, block_identifier=block, ) error_type, msg = self._check_why_deposit_failed( channel_identifier=channel_identifier, partner=partner, token=token, amount_to_deposit=amount_to_deposit, total_deposit=total_deposit, transaction_executed=transaction_executed, block_identifier=block, ) error_msg = f'{error_prefix}. {msg}' if error_type == RaidenRecoverableError: log.warning(error_msg, **log_details) else: log.critical(error_msg, **log_details) raise error_type(error_msg) log.info('setTotalDeposit successful', **log_details)
[ "def", "set_total_deposit", "(", "self", ",", "given_block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", ",", "total_deposit", ":", "TokenAmount", ",", "partner", ":", "Address", ",", ")", ":", "if", "not", "isinstance", "(",...
Set channel's total deposit. `total_deposit` has to be monotonically increasing, this is enforced by the `TokenNetwork` smart contract. This is done for the same reason why the balance proofs have a monotonically increasing transferred amount, it simplifies the analysis of bad behavior and the handling code of out-dated balance proofs. Races to `set_total_deposit` are handled by the smart contract, where largest total deposit wins. The end balance of the funding accounts is undefined. E.g. - Acc1 calls set_total_deposit with 10 tokens - Acc2 calls set_total_deposit with 13 tokens - If Acc2's transaction is mined first, then Acc1 token supply is left intact. - If Acc1's transaction is mined first, then Acc2 will only move 3 tokens. Races for the same account don't have any unexpeted side-effect. Raises: DepositMismatch: If the new request total deposit is lower than the existing total deposit on-chain for the `given_block_identifier`. RaidenRecoverableError: If the channel was closed meanwhile the deposit was in transit. RaidenUnrecoverableError: If the transaction was sucessful and the deposit_amount is not as large as the requested value. RuntimeError: If the token address is empty. ValueError: If an argument is of the invalid type.
[ "Set", "channel", "s", "total", "deposit", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L681-L837
train
216,412
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.close
def close( self, channel_identifier: ChannelID, partner: Address, balance_hash: BalanceHash, nonce: Nonce, additional_hash: AdditionalHash, signature: Signature, given_block_identifier: BlockSpecification, ): """ Close the channel using the provided balance proof. Note: This method must *not* be called without updating the application state, otherwise the node may accept new transfers which cannot be used, because the closer is not allowed to update the balance proof submitted on chain after closing Raises: RaidenRecoverableError: If the channel is already closed. RaidenUnrecoverableError: If the channel does not exist or is settled. """ log_details = { 'token_network': pex(self.address), 'node': pex(self.node_address), 'partner': pex(partner), 'nonce': nonce, 'balance_hash': encode_hex(balance_hash), 'additional_hash': encode_hex(additional_hash), 'signature': encode_hex(signature), } log.debug('closeChannel called', **log_details) checking_block = self.client.get_checking_block() try: self._close_preconditions( channel_identifier, partner=partner, block_identifier=given_block_identifier, ) except NoStateForBlockIdentifier: # If preconditions end up being on pruned state skip them. Estimate # gas will stop us from sending a transaction that will fail pass error_prefix = 'closeChannel call will fail' with self.channel_operations_lock[partner]: gas_limit = self.proxy.estimate_gas( checking_block, 'closeChannel', channel_identifier=channel_identifier, partner=partner, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature, ) if gas_limit: error_prefix = 'closeChannel call failed' transaction_hash = self.proxy.transact( 'closeChannel', safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_CLOSE_CHANNEL), channel_identifier=channel_identifier, partner=partner, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature, ) 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='closeChannel', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_CLOSE_CHANNEL, block_identifier=block, ) error_type, msg = self._check_channel_state_for_close( participant1=self.node_address, participant2=partner, block_identifier=block, channel_identifier=channel_identifier, ) if not error_type: # error_type can also be None above in which case it's # unknown reason why we would fail. error_type = RaidenUnrecoverableError error_msg = f'{error_prefix}. {msg}' if error_type == RaidenRecoverableError: log.warning(error_msg, **log_details) else: log.critical(error_msg, **log_details) raise error_type(error_msg) log.info('closeChannel successful', **log_details)
python
def close( self, channel_identifier: ChannelID, partner: Address, balance_hash: BalanceHash, nonce: Nonce, additional_hash: AdditionalHash, signature: Signature, given_block_identifier: BlockSpecification, ): """ Close the channel using the provided balance proof. Note: This method must *not* be called without updating the application state, otherwise the node may accept new transfers which cannot be used, because the closer is not allowed to update the balance proof submitted on chain after closing Raises: RaidenRecoverableError: If the channel is already closed. RaidenUnrecoverableError: If the channel does not exist or is settled. """ log_details = { 'token_network': pex(self.address), 'node': pex(self.node_address), 'partner': pex(partner), 'nonce': nonce, 'balance_hash': encode_hex(balance_hash), 'additional_hash': encode_hex(additional_hash), 'signature': encode_hex(signature), } log.debug('closeChannel called', **log_details) checking_block = self.client.get_checking_block() try: self._close_preconditions( channel_identifier, partner=partner, block_identifier=given_block_identifier, ) except NoStateForBlockIdentifier: # If preconditions end up being on pruned state skip them. Estimate # gas will stop us from sending a transaction that will fail pass error_prefix = 'closeChannel call will fail' with self.channel_operations_lock[partner]: gas_limit = self.proxy.estimate_gas( checking_block, 'closeChannel', channel_identifier=channel_identifier, partner=partner, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature, ) if gas_limit: error_prefix = 'closeChannel call failed' transaction_hash = self.proxy.transact( 'closeChannel', safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_CLOSE_CHANNEL), channel_identifier=channel_identifier, partner=partner, balance_hash=balance_hash, nonce=nonce, additional_hash=additional_hash, signature=signature, ) 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='closeChannel', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_CLOSE_CHANNEL, block_identifier=block, ) error_type, msg = self._check_channel_state_for_close( participant1=self.node_address, participant2=partner, block_identifier=block, channel_identifier=channel_identifier, ) if not error_type: # error_type can also be None above in which case it's # unknown reason why we would fail. error_type = RaidenUnrecoverableError error_msg = f'{error_prefix}. {msg}' if error_type == RaidenRecoverableError: log.warning(error_msg, **log_details) else: log.critical(error_msg, **log_details) raise error_type(error_msg) log.info('closeChannel successful', **log_details)
[ "def", "close", "(", "self", ",", "channel_identifier", ":", "ChannelID", ",", "partner", ":", "Address", ",", "balance_hash", ":", "BalanceHash", ",", "nonce", ":", "Nonce", ",", "additional_hash", ":", "AdditionalHash", ",", "signature", ":", "Signature", ",...
Close the channel using the provided balance proof. Note: This method must *not* be called without updating the application state, otherwise the node may accept new transfers which cannot be used, because the closer is not allowed to update the balance proof submitted on chain after closing Raises: RaidenRecoverableError: If the channel is already closed. RaidenUnrecoverableError: If the channel does not exist or is settled.
[ "Close", "the", "channel", "using", "the", "provided", "balance", "proof", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L928-L1033
train
216,413
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.settle
def settle( self, channel_identifier: ChannelID, transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, partner: Address, partner_transferred_amount: TokenAmount, partner_locked_amount: TokenAmount, partner_locksroot: Locksroot, given_block_identifier: BlockSpecification, ): """ Settle the channel. """ log_details = { 'channel_identifier': channel_identifier, 'token_network': pex(self.address), 'node': pex(self.node_address), 'partner': pex(partner), 'transferred_amount': transferred_amount, 'locked_amount': locked_amount, 'locksroot': encode_hex(locksroot), 'partner_transferred_amount': partner_transferred_amount, 'partner_locked_amount': partner_locked_amount, 'partner_locksroot': encode_hex(partner_locksroot), } log.debug('settle called', **log_details) checking_block = self.client.get_checking_block() # and now find out our_maximum = transferred_amount + locked_amount partner_maximum = partner_transferred_amount + partner_locked_amount # The second participant transferred + locked amount must be higher our_bp_is_larger = our_maximum > partner_maximum if our_bp_is_larger: kwargs = { 'participant1': partner, 'participant1_transferred_amount': partner_transferred_amount, 'participant1_locked_amount': partner_locked_amount, 'participant1_locksroot': partner_locksroot, 'participant2': self.node_address, 'participant2_transferred_amount': transferred_amount, 'participant2_locked_amount': locked_amount, 'participant2_locksroot': locksroot, } else: kwargs = { 'participant1': self.node_address, 'participant1_transferred_amount': transferred_amount, 'participant1_locked_amount': locked_amount, 'participant1_locksroot': locksroot, 'participant2': partner, 'participant2_transferred_amount': partner_transferred_amount, 'participant2_locked_amount': partner_locked_amount, 'participant2_locksroot': partner_locksroot, } try: self._settle_preconditions( channel_identifier=channel_identifier, partner=partner, block_identifier=given_block_identifier, ) except NoStateForBlockIdentifier: # If preconditions end up being on pruned state skip them. Estimate # gas will stop us from sending a transaction that will fail pass with self.channel_operations_lock[partner]: error_prefix = 'Call to settle will fail' gas_limit = self.proxy.estimate_gas( checking_block, 'settleChannel', channel_identifier=channel_identifier, **kwargs, ) if gas_limit: error_prefix = 'settle call failed' gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SETTLE_CHANNEL) transaction_hash = self.proxy.transact( 'settleChannel', gas_limit, channel_identifier=channel_identifier, **kwargs, ) 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='settleChannel', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_SETTLE_CHANNEL, block_identifier=block, ) msg = self._check_channel_state_after_settle( participant1=self.node_address, participant2=partner, block_identifier=block, channel_identifier=channel_identifier, ) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('settle successful', **log_details)
python
def settle( self, channel_identifier: ChannelID, transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, partner: Address, partner_transferred_amount: TokenAmount, partner_locked_amount: TokenAmount, partner_locksroot: Locksroot, given_block_identifier: BlockSpecification, ): """ Settle the channel. """ log_details = { 'channel_identifier': channel_identifier, 'token_network': pex(self.address), 'node': pex(self.node_address), 'partner': pex(partner), 'transferred_amount': transferred_amount, 'locked_amount': locked_amount, 'locksroot': encode_hex(locksroot), 'partner_transferred_amount': partner_transferred_amount, 'partner_locked_amount': partner_locked_amount, 'partner_locksroot': encode_hex(partner_locksroot), } log.debug('settle called', **log_details) checking_block = self.client.get_checking_block() # and now find out our_maximum = transferred_amount + locked_amount partner_maximum = partner_transferred_amount + partner_locked_amount # The second participant transferred + locked amount must be higher our_bp_is_larger = our_maximum > partner_maximum if our_bp_is_larger: kwargs = { 'participant1': partner, 'participant1_transferred_amount': partner_transferred_amount, 'participant1_locked_amount': partner_locked_amount, 'participant1_locksroot': partner_locksroot, 'participant2': self.node_address, 'participant2_transferred_amount': transferred_amount, 'participant2_locked_amount': locked_amount, 'participant2_locksroot': locksroot, } else: kwargs = { 'participant1': self.node_address, 'participant1_transferred_amount': transferred_amount, 'participant1_locked_amount': locked_amount, 'participant1_locksroot': locksroot, 'participant2': partner, 'participant2_transferred_amount': partner_transferred_amount, 'participant2_locked_amount': partner_locked_amount, 'participant2_locksroot': partner_locksroot, } try: self._settle_preconditions( channel_identifier=channel_identifier, partner=partner, block_identifier=given_block_identifier, ) except NoStateForBlockIdentifier: # If preconditions end up being on pruned state skip them. Estimate # gas will stop us from sending a transaction that will fail pass with self.channel_operations_lock[partner]: error_prefix = 'Call to settle will fail' gas_limit = self.proxy.estimate_gas( checking_block, 'settleChannel', channel_identifier=channel_identifier, **kwargs, ) if gas_limit: error_prefix = 'settle call failed' gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SETTLE_CHANNEL) transaction_hash = self.proxy.transact( 'settleChannel', gas_limit, channel_identifier=channel_identifier, **kwargs, ) 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='settleChannel', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_SETTLE_CHANNEL, block_identifier=block, ) msg = self._check_channel_state_after_settle( participant1=self.node_address, participant2=partner, block_identifier=block, channel_identifier=channel_identifier, ) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('settle successful', **log_details)
[ "def", "settle", "(", "self", ",", "channel_identifier", ":", "ChannelID", ",", "transferred_amount", ":", "TokenAmount", ",", "locked_amount", ":", "TokenAmount", ",", "locksroot", ":", "Locksroot", ",", "partner", ":", "Address", ",", "partner_transferred_amount",...
Settle the channel.
[ "Settle", "the", "channel", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1337-L1449
train
216,414
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.events_filter
def events_filter( self, topics: List[str] = None, from_block: BlockSpecification = None, to_block: BlockSpecification = None, ) -> StatelessFilter: """ Install a new filter for an array of topics emitted by the contract. Args: topics: A list of event ids to filter for. Can also be None, in which case all events are queried. from_block: The block number at which to start looking for events. to_block: The block number at which to stop looking for events. Return: Filter: The filter instance. """ return self.client.new_filter( self.address, topics=topics, from_block=from_block, to_block=to_block, )
python
def events_filter( self, topics: List[str] = None, from_block: BlockSpecification = None, to_block: BlockSpecification = None, ) -> StatelessFilter: """ Install a new filter for an array of topics emitted by the contract. Args: topics: A list of event ids to filter for. Can also be None, in which case all events are queried. from_block: The block number at which to start looking for events. to_block: The block number at which to stop looking for events. Return: Filter: The filter instance. """ return self.client.new_filter( self.address, topics=topics, from_block=from_block, to_block=to_block, )
[ "def", "events_filter", "(", "self", ",", "topics", ":", "List", "[", "str", "]", "=", "None", ",", "from_block", ":", "BlockSpecification", "=", "None", ",", "to_block", ":", "BlockSpecification", "=", "None", ",", ")", "->", "StatelessFilter", ":", "retu...
Install a new filter for an array of topics emitted by the contract. Args: topics: A list of event ids to filter for. Can also be None, in which case all events are queried. from_block: The block number at which to start looking for events. to_block: The block number at which to stop looking for events. Return: Filter: The filter instance.
[ "Install", "a", "new", "filter", "for", "an", "array", "of", "topics", "emitted", "by", "the", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1451-L1472
train
216,415
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork.all_events_filter
def all_events_filter( self, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ) -> StatelessFilter: """ Install a new filter for all the events emitted by the current token network contract Args: from_block: Create filter starting from this block number (default: 0). to_block: Create filter stopping at this block number (default: 'latest'). Return: The filter instance. """ return self.events_filter(None, from_block, to_block)
python
def all_events_filter( self, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ) -> StatelessFilter: """ Install a new filter for all the events emitted by the current token network contract Args: from_block: Create filter starting from this block number (default: 0). to_block: Create filter stopping at this block number (default: 'latest'). Return: The filter instance. """ return self.events_filter(None, from_block, to_block)
[ "def", "all_events_filter", "(", "self", ",", "from_block", ":", "BlockSpecification", "=", "GENESIS_BLOCK_NUMBER", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", ",", ")", "->", "StatelessFilter", ":", "return", "self", ".", "events_filter", "(", "N...
Install a new filter for all the events emitted by the current token network contract Args: from_block: Create filter starting from this block number (default: 0). to_block: Create filter stopping at this block number (default: 'latest'). Return: The filter instance.
[ "Install", "a", "new", "filter", "for", "all", "the", "events", "emitted", "by", "the", "current", "token", "network", "contract" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1474-L1488
train
216,416
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork._check_for_outdated_channel
def _check_for_outdated_channel( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> None: """ Checks whether an operation is being executed on a channel between two participants using an old channel identifier """ try: onchain_channel_details = self._detail_channel( participant1=participant1, participant2=participant2, block_identifier=block_identifier, ) except RaidenRecoverableError: return onchain_channel_identifier = onchain_channel_details.channel_identifier if onchain_channel_identifier != channel_identifier: raise ChannelOutdatedError( 'Current channel identifier is outdated. ' f'current={channel_identifier}, ' f'new={onchain_channel_identifier}', )
python
def _check_for_outdated_channel( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> None: """ Checks whether an operation is being executed on a channel between two participants using an old channel identifier """ try: onchain_channel_details = self._detail_channel( participant1=participant1, participant2=participant2, block_identifier=block_identifier, ) except RaidenRecoverableError: return onchain_channel_identifier = onchain_channel_details.channel_identifier if onchain_channel_identifier != channel_identifier: raise ChannelOutdatedError( 'Current channel identifier is outdated. ' f'current={channel_identifier}, ' f'new={onchain_channel_identifier}', )
[ "def", "_check_for_outdated_channel", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", ",", ")", "->", "None", ":", "try", ":", ...
Checks whether an operation is being executed on a channel between two participants using an old channel identifier
[ "Checks", "whether", "an", "operation", "is", "being", "executed", "on", "a", "channel", "between", "two", "participants", "using", "an", "old", "channel", "identifier" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1490-L1517
train
216,417
raiden-network/raiden
raiden/network/proxies/token_network.py
TokenNetwork._check_channel_state_for_update
def _check_channel_state_for_update( self, channel_identifier: ChannelID, closer: Address, update_nonce: Nonce, block_identifier: BlockSpecification, ) -> Optional[str]: """Check the channel state on chain to see if it has been updated. Compare the nonce, we are about to update the contract with, with the updated nonce in the onchain state and, if it's the same, return a message with which the caller should raise a RaidenRecoverableError. If all is okay return None. """ msg = None closer_details = self._detail_participant( channel_identifier=channel_identifier, participant=closer, partner=self.node_address, block_identifier=block_identifier, ) if closer_details.nonce == update_nonce: msg = ( 'updateNonClosingBalanceProof transaction has already ' 'been mined and updated the channel succesfully.' ) return msg
python
def _check_channel_state_for_update( self, channel_identifier: ChannelID, closer: Address, update_nonce: Nonce, block_identifier: BlockSpecification, ) -> Optional[str]: """Check the channel state on chain to see if it has been updated. Compare the nonce, we are about to update the contract with, with the updated nonce in the onchain state and, if it's the same, return a message with which the caller should raise a RaidenRecoverableError. If all is okay return None. """ msg = None closer_details = self._detail_participant( channel_identifier=channel_identifier, participant=closer, partner=self.node_address, block_identifier=block_identifier, ) if closer_details.nonce == update_nonce: msg = ( 'updateNonClosingBalanceProof transaction has already ' 'been mined and updated the channel succesfully.' ) return msg
[ "def", "_check_channel_state_for_update", "(", "self", ",", "channel_identifier", ":", "ChannelID", ",", "closer", ":", "Address", ",", "update_nonce", ":", "Nonce", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "Optional", "[", "str", "]", ...
Check the channel state on chain to see if it has been updated. Compare the nonce, we are about to update the contract with, with the updated nonce in the onchain state and, if it's the same, return a message with which the caller should raise a RaidenRecoverableError. If all is okay return None.
[ "Check", "the", "channel", "state", "on", "chain", "to", "see", "if", "it", "has", "been", "updated", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network.py#L1624-L1652
train
216,418
raiden-network/raiden
raiden/network/transport/udp/udp_utils.py
event_first_of
def event_first_of(*events: _AbstractLinkable) -> Event: """ Waits until one of `events` is set. The event returned is /not/ cleared with any of the `events`, this value must not be reused if the clearing behavior is used. """ first_finished = Event() if not all(isinstance(e, _AbstractLinkable) for e in events): raise ValueError('all events must be linkable') for event in events: event.rawlink(lambda _: first_finished.set()) return first_finished
python
def event_first_of(*events: _AbstractLinkable) -> Event: """ Waits until one of `events` is set. The event returned is /not/ cleared with any of the `events`, this value must not be reused if the clearing behavior is used. """ first_finished = Event() if not all(isinstance(e, _AbstractLinkable) for e in events): raise ValueError('all events must be linkable') for event in events: event.rawlink(lambda _: first_finished.set()) return first_finished
[ "def", "event_first_of", "(", "*", "events", ":", "_AbstractLinkable", ")", "->", "Event", ":", "first_finished", "=", "Event", "(", ")", "if", "not", "all", "(", "isinstance", "(", "e", ",", "_AbstractLinkable", ")", "for", "e", "in", "events", ")", ":"...
Waits until one of `events` is set. The event returned is /not/ cleared with any of the `events`, this value must not be reused if the clearing behavior is used.
[ "Waits", "until", "one", "of", "events", "is", "set", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L18-L32
train
216,419
raiden-network/raiden
raiden/network/transport/udp/udp_utils.py
timeout_exponential_backoff
def timeout_exponential_backoff( retries: int, timeout: int, maximum: int, ) -> Iterator[int]: """ Timeouts generator with an exponential backoff strategy. Timeouts start spaced by `timeout`, after `retries` exponentially increase the retry delays until `maximum`, then maximum is returned indefinitely. """ yield timeout tries = 1 while tries < retries: tries += 1 yield timeout while timeout < maximum: timeout = min(timeout * 2, maximum) yield timeout while True: yield maximum
python
def timeout_exponential_backoff( retries: int, timeout: int, maximum: int, ) -> Iterator[int]: """ Timeouts generator with an exponential backoff strategy. Timeouts start spaced by `timeout`, after `retries` exponentially increase the retry delays until `maximum`, then maximum is returned indefinitely. """ yield timeout tries = 1 while tries < retries: tries += 1 yield timeout while timeout < maximum: timeout = min(timeout * 2, maximum) yield timeout while True: yield maximum
[ "def", "timeout_exponential_backoff", "(", "retries", ":", "int", ",", "timeout", ":", "int", ",", "maximum", ":", "int", ",", ")", "->", "Iterator", "[", "int", "]", ":", "yield", "timeout", "tries", "=", "1", "while", "tries", "<", "retries", ":", "t...
Timeouts generator with an exponential backoff strategy. Timeouts start spaced by `timeout`, after `retries` exponentially increase the retry delays until `maximum`, then maximum is returned indefinitely.
[ "Timeouts", "generator", "with", "an", "exponential", "backoff", "strategy", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L35-L57
train
216,420
raiden-network/raiden
raiden/network/transport/udp/udp_utils.py
timeout_two_stage
def timeout_two_stage( retries: int, timeout1: int, timeout2: int, ) -> Iterable[int]: """ Timeouts generator with a two stage strategy Timeouts start spaced by `timeout1`, after `retries` increase to `timeout2` which is repeated indefinitely. """ for _ in range(retries): yield timeout1 while True: yield timeout2
python
def timeout_two_stage( retries: int, timeout1: int, timeout2: int, ) -> Iterable[int]: """ Timeouts generator with a two stage strategy Timeouts start spaced by `timeout1`, after `retries` increase to `timeout2` which is repeated indefinitely. """ for _ in range(retries): yield timeout1 while True: yield timeout2
[ "def", "timeout_two_stage", "(", "retries", ":", "int", ",", "timeout1", ":", "int", ",", "timeout2", ":", "int", ",", ")", "->", "Iterable", "[", "int", "]", ":", "for", "_", "in", "range", "(", "retries", ")", ":", "yield", "timeout1", "while", "Tr...
Timeouts generator with a two stage strategy Timeouts start spaced by `timeout1`, after `retries` increase to `timeout2` which is repeated indefinitely.
[ "Timeouts", "generator", "with", "a", "two", "stage", "strategy" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L60-L73
train
216,421
raiden-network/raiden
raiden/network/transport/udp/udp_utils.py
retry
def retry( transport: 'UDPTransport', messagedata: bytes, message_id: UDPMessageID, recipient: Address, stop_event: Event, timeout_backoff: Iterable[int], ) -> bool: """ Send messagedata until it's acknowledged. Exit when: - The message is delivered. - Event_stop is set. - The iterator timeout_backoff runs out. Returns: bool: True if the message was acknowledged, False otherwise. """ async_result = transport.maybe_sendraw_with_result( recipient, messagedata, message_id, ) event_quit = event_first_of( async_result, stop_event, ) for timeout in timeout_backoff: if event_quit.wait(timeout=timeout) is True: break log.debug( 'retrying message', node=pex(transport.raiden.address), recipient=pex(recipient), msgid=message_id, ) transport.maybe_sendraw_with_result( recipient, messagedata, message_id, ) return async_result.ready()
python
def retry( transport: 'UDPTransport', messagedata: bytes, message_id: UDPMessageID, recipient: Address, stop_event: Event, timeout_backoff: Iterable[int], ) -> bool: """ Send messagedata until it's acknowledged. Exit when: - The message is delivered. - Event_stop is set. - The iterator timeout_backoff runs out. Returns: bool: True if the message was acknowledged, False otherwise. """ async_result = transport.maybe_sendraw_with_result( recipient, messagedata, message_id, ) event_quit = event_first_of( async_result, stop_event, ) for timeout in timeout_backoff: if event_quit.wait(timeout=timeout) is True: break log.debug( 'retrying message', node=pex(transport.raiden.address), recipient=pex(recipient), msgid=message_id, ) transport.maybe_sendraw_with_result( recipient, messagedata, message_id, ) return async_result.ready()
[ "def", "retry", "(", "transport", ":", "'UDPTransport'", ",", "messagedata", ":", "bytes", ",", "message_id", ":", "UDPMessageID", ",", "recipient", ":", "Address", ",", "stop_event", ":", "Event", ",", "timeout_backoff", ":", "Iterable", "[", "int", "]", ",...
Send messagedata until it's acknowledged. Exit when: - The message is delivered. - Event_stop is set. - The iterator timeout_backoff runs out. Returns: bool: True if the message was acknowledged, False otherwise.
[ "Send", "messagedata", "until", "it", "s", "acknowledged", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L76-L125
train
216,422
raiden-network/raiden
raiden/network/transport/udp/udp_utils.py
retry_with_recovery
def retry_with_recovery( transport: 'UDPTransport', messagedata: bytes, message_id: UDPMessageID, recipient: Address, stop_event: Event, event_healthy: Event, event_unhealthy: Event, backoff: Iterable[int], ) -> bool: """ Send messagedata while the node is healthy until it's acknowledged. Note: backoff must be an infinite iterator, otherwise this task will become a hot loop. """ # The underlying unhealthy will be cleared, care must be taken to properly # clear stop_or_unhealthy too. stop_or_unhealthy = event_first_of( stop_event, event_unhealthy, ) acknowledged = False while not stop_event.is_set() and not acknowledged: # Packets must not be sent to an unhealthy node, nor should the task # wait for it to become available if the message has been acknowledged. if event_unhealthy.is_set(): log.debug( 'waiting for recipient to become available', node=pex(transport.raiden.address), recipient=pex(recipient), ) wait_recovery( stop_event, event_healthy, ) # Assume wait_recovery returned because unhealthy was cleared and # continue execution, this is safe to do because stop_event is # checked below. stop_or_unhealthy.clear() if stop_event.is_set(): return acknowledged acknowledged = retry( transport, messagedata, message_id, recipient, # retry will stop when this event is set, allowing this task to # wait for recovery when the node becomes unhealthy or to quit if # the stop event is set. stop_or_unhealthy, # Intentionally reusing backoff to restart from the last # timeout/number of iterations. backoff, ) return acknowledged
python
def retry_with_recovery( transport: 'UDPTransport', messagedata: bytes, message_id: UDPMessageID, recipient: Address, stop_event: Event, event_healthy: Event, event_unhealthy: Event, backoff: Iterable[int], ) -> bool: """ Send messagedata while the node is healthy until it's acknowledged. Note: backoff must be an infinite iterator, otherwise this task will become a hot loop. """ # The underlying unhealthy will be cleared, care must be taken to properly # clear stop_or_unhealthy too. stop_or_unhealthy = event_first_of( stop_event, event_unhealthy, ) acknowledged = False while not stop_event.is_set() and not acknowledged: # Packets must not be sent to an unhealthy node, nor should the task # wait for it to become available if the message has been acknowledged. if event_unhealthy.is_set(): log.debug( 'waiting for recipient to become available', node=pex(transport.raiden.address), recipient=pex(recipient), ) wait_recovery( stop_event, event_healthy, ) # Assume wait_recovery returned because unhealthy was cleared and # continue execution, this is safe to do because stop_event is # checked below. stop_or_unhealthy.clear() if stop_event.is_set(): return acknowledged acknowledged = retry( transport, messagedata, message_id, recipient, # retry will stop when this event is set, allowing this task to # wait for recovery when the node becomes unhealthy or to quit if # the stop event is set. stop_or_unhealthy, # Intentionally reusing backoff to restart from the last # timeout/number of iterations. backoff, ) return acknowledged
[ "def", "retry_with_recovery", "(", "transport", ":", "'UDPTransport'", ",", "messagedata", ":", "bytes", ",", "message_id", ":", "UDPMessageID", ",", "recipient", ":", "Address", ",", "stop_event", ":", "Event", ",", "event_healthy", ":", "Event", ",", "event_un...
Send messagedata while the node is healthy until it's acknowledged. Note: backoff must be an infinite iterator, otherwise this task will become a hot loop.
[ "Send", "messagedata", "while", "the", "node", "is", "healthy", "until", "it", "s", "acknowledged", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_utils.py#L142-L206
train
216,423
raiden-network/raiden
raiden/network/proxies/secret_registry.py
SecretRegistry.get_secret_registration_block_by_secrethash
def get_secret_registration_block_by_secrethash( self, secrethash: SecretHash, block_identifier: BlockSpecification, ) -> Optional[BlockNumber]: """Return the block number at which the secret for `secrethash` was registered, None if the secret was never registered. """ result = self.proxy.contract.functions.getSecretRevealBlockHeight( secrethash, ).call(block_identifier=block_identifier) # Block 0 either represents the genesis block or an empty entry in the # secret mapping. This is important for custom genesis files used while # testing. To avoid problems the smart contract can be added as part of # the genesis file, however it's important for its storage to be # empty. if result == 0: return None return result
python
def get_secret_registration_block_by_secrethash( self, secrethash: SecretHash, block_identifier: BlockSpecification, ) -> Optional[BlockNumber]: """Return the block number at which the secret for `secrethash` was registered, None if the secret was never registered. """ result = self.proxy.contract.functions.getSecretRevealBlockHeight( secrethash, ).call(block_identifier=block_identifier) # Block 0 either represents the genesis block or an empty entry in the # secret mapping. This is important for custom genesis files used while # testing. To avoid problems the smart contract can be added as part of # the genesis file, however it's important for its storage to be # empty. if result == 0: return None return result
[ "def", "get_secret_registration_block_by_secrethash", "(", "self", ",", "secrethash", ":", "SecretHash", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "Optional", "[", "BlockNumber", "]", ":", "result", "=", "self", ".", "proxy", ".", "contra...
Return the block number at which the secret for `secrethash` was registered, None if the secret was never registered.
[ "Return", "the", "block", "number", "at", "which", "the", "secret", "for", "secrethash", "was", "registered", "None", "if", "the", "secret", "was", "never", "registered", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/secret_registry.py#L303-L323
train
216,424
raiden-network/raiden
raiden/network/proxies/secret_registry.py
SecretRegistry.is_secret_registered
def is_secret_registered( self, secrethash: SecretHash, block_identifier: BlockSpecification, ) -> bool: """True if the secret for `secrethash` is registered at `block_identifier`. Throws NoStateForBlockIdentifier if the given block_identifier is older than the pruning limit """ if not self.client.can_query_state_for_block(block_identifier): raise NoStateForBlockIdentifier() block = self.get_secret_registration_block_by_secrethash( secrethash=secrethash, block_identifier=block_identifier, ) return block is not None
python
def is_secret_registered( self, secrethash: SecretHash, block_identifier: BlockSpecification, ) -> bool: """True if the secret for `secrethash` is registered at `block_identifier`. Throws NoStateForBlockIdentifier if the given block_identifier is older than the pruning limit """ if not self.client.can_query_state_for_block(block_identifier): raise NoStateForBlockIdentifier() block = self.get_secret_registration_block_by_secrethash( secrethash=secrethash, block_identifier=block_identifier, ) return block is not None
[ "def", "is_secret_registered", "(", "self", ",", "secrethash", ":", "SecretHash", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "bool", ":", "if", "not", "self", ".", "client", ".", "can_query_state_for_block", "(", "block_identifier", ")", ...
True if the secret for `secrethash` is registered at `block_identifier`. Throws NoStateForBlockIdentifier if the given block_identifier is older than the pruning limit
[ "True", "if", "the", "secret", "for", "secrethash", "is", "registered", "at", "block_identifier", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/secret_registry.py#L325-L342
train
216,425
raiden-network/raiden
raiden/ui/console.py
ConsoleTools.register_token
def register_token( self, registry_address_hex: typing.AddressHex, token_address_hex: typing.AddressHex, retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetwork: """ Register a token with the raiden token manager. Args: registry_address: registry address token_address_hex (string): a hex encoded token address. Returns: The token network proxy. """ registry_address = decode_hex(registry_address_hex) token_address = decode_hex(token_address_hex) registry = self._raiden.chain.token_network_registry(registry_address) contracts_version = self._raiden.contract_manager.contracts_version if contracts_version == DEVELOPMENT_CONTRACT_VERSION: token_network_address = registry.add_token_with_limits( token_address=token_address, channel_participant_deposit_limit=UINT256_MAX, token_network_deposit_limit=UINT256_MAX, ) else: token_network_address = registry.add_token_without_limits( token_address=token_address, ) # Register the channel manager with the raiden registry waiting.wait_for_payment_network( self._raiden, registry.address, token_address, retry_timeout, ) return self._raiden.chain.token_network(token_network_address)
python
def register_token( self, registry_address_hex: typing.AddressHex, token_address_hex: typing.AddressHex, retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetwork: """ Register a token with the raiden token manager. Args: registry_address: registry address token_address_hex (string): a hex encoded token address. Returns: The token network proxy. """ registry_address = decode_hex(registry_address_hex) token_address = decode_hex(token_address_hex) registry = self._raiden.chain.token_network_registry(registry_address) contracts_version = self._raiden.contract_manager.contracts_version if contracts_version == DEVELOPMENT_CONTRACT_VERSION: token_network_address = registry.add_token_with_limits( token_address=token_address, channel_participant_deposit_limit=UINT256_MAX, token_network_deposit_limit=UINT256_MAX, ) else: token_network_address = registry.add_token_without_limits( token_address=token_address, ) # Register the channel manager with the raiden registry waiting.wait_for_payment_network( self._raiden, registry.address, token_address, retry_timeout, ) return self._raiden.chain.token_network(token_network_address)
[ "def", "register_token", "(", "self", ",", "registry_address_hex", ":", "typing", ".", "AddressHex", ",", "token_address_hex", ":", "typing", ".", "AddressHex", ",", "retry_timeout", ":", "typing", ".", "NetworkTimeout", "=", "DEFAULT_RETRY_TIMEOUT", ",", ")", "->...
Register a token with the raiden token manager. Args: registry_address: registry address token_address_hex (string): a hex encoded token address. Returns: The token network proxy.
[ "Register", "a", "token", "with", "the", "raiden", "token", "manager", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/console.py#L219-L260
train
216,426
raiden-network/raiden
raiden/ui/console.py
ConsoleTools.open_channel_with_funding
def open_channel_with_funding( self, registry_address_hex, token_address_hex, peer_address_hex, total_deposit, settle_timeout=None, ): """ Convenience method to open a channel. Args: registry_address_hex (str): hex encoded address of the registry for the channel. token_address_hex (str): hex encoded address of the token for the channel. peer_address_hex (str): hex encoded address of the channel peer. total_deposit (int): amount of total funding for the channel. settle_timeout (int): amount of blocks for the settle time (if None use app defaults). Return: netting_channel: the (newly opened) netting channel object. """ # Check, if peer is discoverable registry_address = decode_hex(registry_address_hex) peer_address = decode_hex(peer_address_hex) token_address = decode_hex(token_address_hex) try: self._discovery.get(peer_address) except KeyError: print('Error: peer {} not found in discovery'.format(peer_address_hex)) return None self._api.channel_open( registry_address, token_address, peer_address, settle_timeout=settle_timeout, ) return self._api.set_total_channel_deposit( registry_address, token_address, peer_address, total_deposit, )
python
def open_channel_with_funding( self, registry_address_hex, token_address_hex, peer_address_hex, total_deposit, settle_timeout=None, ): """ Convenience method to open a channel. Args: registry_address_hex (str): hex encoded address of the registry for the channel. token_address_hex (str): hex encoded address of the token for the channel. peer_address_hex (str): hex encoded address of the channel peer. total_deposit (int): amount of total funding for the channel. settle_timeout (int): amount of blocks for the settle time (if None use app defaults). Return: netting_channel: the (newly opened) netting channel object. """ # Check, if peer is discoverable registry_address = decode_hex(registry_address_hex) peer_address = decode_hex(peer_address_hex) token_address = decode_hex(token_address_hex) try: self._discovery.get(peer_address) except KeyError: print('Error: peer {} not found in discovery'.format(peer_address_hex)) return None self._api.channel_open( registry_address, token_address, peer_address, settle_timeout=settle_timeout, ) return self._api.set_total_channel_deposit( registry_address, token_address, peer_address, total_deposit, )
[ "def", "open_channel_with_funding", "(", "self", ",", "registry_address_hex", ",", "token_address_hex", ",", "peer_address_hex", ",", "total_deposit", ",", "settle_timeout", "=", "None", ",", ")", ":", "# Check, if peer is discoverable", "registry_address", "=", "decode_h...
Convenience method to open a channel. Args: registry_address_hex (str): hex encoded address of the registry for the channel. token_address_hex (str): hex encoded address of the token for the channel. peer_address_hex (str): hex encoded address of the channel peer. total_deposit (int): amount of total funding for the channel. settle_timeout (int): amount of blocks for the settle time (if None use app defaults). Return: netting_channel: the (newly opened) netting channel object.
[ "Convenience", "method", "to", "open", "a", "channel", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/console.py#L262-L304
train
216,427
raiden-network/raiden
raiden/ui/console.py
ConsoleTools.wait_for_contract
def wait_for_contract(self, contract_address_hex, timeout=None): """ Wait until a contract is mined Args: contract_address_hex (string): hex encoded address of the contract timeout (int): time to wait for the contract to get mined Returns: True if the contract got mined, false otherwise """ contract_address = decode_hex(contract_address_hex) start_time = time.time() result = self._raiden.chain.client.web3.eth.getCode( to_checksum_address(contract_address), ) current_time = time.time() while not result: if timeout and start_time + timeout > current_time: return False result = self._raiden.chain.client.web3.eth.getCode( to_checksum_address(contract_address), ) gevent.sleep(0.5) current_time = time.time() return len(result) > 0
python
def wait_for_contract(self, contract_address_hex, timeout=None): """ Wait until a contract is mined Args: contract_address_hex (string): hex encoded address of the contract timeout (int): time to wait for the contract to get mined Returns: True if the contract got mined, false otherwise """ contract_address = decode_hex(contract_address_hex) start_time = time.time() result = self._raiden.chain.client.web3.eth.getCode( to_checksum_address(contract_address), ) current_time = time.time() while not result: if timeout and start_time + timeout > current_time: return False result = self._raiden.chain.client.web3.eth.getCode( to_checksum_address(contract_address), ) gevent.sleep(0.5) current_time = time.time() return len(result) > 0
[ "def", "wait_for_contract", "(", "self", ",", "contract_address_hex", ",", "timeout", "=", "None", ")", ":", "contract_address", "=", "decode_hex", "(", "contract_address_hex", ")", "start_time", "=", "time", ".", "time", "(", ")", "result", "=", "self", ".", ...
Wait until a contract is mined Args: contract_address_hex (string): hex encoded address of the contract timeout (int): time to wait for the contract to get mined Returns: True if the contract got mined, false otherwise
[ "Wait", "until", "a", "contract", "is", "mined" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/console.py#L306-L334
train
216,428
raiden-network/raiden
raiden/storage/sqlite.py
_filter_from_dict
def _filter_from_dict(current: Dict[str, Any]) -> Dict[str, Any]: """Takes in a nested dictionary as a filter and returns a flattened filter dictionary""" filter_ = dict() for k, v in current.items(): if isinstance(v, dict): for sub, v2 in _filter_from_dict(v).items(): filter_[f'{k}.{sub}'] = v2 else: filter_[k] = v return filter_
python
def _filter_from_dict(current: Dict[str, Any]) -> Dict[str, Any]: """Takes in a nested dictionary as a filter and returns a flattened filter dictionary""" filter_ = dict() for k, v in current.items(): if isinstance(v, dict): for sub, v2 in _filter_from_dict(v).items(): filter_[f'{k}.{sub}'] = v2 else: filter_[k] = v return filter_
[ "def", "_filter_from_dict", "(", "current", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "filter_", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "current", ".", "items", "(", ")", ":", "if...
Takes in a nested dictionary as a filter and returns a flattened filter dictionary
[ "Takes", "in", "a", "nested", "dictionary", "as", "a", "filter", "and", "returns", "a", "flattened", "filter", "dictionary" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L52-L63
train
216,429
raiden-network/raiden
raiden/storage/sqlite.py
SQLiteStorage.log_run
def log_run(self): """ Log timestamp and raiden version to help with debugging """ version = get_system_spec()['raiden'] cursor = self.conn.cursor() cursor.execute('INSERT INTO runs(raiden_version) VALUES (?)', [version]) self.maybe_commit()
python
def log_run(self): """ Log timestamp and raiden version to help with debugging """ version = get_system_spec()['raiden'] cursor = self.conn.cursor() cursor.execute('INSERT INTO runs(raiden_version) VALUES (?)', [version]) self.maybe_commit()
[ "def", "log_run", "(", "self", ")", ":", "version", "=", "get_system_spec", "(", ")", "[", "'raiden'", "]", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "'INSERT INTO runs(raiden_version) VALUES (?)'", ",", "[",...
Log timestamp and raiden version to help with debugging
[ "Log", "timestamp", "and", "raiden", "version", "to", "help", "with", "debugging" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L117-L122
train
216,430
raiden-network/raiden
raiden/storage/sqlite.py
SQLiteStorage.delete_state_changes
def delete_state_changes(self, state_changes_to_delete: List[int]) -> None: """ Delete state changes. Args: state_changes_to_delete: List of ids to delete. """ with self.write_lock, self.conn: self.conn.executemany( 'DELETE FROM state_events WHERE identifier = ?', state_changes_to_delete, )
python
def delete_state_changes(self, state_changes_to_delete: List[int]) -> None: """ Delete state changes. Args: state_changes_to_delete: List of ids to delete. """ with self.write_lock, self.conn: self.conn.executemany( 'DELETE FROM state_events WHERE identifier = ?', state_changes_to_delete, )
[ "def", "delete_state_changes", "(", "self", ",", "state_changes_to_delete", ":", "List", "[", "int", "]", ")", "->", "None", ":", "with", "self", ".", "write_lock", ",", "self", ".", "conn", ":", "self", ".", "conn", ".", "executemany", "(", "'DELETE FROM ...
Delete state changes. Args: state_changes_to_delete: List of ids to delete.
[ "Delete", "state", "changes", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L181-L191
train
216,431
raiden-network/raiden
raiden/storage/sqlite.py
SQLiteStorage.batch_query_state_changes
def batch_query_state_changes( self, batch_size: int, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> Iterator[List[StateChangeRecord]]: """Batch query state change records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with. """ limit = batch_size offset = 0 result_length = 1 while result_length != 0: result = self._get_state_changes( limit=limit, offset=offset, filters=filters, logical_and=logical_and, ) result_length = len(result) offset += result_length yield result
python
def batch_query_state_changes( self, batch_size: int, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> Iterator[List[StateChangeRecord]]: """Batch query state change records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with. """ limit = batch_size offset = 0 result_length = 1 while result_length != 0: result = self._get_state_changes( limit=limit, offset=offset, filters=filters, logical_and=logical_and, ) result_length = len(result) offset += result_length yield result
[ "def", "batch_query_state_changes", "(", "self", ",", "batch_size", ":", "int", ",", "filters", ":", "List", "[", "Tuple", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "logical_and", ":", "bool", "=", "True", ",", ")", "->", "Iterator", "[", "...
Batch query state change records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with.
[ "Batch", "query", "state", "change", "records", "with", "a", "given", "batch", "size", "and", "an", "optional", "filter" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L390-L413
train
216,432
raiden-network/raiden
raiden/storage/sqlite.py
SQLiteStorage._get_event_records
def _get_event_records( self, limit: int = None, offset: int = None, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> List[EventRecord]: """ Return a batch of event records The batch size can be tweaked with the `limit` and `offset` arguments. Additionally the returned events can be optionally filtered with the `filters` parameter to search for specific data in the event data. """ cursor = self._form_and_execute_json_query( query='SELECT identifier, source_statechange_id, data FROM state_events ', limit=limit, offset=offset, filters=filters, logical_and=logical_and, ) result = [ EventRecord( event_identifier=row[0], state_change_identifier=row[1], data=row[2], ) for row in cursor ] return result
python
def _get_event_records( self, limit: int = None, offset: int = None, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> List[EventRecord]: """ Return a batch of event records The batch size can be tweaked with the `limit` and `offset` arguments. Additionally the returned events can be optionally filtered with the `filters` parameter to search for specific data in the event data. """ cursor = self._form_and_execute_json_query( query='SELECT identifier, source_statechange_id, data FROM state_events ', limit=limit, offset=offset, filters=filters, logical_and=logical_and, ) result = [ EventRecord( event_identifier=row[0], state_change_identifier=row[1], data=row[2], ) for row in cursor ] return result
[ "def", "_get_event_records", "(", "self", ",", "limit", ":", "int", "=", "None", ",", "offset", ":", "int", "=", "None", ",", "filters", ":", "List", "[", "Tuple", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "logical_and", ":", "bool", "=",...
Return a batch of event records The batch size can be tweaked with the `limit` and `offset` arguments. Additionally the returned events can be optionally filtered with the `filters` parameter to search for specific data in the event data.
[ "Return", "a", "batch", "of", "event", "records" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L469-L498
train
216,433
raiden-network/raiden
raiden/storage/sqlite.py
SQLiteStorage.batch_query_event_records
def batch_query_event_records( self, batch_size: int, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> Iterator[List[EventRecord]]: """Batch query event records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with. """ limit = batch_size offset = 0 result_length = 1 while result_length != 0: result = self._get_event_records( limit=limit, offset=offset, filters=filters, logical_and=logical_and, ) result_length = len(result) offset += result_length yield result
python
def batch_query_event_records( self, batch_size: int, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> Iterator[List[EventRecord]]: """Batch query event records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with. """ limit = batch_size offset = 0 result_length = 1 while result_length != 0: result = self._get_event_records( limit=limit, offset=offset, filters=filters, logical_and=logical_and, ) result_length = len(result) offset += result_length yield result
[ "def", "batch_query_event_records", "(", "self", ",", "batch_size", ":", "int", ",", "filters", ":", "List", "[", "Tuple", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "logical_and", ":", "bool", "=", "True", ",", ")", "->", "Iterator", "[", "...
Batch query event records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with.
[ "Batch", "query", "event", "records", "with", "a", "given", "batch", "size", "and", "an", "optional", "filter" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L500-L523
train
216,434
raiden-network/raiden
raiden/storage/sqlite.py
SQLiteStorage.update_snapshots
def update_snapshots(self, snapshots_data: List[Tuple[str, int]]): """Given a list of snapshot data, update them in the DB The snapshots_data should be a list of tuples of snapshots data and identifiers in that order. """ cursor = self.conn.cursor() cursor.executemany( 'UPDATE state_snapshot SET data=? WHERE identifier=?', snapshots_data, ) self.maybe_commit()
python
def update_snapshots(self, snapshots_data: List[Tuple[str, int]]): """Given a list of snapshot data, update them in the DB The snapshots_data should be a list of tuples of snapshots data and identifiers in that order. """ cursor = self.conn.cursor() cursor.executemany( 'UPDATE state_snapshot SET data=? WHERE identifier=?', snapshots_data, ) self.maybe_commit()
[ "def", "update_snapshots", "(", "self", ",", "snapshots_data", ":", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ")", ":", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cursor", ".", "executemany", "(", "'UPDATE state_snapshot ...
Given a list of snapshot data, update them in the DB The snapshots_data should be a list of tuples of snapshots data and identifiers in that order.
[ "Given", "a", "list", "of", "snapshot", "data", "update", "them", "in", "the", "DB" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/sqlite.py#L566-L577
train
216,435
raiden-network/raiden
raiden/transfer/views.py
all_neighbour_nodes
def all_neighbour_nodes(chain_state: ChainState) -> Set[Address]: """ Return the identifiers for all nodes accross all payment networks which have a channel open with this one. """ addresses = set() for payment_network in chain_state.identifiers_to_paymentnetworks.values(): for token_network in payment_network.tokenidentifiers_to_tokennetworks.values(): channel_states = token_network.channelidentifiers_to_channels.values() for channel_state in channel_states: addresses.add(channel_state.partner_state.address) return addresses
python
def all_neighbour_nodes(chain_state: ChainState) -> Set[Address]: """ Return the identifiers for all nodes accross all payment networks which have a channel open with this one. """ addresses = set() for payment_network in chain_state.identifiers_to_paymentnetworks.values(): for token_network in payment_network.tokenidentifiers_to_tokennetworks.values(): channel_states = token_network.channelidentifiers_to_channels.values() for channel_state in channel_states: addresses.add(channel_state.partner_state.address) return addresses
[ "def", "all_neighbour_nodes", "(", "chain_state", ":", "ChainState", ")", "->", "Set", "[", "Address", "]", ":", "addresses", "=", "set", "(", ")", "for", "payment_network", "in", "chain_state", ".", "identifiers_to_paymentnetworks", ".", "values", "(", ")", "...
Return the identifiers for all nodes accross all payment networks which have a channel open with this one.
[ "Return", "the", "identifiers", "for", "all", "nodes", "accross", "all", "payment", "networks", "which", "have", "a", "channel", "open", "with", "this", "one", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L46-L58
train
216,436
raiden-network/raiden
raiden/transfer/views.py
get_token_network_identifiers
def get_token_network_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenNetworkID]: """ Return the list of token networks registered with the given payment network. """ payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_network is not None: return [ token_network.address for token_network in payment_network.tokenidentifiers_to_tokennetworks.values() ] return list()
python
def get_token_network_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenNetworkID]: """ Return the list of token networks registered with the given payment network. """ payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_network is not None: return [ token_network.address for token_network in payment_network.tokenidentifiers_to_tokennetworks.values() ] return list()
[ "def", "get_token_network_identifiers", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", ")", "->", "List", "[", "TokenNetworkID", "]", ":", "payment_network", "=", "chain_state", ".", "identifiers_to_paymentnetworks", ".",...
Return the list of token networks registered with the given payment network.
[ "Return", "the", "list", "of", "token", "networks", "registered", "with", "the", "given", "payment", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L187-L200
train
216,437
raiden-network/raiden
raiden/transfer/views.py
get_token_identifiers
def get_token_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenAddress]: """ Return the list of tokens registered with the given payment network. """ payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_network is not None: return [ token_address for token_address in payment_network.tokenaddresses_to_tokenidentifiers.keys() ] return list()
python
def get_token_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenAddress]: """ Return the list of tokens registered with the given payment network. """ payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_network is not None: return [ token_address for token_address in payment_network.tokenaddresses_to_tokenidentifiers.keys() ] return list()
[ "def", "get_token_identifiers", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", ")", "->", "List", "[", "TokenAddress", "]", ":", "payment_network", "=", "chain_state", ".", "identifiers_to_paymentnetworks", ".", "get", ...
Return the list of tokens registered with the given payment network.
[ "Return", "the", "list", "of", "tokens", "registered", "with", "the", "given", "payment", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L203-L216
train
216,438
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_filter
def get_channelstate_filter( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, filter_fn: Callable, ) -> List[NettingChannelState]: """ Return the state of channels that match the condition in `filter_fn` """ token_network = get_token_network_by_token_address( chain_state, payment_network_id, token_address, ) result: List[NettingChannelState] = [] if not token_network: return result for channel_state in token_network.channelidentifiers_to_channels.values(): if filter_fn(channel_state): result.append(channel_state) return result
python
def get_channelstate_filter( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, filter_fn: Callable, ) -> List[NettingChannelState]: """ Return the state of channels that match the condition in `filter_fn` """ token_network = get_token_network_by_token_address( chain_state, payment_network_id, token_address, ) result: List[NettingChannelState] = [] if not token_network: return result for channel_state in token_network.channelidentifiers_to_channels.values(): if filter_fn(channel_state): result.append(channel_state) return result
[ "def", "get_channelstate_filter", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "filter_fn", ":", "Callable", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", ...
Return the state of channels that match the condition in `filter_fn`
[ "Return", "the", "state", "of", "channels", "that", "match", "the", "condition", "in", "filter_fn" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L347-L368
train
216,439
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_open
def get_channelstate_open( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of open channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_OPENED, )
python
def get_channelstate_open( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of open channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_OPENED, )
[ "def", "get_channelstate_open", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", "("...
Return the state of open channels in a token network.
[ "Return", "the", "state", "of", "open", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L371-L382
train
216,440
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_closing
def get_channelstate_closing( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closing channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSING, )
python
def get_channelstate_closing( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closing channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSING, )
[ "def", "get_channelstate_closing", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of closing channels in a token network.
[ "Return", "the", "state", "of", "closing", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L385-L396
train
216,441
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_closed
def get_channelstate_closed( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closed channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSED, )
python
def get_channelstate_closed( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closed channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_CLOSED, )
[ "def", "get_channelstate_closed", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", "...
Return the state of closed channels in a token network.
[ "Return", "the", "state", "of", "closed", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L399-L410
train
216,442
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_settling
def get_channelstate_settling( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settling channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLING, )
python
def get_channelstate_settling( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settling channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLING, )
[ "def", "get_channelstate_settling", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of settling channels in a token network.
[ "Return", "the", "state", "of", "settling", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L413-L424
train
216,443
raiden-network/raiden
raiden/transfer/views.py
get_channelstate_settled
def get_channelstate_settled( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settled channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLED, )
python
def get_channelstate_settled( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settled channels in a token network.""" return get_channelstate_filter( chain_state, payment_network_id, token_address, lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLED, )
[ "def", "get_channelstate_settled", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of settled channels in a token network.
[ "Return", "the", "state", "of", "settled", "channels", "in", "a", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L427-L438
train
216,444
raiden-network/raiden
raiden/transfer/views.py
role_from_transfer_task
def role_from_transfer_task(transfer_task: TransferTask) -> str: """Return the role and type for the transfer. Throws an exception on error""" if isinstance(transfer_task, InitiatorTask): return 'initiator' if isinstance(transfer_task, MediatorTask): return 'mediator' if isinstance(transfer_task, TargetTask): return 'target' raise ValueError('Argument to role_from_transfer_task is not a TransferTask')
python
def role_from_transfer_task(transfer_task: TransferTask) -> str: """Return the role and type for the transfer. Throws an exception on error""" if isinstance(transfer_task, InitiatorTask): return 'initiator' if isinstance(transfer_task, MediatorTask): return 'mediator' if isinstance(transfer_task, TargetTask): return 'target' raise ValueError('Argument to role_from_transfer_task is not a TransferTask')
[ "def", "role_from_transfer_task", "(", "transfer_task", ":", "TransferTask", ")", "->", "str", ":", "if", "isinstance", "(", "transfer_task", ",", "InitiatorTask", ")", ":", "return", "'initiator'", "if", "isinstance", "(", "transfer_task", ",", "MediatorTask", ")...
Return the role and type for the transfer. Throws an exception on error
[ "Return", "the", "role", "and", "type", "for", "the", "transfer", ".", "Throws", "an", "exception", "on", "error" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L441-L450
train
216,445
raiden-network/raiden
raiden/transfer/views.py
secret_from_transfer_task
def secret_from_transfer_task( transfer_task: Optional[TransferTask], secrethash: SecretHash, ) -> Optional[Secret]: """Return the secret for the transfer, None on EMPTY_SECRET.""" assert isinstance(transfer_task, InitiatorTask) transfer_state = transfer_task.manager_state.initiator_transfers[secrethash] if transfer_state is None: return None return transfer_state.transfer_description.secret
python
def secret_from_transfer_task( transfer_task: Optional[TransferTask], secrethash: SecretHash, ) -> Optional[Secret]: """Return the secret for the transfer, None on EMPTY_SECRET.""" assert isinstance(transfer_task, InitiatorTask) transfer_state = transfer_task.manager_state.initiator_transfers[secrethash] if transfer_state is None: return None return transfer_state.transfer_description.secret
[ "def", "secret_from_transfer_task", "(", "transfer_task", ":", "Optional", "[", "TransferTask", "]", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "Optional", "[", "Secret", "]", ":", "assert", "isinstance", "(", "transfer_task", ",", "InitiatorTask", ")...
Return the secret for the transfer, None on EMPTY_SECRET.
[ "Return", "the", "secret", "for", "the", "transfer", "None", "on", "EMPTY_SECRET", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L453-L465
train
216,446
raiden-network/raiden
raiden/transfer/views.py
get_transfer_role
def get_transfer_role(chain_state: ChainState, secrethash: SecretHash) -> Optional[str]: """ Returns 'initiator', 'mediator' or 'target' to signify the role the node has in a transfer. If a transfer task is not found for the secrethash then the function returns None """ task = chain_state.payment_mapping.secrethashes_to_task.get(secrethash) if not task: return None return role_from_transfer_task(task)
python
def get_transfer_role(chain_state: ChainState, secrethash: SecretHash) -> Optional[str]: """ Returns 'initiator', 'mediator' or 'target' to signify the role the node has in a transfer. If a transfer task is not found for the secrethash then the function returns None """ task = chain_state.payment_mapping.secrethashes_to_task.get(secrethash) if not task: return None return role_from_transfer_task(task)
[ "def", "get_transfer_role", "(", "chain_state", ":", "ChainState", ",", "secrethash", ":", "SecretHash", ")", "->", "Optional", "[", "str", "]", ":", "task", "=", "chain_state", ".", "payment_mapping", ".", "secrethashes_to_task", ".", "get", "(", "secrethash", ...
Returns 'initiator', 'mediator' or 'target' to signify the role the node has in a transfer. If a transfer task is not found for the secrethash then the function returns None
[ "Returns", "initiator", "mediator", "or", "target", "to", "signify", "the", "role", "the", "node", "has", "in", "a", "transfer", ".", "If", "a", "transfer", "task", "is", "not", "found", "for", "the", "secrethash", "then", "the", "function", "returns", "No...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L468-L477
train
216,447
raiden-network/raiden
raiden/transfer/views.py
filter_channels_by_status
def filter_channels_by_status( channel_states: List[NettingChannelState], exclude_states: Optional[List[str]] = None, ) -> List[NettingChannelState]: """ Filter the list of channels by excluding ones for which the state exists in `exclude_states`. """ if exclude_states is None: exclude_states = [] states = [] for channel_state in channel_states: if channel.get_status(channel_state) not in exclude_states: states.append(channel_state) return states
python
def filter_channels_by_status( channel_states: List[NettingChannelState], exclude_states: Optional[List[str]] = None, ) -> List[NettingChannelState]: """ Filter the list of channels by excluding ones for which the state exists in `exclude_states`. """ if exclude_states is None: exclude_states = [] states = [] for channel_state in channel_states: if channel.get_status(channel_state) not in exclude_states: states.append(channel_state) return states
[ "def", "filter_channels_by_status", "(", "channel_states", ":", "List", "[", "NettingChannelState", "]", ",", "exclude_states", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "if...
Filter the list of channels by excluding ones for which the state exists in `exclude_states`.
[ "Filter", "the", "list", "of", "channels", "by", "excluding", "ones", "for", "which", "the", "state", "exists", "in", "exclude_states", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L558-L573
train
216,448
raiden-network/raiden
raiden/transfer/views.py
detect_balance_proof_change
def detect_balance_proof_change( old_state: ChainState, current_state: ChainState, ) -> Iterator[Union[BalanceProofSignedState, BalanceProofUnsignedState]]: """ Compare two states for any received balance_proofs that are not in `old_state`. """ if old_state == current_state: return for payment_network_identifier in current_state.identifiers_to_paymentnetworks: try: old_payment_network = old_state.identifiers_to_paymentnetworks.get( payment_network_identifier, ) except AttributeError: old_payment_network = None current_payment_network = current_state.identifiers_to_paymentnetworks[ payment_network_identifier ] if old_payment_network == current_payment_network: continue for token_network_identifier in current_payment_network.tokenidentifiers_to_tokennetworks: if old_payment_network: old_token_network = old_payment_network.tokenidentifiers_to_tokennetworks.get( token_network_identifier, ) else: old_token_network = None current_token_network = current_payment_network.tokenidentifiers_to_tokennetworks[ token_network_identifier ] if old_token_network == current_token_network: continue for channel_identifier in current_token_network.channelidentifiers_to_channels: if old_token_network: old_channel = old_token_network.channelidentifiers_to_channels.get( channel_identifier, ) else: old_channel = None current_channel = current_token_network.channelidentifiers_to_channels[ channel_identifier ] if current_channel == old_channel: continue else: partner_state_updated = ( current_channel.partner_state.balance_proof is not None and ( old_channel is None or old_channel.partner_state.balance_proof != current_channel.partner_state.balance_proof ) ) if partner_state_updated: assert current_channel.partner_state.balance_proof, MYPY_ANNOTATION yield current_channel.partner_state.balance_proof our_state_updated = ( current_channel.our_state.balance_proof is not None and ( old_channel is None or old_channel.our_state.balance_proof != current_channel.our_state.balance_proof ) ) if our_state_updated: assert current_channel.our_state.balance_proof, MYPY_ANNOTATION yield current_channel.our_state.balance_proof
python
def detect_balance_proof_change( old_state: ChainState, current_state: ChainState, ) -> Iterator[Union[BalanceProofSignedState, BalanceProofUnsignedState]]: """ Compare two states for any received balance_proofs that are not in `old_state`. """ if old_state == current_state: return for payment_network_identifier in current_state.identifiers_to_paymentnetworks: try: old_payment_network = old_state.identifiers_to_paymentnetworks.get( payment_network_identifier, ) except AttributeError: old_payment_network = None current_payment_network = current_state.identifiers_to_paymentnetworks[ payment_network_identifier ] if old_payment_network == current_payment_network: continue for token_network_identifier in current_payment_network.tokenidentifiers_to_tokennetworks: if old_payment_network: old_token_network = old_payment_network.tokenidentifiers_to_tokennetworks.get( token_network_identifier, ) else: old_token_network = None current_token_network = current_payment_network.tokenidentifiers_to_tokennetworks[ token_network_identifier ] if old_token_network == current_token_network: continue for channel_identifier in current_token_network.channelidentifiers_to_channels: if old_token_network: old_channel = old_token_network.channelidentifiers_to_channels.get( channel_identifier, ) else: old_channel = None current_channel = current_token_network.channelidentifiers_to_channels[ channel_identifier ] if current_channel == old_channel: continue else: partner_state_updated = ( current_channel.partner_state.balance_proof is not None and ( old_channel is None or old_channel.partner_state.balance_proof != current_channel.partner_state.balance_proof ) ) if partner_state_updated: assert current_channel.partner_state.balance_proof, MYPY_ANNOTATION yield current_channel.partner_state.balance_proof our_state_updated = ( current_channel.our_state.balance_proof is not None and ( old_channel is None or old_channel.our_state.balance_proof != current_channel.our_state.balance_proof ) ) if our_state_updated: assert current_channel.our_state.balance_proof, MYPY_ANNOTATION yield current_channel.our_state.balance_proof
[ "def", "detect_balance_proof_change", "(", "old_state", ":", "ChainState", ",", "current_state", ":", "ChainState", ",", ")", "->", "Iterator", "[", "Union", "[", "BalanceProofSignedState", ",", "BalanceProofUnsignedState", "]", "]", ":", "if", "old_state", "==", ...
Compare two states for any received balance_proofs that are not in `old_state`.
[ "Compare", "two", "states", "for", "any", "received", "balance_proofs", "that", "are", "not", "in", "old_state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L576-L650
train
216,449
raiden-network/raiden
raiden/network/upnpsock.py
connect
def connect(): """Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information """ upnp = miniupnpc.UPnP() upnp.discoverdelay = 200 providers = upnp.discover() if providers > 1: log.debug('multiple upnp providers found', num_providers=providers) elif providers < 1: log.error('no upnp providers found') return None try: location = upnp.selectigd() log.debug('connected', upnp=upnp) except Exception as e: log.error('Error when connecting to uPnP provider', exception_info=e) return None if not valid_mappable_ipv4(upnp.lanaddr): log.error('could not query your lanaddr', reported=upnp.lanaddr) return None try: # this can fail if router advertises uPnP incorrectly if not valid_mappable_ipv4(upnp.externalipaddress()): log.error('could not query your externalipaddress', reported=upnp.externalipaddress()) return None return upnp, location except Exception: log.error('error when connecting with uPnP provider', location=location) return None
python
def connect(): """Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information """ upnp = miniupnpc.UPnP() upnp.discoverdelay = 200 providers = upnp.discover() if providers > 1: log.debug('multiple upnp providers found', num_providers=providers) elif providers < 1: log.error('no upnp providers found') return None try: location = upnp.selectigd() log.debug('connected', upnp=upnp) except Exception as e: log.error('Error when connecting to uPnP provider', exception_info=e) return None if not valid_mappable_ipv4(upnp.lanaddr): log.error('could not query your lanaddr', reported=upnp.lanaddr) return None try: # this can fail if router advertises uPnP incorrectly if not valid_mappable_ipv4(upnp.externalipaddress()): log.error('could not query your externalipaddress', reported=upnp.externalipaddress()) return None return upnp, location except Exception: log.error('error when connecting with uPnP provider', location=location) return None
[ "def", "connect", "(", ")", ":", "upnp", "=", "miniupnpc", ".", "UPnP", "(", ")", "upnp", ".", "discoverdelay", "=", "200", "providers", "=", "upnp", ".", "discover", "(", ")", "if", "providers", ">", "1", ":", "log", ".", "debug", "(", "'multiple up...
Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information
[ "Try", "to", "connect", "to", "the", "router", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/upnpsock.py#L37-L70
train
216,450
raiden-network/raiden
raiden/network/upnpsock.py
release_port
def release_port(upnp, external_port): """Try to release the port mapping for `external_port`. Args: external_port (int): the port that was previously forwarded to. Returns: success (boolean): if the release was successful. """ mapping = upnp.getspecificportmapping(external_port, 'UDP') if mapping is None: log.error('could not find a port mapping', external=external_port) return False else: log.debug('found existing port mapping', mapping=mapping) if upnp.deleteportmapping(external_port, 'UDP'): log.info('successfully released port mapping', external=external_port) return True log.warning( 'could not release port mapping, check your router for stale mappings', ) return False
python
def release_port(upnp, external_port): """Try to release the port mapping for `external_port`. Args: external_port (int): the port that was previously forwarded to. Returns: success (boolean): if the release was successful. """ mapping = upnp.getspecificportmapping(external_port, 'UDP') if mapping is None: log.error('could not find a port mapping', external=external_port) return False else: log.debug('found existing port mapping', mapping=mapping) if upnp.deleteportmapping(external_port, 'UDP'): log.info('successfully released port mapping', external=external_port) return True log.warning( 'could not release port mapping, check your router for stale mappings', ) return False
[ "def", "release_port", "(", "upnp", ",", "external_port", ")", ":", "mapping", "=", "upnp", ".", "getspecificportmapping", "(", "external_port", ",", "'UDP'", ")", "if", "mapping", "is", "None", ":", "log", ".", "error", "(", "'could not find a port mapping'", ...
Try to release the port mapping for `external_port`. Args: external_port (int): the port that was previously forwarded to. Returns: success (boolean): if the release was successful.
[ "Try", "to", "release", "the", "port", "mapping", "for", "external_port", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/upnpsock.py#L170-L194
train
216,451
raiden-network/raiden
raiden/network/blockchain_service.py
BlockChainService.token
def token(self, token_address: Address) -> Token: """ Return a proxy to interact with a token. """ if not is_binary_address(token_address): raise ValueError('token_address must be a valid address') with self._token_creation_lock: if token_address not in self.address_to_token: self.address_to_token[token_address] = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) return self.address_to_token[token_address]
python
def token(self, token_address: Address) -> Token: """ Return a proxy to interact with a token. """ if not is_binary_address(token_address): raise ValueError('token_address must be a valid address') with self._token_creation_lock: if token_address not in self.address_to_token: self.address_to_token[token_address] = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) return self.address_to_token[token_address]
[ "def", "token", "(", "self", ",", "token_address", ":", "Address", ")", "->", "Token", ":", "if", "not", "is_binary_address", "(", "token_address", ")", ":", "raise", "ValueError", "(", "'token_address must be a valid address'", ")", "with", "self", ".", "_token...
Return a proxy to interact with a token.
[ "Return", "a", "proxy", "to", "interact", "with", "a", "token", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/blockchain_service.py#L132-L145
train
216,452
raiden-network/raiden
raiden/network/blockchain_service.py
BlockChainService.discovery
def discovery(self, discovery_address: Address) -> Discovery: """ Return a proxy to interact with the discovery. """ if not is_binary_address(discovery_address): raise ValueError('discovery_address must be a valid address') with self._discovery_creation_lock: if discovery_address not in self.address_to_discovery: self.address_to_discovery[discovery_address] = Discovery( jsonrpc_client=self.client, discovery_address=discovery_address, contract_manager=self.contract_manager, ) return self.address_to_discovery[discovery_address]
python
def discovery(self, discovery_address: Address) -> Discovery: """ Return a proxy to interact with the discovery. """ if not is_binary_address(discovery_address): raise ValueError('discovery_address must be a valid address') with self._discovery_creation_lock: if discovery_address not in self.address_to_discovery: self.address_to_discovery[discovery_address] = Discovery( jsonrpc_client=self.client, discovery_address=discovery_address, contract_manager=self.contract_manager, ) return self.address_to_discovery[discovery_address]
[ "def", "discovery", "(", "self", ",", "discovery_address", ":", "Address", ")", "->", "Discovery", ":", "if", "not", "is_binary_address", "(", "discovery_address", ")", ":", "raise", "ValueError", "(", "'discovery_address must be a valid address'", ")", "with", "sel...
Return a proxy to interact with the discovery.
[ "Return", "a", "proxy", "to", "interact", "with", "the", "discovery", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/blockchain_service.py#L147-L160
train
216,453
raiden-network/raiden
raiden/network/rpc/client.py
check_address_has_code
def check_address_has_code( client: 'JSONRPCClient', address: Address, contract_name: str = '', ): """ Checks that the given address contains code. """ result = client.web3.eth.getCode(to_checksum_address(address), 'latest') if not result: if contract_name: formated_contract_name = '[{}]: '.format(contract_name) else: formated_contract_name = '' raise AddressWithoutCode( '{}Address {} does not contain code'.format( formated_contract_name, to_checksum_address(address), ), )
python
def check_address_has_code( client: 'JSONRPCClient', address: Address, contract_name: str = '', ): """ Checks that the given address contains code. """ result = client.web3.eth.getCode(to_checksum_address(address), 'latest') if not result: if contract_name: formated_contract_name = '[{}]: '.format(contract_name) else: formated_contract_name = '' raise AddressWithoutCode( '{}Address {} does not contain code'.format( formated_contract_name, to_checksum_address(address), ), )
[ "def", "check_address_has_code", "(", "client", ":", "'JSONRPCClient'", ",", "address", ":", "Address", ",", "contract_name", ":", "str", "=", "''", ",", ")", ":", "result", "=", "client", ".", "web3", ".", "eth", ".", "getCode", "(", "to_checksum_address", ...
Checks that the given address contains code.
[ "Checks", "that", "the", "given", "address", "contains", "code", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L188-L207
train
216,454
raiden-network/raiden
raiden/network/rpc/client.py
dependencies_order_of_build
def dependencies_order_of_build(target_contract, dependencies_map): """ Return an ordered list of contracts that is sufficient to successfully deploy the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph. """ if not dependencies_map: return [target_contract] if target_contract not in dependencies_map: raise ValueError('no dependencies defined for {}'.format(target_contract)) order = [target_contract] todo = list(dependencies_map[target_contract]) while todo: target_contract = todo.pop(0) target_pos = len(order) for dependency in dependencies_map[target_contract]: # we need to add the current contract before all its depedencies if dependency in order: target_pos = order.index(dependency) else: todo.append(dependency) order.insert(target_pos, target_contract) order.reverse() return order
python
def dependencies_order_of_build(target_contract, dependencies_map): """ Return an ordered list of contracts that is sufficient to successfully deploy the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph. """ if not dependencies_map: return [target_contract] if target_contract not in dependencies_map: raise ValueError('no dependencies defined for {}'.format(target_contract)) order = [target_contract] todo = list(dependencies_map[target_contract]) while todo: target_contract = todo.pop(0) target_pos = len(order) for dependency in dependencies_map[target_contract]: # we need to add the current contract before all its depedencies if dependency in order: target_pos = order.index(dependency) else: todo.append(dependency) order.insert(target_pos, target_contract) order.reverse() return order
[ "def", "dependencies_order_of_build", "(", "target_contract", ",", "dependencies_map", ")", ":", "if", "not", "dependencies_map", ":", "return", "[", "target_contract", "]", "if", "target_contract", "not", "in", "dependencies_map", ":", "raise", "ValueError", "(", "...
Return an ordered list of contracts that is sufficient to successfully deploy the target contract. Note: This function assumes that the `dependencies_map` is an acyclic graph.
[ "Return", "an", "ordered", "list", "of", "contracts", "that", "is", "sufficient", "to", "successfully", "deploy", "the", "target", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L232-L262
train
216,455
raiden-network/raiden
raiden/network/rpc/client.py
check_value_error_for_parity
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool: """ For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception. This function checks the thrown exception to see if it's the correct one and if yes returns True, if not returns False """ try: error_data = json.loads(str(value_error).replace("'", '"')) except json.JSONDecodeError: return False if call_type == ParityCallType.ESTIMATE_GAS: code_checks_out = error_data['code'] == -32016 message_checks_out = 'The execution failed due to an exception' in error_data['message'] elif call_type == ParityCallType.CALL: code_checks_out = error_data['code'] == -32015 message_checks_out = 'VM execution error' in error_data['message'] else: raise ValueError('Called check_value_error_for_parity() with illegal call type') if code_checks_out and message_checks_out: return True return False
python
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool: """ For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception. This function checks the thrown exception to see if it's the correct one and if yes returns True, if not returns False """ try: error_data = json.loads(str(value_error).replace("'", '"')) except json.JSONDecodeError: return False if call_type == ParityCallType.ESTIMATE_GAS: code_checks_out = error_data['code'] == -32016 message_checks_out = 'The execution failed due to an exception' in error_data['message'] elif call_type == ParityCallType.CALL: code_checks_out = error_data['code'] == -32015 message_checks_out = 'VM execution error' in error_data['message'] else: raise ValueError('Called check_value_error_for_parity() with illegal call type') if code_checks_out and message_checks_out: return True return False
[ "def", "check_value_error_for_parity", "(", "value_error", ":", "ValueError", ",", "call_type", ":", "ParityCallType", ")", "->", "bool", ":", "try", ":", "error_data", "=", "json", ".", "loads", "(", "str", "(", "value_error", ")", ".", "replace", "(", "\"'...
For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception. This function checks the thrown exception to see if it's the correct one and if yes returns True, if not returns False
[ "For", "parity", "failing", "calls", "and", "functions", "do", "not", "return", "None", "if", "the", "transaction", "will", "fail", "but", "instead", "throw", "a", "ValueError", "exception", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L270-L295
train
216,456
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.get_confirmed_blockhash
def get_confirmed_blockhash(self): """ Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash """ confirmed_block_number = self.web3.eth.blockNumber - self.default_block_num_confirmations if confirmed_block_number < 0: confirmed_block_number = 0 return self.blockhash_from_blocknumber(confirmed_block_number)
python
def get_confirmed_blockhash(self): """ Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash """ confirmed_block_number = self.web3.eth.blockNumber - self.default_block_num_confirmations if confirmed_block_number < 0: confirmed_block_number = 0 return self.blockhash_from_blocknumber(confirmed_block_number)
[ "def", "get_confirmed_blockhash", "(", "self", ")", ":", "confirmed_block_number", "=", "self", ".", "web3", ".", "eth", ".", "blockNumber", "-", "self", ".", "default_block_num_confirmations", "if", "confirmed_block_number", "<", "0", ":", "confirmed_block_number", ...
Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash
[ "Gets", "the", "block", "CONFIRMATION_BLOCKS", "in", "the", "past", "and", "returns", "its", "block", "hash" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L559-L565
train
216,457
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.balance
def balance(self, account: Address): """ Return the balance of the account of the given address. """ return self.web3.eth.getBalance(to_checksum_address(account), 'pending')
python
def balance(self, account: Address): """ Return the balance of the account of the given address. """ return self.web3.eth.getBalance(to_checksum_address(account), 'pending')
[ "def", "balance", "(", "self", ",", "account", ":", "Address", ")", ":", "return", "self", ".", "web3", ".", "eth", ".", "getBalance", "(", "to_checksum_address", "(", "account", ")", ",", "'pending'", ")" ]
Return the balance of the account of the given address.
[ "Return", "the", "balance", "of", "the", "account", "of", "the", "given", "address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L585-L587
train
216,458
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.parity_get_pending_transaction_hash_by_nonce
def parity_get_pending_transaction_hash_by_nonce( self, address: AddressHex, nonce: Nonce, ) -> Optional[TransactionHash]: """Queries the local parity transaction pool and searches for a transaction. Checks the local tx pool for a transaction from a particular address and for a given nonce. If it exists it returns the transaction hash. """ assert self.eth_node is constants.EthClient.PARITY # https://wiki.parity.io/JSONRPC-parity-module.html?q=traceTransaction#parity_alltransactions transactions = self.web3.manager.request_blocking('parity_allTransactions', []) log.debug('RETURNED TRANSACTIONS', transactions=transactions) for tx in transactions: address_match = to_checksum_address(tx['from']) == address if address_match and int(tx['nonce'], 16) == nonce: return tx['hash'] return None
python
def parity_get_pending_transaction_hash_by_nonce( self, address: AddressHex, nonce: Nonce, ) -> Optional[TransactionHash]: """Queries the local parity transaction pool and searches for a transaction. Checks the local tx pool for a transaction from a particular address and for a given nonce. If it exists it returns the transaction hash. """ assert self.eth_node is constants.EthClient.PARITY # https://wiki.parity.io/JSONRPC-parity-module.html?q=traceTransaction#parity_alltransactions transactions = self.web3.manager.request_blocking('parity_allTransactions', []) log.debug('RETURNED TRANSACTIONS', transactions=transactions) for tx in transactions: address_match = to_checksum_address(tx['from']) == address if address_match and int(tx['nonce'], 16) == nonce: return tx['hash'] return None
[ "def", "parity_get_pending_transaction_hash_by_nonce", "(", "self", ",", "address", ":", "AddressHex", ",", "nonce", ":", "Nonce", ",", ")", "->", "Optional", "[", "TransactionHash", "]", ":", "assert", "self", ".", "eth_node", "is", "constants", ".", "EthClient...
Queries the local parity transaction pool and searches for a transaction. Checks the local tx pool for a transaction from a particular address and for a given nonce. If it exists it returns the transaction hash.
[ "Queries", "the", "local", "parity", "transaction", "pool", "and", "searches", "for", "a", "transaction", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L589-L607
train
216,459
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.new_contract_proxy
def new_contract_proxy(self, contract_interface, contract_address: Address): """ Return a proxy for interacting with a smart contract. Args: contract_interface: The contract interface as defined by the json. address: The contract's address. """ return ContractProxy( self, contract=self.new_contract(contract_interface, contract_address), )
python
def new_contract_proxy(self, contract_interface, contract_address: Address): """ Return a proxy for interacting with a smart contract. Args: contract_interface: The contract interface as defined by the json. address: The contract's address. """ return ContractProxy( self, contract=self.new_contract(contract_interface, contract_address), )
[ "def", "new_contract_proxy", "(", "self", ",", "contract_interface", ",", "contract_address", ":", "Address", ")", ":", "return", "ContractProxy", "(", "self", ",", "contract", "=", "self", ".", "new_contract", "(", "contract_interface", ",", "contract_address", "...
Return a proxy for interacting with a smart contract. Args: contract_interface: The contract interface as defined by the json. address: The contract's address.
[ "Return", "a", "proxy", "for", "interacting", "with", "a", "smart", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L628-L638
train
216,460
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.send_transaction
def send_transaction( self, to: Address, startgas: int, value: int = 0, data: bytes = b'', ) -> bytes: """ Helper to send signed messages. This method will use the `privkey` provided in the constructor to locally sign the transaction. This requires an extended server implementation that accepts the variables v, r, and s. """ if to == to_canonical_address(constants.NULL_ADDRESS): warnings.warn('For contract creation the empty string must be used.') with self._nonce_lock: nonce = self._available_nonce gas_price = self.gas_price() transaction = { 'data': data, 'gas': startgas, 'nonce': nonce, 'value': value, 'gasPrice': gas_price, } node_gas_price = self.web3.eth.gasPrice log.debug( 'Calculated gas price for transaction', node=pex(self.address), calculated_gas_price=gas_price, node_gas_price=node_gas_price, ) # add the to address if not deploying a contract if to != b'': transaction['to'] = to_checksum_address(to) signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey) log_details = { 'node': pex(self.address), 'nonce': transaction['nonce'], 'gasLimit': transaction['gas'], 'gasPrice': transaction['gasPrice'], } log.debug('send_raw_transaction called', **log_details) tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction) self._available_nonce += 1 log.debug('send_raw_transaction returned', tx_hash=encode_hex(tx_hash), **log_details) return tx_hash
python
def send_transaction( self, to: Address, startgas: int, value: int = 0, data: bytes = b'', ) -> bytes: """ Helper to send signed messages. This method will use the `privkey` provided in the constructor to locally sign the transaction. This requires an extended server implementation that accepts the variables v, r, and s. """ if to == to_canonical_address(constants.NULL_ADDRESS): warnings.warn('For contract creation the empty string must be used.') with self._nonce_lock: nonce = self._available_nonce gas_price = self.gas_price() transaction = { 'data': data, 'gas': startgas, 'nonce': nonce, 'value': value, 'gasPrice': gas_price, } node_gas_price = self.web3.eth.gasPrice log.debug( 'Calculated gas price for transaction', node=pex(self.address), calculated_gas_price=gas_price, node_gas_price=node_gas_price, ) # add the to address if not deploying a contract if to != b'': transaction['to'] = to_checksum_address(to) signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey) log_details = { 'node': pex(self.address), 'nonce': transaction['nonce'], 'gasLimit': transaction['gas'], 'gasPrice': transaction['gasPrice'], } log.debug('send_raw_transaction called', **log_details) tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction) self._available_nonce += 1 log.debug('send_raw_transaction returned', tx_hash=encode_hex(tx_hash), **log_details) return tx_hash
[ "def", "send_transaction", "(", "self", ",", "to", ":", "Address", ",", "startgas", ":", "int", ",", "value", ":", "int", "=", "0", ",", "data", ":", "bytes", "=", "b''", ",", ")", "->", "bytes", ":", "if", "to", "==", "to_canonical_address", "(", ...
Helper to send signed messages. This method will use the `privkey` provided in the constructor to locally sign the transaction. This requires an extended server implementation that accepts the variables v, r, and s.
[ "Helper", "to", "send", "signed", "messages", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L775-L828
train
216,461
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.poll
def poll( self, transaction_hash: bytes, ): """ Wait until the `transaction_hash` is applied or rejected. Args: transaction_hash: Transaction hash that we are waiting for. """ if len(transaction_hash) != 32: raise ValueError( 'transaction_hash must be a 32 byte hash', ) transaction_hash = encode_hex(transaction_hash) # used to check if the transaction was removed, this could happen # if gas price is too low: # # > Transaction (acbca3d6) below gas price (tx=1 Wei ask=18 # > Shannon). All sequential txs from this address(7d0eae79) # > will be ignored # last_result = None while True: # Could return None for a short period of time, until the # transaction is added to the pool transaction = self.web3.eth.getTransaction(transaction_hash) # if the transaction was added to the pool and then removed if transaction is None and last_result is not None: raise Exception('invalid transaction, check gas price') # the transaction was added to the pool and mined if transaction and transaction['blockNumber'] is not None: last_result = transaction # this will wait for both APPLIED and REVERTED transactions transaction_block = transaction['blockNumber'] confirmation_block = transaction_block + self.default_block_num_confirmations block_number = self.block_number() if block_number >= confirmation_block: return transaction gevent.sleep(1.0)
python
def poll( self, transaction_hash: bytes, ): """ Wait until the `transaction_hash` is applied or rejected. Args: transaction_hash: Transaction hash that we are waiting for. """ if len(transaction_hash) != 32: raise ValueError( 'transaction_hash must be a 32 byte hash', ) transaction_hash = encode_hex(transaction_hash) # used to check if the transaction was removed, this could happen # if gas price is too low: # # > Transaction (acbca3d6) below gas price (tx=1 Wei ask=18 # > Shannon). All sequential txs from this address(7d0eae79) # > will be ignored # last_result = None while True: # Could return None for a short period of time, until the # transaction is added to the pool transaction = self.web3.eth.getTransaction(transaction_hash) # if the transaction was added to the pool and then removed if transaction is None and last_result is not None: raise Exception('invalid transaction, check gas price') # the transaction was added to the pool and mined if transaction and transaction['blockNumber'] is not None: last_result = transaction # this will wait for both APPLIED and REVERTED transactions transaction_block = transaction['blockNumber'] confirmation_block = transaction_block + self.default_block_num_confirmations block_number = self.block_number() if block_number >= confirmation_block: return transaction gevent.sleep(1.0)
[ "def", "poll", "(", "self", ",", "transaction_hash", ":", "bytes", ",", ")", ":", "if", "len", "(", "transaction_hash", ")", "!=", "32", ":", "raise", "ValueError", "(", "'transaction_hash must be a 32 byte hash'", ",", ")", "transaction_hash", "=", "encode_hex"...
Wait until the `transaction_hash` is applied or rejected. Args: transaction_hash: Transaction hash that we are waiting for.
[ "Wait", "until", "the", "transaction_hash", "is", "applied", "or", "rejected", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L830-L877
train
216,462
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.new_filter
def new_filter( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> StatelessFilter: """ Create a filter in the ethereum node. """ logs_blocks_sanity_check(from_block, to_block) return StatelessFilter( self.web3, { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, }, )
python
def new_filter( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> StatelessFilter: """ Create a filter in the ethereum node. """ logs_blocks_sanity_check(from_block, to_block) return StatelessFilter( self.web3, { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, }, )
[ "def", "new_filter", "(", "self", ",", "contract_address", ":", "Address", ",", "topics", ":", "List", "[", "str", "]", "=", "None", ",", "from_block", ":", "BlockSpecification", "=", "0", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", ",", "...
Create a filter in the ethereum node.
[ "Create", "a", "filter", "in", "the", "ethereum", "node", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L879-L896
train
216,463
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.get_filter_events
def get_filter_events( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> List[Dict]: """ Get events for the given query. """ logs_blocks_sanity_check(from_block, to_block) return self.web3.eth.getLogs({ 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, })
python
def get_filter_events( self, contract_address: Address, topics: List[str] = None, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> List[Dict]: """ Get events for the given query. """ logs_blocks_sanity_check(from_block, to_block) return self.web3.eth.getLogs({ 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, })
[ "def", "get_filter_events", "(", "self", ",", "contract_address", ":", "Address", ",", "topics", ":", "List", "[", "str", "]", "=", "None", ",", "from_block", ":", "BlockSpecification", "=", "0", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", "...
Get events for the given query.
[ "Get", "events", "for", "the", "given", "query", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L898-L912
train
216,464
raiden-network/raiden
raiden/network/rpc/client.py
JSONRPCClient.check_for_insufficient_eth
def check_for_insufficient_eth( self, transaction_name: str, transaction_executed: bool, required_gas: int, block_identifier: BlockSpecification, ): """ After estimate gas failure checks if our address has enough balance. If the account did not have enough ETH balance to execute the, transaction then it raises an `InsufficientFunds` error """ if transaction_executed: return our_address = to_checksum_address(self.address) balance = self.web3.eth.getBalance(our_address, block_identifier) required_balance = required_gas * self.gas_price() if balance < required_balance: msg = f'Failed to execute {transaction_name} due to insufficient ETH' log.critical(msg, required_wei=required_balance, actual_wei=balance) raise InsufficientFunds(msg)
python
def check_for_insufficient_eth( self, transaction_name: str, transaction_executed: bool, required_gas: int, block_identifier: BlockSpecification, ): """ After estimate gas failure checks if our address has enough balance. If the account did not have enough ETH balance to execute the, transaction then it raises an `InsufficientFunds` error """ if transaction_executed: return our_address = to_checksum_address(self.address) balance = self.web3.eth.getBalance(our_address, block_identifier) required_balance = required_gas * self.gas_price() if balance < required_balance: msg = f'Failed to execute {transaction_name} due to insufficient ETH' log.critical(msg, required_wei=required_balance, actual_wei=balance) raise InsufficientFunds(msg)
[ "def", "check_for_insufficient_eth", "(", "self", ",", "transaction_name", ":", "str", ",", "transaction_executed", ":", "bool", ",", "required_gas", ":", "int", ",", "block_identifier", ":", "BlockSpecification", ",", ")", ":", "if", "transaction_executed", ":", ...
After estimate gas failure checks if our address has enough balance. If the account did not have enough ETH balance to execute the, transaction then it raises an `InsufficientFunds` error
[ "After", "estimate", "gas", "failure", "checks", "if", "our", "address", "has", "enough", "balance", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L914-L935
train
216,465
raiden-network/raiden
raiden/utils/upgrades.py
get_db_version
def get_db_version(db_filename: Path) -> int: """Return the version value stored in the db""" assert os.path.exists(db_filename) # Perform a query directly through SQL rather than using # storage.get_version() # as get_version will return the latest version if it doesn't # find a record in the database. conn = sqlite3.connect( str(db_filename), detect_types=sqlite3.PARSE_DECLTYPES, ) cursor = conn.cursor() try: cursor.execute('SELECT value FROM settings WHERE name="version";') result = cursor.fetchone() except sqlite3.OperationalError: raise RuntimeError( 'Corrupted database. Database does not the settings table.', ) if not result: raise RuntimeError( 'Corrupted database. Settings table does not contain an entry the db version.', ) return int(result[0])
python
def get_db_version(db_filename: Path) -> int: """Return the version value stored in the db""" assert os.path.exists(db_filename) # Perform a query directly through SQL rather than using # storage.get_version() # as get_version will return the latest version if it doesn't # find a record in the database. conn = sqlite3.connect( str(db_filename), detect_types=sqlite3.PARSE_DECLTYPES, ) cursor = conn.cursor() try: cursor.execute('SELECT value FROM settings WHERE name="version";') result = cursor.fetchone() except sqlite3.OperationalError: raise RuntimeError( 'Corrupted database. Database does not the settings table.', ) if not result: raise RuntimeError( 'Corrupted database. Settings table does not contain an entry the db version.', ) return int(result[0])
[ "def", "get_db_version", "(", "db_filename", ":", "Path", ")", "->", "int", ":", "assert", "os", ".", "path", ".", "exists", "(", "db_filename", ")", "# Perform a query directly through SQL rather than using", "# storage.get_version()", "# as get_version will return the lat...
Return the version value stored in the db
[ "Return", "the", "version", "value", "stored", "in", "the", "db" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/upgrades.py#L73-L101
train
216,466
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
get_or_deploy_token
def get_or_deploy_token(runner) -> Tuple[ContractProxy, int]: """ Deploy or reuse """ token_contract = runner.contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN) token_config = runner.scenario.get('token', {}) if not token_config: token_config = {} address = token_config.get('address') block = token_config.get('block', 0) reuse = token_config.get('reuse', False) token_address_file = runner.data_path.joinpath('token.infos') if reuse: if address: raise ScenarioError('Token settings "address" and "reuse" are mutually exclusive.') if token_address_file.exists(): token_data = json.loads(token_address_file.read_text()) address = token_data['address'] block = token_data['block'] if address: check_address_has_code(runner.client, address, 'Token') token_ctr = runner.client.new_contract_proxy(token_contract['abi'], address) log.debug( "Reusing token", address=to_checksum_address(address), name=token_ctr.contract.functions.name().call(), symbol=token_ctr.contract.functions.symbol().call(), ) return token_ctr, block token_id = uuid.uuid4() now = datetime.now() name = token_config.get('name', f"Scenario Test Token {token_id!s} {now:%Y-%m-%dT%H:%M}") symbol = token_config.get('symbol', f"T{token_id!s:.3}") decimals = token_config.get('decimals', 0) log.debug("Deploying token", name=name, symbol=symbol, decimals=decimals) token_ctr, receipt = runner.client.deploy_solidity_contract( 'CustomToken', runner.contract_manager.contracts, constructor_parameters=(0, decimals, name, symbol), ) contract_deployment_block = receipt['blockNumber'] contract_checksum_address = to_checksum_address(token_ctr.contract_address) if reuse: token_address_file.write_text(json.dumps({ 'address': contract_checksum_address, 'block': contract_deployment_block, })) log.info( "Deployed token", address=contract_checksum_address, name=name, symbol=symbol, ) return token_ctr, contract_deployment_block
python
def get_or_deploy_token(runner) -> Tuple[ContractProxy, int]: """ Deploy or reuse """ token_contract = runner.contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN) token_config = runner.scenario.get('token', {}) if not token_config: token_config = {} address = token_config.get('address') block = token_config.get('block', 0) reuse = token_config.get('reuse', False) token_address_file = runner.data_path.joinpath('token.infos') if reuse: if address: raise ScenarioError('Token settings "address" and "reuse" are mutually exclusive.') if token_address_file.exists(): token_data = json.loads(token_address_file.read_text()) address = token_data['address'] block = token_data['block'] if address: check_address_has_code(runner.client, address, 'Token') token_ctr = runner.client.new_contract_proxy(token_contract['abi'], address) log.debug( "Reusing token", address=to_checksum_address(address), name=token_ctr.contract.functions.name().call(), symbol=token_ctr.contract.functions.symbol().call(), ) return token_ctr, block token_id = uuid.uuid4() now = datetime.now() name = token_config.get('name', f"Scenario Test Token {token_id!s} {now:%Y-%m-%dT%H:%M}") symbol = token_config.get('symbol', f"T{token_id!s:.3}") decimals = token_config.get('decimals', 0) log.debug("Deploying token", name=name, symbol=symbol, decimals=decimals) token_ctr, receipt = runner.client.deploy_solidity_contract( 'CustomToken', runner.contract_manager.contracts, constructor_parameters=(0, decimals, name, symbol), ) contract_deployment_block = receipt['blockNumber'] contract_checksum_address = to_checksum_address(token_ctr.contract_address) if reuse: token_address_file.write_text(json.dumps({ 'address': contract_checksum_address, 'block': contract_deployment_block, })) log.info( "Deployed token", address=contract_checksum_address, name=name, symbol=symbol, ) return token_ctr, contract_deployment_block
[ "def", "get_or_deploy_token", "(", "runner", ")", "->", "Tuple", "[", "ContractProxy", ",", "int", "]", ":", "token_contract", "=", "runner", ".", "contract_manager", ".", "get_contract", "(", "CONTRACT_CUSTOM_TOKEN", ")", "token_config", "=", "runner", ".", "sc...
Deploy or reuse
[ "Deploy", "or", "reuse" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L199-L257
train
216,467
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
get_udc_and_token
def get_udc_and_token(runner) -> Tuple[Optional[ContractProxy], Optional[ContractProxy]]: """ Return contract proxies for the UserDepositContract and associated token """ from scenario_player.runner import ScenarioRunner assert isinstance(runner, ScenarioRunner) udc_config = runner.scenario.services.get('udc', {}) if not udc_config.get('enable', False): return None, None udc_address = udc_config.get('address') if udc_address is None: contracts = get_contracts_deployment_info( chain_id=runner.chain_id, version=DEVELOPMENT_CONTRACT_VERSION, ) udc_address = contracts['contracts'][CONTRACT_USER_DEPOSIT]['address'] udc_abi = runner.contract_manager.get_contract_abi(CONTRACT_USER_DEPOSIT) udc_proxy = runner.client.new_contract_proxy(udc_abi, udc_address) ud_token_address = udc_proxy.contract.functions.token().call() # FIXME: We assume the UD token is a CustomToken (supporting the `mint()` function) custom_token_abi = runner.contract_manager.get_contract_abi(CONTRACT_CUSTOM_TOKEN) ud_token_proxy = runner.client.new_contract_proxy(custom_token_abi, ud_token_address) return udc_proxy, ud_token_proxy
python
def get_udc_and_token(runner) -> Tuple[Optional[ContractProxy], Optional[ContractProxy]]: """ Return contract proxies for the UserDepositContract and associated token """ from scenario_player.runner import ScenarioRunner assert isinstance(runner, ScenarioRunner) udc_config = runner.scenario.services.get('udc', {}) if not udc_config.get('enable', False): return None, None udc_address = udc_config.get('address') if udc_address is None: contracts = get_contracts_deployment_info( chain_id=runner.chain_id, version=DEVELOPMENT_CONTRACT_VERSION, ) udc_address = contracts['contracts'][CONTRACT_USER_DEPOSIT]['address'] udc_abi = runner.contract_manager.get_contract_abi(CONTRACT_USER_DEPOSIT) udc_proxy = runner.client.new_contract_proxy(udc_abi, udc_address) ud_token_address = udc_proxy.contract.functions.token().call() # FIXME: We assume the UD token is a CustomToken (supporting the `mint()` function) custom_token_abi = runner.contract_manager.get_contract_abi(CONTRACT_CUSTOM_TOKEN) ud_token_proxy = runner.client.new_contract_proxy(custom_token_abi, ud_token_address) return udc_proxy, ud_token_proxy
[ "def", "get_udc_and_token", "(", "runner", ")", "->", "Tuple", "[", "Optional", "[", "ContractProxy", "]", ",", "Optional", "[", "ContractProxy", "]", "]", ":", "from", "scenario_player", ".", "runner", "import", "ScenarioRunner", "assert", "isinstance", "(", ...
Return contract proxies for the UserDepositContract and associated token
[ "Return", "contract", "proxies", "for", "the", "UserDepositContract", "and", "associated", "token" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L260-L285
train
216,468
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
mint_token_if_balance_low
def mint_token_if_balance_low( token_contract: ContractProxy, target_address: str, min_balance: int, fund_amount: int, gas_limit: int, mint_msg: str, no_action_msg: str = None, ) -> Optional[TransactionHash]: """ Check token balance and mint if below minimum """ balance = token_contract.contract.functions.balanceOf(target_address).call() if balance < min_balance: mint_amount = fund_amount - balance log.debug(mint_msg, address=target_address, amount=mint_amount) return token_contract.transact('mintFor', gas_limit, mint_amount, target_address) else: if no_action_msg: log.debug(no_action_msg, balance=balance) return None
python
def mint_token_if_balance_low( token_contract: ContractProxy, target_address: str, min_balance: int, fund_amount: int, gas_limit: int, mint_msg: str, no_action_msg: str = None, ) -> Optional[TransactionHash]: """ Check token balance and mint if below minimum """ balance = token_contract.contract.functions.balanceOf(target_address).call() if balance < min_balance: mint_amount = fund_amount - balance log.debug(mint_msg, address=target_address, amount=mint_amount) return token_contract.transact('mintFor', gas_limit, mint_amount, target_address) else: if no_action_msg: log.debug(no_action_msg, balance=balance) return None
[ "def", "mint_token_if_balance_low", "(", "token_contract", ":", "ContractProxy", ",", "target_address", ":", "str", ",", "min_balance", ":", "int", ",", "fund_amount", ":", "int", ",", "gas_limit", ":", "int", ",", "mint_msg", ":", "str", ",", "no_action_msg", ...
Check token balance and mint if below minimum
[ "Check", "token", "balance", "and", "mint", "if", "below", "minimum" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L288-L307
train
216,469
raiden-network/raiden
raiden/storage/wal.py
WriteAheadLog.log_and_dispatch
def log_and_dispatch(self, state_change): """ Log and apply a state change. This function will first write the state change to the write-ahead-log, in case of a node crash the state change can be recovered and replayed to restore the node state. Events produced by applying state change are also saved. """ with self._lock: timestamp = datetime.utcnow().isoformat(timespec='milliseconds') state_change_id = self.storage.write_state_change(state_change, timestamp) self.state_change_id = state_change_id events = self.state_manager.dispatch(state_change) self.storage.write_events(state_change_id, events, timestamp) return events
python
def log_and_dispatch(self, state_change): """ Log and apply a state change. This function will first write the state change to the write-ahead-log, in case of a node crash the state change can be recovered and replayed to restore the node state. Events produced by applying state change are also saved. """ with self._lock: timestamp = datetime.utcnow().isoformat(timespec='milliseconds') state_change_id = self.storage.write_state_change(state_change, timestamp) self.state_change_id = state_change_id events = self.state_manager.dispatch(state_change) self.storage.write_events(state_change_id, events, timestamp) return events
[ "def", "log_and_dispatch", "(", "self", ",", "state_change", ")", ":", "with", "self", ".", "_lock", ":", "timestamp", "=", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", "timespec", "=", "'milliseconds'", ")", "state_change_id", "=", "self", ...
Log and apply a state change. This function will first write the state change to the write-ahead-log, in case of a node crash the state change can be recovered and replayed to restore the node state. Events produced by applying state change are also saved.
[ "Log", "and", "apply", "a", "state", "change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/wal.py#L64-L83
train
216,470
raiden-network/raiden
raiden/storage/wal.py
WriteAheadLog.snapshot
def snapshot(self): """ Snapshot the application state. Snapshots are used to restore the application state, either after a restart or a crash. """ with self._lock: current_state = self.state_manager.current_state state_change_id = self.state_change_id # otherwise no state change was dispatched if state_change_id: self.storage.write_state_snapshot(state_change_id, current_state)
python
def snapshot(self): """ Snapshot the application state. Snapshots are used to restore the application state, either after a restart or a crash. """ with self._lock: current_state = self.state_manager.current_state state_change_id = self.state_change_id # otherwise no state change was dispatched if state_change_id: self.storage.write_state_snapshot(state_change_id, current_state)
[ "def", "snapshot", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "current_state", "=", "self", ".", "state_manager", ".", "current_state", "state_change_id", "=", "self", ".", "state_change_id", "# otherwise no state change was dispatched", "if", "state_...
Snapshot the application state. Snapshots are used to restore the application state, either after a restart or a crash.
[ "Snapshot", "the", "application", "state", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/wal.py#L85-L97
train
216,471
raiden-network/raiden
raiden/blockchain_events_handler.py
handle_tokennetwork_new
def handle_tokennetwork_new(raiden: 'RaidenService', event: Event): """ Handles a `TokenNetworkCreated` event. """ data = event.event_data args = data['args'] block_number = data['block_number'] token_network_address = args['token_network_address'] token_address = typing.TokenAddress(args['token_address']) block_hash = data['block_hash'] token_network_proxy = raiden.chain.token_network(token_network_address) raiden.blockchain_events.add_token_network_listener( token_network_proxy=token_network_proxy, contract_manager=raiden.contract_manager, from_block=block_number, ) token_network_state = TokenNetworkState( token_network_address, token_address, ) transaction_hash = event.event_data['transaction_hash'] new_token_network = ContractReceiveNewTokenNetwork( transaction_hash=transaction_hash, payment_network_identifier=event.originating_contract, token_network=token_network_state, block_number=block_number, block_hash=block_hash, ) raiden.handle_and_track_state_change(new_token_network)
python
def handle_tokennetwork_new(raiden: 'RaidenService', event: Event): """ Handles a `TokenNetworkCreated` event. """ data = event.event_data args = data['args'] block_number = data['block_number'] token_network_address = args['token_network_address'] token_address = typing.TokenAddress(args['token_address']) block_hash = data['block_hash'] token_network_proxy = raiden.chain.token_network(token_network_address) raiden.blockchain_events.add_token_network_listener( token_network_proxy=token_network_proxy, contract_manager=raiden.contract_manager, from_block=block_number, ) token_network_state = TokenNetworkState( token_network_address, token_address, ) transaction_hash = event.event_data['transaction_hash'] new_token_network = ContractReceiveNewTokenNetwork( transaction_hash=transaction_hash, payment_network_identifier=event.originating_contract, token_network=token_network_state, block_number=block_number, block_hash=block_hash, ) raiden.handle_and_track_state_change(new_token_network)
[ "def", "handle_tokennetwork_new", "(", "raiden", ":", "'RaidenService'", ",", "event", ":", "Event", ")", ":", "data", "=", "event", ".", "event_data", "args", "=", "data", "[", "'args'", "]", "block_number", "=", "data", "[", "'block_number'", "]", "token_n...
Handles a `TokenNetworkCreated` event.
[ "Handles", "a", "TokenNetworkCreated", "event", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/blockchain_events_handler.py#L45-L75
train
216,472
raiden-network/raiden
tools/scenario-player/scenario_player/tasks/blockchain.py
query_blockchain_events
def query_blockchain_events( web3: Web3, contract_manager: ContractManager, contract_address: Address, contract_name: str, topics: List, from_block: BlockNumber, to_block: BlockNumber, ) -> List[Dict]: """Returns events emmitted by a contract for a given event name, within a certain range. Args: web3: A Web3 instance contract_manager: A contract manager contract_address: The address of the contract to be filtered, can be `None` contract_name: The name of the contract topics: The topics to filter for from_block: The block to start search events to_block: The block to stop searching for events Returns: All matching events """ filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, } events = web3.eth.getLogs(filter_params) contract_abi = contract_manager.get_contract_abi(contract_name) return [ decode_event( abi=contract_abi, log_=raw_event, ) for raw_event in events ]
python
def query_blockchain_events( web3: Web3, contract_manager: ContractManager, contract_address: Address, contract_name: str, topics: List, from_block: BlockNumber, to_block: BlockNumber, ) -> List[Dict]: """Returns events emmitted by a contract for a given event name, within a certain range. Args: web3: A Web3 instance contract_manager: A contract manager contract_address: The address of the contract to be filtered, can be `None` contract_name: The name of the contract topics: The topics to filter for from_block: The block to start search events to_block: The block to stop searching for events Returns: All matching events """ filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': to_checksum_address(contract_address), 'topics': topics, } events = web3.eth.getLogs(filter_params) contract_abi = contract_manager.get_contract_abi(contract_name) return [ decode_event( abi=contract_abi, log_=raw_event, ) for raw_event in events ]
[ "def", "query_blockchain_events", "(", "web3", ":", "Web3", ",", "contract_manager", ":", "ContractManager", ",", "contract_address", ":", "Address", ",", "contract_name", ":", "str", ",", "topics", ":", "List", ",", "from_block", ":", "BlockNumber", ",", "to_bl...
Returns events emmitted by a contract for a given event name, within a certain range. Args: web3: A Web3 instance contract_manager: A contract manager contract_address: The address of the contract to be filtered, can be `None` contract_name: The name of the contract topics: The topics to filter for from_block: The block to start search events to_block: The block to stop searching for events Returns: All matching events
[ "Returns", "events", "emmitted", "by", "a", "contract", "for", "a", "given", "event", "name", "within", "a", "certain", "range", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/tasks/blockchain.py#L50-L89
train
216,473
raiden-network/raiden
raiden/storage/migrations/v16_to_v17.py
upgrade_v16_to_v17
def upgrade_v16_to_v17(storage: SQLiteStorage, old_version: int, current_version: int, **kwargs): """ InitiatorPaymentState was changed so that the "initiator" attribute is renamed to "initiator_transfers" and converted to a list. """ if old_version == SOURCE_VERSION: _transform_snapshots(storage) return TARGET_VERSION
python
def upgrade_v16_to_v17(storage: SQLiteStorage, old_version: int, current_version: int, **kwargs): """ InitiatorPaymentState was changed so that the "initiator" attribute is renamed to "initiator_transfers" and converted to a list. """ if old_version == SOURCE_VERSION: _transform_snapshots(storage) return TARGET_VERSION
[ "def", "upgrade_v16_to_v17", "(", "storage", ":", "SQLiteStorage", ",", "old_version", ":", "int", ",", "current_version", ":", "int", ",", "*", "*", "kwargs", ")", ":", "if", "old_version", "==", "SOURCE_VERSION", ":", "_transform_snapshots", "(", "storage", ...
InitiatorPaymentState was changed so that the "initiator" attribute is renamed to "initiator_transfers" and converted to a list.
[ "InitiatorPaymentState", "was", "changed", "so", "that", "the", "initiator", "attribute", "is", "renamed", "to", "initiator_transfers", "and", "converted", "to", "a", "list", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/migrations/v16_to_v17.py#L52-L59
train
216,474
raiden-network/raiden
raiden/storage/versions.py
filter_db_names
def filter_db_names(paths: List[str]) -> List[str]: """Returns a filtered list of `paths`, where every name matches our format. Args: paths: A list of file names. """ return [ db_path for db_path in paths if VERSION_RE.match(os.path.basename(db_path)) ]
python
def filter_db_names(paths: List[str]) -> List[str]: """Returns a filtered list of `paths`, where every name matches our format. Args: paths: A list of file names. """ return [ db_path for db_path in paths if VERSION_RE.match(os.path.basename(db_path)) ]
[ "def", "filter_db_names", "(", "paths", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "[", "db_path", "for", "db_path", "in", "paths", "if", "VERSION_RE", ".", "match", "(", "os", ".", "path", ".", "basename", "(", ...
Returns a filtered list of `paths`, where every name matches our format. Args: paths: A list of file names.
[ "Returns", "a", "filtered", "list", "of", "paths", "where", "every", "name", "matches", "our", "format", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/versions.py#L37-L47
train
216,475
raiden-network/raiden
raiden/network/proxies/utils.py
compare_contract_versions
def compare_contract_versions( proxy: ContractProxy, expected_version: str, contract_name: str, address: Address, ) -> None: """Compare version strings of a contract. If not matching raise ContractVersionMismatch. Also may raise AddressWrongContract if the contract contains no code.""" assert isinstance(expected_version, str) try: deployed_version = proxy.contract.functions.contract_version().call() except BadFunctionCallOutput: raise AddressWrongContract('') deployed_version = deployed_version.replace('_', '0') expected_version = expected_version.replace('_', '0') deployed = [int(x) for x in deployed_version.split('.')] expected = [int(x) for x in expected_version.split('.')] if deployed != expected: raise ContractVersionMismatch( f'Provided {contract_name} contract ({to_normalized_address(address)}) ' f'version mismatch. Expected: {expected_version} Got: {deployed_version}', )
python
def compare_contract_versions( proxy: ContractProxy, expected_version: str, contract_name: str, address: Address, ) -> None: """Compare version strings of a contract. If not matching raise ContractVersionMismatch. Also may raise AddressWrongContract if the contract contains no code.""" assert isinstance(expected_version, str) try: deployed_version = proxy.contract.functions.contract_version().call() except BadFunctionCallOutput: raise AddressWrongContract('') deployed_version = deployed_version.replace('_', '0') expected_version = expected_version.replace('_', '0') deployed = [int(x) for x in deployed_version.split('.')] expected = [int(x) for x in expected_version.split('.')] if deployed != expected: raise ContractVersionMismatch( f'Provided {contract_name} contract ({to_normalized_address(address)}) ' f'version mismatch. Expected: {expected_version} Got: {deployed_version}', )
[ "def", "compare_contract_versions", "(", "proxy", ":", "ContractProxy", ",", "expected_version", ":", "str", ",", "contract_name", ":", "str", ",", "address", ":", "Address", ",", ")", "->", "None", ":", "assert", "isinstance", "(", "expected_version", ",", "s...
Compare version strings of a contract. If not matching raise ContractVersionMismatch. Also may raise AddressWrongContract if the contract contains no code.
[ "Compare", "version", "strings", "of", "a", "contract", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/utils.py#L16-L42
train
216,476
raiden-network/raiden
raiden/network/proxies/utils.py
get_onchain_locksroots
def get_onchain_locksroots( chain: 'BlockChainService', canonical_identifier: CanonicalIdentifier, participant1: Address, participant2: Address, block_identifier: BlockSpecification, ) -> Tuple[Locksroot, Locksroot]: """Return the locksroot for `participant1` and `participant2` at `block_identifier`.""" payment_channel = chain.payment_channel(canonical_identifier=canonical_identifier) token_network = payment_channel.token_network # This will not raise RaidenRecoverableError because we are providing the channel_identifier participants_details = token_network.detail_participants( participant1=participant1, participant2=participant2, channel_identifier=canonical_identifier.channel_identifier, block_identifier=block_identifier, ) our_details = participants_details.our_details our_locksroot = our_details.locksroot partner_details = participants_details.partner_details partner_locksroot = partner_details.locksroot return our_locksroot, partner_locksroot
python
def get_onchain_locksroots( chain: 'BlockChainService', canonical_identifier: CanonicalIdentifier, participant1: Address, participant2: Address, block_identifier: BlockSpecification, ) -> Tuple[Locksroot, Locksroot]: """Return the locksroot for `participant1` and `participant2` at `block_identifier`.""" payment_channel = chain.payment_channel(canonical_identifier=canonical_identifier) token_network = payment_channel.token_network # This will not raise RaidenRecoverableError because we are providing the channel_identifier participants_details = token_network.detail_participants( participant1=participant1, participant2=participant2, channel_identifier=canonical_identifier.channel_identifier, block_identifier=block_identifier, ) our_details = participants_details.our_details our_locksroot = our_details.locksroot partner_details = participants_details.partner_details partner_locksroot = partner_details.locksroot return our_locksroot, partner_locksroot
[ "def", "get_onchain_locksroots", "(", "chain", ":", "'BlockChainService'", ",", "canonical_identifier", ":", "CanonicalIdentifier", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", ")", ...
Return the locksroot for `participant1` and `participant2` at `block_identifier`.
[ "Return", "the", "locksroot", "for", "participant1", "and", "participant2", "at", "block_identifier", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/utils.py#L45-L70
train
216,477
raiden-network/raiden
raiden/transfer/node.py
inplace_delete_message_queue
def inplace_delete_message_queue( chain_state: ChainState, state_change: Union[ReceiveDelivered, ReceiveProcessed], queueid: QueueIdentifier, ) -> None: """ Filter messages from queue, if the queue becomes empty, cleanup the queue itself. """ queue = chain_state.queueids_to_queues.get(queueid) if not queue: return inplace_delete_message( message_queue=queue, state_change=state_change, ) if len(queue) == 0: del chain_state.queueids_to_queues[queueid] else: chain_state.queueids_to_queues[queueid] = queue
python
def inplace_delete_message_queue( chain_state: ChainState, state_change: Union[ReceiveDelivered, ReceiveProcessed], queueid: QueueIdentifier, ) -> None: """ Filter messages from queue, if the queue becomes empty, cleanup the queue itself. """ queue = chain_state.queueids_to_queues.get(queueid) if not queue: return inplace_delete_message( message_queue=queue, state_change=state_change, ) if len(queue) == 0: del chain_state.queueids_to_queues[queueid] else: chain_state.queueids_to_queues[queueid] = queue
[ "def", "inplace_delete_message_queue", "(", "chain_state", ":", "ChainState", ",", "state_change", ":", "Union", "[", "ReceiveDelivered", ",", "ReceiveProcessed", "]", ",", "queueid", ":", "QueueIdentifier", ",", ")", "->", "None", ":", "queue", "=", "chain_state"...
Filter messages from queue, if the queue becomes empty, cleanup the queue itself.
[ "Filter", "messages", "from", "queue", "if", "the", "queue", "becomes", "empty", "cleanup", "the", "queue", "itself", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L498-L516
train
216,478
raiden-network/raiden
raiden/transfer/node.py
inplace_delete_message
def inplace_delete_message( message_queue: List[SendMessageEvent], state_change: Union[ReceiveDelivered, ReceiveProcessed], ) -> None: """ Check if the message exists in queue with ID `queueid` and exclude if found.""" for message in list(message_queue): message_found = ( message.message_identifier == state_change.message_identifier and message.recipient == state_change.sender ) if message_found: message_queue.remove(message)
python
def inplace_delete_message( message_queue: List[SendMessageEvent], state_change: Union[ReceiveDelivered, ReceiveProcessed], ) -> None: """ Check if the message exists in queue with ID `queueid` and exclude if found.""" for message in list(message_queue): message_found = ( message.message_identifier == state_change.message_identifier and message.recipient == state_change.sender ) if message_found: message_queue.remove(message)
[ "def", "inplace_delete_message", "(", "message_queue", ":", "List", "[", "SendMessageEvent", "]", ",", "state_change", ":", "Union", "[", "ReceiveDelivered", ",", "ReceiveProcessed", "]", ",", ")", "->", "None", ":", "for", "message", "in", "list", "(", "messa...
Check if the message exists in queue with ID `queueid` and exclude if found.
[ "Check", "if", "the", "message", "exists", "in", "queue", "with", "ID", "queueid", "and", "exclude", "if", "found", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L519-L530
train
216,479
raiden-network/raiden
raiden/transfer/node.py
handle_delivered
def handle_delivered( chain_state: ChainState, state_change: ReceiveDelivered, ) -> TransitionResult[ChainState]: """ Check if the "Delivered" message exists in the global queue and delete if found.""" queueid = QueueIdentifier(state_change.sender, CHANNEL_IDENTIFIER_GLOBAL_QUEUE) inplace_delete_message_queue(chain_state, state_change, queueid) return TransitionResult(chain_state, [])
python
def handle_delivered( chain_state: ChainState, state_change: ReceiveDelivered, ) -> TransitionResult[ChainState]: """ Check if the "Delivered" message exists in the global queue and delete if found.""" queueid = QueueIdentifier(state_change.sender, CHANNEL_IDENTIFIER_GLOBAL_QUEUE) inplace_delete_message_queue(chain_state, state_change, queueid) return TransitionResult(chain_state, [])
[ "def", "handle_delivered", "(", "chain_state", ":", "ChainState", ",", "state_change", ":", "ReceiveDelivered", ",", ")", "->", "TransitionResult", "[", "ChainState", "]", ":", "queueid", "=", "QueueIdentifier", "(", "state_change", ".", "sender", ",", "CHANNEL_ID...
Check if the "Delivered" message exists in the global queue and delete if found.
[ "Check", "if", "the", "Delivered", "message", "exists", "in", "the", "global", "queue", "and", "delete", "if", "found", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L620-L627
train
216,480
raiden-network/raiden
raiden/transfer/node.py
is_transaction_effect_satisfied
def is_transaction_effect_satisfied( chain_state: ChainState, transaction: ContractSendEvent, state_change: StateChange, ) -> bool: """ True if the side-effect of `transaction` is satisfied by `state_change`. This predicate is used to clear the transaction queue. This should only be done once the expected side effect of a transaction is achieved. This doesn't necessarily mean that the transaction sent by *this* node was mined, but only that *some* transaction which achieves the same side-effect was successfully executed and mined. This distinction is important for restarts and to reduce the number of state changes. On restarts: The state of the on-chain channel could have changed while the node was offline. Once the node learns about the change (e.g. the channel was settled), new transactions can be dispatched by Raiden as a side effect for the on-chain *event* (e.g. do the batch unlock with the latest merkle tree), but the dispatched transaction could have been completed by another agent (e.g. the partner node). For these cases, the transaction from a different address which achieves the same side-effect is sufficient, otherwise unnecessary transactions would be sent by the node. NOTE: The above is not important for transactions sent as a side-effect for a new *block*. On restart the node first synchronizes its state by querying for new events, only after the off-chain state is up-to-date, a Block state change is dispatched. At this point some transactions are not required anymore and therefore are not dispatched. On the number of state changes: Accepting a transaction from another address removes the need for clearing state changes, e.g. when our node's close transaction fails but its partner's close transaction succeeds. """ # These transactions are not made atomic through the WAL. They are sent # exclusively through the external APIs. # # - ContractReceiveChannelNew # - ContractReceiveChannelNewBalance # - ContractReceiveNewPaymentNetwork # - ContractReceiveNewTokenNetwork # - ContractReceiveRouteNew # # Note: Deposits and Withdraws must consider a transaction with a higher # value as sufficient, because the values are monotonically increasing and # the transaction with a lower value will never be executed. # Transactions are used to change the on-chain state of a channel. It # doesn't matter if the sender of the transaction is the local node or # another node authorized to perform the operation. So, for the following # transactions, as long as the side-effects are the same, the local # transaction can be removed from the queue. # # - An update transfer can be done by a trusted third party (i.e. monitoring service) # - A close transaction can be sent by our partner # - A settle transaction can be sent by anyone # - A secret reveal can be done by anyone # - A lower nonce is not a valid replacement, since that is an older balance # proof # - A larger raiden state change nonce is impossible. # That would require the partner node to produce an invalid balance proof, # and this node to accept the invalid balance proof and sign it is_valid_update_transfer = ( isinstance(state_change, ContractReceiveUpdateTransfer) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier and state_change.nonce == transaction.balance_proof.nonce ) if is_valid_update_transfer: return True # The balance proof data cannot be verified, the local close could have # lost a race against a remote close, and the balance proof data would be # the one provided by this node's partner is_valid_close = ( isinstance(state_change, ContractReceiveChannelClosed) and isinstance(transaction, ContractSendChannelClose) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_close: return True is_valid_settle = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelSettle) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_settle: return True is_valid_secret_reveal = ( isinstance(state_change, ContractReceiveSecretReveal) and isinstance(transaction, ContractSendSecretReveal) and state_change.secret == transaction.secret ) if is_valid_secret_reveal: return True is_batch_unlock = ( isinstance(state_change, ContractReceiveChannelBatchUnlock) and isinstance(transaction, ContractSendChannelBatchUnlock) ) if is_batch_unlock: assert isinstance(state_change, ContractReceiveChannelBatchUnlock), MYPY_ANNOTATION assert isinstance(transaction, ContractSendChannelBatchUnlock), MYPY_ANNOTATION our_address = chain_state.our_address # Don't assume that because we sent the transaction, we are a # participant partner_address = None if state_change.participant == our_address: partner_address = state_change.partner elif state_change.partner == our_address: partner_address = state_change.participant # Use the second address as the partner address, but check that a # channel exists for our_address and partner_address if partner_address: channel_state = views.get_channelstate_by_token_network_and_partner( chain_state, TokenNetworkID(state_change.token_network_identifier), partner_address, ) # If the channel was cleared, that means that both # sides of the channel were successfully unlocked. # In this case, we clear the batch unlock # transaction from the queue only in case there # were no more locked funds to unlock. if channel_state is None: return True return False
python
def is_transaction_effect_satisfied( chain_state: ChainState, transaction: ContractSendEvent, state_change: StateChange, ) -> bool: """ True if the side-effect of `transaction` is satisfied by `state_change`. This predicate is used to clear the transaction queue. This should only be done once the expected side effect of a transaction is achieved. This doesn't necessarily mean that the transaction sent by *this* node was mined, but only that *some* transaction which achieves the same side-effect was successfully executed and mined. This distinction is important for restarts and to reduce the number of state changes. On restarts: The state of the on-chain channel could have changed while the node was offline. Once the node learns about the change (e.g. the channel was settled), new transactions can be dispatched by Raiden as a side effect for the on-chain *event* (e.g. do the batch unlock with the latest merkle tree), but the dispatched transaction could have been completed by another agent (e.g. the partner node). For these cases, the transaction from a different address which achieves the same side-effect is sufficient, otherwise unnecessary transactions would be sent by the node. NOTE: The above is not important for transactions sent as a side-effect for a new *block*. On restart the node first synchronizes its state by querying for new events, only after the off-chain state is up-to-date, a Block state change is dispatched. At this point some transactions are not required anymore and therefore are not dispatched. On the number of state changes: Accepting a transaction from another address removes the need for clearing state changes, e.g. when our node's close transaction fails but its partner's close transaction succeeds. """ # These transactions are not made atomic through the WAL. They are sent # exclusively through the external APIs. # # - ContractReceiveChannelNew # - ContractReceiveChannelNewBalance # - ContractReceiveNewPaymentNetwork # - ContractReceiveNewTokenNetwork # - ContractReceiveRouteNew # # Note: Deposits and Withdraws must consider a transaction with a higher # value as sufficient, because the values are monotonically increasing and # the transaction with a lower value will never be executed. # Transactions are used to change the on-chain state of a channel. It # doesn't matter if the sender of the transaction is the local node or # another node authorized to perform the operation. So, for the following # transactions, as long as the side-effects are the same, the local # transaction can be removed from the queue. # # - An update transfer can be done by a trusted third party (i.e. monitoring service) # - A close transaction can be sent by our partner # - A settle transaction can be sent by anyone # - A secret reveal can be done by anyone # - A lower nonce is not a valid replacement, since that is an older balance # proof # - A larger raiden state change nonce is impossible. # That would require the partner node to produce an invalid balance proof, # and this node to accept the invalid balance proof and sign it is_valid_update_transfer = ( isinstance(state_change, ContractReceiveUpdateTransfer) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier and state_change.nonce == transaction.balance_proof.nonce ) if is_valid_update_transfer: return True # The balance proof data cannot be verified, the local close could have # lost a race against a remote close, and the balance proof data would be # the one provided by this node's partner is_valid_close = ( isinstance(state_change, ContractReceiveChannelClosed) and isinstance(transaction, ContractSendChannelClose) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_close: return True is_valid_settle = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelSettle) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_valid_settle: return True is_valid_secret_reveal = ( isinstance(state_change, ContractReceiveSecretReveal) and isinstance(transaction, ContractSendSecretReveal) and state_change.secret == transaction.secret ) if is_valid_secret_reveal: return True is_batch_unlock = ( isinstance(state_change, ContractReceiveChannelBatchUnlock) and isinstance(transaction, ContractSendChannelBatchUnlock) ) if is_batch_unlock: assert isinstance(state_change, ContractReceiveChannelBatchUnlock), MYPY_ANNOTATION assert isinstance(transaction, ContractSendChannelBatchUnlock), MYPY_ANNOTATION our_address = chain_state.our_address # Don't assume that because we sent the transaction, we are a # participant partner_address = None if state_change.participant == our_address: partner_address = state_change.partner elif state_change.partner == our_address: partner_address = state_change.participant # Use the second address as the partner address, but check that a # channel exists for our_address and partner_address if partner_address: channel_state = views.get_channelstate_by_token_network_and_partner( chain_state, TokenNetworkID(state_change.token_network_identifier), partner_address, ) # If the channel was cleared, that means that both # sides of the channel were successfully unlocked. # In this case, we clear the batch unlock # transaction from the queue only in case there # were no more locked funds to unlock. if channel_state is None: return True return False
[ "def", "is_transaction_effect_satisfied", "(", "chain_state", ":", "ChainState", ",", "transaction", ":", "ContractSendEvent", ",", "state_change", ":", "StateChange", ",", ")", "->", "bool", ":", "# These transactions are not made atomic through the WAL. They are sent", "# e...
True if the side-effect of `transaction` is satisfied by `state_change`. This predicate is used to clear the transaction queue. This should only be done once the expected side effect of a transaction is achieved. This doesn't necessarily mean that the transaction sent by *this* node was mined, but only that *some* transaction which achieves the same side-effect was successfully executed and mined. This distinction is important for restarts and to reduce the number of state changes. On restarts: The state of the on-chain channel could have changed while the node was offline. Once the node learns about the change (e.g. the channel was settled), new transactions can be dispatched by Raiden as a side effect for the on-chain *event* (e.g. do the batch unlock with the latest merkle tree), but the dispatched transaction could have been completed by another agent (e.g. the partner node). For these cases, the transaction from a different address which achieves the same side-effect is sufficient, otherwise unnecessary transactions would be sent by the node. NOTE: The above is not important for transactions sent as a side-effect for a new *block*. On restart the node first synchronizes its state by querying for new events, only after the off-chain state is up-to-date, a Block state change is dispatched. At this point some transactions are not required anymore and therefore are not dispatched. On the number of state changes: Accepting a transaction from another address removes the need for clearing state changes, e.g. when our node's close transaction fails but its partner's close transaction succeeds.
[ "True", "if", "the", "side", "-", "effect", "of", "transaction", "is", "satisfied", "by", "state_change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1043-L1180
train
216,481
raiden-network/raiden
raiden/transfer/node.py
is_transaction_invalidated
def is_transaction_invalidated(transaction, state_change): """ True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local transaction is executed before it. The first case is handled by the predicate `is_transaction_effect_satisfied`, where a transaction from a different source which does the same thing is considered. This predicate handles the second scenario. A transaction can **only** invalidate another iff both share a valid initial state but a different end state. Valid example: A close can invalidate a deposit, because both a close and a deposit can be executed from an opened state (same initial state), but a close transaction will transition the channel to a closed state which doesn't allow for deposits (different end state). Invalid example: A settle transaction cannot invalidate a deposit because a settle is only allowed for the closed state and deposits are only allowed for the open state. In such a case a deposit should never have been sent. The deposit transaction for an invalid state is a bug and not a transaction which was invalidated. """ # Most transactions cannot be invalidated by others. These are: # # - close transactions # - settle transactions # - batch unlocks # # Deposits and withdraws are invalidated by the close, but these are not # made atomic through the WAL. is_our_failed_update_transfer = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_our_failed_update_transfer: return True return False
python
def is_transaction_invalidated(transaction, state_change): """ True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local transaction is executed before it. The first case is handled by the predicate `is_transaction_effect_satisfied`, where a transaction from a different source which does the same thing is considered. This predicate handles the second scenario. A transaction can **only** invalidate another iff both share a valid initial state but a different end state. Valid example: A close can invalidate a deposit, because both a close and a deposit can be executed from an opened state (same initial state), but a close transaction will transition the channel to a closed state which doesn't allow for deposits (different end state). Invalid example: A settle transaction cannot invalidate a deposit because a settle is only allowed for the closed state and deposits are only allowed for the open state. In such a case a deposit should never have been sent. The deposit transaction for an invalid state is a bug and not a transaction which was invalidated. """ # Most transactions cannot be invalidated by others. These are: # # - close transactions # - settle transactions # - batch unlocks # # Deposits and withdraws are invalidated by the close, but these are not # made atomic through the WAL. is_our_failed_update_transfer = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_identifier == transaction.token_network_identifier and state_change.channel_identifier == transaction.channel_identifier ) if is_our_failed_update_transfer: return True return False
[ "def", "is_transaction_invalidated", "(", "transaction", ",", "state_change", ")", ":", "# Most transactions cannot be invalidated by others. These are:", "#", "# - close transactions", "# - settle transactions", "# - batch unlocks", "#", "# Deposits and withdraws are invalidated by the ...
True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local transaction is executed before it. The first case is handled by the predicate `is_transaction_effect_satisfied`, where a transaction from a different source which does the same thing is considered. This predicate handles the second scenario. A transaction can **only** invalidate another iff both share a valid initial state but a different end state. Valid example: A close can invalidate a deposit, because both a close and a deposit can be executed from an opened state (same initial state), but a close transaction will transition the channel to a closed state which doesn't allow for deposits (different end state). Invalid example: A settle transaction cannot invalidate a deposit because a settle is only allowed for the closed state and deposits are only allowed for the open state. In such a case a deposit should never have been sent. The deposit transaction for an invalid state is a bug and not a transaction which was invalidated.
[ "True", "if", "the", "transaction", "is", "made", "invalid", "by", "state_change", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1183-L1232
train
216,482
raiden-network/raiden
raiden/transfer/node.py
is_transaction_expired
def is_transaction_expired(transaction, block_number): """ True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. If the current block is higher than any of these expirations blocks, the transaction is expired and cannot be successfully executed. """ is_update_expired = ( isinstance(transaction, ContractSendChannelUpdateTransfer) and transaction.expiration < block_number ) if is_update_expired: return True is_secret_register_expired = ( isinstance(transaction, ContractSendSecretReveal) and transaction.expiration < block_number ) if is_secret_register_expired: return True return False
python
def is_transaction_expired(transaction, block_number): """ True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. If the current block is higher than any of these expirations blocks, the transaction is expired and cannot be successfully executed. """ is_update_expired = ( isinstance(transaction, ContractSendChannelUpdateTransfer) and transaction.expiration < block_number ) if is_update_expired: return True is_secret_register_expired = ( isinstance(transaction, ContractSendSecretReveal) and transaction.expiration < block_number ) if is_secret_register_expired: return True return False
[ "def", "is_transaction_expired", "(", "transaction", ",", "block_number", ")", ":", "is_update_expired", "=", "(", "isinstance", "(", "transaction", ",", "ContractSendChannelUpdateTransfer", ")", "and", "transaction", ".", "expiration", "<", "block_number", ")", "if",...
True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. If the current block is higher than any of these expirations blocks, the transaction is expired and cannot be successfully executed.
[ "True", "if", "transaction", "cannot", "be", "mined", "because", "it", "has", "expired", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1235-L1259
train
216,483
raiden-network/raiden
raiden/network/proxies/user_deposit.py
UserDeposit.deposit
def deposit( self, beneficiary: Address, total_deposit: TokenAmount, block_identifier: BlockSpecification, ) -> None: """ Deposit provided amount into the user-deposit contract to the beneficiary's account. """ token_address = self.token_address(block_identifier) token = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) log_details = { 'beneficiary': pex(beneficiary), 'contract': pex(self.address), 'total_deposit': total_deposit, } checking_block = self.client.get_checking_block() error_prefix = 'Call to deposit will fail' with self.deposit_lock: amount_to_deposit, log_details = self._deposit_preconditions( total_deposit=total_deposit, beneficiary=beneficiary, token=token, block_identifier=block_identifier, ) gas_limit = self.proxy.estimate_gas( checking_block, 'deposit', to_checksum_address(beneficiary), total_deposit, ) if gas_limit: error_prefix = 'Call to deposit failed' log.debug('deposit called', **log_details) transaction_hash = self.proxy.transact( 'deposit', safe_gas_limit(gas_limit), to_checksum_address(beneficiary), total_deposit, ) self.client.poll(transaction_hash) receipt_or_none = check_transaction_threw(self.client, transaction_hash) transaction_executed = gas_limit is not None if not transaction_executed or receipt_or_none: if transaction_executed: block = receipt_or_none['blockNumber'] else: block = checking_block self.proxy.jsonrpc_client.check_for_insufficient_eth( transaction_name='deposit', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_UDC_DEPOSIT, block_identifier=block, ) msg = self._check_why_deposit_failed( token=token, amount_to_deposit=amount_to_deposit, total_deposit=total_deposit, block_identifier=block, ) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('deposit successful', **log_details)
python
def deposit( self, beneficiary: Address, total_deposit: TokenAmount, block_identifier: BlockSpecification, ) -> None: """ Deposit provided amount into the user-deposit contract to the beneficiary's account. """ token_address = self.token_address(block_identifier) token = Token( jsonrpc_client=self.client, token_address=token_address, contract_manager=self.contract_manager, ) log_details = { 'beneficiary': pex(beneficiary), 'contract': pex(self.address), 'total_deposit': total_deposit, } checking_block = self.client.get_checking_block() error_prefix = 'Call to deposit will fail' with self.deposit_lock: amount_to_deposit, log_details = self._deposit_preconditions( total_deposit=total_deposit, beneficiary=beneficiary, token=token, block_identifier=block_identifier, ) gas_limit = self.proxy.estimate_gas( checking_block, 'deposit', to_checksum_address(beneficiary), total_deposit, ) if gas_limit: error_prefix = 'Call to deposit failed' log.debug('deposit called', **log_details) transaction_hash = self.proxy.transact( 'deposit', safe_gas_limit(gas_limit), to_checksum_address(beneficiary), total_deposit, ) self.client.poll(transaction_hash) receipt_or_none = check_transaction_threw(self.client, transaction_hash) transaction_executed = gas_limit is not None if not transaction_executed or receipt_or_none: if transaction_executed: block = receipt_or_none['blockNumber'] else: block = checking_block self.proxy.jsonrpc_client.check_for_insufficient_eth( transaction_name='deposit', transaction_executed=transaction_executed, required_gas=GAS_REQUIRED_FOR_UDC_DEPOSIT, block_identifier=block, ) msg = self._check_why_deposit_failed( token=token, amount_to_deposit=amount_to_deposit, total_deposit=total_deposit, block_identifier=block, ) error_msg = f'{error_prefix}. {msg}' log.critical(error_msg, **log_details) raise RaidenUnrecoverableError(error_msg) log.info('deposit successful', **log_details)
[ "def", "deposit", "(", "self", ",", "beneficiary", ":", "Address", ",", "total_deposit", ":", "TokenAmount", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "None", ":", "token_address", "=", "self", ".", "token_address", "(", "block_identifi...
Deposit provided amount into the user-deposit contract to the beneficiary's account.
[ "Deposit", "provided", "amount", "into", "the", "user", "-", "deposit", "contract", "to", "the", "beneficiary", "s", "account", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/user_deposit.py#L68-L144
train
216,484
raiden-network/raiden
raiden/network/proxies/user_deposit.py
UserDeposit.effective_balance
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance: """ The user's balance with planned withdrawals deducted. """ fn = getattr(self.proxy.contract.functions, 'effectiveBalance') balance = fn(address).call(block_identifier=block_identifier) if balance == b'': raise RuntimeError(f"Call to 'effectiveBalance' returned nothing") return balance
python
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance: """ The user's balance with planned withdrawals deducted. """ fn = getattr(self.proxy.contract.functions, 'effectiveBalance') balance = fn(address).call(block_identifier=block_identifier) if balance == b'': raise RuntimeError(f"Call to 'effectiveBalance' returned nothing") return balance
[ "def", "effective_balance", "(", "self", ",", "address", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "Balance", ":", "fn", "=", "getattr", "(", "self", ".", "proxy", ".", "contract", ".", "functions", ",", "'effectiveBalance'...
The user's balance with planned withdrawals deducted.
[ "The", "user", "s", "balance", "with", "planned", "withdrawals", "deducted", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/user_deposit.py#L146-L154
train
216,485
raiden-network/raiden
raiden/encoding/encoders.py
integer.validate
def validate(self, value: int): ''' Validates the integer is in the value range. ''' if not isinstance(value, int): raise ValueError('value is not an integer') if self.minimum > value or self.maximum < value: msg = ( '{} is outside the valide range [{},{}]' ).format(value, self.minimum, self.maximum) raise ValueError(msg)
python
def validate(self, value: int): ''' Validates the integer is in the value range. ''' if not isinstance(value, int): raise ValueError('value is not an integer') if self.minimum > value or self.maximum < value: msg = ( '{} is outside the valide range [{},{}]' ).format(value, self.minimum, self.maximum) raise ValueError(msg)
[ "def", "validate", "(", "self", ",", "value", ":", "int", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "ValueError", "(", "'value is not an integer'", ")", "if", "self", ".", "minimum", ">", "value", "or", "self", "...
Validates the integer is in the value range.
[ "Validates", "the", "integer", "is", "in", "the", "value", "range", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/encoding/encoders.py#L11-L20
train
216,486
raiden-network/raiden
raiden/api/python.py
event_filter_for_payments
def event_filter_for_payments( event: architecture.Event, token_network_identifier: TokenNetworkID = None, partner_address: Address = None, ) -> bool: """Filters out non payment history related events - If no other args are given, all payment related events match - If a token network identifier is given then only payment events for that match - If a partner is also given then if the event is a payment sent event and the target matches it's returned. If it's a payment received and the initiator matches then it's returned. """ is_matching_event = ( isinstance(event, EVENTS_PAYMENT_HISTORY_RELATED) and ( token_network_identifier is None or token_network_identifier == event.token_network_identifier ) ) if not is_matching_event: return False sent_and_target_matches = ( isinstance(event, (EventPaymentSentFailed, EventPaymentSentSuccess)) and ( partner_address is None or event.target == partner_address ) ) received_and_initiator_matches = ( isinstance(event, EventPaymentReceivedSuccess) and ( partner_address is None or event.initiator == partner_address ) ) return sent_and_target_matches or received_and_initiator_matches
python
def event_filter_for_payments( event: architecture.Event, token_network_identifier: TokenNetworkID = None, partner_address: Address = None, ) -> bool: """Filters out non payment history related events - If no other args are given, all payment related events match - If a token network identifier is given then only payment events for that match - If a partner is also given then if the event is a payment sent event and the target matches it's returned. If it's a payment received and the initiator matches then it's returned. """ is_matching_event = ( isinstance(event, EVENTS_PAYMENT_HISTORY_RELATED) and ( token_network_identifier is None or token_network_identifier == event.token_network_identifier ) ) if not is_matching_event: return False sent_and_target_matches = ( isinstance(event, (EventPaymentSentFailed, EventPaymentSentSuccess)) and ( partner_address is None or event.target == partner_address ) ) received_and_initiator_matches = ( isinstance(event, EventPaymentReceivedSuccess) and ( partner_address is None or event.initiator == partner_address ) ) return sent_and_target_matches or received_and_initiator_matches
[ "def", "event_filter_for_payments", "(", "event", ":", "architecture", ".", "Event", ",", "token_network_identifier", ":", "TokenNetworkID", "=", "None", ",", "partner_address", ":", "Address", "=", "None", ",", ")", "->", "bool", ":", "is_matching_event", "=", ...
Filters out non payment history related events - If no other args are given, all payment related events match - If a token network identifier is given then only payment events for that match - If a partner is also given then if the event is a payment sent event and the target matches it's returned. If it's a payment received and the initiator matches then it's returned.
[ "Filters", "out", "non", "payment", "history", "related", "events" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L83-L120
train
216,487
raiden-network/raiden
raiden/api/python.py
RaidenAPI.token_network_register
def token_network_register( self, registry_address: PaymentNetworkID, token_address: TokenAddress, channel_participant_deposit_limit: TokenAmount, token_network_deposit_limit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetworkAddress: """Register the `token_address` in the blockchain. If the address is already registered but the event has not been processed this function will block until the next block to make sure the event is processed. Raises: InvalidAddress: If the registry_address or token_address is not a valid address. AlreadyRegisteredTokenAddress: If the token is already registered. TransactionThrew: If the register transaction failed, this may happen because the account has not enough balance to pay for the gas or this register call raced with another transaction and lost. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address in self.get_tokens_list(registry_address): raise AlreadyRegisteredTokenAddress('Token already registered') contracts_version = self.raiden.contract_manager.contracts_version registry = self.raiden.chain.token_network_registry(registry_address) try: if contracts_version == DEVELOPMENT_CONTRACT_VERSION: return registry.add_token_with_limits( token_address=token_address, channel_participant_deposit_limit=channel_participant_deposit_limit, token_network_deposit_limit=token_network_deposit_limit, ) else: return registry.add_token_without_limits( token_address=token_address, ) except RaidenRecoverableError as e: if 'Token already registered' in str(e): raise AlreadyRegisteredTokenAddress('Token already registered') # else raise finally: # Assume the transaction failed because the token is already # registered with the smart contract and this node has not yet # polled for the event (otherwise the check above would have # failed). # # To provide a consistent view to the user, wait one block, this # will guarantee that the events have been processed. next_block = self.raiden.get_block_number() + 1 waiting.wait_for_block(self.raiden, next_block, retry_timeout)
python
def token_network_register( self, registry_address: PaymentNetworkID, token_address: TokenAddress, channel_participant_deposit_limit: TokenAmount, token_network_deposit_limit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetworkAddress: """Register the `token_address` in the blockchain. If the address is already registered but the event has not been processed this function will block until the next block to make sure the event is processed. Raises: InvalidAddress: If the registry_address or token_address is not a valid address. AlreadyRegisteredTokenAddress: If the token is already registered. TransactionThrew: If the register transaction failed, this may happen because the account has not enough balance to pay for the gas or this register call raced with another transaction and lost. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address in self.get_tokens_list(registry_address): raise AlreadyRegisteredTokenAddress('Token already registered') contracts_version = self.raiden.contract_manager.contracts_version registry = self.raiden.chain.token_network_registry(registry_address) try: if contracts_version == DEVELOPMENT_CONTRACT_VERSION: return registry.add_token_with_limits( token_address=token_address, channel_participant_deposit_limit=channel_participant_deposit_limit, token_network_deposit_limit=token_network_deposit_limit, ) else: return registry.add_token_without_limits( token_address=token_address, ) except RaidenRecoverableError as e: if 'Token already registered' in str(e): raise AlreadyRegisteredTokenAddress('Token already registered') # else raise finally: # Assume the transaction failed because the token is already # registered with the smart contract and this node has not yet # polled for the event (otherwise the check above would have # failed). # # To provide a consistent view to the user, wait one block, this # will guarantee that the events have been processed. next_block = self.raiden.get_block_number() + 1 waiting.wait_for_block(self.raiden, next_block, retry_timeout)
[ "def", "token_network_register", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "channel_participant_deposit_limit", ":", "TokenAmount", ",", "token_network_deposit_limit", ":", "TokenAmount", ",", "retry_timeo...
Register the `token_address` in the blockchain. If the address is already registered but the event has not been processed this function will block until the next block to make sure the event is processed. Raises: InvalidAddress: If the registry_address or token_address is not a valid address. AlreadyRegisteredTokenAddress: If the token is already registered. TransactionThrew: If the register transaction failed, this may happen because the account has not enough balance to pay for the gas or this register call raced with another transaction and lost.
[ "Register", "the", "token_address", "in", "the", "blockchain", ".", "If", "the", "address", "is", "already", "registered", "but", "the", "event", "has", "not", "been", "processed", "this", "function", "will", "block", "until", "the", "next", "block", "to", "...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L220-L279
train
216,488
raiden-network/raiden
raiden/api/python.py
RaidenAPI.token_network_connect
def token_network_connect( self, registry_address: PaymentNetworkID, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: """ Automatically maintain channels open for the given token network. Args: token_address: the ERC20 token network to connect to. funds: the amount of funds that can be used by the ConnectionMananger. initial_channel_target: number of channels to open proactively. joinable_funds_target: fraction of the funds that will be used to join channels opened by other participants. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( raiden=self.raiden, channels_to_open=initial_channel_target, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) connection_manager.connect( funds=funds, initial_channel_target=initial_channel_target, joinable_funds_target=joinable_funds_target, )
python
def token_network_connect( self, registry_address: PaymentNetworkID, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: """ Automatically maintain channels open for the given token network. Args: token_address: the ERC20 token network to connect to. funds: the amount of funds that can be used by the ConnectionMananger. initial_channel_target: number of channels to open proactively. joinable_funds_target: fraction of the funds that will be used to join channels opened by other participants. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( raiden=self.raiden, channels_to_open=initial_channel_target, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) connection_manager.connect( funds=funds, initial_channel_target=initial_channel_target, joinable_funds_target=joinable_funds_target, )
[ "def", "token_network_connect", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "funds", ":", "TokenAmount", ",", "initial_channel_target", ":", "int", "=", "3", ",", "joinable_funds_target", ":", "float...
Automatically maintain channels open for the given token network. Args: token_address: the ERC20 token network to connect to. funds: the amount of funds that can be used by the ConnectionMananger. initial_channel_target: number of channels to open proactively. joinable_funds_target: fraction of the funds that will be used to join channels opened by other participants.
[ "Automatically", "maintain", "channels", "open", "for", "the", "given", "token", "network", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L281-L329
train
216,489
raiden-network/raiden
raiden/api/python.py
RaidenAPI.token_network_leave
def token_network_leave( self, registry_address: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """ Close all channels and wait for settlement. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address not in self.get_tokens_list(registry_address): raise UnknownTokenAddress('token_address unknown') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) return connection_manager.leave(registry_address)
python
def token_network_leave( self, registry_address: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """ Close all channels and wait for settlement. """ if not is_binary_address(registry_address): raise InvalidAddress('registry_address must be a valid address in binary') if not is_binary_address(token_address): raise InvalidAddress('token_address must be a valid address in binary') if token_address not in self.get_tokens_list(registry_address): raise UnknownTokenAddress('token_address unknown') token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, token_address=token_address, ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_identifier, ) return connection_manager.leave(registry_address)
[ "def", "token_network_leave", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "if", "not", "is_binary_address", "(", "registry_address", ")", ":...
Close all channels and wait for settlement.
[ "Close", "all", "channels", "and", "wait", "for", "settlement", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L331-L355
train
216,490
raiden-network/raiden
raiden/api/python.py
RaidenAPI.channel_open
def channel_open( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: """ Open a channel with the peer at `partner_address` with the given `token_address`. """ if settle_timeout is None: settle_timeout = self.raiden.config['settle_timeout'] if settle_timeout < self.raiden.config['reveal_timeout'] * 2: raise InvalidSettleTimeout( 'settle_timeout can not be smaller than double the reveal_timeout', ) if not is_binary_address(registry_address): raise InvalidAddress('Expected binary address format for registry in channel open') if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel open') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel open') chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: raise DuplicatedChannelError('Channel with given partner address already exists') registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = registry.get_token_network(token_address) if token_network_address is None: raise TokenNotRegistered( 'Token network for token %s does not exist' % to_checksum_address(token_address), ) token_network = self.raiden.chain.token_network( registry.get_token_network(token_address), ) with self.raiden.gas_reserve_lock: has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=views.state_from_raiden(self.raiden).block_hash, ) except DuplicatedChannelError: log.info('partner opened channel first') waiting.wait_for_newchannel( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f'channel {channel_state} is gone' return channel_state.identifier
python
def channel_open( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: """ Open a channel with the peer at `partner_address` with the given `token_address`. """ if settle_timeout is None: settle_timeout = self.raiden.config['settle_timeout'] if settle_timeout < self.raiden.config['reveal_timeout'] * 2: raise InvalidSettleTimeout( 'settle_timeout can not be smaller than double the reveal_timeout', ) if not is_binary_address(registry_address): raise InvalidAddress('Expected binary address format for registry in channel open') if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel open') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel open') chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: raise DuplicatedChannelError('Channel with given partner address already exists') registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = registry.get_token_network(token_address) if token_network_address is None: raise TokenNotRegistered( 'Token network for token %s does not exist' % to_checksum_address(token_address), ) token_network = self.raiden.chain.token_network( registry.get_token_network(token_address), ) with self.raiden.gas_reserve_lock: has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=views.state_from_raiden(self.raiden).block_hash, ) except DuplicatedChannelError: log.info('partner opened channel first') waiting.wait_for_newchannel( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f'channel {channel_state} is gone' return channel_state.identifier
[ "def", "channel_open", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "settle_timeout", ":", "BlockTimeout", "=", "None", ",", "retry_timeout", ":", "NetworkTimeo...
Open a channel with the peer at `partner_address` with the given `token_address`.
[ "Open", "a", "channel", "with", "the", "peer", "at", "partner_address", "with", "the", "given", "token_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L357-L447
train
216,491
raiden-network/raiden
raiden/api/python.py
RaidenAPI.set_total_channel_deposit
def set_total_channel_deposit( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, total_deposit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ): """ Set the `total_deposit` in the channel with the peer at `partner_address` and the given `token_address` in order to be able to do transfers. Raises: InvalidAddress: If either token_address or partner_address is not 20 bytes long. TransactionThrew: May happen for multiple reasons: - If the token approval fails, e.g. the token may validate if account has enough balance for the allowance. - The deposit failed, e.g. the allowance did not set the token aside for use and the user spent it before deposit was called. - The channel was closed/settled between the allowance call and the deposit call. AddressWithoutCode: The channel was settled during the deposit execution. DepositOverLimit: The total deposit amount is higher than the limit. """ chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers( chain_state, registry_address, ) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel deposit') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel deposit') if token_address not in token_addresses: raise UnknownTokenAddress('Unknown token address') if channel_state is None: raise InvalidAddress('No channel with partner_address for the given token') if self.raiden.config['environment_type'] == Environment.PRODUCTION: per_token_network_deposit_limit = RED_EYES_PER_TOKEN_NETWORK_LIMIT else: per_token_network_deposit_limit = UINT256_MAX token = self.raiden.chain.token(token_address) token_network_registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = token_network_registry.get_token_network(token_address) token_network_proxy = self.raiden.chain.token_network(token_network_address) channel_proxy = self.raiden.chain.payment_channel( canonical_identifier=channel_state.canonical_identifier, ) if total_deposit == 0: raise DepositMismatch('Attempted to deposit with total deposit being 0') addendum = total_deposit - channel_state.our_state.contract_balance total_network_balance = token.balance_of(registry_address) if total_network_balance + addendum > per_token_network_deposit_limit: raise DepositOverLimit( f'The deposit of {addendum} will exceed the ' f'token network limit of {per_token_network_deposit_limit}', ) balance = token.balance_of(self.raiden.address) functions = token_network_proxy.proxy.contract.functions deposit_limit = functions.channel_participant_deposit_limit().call() if total_deposit > deposit_limit: raise DepositOverLimit( f'The additional deposit of {addendum} will exceed the ' f'channel participant limit of {deposit_limit}', ) # If this check succeeds it does not imply the the `deposit` will # succeed, since the `deposit` transaction may race with another # transaction. if not balance >= addendum: msg = 'Not enough balance to deposit. {} Available={} Needed={}'.format( pex(token_address), balance, addendum, ) raise InsufficientFunds(msg) # set_total_deposit calls approve # token.approve(netcontract_address, addendum) channel_proxy.set_total_deposit( total_deposit=total_deposit, block_identifier=views.state_from_raiden(self.raiden).block_hash, ) target_address = self.raiden.address waiting.wait_for_participant_newbalance( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, target_address=target_address, target_balance=total_deposit, retry_timeout=retry_timeout, )
python
def set_total_channel_deposit( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, total_deposit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ): """ Set the `total_deposit` in the channel with the peer at `partner_address` and the given `token_address` in order to be able to do transfers. Raises: InvalidAddress: If either token_address or partner_address is not 20 bytes long. TransactionThrew: May happen for multiple reasons: - If the token approval fails, e.g. the token may validate if account has enough balance for the allowance. - The deposit failed, e.g. the allowance did not set the token aside for use and the user spent it before deposit was called. - The channel was closed/settled between the allowance call and the deposit call. AddressWithoutCode: The channel was settled during the deposit execution. DepositOverLimit: The total deposit amount is higher than the limit. """ chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers( chain_state, registry_address, ) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel deposit') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel deposit') if token_address not in token_addresses: raise UnknownTokenAddress('Unknown token address') if channel_state is None: raise InvalidAddress('No channel with partner_address for the given token') if self.raiden.config['environment_type'] == Environment.PRODUCTION: per_token_network_deposit_limit = RED_EYES_PER_TOKEN_NETWORK_LIMIT else: per_token_network_deposit_limit = UINT256_MAX token = self.raiden.chain.token(token_address) token_network_registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = token_network_registry.get_token_network(token_address) token_network_proxy = self.raiden.chain.token_network(token_network_address) channel_proxy = self.raiden.chain.payment_channel( canonical_identifier=channel_state.canonical_identifier, ) if total_deposit == 0: raise DepositMismatch('Attempted to deposit with total deposit being 0') addendum = total_deposit - channel_state.our_state.contract_balance total_network_balance = token.balance_of(registry_address) if total_network_balance + addendum > per_token_network_deposit_limit: raise DepositOverLimit( f'The deposit of {addendum} will exceed the ' f'token network limit of {per_token_network_deposit_limit}', ) balance = token.balance_of(self.raiden.address) functions = token_network_proxy.proxy.contract.functions deposit_limit = functions.channel_participant_deposit_limit().call() if total_deposit > deposit_limit: raise DepositOverLimit( f'The additional deposit of {addendum} will exceed the ' f'channel participant limit of {deposit_limit}', ) # If this check succeeds it does not imply the the `deposit` will # succeed, since the `deposit` transaction may race with another # transaction. if not balance >= addendum: msg = 'Not enough balance to deposit. {} Available={} Needed={}'.format( pex(token_address), balance, addendum, ) raise InsufficientFunds(msg) # set_total_deposit calls approve # token.approve(netcontract_address, addendum) channel_proxy.set_total_deposit( total_deposit=total_deposit, block_identifier=views.state_from_raiden(self.raiden).block_hash, ) target_address = self.raiden.address waiting.wait_for_participant_newbalance( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, target_address=target_address, target_balance=total_deposit, retry_timeout=retry_timeout, )
[ "def", "set_total_channel_deposit", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "total_deposit", ":", "TokenAmount", ",", "retry_timeout", ":", "NetworkTimeout", ...
Set the `total_deposit` in the channel with the peer at `partner_address` and the given `token_address` in order to be able to do transfers. Raises: InvalidAddress: If either token_address or partner_address is not 20 bytes long. TransactionThrew: May happen for multiple reasons: - If the token approval fails, e.g. the token may validate if account has enough balance for the allowance. - The deposit failed, e.g. the allowance did not set the token aside for use and the user spent it before deposit was called. - The channel was closed/settled between the allowance call and the deposit call. AddressWithoutCode: The channel was settled during the deposit execution. DepositOverLimit: The total deposit amount is higher than the limit.
[ "Set", "the", "total_deposit", "in", "the", "channel", "with", "the", "peer", "at", "partner_address", "and", "the", "given", "token_address", "in", "order", "to", "be", "able", "to", "do", "transfers", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L449-L563
train
216,492
raiden-network/raiden
raiden/api/python.py
RaidenAPI.get_node_network_state
def get_node_network_state(self, node_address: Address): """ Returns the currently network status of `node_address`. """ return views.get_node_network_status( chain_state=views.state_from_raiden(self.raiden), node_address=node_address, )
python
def get_node_network_state(self, node_address: Address): """ Returns the currently network status of `node_address`. """ return views.get_node_network_status( chain_state=views.state_from_raiden(self.raiden), node_address=node_address, )
[ "def", "get_node_network_state", "(", "self", ",", "node_address", ":", "Address", ")", ":", "return", "views", ".", "get_node_network_status", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "node_address", "=",...
Returns the currently network status of `node_address`.
[ "Returns", "the", "currently", "network", "status", "of", "node_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L701-L706
train
216,493
raiden-network/raiden
raiden/api/python.py
RaidenAPI.get_tokens_list
def get_tokens_list(self, registry_address: PaymentNetworkID): """Returns a list of tokens the node knows about""" tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_list
python
def get_tokens_list(self, registry_address: PaymentNetworkID): """Returns a list of tokens the node knows about""" tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_list
[ "def", "get_tokens_list", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ")", ":", "tokens_list", "=", "views", ".", "get_token_identifiers", "(", "chain_state", "=", "views", ".", "state_from_raiden", "(", "self", ".", "raiden", ")", ",", "payme...
Returns a list of tokens the node knows about
[ "Returns", "a", "list", "of", "tokens", "the", "node", "knows", "about" ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L712-L718
train
216,494
raiden-network/raiden
raiden/api/python.py
RaidenAPI.transfer_and_wait
def transfer_and_wait( self, registry_address: PaymentNetworkID, token_address: TokenAddress, amount: TokenAmount, target: Address, identifier: PaymentID = None, transfer_timeout: int = None, secret: Secret = None, secret_hash: SecretHash = None, ): """ Do a transfer with `target` with the given `amount` of `token_address`. """ # pylint: disable=too-many-arguments payment_status = self.transfer_async( registry_address=registry_address, token_address=token_address, amount=amount, target=target, identifier=identifier, secret=secret, secret_hash=secret_hash, ) payment_status.payment_done.wait(timeout=transfer_timeout) return payment_status
python
def transfer_and_wait( self, registry_address: PaymentNetworkID, token_address: TokenAddress, amount: TokenAmount, target: Address, identifier: PaymentID = None, transfer_timeout: int = None, secret: Secret = None, secret_hash: SecretHash = None, ): """ Do a transfer with `target` with the given `amount` of `token_address`. """ # pylint: disable=too-many-arguments payment_status = self.transfer_async( registry_address=registry_address, token_address=token_address, amount=amount, target=target, identifier=identifier, secret=secret, secret_hash=secret_hash, ) payment_status.payment_done.wait(timeout=transfer_timeout) return payment_status
[ "def", "transfer_and_wait", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "amount", ":", "TokenAmount", ",", "target", ":", "Address", ",", "identifier", ":", "PaymentID", "=", "None", ",", "transf...
Do a transfer with `target` with the given `amount` of `token_address`.
[ "Do", "a", "transfer", "with", "target", "with", "the", "given", "amount", "of", "token_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L731-L755
train
216,495
raiden-network/raiden
raiden/api/python.py
RaidenAPI.get_blockchain_events_token_network
def get_blockchain_events_token_network( self, token_address: TokenAddress, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ): """Returns a list of blockchain events coresponding to the token_address.""" if not is_binary_address(token_address): raise InvalidAddress( 'Expected binary address format for token in get_blockchain_events_token_network', ) token_network_address = self.raiden.default_registry.get_token_network( token_address, ) if token_network_address is None: raise UnknownTokenAddress('Token address is not known.') returned_events = blockchain_events.get_token_network_events( chain=self.raiden.chain, token_network_address=token_network_address, contract_manager=self.raiden.contract_manager, events=blockchain_events.ALL_EVENTS, from_block=from_block, to_block=to_block, ) for event in returned_events: if event.get('args'): event['args'] = dict(event['args']) returned_events.sort(key=lambda evt: evt.get('block_number'), reverse=True) return returned_events
python
def get_blockchain_events_token_network( self, token_address: TokenAddress, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ): """Returns a list of blockchain events coresponding to the token_address.""" if not is_binary_address(token_address): raise InvalidAddress( 'Expected binary address format for token in get_blockchain_events_token_network', ) token_network_address = self.raiden.default_registry.get_token_network( token_address, ) if token_network_address is None: raise UnknownTokenAddress('Token address is not known.') returned_events = blockchain_events.get_token_network_events( chain=self.raiden.chain, token_network_address=token_network_address, contract_manager=self.raiden.contract_manager, events=blockchain_events.ALL_EVENTS, from_block=from_block, to_block=to_block, ) for event in returned_events: if event.get('args'): event['args'] = dict(event['args']) returned_events.sort(key=lambda evt: evt.get('block_number'), reverse=True) return returned_events
[ "def", "get_blockchain_events_token_network", "(", "self", ",", "token_address", ":", "TokenAddress", ",", "from_block", ":", "BlockSpecification", "=", "GENESIS_BLOCK_NUMBER", ",", "to_block", ":", "BlockSpecification", "=", "'latest'", ",", ")", ":", "if", "not", ...
Returns a list of blockchain events coresponding to the token_address.
[ "Returns", "a", "list", "of", "blockchain", "events", "coresponding", "to", "the", "token_address", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L922-L956
train
216,496
raiden-network/raiden
raiden/api/python.py
RaidenAPI.create_monitoring_request
def create_monitoring_request( self, balance_proof: BalanceProofSignedState, reward_amount: TokenAmount, ) -> Optional[RequestMonitoring]: """ This method can be used to create a `RequestMonitoring` message. It will contain all data necessary for an external monitoring service to - send an updateNonClosingBalanceProof transaction to the TokenNetwork contract, for the `balance_proof` that we received from a channel partner. - claim the `reward_amount` from the UDC. """ # create RequestMonitoring message from the above + `reward_amount` monitor_request = RequestMonitoring.from_balance_proof_signed_state( balance_proof=balance_proof, reward_amount=reward_amount, ) # sign RequestMonitoring and return monitor_request.sign(self.raiden.signer) return monitor_request
python
def create_monitoring_request( self, balance_proof: BalanceProofSignedState, reward_amount: TokenAmount, ) -> Optional[RequestMonitoring]: """ This method can be used to create a `RequestMonitoring` message. It will contain all data necessary for an external monitoring service to - send an updateNonClosingBalanceProof transaction to the TokenNetwork contract, for the `balance_proof` that we received from a channel partner. - claim the `reward_amount` from the UDC. """ # create RequestMonitoring message from the above + `reward_amount` monitor_request = RequestMonitoring.from_balance_proof_signed_state( balance_proof=balance_proof, reward_amount=reward_amount, ) # sign RequestMonitoring and return monitor_request.sign(self.raiden.signer) return monitor_request
[ "def", "create_monitoring_request", "(", "self", ",", "balance_proof", ":", "BalanceProofSignedState", ",", "reward_amount", ":", "TokenAmount", ",", ")", "->", "Optional", "[", "RequestMonitoring", "]", ":", "# create RequestMonitoring message from the above + `reward_amount...
This method can be used to create a `RequestMonitoring` message. It will contain all data necessary for an external monitoring service to - send an updateNonClosingBalanceProof transaction to the TokenNetwork contract, for the `balance_proof` that we received from a channel partner. - claim the `reward_amount` from the UDC.
[ "This", "method", "can", "be", "used", "to", "create", "a", "RequestMonitoring", "message", ".", "It", "will", "contain", "all", "data", "necessary", "for", "an", "external", "monitoring", "service", "to", "-", "send", "an", "updateNonClosingBalanceProof", "tran...
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L995-L1013
train
216,497
raiden-network/raiden
raiden/transfer/mediated_transfer/state.py
lockedtransfersigned_from_message
def lockedtransfersigned_from_message(message: 'LockedTransfer') -> 'LockedTransferSignedState': """ Create LockedTransferSignedState from a LockedTransfer message. """ balance_proof = balanceproof_from_envelope(message) lock = HashTimeLockState( message.lock.amount, message.lock.expiration, message.lock.secrethash, ) transfer_state = LockedTransferSignedState( message.message_identifier, message.payment_identifier, message.token, balance_proof, lock, message.initiator, message.target, ) return transfer_state
python
def lockedtransfersigned_from_message(message: 'LockedTransfer') -> 'LockedTransferSignedState': """ Create LockedTransferSignedState from a LockedTransfer message. """ balance_proof = balanceproof_from_envelope(message) lock = HashTimeLockState( message.lock.amount, message.lock.expiration, message.lock.secrethash, ) transfer_state = LockedTransferSignedState( message.message_identifier, message.payment_identifier, message.token, balance_proof, lock, message.initiator, message.target, ) return transfer_state
[ "def", "lockedtransfersigned_from_message", "(", "message", ":", "'LockedTransfer'", ")", "->", "'LockedTransferSignedState'", ":", "balance_proof", "=", "balanceproof_from_envelope", "(", "message", ")", "lock", "=", "HashTimeLockState", "(", "message", ".", "lock", "....
Create LockedTransferSignedState from a LockedTransfer message.
[ "Create", "LockedTransferSignedState", "from", "a", "LockedTransfer", "message", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/state.py#L51-L71
train
216,498
raiden-network/raiden
raiden/ui/cli.py
version
def version(short): """Print version information and exit. """ if short: print(get_system_spec()['raiden']) else: print(json.dumps( get_system_spec(), indent=2, ))
python
def version(short): """Print version information and exit. """ if short: print(get_system_spec()['raiden']) else: print(json.dumps( get_system_spec(), indent=2, ))
[ "def", "version", "(", "short", ")", ":", "if", "short", ":", "print", "(", "get_system_spec", "(", ")", "[", "'raiden'", "]", ")", "else", ":", "print", "(", "json", ".", "dumps", "(", "get_system_spec", "(", ")", ",", "indent", "=", "2", ",", ")"...
Print version information and exit.
[ "Print", "version", "information", "and", "exit", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/cli.py#L553-L561
train
216,499