def api_raiden_service(monkeypatch, api_test_server, api_test_context, blockchain_services, transport_class, max_unresponsive_time, send_ping_time, reveal_timeout, raiden_udp_ports): blockchain = blockchain_services[0] config = copy.deepcopy(App.default_config) config['port'] = raiden_udp_ports[0] config['host'] = '127.0.0.1' config['privatekey_hex'] = blockchain.private_key.encode('hex') config['send_ping_time'] = send_ping_time config['max_unresponsive_time'] = max_unresponsive_time config['reveal_timeout'] = reveal_timeout raiden_service = RaidenService(blockchain, blockchain.private_key, transport_class, Discovery(), config) monkeypatch.setattr(raiden_service.api, 'get_channel_list', api_test_context.query_channels) monkeypatch.setattr(raiden_service.api, 'get_tokens_list', api_test_context.query_tokens) monkeypatch.setattr(raiden_service.api, 'open', api_test_context.open_channel) monkeypatch.setattr(raiden_service.api, 'deposit', api_test_context.deposit) monkeypatch.setattr(raiden_service.api, 'close', api_test_context.close) monkeypatch.setattr(raiden_service.api, 'settle', api_test_context.settle) monkeypatch.setattr(raiden_service.api, 'get_channel', api_test_context.get_channel) # also make sure that the test server's raiden_api uses this mock # raiden service monkeypatch.setattr(api_test_server, 'raiden_api', raiden_service.api) return raiden_service
def __init__(self, config, chain, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery if config.get('socket'): transport = transport_class( None, None, socket=config['socket'], ) else: transport = transport_class( config['host'], config['port'], ) transport.throttle_policy = TokenBucket( config['protocol']['throttle_capacity'], config['protocol']['throttle_fill_rate']) self.raiden = RaidenService( chain, decode_hex(config['privatekey_hex']), transport, discovery, config, ) self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__(self, config, chain, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery if config.get('socket'): transport = transport_class( None, None, socket=config['socket'], ) else: transport = transport_class( config['host'], config['port'], ) transport.throttle_policy = TokenBucket( config['protocol']['throttle_capacity'], config['protocol']['throttle_fill_rate']) self.raiden = RaidenService( chain, decode_hex(config['privatekey_hex']), transport, discovery, config, ) self.start_console = self.config['console']
def __init__(self, config, chain, default_registry, transport, discovery=None): register_error_handler(greenlet_error_handler) self.config = config self.discovery = discovery try: self.raiden = RaidenService( chain, default_registry, unhexlify(config['privatekey_hex']), transport, config, discovery, ) except filelock.Timeout: pubkey = address_encoder( privatekey_to_address(unhexlify(self.config['privatekey_hex'])) ) print( f'FATAL: Another Raiden instance already running for account {pubkey} on ' f'network id {chain.network_id}' ) sys.exit(1) self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__( self, config: Dict, chain: BlockChainService, default_registry: Registry, default_secret_registry: SecretRegistry, transport, discovery: Discovery = None, ): self.config = config self.discovery = discovery try: self.raiden = RaidenService( chain, default_registry, default_secret_registry, unhexlify(config['privatekey_hex']), transport, config, discovery, ) except filelock.Timeout: pubkey = to_normalized_address( privatekey_to_address(unhexlify( self.config['privatekey_hex'])), ) print( f'FATAL: Another Raiden instance already running for account {pubkey} on ' f'network id {chain.network_id}', ) sys.exit(1) self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__(self, config, chain, default_registry, discovery, transport): self.config = config self.discovery = discovery try: self.raiden = RaidenService( chain, default_registry, unhexlify(config['privatekey_hex']), transport, discovery, config, ) except filelock.Timeout: pubkey = privatekey_to_address( unhexlify(self.config['privatekey_hex'])) print( 'FATAL: Another Raiden instance already running for account 0x%s' % hexlify(str(pubkey))) sys.exit(1) self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__( self, config: RaidenConfig, rpc_client: JSONRPCClient, proxy_manager: ProxyManager, query_start_block: BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, default_service_registry: Optional[ServiceRegistry], default_user_deposit: Optional[UserDeposit], default_one_to_n_address: Optional[OneToNAddress], default_msc_address: Optional[MonitoringServiceAddress], transport: MatrixTransport, raiden_event_handler: EventHandler, message_handler: MessageHandler, routing_mode: RoutingMode, api_server: APIServer = None, ): raiden = RaidenService( rpc_client=rpc_client, proxy_manager=proxy_manager, query_start_block=query_start_block, default_registry=default_registry, default_secret_registry=default_secret_registry, default_service_registry=default_service_registry, default_user_deposit=default_user_deposit, default_one_to_n_address=default_one_to_n_address, default_msc_address=default_msc_address, transport=transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, routing_mode=routing_mode, config=config, api_server=api_server, ) # check that the settlement timeout fits the limits of the contract settlement_timeout_min = default_registry.settlement_timeout_min(BLOCK_ID_LATEST) settlement_timeout_max = default_registry.settlement_timeout_max(BLOCK_ID_LATEST) invalid_settle_timeout = ( config.settle_timeout < settlement_timeout_min or config.settle_timeout > settlement_timeout_max or config.settle_timeout < config.reveal_timeout * 2 ) if invalid_settle_timeout: raise InvalidSettleTimeout( ( "Settlement timeout for Registry contract {} must " "be in range [{}, {}], is {}" ).format( to_checksum_address(default_registry.address), settlement_timeout_min, settlement_timeout_max, config.settle_timeout, ) ) self.config = config self.raiden = raiden
def __init__( self, config: typing.Dict, chain: BlockChainService, query_start_block: typing.BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, transport, raiden_event_handler, message_handler, discovery: Discovery = None, ): raiden = RaidenService( chain=chain, query_start_block=query_start_block, default_registry=default_registry, default_secret_registry=default_secret_registry, private_key_bin=unhexlify(config['privatekey_hex']), transport=transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, config=config, discovery=discovery, ) # Check if files with older versions of the DB exist, emit a warning db_base_path = os.path.dirname(config['database_path']) if older_db_files_exist(db_base_path): log.warning( 'Older versions of the database exist in ' f'{db_base_path}. Since a newer breaking version is introduced, ' 'it is advised that you leave all token networks before upgrading and ' 'then proceed with the upgrade.', ) # check that the settlement timeout fits the limits of the contract invalid_settle_timeout = ( config['settle_timeout'] < default_registry.settlement_timeout_min() or config['settle_timeout'] > default_registry.settlement_timeout_max() or config['settle_timeout'] < config['reveal_timeout'] * 2) if invalid_settle_timeout: raise InvalidSettleTimeout( ('Settlement timeout for Registry contract {} must ' 'be in range [{}, {}], is {}').format( to_checksum_address(default_registry.address), default_registry.settlement_timeout_min(), default_registry.settlement_timeout_max(), config['settle_timeout'], ), ) self.config = config self.discovery = discovery self.raiden = raiden self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__( self, config: typing.Dict, rpc_client: JSONRPCClient, proxy_manager: ProxyManager, query_start_block: typing.BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, default_service_registry: typing.Optional[ServiceRegistry], default_one_to_n_address: typing.Optional[Address], default_msc_address: Address, transport: MatrixTransport, raiden_event_handler: EventHandler, message_handler: MessageHandler, routing_mode: RoutingMode, user_deposit: UserDeposit = None, ): raiden = RaidenService( rpc_client=rpc_client, proxy_manager=proxy_manager, query_start_block=query_start_block, default_registry=default_registry, default_one_to_n_address=default_one_to_n_address, default_secret_registry=default_secret_registry, default_service_registry=default_service_registry, default_msc_address=default_msc_address, transport=transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, routing_mode=routing_mode, config=config, user_deposit=user_deposit, ) # check that the settlement timeout fits the limits of the contract settlement_timeout_min = default_registry.settlement_timeout_min("latest") settlement_timeout_max = default_registry.settlement_timeout_max("latest") invalid_settle_timeout = ( config["settle_timeout"] < settlement_timeout_min or config["settle_timeout"] > settlement_timeout_max or config["settle_timeout"] < config["reveal_timeout"] * 2 ) if invalid_settle_timeout: raise InvalidSettleTimeout( ( "Settlement timeout for Registry contract {} must " "be in range [{}, {}], is {}" ).format( to_checksum_address(default_registry.address), settlement_timeout_min, settlement_timeout_max, config["settle_timeout"], ) ) self.config = config self.user_deposit = user_deposit self.raiden = raiden
def __init__(self, config, chain, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery self.transport = transport_class(config['host'], config['port']) self.raiden = RaidenService(chain, config['privkey'], self.transport, discovery, config) discovery.register(self.raiden.address, self.transport.host, self.transport.port)
def test_recovery_blockchain_events(raiden_network: List[RaidenService], restart_node, token_addresses, network_wait): """Close one of the two raiden apps that have a channel between them, have the counterparty close the channel and then make sure the restarted app sees the change """ app0, app1 = raiden_network token_address = token_addresses[0] app0.stop() new_transport = MatrixTransport(config=app0.config.transport, environment=app0.config.environment_type) app1_api = RaidenAPI(app1) app1_api.channel_close( registry_address=app0.default_registry.address, token_address=token_address, partner_address=app0.address, ) app0.stop() raiden_event_handler = RaidenEventHandler() message_handler = MessageHandler() app0_restart = RaidenService( config=app0.config, rpc_client=app0.rpc_client, proxy_manager=app0.proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle( app0.default_registry, app0.default_secret_registry, ), services_bundle=app0.default_services_bundle, transport=new_transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, routing_mode=RoutingMode.PRIVATE, ) del app0 # from here on the app0_restart should be used restart_node(app0_restart) wal = app0_restart.wal assert wal # wait for the nodes' healthcheck to update the network statuses waiting.wait_for_healthy(app0_restart, app1.address, network_wait) waiting.wait_for_healthy(app1, app0_restart.address, network_wait) restarted_state_changes = wal.storage.get_statechanges_by_range( RANGE_ALL_STATE_CHANGES) assert search_for_item(restarted_state_changes, ContractReceiveChannelClosed, {})
def __init__( self, config: typing.Dict, chain: BlockChainService, query_start_block: typing.BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, default_service_registry: typing.Optional[ServiceRegistry], transport, raiden_event_handler, message_handler, discovery: Discovery = None, user_deposit: UserDeposit = None, ): raiden = RaidenService( chain=chain, query_start_block=query_start_block, default_registry=default_registry, default_secret_registry=default_secret_registry, default_service_registry=default_service_registry, transport=transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, config=config, discovery=discovery, user_deposit=user_deposit, ) # check that the settlement timeout fits the limits of the contract invalid_settle_timeout = ( config['settle_timeout'] < default_registry.settlement_timeout_min() or config['settle_timeout'] > default_registry.settlement_timeout_max() or config['settle_timeout'] < config['reveal_timeout'] * 2 ) if invalid_settle_timeout: raise InvalidSettleTimeout( ( 'Settlement timeout for Registry contract {} must ' 'be in range [{}, {}], is {}' ).format( to_checksum_address(default_registry.address), default_registry.settlement_timeout_min(), default_registry.settlement_timeout_max(), config['settle_timeout'], ), ) self.config = config self.discovery = discovery self.user_deposit = user_deposit self.raiden = raiden self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__(self, config, chain, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery self.transport = transport_class(config['host'], config['port']) self.raiden = RaidenService( chain, decode_hex(config['privatekey_hex']), self.transport, discovery, config, ) self.services = {'raiden': self.raiden} self.start_console = True
def api_raiden_service(monkeypatch, api_backend, api_test_context, blockchain_services, transport_class, reveal_timeout, raiden_udp_ports, tmpdir): blockchain = blockchain_services[0] config = copy.deepcopy(App.DEFAULT_CONFIG) config['port'] = raiden_udp_ports[0] config['host'] = '127.0.0.1' config['external_ip'] = '127.0.0.1' config['external_port'] = raiden_udp_ports[0] config['privatekey_hex'] = blockchain.private_key.encode('hex') config['reveal_timeout'] = reveal_timeout config['database_path'] = os.path.join(tmpdir.strpath, 'database.db') raiden_service = RaidenService( blockchain, blockchain.private_key, transport_class(config['host'], config['port']), Discovery(), config) api = RaidenAPI(raiden_service) monkeypatch.setattr(api, 'get_channel_list', api_test_context.query_channels) monkeypatch.setattr(api, 'get_tokens_list', api_test_context.query_tokens) monkeypatch.setattr(api, 'open', api_test_context.open_channel) monkeypatch.setattr(api, 'deposit', api_test_context.deposit) monkeypatch.setattr(api, 'close', api_test_context.close) monkeypatch.setattr(api, 'settle', api_test_context.settle) monkeypatch.setattr(api, 'get_channel', api_test_context.get_channel) monkeypatch.setattr(api, 'get_network_events', api_test_context.get_network_events) monkeypatch.setattr(api, 'get_token_network_events', api_test_context.get_token_network_events) monkeypatch.setattr(api, 'get_channel_events', api_test_context.get_channel_events) monkeypatch.setattr(api, 'transfer', api_test_context.transfer) monkeypatch.setattr(api, 'token_swap', api_test_context.token_swap) monkeypatch.setattr(api, 'expect_token_swap', api_test_context.expect_token_swap) monkeypatch.setattr(api, 'connect_token_network', api_test_context.connect) monkeypatch.setattr(api, 'leave_token_network', api_test_context.leave) monkeypatch.setattr(api, 'get_connection_manager_funds', api_test_context.get_connection_manager_funds) monkeypatch.setattr(api, 'get_connection_managers_list', api_test_context.get_connection_managers_list) monkeypatch.setattr(api, 'register_token', api_test_context.register_token) monkeypatch.setattr(api, 'manager_address_if_token_registered', api_test_context.manager_address_if_token_registered) # also make sure that the test server's raiden_api uses this mock # raiden service _, raiden_api = api_backend monkeypatch.setattr(raiden_api, 'raiden_api', api) return raiden_service
def __init__( self, config: Dict, chain: BlockChainService, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, transport, discovery: Discovery = None, ): self.config = config self.discovery = discovery # check that the settlement timeout fits the limits of the contract invalid_timeout = (config['settle_timeout'] < default_registry.settlement_timeout_min() or config['settle_timeout'] > default_registry.settlement_timeout_max()) if invalid_timeout: raise InvalidSettleTimeout( ('Settlement timeout for Registry contract {} must ' 'be in range [{}, {}], is {}').format( to_checksum_address(default_registry.address), default_registry.settlement_timeout_min(), default_registry.settlement_timeout_max(), config['settle_timeout'], ), ) try: self.raiden = RaidenService( chain, default_registry, default_secret_registry, unhexlify(config['privatekey_hex']), transport, config, discovery, ) except filelock.Timeout: pubkey = to_normalized_address( privatekey_to_address(unhexlify( self.config['privatekey_hex'])), ) print( f'FATAL: Another Raiden instance already running for account {pubkey} on ' f'network id {chain.network_id}', ) sys.exit(1) self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def api_raiden_service( monkeypatch, api_backend, api_test_context, blockchain_services, transport_class, max_unresponsive_time, send_ping_time, reveal_timeout, raiden_udp_ports, tmpdir): blockchain = blockchain_services[0] config = copy.deepcopy(App.default_config) config['port'] = raiden_udp_ports[0] config['host'] = '127.0.0.1' config['privatekey_hex'] = blockchain.private_key.encode('hex') config['send_ping_time'] = send_ping_time config['max_unresponsive_time'] = max_unresponsive_time config['reveal_timeout'] = reveal_timeout config['database_path'] = os.path.join(tmpdir.strpath, 'database.db') raiden_service = RaidenService( blockchain, blockchain.private_key, transport_class, Discovery(), config ) api = RaidenAPI(raiden_service) monkeypatch.setattr(api, 'get_channel_list', api_test_context.query_channels) monkeypatch.setattr(api, 'get_tokens_list', api_test_context.query_tokens) monkeypatch.setattr(api, 'open', api_test_context.open_channel) monkeypatch.setattr(api, 'deposit', api_test_context.deposit) monkeypatch.setattr(api, 'close', api_test_context.close) monkeypatch.setattr(api, 'settle', api_test_context.settle) monkeypatch.setattr(api, 'get_channel', api_test_context.get_channel) monkeypatch.setattr(api, 'get_network_events', api_test_context.get_network_events) monkeypatch.setattr(api, 'get_token_network_events', api_test_context.get_token_network_events) monkeypatch.setattr(api, 'get_channel_events', api_test_context.get_channel_events) monkeypatch.setattr(api, 'transfer', api_test_context.transfer) monkeypatch.setattr(api, 'token_swap', api_test_context.token_swap) monkeypatch.setattr(api, 'expect_token_swap', api_test_context.expect_token_swap) # also make sure that the test server's raiden_api uses this mock # raiden service _, raiden_api = api_backend monkeypatch.setattr(raiden_api, 'raiden_api', api) return raiden_service
def __init__(self, config, chain, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery self.transport = transport_class(config['host'], config['port']) self.transport.throttle_policy = TokenBucket( config['throttle_capacity'], config['throttle_fill_rate']) self.raiden = RaidenService( chain, decode_hex(config['privatekey_hex']), self.transport, discovery, config, ) self.services = {'raiden': self.raiden} self.start_console = True
def __init__( self, config: typing.Dict, chain: BlockChainService, query_start_block: typing.BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, transport, discovery: Discovery = None, ): self.config = config self.discovery = discovery # check that the settlement timeout fits the limits of the contract invalid_timeout = (config['settle_timeout'] < default_registry.settlement_timeout_min() or config['settle_timeout'] > default_registry.settlement_timeout_max()) if invalid_timeout: raise InvalidSettleTimeout( ('Settlement timeout for Registry contract {} must ' 'be in range [{}, {}], is {}').format( to_checksum_address(default_registry.address), default_registry.settlement_timeout_min(), default_registry.settlement_timeout_max(), config['settle_timeout'], ), ) try: self.raiden = RaidenService( chain=chain, query_start_block=query_start_block, default_registry=default_registry, default_secret_registry=default_secret_registry, private_key_bin=unhexlify(config['privatekey_hex']), transport=transport, config=config, discovery=discovery, ) except filelock.Timeout: pubkey = to_normalized_address( privatekey_to_address(unhexlify( self.config['privatekey_hex'])), ) print( f'FATAL: Another Raiden instance already running for account {pubkey} on ' f'network id {chain.network_id}', ) sys.exit(1)
def __init__(self, config, chain, default_registry, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery if config.get('socket'): transport = transport_class( None, None, socket=config['socket'], ) else: transport = transport_class( config['host'], config['port'], ) transport.throttle_policy = TokenBucket( config['protocol']['throttle_capacity'], config['protocol']['throttle_fill_rate']) try: self.raiden = RaidenService( chain, default_registry, decode_hex(config['privatekey_hex']), transport, discovery, config, ) except filelock.Timeout: pubkey = privatekey_to_address( decode_hex(self.config['privatekey_hex'])) print( 'FATAL: Another Raiden instance already running for account 0x%s' % str(pubkey).encode('hex')) sys.exit(1) self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def __init__( self, config: typing.Dict, chain: BlockChainService, query_start_block: typing.BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, transport, discovery: Discovery = None, ): raiden = RaidenService( chain=chain, query_start_block=query_start_block, default_registry=default_registry, default_secret_registry=default_secret_registry, private_key_bin=unhexlify(config['privatekey_hex']), transport=transport, config=config, discovery=discovery, ) # check that the settlement timeout fits the limits of the contract invalid_timeout = (config['settle_timeout'] < default_registry.settlement_timeout_min() or config['settle_timeout'] > default_registry.settlement_timeout_max()) if invalid_timeout: raise InvalidSettleTimeout( ('Settlement timeout for Registry contract {} must ' 'be in range [{}, {}], is {}').format( to_checksum_address(default_registry.address), default_registry.settlement_timeout_min(), default_registry.settlement_timeout_max(), config['settle_timeout'], ), ) self.config = config self.discovery = discovery self.raiden = raiden self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()
def test_initialize_wal_throws_when_lock_is_taken(raiden_network: List[RaidenService]): """Raiden must throw a proper exception when the filelock of the DB is already taken. Test for https://github.com/raiden-network/raiden/issues/6079 """ app0, _ = raiden_network # Start a second app, that should throw an expection, as the lock is already taken app0_2 = RaidenService( config=app0.config, rpc_client=app0.rpc_client, proxy_manager=app0.proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle(app0.default_registry, app0.default_secret_registry), services_bundle=app0.default_services_bundle, transport=app0.transport, raiden_event_handler=RaidenEventHandler(), message_handler=MessageHandler(), routing_mode=RoutingMode.PRIVATE, ) with pytest.raises(RaidenUnrecoverableError): app0_2.start()
def test_broadcast_messages_must_be_sent_before_protocol_messages_on_restarts( raiden_network: List[RaidenService], restart_node, number_of_nodes, token_addresses, network_wait, ): """Raiden must broadcast the latest known balance proof on restarts. Regression test for: https://github.com/raiden-network/raiden/issues/3656. """ app0, app1 = raiden_network app0.config.services.monitoring_enabled = True # Send a transfer to make sure the state has a balance proof to broadcast token_address = token_addresses[0] amount = PaymentAmount(10) payment_id = PaymentID(23) transfer( initiator_app=app1, target_app=app0, token_address=token_address, amount=amount, identifier=payment_id, timeout=network_wait * number_of_nodes, ) app0.stop() transport = MatrixTransport( config=app0.config.transport, environment=app0.config.environment_type ) transport.send_async = Mock() # type: ignore transport._send_raw = Mock() # type: ignore old_start_transport = transport.start # Asserts the balance proofs are broadcasted before protocol messages def start_transport(*args, **kwargs): # Before restart the transport's broadcast queue should be initialized # There should be 3 messages in the queue: # - A `MonitorRequest` to the MS # - A `PFSCapacityUpdate` # - A `PFSFeeUpdate` queue_copy = transport._broadcast_queue.copy() queued_messages = list() for _ in range(len(transport._broadcast_queue)): queued_messages.append(queue_copy.get()) def num_matching_queued_messages(room: str, message_type: Type) -> int: return len( [ item for item in queued_messages if item[0] == room and type(item[1]) == message_type ] ) assert num_matching_queued_messages(MONITORING_BROADCASTING_ROOM, RequestMonitoring) == 1 assert num_matching_queued_messages(PATH_FINDING_BROADCASTING_ROOM, PFSFeeUpdate) == 1 assert num_matching_queued_messages(PATH_FINDING_BROADCASTING_ROOM, PFSCapacityUpdate) == 1 old_start_transport(*args, **kwargs) transport.start = start_transport # type: ignore app0_restart = RaidenService( config=app0.config, rpc_client=app0.rpc_client, proxy_manager=app0.proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle(app0.default_registry, app0.default_secret_registry), services_bundle=app0.default_services_bundle, transport=transport, raiden_event_handler=RaidenEventHandler(), message_handler=MessageHandler(), routing_mode=RoutingMode.PFS, # not private mode, otherwise no PFS updates are queued ) restart_node(app0_restart)
def run_raiden_service( address: Address, keystore_path: str, gas_price: Callable, eth_rpc_endpoint: str, user_deposit_contract_address: Optional[UserDepositAddress], api_address: Endpoint, rpc: bool, rpccorsdomain: str, sync_check: bool, console: bool, password_file: TextIO, web_ui: bool, datadir: Optional[str], matrix_server: str, chain_id: ChainID, environment_type: Environment, unrecoverable_error_should_crash: bool, pathfinding_service_address: str, pathfinding_max_paths: int, enable_monitoring: bool, resolver_endpoint: str, default_reveal_timeout: BlockTimeout, default_settle_timeout: BlockTimeout, routing_mode: RoutingMode, flat_fee: Tuple[Tuple[TokenAddress, FeeAmount], ...], proportional_fee: Tuple[Tuple[TokenAddress, ProportionalFeeAmount], ...], proportional_imbalance_fee: Tuple[Tuple[TokenAddress, ProportionalFeeAmount], ...], blockchain_query_interval: float, cap_mediation_fees: bool, ** kwargs: Any, # FIXME: not used here, but still receives stuff in smoketest ) -> RaidenService: # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument token_network_registry_deployed_at: Optional[BlockNumber] smart_contracts_start_at: BlockNumber if datadir is None: datadir = os.path.join(os.path.expanduser("~"), ".raiden") account_manager = AccountManager(keystore_path) web3 = Web3(HTTPProvider(rpc_normalized_endpoint(eth_rpc_endpoint))) check_sql_version() check_ethereum_has_accounts(account_manager) check_ethereum_chain_id(chain_id, web3) address, privatekey = get_account_and_private_key(account_manager, address, password_file) api_host, api_port = split_endpoint(api_address) if not api_port: api_port = DEFAULT_HTTP_SERVER_PORT domain_list = [] if rpccorsdomain: if "," in rpccorsdomain: for domain in rpccorsdomain.split(","): domain_list.append(str(domain)) else: domain_list.append(str(rpccorsdomain)) # Set up config fee_config = prepare_mediation_fee_config( cli_token_to_flat_fee=flat_fee, cli_token_to_proportional_fee=proportional_fee, cli_token_to_proportional_imbalance_fee=proportional_imbalance_fee, cli_cap_mediation_fees=cap_mediation_fees, ) rest_api_config = RestApiConfig( rest_api_enabled=rpc, web_ui_enabled=rpc and web_ui, cors_domain_list=domain_list, eth_rpc_endpoint=eth_rpc_endpoint, host=api_host, port=api_port, ) config = RaidenConfig( chain_id=chain_id, environment_type=environment_type, reveal_timeout=default_reveal_timeout, settle_timeout=default_settle_timeout, console=console, mediation_fees=fee_config, unrecoverable_error_should_crash=unrecoverable_error_should_crash, resolver_endpoint=resolver_endpoint, rest_api=rest_api_config, ) config.blockchain.query_interval = blockchain_query_interval config.services.monitoring_enabled = enable_monitoring config.services.pathfinding_max_paths = pathfinding_max_paths config.transport.server = matrix_server contracts = load_deployed_contracts_data(config, chain_id) rpc_client = JSONRPCClient( web3=web3, privkey=privatekey, gas_price_strategy=gas_price, block_num_confirmations=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS, ) token_network_registry_deployed_at = None if "TokenNetworkRegistry" in contracts: token_network_registry_deployed_at = BlockNumber( contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["block_number"]) if token_network_registry_deployed_at is None: smart_contracts_start_at = get_smart_contracts_start_at(chain_id) else: smart_contracts_start_at = token_network_registry_deployed_at proxy_manager = ProxyManager( rpc_client=rpc_client, contract_manager=ContractManager(config.contracts_path), metadata=ProxyManagerMetadata( token_network_registry_deployed_at= token_network_registry_deployed_at, filters_start_at=smart_contracts_start_at, ), ) api_server: Optional[APIServer] = None if config.rest_api.rest_api_enabled: api_server = start_api_server(rpc_client=rpc_client, config=config.rest_api, eth_rpc_endpoint=eth_rpc_endpoint) if sync_check: check_synced(rpc_client) # The user has the option to launch Raiden with a custom # user deposit contract address. This can be used to load # the addresses for the rest of the deployed contracts. # The steps done here make sure that if a UDC address is provided, # the address has to be valid and all the connected contracts # are configured properly. # If a UDC address was not provided, Raiden would fall back # to using the ones deployed and provided by the raiden-contracts package. if user_deposit_contract_address is not None: if not is_address(user_deposit_contract_address): raise RaidenError("The user deposit address is invalid") deployed_addresses = load_deployment_addresses_from_udc( proxy_manager=proxy_manager, user_deposit_address=user_deposit_contract_address, block_identifier=BLOCK_ID_LATEST, ) else: deployed_addresses = load_deployment_addresses_from_contracts( contracts=contracts) # Load the available matrix servers when no matrix server is given # The list is used in a PFS check if config.transport.server == MATRIX_AUTO_SELECT_SERVER: fetch_available_matrix_servers(config.transport, environment_type) raiden_bundle = raiden_bundle_from_contracts_deployment( proxy_manager=proxy_manager, token_network_registry_address=deployed_addresses. token_network_registry_address, secret_registry_address=deployed_addresses.secret_registry_address, ) services_bundle = services_bundle_from_contracts_deployment( config=config, deployed_addresses=deployed_addresses, proxy_manager=proxy_manager, routing_mode=routing_mode, pathfinding_service_address=pathfinding_service_address, enable_monitoring=enable_monitoring, ) check_ethereum_confirmed_block_is_not_pruned( jsonrpc_client=rpc_client, secret_registry=raiden_bundle.secret_registry, confirmation_blocks=config.blockchain.confirmation_blocks, ) database_path = Path( os.path.join( datadir, f"node_{pex(address)}", f"netid_{chain_id}", f"network_{pex(raiden_bundle.token_network_registry.address)}", f"v{RAIDEN_DB_VERSION}_log.db", )) config.database_path = database_path print(f"Raiden is running in {environment_type.value.lower()} mode") print("\nYou are connected to the '{}' network and the DB path is: {}". format(ID_TO_CHAINNAME.get(chain_id, chain_id), database_path)) matrix_transport = setup_matrix(config.transport, config.services, environment_type, routing_mode) event_handler: EventHandler = RaidenEventHandler() # User should be told how to set fees, if using default fee settings log.debug("Fee Settings", fee_settings=fee_config) has_default_fees = (len(fee_config.token_to_flat_fee) == 0 and len(fee_config.token_to_proportional_fee) == 0 and len(fee_config.token_to_proportional_imbalance_fee) == 0) if has_default_fees: click.secho( "Default fee settings are used. " "If you want use Raiden with mediation fees - flat, proportional and imbalance fees - " "see https://raiden-network.readthedocs.io/en/latest/overview_and_guide.html#firing-it-up", # noqa: E501 fg="yellow", ) # Only send feedback when PFS is used if routing_mode == RoutingMode.PFS: event_handler = PFSFeedbackEventHandler(event_handler) message_handler = MessageHandler() raiden_service = RaidenService( config=config, rpc_client=rpc_client, proxy_manager=proxy_manager, query_start_block=smart_contracts_start_at, raiden_bundle=raiden_bundle, services_bundle=services_bundle, transport=matrix_transport, raiden_event_handler=event_handler, message_handler=message_handler, routing_mode=routing_mode, api_server=api_server, ) raiden_service.start() if config.pfs_config is not None: # This has to be done down here since there is a circular dependency # between the PFS and Transport pfs_broadcast_room_key = make_room_alias( config.chain_id, PATH_FINDING_BROADCASTING_ROOM) check_pfs_transport_configuration( pfs_info=config.pfs_config.info, pfs_was_autoselected=( pathfinding_service_address == MATRIX_AUTO_SELECT_SERVER), transport_pfs_broadcast_room_id=matrix_transport. broadcast_rooms[pfs_broadcast_room_key].room_id, matrix_server_url=matrix_transport.server_url, matrix_server_was_autoselected=( config.transport.server == MATRIX_AUTO_SELECT_SERVER), ) return raiden_service
def test_recovery_unhappy_case( raiden_network: List[RaidenService], restart_node, number_of_nodes, deposit, token_addresses, network_wait, retry_timeout, ): app0, app1, app2 = raiden_network token_address = token_addresses[0] chain_state = views.state_from_raiden(app0) token_network_registry_address = app0.default_registry.address token_network_address = views.get_token_network_address_by_token_address( chain_state, token_network_registry_address, token_address) # make a few transfers from app0 to app2 amount = PaymentAmount(1) spent_amount = deposit - 2 for identifier in range(spent_amount): transfer( initiator_app=app0, target_app=app2, token_address=token_address, amount=amount, identifier=PaymentID(identifier), timeout=network_wait * number_of_nodes, routes=[[app0.address, app1.address, app2.address]], ) app0.stop() new_transport = MatrixTransport(config=app0.config.transport, environment=app0.config.environment_type) app0.stop() RaidenAPI(app1).channel_close(app1.default_registry.address, token_address, app0.address) channel01 = views.get_channelstate_for( views.state_from_raiden(app1), app1.default_registry.address, token_address, app0.address, ) assert channel01 waiting.wait_for_settle( app1, app1.default_registry.address, token_address, [channel01.identifier], retry_timeout, ) raiden_event_handler = RaidenEventHandler() message_handler = MessageHandler() app0_restart = RaidenService( config=app0.config, rpc_client=app0.rpc_client, proxy_manager=app0.proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle(app0.default_registry, app0.default_secret_registry), services_bundle=app0.default_services_bundle, transport=new_transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, routing_mode=RoutingMode.PRIVATE, ) del app0 # from here on the app0_restart should be used restart_node(app0_restart) wal = app0_restart.wal assert wal state_changes = wal.storage.get_statechanges_by_range( RANGE_ALL_STATE_CHANGES) assert search_for_item( state_changes, ContractReceiveChannelSettled, { "token_network_address": token_network_address, "channel_identifier": channel01.identifier, }, )
def test_payment_statuses_are_restored( # pylint: disable=unused-argument raiden_network: List[RaidenService], restart_node: RestartNode, token_addresses: List[TokenAddress], network_wait: float, ): """Test that when the Raiden is restarted, the dictionary of `targets_to_identifiers_to_statuses` is populated before the transport is started. This should happen because if a client gets restarted during a transfer cycle, once restarted, the client will proceed with the cycle until the transfer is successfully sent. However, the dictionary `targets_to_identifiers_to_statuses` will not contain the payment identifiers that were originally registered when the previous client started the transfers. Related issue: https://github.com/raiden-network/raiden/issues/3432 """ app0, app1 = raiden_network token_address = token_addresses[0] chain_state = views.state_from_raiden(app0) token_network_registry_address = app0.default_registry.address token_network_address = views.get_token_network_address_by_token_address( chain_state, token_network_registry_address, token_address) assert token_network_address target_address = TargetAddress(app1.address) # make a few transfers from app0 to app1 amount = PaymentAmount(1) spent_amount = TokenAmount(7) for identifier in range(spent_amount): # Make sure the transfer is not completed secret = make_secret(identifier) assert isinstance(app0.raiden_event_handler, HoldRaidenEventHandler) # for mypy app0.raiden_event_handler.hold(SendSecretReveal, {"secret": secret}) identifier = identifier + 1 payment_status = app0.mediated_transfer_async( token_network_address=token_network_address, amount=amount, target=target_address, identifier=PaymentID(identifier), secret=secret, ) assert payment_status.payment_identifier == identifier app0_restart = RaidenService( config=app0.config, rpc_client=app0.rpc_client, proxy_manager=app0.proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle( app0.default_registry, app0.default_secret_registry, ), services_bundle=app0.default_services_bundle, transport=MatrixTransport(config=app0.config.transport, environment=app0.config.environment_type), raiden_event_handler=RaidenEventHandler(), message_handler=MessageHandler(), routing_mode=RoutingMode.PRIVATE, ) app0.stop() del app0 # from here on the app0_restart should be used # stop app1 to make sure that we don't complete the transfers before our checks app1.stop() restart_node(app0_restart) # Check that the payment statuses were restored properly after restart for identifier in range(spent_amount): identifier = PaymentID(identifier + 1) mapping = app0_restart.targets_to_identifiers_to_statuses status = mapping[target_address][identifier] assert status.amount == 1 assert status.payment_identifier == identifier assert status.token_network_address == token_network_address restart_node(app1) # now that our checks are done start app1 again with watch_for_unlock_failures(*raiden_network): waiting.wait_for_healthy(app0_restart, app1.address, network_wait) with gevent.Timeout(60): waiting.wait_for_payment_balance( raiden=app1, token_network_registry_address=token_network_registry_address, token_address=token_address, partner_address=app0_restart.address, target_address=Address(target_address), target_balance=spent_amount, retry_timeout=network_wait, ) # Check that payments are completed after both nodes come online after restart for identifier in range(spent_amount): assert raiden_events_search_for_item( app0_restart, EventPaymentSentSuccess, { "identifier": identifier + 1, "amount": 1 }, )
def create_apps( chain_id: ChainID, contracts_path: Path, blockchain_services: List[ProxyManager], token_network_registry_address: TokenNetworkRegistryAddress, one_to_n_address: Optional[OneToNAddress], secret_registry_address: SecretRegistryAddress, service_registry_address: Optional[ServiceRegistryAddress], user_deposit_address: Optional[UserDepositAddress], monitoring_service_contract_address: MonitoringServiceAddress, reveal_timeout: BlockTimeout, settle_timeout: BlockTimeout, database_basedir: str, retry_interval_initial: float, retry_interval_max: float, retries_before_backoff: int, environment_type: Environment, unrecoverable_error_should_crash: bool, local_matrix_url: Optional[ParsedURL], broadcast_rooms: List[str], routing_mode: RoutingMode, blockchain_query_interval: float, resolver_ports: List[Optional[int]], enable_rest_api: bool, port_generator: Iterator[Port], capabilities_config: CapabilitiesConfig, ) -> List[RaidenService]: """ Create the apps.""" # pylint: disable=too-many-locals apps = [] for idx, proxy_manager in enumerate(blockchain_services): database_path = database_from_privatekey(base_dir=database_basedir, app_number=idx) assert len(resolver_ports) > idx resolver_port = resolver_ports[idx] config = RaidenConfig( chain_id=chain_id, environment_type=environment_type, unrecoverable_error_should_crash=unrecoverable_error_should_crash, reveal_timeout=reveal_timeout, settle_timeout=settle_timeout, contracts_path=contracts_path, database_path=database_path, blockchain=BlockchainConfig( confirmation_blocks=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS, query_interval=blockchain_query_interval, ), mediation_fees=MediationFeeConfig(), services=ServiceConfig(monitoring_enabled=False), rest_api=RestApiConfig(rest_api_enabled=enable_rest_api, host=Host("localhost"), port=next(port_generator)), console=False, transport_type="matrix", ) config.transport.capabilities_config = capabilities_config if local_matrix_url is not None: config.transport = MatrixTransportConfig( broadcast_rooms=broadcast_rooms, retries_before_backoff=retries_before_backoff, retry_interval_initial=retry_interval_initial, retry_interval_max=retry_interval_max, server=local_matrix_url, available_servers=[], capabilities_config=capabilities_config, ) assert config.transport.capabilities_config is not None if resolver_port is not None: config.resolver_endpoint = f"http://localhost:{resolver_port}" registry = proxy_manager.token_network_registry( token_network_registry_address, block_identifier=BLOCK_ID_LATEST) secret_registry = proxy_manager.secret_registry( secret_registry_address, block_identifier=BLOCK_ID_LATEST) services_bundle = None if user_deposit_address: user_deposit = proxy_manager.user_deposit( user_deposit_address, block_identifier=BLOCK_ID_LATEST) service_registry: Optional[ServiceRegistry] = None if service_registry_address: service_registry = proxy_manager.service_registry( service_registry_address, block_identifier=BLOCK_ID_LATEST) monitoring_service = None if monitoring_service_contract_address: monitoring_service = proxy_manager.monitoring_service( monitoring_service_contract_address, block_identifier=BLOCK_ID_LATEST) one_to_n = None if one_to_n_address: one_to_n = proxy_manager.one_to_n( one_to_n_address, block_identifier=BLOCK_ID_LATEST) services_bundle = ServicesBundle(user_deposit, service_registry, monitoring_service, one_to_n) # Use `TestMatrixTransport` that saves sent messages for assertions in tests assert config.transport.capabilities_config is not None transport = TestMatrixTransport(config=config.transport, environment=environment_type) raiden_event_handler = RaidenEventHandler() hold_handler = HoldRaidenEventHandler(raiden_event_handler) message_handler = WaitForMessage() api_server = None if enable_rest_api: api_server = start_api_server(rpc_client=proxy_manager.client, config=config.rest_api, eth_rpc_endpoint="bla") app = RaidenService( config=config, rpc_client=proxy_manager.client, proxy_manager=proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle(registry, secret_registry), services_bundle=services_bundle, transport=transport, raiden_event_handler=hold_handler, message_handler=message_handler, routing_mode=routing_mode, api_server=api_server, ) apps.append(app) return apps
def test_send_queued_messages_after_restart( # pylint: disable=unused-argument raiden_network: List[RaidenService], restart_node: RestartNode, deposit: TokenAmount, token_addresses: List[TokenAddress], network_wait: float, ): """Test re-sending of undelivered messages on node restart""" app0, app1 = raiden_network token_address = token_addresses[0] chain_state = views.state_from_raiden(app0) token_network_registry_address = app0.default_registry.address token_network_address = views.get_token_network_address_by_token_address( chain_state, token_network_registry_address, token_address) assert token_network_address number_of_transfers = 7 amount_per_transfer = PaymentAmount(1) total_transferred_amount = TokenAmount(amount_per_transfer * number_of_transfers) # Make sure none of the transfers will be sent before the restart transfers = [] for secret_seed in range(number_of_transfers): secret = make_secret(secret_seed) secrethash = sha256_secrethash(secret) transfers.append((create_default_identifier(), amount_per_transfer, secret, secrethash)) assert isinstance(app0.raiden_event_handler, HoldRaidenEventHandler) # for mypy app0.raiden_event_handler.hold( SendLockedTransfer, {"transfer": { "lock": { "secrethash": secrethash } }}) for identifier, amount, secret, _ in transfers: app0.mediated_transfer_async( token_network_address=token_network_address, amount=amount, target=TargetAddress(app1.address), identifier=identifier, secret=secret, ) app0.stop() # Restart the app. The pending transfers must be processed. new_transport = MatrixTransport(config=app0.config.transport, environment=app0.config.environment_type) raiden_event_handler = RaidenEventHandler() message_handler = MessageHandler() app0_restart = RaidenService( config=app0.config, rpc_client=app0.rpc_client, proxy_manager=app0.proxy_manager, query_start_block=BlockNumber(0), raiden_bundle=RaidenBundle( app0.default_registry, app0.default_secret_registry, ), services_bundle=app0.default_services_bundle, transport=new_transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, routing_mode=RoutingMode.PRIVATE, ) del app0 restart_node(app0_restart) # XXX: There is no synchronization among the app and the test, so it is # possible between `start` and the check below that some of the transfers # have completed, making it flaky. # # Make sure the transfers are in the queue and fail otherwise. chain_state = views.state_from_raiden(app0_restart) for _, _, _, secrethash in transfers: msg = "The secrethashes of the pending transfers must be in the queue after a restart." assert secrethash in chain_state.payment_mapping.secrethashes_to_task, msg timeout = block_offset_timeout( app1, "Timeout waiting for balance update of app0") with watch_for_unlock_failures(*raiden_network), timeout: waiting.wait_for_payment_balance( raiden=app0_restart, token_network_registry_address=token_network_registry_address, token_address=token_address, partner_address=app1.address, target_address=app1.address, target_balance=total_transferred_amount, retry_timeout=network_wait, ) timeout.exception_to_throw = ValueError( "Timeout waiting for balance update of app1") waiting.wait_for_payment_balance( raiden=app1, token_network_registry_address=token_network_registry_address, token_address=token_address, partner_address=app0_restart.address, target_address=app1.address, target_balance=total_transferred_amount, retry_timeout=network_wait, ) assert_synced_channel_state( token_network_address, app0_restart, Balance(deposit - total_transferred_amount), [], app1, Balance(deposit + total_transferred_amount), [], ) new_transport.stop()
def __init__( self, config: typing.Dict, chain: BlockChainService, query_start_block: typing.BlockNumber, default_registry: TokenNetworkRegistry, default_secret_registry: SecretRegistry, transport, raiden_event_handler, message_handler, discovery: Discovery = None, ): raiden = RaidenService( chain=chain, query_start_block=query_start_block, default_registry=default_registry, default_secret_registry=default_secret_registry, private_key_bin=decode_hex(config['privatekey_hex']), transport=transport, raiden_event_handler=raiden_event_handler, message_handler=message_handler, config=config, discovery=discovery, ) # Check if files with older versions of the DB exist, emit a warning db_base_path = os.path.dirname(config['database_path']) old_version_path = older_db_file(db_base_path) if old_version_path: old_version_file = os.path.basename(old_version_path) raise RuntimeError( f'A database file for a previous version of Raiden exists ' f'{old_version_path}. Because the new version of Raiden ' f'introduces changes which break compatibility with the old ' f'database, a new database is necessary. The new database ' f'file will be created automatically for you, but as a side effect all ' f'previous data will be unavailable. The only way to proceed ' f'without the risk of losing funds is to leave all token networks ' f'and *make a backup* of the existing database. Please, *after* all the ' f'existing channels have been settled, make sure to make a backup by ' f'renaming {old_version_file} to {old_version_file}_backup. Then the new ' f'version of Raiden can be used.', ) # check that the settlement timeout fits the limits of the contract invalid_settle_timeout = ( config['settle_timeout'] < default_registry.settlement_timeout_min() or config['settle_timeout'] > default_registry.settlement_timeout_max() or config['settle_timeout'] < config['reveal_timeout'] * 2) if invalid_settle_timeout: raise InvalidSettleTimeout( ('Settlement timeout for Registry contract {} must ' 'be in range [{}, {}], is {}').format( to_checksum_address(default_registry.address), default_registry.settlement_timeout_min(), default_registry.settlement_timeout_max(), config['settle_timeout'], ), ) self.config = config self.discovery = discovery self.raiden = raiden self.start_console = self.config['console'] # raiden.ui.console:Console assumes that a services # attribute is available for auto-registration self.services = dict()