Ejemplo n.º 1
0
def connect_to_blockchain(
    eth_rpc: URI,
    gas_price_strategy: Optional[Callable[[Web3, Any], Wei]],
    used_contracts: List[str],
    address_overwrites: Dict[str, Address],
    development_environment: ContractDevEnvironment,
) -> Tuple[Web3, Dict[str, Contract], BlockNumber]:
    try:
        provider = HTTPProvider(eth_rpc)
        web3 = Web3(provider)
        # Will throw ConnectionError on bad Ethereum client
        chain_id = ChainID(web3.eth.chain_id)
    except requests.exceptions.ConnectionError:
        log.error(
            "Can not connect to the Ethereum client. Please check that it is running and that "
            "your settings are correct.",
            eth_rpc=eth_rpc,
        )
        sys.exit(1)

    # Add POA middleware for geth POA chains, no/op for other chains
    web3.middleware_onion.inject(geth_poa_middleware, layer=0)

    # Set gas price strategy
    # for that we also need a cache middleware, otherwise sampling is expensive
    web3.middleware_onion.add(simple_cache_middleware)

    if not gas_price_strategy:
        chain_id = ChainID(web3.eth.chain_id)
        gas_price_strategy = (rpc_gas_price_strategy
                              if "arbitrum" in ID_TO_CHAINNAME.get(
                                  chain_id, "") else fast_gas_price_strategy)

    web3.eth.setGasPriceStrategy(gas_price_strategy)

    # give web3 some time between retries before failing
    # TODO: find a way to to this type safe
    provider.middlewares.replace(  # type: ignore
        "http_retry_request", http_retry_with_backoff_middleware)

    addresses, start_block = get_contract_addresses_and_start_block(
        chain_id=chain_id,
        contracts=used_contracts,
        address_overwrites=address_overwrites,
        development_environment=development_environment,
    )
    contracts = {
        c: web3.eth.contract(abi=CONTRACT_MANAGER.get_contract_abi(c),
                             address=address)
        for c, address in addresses.items()
    }

    return web3, contracts, start_block
Ejemplo n.º 2
0
def test_setup_proxies_no_service_registry_but_pfs() -> None:
    """
    Test that if no service registry is provided but a manual pfs address is given then startup
    still works

    Regression test for https://github.com/raiden-network/raiden/issues/3740
    """
    chain_id = ChainID(5)
    config = RaidenConfig(
        chain_id=chain_id,
        environment_type=Environment.DEVELOPMENT,
        services=ServiceConfig(
            pathfinding_max_fee=TokenAmount(100),
            pathfinding_iou_timeout=BlockTimeout(500),
            pathfinding_max_paths=5,
        ),
    )
    config.transport.available_servers = ["http://matrix.example.com"]
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    PFS_INFO = PFSInfo(
        url="my-pfs",
        price=TokenAmount(12),
        chain_id=ChainID(5),
        token_network_registry_address=TokenNetworkRegistryAddress(
            to_canonical_address(contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["address"])
        ),
        user_deposit_address=user_deposit_address_test_default,
        confirmed_block_number=BlockNumber(1),
        payment_address=pfs_payment_address_default,
        message="This is your favorite pathfinding service",
        operator="John Doe",
        version="0.0.3",
        matrix_server="http://matrix.example.com",
        matrix_room_id="!room-id:matrix.example.com",
    )
    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
        services_bundle = services_bundle_from_contracts_deployment(
            config=config,
            proxy_manager=proxy_manager,  # type: ignore
            deployed_addresses=deployed_addresses,
            routing_mode=RoutingMode.PFS,
            pathfinding_service_address="my-pfs",
            enable_monitoring=True,
        )
    assert services_bundle
Ejemplo n.º 3
0
def test_setup_proxies_raiden_addresses_are_given():
    """
    Test that startup for proxies works fine if only raiden addresses are given
    """
    chain_id = ChainID(5)
    config = RaidenConfig(chain_id=chain_id,
                          environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    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,
        proxy_manager=proxy_manager,
        deployed_addresses=deployed_addresses,
        routing_mode=RoutingMode.LOCAL,
        pathfinding_service_address=None,
        enable_monitoring=False,
    )
    assert raiden_bundle
    assert services_bundle
    assert raiden_bundle.token_network_registry
    assert raiden_bundle.secret_registry
    assert services_bundle.user_deposit
    assert not services_bundle.service_registry
Ejemplo n.º 4
0
def test_setup_proxies_all_addresses_are_given():
    """
    Test that startup for proxies works fine if all addresses are given and routing is local
    """
    chain_id = ChainID(5)
    config = RaidenConfig(chain_id=chain_id,
                          environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
        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,
            proxy_manager=proxy_manager,
            deployed_addresses=deployed_addresses,
            routing_mode=RoutingMode.LOCAL,
            pathfinding_service_address="my-pfs",
            enable_monitoring=True,
        )
    assert raiden_bundle
    assert services_bundle
    assert raiden_bundle.token_network_registry
    assert raiden_bundle.secret_registry
    assert services_bundle.user_deposit
    assert not services_bundle.service_registry
def test_ecrecover_output(
    token_network: Contract,
    signature_test_contract: Contract,
    get_accounts: Callable,
    create_channel: Callable,
    create_balance_proof: Callable,
) -> None:
    """ecrecover returns the address that was used to sign a balance proof"""
    (A, B) = get_accounts(2)
    channel_identifier = create_channel(A, B)[0]
    balance_proof_A = create_balance_proof(channel_identifier, A, 2, 0, 3)
    signature = balance_proof_A.original_signature
    r = signature[:32]
    s = signature[32:64]
    v = signature[64:]
    balance_proof_hash = eth_sign_hash_message(
        pack_balance_proof(
            token_network_address=token_network.address,
            chain_identifier=ChainID(
                token_network.functions.chain_id().call()),
            channel_identifier=channel_identifier,
            balance_hash=balance_proof_A.balance_hash,
            nonce=balance_proof_A.nonce,
            additional_hash=balance_proof_A.additional_hash,
            msg_type=MessageTypeId.BALANCE_PROOF,
        ))

    address = signature_test_contract.functions.verifyEcrecoverOutput(
        balance_proof_hash, r, s, int.from_bytes(v, byteorder="big")).call()
    assert address == A
Ejemplo n.º 6
0
    def f(
            chain_id: ChainID = ChainID(1),
            amount: TokenAmount = TokenAmount(50),
            nonce: Nonce = Nonce(1),
            channel_id: ChannelID = ChannelID(1),
    ) -> RequestMonitoring:
        balance_proof = HashedBalanceProof(
            channel_identifier=channel_id,
            token_network_address=TokenNetworkAddress(b"1" * 20),
            chain_id=chain_id,
            nonce=nonce,
            additional_hash="",
            balance_hash=encode_hex(bytes([amount])),
            priv_key=get_random_privkey(),
        )
        request_monitoring = balance_proof.get_request_monitoring(
            privkey=non_closing_privkey,
            reward_amount=TokenAmount(55),
            monitoring_service_contract_address=TEST_MSC_ADDRESS,
        )

        # usually not a property of RequestMonitoring, but added for convenience in these tests
        request_monitoring.non_closing_signer = to_checksum_address(  # type: ignore
            non_closing_address)
        return request_monitoring
Ejemplo n.º 7
0
def get_network_to_broadcast_rooms(
        api: GMatrixHttpApi) -> Dict[str, List[RoomInfo]]:

    room_alias_fragments = [
        DISCOVERY_DEFAULT_ROOM,
        PATH_FINDING_BROADCASTING_ROOM,
        MONITORING_BROADCASTING_ROOM,
    ]

    server = urlparse(api.base_url).netloc
    network_to_broadcast: Dict[str, List[RoomInfo]] = dict()

    for network in Networks:
        broadcast_room_infos: List[RoomInfo] = list()
        network_to_broadcast[str(network.value)] = broadcast_room_infos
        for room_alias_fragment in room_alias_fragments:
            broadcast_room_alias = make_room_alias(ChainID(network.value),
                                                   room_alias_fragment)
            local_room_alias = f"#{broadcast_room_alias}:{server}"

            try:
                room_id = api.get_room_id(local_room_alias)
                broadcast_room_infos.append(
                    RoomInfo(room_id, broadcast_room_alias, server))
            except MatrixError as ex:
                click.secho(
                    f"Could not find room {broadcast_room_alias} with error {ex}"
                )

    return network_to_broadcast
Ejemplo n.º 8
0
    def verify_deployed_service_contracts_in_filesystem(
        self,
        token_address: HexAddress,
        user_deposit_whole_balance_limit: int,
        token_network_registry_address: HexAddress,
    ) -> None:
        chain_id = ChainID(self.web3.eth.chain_id)

        deployment_data = get_contracts_deployment_info(
            chain_id=chain_id,
            version=self.contract_manager.contracts_version,
            module=DeploymentModule.SERVICES,
        )
        deployment_file_path = contracts_deployed_path(
            chain_id=chain_id,
            version=self.contract_manager.contracts_version,
            services=True)
        if deployment_data is None:
            raise RuntimeError(
                f"Deployment data cannot be found at {deployment_file_path}")

        if self.verify_service_contracts_deployment_data(
                token_address=token_address,
                user_deposit_whole_balance_limit=
                user_deposit_whole_balance_limit,
                deployed_contracts_info=deployment_data,
                token_network_registry_address=token_network_registry_address,
        ):
            print(
                f"Deployment info from {deployment_file_path} has been verified "
                "and it is CORRECT.")
Ejemplo n.º 9
0
def test_setup_proxies_no_service_registry_and_no_pfs_address_but_requesting_pfs(
        environment_type):
    """
    Test that if pfs routing mode is requested and no address or service registry is given
    then the client exits with an error message
    """

    chain_id = ChainID(5)
    config = RaidenConfig(
        chain_id=chain_id,
        environment_type=environment_type,
        services=ServiceConfig(pathfinding_max_fee=100,
                               pathfinding_iou_timeout=500,
                               pathfinding_max_paths=5),
    )
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    with pytest.raises(RaidenError):
        deployed_addresses = load_deployment_addresses_from_contracts(
            contracts)
        with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
            services_bundle_from_contracts_deployment(
                config=config,
                proxy_manager=proxy_manager,
                deployed_addresses=deployed_addresses,
                routing_mode=RoutingMode.PFS,
                pathfinding_service_address=None,
                enable_monitoring=False,
            )
Ejemplo n.º 10
0
def main(
    private_key: str,
    state_db: str,
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,
    rdn_per_eth: float,
    expire_within: Timestamp,
) -> None:
    pfs_address = private_key_to_address(private_key)
    chain_id = ChainID(web3.eth.chain_id)
    database = PFSDatabase(filename=state_db,
                           chain_id=chain_id,
                           pfs_address=pfs_address,
                           sync_start_block=start_block)

    claim_cost_rdn = calc_claim_cost_rdn(web3, rdn_per_eth)
    time_now = get_posix_utc_time_now()
    ious = list(
        get_claimable_ious(
            database,
            claimable_until_after=time_now,
            claimable_until_before=Timestamp(time_now + expire_within),
            claim_cost_rdn=claim_cost_rdn,
        ))
    print(f"Found {len(ious)} claimable IOUs")
    _, failures = claim_ious(ious, claim_cost_rdn,
                             contracts[CONTRACT_ONE_TO_N], web3, database)
    if failures:
        sys.exit(1)
def test_verify(
    token_network: Contract,
    signature_test_contract: Contract,
    get_accounts: Callable,
    create_channel: Callable,
    create_balance_proof: Callable,
) -> None:
    """ECVerify.ecverify returns the correct address

    This test checks if the signature test contract returns the correct
    addresses on the balance hash signed by both ends of a channel"""
    (A, B) = get_accounts(2)
    channel_identifier = create_channel(A, B)[0]

    balance_proof_A = create_balance_proof(channel_identifier, A, 2, 0, 3)
    signature = balance_proof_A.original_signature
    balance_proof_hash = eth_sign_hash_message(
        pack_balance_proof(
            token_network_address=token_network.address,
            chain_identifier=ChainID(
                token_network.functions.chain_id().call()),
            channel_identifier=channel_identifier,
            balance_hash=balance_proof_A.balance_hash,
            nonce=balance_proof_A.nonce,
            additional_hash=balance_proof_A.additional_hash,
            msg_type=MessageTypeId.BALANCE_PROOF,
        ))
    address = signature_test_contract.functions.verify(balance_proof_hash,
                                                       signature).call()
    assert address == A

    balance_proof_B = create_balance_proof(channel_identifier, B, 0, 0, 0)
    signature = balance_proof_B.original_signature
    balance_proof_hash = eth_sign_hash_message(
        pack_balance_proof(
            token_network_address=token_network.address,
            chain_identifier=ChainID(
                token_network.functions.chain_id().call()),
            channel_identifier=channel_identifier,
            balance_hash=balance_proof_B.balance_hash,
            nonce=balance_proof_B.nonce,
            additional_hash=balance_proof_B.additional_hash,
            msg_type=MessageTypeId.BALANCE_PROOF,
        ))
    address = signature_test_contract.functions.verify(balance_proof_hash,
                                                       signature).call()
    assert address == B
Ejemplo n.º 12
0
def test_setup_proxies_all_addresses_are_known():
    """
    Test that startup for proxies works fine if all addresses are given and routing is basic
    """
    chain_id = ChainID(5)
    config = RaidenConfig(chain_id=chain_id,
                          environment_type=Environment.DEVELOPMENT)
    config.transport.available_servers = ["http://matrix.example.com"]
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())
    PFS_INFO = PFSInfo(
        url="my-pfs",
        price=TokenAmount(12),
        chain_id=ChainID(5),
        token_network_registry_address=to_canonical_address(
            contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["address"]),
        user_deposit_address=user_deposit_address_test_default,
        payment_address=pfs_payment_address_default,
        confirmed_block_number=BlockNumber(1),
        message="This is your favorite pathfinding service",
        operator="John Doe",
        version="0.0.3",
        matrix_server="http://matrix.example.com",
        matrix_room_id="!room-id:matrix.example.com",
    )
    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
        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,
            proxy_manager=proxy_manager,
            deployed_addresses=deployed_addresses,
            routing_mode=RoutingMode.PFS,
            pathfinding_service_address="my-pfs",
            enable_monitoring=False,
        )
    assert raiden_bundle
    assert services_bundle
    assert raiden_bundle.token_network_registry
    assert raiden_bundle.secret_registry
    assert services_bundle.user_deposit
    assert services_bundle.service_registry
Ejemplo n.º 13
0
    def test_can_get_contract_address(self):
        udc_address = get_contract_address(1, CONTRACT_USER_DEPOSIT)

        deployment_info = get_contracts_deployment_info(ChainID(1))
        assert deployment_info
        expected_udc_address = to_canonical_address(
            deployment_info["contracts"][CONTRACT_USER_DEPOSIT]["address"]
        )
        self.assertEqual(udc_address, expected_udc_address)
Ejemplo n.º 14
0
    def register_token_network(
        self,
        token_registry_abi: ABI,
        token_registry_address: ChecksumAddress,
        token_address: ChecksumAddress,
        channel_participant_deposit_limit: int,
        token_network_deposit_limit: int,
    ) -> Dict[str, Any]:
        """Register token with a TokenNetworkRegistry contract."""
        token_network_registry = self.web3.eth.contract(
            abi=token_registry_abi, address=token_registry_address)

        command = token_network_registry.functions.createERC20TokenNetwork(
            token_address, channel_participant_deposit_limit,
            token_network_deposit_limit)
        self.transact(command)

        LOG.debug("Collecting constructor parameters for later verification")
        chain_id = ChainID(self.web3.eth.chain_id)
        deployment_data = get_contracts_deployment_info(
            chain_id=chain_id,
            version=self.contract_manager.contracts_version,
            module=DeploymentModule.RAIDEN,
        )
        assert deployment_data
        secret_registry = self.contract_instance_from_deployment_data(
            deployment_data, CONTRACT_SECRET_REGISTRY)
        token_network_registry = self.contract_instance_from_deployment_data(
            deployment_data, CONTRACT_TOKEN_NETWORK_REGISTRY)
        settle_timeout_min = token_network_registry.functions.settlement_timeout_min(
        ).call()
        settle_timeout_max = token_network_registry.functions.settlement_timeout_max(
        ).call()
        constructor_arguments = dict(
            _token_address=token_address,
            _secret_registry=secret_registry.address,
            _chain_id=chain_id,
            _settlement_timeout_min=settle_timeout_min,
            _settlement_timeout_max=settle_timeout_max,
            _controller=self.owner,
            _channel_participant_deposit_limit=
            channel_participant_deposit_limit,
            _token_network_deposit_limit=token_network_deposit_limit,
        )

        LOG.debug("Getting address of new token network")
        token_network_address = "0x0"
        while int(token_network_address, 16) == 0:
            token_network_address = token_network_registry.functions.token_to_token_networks(
                token_address).call()
            time.sleep(2)
        LOG.debug(f"TokenNetwork address: {token_network_address}")
        return dict(
            token_network_address=token_network_address,
            constructor_arguments=constructor_arguments,
        )
Ejemplo n.º 15
0
def wait_for_sync(rpc_client: JSONRPCClient, tolerance: BlockTimeout, sleep: float) -> None:
    # print something since the actual test may take a few moments for the first
    # iteration
    print("Checking if the ethereum node is synchronized")

    # Only use blockcypher on mainnet
    if rpc_client.chain_id == ChainID(1):
        wait_for_sync_blockcypher(rpc_client, tolerance, sleep)

    wait_for_sync_rpc_api(rpc_client, tolerance, sleep)
Ejemplo n.º 16
0
def get_token_network_registry_contract(w3: Web3):
    chain_id = int(w3.net.version)
    manager = ContractManager(contracts_precompiled_path())

    contract_data = get_contracts_deployment_info(ChainID(chain_id))
    assert contract_data
    address = contract_data["contracts"][CONTRACT_TOKEN_NETWORK_REGISTRY]["address"]

    abi = manager.get_contract_abi(CONTRACT_TOKEN_NETWORK_REGISTRY)
    return w3.eth.contract(abi=abi, address=address)
Ejemplo n.º 17
0
    def __init__(
        self,
        web3: Web3,
        privkey: Optional[PrivateKey],
        gas_price_strategy: Callable = rpc_gas_price_strategy,
        gas_estimate_correction: Callable = lambda gas: gas,
        block_num_confirmations: int = 0,
    ) -> None:
        if privkey is None or len(privkey) != 32:
            raise ValueError("Invalid private key")

        if block_num_confirmations < 0:
            raise ValueError("Number of confirmations has to be positive")

        monkey_patch_web3(web3, gas_price_strategy)

        version = web3.version.node
        supported, eth_node, _ = is_supported_client(version)

        if not supported:
            raise EthNodeInterfaceError(
                f"Unsupported Ethereum client {version}")

        address = privatekey_to_address(privkey)
        address_checksumed = to_checksum_address(address)

        if eth_node is EthClient.PARITY:
            parity_assert_rpc_interfaces(web3)
            available_nonce = parity_discover_next_available_nonce(
                web3, address_checksumed)

        elif eth_node is EthClient.GETH:
            geth_assert_rpc_interfaces(web3)
            available_nonce = geth_discover_next_available_nonce(
                web3, address_checksumed)

        self.eth_node = eth_node
        self.privkey = privkey
        self.address = address
        self.web3 = web3
        self.default_block_num_confirmations = block_num_confirmations

        # Ask for the chain id only once and store it here
        self.chain_id = ChainID(int(self.web3.version.network))

        self._available_nonce = available_nonce
        self._nonce_lock = Semaphore()
        self._gas_estimate_correction = gas_estimate_correction

        log.debug(
            "JSONRPCClient created",
            node=to_checksum_address(self.address),
            available_nonce=available_nonce,
            client=version,
        )
Ejemplo n.º 18
0
def _add_token_network_deploy_info(
    token_network: Dict[str, Any], deployer: ContractDeployer, contracts_version: str
) -> None:
    """ Add deploy info dict to the deploy_*.json file """
    deployment_file_path = contracts_deployed_path(
        chain_id=ChainID(deployer.web3.eth.chainId), version=contracts_version
    )
    with deployment_file_path.open() as f:
        deployed_contracts_info: DeployedContracts = json.load(f)
    deployed_contracts_info.setdefault("token_networks", []).append(token_network)
    deployer.store_and_verify_deployment_info_raiden(
        deployed_contracts_info=deployed_contracts_info
    )
Ejemplo n.º 19
0
    def _store_deployment_info(self, services: bool,
                               deployment_info: DeployedContracts) -> None:
        deployment_file_path = contracts_deployed_path(
            chain_id=ChainID(self.web3.eth.chain_id),
            version=self.contracts_version,
            services=services,
        )
        with deployment_file_path.open(mode="w") as target_file:
            target_file.write(json.dumps(deployment_info, indent=2))

        print(
            f'Deployment information for chain id = {deployment_info["chain_id"]} '
            f" has been updated at {deployment_file_path}.")
Ejemplo n.º 20
0
    def __init__(  # pylint: disable=too-many-arguments
        self,
        web3: Web3,
        private_key: PrivateKey,
        db_filename: str,
        contracts: Dict[str, Contract],
        sync_start_block: BlockNumber,
        required_confirmations: BlockTimeout,
        poll_interval: float,
        min_reward: int = 0,
        get_timestamp_now: Callable = get_posix_utc_time_now,
    ):
        self.web3 = web3
        self.chain_id = ChainID(web3.eth.chain_id)
        self.private_key = private_key
        self.address = private_key_to_address(private_key)
        self.poll_interval = poll_interval
        self.service_registry = contracts[CONTRACT_SERVICE_REGISTRY]
        self.token_network_registry = contracts[
            CONTRACT_TOKEN_NETWORK_REGISTRY]
        self.get_timestamp_now = get_timestamp_now
        self.try_scheduled_events_after = get_timestamp_now()

        web3.middleware_onion.add(
            construct_sign_and_send_raw_middleware(private_key))

        monitoring_contract = contracts[CONTRACT_MONITORING_SERVICE]
        user_deposit_contract = contracts[CONTRACT_USER_DEPOSIT]

        self.database = Database(
            filename=db_filename,
            chain_id=self.chain_id,
            registry_address=to_canonical_address(
                self.token_network_registry.address),
            receiver=self.address,
            msc_address=MonitoringServiceAddress(
                to_canonical_address(monitoring_contract.address)),
            sync_start_block=sync_start_block,
        )
        ms_state = self.database.load_state()

        self.context = Context(
            ms_state=ms_state,
            database=self.database,
            web3=self.web3,
            monitoring_service_contract=monitoring_contract,
            user_deposit_contract=user_deposit_contract,
            min_reward=min_reward,
            required_confirmations=required_confirmations,
        )
Ejemplo n.º 21
0
def get_discovery_room(api: GMatrixHttpApi,
                       network_value: int) -> Optional[RoomInfo]:

    server = urlparse(api.base_url).netloc
    discovery_room_alias = make_room_alias(ChainID(network_value),
                                           DISCOVERY_DEFAULT_ROOM)
    local_room_alias = f"#{discovery_room_alias}:{server}"

    try:
        room_id = api.get_room_id(local_room_alias)
        return RoomInfo(room_id, discovery_room_alias, server)
    except MatrixError as ex:
        click.secho(
            f"Could not find room {discovery_room_alias} with error {ex}")

    return None
Ejemplo n.º 22
0
    def verify_deployed_contracts_in_filesystem(self) -> None:
        chain_id = ChainID(self.web3.eth.chain_id)

        deployment_data = get_contracts_deployment_info(
            chain_id=chain_id,
            version=self.contract_manager.contracts_version,
            module=DeploymentModule.RAIDEN,
        )
        deployment_file_path = contracts_deployed_path(
            chain_id=chain_id, version=self.contract_manager.contracts_version)
        if deployment_data is None:
            raise RuntimeError(
                f"Deployment data cannot be found at {deployment_file_path}")

        if self.verify_deployment_data(deployment_data):
            print(
                f"Deployment info from {deployment_file_path} has been verified "
                "and it is CORRECT.")
Ejemplo n.º 23
0
def test_claim_by_unregistered_service(
    one_to_n_contract: Contract,
    deposit_to_udc: Callable,
    get_accounts: Callable,
    get_private_key: Callable,
    web3: Web3,
) -> None:
    """OneToN contract should not work for an unregistered service provider."""
    (A, B) = get_accounts(2)
    deposit_to_udc(A, 30)

    amount = TokenAmount(10)
    expiration = BlockExpiration(web3.eth.block_number + 2)
    chain_id = web3.eth.chain_id

    signature = sign_one_to_n_iou(
        get_private_key(A),
        sender=A,
        receiver=B,
        amount=amount,
        expiration_block=expiration,
        one_to_n_address=one_to_n_contract.address,
        chain_id=ChainID(chain_id),
    )

    # Doesn't work because B is not registered
    with pytest.raises(TransactionFailed, match="receiver not registered"):
        call_and_transact(
            one_to_n_contract.functions.claim(
                sender=A,
                receiver=B,
                amount=amount,
                expiration_block=expiration,
                one_to_n_address=one_to_n_contract.address,
                signature=signature,
            ),
            {"from": A},
        )
Ejemplo n.º 24
0
 def f(
         sender_priv_key: PrivateKey,
         receiver: Address,
         amount=1,
         claimable_until=1000000000 * 15 + MIN_IOU_EXPIRY,
         one_to_n_address: Address = one_to_n_contract_address,
         chain_id: ChainID = ChainID(61),
 ) -> IOU:
     receiver_hex: str = to_checksum_address(receiver)
     iou_dict = {
         "sender":
         to_checksum_address(private_key_to_address(sender_priv_key)),
         "receiver": receiver_hex,
         "amount": amount,
         "claimable_until": claimable_until,
         "one_to_n_address": to_checksum_address(one_to_n_address),
         "chain_id": chain_id,
     }
     iou_dict["signature"] = encode_hex(
         sign_one_to_n_iou(privatekey=sender_priv_key, **iou_dict))
     iou = IOU.Schema().load(iou_dict)
     iou.claimed = False
     return iou
def test_deploy_data_not_deployed() -> None:
    assert (
        get_contracts_deployment_info(ChainID(1), "0.8.0", module=DeploymentModule.RAIDEN) is None
    )
Ejemplo n.º 26
0
def print_gas_one_to_n(
    one_to_n_contract: Contract,
    deposit_to_udc: Callable,
    print_gas: Callable,
    make_iou: Callable,
    web3: Web3,
    get_private_key: Callable,
    create_service_account: Callable,
    create_account: Callable,
) -> None:
    """Abusing pytest to print gas cost of OneToN functions"""
    A = create_account()
    B = create_service_account()
    deposit_to_udc(A, 30)

    # happy case
    chain_id = web3.eth.chain_id
    amount = TokenAmount(10)
    expiration = BlockExpiration(web3.eth.block_number + 2)
    signature = sign_one_to_n_iou(
        get_private_key(A),
        sender=A,
        receiver=B,
        amount=amount,
        expiration_block=expiration,
        one_to_n_address=one_to_n_contract.address,
        chain_id=ChainID(chain_id),
    )
    txn_hash = call_and_transact(
        one_to_n_contract.functions.claim(A, B, amount, expiration,
                                          one_to_n_contract.address,
                                          signature),
        {"from": A},
    )

    print_gas(txn_hash, CONTRACT_ONE_TO_N + ".claim")

    # bulk claims gas prices
    def concat_iou_data(ious: List[Dict], key: str) -> List:
        return [iou[key] for iou in ious]

    def concat_iou_signatures(ious: List[Dict]) -> bytes:
        result = b""
        for iou in ious:
            result += iou["signature"]

        return result

    for num_ious in (1, 6):
        receivers = [create_service_account() for i in range(num_ious)]
        ious = [make_iou(A, r) for r in receivers]

        txn_hash = call_and_transact(
            one_to_n_contract.functions.bulkClaim(
                concat_iou_data(ious, "sender"),
                concat_iou_data(ious, "receiver"),
                concat_iou_data(ious, "amount"),
                concat_iou_data(ious, "expiration_block"),
                one_to_n_contract.address,
                concat_iou_signatures(ious),
            ),
            {"from": A},
        )
        print_gas(txn_hash, CONTRACT_ONE_TO_N + f".bulkClaim {num_ious} ious")
Ejemplo n.º 27
0
def test_check_network_id_raises_with_mismatching_ids():
    check_ethereum_network_id(ChainID(68), MockWeb3(68))

    with pytest.raises(RaidenError):
        check_ethereum_network_id(ChainID(61), MockWeb3(68))
Ejemplo n.º 28
0
    CONTRACT_USER_DEPOSIT,
)
from raiden_contracts.utils.type_aliases import ChainID

token_network_registry_address_test_default = TokenNetworkRegistryAddress(
    to_canonical_address("0xB9633dd9a9a71F22C933bF121d7a22008f66B908"))
user_deposit_address_test_default = Address(
    to_canonical_address("0x8888888888888888888888888888888888888888"))

pfs_payment_address_default = to_canonical_address(
    "0xB9633dd9a9a71F22C933bF121d7a22008f66B907")

PFS_INFO = PFSInfo(
    url="my-pfs",
    price=TokenAmount(12),
    chain_id=ChainID(5),
    token_network_registry_address=token_network_registry_address_test_default,
    user_deposit_address=user_deposit_address_test_default,
    payment_address=pfs_payment_address_default,
    confirmed_block_number=BlockNumber(1),
    message="This is your favorite pathfinding service",
    operator="John Doe",
    version="0.0.3",
)


def test_check_network_id_raises_with_mismatching_ids():
    check_ethereum_network_id(ChainID(68), MockWeb3(68))

    with pytest.raises(RaidenError):
        check_ethereum_network_id(ChainID(61), MockWeb3(68))
Ejemplo n.º 29
0
class Networks(Enum):
    INTEGRATION = ChainID(4321)
Ejemplo n.º 30
0
    def _ensure_room_for_network(self, network: Networks,
                                 alias_fragment: str) -> None:
        log.info(f"Ensuring {alias_fragment} room for {network.name}")
        room_alias_prefix = make_room_alias(ChainID(network.value),
                                            alias_fragment)
        room_infos: Dict[str, Optional[RoomInfo]] = {
            server_name: self._get_room(server_name, room_alias_prefix)
            for server_name in self._known_servers.keys()
        }
        first_server_room_info = room_infos[self._first_server_name]

        if not first_server_room_info:
            log.warning("First server room missing")
            if self._is_first_server:
                log.info("Creating room", server_name=self._own_server_name)
                first_server_room_info = self._create_room(
                    self._own_server_name, room_alias_prefix)
                room_infos[self._first_server_name] = first_server_room_info
            else:
                raise EnsurerError("First server room missing.")

        are_all_rooms_the_same = all(
            room_info is not None
            and room_info.room_id == first_server_room_info.room_id
            for room_info in room_infos.values())
        if not are_all_rooms_the_same:
            log.warning(
                "Room id mismatch",
                alias_prefix=room_alias_prefix,
                expected=first_server_room_info.room_id,
                found={
                    server_name: room_info.room_id if room_info else None
                    for server_name, room_info in room_infos.items()
                },
            )
            own_server_room_info = room_infos.get(self._own_server_name)
            own_server_room_alias = f"#{room_alias_prefix}:{self._own_server_name}"
            first_server_room_alias = f"#{room_alias_prefix}:{self._first_server_name}"
            if not own_server_room_info:
                log.warning(
                    "Room missing on own server, adding alias",
                    server_name=self._own_server_name,
                    room_id=first_server_room_info.room_id,
                    new_room_alias=own_server_room_alias,
                )
                self._join_and_alias_room(first_server_room_alias,
                                          own_server_room_alias)
                log.info("Room alias set", alias=own_server_room_alias)
            elif own_server_room_info.room_id != first_server_room_info.room_id:
                log.warning(
                    "Conflicting local room, reassigning alias",
                    server_name=self._own_server_name,
                    expected_room_id=first_server_room_info.room_id,
                    current_room_id=own_server_room_info.room_id,
                )
                self._own_api.remove_room_alias(own_server_room_alias)
                self._join_and_alias_room(first_server_room_alias,
                                          own_server_room_alias)
                log.info(
                    "Room alias updated",
                    alias=own_server_room_alias,
                    room_id=first_server_room_info.room_id,
                )
            else:
                log.warning(
                    "Mismatching rooms on other servers. Doing nothing.")
        else:
            log.info(
                "Room state ok.",
                network=network,
                server_rooms={
                    server_name: room_info.room_id if room_info else None
                    for server_name, room_info in room_infos.items()
                },
            )