Exemplo n.º 1
0
    def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None:
        """
        Validates that ContractType keys in attr_dict reference existing manifest ContractTypes.
        """
        attr_dict_names = list(attr_dict.keys())

        if not self.unlinked_references and not self.linked_references:
            raise BytecodeLinkingError(
                "Unable to validate attr dict, this contract has no linked/unlinked references."
            )

        unlinked_refs = self.unlinked_references or ({}, )
        linked_refs = self.linked_references or ({}, )
        all_link_refs = unlinked_refs + linked_refs

        all_link_names = [ref["name"] for ref in all_link_refs if ref]
        if set(attr_dict_names) != set(all_link_names):
            raise BytecodeLinkingError(
                "All link references must be defined when calling "
                "`link_bytecode` on a contract factory.")
        for address in attr_dict.values():
            if not is_canonical_address(address):
                raise BytecodeLinkingError(
                    f"Address: {address} as specified in the attr_dict is not "
                    "a valid canoncial address.")
Exemplo n.º 2
0
    def set_registry(self, address: Address) -> None:
        """
        Sets the current registry used in ``web3.pm`` functions that read/write to an on-chain
        registry. This method accepts checksummed/canonical addresses or ENS names. Addresses
        must point to an on-chain instance of an ERC1319 registry implementation.

        To use an ENS domain as the address, make sure a valid ENS instance set as ``web3.ens``.

        * Parameters:
            * ``address``: Address of on-chain Registry.
        """
        if is_canonical_address(address) or is_checksum_address(address):
            self.registry = SimpleRegistry(address, self.web3)
        elif is_ens_name(address):
            self._validate_set_ens()
            addr_lookup = self.web3.ens.address(address)
            if not addr_lookup:
                raise NameNotFound(
                    "No address found after ENS lookup for name: {0}.".format(
                        address))
            self.registry = SimpleRegistry(addr_lookup, self.web3)
        else:
            raise PMError(
                "Expected a canonical/checksummed address or ENS name for the address, "
                "instead received {0}.".format(type(address)))
Exemplo n.º 3
0
    def set_registry(self, address: Address) -> None:
        """
        Sets the current registry used in ``web3.pm`` functions that read/write to an on-chain
        registry. This method accepts checksummed/canonical addresses or ENS names. Addresses
        must point to an instance of the Vyper Reference Registry implementation.
        If you want to use a different registry implementation with ``web3.pm``, manually
        set the ``web3.pm.registry`` attribute to any subclass of ``ERCRegistry``.

        To use an ENS domain as the address, make sure a valid ENS instance set as ``web3.ens``.

        * Parameters:
            * ``address``: Address of on-chain Vyper Reference Registry.
        """
        if is_canonical_address(address) or is_checksum_address(address):
            canonical_address = to_canonical_address(address)
            self.registry = VyperReferenceRegistry(canonical_address,
                                                   self.web3)
        elif is_ens_name(address):
            self._validate_set_ens()
            addr_lookup = self.web3.ens.address(address)
            if not addr_lookup:
                raise NameNotFound(
                    "No address found after ENS lookup for name: {0}.".format(
                        address))
            self.registry = VyperReferenceRegistry(
                to_canonical_address(addr_lookup), self.web3)
        else:
            raise PMError(
                "Expected a canonical/checksummed address or ENS name for the address, "
                "instead received {0}.".format(type(address)))
Exemplo n.º 4
0
def compute_leaf_hash(item: Item) -> bytes:
    address, value = item
    if not is_canonical_address(address):
        raise ValueError("Address must be a canonical address")

    if value < 0 or value >= 2**256:
        raise ValueError("value is negative or too large")

    return keccak(address + value.to_bytes(32, "big"))
Exemplo n.º 5
0
def validate_address(address: Any) -> None:
    """
    Raise a ValidationError if an address is not canonicalized.
    """
    if not is_address(address):
        raise ValidationError(f"Expected an address, got: {address}")
    if not is_canonical_address(address):
        raise ValidationError(
            "Py-EthPM library only accepts canonicalized addresses. "
            f"{address} is not in the accepted format.")
Exemplo n.º 6
0
def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> bytes:
    """
    Returns the new bytecode with `value` put into the location indicated by `offset` and `length`.
    """
    try:
        validate_empty_bytes(offset, length, bytecode)
    except EthPMValidationError:
        raise BytecodeLinkingError("Link references cannot be applied to bytecode")

    address = value if is_canonical_address(value) else to_canonical_address(value)
    new_bytes = (
        # Ignore linting error b/c conflict b/w black & flake8
        bytecode[:offset] + address + bytecode[offset + length:]  # noqa: E201, E203
    )
    return new_bytes
Exemplo n.º 7
0
    def __init__(
        self,
        validator_proxy_contract,
        validator_address,
        poll_interval,
        control_queue,
        stop_validating_callback,
    ) -> None:
        self.validator_proxy_contract = validator_proxy_contract
        if not is_canonical_address(validator_address):
            raise ValueError(
                "Validator address must be given in canonical format")
        self.validator_address = validator_address

        self.poll_interval = poll_interval
        self.control_queue = control_queue
        self.stop_validating_callback = stop_validating_callback
Exemplo n.º 8
0
def make_call_context(sender_address,
                      gas,
                      value=None,
                      gas_price=None,
                      data=None):
    if not is_canonical_address(sender_address):
        raise ValueError(
            'sender_address should be provided in the canonical format')
    if not (isinstance(gas, int) and gas > 0):
        raise ValueError('gas should be provided as positive integer')
    # Both 'from' and 'gas' are required in eth_tester
    yield 'from', to_checksum_address(sender_address)
    yield 'gas', gas
    if value is not None:
        yield 'value', value
    if gas_price is not None:
        yield 'gas_price', gas_price
    if data is not None:
        yield 'data', data
Exemplo n.º 9
0
def make_call_context(sender_address: bytes,
                      gas: int,
                      value: int=None,
                      gas_price: int=None,
                      data: bytes=None) -> Generator[Tuple[str, Any], None, None]:
    """
    Makes the context for message call.
    """
    if not is_canonical_address(sender_address):
        raise ValueError('sender_address should be provided in the canonical format')
    if not (isinstance(gas, int) and gas > 0):
        raise ValueError('gas should be provided as positive integer')
    # Both 'from' and 'gas' are required in eth_tester
    yield 'from', to_checksum_address(sender_address)
    yield 'gas', gas
    if value is not None:
        yield 'value', value
    if gas_price is not None:
        yield 'gas_price', gas_price
    if data is not None:
        yield 'data', data
Exemplo n.º 10
0
def test_configure_pfs(service_registry_address, private_keys, web3,
                       contract_manager):
    chain_id = ChainID(int(web3.net.version))
    service_registry, urls = deploy_service_registry_and_set_urls(
        private_keys=private_keys,
        web3=web3,
        contract_manager=contract_manager,
        service_registry_address=service_registry_address,
    )
    json_data = {
        "price_info":
        0,
        "network_info": {
            "chain_id":
            chain_id,
            "token_network_registry_address":
            to_checksum_address(token_network_registry_address_test_default),
            "user_deposit_address":
            to_checksum_address(privatekey_to_address(private_keys[1])),
            "confirmed_block": {
                "number": 10
            },
        },
        "message":
        "This is your favorite pathfinding service",
        "operator":
        "John Doe",
        "version":
        "0.0.1",
        "payment_address":
        to_checksum_address(privatekey_to_address(private_keys[0])),
    }

    response = mocked_json_response(response_data=json_data)

    # With local routing configure_pfs should raise assertion
    with pytest.raises(AssertionError):
        _ = configure_pfs_or_exit(
            pfs_url="",
            routing_mode=RoutingMode.LOCAL,
            service_registry=service_registry,
            node_network_id=chain_id,
            token_network_registry_address=
            token_network_registry_address_test_default,
            pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
        )

    # With private routing configure_pfs should raise assertion
    with pytest.raises(AssertionError):
        _ = configure_pfs_or_exit(
            pfs_url="",
            routing_mode=RoutingMode.PRIVATE,
            service_registry=service_registry,
            node_network_id=chain_id,
            token_network_registry_address=
            token_network_registry_address_test_default,
            pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
        )

    # Asking for auto address
    # To make this deterministic we need to patch the random selection function
    patch_random = patch("raiden.network.pathfinding.get_random_pfs",
                         return_value="http://foo")
    with patch.object(requests, "get", return_value=response), patch_random:
        config = configure_pfs_or_exit(
            pfs_url=MATRIX_AUTO_SELECT_SERVER,
            routing_mode=RoutingMode.PFS,
            service_registry=service_registry,
            node_network_id=chain_id,
            token_network_registry_address=
            token_network_registry_address_test_default,
            pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
        )
    assert config.url in urls
    assert is_canonical_address(config.payment_address)

    # Configuring a valid given address
    given_address = "http://foo"
    with patch.object(requests, "get", return_value=response):
        config = configure_pfs_or_exit(
            pfs_url=given_address,
            routing_mode=RoutingMode.PFS,
            service_registry=service_registry,
            node_network_id=chain_id,
            token_network_registry_address=
            token_network_registry_address_test_default,
            pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
        )
    assert config.url == given_address
    assert is_same_address(config.payment_address,
                           json_data["payment_address"])
    assert config.price == json_data["price_info"]

    # Bad address, should exit the program
    bad_address = "http://badaddress"
    with pytest.raises(RaidenError):
        with patch.object(requests,
                          "get",
                          side_effect=requests.RequestException()):
            # Configuring a given address
            _ = configure_pfs_or_exit(
                pfs_url=bad_address,
                routing_mode=RoutingMode.PFS,
                service_registry=service_registry,
                node_network_id=chain_id,
                token_network_registry_address=
                token_network_registry_address_test_default,
                pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
            )

    # Addresses of token network registries of pfs and client conflict, should exit the client
    response = mocked_json_response(response_data=json_data)
    with pytest.raises(RaidenError):
        with patch.object(requests, "get", return_value=response):
            _ = configure_pfs_or_exit(
                pfs_url="http://foo",
                routing_mode=RoutingMode.PFS,
                service_registry=service_registry,
                node_network_id=chain_id,
                token_network_registry_address=TokenNetworkRegistryAddress(
                    to_canonical_address(
                        "0x2222222222222222222222222222222222222221")),
                pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
            )

    # ChainIDs of pfs and client conflict, should exit the client
    response = mocked_json_response(response_data=json_data)
    with pytest.raises(RaidenError):
        with patch.object(requests, "get", return_value=response):
            configure_pfs_or_exit(
                pfs_url="http://foo",
                routing_mode=RoutingMode.PFS,
                service_registry=service_registry,
                node_network_id=ChainID(chain_id + 1),
                token_network_registry_address=
                token_network_registry_address_test_default,
                pathfinding_max_fee=DEFAULT_PATHFINDING_MAX_FEE,
            )
def test_to_canonical_address_from_public_key(private_key):
    address = private_key.public_key.to_canonical_address()
    assert is_canonical_address(address)
    assert is_same_address(address, ADDRESS)
Exemplo n.º 12
0
def validate_canonical_address(value):
    validate_bytes(value)
    if not is_canonical_address(value):
        raise ValidationError("Value must be a 20 byte string")