Ejemplo n.º 1
0
    def open_channel(self,
                     token_address,
                     partner_address,
                     settle_timeout=None,
                     reveal_timeout=None):

        if settle_timeout < NETTINGCHANNEL_SETTLE_TIMEOUT_MIN:
            raise InvalidSettleTimeout(
                'Configured minimum `settle_timeout` is {} blocks.'.format(
                    NETTINGCHANNEL_SETTLE_TIMEOUT_MIN))

        if not isaddress(token_address):
            raise InvalidAddress(
                'Expected binary address format for token in channel open')

        if not isaddress(partner_address):
            raise InvalidAddress(
                'Expected binary address format for partner in channel open')

        reveal_value = reveal_timeout if reveal_timeout is not None else self.reveal_timeout
        channel = self.make_channel(token_address=token_address,
                                    partner_address=partner_address,
                                    settle_timeout=settle_timeout,
                                    reveal_timeout=reveal_value)
        self.channels.append(channel)
        return channel
    def open_channel(
            self,
            token_address,
            partner_address,
            settle_timeout=None,
            reveal_timeout=None):

        invalid_timeout = (
            settle_timeout < NETTINGCHANNEL_SETTLE_TIMEOUT_MIN or
            settle_timeout > NETTINGCHANNEL_SETTLE_TIMEOUT_MAX
        )
        if invalid_timeout:
            raise InvalidSettleTimeout('`settle_timeout` should be in range [{}, {}].'.format(
                NETTINGCHANNEL_SETTLE_TIMEOUT_MIN, NETTINGCHANNEL_SETTLE_TIMEOUT_MAX
            ))

        if not isaddress(token_address):
            raise InvalidAddress('Expected binary address format for token in channel open')

        if not isaddress(partner_address):
            raise InvalidAddress('Expected binary address format for partner in channel open')

        reveal_value = reveal_timeout if reveal_timeout is not None else self.reveal_timeout
        channel = self.make_channel(
            token_address=token_address,
            partner_address=partner_address,
            settle_timeout=settle_timeout,
            reveal_timeout=reveal_value
        )
        self.channels.append(channel)
        return channel
Ejemplo n.º 3
0
    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
Ejemplo n.º 4
0
    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()
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
    def channel_open(
        self,
        registry_address,
        token_address,
        partner_address,
        settle_timeout=None,
        reveal_timeout=None,
        poll_timeout=DEFAULT_POLL_TIMEOUT,
        retry_timeout=DEFAULT_RETRY_TIMEOUT,
    ):
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if reveal_timeout is None:
            reveal_timeout = self.raiden.config['reveal_timeout']

        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout <= reveal_timeout:
            raise InvalidSettleTimeout(
                'reveal_timeout can not be larger-or-equal to settle_timeout',
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress(
                'Expected binary address format for registry in channel open')

        if not is_binary_address(token_address):
            raise InvalidAddress(
                'Expected binary address format for token in channel open')

        if not is_binary_address(partner_address):
            raise InvalidAddress(
                'Expected binary address format for partner in channel open')

        registry = self.raiden.chain.token_network_registry(registry_address)
        token_network = registry.token_network_by_token(token_address)
        channel_identifier = token_network.new_netting_channel(
            partner_address,
            settle_timeout,
        )

        msg = 'After {} seconds the channel was not properly created.'.format(
            poll_timeout, )

        with gevent.Timeout(poll_timeout, EthNodeCommunicationError(msg)):
            waiting.wait_for_newchannel(
                self.raiden,
                registry_address,
                token_address,
                partner_address,
                retry_timeout,
            )

        return channel_identifier
Ejemplo n.º 7
0
    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()
Ejemplo n.º 8
0
    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()
Ejemplo n.º 9
0
    def can_open_channel(registry_address: PaymentNetworkID,
                         token_address: TokenAddress, creator_address: Address,
                         partner_address: Address,
                         settle_timeout: BlockTimeout, raiden) -> TokenNetwork:

        if settle_timeout < raiden.config["reveal_timeout"] * 2:
            raise InvalidSettleTimeout(
                "settle_timeout can not be smaller than double the reveal_timeout"
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress(
                "Expected binary address format for registry in channel open")

        if not is_binary_address(token_address):
            raise InvalidAddress(
                "Expected binary address format for token in channel open")

        if not is_binary_address(partner_address):
            raise InvalidAddress(
                "Expected binary address format for partner in channel open")

        if not is_binary_address(creator_address):
            raise InvalidAddress(
                "Expected binary address format for creator in channel open")

        chain_state = views.state_from_raiden(raiden)

        channel_state = views.get_channelstate_for(
            chain_state=chain_state,
            payment_network_id=registry_address,
            creator_address=creator_address,
            token_address=token_address,
            partner_address=partner_address,
        )
        if channel_state:
            raise DuplicatedChannelError(
                "Channel with given partner address already exists")

        registry: TokenNetworkRegistry = raiden.chain.token_network_registry(
            registry_address)
        token_network = raiden.chain.token_network(
            registry.get_token_network(token_address))

        if token_network is None:
            raise TokenNotRegistered(
                "Token network for token %s does not exist" %
                to_checksum_address(token_address))
        return token_network
Ejemplo n.º 10
0
    def channel_open(self,
                     token_address,
                     partner_address,
                     settle_timeout=None,
                     reveal_timeout=None,
                     poll_timeout=DEFAULT_POLL_TIMEOUT):
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if reveal_timeout is None:
            reveal_timeout = self.raiden.config['reveal_timeout']

        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout <= reveal_timeout:
            raise InvalidSettleTimeout(
                'reveal_timeout can not be larger-or-equal to settle_timeout')

        if not isaddress(token_address):
            raise InvalidAddress(
                'Expected binary address format for token in channel open')

        if not isaddress(partner_address):
            raise InvalidAddress(
                'Expected binary address format for partner in channel open')

        channel_manager = self.raiden.default_registry.manager_by_token(
            token_address)
        netcontract_address = channel_manager.new_netting_channel(
            partner_address,
            settle_timeout,
        )

        msg = 'After {} seconds the channel was not properly created.'.format(
            poll_timeout)

        registry_address = self.raiden.default_registry.address
        with gevent.Timeout(poll_timeout, EthNodeCommunicationError(msg)):
            waiting.wait_for_newchannel(
                self.raiden,
                registry_address,
                token_address,
                partner_address,
                self.raiden.alarm.wait_time,
            )

        return netcontract_address
Ejemplo n.º 11
0
    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)
Ejemplo n.º 12
0
    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()
Ejemplo n.º 13
0
    def open(self,
             token_address,
             partner_address,
             settle_timeout=None,
             reveal_timeout=None):
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if reveal_timeout is None:
            reveal_timeout = self.raiden.config['reveal_timeout']

        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout <= reveal_timeout:
            raise InvalidSettleTimeout(
                'reveal_timeout can not be larger-or-equal to settle_timeout')

        if not isaddress(token_address):
            raise InvalidAddress(
                'Expected binary address format for token in channel open')

        if not isaddress(partner_address):
            raise InvalidAddress(
                'Expected binary address format for partner in channel open')

        channel_manager = self.raiden.default_registry.manager_by_token(
            token_address)
        assert token_address in self.raiden.token_to_channelgraph

        netcontract_address = channel_manager.new_netting_channel(
            self.raiden.address,
            partner_address,
            settle_timeout,
        )
        while netcontract_address not in self.raiden.chain.address_to_nettingchannel:
            gevent.sleep(self.raiden.alarm.wait_time)

        graph = self.raiden.token_to_channelgraph[token_address]
        while partner_address not in graph.partneraddress_to_channel:
            gevent.sleep(self.raiden.alarm.wait_time)
        channel = graph.partneraddress_to_channel[partner_address]
        return channel
Ejemplo n.º 14
0
    def open(
            self,
            token_address,
            partner_address,
            settle_timeout=None,
            reveal_timeout=None):
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if reveal_timeout is None:
            reveal_timeout = self.raiden.config['reveal_timeout']

        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout < self.raiden.config['settle_timeout']:
            raise InvalidSettleTimeout('Configured minimum `settle_timeout` is {} blocks.'.format(
                self.raiden.config['settle_timeout']
            ))

        if not isaddress(token_address):
            raise InvalidAddress('Expected binary address format for token in channel open')

        if not isaddress(partner_address):
            raise InvalidAddress('Expected binary address format for partner in channel open')

        channel_manager = self.raiden.chain.manager_by_token(token_address)
        assert token_address in self.raiden.channelgraphs

        netcontract_address = channel_manager.new_netting_channel(
            self.raiden.address,
            partner_address,
            settle_timeout,
        )
        while netcontract_address not in self.raiden.chain.address_contract:
            gevent.sleep(self.raiden.alarm.wait_time)

        graph = self.raiden.channelgraphs[token_address]
        while partner_address not in graph.partneraddress_channel:
            gevent.sleep(self.raiden.alarm.wait_time)
        channel = graph.partneraddress_channel[partner_address]
        return channel
Ejemplo n.º 15
0
    def channel_open(
            self,
            registry_address: typing.PaymentNetworkID,
            token_address: typing.TokenAddress,
            partner_address: typing.Address,
            settle_timeout: typing.BlockTimeout = None,
            reveal_timeout: typing.BlockTimeout = None,
            retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
    ) -> typing.ChannelID:
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if reveal_timeout is None:
            reveal_timeout = self.raiden.config['reveal_timeout']

        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout <= reveal_timeout:
            raise InvalidSettleTimeout(
                'reveal_timeout can not be larger-or-equal to settle_timeout',
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress('Expected binary address format for registry in channel open')

        if not is_binary_address(token_address):
            raise InvalidAddress('Expected binary address format for token in channel open')

        if not is_binary_address(partner_address):
            raise InvalidAddress('Expected binary address format for partner in channel open')

        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state,
            registry_address,
            token_address,
            partner_address,
        )

        if channel_state:
            raise DuplicatedChannelError('Channel with given partner address already exists')

        registry = self.raiden.chain.token_network_registry(registry_address)
        token_network_address = registry.get_token_network(token_address)

        if token_network_address is None:
            raise TokenNotRegistered(
                'Token network for token %s does not exist' % to_checksum_address(token_address),
            )

        token_network = self.raiden.chain.token_network(
            registry.get_token_network(token_address),
        )

        try:
            token_network.new_netting_channel(
                partner_address,
                settle_timeout,
            )
        except DuplicatedChannelError:
            log.info('partner opened channel first')

        waiting.wait_for_newchannel(
            self.raiden,
            registry_address,
            token_address,
            partner_address,
            retry_timeout,
        )
        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state,
            registry_address,
            token_address,
            partner_address,
        )

        return channel_state.identifier
Ejemplo n.º 16
0
    def new_netting_channel(
        self,
        partner: typing.Address,
        settle_timeout: int,
    ) -> typing.ChannelID:
        """ Creates a new channel in the TokenNetwork contract.

        Args:
            partner: The peer to open the channel with.
            settle_timeout: The settle timout to use for this channel.

        Returns:
            The ChannelID of the new netting channel.
        """
        if not is_binary_address(partner):
            raise InvalidAddress(
                'Expected binary address format for channel partner')

        invalid_timeout = (settle_timeout < self.settlement_timeout_min()
                           or settle_timeout > self.settlement_timeout_max())
        if invalid_timeout:
            raise InvalidSettleTimeout(
                'settle_timeout must be in range [{}, {}], is {}'.format(
                    self.settlement_timeout_min(),
                    self.settlement_timeout_max(),
                    settle_timeout,
                ))

        if self.node_address == partner:
            raise SamePeerAddress(
                'The other peer must not have the same address as the client.')

        log_details = {
            'peer1': pex(self.node_address),
            'peer2': pex(partner),
        }
        log.debug('new_netting_channel called', **log_details)

        # Prevent concurrent attempts to open a channel with the same token and
        # partner address.
        if partner not in self.open_channel_transactions:
            new_open_channel_transaction = AsyncResult()
            self.open_channel_transactions[
                partner] = new_open_channel_transaction

            try:
                transaction_hash = self._new_netting_channel(
                    partner, settle_timeout)
            except Exception as e:
                log.critical('new_netting_channel failed', **log_details)
                new_open_channel_transaction.set_exception(e)
                raise
            else:
                new_open_channel_transaction.set(transaction_hash)
            finally:
                self.open_channel_transactions.pop(partner, None)
        else:
            # All other concurrent threads should block on the result of opening this channel
            self.open_channel_transactions[partner].get()

        channel_created = self.channel_exists_and_not_settled(
            self.node_address, partner)
        if channel_created is False:
            log.critical('new_netting_channel failed', **log_details)
            raise RaidenUnrecoverableError('creating new channel failed')

        channel_identifier = self.detail_channel(self.node_address,
                                                 partner).channel_identifier
        log_details['channel_identifier'] = channel_identifier
        log.info('new_netting_channel succesful', **log_details)

        return channel_identifier
Ejemplo n.º 17
0
    def new_netting_channel(self, other_peer: Address, settle_timeout: int) -> Address:
        """ Creates and deploys a new netting channel contract.

        Args:
            other_peer: The peer to open the channel with.
            settle_timeout: The settle timout to use for this channel.

        Returns:
            The address of the new netting channel.
        """
        if not isaddress(other_peer):
            raise ValueError('The other_peer must be a valid address')

        invalid_timeout = (
            settle_timeout < NETTINGCHANNEL_SETTLE_TIMEOUT_MIN or
            settle_timeout > NETTINGCHANNEL_SETTLE_TIMEOUT_MAX
        )
        if invalid_timeout:
            raise InvalidSettleTimeout('settle_timeout must be in range [{}, {}]'.format(
                NETTINGCHANNEL_SETTLE_TIMEOUT_MIN, NETTINGCHANNEL_SETTLE_TIMEOUT_MAX
            ))

        local_address = privatekey_to_address(self.client.privkey)
        if local_address == other_peer:
            raise SamePeerAddress('The other peer must not have the same address as the client.')

        # Prevent concurrent attempts to open a channel with the same token and
        # partner address.
        if other_peer not in self.open_channel_transactions:
            new_open_channel_transaction = AsyncResult()
            self.open_channel_transactions[other_peer] = new_open_channel_transaction

            try:
                transaction_hash = self._new_netting_channel(other_peer, settle_timeout)
            except Exception as e:
                new_open_channel_transaction.set_exception(e)
                raise
            else:
                new_open_channel_transaction.set(transaction_hash)
            finally:
                self.open_channel_transactions.pop(other_peer, None)
        else:
            # All other concurrent threads should block on the result of opening this channel
            transaction_hash = self.open_channel_transactions[other_peer].get()

        netting_channel_results_encoded = self.proxy.call(
            'getChannelWith',
            other_peer,
        )

        # address is at index 0
        netting_channel_address_encoded = netting_channel_results_encoded

        if not netting_channel_address_encoded:
            log.error(
                'netting_channel_address failed',
                peer1=pex(local_address),
                peer2=pex(other_peer)
            )
            raise RuntimeError('netting_channel_address failed')

        netting_channel_address_bin = address_decoder(netting_channel_address_encoded)

        log.info(
            'new_netting_channel called',
            peer1=pex(local_address),
            peer2=pex(other_peer),
            netting_channel=pex(netting_channel_address_bin),
        )

        return netting_channel_address_bin
Ejemplo n.º 18
0
    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()
Ejemplo n.º 19
0
    def new_netting_channel(
            self,
            partner: typing.Address,
            settle_timeout: int,
    ) -> typing.ChannelID:
        """ Creates a new channel in the TokenNetwork contract.

        Args:
            partner: The peer to open the channel with.
            settle_timeout: The settle timout to use for this channel.

        Returns:
            The address of the new netting channel.
        """
        if not is_binary_address(partner):
            raise InvalidAddress('Expected binary address format for channel partner')

        invalid_timeout = (
            settle_timeout < NETTINGCHANNEL_SETTLE_TIMEOUT_MIN or
            settle_timeout > NETTINGCHANNEL_SETTLE_TIMEOUT_MAX
        )
        if invalid_timeout:
            raise InvalidSettleTimeout('settle_timeout must be in range [{}, {}]'.format(
                NETTINGCHANNEL_SETTLE_TIMEOUT_MIN, NETTINGCHANNEL_SETTLE_TIMEOUT_MAX,
            ))

        if self.node_address == partner:
            raise SamePeerAddress('The other peer must not have the same address as the client.')

        # Prevent concurrent attempts to open a channel with the same token and
        # partner address.
        if partner not in self.open_channel_transactions:
            new_open_channel_transaction = AsyncResult()
            self.open_channel_transactions[partner] = new_open_channel_transaction

            try:
                transaction_hash = self._new_netting_channel(partner, settle_timeout)
            except Exception as e:
                new_open_channel_transaction.set_exception(e)
                raise
            else:
                new_open_channel_transaction.set(transaction_hash)
            finally:
                self.open_channel_transactions.pop(partner, None)
        else:
            # All other concurrent threads should block on the result of opening this channel
            transaction_hash = self.open_channel_transactions[partner].get()

        channel_created = self.channel_exists(partner)
        if channel_created is False:
            log.error(
                'creating new channel failed',
                peer1=pex(self.node_address),
                peer2=pex(partner),
            )
            raise RuntimeError('creating new channel failed')

        channel_identifier = self.detail_channel(partner)['channel_identifier']

        log.info(
            'new_netting_channel called',
            peer1=pex(self.node_address),
            peer2=pex(partner),
            channel_identifier=channel_identifier,
        )

        return channel_identifier
Ejemplo n.º 20
0
    def channel_open(
        self,
        registry_address: TokenNetworkRegistryAddress,
        token_address: TokenAddress,
        partner_address: Address,
        settle_timeout: BlockTimeout = None,
        reveal_timeout: BlockTimeout = None,
        retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
    ) -> ChannelID:
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if settle_timeout is None:
            settle_timeout = self.raiden.config.settle_timeout

        if reveal_timeout is None:
            reveal_timeout = self.raiden.config.reveal_timeout

        if reveal_timeout <= 0:
            raise InvalidRevealTimeout(
                "reveal_timeout should be larger than zero")

        if settle_timeout < reveal_timeout * 2:
            raise InvalidSettleTimeout(
                "`settle_timeout` can not be smaller than double the "
                "`reveal_timeout`.\n "
                "\n "
                "The setting `reveal_timeout` determines the maximum number of "
                "blocks it should take a transaction to be mined when the "
                "blockchain is under congestion. This setting determines the "
                "when a node must go on-chain to register a secret, and it is "
                "therefore the lower bound of the lock expiration. The "
                "`settle_timeout` determines when a channel can be settled "
                "on-chain, for this operation to be safe all locks must have "
                "been resolved, for this reason the `settle_timeout` has to be "
                "larger than `reveal_timeout`.")

        if not is_binary_address(registry_address):
            raise InvalidBinaryAddress(
                "Expected binary address format for registry in channel open")

        if not is_binary_address(token_address):
            raise InvalidBinaryAddress(
                "Expected binary address format for token in channel open")

        if not is_binary_address(partner_address):
            raise InvalidBinaryAddress(
                "Expected binary address format for partner in channel open")

        confirmed_block_identifier = views.get_confirmed_blockhash(self.raiden)
        registry = self.raiden.proxy_manager.token_network_registry(
            registry_address, block_identifier=confirmed_block_identifier)

        settlement_timeout_min = registry.settlement_timeout_min(
            block_identifier=confirmed_block_identifier)
        settlement_timeout_max = registry.settlement_timeout_max(
            block_identifier=confirmed_block_identifier)

        if settle_timeout < settlement_timeout_min:
            raise InvalidSettleTimeout(
                f"Settlement timeout should be at least {settlement_timeout_min}"
            )

        if settle_timeout > settlement_timeout_max:
            raise InvalidSettleTimeout(
                f"Settlement timeout exceeds max of {settlement_timeout_max}")

        token_network_address = registry.get_token_network(
            token_address=token_address,
            block_identifier=confirmed_block_identifier)
        if token_network_address is None:
            raise TokenNotRegistered(
                "Token network for token %s does not exist" %
                to_checksum_address(token_address))

        token_network = self.raiden.proxy_manager.token_network(
            address=token_network_address,
            block_identifier=confirmed_block_identifier)

        safety_deprecation_switch = token_network.safety_deprecation_switch(
            block_identifier=confirmed_block_identifier)

        if safety_deprecation_switch:
            msg = (
                "This token_network has been deprecated. New channels cannot be "
                "open for this network, usage of the newly deployed token "
                "network contract is highly encouraged.")
            raise TokenNetworkDeprecated(msg)

        duplicated_channel = self.is_already_existing_channel(
            token_network_address=token_network_address,
            partner_address=partner_address,
            block_identifier=confirmed_block_identifier,
        )
        if duplicated_channel:
            raise DuplicatedChannelError(
                f"A channel with {to_checksum_address(partner_address)} for token "
                f"{to_checksum_address(token_address)} already exists. "
                f"(At blockhash: {confirmed_block_identifier.hex()})")

        has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(
            self.raiden, channels_to_open=1)

        if not has_enough_reserve:
            raise InsufficientGasReserve(
                "The account balance is below the estimated amount necessary to "
                "finish the lifecycles of all active channels. A balance of at "
                f"least {estimated_required_reserve} wei is required.")

        try:
            token_network.new_netting_channel(
                partner=partner_address,
                settle_timeout=settle_timeout,
                given_block_identifier=confirmed_block_identifier,
            )
        except DuplicatedChannelError:
            log.info("partner opened channel first")
        except RaidenRecoverableError:
            # The channel may have been created in the pending block.
            duplicated_channel = self.is_already_existing_channel(
                token_network_address=token_network_address,
                partner_address=partner_address)
            if duplicated_channel:
                log.info("Channel has already been opened")
            else:
                raise

        waiting.wait_for_newchannel(
            raiden=self.raiden,
            token_network_registry_address=registry_address,
            token_address=token_address,
            partner_address=partner_address,
            retry_timeout=retry_timeout,
        )

        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state=chain_state,
            token_network_registry_address=registry_address,
            token_address=token_address,
            partner_address=partner_address,
        )

        assert channel_state, f"channel {channel_state} is gone"

        self.raiden.set_channel_reveal_timeout(
            canonical_identifier=channel_state.canonical_identifier,
            reveal_timeout=reveal_timeout)

        return channel_state.identifier
Ejemplo n.º 21
0
    def channel_open(
        self,
        registry_address: PaymentNetworkID,
        token_address: TokenAddress,
        partner_address: Address,
        settle_timeout: BlockTimeout = None,
        retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
    ) -> ChannelID:
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if settle_timeout is None:
            settle_timeout = self.raiden.config["settle_timeout"]

        if settle_timeout < self.raiden.config["reveal_timeout"] * 2:
            raise InvalidSettleTimeout(
                "settle_timeout can not be smaller than double the reveal_timeout"
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress("Expected binary address format for registry in channel open")

        if not is_binary_address(token_address):
            raise InvalidAddress("Expected binary address format for token in channel open")

        if not is_binary_address(partner_address):
            raise InvalidAddress("Expected binary address format for partner in channel open")

        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state=chain_state,
            payment_network_id=registry_address,
            token_address=token_address,
            partner_address=partner_address,
        )

        if channel_state:
            raise DuplicatedChannelError("Channel with given partner address already exists")

        registry = self.raiden.chain.token_network_registry(registry_address)
        token_network_address = registry.get_token_network(token_address)

        if token_network_address is None:
            raise TokenNotRegistered(
                "Token network for token %s does not exist" % to_checksum_address(token_address)
            )

        token_network = self.raiden.chain.token_network(registry.get_token_network(token_address))

        with self.raiden.gas_reserve_lock:
            has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(
                self.raiden, channels_to_open=1
            )

            if not has_enough_reserve:
                raise InsufficientGasReserve(
                    (
                        "The account balance is below the estimated amount necessary to "
                        "finish the lifecycles of all active channels. A balance of at "
                        f"least {estimated_required_reserve} wei is required."
                    )
                )

            try:
                token_network.new_netting_channel(
                    partner=partner_address,
                    settle_timeout=settle_timeout,
                    given_block_identifier=views.state_from_raiden(self.raiden).block_hash,
                )
            except DuplicatedChannelError:
                log.info("partner opened channel first")

        waiting.wait_for_newchannel(
            raiden=self.raiden,
            payment_network_id=registry_address,
            token_address=token_address,
            partner_address=partner_address,
            retry_timeout=retry_timeout,
        )
        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state=chain_state,
            payment_network_id=registry_address,
            token_address=token_address,
            partner_address=partner_address,
        )

        assert channel_state, f"channel {channel_state} is gone"

        return channel_state.identifier
Ejemplo n.º 22
0
    def new_netting_channel(self, other_peer: Address,
                            settle_timeout: int) -> Address:
        """ Creates and deploys a new netting channel contract.

        Args:
            other_peer: The peer to open the channel with.
            settle_timeout: The settle timout to use for this channel.

        Returns:
            The address of the new netting channel.
        """
        if not isaddress(other_peer):
            raise ValueError('The other_peer must be a valid address')

        invalid_timeout = (settle_timeout < NETTINGCHANNEL_SETTLE_TIMEOUT_MIN
                           or
                           settle_timeout > NETTINGCHANNEL_SETTLE_TIMEOUT_MAX)
        if invalid_timeout:
            raise InvalidSettleTimeout(
                'settle_timeout must be in range [{}, {}]'.format(
                    NETTINGCHANNEL_SETTLE_TIMEOUT_MIN,
                    NETTINGCHANNEL_SETTLE_TIMEOUT_MAX))

        local_address = privatekey_to_address(self.client.privkey)
        if local_address == other_peer:
            raise SamePeerAddress(
                'The other peer must not have the same address as the client.')

        transaction_hash = estimate_and_transact(
            self.proxy,
            'newChannel',
            other_peer,
            settle_timeout,
        )

        self.client.poll(unhexlify(transaction_hash),
                         timeout=self.poll_timeout)

        if check_transaction_threw(self.client, transaction_hash):
            raise DuplicatedChannelError('Duplicated channel')

        netting_channel_results_encoded = self.proxy.call(
            'getChannelWith',
            other_peer,
        )

        # address is at index 0
        netting_channel_address_encoded = netting_channel_results_encoded

        if not netting_channel_address_encoded:
            log.error('netting_channel_address failed',
                      peer1=pex(local_address),
                      peer2=pex(other_peer))
            raise RuntimeError('netting_channel_address failed')

        netting_channel_address_bin = address_decoder(
            netting_channel_address_encoded)

        if log.isEnabledFor(logging.INFO):
            log.info(
                'new_netting_channel called',
                peer1=pex(local_address),
                peer2=pex(other_peer),
                netting_channel=pex(netting_channel_address_bin),
            )

        return netting_channel_address_bin
Ejemplo n.º 23
0
    def channel_open(
        self,
        registry_address: typing.PaymentNetworkID,
        token_address: typing.TokenAddress,
        partner_address: typing.Address,
        settle_timeout: typing.BlockTimeout = None,
        retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
    ) -> typing.ChannelID:
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout < self.raiden.config['reveal_timeout'] * 2:
            raise InvalidSettleTimeout(
                'settle_timeout can not be smaller than double the reveal_timeout',
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress(
                'Expected binary address format for registry in channel open')

        if not is_binary_address(token_address):
            raise InvalidAddress(
                'Expected binary address format for token in channel open')

        if not is_binary_address(partner_address):
            raise InvalidAddress(
                'Expected binary address format for partner in channel open')

        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state,
            registry_address,
            token_address,
            partner_address,
        )

        if channel_state:
            raise DuplicatedChannelError(
                'Channel with given partner address already exists')

        registry = self.raiden.chain.token_network_registry(registry_address)
        token_network_address = registry.get_token_network(token_address)

        if token_network_address is None:
            raise TokenNotRegistered(
                'Token network for token %s does not exist' %
                to_checksum_address(token_address), )

        token_network = self.raiden.chain.token_network(
            registry.get_token_network(token_address), )

        has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(
            self.raiden,
            channels_to_open=1,
        )

        if not has_enough_reserve:
            raise InsufficientGasReserve((
                'The account balance is below the estimated amount necessary to '
                'finish the lifecycles of all active channels. A balance of at '
                f'least {estimated_required_reserve} wei is required.'))

        try:
            token_network.new_netting_channel(
                partner_address,
                settle_timeout,
            )
        except DuplicatedChannelError:
            log.info('partner opened channel first')

        waiting.wait_for_newchannel(
            self.raiden,
            registry_address,
            token_address,
            partner_address,
            retry_timeout,
        )
        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state,
            registry_address,
            token_address,
            partner_address,
        )

        return channel_state.identifier
Ejemplo n.º 24
0
    def channel_open(
        self,
        registry_address,
        token_address,
        partner_address,
        settle_timeout=None,
        reveal_timeout=None,
        poll_timeout=DEFAULT_POLL_TIMEOUT,
        retry_timeout=DEFAULT_RETRY_TIMEOUT,
    ):
        """ Open a channel with the peer at `partner_address`
        with the given `token_address`.
        """
        if reveal_timeout is None:
            reveal_timeout = self.raiden.config['reveal_timeout']

        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout <= reveal_timeout:
            raise InvalidSettleTimeout(
                'reveal_timeout can not be larger-or-equal to settle_timeout',
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress(
                'Expected binary address format for registry in channel open')

        if not is_binary_address(token_address):
            raise InvalidAddress(
                'Expected binary address format for token in channel open')

        if not is_binary_address(partner_address):
            raise InvalidAddress(
                'Expected binary address format for partner in channel open')

        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state,
            registry_address,
            token_address,
            partner_address,
        )

        if channel_state:
            raise DuplicatedChannelError(
                'Channel with given partner address already exists')

        registry = self.raiden.chain.token_network_registry(registry_address)
        token_network = self.raiden.chain.token_network(
            registry.get_token_network(token_address), )

        try:
            token_network.new_netting_channel(
                partner_address,
                settle_timeout,
            )
        except DuplicatedChannelError:
            log.info('partner opened channel first')

        msg = 'After {} seconds the channel was not properly created.'.format(
            poll_timeout, )

        with gevent.Timeout(poll_timeout, EthNodeCommunicationError(msg)):
            waiting.wait_for_newchannel(
                self.raiden,
                registry_address,
                token_address,
                partner_address,
                retry_timeout,
            )
        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state,
            registry_address,
            token_address,
            partner_address,
        )

        return channel_state.identifier