idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
27,700
def _redact_secret ( data : Union [ Dict , List ] , ) -> Union [ Dict , List ] : if isinstance ( data , dict ) : stack = [ data ] else : stack = [ ] while stack : current = stack . pop ( ) if 'secret' in current : current [ 'secret' ] = '<redacted>' else : stack . extend ( value for value in current . values ( ) if isi...
Modify data in - place and replace keys named secret .
27,701
def stop ( self ) : if self . stop_event . ready ( ) : return self . stop_event . set ( ) self . transport . stop ( ) self . alarm . stop ( ) self . transport . join ( ) self . alarm . join ( ) self . blockchain_events . uninstall_all_event_listeners ( ) self . wal . storage . conn . close ( ) if self . db_lock is not ...
Stop the node gracefully . Raise if any stop - time error occurred on any subtask
27,702
def _start_transport ( self , chain_state : ChainState ) : assert self . alarm . is_primed ( ) , f'AlarmTask not primed. node:{self!r}' assert self . ready_to_process_events , f'Event procossing disable. node:{self!r}' self . transport . start ( raiden_service = self , message_handler = self . message_handler , prev_au...
Initialize the transport and related facilities .
27,703
def handle_and_track_state_change ( self , state_change : StateChange ) : for greenlet in self . handle_state_change ( state_change ) : self . add_pending_greenlet ( greenlet )
Dispatch the state change and does not handle the exceptions .
27,704
def handle_state_change ( self , state_change : StateChange ) -> List [ Greenlet ] : assert self . wal , f'WAL not restored. node:{self!r}' log . debug ( 'State change' , node = pex ( self . address ) , state_change = _redact_secret ( serialize . JSONSerializer . serialize ( state_change ) ) , ) old_state = views . sta...
Dispatch the state change and return the processing threads .
27,705
def handle_event ( self , raiden_event : RaidenEvent ) -> Greenlet : return gevent . spawn ( self . _handle_event , raiden_event )
Spawn a new thread to handle a Raiden event .
27,706
def start_health_check_for ( self , node_address : Address ) : if self . transport : self . transport . start_health_check ( node_address )
Start health checking node_address .
27,707
def _callback_new_block ( self , latest_block : Dict ) : with self . event_poll_lock : latest_block_number = latest_block [ 'number' ] confirmed_block_number = max ( GENESIS_BLOCK_NUMBER , latest_block_number - self . config [ 'blockchain' ] [ 'confirmation_blocks' ] , ) confirmed_block = self . chain . client . web3 ....
Called once a new block is detected by the alarm task .
27,708
def _initialize_transactions_queues ( self , chain_state : ChainState ) : assert self . alarm . is_primed ( ) , f'AlarmTask not primed. node:{self!r}' pending_transactions = views . get_pending_transactions ( chain_state ) log . debug ( 'Processing pending transactions' , num_pending_transactions = len ( pending_transa...
Initialize the pending transaction queue from the previous run .
27,709
def _initialize_payment_statuses ( self , chain_state : ChainState ) : with self . payment_identifier_lock : for task in chain_state . payment_mapping . secrethashes_to_task . values ( ) : if not isinstance ( task , InitiatorTask ) : continue initiator = next ( iter ( task . manager_state . initiator_transfers . values...
Re - initialize targets_to_identifiers_to_statuses .
27,710
def _initialize_messages_queues ( self , chain_state : ChainState ) : assert not self . transport , f'Transport is running. node:{self!r}' assert self . alarm . is_primed ( ) , f'AlarmTask not primed. node:{self!r}' events_queues = views . get_all_messagequeues ( chain_state ) for queue_identifier , event_queue in even...
Initialize all the message queues with the transport .
27,711
def _initialize_monitoring_services_queue ( self , chain_state : ChainState ) : msg = ( 'Transport was started before the monitoring service queue was updated. ' 'This can lead to safety issue. node:{self!r}' ) assert not self . transport , msg msg = ( 'The node state was not yet recovered, cant read balance proofs. no...
Send the monitoring requests for all current balance proofs .
27,712
def _initialize_whitelists ( self , chain_state : ChainState ) : for neighbour in views . all_neighbour_nodes ( chain_state ) : if neighbour == ConnectionManager . BOOTSTRAP_ADDR : continue self . transport . whitelist ( neighbour ) events_queues = views . get_all_messagequeues ( chain_state ) for event_queue in events...
Whitelist neighbors and mediated transfer targets on transport
27,713
def sign ( self , message : Message ) : if not isinstance ( message , SignedMessage ) : raise ValueError ( '{} is not signable.' . format ( repr ( message ) ) ) message . sign ( self . signer )
Sign message inplace .
27,714
def mediated_transfer_async ( self , token_network_identifier : TokenNetworkID , amount : PaymentAmount , target : TargetAddress , identifier : PaymentID , fee : FeeAmount = MEDIATION_FEE , secret : Secret = None , secret_hash : SecretHash = None , ) -> PaymentStatus : if secret is None : if secret_hash is None : secre...
Transfer amount between this node and target .
27,715
def from_dict_hook ( data ) : type_ = data . get ( '_type' , None ) if type_ is not None : klass = _import_type ( type_ ) msg = '_type must point to a class with `from_dict` static method' assert hasattr ( klass , 'from_dict' ) , msg return klass . from_dict ( data ) return data
Decode internal objects encoded using to_dict_hook .
27,716
def to_dict_hook ( obj ) : if hasattr ( obj , 'to_dict' ) : result = obj . to_dict ( ) assert isinstance ( result , dict ) , 'to_dict must return a dictionary' result [ '_type' ] = f'{obj.__module__}.{obj.__class__.__name__}' result [ '_version' ] = 0 return result raise TypeError ( f'Object of type {obj.__class__.__na...
Convert internal objects to a serializable representation .
27,717
def rgb_color_picker ( obj , min_luminance = None , max_luminance = None ) : color_value = int . from_bytes ( hashlib . md5 ( str ( obj ) . encode ( 'utf-8' ) ) . digest ( ) , 'little' , ) % 0xffffff color = Color ( f'#{color_value:06x}' ) if min_luminance and color . get_luminance ( ) < min_luminance : color . set_lum...
Modified version of colour . RGB_color_picker
27,718
def random_secret ( ) -> Secret : while True : secret = os . urandom ( 32 ) if secret != constants . EMPTY_HASH : return Secret ( secret )
Return a random 32 byte secret except the 0 secret since it s not accepted in the contracts
27,719
def address_checksum_and_decode ( addr : str ) -> Address : if not is_0x_prefixed ( addr ) : raise InvalidAddress ( 'Address must be 0x prefixed' ) if not is_checksum_address ( addr ) : raise InvalidAddress ( 'Address must be EIP55 checksummed' ) addr_bytes = decode_hex ( addr ) assert len ( addr_bytes ) in ( 20 , 0 ) ...
Accepts a string address and turns it into binary .
27,720
def privatekey_to_publickey ( private_key_bin : bytes ) -> bytes : if not ishash ( private_key_bin ) : raise ValueError ( 'private_key_bin format mismatch. maybe hex encoded?' ) return keys . PrivateKey ( private_key_bin ) . public_key . to_bytes ( )
Returns public key in bitcoins bin encoding .
27,721
def get_system_spec ( ) -> Dict [ str , str ] : import pkg_resources import platform if sys . platform == 'darwin' : system_info = 'macOS {} {}' . format ( platform . mac_ver ( ) [ 0 ] , platform . architecture ( ) [ 0 ] , ) else : system_info = '{} {} {}' . format ( platform . system ( ) , '_' . join ( part for part i...
Collect information about the system and installation .
27,722
def safe_gas_limit ( * estimates : int ) -> int : assert None not in estimates , 'if estimateGas returned None it should not reach here' calculated_limit = max ( estimates ) return int ( calculated_limit * constants . GAS_FACTOR )
Calculates a safe gas limit for a number of gas estimates including a security margin
27,723
def block_specification_to_number ( block : BlockSpecification , web3 : Web3 ) -> BlockNumber : if isinstance ( block , str ) : msg = f"string block specification can't contain {block}" assert block in ( 'latest' , 'pending' ) , msg number = web3 . eth . getBlock ( block ) [ 'number' ] elif isinstance ( block , T_Block...
Converts a block specification to an actual block number
27,724
def detail ( self , block_identifier : BlockSpecification ) -> ChannelDetails : return self . token_network . detail ( participant1 = self . participant1 , participant2 = self . participant2 , block_identifier = block_identifier , channel_identifier = self . channel_identifier , )
Returns the channel details .
27,725
def settle_timeout ( self ) -> int : filter_args = get_filter_args_for_specific_event_from_channel ( token_network_address = self . token_network . address , channel_identifier = self . channel_identifier , event_name = ChannelEvent . OPENED , contract_manager = self . contract_manager , ) events = self . token_network...
Returns the channels settle_timeout .
27,726
def opened ( self , block_identifier : BlockSpecification ) -> bool : return self . token_network . channel_is_opened ( participant1 = self . participant1 , participant2 = self . participant2 , block_identifier = block_identifier , channel_identifier = self . channel_identifier , )
Returns if the channel is opened .
27,727
def closed ( self , block_identifier : BlockSpecification ) -> bool : return self . token_network . channel_is_closed ( participant1 = self . participant1 , participant2 = self . participant2 , block_identifier = block_identifier , channel_identifier = self . channel_identifier , )
Returns if the channel is closed .
27,728
def settled ( self , block_identifier : BlockSpecification ) -> bool : return self . token_network . channel_is_settled ( participant1 = self . participant1 , participant2 = self . participant2 , block_identifier = block_identifier , channel_identifier = self . channel_identifier , )
Returns if the channel is settled .
27,729
def closing_address ( self , block_identifier : BlockSpecification ) -> Optional [ Address ] : return self . token_network . closing_address ( participant1 = self . participant1 , participant2 = self . participant2 , block_identifier = block_identifier , channel_identifier = self . channel_identifier , )
Returns the address of the closer of the channel .
27,730
def close ( self , nonce : Nonce , balance_hash : BalanceHash , additional_hash : AdditionalHash , signature : Signature , block_identifier : BlockSpecification , ) : self . token_network . close ( channel_identifier = self . channel_identifier , partner = self . participant2 , balance_hash = balance_hash , nonce = non...
Closes the channel using the provided balance proof .
27,731
def update_transfer ( self , nonce : Nonce , balance_hash : BalanceHash , additional_hash : AdditionalHash , partner_signature : Signature , signature : Signature , block_identifier : BlockSpecification , ) : self . token_network . update_transfer ( channel_identifier = self . channel_identifier , partner = self . part...
Updates the channel using the provided balance proof .
27,732
def settle ( self , transferred_amount : TokenAmount , locked_amount : TokenAmount , locksroot : Locksroot , partner_transferred_amount : TokenAmount , partner_locked_amount : TokenAmount , partner_locksroot : Locksroot , block_identifier : BlockSpecification , ) : self . token_network . settle ( channel_identifier = s...
Settles the channel .
27,733
def events_for_unlock_lock ( initiator_state : InitiatorTransferState , channel_state : NettingChannelState , secret : Secret , secrethash : SecretHash , pseudo_random_generator : random . Random , ) -> List [ Event ] : transfer_description = initiator_state . transfer_description message_identifier = message_identifie...
Unlocks the lock offchain and emits the events for the successful payment .
27,734
def handle_block ( initiator_state : InitiatorTransferState , state_change : Block , channel_state : NettingChannelState , pseudo_random_generator : random . Random , ) -> TransitionResult [ InitiatorTransferState ] : secrethash = initiator_state . transfer . lock . secrethash locked_lock = channel_state . our_state . ...
Checks if the lock has expired and if it has sends a remove expired lock and emits the failing events .
27,735
def next_channel_from_routes ( available_routes : List [ RouteState ] , channelidentifiers_to_channels : ChannelMap , transfer_amount : PaymentAmount , ) -> Optional [ NettingChannelState ] : for route in available_routes : channel_identifier = route . channel_identifier channel_state = channelidentifiers_to_channels ....
Returns the first channel that can be used to start the transfer . The routing service can race with local changes so the recommended routes must be validated .
27,736
def send_lockedtransfer ( transfer_description : TransferDescriptionWithSecretState , channel_state : NettingChannelState , message_identifier : MessageID , block_number : BlockNumber , ) -> SendLockedTransfer : assert channel_state . token_network_identifier == transfer_description . token_network_identifier lock_expi...
Create a mediated transfer using channel .
27,737
def handle_offchain_secretreveal ( initiator_state : InitiatorTransferState , state_change : ReceiveSecretReveal , channel_state : NettingChannelState , pseudo_random_generator : random . Random , ) -> TransitionResult [ InitiatorTransferState ] : iteration : TransitionResult [ InitiatorTransferState ] valid_reveal = i...
Once the next hop proves it knows the secret the initiator can unlock the mediated transfer .
27,738
def handle_onchain_secretreveal ( initiator_state : InitiatorTransferState , state_change : ContractReceiveSecretReveal , channel_state : NettingChannelState , pseudo_random_generator : random . Random , ) -> TransitionResult [ InitiatorTransferState ] : iteration : TransitionResult [ InitiatorTransferState ] secret = ...
When a secret is revealed on - chain all nodes learn the secret .
27,739
def is_lock_pending ( end_state : NettingChannelEndState , secrethash : SecretHash , ) -> bool : return ( secrethash in end_state . secrethashes_to_lockedlocks or secrethash in end_state . secrethashes_to_unlockedlocks or secrethash in end_state . secrethashes_to_onchain_unlockedlocks )
True if the secrethash corresponds to a lock that is pending to be claimed and didn t expire .
27,740
def is_deposit_confirmed ( channel_state : NettingChannelState , block_number : BlockNumber , ) -> bool : if not channel_state . deposit_transaction_queue : return False return is_transaction_confirmed ( channel_state . deposit_transaction_queue [ 0 ] . block_number , block_number , )
True if the block which mined the deposit transaction has been confirmed .
27,741
def is_lock_expired ( end_state : NettingChannelEndState , lock : LockType , block_number : BlockNumber , lock_expiration_threshold : BlockNumber , ) -> SuccessOrError : secret_registered_on_chain = lock . secrethash in end_state . secrethashes_to_onchain_unlockedlocks if secret_registered_on_chain : return ( False , '...
Determine whether a lock has expired .
27,742
def is_secret_known ( end_state : NettingChannelEndState , secrethash : SecretHash , ) -> bool : return ( secrethash in end_state . secrethashes_to_unlockedlocks or secrethash in end_state . secrethashes_to_onchain_unlockedlocks )
True if the secrethash is for a lock with a known secret .
27,743
def get_secret ( end_state : NettingChannelEndState , secrethash : SecretHash , ) -> Optional [ Secret ] : partial_unlock_proof = end_state . secrethashes_to_unlockedlocks . get ( secrethash ) if partial_unlock_proof is None : partial_unlock_proof = end_state . secrethashes_to_onchain_unlockedlocks . get ( secrethash )...
Returns secret if the secrethash is for a lock with a known secret .
27,744
def is_balance_proof_safe_for_onchain_operations ( balance_proof : BalanceProofSignedState , ) -> bool : total_amount = balance_proof . transferred_amount + balance_proof . locked_amount return total_amount <= UINT256_MAX
Check if the balance proof would overflow onchain .
27,745
def is_balance_proof_usable_onchain ( received_balance_proof : BalanceProofSignedState , channel_state : NettingChannelState , sender_state : NettingChannelEndState , ) -> SuccessOrError : expected_nonce = get_next_nonce ( sender_state ) is_valid_signature_ , signature_msg = is_valid_signature ( received_balance_proof ...
Checks the balance proof can be used on - chain .
27,746
def get_distributable ( sender : NettingChannelEndState , receiver : NettingChannelEndState , ) -> TokenAmount : _ , _ , transferred_amount , locked_amount = get_current_balanceproof ( sender ) distributable = get_balance ( sender , receiver ) - get_amount_locked ( sender ) overflow_limit = max ( UINT256_MAX - transfer...
Return the amount of tokens that can be used by the sender .
27,747
def get_batch_unlock ( end_state : NettingChannelEndState , ) -> Optional [ MerkleTreeLeaves ] : if len ( end_state . merkletree . layers [ LEAVES ] ) == 0 : return None lockhashes_to_locks = dict ( ) lockhashes_to_locks . update ( { lock . lockhash : lock for secrethash , lock in end_state . secrethashes_to_lockedlock...
Unlock proof for an entire merkle tree of pending locks
27,748
def get_lock ( end_state : NettingChannelEndState , secrethash : SecretHash , ) -> Optional [ HashTimeLockState ] : lock = end_state . secrethashes_to_lockedlocks . get ( secrethash ) if not lock : partial_unlock = end_state . secrethashes_to_unlockedlocks . get ( secrethash ) if not partial_unlock : partial_unlock = e...
Return the lock correspoding to secrethash or None if the lock is unknown .
27,749
def lock_exists_in_either_channel_side ( channel_state : NettingChannelState , secrethash : SecretHash , ) -> bool : lock = get_lock ( channel_state . our_state , secrethash ) if not lock : lock = get_lock ( channel_state . partner_state , secrethash ) return lock is not None
Check if the lock with secrethash exists in either our state or the partner s state
27,750
def _del_lock ( end_state : NettingChannelEndState , secrethash : SecretHash ) -> None : assert is_lock_pending ( end_state , secrethash ) _del_unclaimed_lock ( end_state , secrethash ) if secrethash in end_state . secrethashes_to_onchain_unlockedlocks : del end_state . secrethashes_to_onchain_unlockedlocks [ secrethas...
Removes the lock from the indexing structures .
27,751
def compute_merkletree_with ( merkletree : MerkleTreeState , lockhash : LockHash , ) -> Optional [ MerkleTreeState ] : result = None leaves = merkletree . layers [ LEAVES ] if lockhash not in leaves : leaves = list ( leaves ) leaves . append ( Keccak256 ( lockhash ) ) result = MerkleTreeState ( compute_layers ( leaves ...
Register the given lockhash with the existing merkle tree .
27,752
def register_offchain_secret ( channel_state : NettingChannelState , secret : Secret , secrethash : SecretHash , ) -> None : our_state = channel_state . our_state partner_state = channel_state . partner_state register_secret_endstate ( our_state , secret , secrethash ) register_secret_endstate ( partner_state , secret ...
This will register the secret and set the lock to the unlocked stated .
27,753
def register_onchain_secret ( channel_state : NettingChannelState , secret : Secret , secrethash : SecretHash , secret_reveal_block_number : BlockNumber , delete_lock : bool = True , ) -> None : our_state = channel_state . our_state partner_state = channel_state . partner_state register_onchain_secret_endstate ( our_st...
This will register the onchain secret and set the lock to the unlocked stated .
27,754
def handle_receive_lockedtransfer ( channel_state : NettingChannelState , mediated_transfer : LockedTransferSignedState , ) -> EventsOrError : events : List [ Event ] is_valid , msg , merkletree = is_valid_lockedtransfer ( mediated_transfer , channel_state , channel_state . partner_state , channel_state . our_state , )...
Register the latest known transfer .
27,755
def get ( self , block = True , timeout = None ) : value = self . _queue . get ( block , timeout ) if self . _queue . empty ( ) : self . clear ( ) return value
Removes and returns an item from the queue .
27,756
def copy ( self ) : copy = self . _queue . copy ( ) result = list ( ) while not copy . empty ( ) : result . append ( copy . get_nowait ( ) ) return result
Copies the current queue items .
27,757
def get_best_routes_internal ( chain_state : ChainState , token_network_id : TokenNetworkID , from_address : InitiatorAddress , to_address : TargetAddress , amount : int , previous_address : Optional [ Address ] , ) -> List [ RouteState ] : available_routes = list ( ) token_network = views . get_token_network_by_identi...
Returns a list of channels that can be used to make a transfer .
27,758
def get_joined_members ( self , force_resync = False ) -> List [ User ] : if force_resync : response = self . client . api . get_room_members ( self . room_id ) for event in response [ 'chunk' ] : if event [ 'content' ] [ 'membership' ] == 'join' : user_id = event [ "state_key" ] if user_id not in self . _members : sel...
Return a list of members of this room .
27,759
def update_aliases ( self ) : changed = False try : response = self . client . api . get_room_state ( self . room_id ) except MatrixRequestError : return False for chunk in response : content = chunk . get ( 'content' ) if content : if 'aliases' in content : aliases = content [ 'aliases' ] if aliases != self . aliases ...
Get aliases information from room state
27,760
def stop_listener_thread ( self ) : self . should_listen = False if self . sync_thread : self . sync_thread . kill ( ) self . sync_thread . get ( ) if self . _handle_thread is not None : self . _handle_thread . get ( ) self . sync_thread = None self . _handle_thread = None
Kills sync_thread greenlet before joining it
27,761
def typing ( self , room : Room , timeout : int = 5000 ) : path = f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}' return self . api . _send ( 'PUT' , path , { 'typing' : True , 'timeout' : timeout } )
Send typing event directly to api
27,762
def _mkroom ( self , room_id : str ) -> Room : if room_id not in self . rooms : self . rooms [ room_id ] = Room ( self , room_id ) room = self . rooms [ room_id ] if not room . canonical_alias : room . update_aliases ( ) return room
Uses a geventified Room subclass
27,763
def set_sync_limit ( self , limit : int ) -> Optional [ int ] : try : prev_limit = json . loads ( self . sync_filter ) [ 'room' ] [ 'timeline' ] [ 'limit' ] except ( json . JSONDecodeError , KeyError ) : prev_limit = None self . sync_filter = json . dumps ( { 'room' : { 'timeline' : { 'limit' : limit } } } ) return pre...
Sets the events limit per room for sync and return previous limit
27,764
def handle_request_parsing_error ( err , _req , _schema , _err_status_code , _err_headers , ) : abort ( HTTPStatus . BAD_REQUEST , errors = err . messages )
This handles request parsing errors generated for example by schema field validation failing .
27,765
def hexbytes_to_str ( map_ : Dict ) : for k , v in map_ . items ( ) : if isinstance ( v , HexBytes ) : map_ [ k ] = encode_hex ( v )
Converts values that are of type HexBytes to strings .
27,766
def encode_byte_values ( map_ : Dict ) : for k , v in map_ . items ( ) : if isinstance ( v , bytes ) : map_ [ k ] = encode_hex ( v )
Converts values that are of type bytes to strings .
27,767
def normalize_events_list ( old_list ) : new_list = [ ] for _event in old_list : new_event = dict ( _event ) if new_event . get ( 'args' ) : new_event [ 'args' ] = dict ( new_event [ 'args' ] ) encode_byte_values ( new_event [ 'args' ] ) if new_event . get ( 'queue_identifier' ) : del new_event [ 'queue_identifier' ] h...
Internally the event_type key is prefixed with underscore but the API returns an object without that prefix
27,768
def unhandled_exception ( self , exception : Exception ) : log . critical ( 'Unhandled exception when processing endpoint request' , exc_info = True , node = pex ( self . rest_api . raiden_api . address ) , ) self . greenlet . kill ( exception ) return api_error ( [ str ( exception ) ] , HTTPStatus . INTERNAL_SERVER_ER...
Flask . errorhandler when an exception wasn t correctly handled
27,769
def get_connection_managers_info ( self , registry_address : typing . PaymentNetworkID ) : log . debug ( 'Getting connection managers info' , node = pex ( self . raiden_api . address ) , registry_address = to_checksum_address ( registry_address ) , ) connection_managers = dict ( ) for token in self . raiden_api . get_t...
Get a dict whose keys are token addresses and whose values are open channels funds of last request sum of deposits and number of channels
27,770
def setup_network_id_or_exit ( config : Dict [ str , Any ] , given_network_id : int , web3 : Web3 , ) -> Tuple [ int , bool ] : node_network_id = int ( web3 . version . network ) known_given_network_id = given_network_id in ID_TO_NETWORKNAME known_node_network_id = node_network_id in ID_TO_NETWORKNAME if node_network_i...
Takes the given network id and checks it against the connected network
27,771
def setup_environment ( config : Dict [ str , Any ] , environment_type : Environment ) -> None : if environment_type == Environment . PRODUCTION : config [ 'transport' ] [ 'matrix' ] [ 'private_rooms' ] = True config [ 'environment_type' ] = environment_type print ( f'Raiden is running in {environment_type.value.lower(...
Sets the config depending on the environment type
27,772
def setup_contracts_or_exit ( config : Dict [ str , Any ] , network_id : int , ) -> Dict [ str , Any ] : environment_type = config [ 'environment_type' ] not_allowed = ( network_id == 1 and environment_type == Environment . DEVELOPMENT ) if not_allowed : click . secho ( f'The chosen network ({ID_TO_NETWORKNAME[network_...
Sets the contract deployment data depending on the network id and environment type
27,773
def dispatch ( self , state_change : StateChange ) -> List [ Event ] : assert isinstance ( state_change , StateChange ) next_state = deepcopy ( self . current_state ) iteration = self . state_transition ( next_state , state_change , ) assert isinstance ( iteration , TransitionResult ) self . current_state = iteration ....
Apply the state_change in the current machine and return the resulting events .
27,774
def wait_for_newchannel ( raiden : 'RaidenService' , payment_network_id : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , retry_timeout : float , ) -> None : channel_state = views . get_channelstate_for ( views . state_from_raiden ( raiden ) , payment_network_id , token_address , partner_a...
Wait until the channel with partner_address is registered .
27,775
def wait_for_participant_newbalance ( raiden : 'RaidenService' , payment_network_id : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , target_address : Address , target_balance : TokenAmount , retry_timeout : float , ) -> None : if target_address == raiden . address : balance = lambda chann...
Wait until a given channels balance exceeds the target balance .
27,776
def wait_for_payment_balance ( raiden : 'RaidenService' , payment_network_id : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , target_address : Address , target_balance : TokenAmount , retry_timeout : float , ) -> None : def get_balance ( end_state ) : if end_state . balance_proof : return...
Wait until a given channel s balance exceeds the target balance .
27,777
def wait_for_channel_in_states ( raiden : 'RaidenService' , payment_network_id : PaymentNetworkID , token_address : TokenAddress , channel_ids : List [ ChannelID ] , retry_timeout : float , target_states : Sequence [ str ] , ) -> None : chain_state = views . state_from_raiden ( raiden ) token_network = views . get_toke...
Wait until all channels are in target_states .
27,778
def wait_for_close ( raiden : 'RaidenService' , payment_network_id : PaymentNetworkID , token_address : TokenAddress , channel_ids : List [ ChannelID ] , retry_timeout : float , ) -> None : return wait_for_channel_in_states ( raiden = raiden , payment_network_id = payment_network_id , token_address = token_address , ch...
Wait until all channels are closed .
27,779
def wait_for_healthy ( raiden : 'RaidenService' , node_address : Address , retry_timeout : float , ) -> None : network_statuses = views . get_networkstatuses ( views . state_from_raiden ( raiden ) , ) while network_statuses . get ( node_address ) != NODE_NETWORK_REACHABLE : gevent . sleep ( retry_timeout ) network_stat...
Wait until node_address becomes healthy .
27,780
def wait_for_transfer_success ( raiden : 'RaidenService' , payment_identifier : PaymentID , amount : PaymentAmount , retry_timeout : float , ) -> None : found = False while not found : state_events = raiden . wal . storage . get_events ( ) for event in state_events : found = ( isinstance ( event , EventPaymentReceivedS...
Wait until a transfer with a specific identifier and amount is seen in the WAL .
27,781
def poll_all_received_events ( self ) : locked = False try : with Timeout ( 10 ) : locked = self . lock . acquire ( blocking = False ) if not locked : return else : received_transfers = self . api . get_raiden_events_payment_history ( token_address = self . token_address , offset = self . last_poll_offset , ) received_...
This will be triggered once for each echo_node_alarm_callback . It polls all channels for EventPaymentReceivedSuccess events adds all new events to the self . received_transfers queue and respawns self . echo_node_worker if it died .
27,782
def echo_worker ( self ) : log . debug ( 'echo worker' , qsize = self . received_transfers . qsize ( ) ) while self . stop_signal is None : if self . received_transfers . qsize ( ) > 0 : transfer = self . received_transfers . get ( ) if transfer in self . seen_transfers : log . debug ( 'duplicate transfer ignored' , in...
The echo_worker works through the self . received_transfers queue and spawns self . on_transfer greenlets for all not - yet - seen transfers .
27,783
def start ( self ) : if self . greenlet : raise RuntimeError ( f'Greenlet {self.greenlet!r} already started' ) pristine = ( not self . greenlet . dead and tuple ( self . greenlet . args ) == tuple ( self . args ) and self . greenlet . kwargs == self . kwargs ) if not pristine : self . greenlet = Greenlet ( self . _run ...
Synchronously start task
27,784
def on_error ( self , subtask : Greenlet ) : log . error ( 'Runnable subtask died!' , this = self , running = bool ( self ) , subtask = subtask , exc = subtask . exception , ) if not self . greenlet : return self . greenlet . kill ( subtask . exception )
Default callback for substasks link_exception
27,785
def join_global_room ( client : GMatrixClient , name : str , servers : Sequence [ str ] = ( ) ) -> Room : our_server_name = urlparse ( client . api . base_url ) . netloc assert our_server_name , 'Invalid client\'s homeserver url' servers = [ our_server_name ] + [ urlparse ( s ) . netloc for s in servers if urlparse ( s...
Join or create a global public room with given name
27,786
def login_or_register ( client : GMatrixClient , signer : Signer , prev_user_id : str = None , prev_access_token : str = None , ) -> User : server_url = client . api . base_url server_name = urlparse ( server_url ) . netloc base_username = to_normalized_address ( signer . address ) _match_user = re . match ( f'^@{re.es...
Login to a Raiden matrix server with password and displayname proof - of - keys
27,787
def validate_userid_signature ( user : User ) -> Optional [ Address ] : match = USERID_RE . match ( user . user_id ) if not match : return None encoded_address = match . group ( 1 ) address : Address = to_canonical_address ( encoded_address ) try : displayname = user . get_display_name ( ) recovered = recover ( data = ...
Validate a userId format and signature on displayName and return its address
27,788
def sort_servers_closest ( servers : Sequence [ str ] ) -> Sequence [ Tuple [ str , float ] ] : if not { urlparse ( url ) . scheme for url in servers } . issubset ( { 'http' , 'https' } ) : raise TransportError ( 'Invalid server urls' ) get_rtt_jobs = set ( gevent . spawn ( lambda url : ( url , get_http_rtt ( url ) ) ,...
Sorts a list of servers by http round - trip time
27,789
def make_client ( servers : Sequence [ str ] , * args , ** kwargs ) -> GMatrixClient : if len ( servers ) > 1 : sorted_servers = [ server_url for ( server_url , _ ) in sort_servers_closest ( servers ) ] log . info ( 'Automatically selecting matrix homeserver based on RTT' , sorted_servers = sorted_servers , ) elif len ...
Given a list of possible servers chooses the closest available and create a GMatrixClient
27,790
def add_userid_for_address ( self , address : Address , user_id : str ) : self . _address_to_userids [ address ] . add ( user_id )
Add a user_id for the given address .
27,791
def add_userids_for_address ( self , address : Address , user_ids : Iterable [ str ] ) : self . _address_to_userids [ address ] . update ( user_ids )
Add multiple user_ids for the given address .
27,792
def get_userids_for_address ( self , address : Address ) -> Set [ str ] : if not self . is_address_known ( address ) : return set ( ) return self . _address_to_userids [ address ]
Return all known user ids for the given address .
27,793
def get_userid_presence ( self , user_id : str ) -> UserPresence : return self . _userid_to_presence . get ( user_id , UserPresence . UNKNOWN )
Return the current presence state of user_id .
27,794
def get_address_reachability ( self , address : Address ) -> AddressReachability : return self . _address_to_reachability . get ( address , AddressReachability . UNKNOWN )
Return the current reachability state for address .
27,795
def force_user_presence ( self , user : User , presence : UserPresence ) : self . _userid_to_presence [ user . user_id ] = presence
Forcibly set the user presence to presence .
27,796
def refresh_address_presence ( self , address ) : composite_presence = { self . _fetch_user_presence ( uid ) for uid in self . _address_to_userids [ address ] } new_presence = UserPresence . UNKNOWN for presence in UserPresence . __members__ . values ( ) : if presence in composite_presence : new_presence = presence bre...
Update synthesized address presence state from cached user presence states .
27,797
def _presence_listener ( self , event : Dict [ str , Any ] ) : if self . _stop_event . ready ( ) : return user_id = event [ 'sender' ] if event [ 'type' ] != 'm.presence' or user_id == self . _user_id : return user = self . _get_user ( user_id ) user . displayname = event [ 'content' ] . get ( 'displayname' ) or user ....
Update cached user presence state from Matrix presence events .
27,798
def check_version ( current_version : str ) : app_version = parse_version ( current_version ) while True : try : _do_check_version ( app_version ) except requests . exceptions . HTTPError as herr : click . secho ( 'Error while checking for version' , fg = 'red' ) print ( herr ) except ValueError as verr : click . secho...
Check periodically for a new release
27,799
def check_gas_reserve ( raiden ) : while True : has_enough_balance , estimated_required_balance = gas_reserve . has_enough_gas_reserve ( raiden , channels_to_open = 1 , ) estimated_required_balance_eth = Web3 . fromWei ( estimated_required_balance , 'ether' ) if not has_enough_balance : log . info ( 'Missing gas reserv...
Check periodically for gas reserve in the account