Python eth_typing.HexStr() Examples

The following are 19 code examples of eth_typing.HexStr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module eth_typing , or try the search function .
Example #1
Source File: conversions.py    From eth-utils with MIT License 6 votes vote down vote up
def to_bytes(
    primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> bytes:
    if is_boolean(primitive):
        return b"\x01" if primitive else b"\x00"
    elif isinstance(primitive, bytearray):
        return bytes(primitive)
    elif isinstance(primitive, bytes):
        return primitive
    elif is_integer(primitive):
        return to_bytes(hexstr=to_hex(primitive))
    elif hexstr is not None:
        if len(hexstr) % 2:
            # type check ignored here because casting an Optional arg to str is not possible
            hexstr = "0x0" + remove_0x_prefix(hexstr)  # type: ignore
        return decode_hex(hexstr)
    elif text is not None:
        return text.encode("utf-8")
    raise TypeError(
        "expected a bool, int, byte or bytearray in first arg, or keyword of hexstr or text"
    ) 
Example #2
Source File: test_deploy_script.py    From raiden-contracts with MIT License 6 votes vote down vote up
def test_user_deposit_deployment_with_wrong_one_to_n_address() -> None:
    """ ContractVerifier.verify_user_deposit_deployment raises on a wrong OneToN address """
    token_addr = HexAddress(HexStr("0xDa12Dc74D2d0881749CCd9330ac4f0aecda5686a"))
    user_deposit_constructor_arguments = [token_addr, UINT256_MAX]
    wrong_one_to_n_address = FAKE_ADDRESS
    user_deposit_mock = MagicMock()
    mock_token_address = MagicMock()
    mock_token_address.call.return_value = token_addr
    user_deposit_mock.functions.token.return_value = mock_token_address

    with pytest.raises(RuntimeError):
        _verify_user_deposit_deployment(
            user_deposit=user_deposit_mock,
            constructor_arguments=user_deposit_constructor_arguments,
            token_address=token_addr,
            user_deposit_whole_balance_limit=UINT256_MAX,
            one_to_n_address=wrong_one_to_n_address,
            monitoring_service_address=HexAddress(
                HexStr("0xb7765972d78B6C97bB0a5a6b7529DC1fb64aA287")
            ),
        ) 
Example #3
Source File: test_deploy_script.py    From raiden-contracts with MIT License 6 votes vote down vote up
def test_deploy_services_with_controller(
    mock_deploy: MagicMock, mock_verify: MagicMock, privkey_file: IO
) -> None:
    """ Calling deploy raiden command """
    with patch.object(Eth, "getBalance", return_value=1):
        runner = CliRunner()
        result = runner.invoke(
            services,
            deploy_services_arguments(
                privkey=privkey_file.name,
                save_info=None,
                service_registry_controller=HexAddress(HexStr("0x" + "1" * 40)),
                token_network_registry_address=FAKE_ADDRESS,
            ),
        )
        assert result.exception is None
        assert result.exit_code == 0
        mock_deploy.assert_called_once()
        mock_verify.assert_called_once() 
Example #4
Source File: test_deploy_data.py    From raiden-contracts with MIT License 6 votes vote down vote up
def test_verify_existent_deployment_with_wrong_code(
    token_network_registry_contract: Contract,
) -> None:
    """ Test verify_deployed_contracts_in_filesystem() with an existent deployment data

    but with a fake web3 that does not return the correct code.
    """
    web3_mock = Mock()
    web3_mock.version.network = 5
    web3_mock.eth.getTransactionReceipt = lambda _: {
        "blockNumber": 10711807,
        "gasUsed": 555366,
        "contractAddress": "0x8Ff327f7ed03cD6Bd5e611E9e404B47d8c9Db81E",
    }
    verifier = ContractVerifier(web3=web3_mock, contracts_version=ALDERAAN_VERSION)
    # The Mock returns a wrong block number, so the comparison fails.
    with pytest.raises(RuntimeError):
        verifier.verify_deployed_contracts_in_filesystem()
    with pytest.raises(RuntimeError):
        verifier.verify_deployed_service_contracts_in_filesystem(
            token_address=HexAddress(HexStr("0x5Fc523e13fBAc2140F056AD7A96De2cC0C4Cc63A")),
            user_deposit_whole_balance_limit=2 ** 256 - 1,
            token_network_registry_address=token_network_registry_contract.address,
        ) 
Example #5
Source File: test_deploy_data.py    From raiden-contracts with MIT License 6 votes vote down vote up
def test_verify_existent_deployment(token_network_registry_contract: Contract) -> None:
    """ Test verify_deployed_contracts_in_filesystem() with an existent deployment data

    but with a fake web3 that returns a wrong block number for deployment.
    """
    web3_mock = Mock()
    web3_mock.version.network = 5
    web3_mock.eth.getTransactionReceipt = lambda _: {"blockNumber": 0}
    verifier = ContractVerifier(web3=web3_mock, contracts_version=ALDERAAN_VERSION)
    # The Mock returns a wrong block number, so the comparison fails.
    with pytest.raises(RuntimeError):
        verifier.verify_deployed_contracts_in_filesystem()
    with pytest.raises(RuntimeError):
        verifier.verify_deployed_service_contracts_in_filesystem(
            token_address=HexAddress(HexStr("0x5Fc523e13fBAc2140F056AD7A96De2cC0C4Cc63A")),
            user_deposit_whole_balance_limit=2 ** 256 - 1,
            token_network_registry_address=token_network_registry_contract.address,
        ) 
Example #6
Source File: main.py    From web3.py with MIT License 6 votes vote down vote up
def solidityKeccak(cls, abi_types: List[TypeStr], values: List[Any]) -> bytes:
        """
        Executes keccak256 exactly as Solidity does.
        Takes list of abi_types as inputs -- `[uint24, int8[], bool]`
        and list of corresponding values  -- `[20, [-1, 5, 0], True]`
        """
        if len(abi_types) != len(values):
            raise ValueError(
                "Length mismatch between provided abi types and values.  Got "
                "{0} types and {1} values.".format(len(abi_types), len(values))
            )

        if isinstance(cls, type):
            w3 = None
        else:
            w3 = cls
        normalized_values = map_abi_data([abi_ens_resolver(w3)], abi_types, values)

        hex_string = add_0x_prefix(HexStr(''.join(
            remove_0x_prefix(hex_encode_abi_type(abi_type, value))
            for abi_type, value
            in zip(abi_types, normalized_values)
        )))
        return cls.keccak(hexstr=hex_string) 
Example #7
Source File: address.py    From eth-utils with MIT License 6 votes vote down vote up
def to_normalized_address(value: AnyStr) -> HexAddress:
    """
    Converts an address to its normalized hexadecimal representation.
    """
    try:
        hex_address = hexstr_if_str(to_hex, value).lower()
    except AttributeError:
        raise TypeError(
            "Value must be any string, instead got type {}".format(type(value))
        )
    if is_address(hex_address):
        return HexAddress(HexStr(hex_address))
    else:
        raise ValueError(
            "Unknown format {}, attempted to normalize to {}".format(value, hex_address)
        ) 
Example #8
Source File: address.py    From eth-utils with MIT License 6 votes vote down vote up
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
    """
    Makes a checksum address given a supported format.
    """
    norm_address = to_normalized_address(value)
    address_hash = encode_hex(keccak(text=remove_0x_prefix(HexStr(norm_address))))

    checksum_address = add_0x_prefix(
        HexStr(
            "".join(
                (
                    norm_address[i].upper()
                    if int(address_hash[i], 16) > 7
                    else norm_address[i]
                )
                for i in range(2, 42)
            )
        )
    )
    return ChecksumAddress(HexAddress(checksum_address)) 
Example #9
Source File: zero_ex_custom_utils_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def is_valid_signature(
    provider: BaseProvider, data: str, signature: str, signer_address: str, chain_id: int = 1
) -> bool:
    """Check the validity of the supplied signature.
    Check if the supplied `signature`:code: corresponds to signing `data`:code:
    with the private key corresponding to `signer_address`:code:.
    :param provider: A Web3 provider able to access the 0x Exchange contract.
    :param data: The hex encoded data signed by the supplied signature.
    :param signature: The hex encoded signature.
    :param signer_address: The hex encoded address that signed the data to
        produce the supplied signature.
    :returns: Tuple consisting of a boolean and a string.  Boolean is true if
        valid, false otherwise.  If false, the string describes the reason.
    >>> is_valid_signature(
    ...     Web3.HTTPProvider("http://127.0.0.1:8545"),
    ...     '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0',
    ...     '0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace225403',
    ...     '0x5409ed021d9299bf6814279a6a1411a7e866a631',
    ... )
    True
    """  # noqa: E501 (line too long)
    assert_is_provider(provider, "provider")
    assert_is_hex_string(data, "data")
    assert_is_hex_string(signature, "signature")
    assert_is_address(signer_address, "signer_address")

    return Exchange(
        provider,
        chain_to_addresses(
            ChainId(
                chain_id  # defaults to always be mainnet
            )
        ).exchange,
    ).is_valid_hash_signature.call(
        bytes.fromhex(remove_0x_prefix(HexStr(data))),
        to_checksum_address(signer_address),
        bytes.fromhex(remove_0x_prefix(HexStr(signature))),
    ) 
Example #10
Source File: conversions.py    From eth-utils with MIT License 5 votes vote down vote up
def to_hex(
    primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> HexStr:
    """
    Auto converts any supported value into its hex representation.
    Trims leading zeros, as defined in:
    https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding
    """
    if hexstr is not None:
        return add_0x_prefix(HexStr(hexstr.lower()))

    if text is not None:
        return encode_hex(text.encode("utf-8"))

    if is_boolean(primitive):
        return HexStr("0x1") if primitive else HexStr("0x0")

    if isinstance(primitive, (bytes, bytearray)):
        return encode_hex(primitive)
    elif is_string(primitive):
        raise TypeError(
            "Unsupported type: The primitive argument must be one of: bytes,"
            "bytearray, int or bool and not str"
        )

    if is_integer(primitive):
        return HexStr(hex(primitive))

    raise TypeError(
        "Unsupported type: '{0}'.  Must be one of: bool, str, bytes, bytearray"
        "or int.".format(repr(type(primitive)))
    ) 
Example #11
Source File: main.py    From web3.py with MIT License 5 votes vote down vote up
def keccak(primitive: Optional[Primitives] = None, text: Optional[str] = None,
               hexstr: Optional[HexStr] = None) -> bytes:
        if isinstance(primitive, (bytes, int, type(None))):
            input_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
            return eth_utils_keccak(input_bytes)

        raise TypeError(
            "You called keccak with first arg %r and keywords %r. You must call it with one of "
            "these approaches: keccak(text='txt'), keccak(hexstr='0x747874'), "
            "keccak(b'\\x74\\x78\\x74'), or keccak(0x747874)." % (
                primitive,
                {'text': text, 'hexstr': hexstr}
            )
        ) 
Example #12
Source File: main.py    From web3.py with MIT License 5 votes vote down vote up
def sha3(primitive: Optional[Primitives] = None, text: Optional[str] = None,
             hexstr: Optional[HexStr] = None) -> bytes:
        return Web3.keccak(primitive, text, hexstr) 
Example #13
Source File: hexadecimal.py    From eth-utils with MIT License 5 votes vote down vote up
def add_0x_prefix(value: HexStr) -> HexStr:
    if is_0x_prefixed(value):
        return value
    return HexStr("0x" + value) 
Example #14
Source File: hexadecimal.py    From eth-utils with MIT License 5 votes vote down vote up
def remove_0x_prefix(value: HexStr) -> HexStr:
    if is_0x_prefixed(value):
        return HexStr(value[2:])
    return value 
Example #15
Source File: hexadecimal.py    From eth-utils with MIT License 5 votes vote down vote up
def encode_hex(value: AnyStr) -> HexStr:
    if not is_string(value):
        raise TypeError("Value must be an instance of str or unicode")
    elif isinstance(value, (bytes, bytearray)):
        ascii_bytes = value
    else:
        ascii_bytes = value.encode("ascii")

    binary_hex = binascii.hexlify(ascii_bytes)
    return add_0x_prefix(HexStr(binary_hex.decode("ascii"))) 
Example #16
Source File: conversions.py    From eth-utils with MIT License 5 votes vote down vote up
def hexstr_if_str(
    to_type: Callable[..., T], hexstr_or_primitive: Union[bytes, int, str]
) -> T:
    """
    Convert to a type, assuming that strings can be only hexstr (not unicode text)

    :param to_type function: takes the arguments (primitive, hexstr=hexstr, text=text),
        eg~ to_bytes, to_text, to_hex, to_int, etc
    :param hexstr_or_primitive bytes, str, int: value to convert
    """
    if isinstance(hexstr_or_primitive, str):
        if remove_0x_prefix(HexStr(hexstr_or_primitive)) and not is_hexstr(
            hexstr_or_primitive
        ):
            raise ValueError(
                "when sending a str, it must be a hex string. Got: {0!r}".format(
                    hexstr_or_primitive
                )
            )
        return to_type(hexstr=hexstr_or_primitive)
    else:
        return to_type(hexstr_or_primitive) 
Example #17
Source File: conversions.py    From eth-utils with MIT License 5 votes vote down vote up
def to_text(
    primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> str:
    if hexstr is not None:
        return to_bytes(hexstr=hexstr).decode("utf-8")
    elif text is not None:
        return text
    elif isinstance(primitive, str):
        return to_text(hexstr=primitive)
    elif isinstance(primitive, (bytes, bytearray)):
        return primitive.decode("utf-8")
    elif is_integer(primitive):
        byte_encoding = int_to_big_endian(primitive)
        return to_text(byte_encoding)
    raise TypeError("Expected an int, bytes, bytearray or hexstr.") 
Example #18
Source File: conversions.py    From eth-utils with MIT License 5 votes vote down vote up
def to_int(
    primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> int:
    """
    Converts value to its integer representation.
    Values are converted this way:

     * primitive:

       * bytes, bytearrays: big-endian integer
       * bool: True => 1, False => 0
     * hexstr: interpret hex as integer
     * text: interpret as string of digits, like '12' => 12
    """
    if hexstr is not None:
        return int(hexstr, 16)
    elif text is not None:
        return int(text)
    elif isinstance(primitive, (bytes, bytearray)):
        return big_endian_to_int(primitive)
    elif isinstance(primitive, str):
        raise TypeError("Pass in strings with keyword hexstr or text")
    elif isinstance(primitive, (int, bool)):
        return int(primitive)
    else:
        raise TypeError(
            "Invalid type.  Expected one of int/bool/str/bytes/bytearray.  Got "
            "{0}".format(type(primitive))
        ) 
Example #19
Source File: deprecation_switch_testnet.py    From raiden-contracts with MIT License 4 votes vote down vote up
def deprecation_test(
    ctx: click.Context,
    private_key: str,
    rpc_provider: URI,
    wait: int,
    gas_price: int,
    gas_limit: int,
) -> None:
    """ Turn on the deprecation switch and see channel opening fails """
    setup_ctx(
        ctx=ctx,
        private_key=private_key,
        password_file=None,
        rpc_provider=rpc_provider,
        wait=wait,
        gas_price=gas_price,
        gas_limit=gas_limit,
    )
    deployer = ctx.obj["deployer"]

    # We deploy the Raiden Network contracts and register a token network
    token_amount = MAX_ETH_CHANNEL_PARTICIPANT * 6
    channel_participant_deposit_limit = MAX_ETH_CHANNEL_PARTICIPANT
    token_network_deposit_limit = MAX_ETH_TOKEN_NETWORK
    (_, token_network, _) = deprecation_test_setup(
        deployer=deployer,
        token_amount=token_amount,
        channel_participant_deposit_limit=channel_participant_deposit_limit,
        token_network_deposit_limit=token_network_deposit_limit,
    )

    log.info("Checking that channels can be opened and deposits can be made.")

    # Check that we can open channels and deposit on behalf of A and B
    # Some arbitrary Ethereum addresses
    A = HexAddress(HexStr("0x6AA63296FA94975017244769F00F0c64DB7d7115"))
    B = HexAddress(HexStr("0xc9a4fad99B6d7D3e48D18d2585470cd8f27FA61e"))
    channel_identifier = open_and_deposit(A=A, B=B, token_network=token_network, deployer=deployer)
    log.info("Seding transaction to activate the deprecation switch.")

    # Activate deprecation switch
    assert token_network.functions.safety_deprecation_switch().call() is False
    txhash = deployer.transact(token_network.functions.deprecate())
    log.debug(f"Deprecation txHash={encode_hex(txhash)}")
    assert token_network.functions.safety_deprecation_switch().call() is True

    log.info("Checking that channels cannot be opened anymore and no more deposits are allowed.")

    # Check that we cannot open more channels or deposit
    C = HexAddress(HexStr("0x5a23cedB607684118ccf7906dF3e24Efd2964719"))
    D = HexAddress(HexStr("0x3827B9cDc68f061aa614F1b97E23664ef3b9220A"))
    open_and_deposit(
        A=C,
        B=D,
        token_network=token_network,
        deployer=deployer,
        channel_identifier=channel_identifier,
        txn_success_status=False,
    )

    log.info("Deprecation switch test OK.")