idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
27,500
def determine_run_number ( self ) -> int : run_number = 0 run_number_file = self . data_path . joinpath ( 'run_number.txt' ) if run_number_file . exists ( ) : run_number = int ( run_number_file . read_text ( ) ) + 1 run_number_file . write_text ( str ( run_number ) ) log . info ( 'Run number' , run_number = run_number ...
Determine the current run number .
27,501
def select_chain ( self , chain_urls : Dict [ str , List [ str ] ] ) -> Tuple [ str , List [ str ] ] : chain_name = self . scenario . chain_name if chain_name in ( 'any' , 'Any' , 'ANY' ) : chain_name = random . choice ( list ( chain_urls . keys ( ) ) ) log . info ( 'Using chain' , chain = chain_name ) try : return cha...
Select a chain and return its name and RPC URL .
27,502
def pack_balance_proof ( nonce : Nonce , balance_hash : BalanceHash , additional_hash : AdditionalHash , canonical_identifier : CanonicalIdentifier , msg_type : MessageTypeId = MessageTypeId . BALANCE_PROOF , ) -> bytes : return pack_data ( [ 'address' , 'uint256' , 'uint256' , 'uint256' , 'bytes32' , 'uint256' , 'byte...
Packs balance proof data to be signed
27,503
def pack_balance_proof_update ( nonce : Nonce , balance_hash : BalanceHash , additional_hash : AdditionalHash , canonical_identifier : CanonicalIdentifier , partner_signature : Signature , ) -> bytes : return pack_balance_proof ( nonce = nonce , balance_hash = balance_hash , additional_hash = additional_hash , canonica...
Packs balance proof data to be signed for updateNonClosingBalanceProof
27,504
def healthcheck ( transport : 'UDPTransport' , recipient : Address , stop_event : Event , event_healthy : Event , event_unhealthy : Event , nat_keepalive_retries : int , nat_keepalive_timeout : int , nat_invitation_timeout : int , ping_nonce : Dict [ str , Nonce ] , ) : log . debug ( 'starting healthcheck for' , node =...
Sends a periodical Ping to recipient to check its health .
27,505
def get_token_network ( self , token_address : TokenAddress , block_identifier : BlockSpecification = 'latest' , ) -> Optional [ Address ] : if not isinstance ( token_address , T_TargetAddress ) : raise ValueError ( 'token_address must be an address' ) address = self . proxy . contract . functions . token_to_token_netw...
Return the token network address for the given token or None if there is no correspoding address .
27,506
def add_token_with_limits ( self , token_address : TokenAddress , channel_participant_deposit_limit : TokenAmount , token_network_deposit_limit : TokenAmount , ) -> Address : return self . _add_token ( token_address = token_address , additional_arguments = { '_channel_participant_deposit_limit' : channel_participant_de...
Register token of token_address with the token network . The limits apply for version 0 . 13 . 0 and above of raiden - contracts since instantiation also takes the limits as constructor arguments .
27,507
def add_token_without_limits ( self , token_address : TokenAddress , ) -> Address : return self . _add_token ( token_address = token_address , additional_arguments = dict ( ) , )
Register token of token_address with the token network . This applies for versions prior to 0 . 13 . 0 of raiden - contracts since limits were hardcoded into the TokenNetwork contract .
27,508
def get_free_port ( initial_port : int = 0 , socket_kind : SocketKind = SocketKind . SOCK_STREAM , reliable : bool = True , ) : def _port_generator ( ) : if initial_port == 0 : next_port = repeat ( 0 ) else : next_port = count ( start = initial_port ) for port_candidate in next_port : sock = socket . socket ( socket . ...
Find an unused TCP port .
27,509
def get_http_rtt ( url : str , samples : int = 3 , method : str = 'head' , timeout : int = 1 , ) -> Optional [ float ] : durations = [ ] for _ in range ( samples ) : try : durations . append ( requests . request ( method , url , timeout = timeout ) . elapsed . total_seconds ( ) , ) except ( RequestException , OSError )...
Determine the average HTTP RTT to url over the number of samples . Returns None if the server is unreachable .
27,510
def _add_blockhash_to_state_changes ( storage : SQLiteStorage , cache : BlockHashCache ) -> None : batch_size = 50 batch_query = storage . batch_query_state_changes ( batch_size = batch_size , filters = [ ( '_type' , 'raiden.transfer.state_change.ContractReceive%' ) , ( '_type' , 'raiden.transfer.state_change.ActionIni...
Adds blockhash to ContractReceiveXXX and ActionInitChain state changes
27,511
def _add_blockhash_to_events ( storage : SQLiteStorage , cache : BlockHashCache ) -> None : batch_query = storage . batch_query_event_records ( batch_size = 500 , filters = [ ( '_type' , 'raiden.transfer.events.ContractSend%' ) ] , ) for events_batch in batch_query : updated_events = [ ] for event in events_batch : dat...
Adds blockhash to all ContractSendXXX events
27,512
def _transform_snapshot ( raw_snapshot : str , storage : SQLiteStorage , cache : BlockHashCache , ) -> str : snapshot = json . loads ( raw_snapshot ) block_number = int ( snapshot [ 'block_number' ] ) snapshot [ 'block_hash' ] = cache . get ( block_number ) pending_transactions = snapshot [ 'pending_transactions' ] new...
Upgrades a single snapshot by adding the blockhash to it and to any pending transactions
27,513
def _transform_snapshots_for_blockhash ( storage : SQLiteStorage , cache : BlockHashCache ) -> None : snapshots = storage . get_snapshots ( ) snapshot_records = [ TransformSnapshotRecord ( data = snapshot . data , identifier = snapshot . identifier , storage = storage , cache = cache , ) for snapshot in snapshots ] poo...
Upgrades the snapshots by adding the blockhash to it and to any pending transactions
27,514
def get ( self , block_number : BlockNumber ) -> str : if block_number in self . mapping : return self . mapping [ block_number ] block_hash = self . web3 . eth . getBlock ( block_number ) [ 'hash' ] block_hash = block_hash . hex ( ) self . mapping [ block_number ] = block_hash return block_hash
Given a block number returns the hex representation of the blockhash
27,515
def has_enough_gas_reserve ( raiden , channels_to_open : int = 0 , ) -> Tuple [ bool , int ] : secure_reserve_estimate = get_reserve_estimate ( raiden , channels_to_open ) current_account_balance = raiden . chain . client . balance ( raiden . chain . client . address ) return secure_reserve_estimate <= current_account_...
Checks if the account has enough balance to handle the lifecycles of all open channels as well as the to be created channels .
27,516
def hash_pair ( first : Keccak256 , second : Optional [ Keccak256 ] ) -> Keccak256 : assert first is not None if second is None : return first if first > second : return sha3 ( second + first ) return sha3 ( first + second )
Computes the keccak hash of the elements ordered topologically .
27,517
def compute_layers ( elements : List [ Keccak256 ] ) -> List [ List [ Keccak256 ] ] : elements = list ( elements ) assert elements , 'Use make_empty_merkle_tree if there are no elements' if not all ( isinstance ( item , bytes ) for item in elements ) : raise ValueError ( 'all elements must be bytes' ) if any ( len ( it...
Computes the layers of the merkletree .
27,518
def compute_merkleproof_for ( merkletree : 'MerkleTreeState' , element : Keccak256 ) -> List [ Keccak256 ] : idx = merkletree . layers [ LEAVES ] . index ( element ) proof = [ ] for layer in merkletree . layers : if idx % 2 : pair = idx - 1 else : pair = idx + 1 if pair < len ( layer ) : proof . append ( layer [ pair ]...
Containment proof for element .
27,519
def validate_proof ( proof : List [ Keccak256 ] , root : Keccak256 , leaf_element : Keccak256 ) -> bool : hash_ = leaf_element for pair in proof : hash_ = hash_pair ( hash_ , pair ) return hash_ == root
Checks that leaf_element was contained in the tree represented by merkleroot .
27,520
def merkleroot ( merkletree : 'MerkleTreeState' ) -> Locksroot : assert merkletree . layers , 'the merkle tree layers are empty' assert merkletree . layers [ MERKLEROOT ] , 'the root layer is empty' return Locksroot ( merkletree . layers [ MERKLEROOT ] [ 0 ] )
Return the root element of the merkle tree .
27,521
def _add_onchain_locksroot_to_channel_settled_state_changes ( raiden : RaidenService , storage : SQLiteStorage , ) -> None : batch_size = 50 batch_query = storage . batch_query_state_changes ( batch_size = batch_size , filters = [ ( '_type' , 'raiden.transfer.state_change.ContractReceiveChannelSettled' ) , ] , ) for st...
Adds our_onchain_locksroot and partner_onchain_locksroot to ContractReceiveChannelSettled .
27,522
def _add_onchain_locksroot_to_snapshot ( raiden : RaidenService , storage : SQLiteStorage , snapshot_record : StateChangeRecord , ) -> str : snapshot = json . loads ( snapshot_record . data ) for payment_network in snapshot . get ( 'identifiers_to_paymentnetworks' , dict ( ) ) . values ( ) : for token_network in paymen...
Add onchain_locksroot to each NettingChannelEndState
27,523
def add_greenlet_name ( _logger : str , _method_name : str , event_dict : Dict [ str , Any ] , ) -> Dict [ str , Any ] : current_greenlet = gevent . getcurrent ( ) greenlet_name = getattr ( current_greenlet , 'name' , None ) if greenlet_name is not None and not greenlet_name . startswith ( 'Greenlet-' ) : event_dict [ ...
Add greenlet_name to the event dict for greenlets that have a non - default name .
27,524
def redactor ( blacklist : Dict [ Pattern , str ] ) -> Callable [ [ str ] , str ] : def processor_wrapper ( msg : str ) -> str : for regex , repl in blacklist . items ( ) : if repl is None : repl = '<redacted>' msg = regex . sub ( repl , msg ) return msg return processor_wrapper
Returns a function which transforms a str replacing all matches for its replacement
27,525
def _wrap_tracebackexception_format ( redact : Callable [ [ str ] , str ] ) : original_format = getattr ( TracebackException , '_original' , None ) if original_format is None : original_format = TracebackException . format setattr ( TracebackException , '_original' , original_format ) @ wraps ( original_format ) def tr...
Monkey - patch TracebackException . format to redact printed lines .
27,526
def should_log ( self , logger_name : str , level : str ) -> bool : if ( logger_name , level ) not in self . _should_log : log_level_per_rule = self . _get_log_level ( logger_name ) log_level_per_rule_numeric = getattr ( logging , log_level_per_rule . upper ( ) , 10 ) log_level_event_numeric = getattr ( logging , level...
Returns if a message for the logger should be logged .
27,527
def _update_statechanges ( storage : SQLiteStorage ) : batch_size = 50 batch_query = storage . batch_query_state_changes ( batch_size = batch_size , filters = [ ( '_type' , 'raiden.transfer.state_change.ContractReceiveChannelNew' ) , ] , ) for state_changes_batch in batch_query : updated_state_changes = list ( ) for st...
Update each ContractReceiveChannelNew s channel_state member by setting the mediation_fee that was added to the NettingChannelState
27,528
def get_contract_events ( chain : BlockChainService , abi : Dict , contract_address : Address , topics : Optional [ List [ str ] ] , from_block : BlockSpecification , to_block : BlockSpecification , ) -> List [ Dict ] : verify_block_number ( from_block , 'from_block' ) verify_block_number ( to_block , 'to_block' ) even...
Query the blockchain for all events of the smart contract at contract_address that match the filters topics from_block and to_block .
27,529
def get_token_network_registry_events ( chain : BlockChainService , token_network_registry_address : PaymentNetworkID , contract_manager : ContractManager , events : Optional [ List [ str ] ] = ALL_EVENTS , from_block : BlockSpecification = GENESIS_BLOCK_NUMBER , to_block : BlockSpecification = 'latest' , ) -> List [ D...
Helper to get all events of the Registry contract at registry_address .
27,530
def get_token_network_events ( chain : BlockChainService , token_network_address : Address , contract_manager : ContractManager , events : Optional [ List [ str ] ] = ALL_EVENTS , from_block : BlockSpecification = GENESIS_BLOCK_NUMBER , to_block : BlockSpecification = 'latest' , ) -> List [ Dict ] : return get_contract...
Helper to get all events of the ChannelManagerContract at token_address .
27,531
def get_all_netting_channel_events ( chain : BlockChainService , token_network_address : TokenNetworkAddress , netting_channel_identifier : ChannelID , contract_manager : ContractManager , from_block : BlockSpecification = GENESIS_BLOCK_NUMBER , to_block : BlockSpecification = 'latest' , ) -> List [ Dict ] : filter_arg...
Helper to get all events of a NettingChannelContract .
27,532
def decode_event_to_internal ( abi , log_event ) : decoded_event = decode_event ( abi , log_event ) if not decoded_event : raise UnknownEventType ( ) data = dict ( decoded_event ) args = dict ( data [ 'args' ] ) data [ 'args' ] = args data [ 'block_number' ] = log_event . pop ( 'blockNumber' ) data [ 'transaction_hash'...
Enforce the binary for internal usage .
27,533
def poll_blockchain_events ( self , block_number : typing . BlockNumber ) : for event_listener in self . event_listeners : assert isinstance ( event_listener . filter , StatelessFilter ) for log_event in event_listener . filter . get_new_entries ( block_number ) : yield decode_event_to_internal ( event_listener . abi ,...
Poll for new blockchain events up to block_number .
27,534
def generate_accounts ( seeds ) : return { seed : { 'privatekey' : encode_hex ( sha3 ( seed ) ) , 'address' : encode_hex ( privatekey_to_address ( sha3 ( seed ) ) ) , } for seed in seeds }
Create private keys and addresses for all seeds .
27,535
def mk_genesis ( accounts , initial_alloc = denoms . ether * 100000000 ) : genesis = GENESIS_STUB . copy ( ) genesis [ 'extraData' ] = encode_hex ( CLUSTER_NAME ) genesis [ 'alloc' ] . update ( { account : { 'balance' : str ( initial_alloc ) , } for account in accounts } ) genesis [ 'alloc' ] [ '19e7e376e7c213b7e7e7e46...
Create a genesis - block dict with allocation for all accounts .
27,536
def token_address ( self ) -> Address : return to_canonical_address ( self . proxy . contract . functions . token ( ) . call ( ) )
Return the token of this manager .
27,537
def new_netting_channel ( self , partner : Address , settle_timeout : int , given_block_identifier : BlockSpecification , ) -> ChannelID : checking_block = self . client . get_checking_block ( ) self . _new_channel_preconditions ( partner = partner , settle_timeout = settle_timeout , block_identifier = given_block_iden...
Creates a new channel in the TokenNetwork contract .
27,538
def _channel_exists_and_not_settled ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID = None , ) -> bool : try : channel_state = self . _get_channel_state ( participant1 = participant1 , participant2 = participant2 , block_identifier = bloc...
Returns if the channel exists and is in a non - settled state
27,539
def _detail_participant ( self , channel_identifier : ChannelID , participant : Address , partner : Address , block_identifier : BlockSpecification , ) -> ParticipantDetails : data = self . _call_and_check_result ( block_identifier , 'getChannelParticipantInfo' , channel_identifier = channel_identifier , participant = ...
Returns a dictionary with the channel participant information .
27,540
def _detail_channel ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID = None , ) -> ChannelData : channel_identifier = self . _inspect_channel_identifier ( participant1 = participant1 , participant2 = participant2 , called_by_fn = '_detail_...
Returns a ChannelData instance with the channel specific information .
27,541
def detail_participants ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID = None , ) -> ParticipantsDetails : if self . node_address not in ( participant1 , participant2 ) : raise ValueError ( 'One participant must be the node address' ) if...
Returns a ParticipantsDetails instance with the participants channel information .
27,542
def detail ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID = None , ) -> ChannelDetails : if self . node_address not in ( participant1 , participant2 ) : raise ValueError ( 'One participant must be the node address' ) if self . node_addre...
Returns a ChannelDetails instance with all the details of the channel and the channel participants .
27,543
def channel_is_opened ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID , ) -> bool : try : channel_state = self . _get_channel_state ( participant1 = participant1 , participant2 = participant2 , block_identifier = block_identifier , channe...
Returns true if the channel is in an open state false otherwise .
27,544
def channel_is_closed ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID , ) -> bool : try : channel_state = self . _get_channel_state ( participant1 = participant1 , participant2 = participant2 , block_identifier = block_identifier , channe...
Returns true if the channel is in a closed state false otherwise .
27,545
def channel_is_settled ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID , ) -> bool : try : channel_state = self . _get_channel_state ( participant1 = participant1 , participant2 = participant2 , block_identifier = block_identifier , chann...
Returns true if the channel is in a settled state false otherwise .
27,546
def closing_address ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID = None , ) -> Optional [ Address ] : try : channel_data = self . _detail_channel ( participant1 = participant1 , participant2 = participant2 , block_identifier = block_id...
Returns the address of the closer if the channel is closed and not settled . None otherwise .
27,547
def set_total_deposit ( self , given_block_identifier : BlockSpecification , channel_identifier : ChannelID , total_deposit : TokenAmount , partner : Address , ) : if not isinstance ( total_deposit , int ) : raise ValueError ( 'total_deposit needs to be an integer number.' ) token_address = self . token_address ( ) tok...
Set channel s total deposit .
27,548
def close ( self , channel_identifier : ChannelID , partner : Address , balance_hash : BalanceHash , nonce : Nonce , additional_hash : AdditionalHash , signature : Signature , given_block_identifier : BlockSpecification , ) : log_details = { 'token_network' : pex ( self . address ) , 'node' : pex ( self . node_address ...
Close the channel using the provided balance proof .
27,549
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 .
27,550
def events_filter ( self , topics : List [ str ] = None , from_block : BlockSpecification = None , to_block : BlockSpecification = None , ) -> StatelessFilter : return self . client . new_filter ( self . address , topics = topics , from_block = from_block , to_block = to_block , )
Install a new filter for an array of topics emitted by the contract .
27,551
def all_events_filter ( self , from_block : BlockSpecification = GENESIS_BLOCK_NUMBER , to_block : BlockSpecification = 'latest' , ) -> StatelessFilter : return self . events_filter ( None , from_block , to_block )
Install a new filter for all the events emitted by the current token network contract
27,552
def _check_for_outdated_channel ( self , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , channel_identifier : ChannelID , ) -> None : try : onchain_channel_details = self . _detail_channel ( participant1 = participant1 , participant2 = participant2 , block_identifier = block_id...
Checks whether an operation is being executed on a channel between two participants using an old channel identifier
27,553
def _check_channel_state_for_update ( self , channel_identifier : ChannelID , closer : Address , update_nonce : Nonce , block_identifier : BlockSpecification , ) -> Optional [ str ] : msg = None closer_details = self . _detail_participant ( channel_identifier = channel_identifier , participant = closer , partner = self...
Check the channel state on chain to see if it has been updated .
27,554
def event_first_of ( * events : _AbstractLinkable ) -> Event : 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
Waits until one of events is set .
27,555
def timeout_exponential_backoff ( retries : int , timeout : int , maximum : int , ) -> Iterator [ int ] : 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
Timeouts generator with an exponential backoff strategy .
27,556
def timeout_two_stage ( retries : int , timeout1 : int , timeout2 : int , ) -> Iterable [ int ] : for _ in range ( retries ) : yield timeout1 while True : yield timeout2
Timeouts generator with a two stage strategy
27,557
def retry ( transport : 'UDPTransport' , messagedata : bytes , message_id : UDPMessageID , recipient : Address , stop_event : Event , timeout_backoff : Iterable [ int ] , ) -> bool : async_result = transport . maybe_sendraw_with_result ( recipient , messagedata , message_id , ) event_quit = event_first_of ( async_resul...
Send messagedata until it s acknowledged .
27,558
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 : stop_or_unhealthy = event_first_of ( stop_event , event_unhealthy , ) acknowledge...
Send messagedata while the node is healthy until it s acknowledged .
27,559
def get_secret_registration_block_by_secrethash ( self , secrethash : SecretHash , block_identifier : BlockSpecification , ) -> Optional [ BlockNumber ] : result = self . proxy . contract . functions . getSecretRevealBlockHeight ( secrethash , ) . call ( block_identifier = block_identifier ) if result == 0 : return Non...
Return the block number at which the secret for secrethash was registered None if the secret was never registered .
27,560
def is_secret_registered ( self , secrethash : SecretHash , block_identifier : BlockSpecification , ) -> bool : if not self . client . can_query_state_for_block ( block_identifier ) : raise NoStateForBlockIdentifier ( ) block = self . get_secret_registration_block_by_secrethash ( secrethash = secrethash , block_identif...
True if the secret for secrethash is registered at block_identifier .
27,561
def register_token ( self , registry_address_hex : typing . AddressHex , token_address_hex : typing . AddressHex , retry_timeout : typing . NetworkTimeout = DEFAULT_RETRY_TIMEOUT , ) -> TokenNetwork : registry_address = decode_hex ( registry_address_hex ) token_address = decode_hex ( token_address_hex ) registry = self...
Register a token with the raiden token manager .
27,562
def open_channel_with_funding ( self , registry_address_hex , token_address_hex , peer_address_hex , total_deposit , settle_timeout = None , ) : registry_address = decode_hex ( registry_address_hex ) peer_address = decode_hex ( peer_address_hex ) token_address = decode_hex ( token_address_hex ) try : self . _discovery ...
Convenience method to open a channel .
27,563
def wait_for_contract ( self , contract_address_hex , timeout = None ) : 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...
Wait until a contract is mined
27,564
def _filter_from_dict ( current : Dict [ str , Any ] ) -> Dict [ str , Any ] : 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_
Takes in a nested dictionary as a filter and returns a flattened filter dictionary
27,565
def log_run ( self ) : version = get_system_spec ( ) [ 'raiden' ] cursor = self . conn . cursor ( ) cursor . execute ( 'INSERT INTO runs(raiden_version) VALUES (?)' , [ version ] ) self . maybe_commit ( )
Log timestamp and raiden version to help with debugging
27,566
def delete_state_changes ( self , state_changes_to_delete : List [ int ] ) -> None : with self . write_lock , self . conn : self . conn . executemany ( 'DELETE FROM state_events WHERE identifier = ?' , state_changes_to_delete , )
Delete state changes .
27,567
def batch_query_state_changes ( self , batch_size : int , filters : List [ Tuple [ str , Any ] ] = None , logical_and : bool = True , ) -> Iterator [ List [ StateChangeRecord ] ] : limit = batch_size offset = 0 result_length = 1 while result_length != 0 : result = self . _get_state_changes ( limit = limit , offset = of...
Batch query state change records with a given batch size and an optional filter
27,568
def _get_event_records ( self , limit : int = None , offset : int = None , filters : List [ Tuple [ str , Any ] ] = None , logical_and : bool = True , ) -> List [ EventRecord ] : cursor = self . _form_and_execute_json_query ( query = 'SELECT identifier, source_statechange_id, data FROM state_events ' , limit = limit , ...
Return a batch of event records
27,569
def batch_query_event_records ( self , batch_size : int , filters : List [ Tuple [ str , Any ] ] = None , logical_and : bool = True , ) -> Iterator [ List [ EventRecord ] ] : limit = batch_size offset = 0 result_length = 1 while result_length != 0 : result = self . _get_event_records ( limit = limit , offset = offset ,...
Batch query event records with a given batch size and an optional filter
27,570
def update_snapshots ( self , snapshots_data : List [ Tuple [ str , int ] ] ) : cursor = self . conn . cursor ( ) cursor . executemany ( 'UPDATE state_snapshot SET data=? WHERE identifier=?' , snapshots_data , ) self . maybe_commit ( )
Given a list of snapshot data update them in the DB
27,571
def all_neighbour_nodes ( chain_state : ChainState ) -> Set [ Address ] : 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_...
Return the identifiers for all nodes accross all payment networks which have a channel open with this one .
27,572
def get_token_network_identifiers ( chain_state : ChainState , payment_network_id : PaymentNetworkID , ) -> List [ TokenNetworkID ] : 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...
Return the list of token networks registered with the given payment network .
27,573
def get_token_identifiers ( chain_state : ChainState , payment_network_id : PaymentNetworkID , ) -> List [ TokenAddress ] : payment_network = chain_state . identifiers_to_paymentnetworks . get ( payment_network_id ) if payment_network is not None : return [ token_address for token_address in payment_network . tokenaddr...
Return the list of tokens registered with the given payment network .
27,574
def get_channelstate_filter ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , filter_fn : Callable , ) -> List [ NettingChannelState ] : token_network = get_token_network_by_token_address ( chain_state , payment_network_id , token_address , ) result : List [ NettingChan...
Return the state of channels that match the condition in filter_fn
27,575
def get_channelstate_open ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : return get_channelstate_filter ( chain_state , payment_network_id , token_address , lambda channel_state : channel . get_status ( channel_state ) == CHANNEL_S...
Return the state of open channels in a token network .
27,576
def get_channelstate_closing ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : return get_channelstate_filter ( chain_state , payment_network_id , token_address , lambda channel_state : channel . get_status ( channel_state ) == CHANNE...
Return the state of closing channels in a token network .
27,577
def get_channelstate_closed ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : return get_channelstate_filter ( chain_state , payment_network_id , token_address , lambda channel_state : channel . get_status ( channel_state ) == CHANNEL...
Return the state of closed channels in a token network .
27,578
def get_channelstate_settling ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : return get_channelstate_filter ( chain_state , payment_network_id , token_address , lambda channel_state : channel . get_status ( channel_state ) == CHANN...
Return the state of settling channels in a token network .
27,579
def get_channelstate_settled ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : return get_channelstate_filter ( chain_state , payment_network_id , token_address , lambda channel_state : channel . get_status ( channel_state ) == CHANNE...
Return the state of settled channels in a token network .
27,580
def role_from_transfer_task ( transfer_task : TransferTask ) -> str : if isinstance ( transfer_task , InitiatorTask ) : return 'initiator' if isinstance ( transfer_task , MediatorTask ) : return 'mediator' if isinstance ( transfer_task , TargetTask ) : return 'target' raise ValueError ( 'Argument to role_from_transfer_...
Return the role and type for the transfer . Throws an exception on error
27,581
def secret_from_transfer_task ( transfer_task : Optional [ TransferTask ] , secrethash : SecretHash , ) -> Optional [ Secret ] : assert isinstance ( transfer_task , InitiatorTask ) transfer_state = transfer_task . manager_state . initiator_transfers [ secrethash ] if transfer_state is None : return None return transfer...
Return the secret for the transfer None on EMPTY_SECRET .
27,582
def get_transfer_role ( chain_state : ChainState , secrethash : SecretHash ) -> Optional [ str ] : task = chain_state . payment_mapping . secrethashes_to_task . get ( secrethash ) if not task : return None return role_from_transfer_task ( task )
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
27,583
def filter_channels_by_status ( channel_states : List [ NettingChannelState ] , exclude_states : Optional [ List [ str ] ] = None , ) -> List [ NettingChannelState ] : if exclude_states is None : exclude_states = [ ] states = [ ] for channel_state in channel_states : if channel . get_status ( channel_state ) not in exc...
Filter the list of channels by excluding ones for which the state exists in exclude_states .
27,584
def detect_balance_proof_change ( old_state : ChainState , current_state : ChainState , ) -> Iterator [ Union [ BalanceProofSignedState , BalanceProofUnsignedState ] ] : if old_state == current_state : return for payment_network_identifier in current_state . identifiers_to_paymentnetworks : try : old_payment_network = ...
Compare two states for any received balance_proofs that are not in old_state .
27,585
def connect ( ) : upnp = miniupnpc . UPnP ( ) upnp . discoverdelay = 200 providers = upnp . discover ( ) if providers > 1 : log . debug ( 'multiple upnp providers found' , num_providers = providers ) elif providers < 1 : log . error ( 'no upnp providers found' ) return None try : location = upnp . selectigd ( ) log . d...
Try to connect to the router .
27,586
def release_port ( upnp , external_port ) : mapping = upnp . getspecificportmapping ( external_port , 'UDP' ) if mapping is None : log . error ( 'could not find a port mapping' , external = external_port ) return False else : log . debug ( 'found existing port mapping' , mapping = mapping ) if upnp . deleteportmapping ...
Try to release the port mapping for external_port .
27,587
def token ( self , token_address : Address ) -> Token : if not is_binary_address ( token_address ) : raise ValueError ( 'token_address must be a valid address' ) with self . _token_creation_lock : if token_address not in self . address_to_token : self . address_to_token [ token_address ] = Token ( jsonrpc_client = self...
Return a proxy to interact with a token .
27,588
def discovery ( self , discovery_address : Address ) -> Discovery : if not is_binary_address ( discovery_address ) : raise ValueError ( 'discovery_address must be a valid address' ) with self . _discovery_creation_lock : if discovery_address not in self . address_to_discovery : self . address_to_discovery [ discovery_a...
Return a proxy to interact with the discovery .
27,589
def check_address_has_code ( client : 'JSONRPCClient' , address : Address , contract_name : str = '' , ) : result = client . web3 . eth . getCode ( to_checksum_address ( address ) , 'latest' ) if not result : if contract_name : formated_contract_name = '[{}]: ' . format ( contract_name ) else : formated_contract_name =...
Checks that the given address contains code .
27,590
def dependencies_order_of_build ( target_contract , dependencies_map ) : if not dependencies_map : return [ target_contract ] if target_contract not in dependencies_map : raise ValueError ( 'no dependencies defined for {}' . format ( target_contract ) ) order = [ target_contract ] todo = list ( dependencies_map [ targe...
Return an ordered list of contracts that is sufficient to successfully deploy the target contract .
27,591
def check_value_error_for_parity ( value_error : ValueError , call_type : ParityCallType ) -> bool : try : error_data = json . loads ( str ( value_error ) . replace ( "'" , '"' ) ) except json . JSONDecodeError : return False if call_type == ParityCallType . ESTIMATE_GAS : code_checks_out = error_data [ 'code' ] == - 3...
For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception .
27,592
def get_confirmed_blockhash ( self ) : confirmed_block_number = self . web3 . eth . blockNumber - self . default_block_num_confirmations if confirmed_block_number < 0 : confirmed_block_number = 0 return self . blockhash_from_blocknumber ( confirmed_block_number )
Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash
27,593
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 .
27,594
def parity_get_pending_transaction_hash_by_nonce ( self , address : AddressHex , nonce : Nonce , ) -> Optional [ TransactionHash ] : assert self . eth_node is constants . EthClient . PARITY transactions = self . web3 . manager . request_blocking ( 'parity_allTransactions' , [ ] ) log . debug ( 'RETURNED TRANSACTIONS' ,...
Queries the local parity transaction pool and searches for a transaction .
27,595
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 .
27,596
def send_transaction ( self , to : Address , startgas : int , value : int = 0 , data : bytes = b'' , ) -> bytes : if to == to_canonical_address ( constants . NULL_ADDRESS ) : warnings . warn ( 'For contract creation the empty string must be used.' ) with self . _nonce_lock : nonce = self . _available_nonce gas_price = ...
Helper to send signed messages .
27,597
def poll ( self , transaction_hash : bytes , ) : if len ( transaction_hash ) != 32 : raise ValueError ( 'transaction_hash must be a 32 byte hash' , ) transaction_hash = encode_hex ( transaction_hash ) last_result = None while True : transaction = self . web3 . eth . getTransaction ( transaction_hash ) if transaction is...
Wait until the transaction_hash is applied or rejected .
27,598
def new_filter ( self , contract_address : Address , topics : List [ str ] = None , from_block : BlockSpecification = 0 , to_block : BlockSpecification = 'latest' , ) -> StatelessFilter : logs_blocks_sanity_check ( from_block , to_block ) return StatelessFilter ( self . web3 , { 'fromBlock' : from_block , 'toBlock' : t...
Create a filter in the ethereum node .
27,599
def get_filter_events ( self , contract_address : Address , topics : List [ str ] = None , from_block : BlockSpecification = 0 , to_block : BlockSpecification = 'latest' , ) -> List [ Dict ] : logs_blocks_sanity_check ( from_block , to_block ) return self . web3 . eth . getLogs ( { 'fromBlock' : from_block , 'toBlock' ...
Get events for the given query .