Exemple #1
0
def normalize_fixture(fixture):
    normalized_fixture = {
        'in':
        tuple((
            decode_hex(key) if is_0x_prefixed(key) else force_bytes(key),
            (decode_hex(value) if is_0x_prefixed(value) else force_bytes(value)
             ) if value is not None else None,
        ) for key, value in (fixture['in'].items(
        ) if isinstance(fixture['in'], dict) else fixture['in'])),
        'root':
        decode_hex(fixture['root'])
    }
    return normalized_fixture
Exemple #2
0
def pack(*args) -> bytes:
    def format_int(value, size):
        assert isinstance(value, int)
        assert isinstance(size, int)
        if value >= 0:
            return decode_hex('{:x}'.format(value).zfill(size // 4))
        else:
            return decode_hex('{:x}'.format((1 << size) + value))

    msg = b''
    for arg in args:
        assert arg is not None
        if isinstance(arg, bytes):
            msg += arg
        elif isinstance(arg, str):
            if is_0x_prefixed(arg):
                msg += decode_hex(arg)
            else:
                msg += arg.encode()
        elif isinstance(arg, bool):
            msg += format_int(int(arg), 8)
        elif isinstance(arg, int):
            msg += format_int(arg, 256)
        elif isinstance(arg, tuple):
            msg += format_int(arg[0], arg[1])
        else:
            raise ValueError('Unsupported type: {}.'.format(type(arg)))

    return msg
 def first_pass_check_address_arr(cls, address_param_lst, param_name, base_param_type, conversion_errors):
     error_flag = False
     ret = address_param_lst
     for idx, each_addr in enumerate(address_param_lst):
         each_addr = str(each_addr)
         ret[idx] = "0x"
         if not eth_utils.is_0x_prefixed(each_addr):
             if param_name not in conversion_errors:
                 conversion_errors[param_name] = {"message": [], "failed_indexes": []}
             e_m = "Expected type: address. Supplied argument {0} not a hexadecimal value".format(each_addr)
             conversion_errors[param_name]["message"].append(e_m)
             conversion_errors[param_name]["failed_indexes"].append(idx)
             error_flag = True
         else:
             if not eth_utils.is_address(each_addr):
                 if param_name not in conversion_errors:
                     conversion_errors[param_name] = {"message": [], "failed_indexes": []}
                 e_m = "Expected type: address. Supplied argument {0} is not a valid Ethereum address".format(
                     each_addr)
                 conversion_errors[param_name]["message"].append(e_m)
                 conversion_errors[param_name]["failed_indexes"].append(idx)
                 error_flag = True
             else:
                 ret[idx] = each_addr
     return (ret, error_flag)
def validate_block_header(ctx, param, value):
    if is_hex(value) and is_0x_prefixed(value):
        return decode_hex(value)
    else:
        raise click.BadParameter(
            f"A block header parameter seems to be not well structured: {value}"
        )
Exemple #5
0
def pack(*args) -> bytes:
    """
    Simulates Solidity's sha3 packing. Integers can be passed as tuples where the second tuple
    element specifies the variable's size in bits, e.g.:
    sha3((5, 32))
    would be equivalent to Solidity's
    sha3(uint32(5))
    Default size is 256.
    """
    def format_int(value, size):
        assert isinstance(value, int)
        assert isinstance(size, int)
        if value >= 0:
            return decode_hex('{:x}'.format(value).zfill(size // 4))
        else:
            return decode_hex('{:x}'.format((1 << size) + value))

    msg = b''
    for arg in args:
        assert arg
        if isinstance(arg, bytes):
            msg += arg
        elif isinstance(arg, str):
            if is_0x_prefixed(arg):
                msg += decode_hex(arg)
            else:
                msg += arg.encode()
        elif isinstance(arg, int):
            msg += format_int(arg, 256)
        elif isinstance(arg, tuple):
            msg += format_int(arg[0], arg[1])
        else:
            raise ValueError('Unsupported type: {}.'.format(type(arg)))

    return msg
Exemple #6
0
def to_decimal(value=None, hexstr=None, text=None):
    """
    Converts value to it's decimal representation in string
    """
    assert_one_val(value, hexstr=hexstr, text=text)

    if hexstr is not None:
        return int(hexstr, 16)
    elif text is not None:
        return int(text)
    elif is_string(value):
        if bytes != str and isinstance(value, bytes):
            return to_decimal(hexstr=to_hex(value))
        elif is_0x_prefixed(value) or _is_prefixed(value, '-0x'):
            warnings.warn(
                DeprecationWarning(
                    "Sending a hex string in the first position has been deprecated. Please use "
                    "toDecimal(hexstr='%s') instead." % value))
            return to_decimal(hexstr=value)
        else:
            try:
                return int(value)
            except ValueError:
                return to_decimal(hexstr=to_hex(value))
    else:
        return int(value)
Exemple #7
0
async def test_checkout_consumer():
    checkout = CheckoutFactory()
    checkout.store.accepted_currencies.add(checkout.payment_order.currency)

    communicator = WebsocketCommunicator(application,
                                         f"checkout/{checkout.id}")
    ok, protocol_or_error = await communicator.connect()

    assert ok, "Failed to connect"

    tx = TransactionFactory()
    await sync_to_async(blockchain_payment_sent.send)(
        sender=EthereumToken,
        amount=checkout.payment_order.as_token_amount,
        recipient=checkout.payment_order.payment_method.wallet.address,
        transaction_hash=tx.hash,
    )

    response = await communicator.receive_json_from()
    assert "event" in response
    assert "voucher" in response
    assert "identifier" in response
    assert "payment_method" in response

    assert is_0x_prefixed(response["identifier"])

    assert response["payment_method"] == PAYMENT_METHODS.blockchain
    assert response["event"] == "payment.sent"
def pack(*args) -> bytes:
    """
    Simulates Solidity's sha3 packing. Integers can be passed as tuples where the second tuple
    element specifies the variable's size in bits, e.g.:
    sha3((5, 32))
    would be equivalent to Solidity's
    sha3(uint32(5))
    Default size is 256.
    """
    def format_int(value, size):
        assert isinstance(value, int)
        assert isinstance(size, int)
        if value >= 0:
            return decode_hex('{:x}'.format(value).zfill(size // 4))
        else:
            return decode_hex('{:x}'.format((1 << size) + value))

    msg = b''
    for arg in args:
        assert arg
        if isinstance(arg, bytes):
            msg += arg
        elif isinstance(arg, str):
            if is_0x_prefixed(arg):
                msg += decode_hex(arg)
            else:
                msg += arg.encode()
        elif isinstance(arg, int):
            msg += format_int(arg, 256)
        elif isinstance(arg, tuple):
            msg += format_int(arg[0], arg[1])
        else:
            raise ValueError('Unsupported type: {}.'.format(type(arg)))

    return msg
Exemple #9
0
def to_hex(value):
    """
    Auto converts any supported value into it's hex representation.
    """
    if is_boolean(value):
        return "0x1" if value else "0x0"

    if is_dict(value):
        return encode_hex(json.dumps(value, sort_keys=True))

    if is_string(value):
        if is_prefixed(value, '-0x'):
            return from_decimal(value)
        elif is_0x_prefixed(value):
            return value
        else:
            return encode_hex(value)

    if is_integer(value):
        return from_decimal(value)

    raise TypeError(
        "Unsupported type: '{0}'.  Must be one of Boolean, Dictionary, String, "
        "or Integer.".format(repr(type(value)))
    )
Exemple #10
0
def to_int(value):
    if is_0x_prefixed(value):
        if len(value) == 2:
            return 0
        else:
            return int(value, 16)
    else:
        return int(value)
def test_initcode_simple_contract(runner):
    result = runner.invoke(main, "initcode OtherContract -d testcontracts")
    print(result.output)
    assert result.exit_code == 0

    transaction_hash = result.output.splitlines()[-1]

    assert is_hex(transaction_hash)
    assert is_0x_prefixed(transaction_hash)
Exemple #12
0
def is_ens_name(value):
    if not isinstance(value, str):
        return False
    elif is_hex_address(value):
        return False
    elif is_0x_prefixed(value) and is_hex(value):
        return False
    else:
        return ENS.is_valid_name(value)
Exemple #13
0
def is_ens_name(value):
    if not isinstance(value, str):
        return False
    elif is_hex_address(value):
        return False
    elif is_0x_prefixed(value) and is_hex(value):
        return False
    else:
        return ENS.is_valid_name(value)
def test_initcode_with_constructor_argument(runner, key_password):
    result = runner.invoke(main,
                           "initcode TestContract 123456 -d testcontracts",
                           input=key_password)
    assert result.exit_code == 0

    transaction_hash = result.output.splitlines()[-1]

    assert is_hex(transaction_hash)
    assert is_0x_prefixed(transaction_hash)
Exemple #15
0
def from_decimal(value):
    """
    Converts numeric value to its hex representation
    """
    if is_string(value):
        if is_0x_prefixed(value) or _is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)

    return to_hex(value)
Exemple #16
0
def validate_abi_value(abi_type, value):
    """
    Helper function for validating a value against the expected abi_type
    Note: abi_type 'bytes' must either be python3 'bytes' object or ''
    """
    if is_array_type(abi_type) and is_list_like(value):
        # validate length
        specified_length = length_of_array_type(abi_type)
        if specified_length is not None:
            if specified_length < 1:
                raise TypeError(
                    "Invalid abi-type: {abi_type}. Length of fixed sized arrays"
                    "must be greater than 0."
                    .format(abi_type=abi_type)
                )
            if specified_length != len(value):
                raise TypeError(
                    "The following array length does not the length specified"
                    "by the abi-type, {abi_type}: {value}"
                    .format(abi_type=abi_type, value=value)
                )

        # validate sub_types
        sub_type = sub_type_of_array_type(abi_type)
        for v in value:
            validate_abi_value(sub_type, v)
        return
    elif is_bool_type(abi_type) and is_boolean(value):
        return
    elif is_uint_type(abi_type) and is_integer(value) and value >= 0:
        return
    elif is_int_type(abi_type) and is_integer(value):
        return
    elif is_address_type(abi_type):
        validate_address(value)
        return
    elif is_bytes_type(abi_type):
        if sys.version_info.major >= 3 and is_bytes(value):
            return
        elif is_string(value):
            if is_0x_prefixed(value):
                return
            else:
                raise TypeError(
                    "ABI values of abi-type 'bytes' must be either"
                    "a python3 'bytes' object or an '0x' prefixed string."
                )
    elif is_string_type(abi_type) and is_string(value):
        return

    raise TypeError(
        "The following abi value is not a '{abi_type}': {value}"
        .format(abi_type=abi_type, value=value)
    )
Exemple #17
0
def validate_abi_value(abi_type: TypeStr, value: Any) -> None:
    """
    Helper function for validating a value against the expected abi_type
    Note: abi_type 'bytes' must either be python3 'bytes' object or ''
    """
    if is_array_type(abi_type) and is_list_like(value):
        # validate length
        specified_length = length_of_array_type(abi_type)
        if specified_length is not None:
            if specified_length < 1:
                raise TypeError(
                    "Invalid abi-type: {abi_type}. Length of fixed sized arrays"
                    "must be greater than 0."
                    .format(abi_type=abi_type)
                )
            if specified_length != len(value):
                raise TypeError(
                    "The following array length does not the length specified"
                    "by the abi-type, {abi_type}: {value}"
                    .format(abi_type=abi_type, value=value)
                )

        # validate sub_types
        sub_type = sub_type_of_array_type(abi_type)
        for v in value:
            validate_abi_value(sub_type, v)
        return
    elif is_bool_type(abi_type) and is_boolean(value):
        return
    elif is_uint_type(abi_type) and is_integer(value) and value >= 0:
        return
    elif is_int_type(abi_type) and is_integer(value):
        return
    elif is_address_type(abi_type):
        validate_address(value)
        return
    elif is_bytes_type(abi_type):
        if is_bytes(value):
            return
        elif is_string(value):
            if is_0x_prefixed(value):
                return
            else:
                raise TypeError(
                    "ABI values of abi-type 'bytes' must be either"
                    "a python3 'bytes' object or an '0x' prefixed string."
                )
    elif is_string_type(abi_type) and is_string(value):
        return

    raise TypeError(
        "The following abi value is not a '{abi_type}': {value}"
        .format(abi_type=abi_type, value=value)
    )
Exemple #18
0
def to_int(value):
    """
    Robust to integer conversion, handling hex values, string representations,
    and special cases like `0x`.
    """
    if is_0x_prefixed(value):
        if len(value) == 2:
            return 0
        else:
            return int(value, 16)
    else:
        return int(value)
Exemple #19
0
def to_int(value):
    """
    Robust to integer conversion, handling hex values, string representations,
    and special cases like `0x`.
    """
    if is_0x_prefixed(value):
        if len(value) == 2:
            return 0
        else:
            return int(value, 16)
    else:
        return int(value)
Exemple #20
0
    def to_python(self, value):
        if not is_0x_prefixed(value):
            raise InvalidEndpoint('Not a valid hex address, 0x prefix missing.')

        if not is_checksum_address(value):
            raise InvalidEndpoint('Not a valid EIP55 encoded address.')

        try:
            value = to_canonical_address(value)
        except ValueError:
            raise InvalidEndpoint('Could not decode hex.')

        return value
Exemple #21
0
    def _deserialize(self, value, attr, data, **kwargs):  # pylint: disable=unused-argument
        if not is_0x_prefixed(value):
            self.fail("missing_prefix")

        try:
            value = to_bytes(hexstr=value)
        except binascii.Error:
            self.fail("invalid_data")

        if len(value) != SECRETHASH_LENGTH:
            self.fail("invalid_size")

        return value
Exemple #22
0
def to_decimal(value):
    """
    Converts value to it's decimal representation in string
    """
    if is_string(value):
        if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)
    else:
        value = int(value)

    return value
Exemple #23
0
def to_decimal(value):
    """
    Converts value to it's decimal representation in string
    """
    if is_string(value):
        if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)
    else:
        value = int(value)

    return value
Exemple #24
0
    def to_python(value):
        if not is_0x_prefixed(value):
            raise InvalidEndpoint("Not a valid hex address, 0x prefix missing.")

        if not is_checksum_address(value):
            raise InvalidEndpoint("Not a valid EIP55 encoded address.")

        try:
            value = to_canonical_address(value)
        except ValueError:
            raise InvalidEndpoint("Could not decode hex.")

        return value
Exemple #25
0
    def to_python(self, value):  # pylint: disable=no-self-use
        if not is_0x_prefixed(value):
            raise InvalidEndpoint('Not a valid hex address, 0x prefix missing.')

        if not is_checksum_address(value):
            raise InvalidEndpoint('Not a valid EIP55 encoded address.')

        try:
            value = to_canonical_address(value)
        except ValueError:
            raise InvalidEndpoint('Could not decode hex.')

        return value
Exemple #26
0
def address_checksum_and_decode(addr: str) -> Address:
    """ Accepts a string address and turns it into binary.

        Makes sure that the string address provided starts is 0x prefixed and
        checksummed according to EIP55 specification
    """
    if not is_0x_prefixed(addr):
        raise InvalidChecksummedAddress("Address must be 0x prefixed")

    if not is_checksum_address(addr):
        raise InvalidChecksummedAddress("Address must be EIP55 checksummed")

    return to_canonical_address(addr)
Exemple #27
0
def deserialize_address_helper(self, value, attr, data):  # pylint: disable=unused-argument
    if not is_0x_prefixed(value):
        self.fail("missing_prefix")

    if not is_checksum_address(value):
        self.fail("invalid_checksum")
    try:
        value = to_canonical_address(value)
    except ValueError:
        self.fail("invalid_data")
    if len(value) != 20:
        self.fail("invalid_size")
    return value
Exemple #28
0
def from_decimal(value):
    """
    Converts numeric value to it's hex representation
    """
    if is_string(value):
        if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)

    # python2 longs end up with an `L` hanging off the end of their hexidecimal
    # representation.
    result = hex(value).rstrip('L')
    return result
def test_send_transaction_to_contract_find_duplicated_function_by_argument_length(
        runner, test_contract_address, test_contract_name):
    result = runner.invoke(
        main,
        (f"transact -d testcontracts --jsonrpc test --gas-price 1 --contract-address {test_contract_address} "
         f"-- {test_contract_name} duplicatedDifferentArgumentLength 1"),
    )

    assert result.exit_code == 0

    transaction_hash = result.output.splitlines()[-1]

    assert is_hex(transaction_hash)
    assert is_0x_prefixed(transaction_hash)
def test_send_transaction_to_contract(runner, test_contract_address,
                                      test_contract_name):
    result = runner.invoke(
        main,
        (f"transact -d testcontracts --jsonrpc test --gas-price 1 --contract-address {test_contract_address} "
         f"-- {test_contract_name} set 1"),
    )

    assert result.exit_code == 0

    transaction_hash = result.output.splitlines()[-1]

    assert is_hex(transaction_hash)
    assert is_0x_prefixed(transaction_hash)
Exemple #31
0
def normalize_int(value):
    """
    Robust to integer conversion, handling hex values, string representations,
    and special cases like `0x`.
    """
    if is_bytes(value):
        return big_endian_to_int(value)
    if is_hex(value) and is_0x_prefixed(value):
        if len(value) == 2:
            return 0
        else:
            return int(value, 16)
    else:
        return int(value)
Exemple #32
0
def from_decimal(value):
    """
    Converts numeric value to it's hex representation
    """
    if is_string(value):
        if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)

    # python2 longs end up with an `L` hanging off the end of their hexidecimal
    # representation.
    result = hex(value).rstrip('L')
    return result
Exemple #33
0
def address_checksum_and_decode(addr: str) -> typing.Address:
    """ Accepts a string address and turns it into binary.

        Makes sure that the string address provided starts is 0x prefixed and
        checksummed according to EIP55 specification
    """
    if not is_0x_prefixed(addr):
        raise InvalidAddress('Address must be 0x prefixed')

    if not is_checksum_address(addr):
        raise InvalidAddress('Address must be EIP55 checksummed')

    addr_bytes = decode_hex(addr)
    assert len(addr_bytes) in (20, 0)
    return typing.Address(addr_bytes)
 def first_pass_check_byte(cls, single_param, param_name, param_type, conversion_errors):
     error_flag = False
     if eth_utils.is_0x_prefixed(single_param):
         pc = eth_utils.remove_0x_prefix(single_param)
         pc_to_bytes = bytes.fromhex(pc)
         ret = pc_to_bytes
     else:
         try:
             ret = single_param.encode('utf-8')
         except:
             conversion_errors[param_name] = "Expected type: {0}. Supplied argument not a valid byte object.".format(
                 param_type)
             error_flag = True
             ret = "".encode('utf-8')
     return (ret, error_flag)
Exemple #35
0
def address_checksum_and_decode(addr: str) -> Address:
    """ Accepts a string address and turns it into binary.

        Makes sure that the string address provided starts is 0x prefixed and
        checksummed according to EIP55 specification
    """
    if not is_0x_prefixed(addr):
        raise InvalidAddress("Address must be 0x prefixed")

    if not is_checksum_address(addr):
        raise InvalidAddress("Address must be EIP55 checksummed")

    addr_bytes = decode_hex(addr)
    assert len(addr_bytes) in (20, 0)
    return Address(addr_bytes)
Exemple #36
0
def inputPostFormatter(post):
    """
    Formats the input of a whisper post and converts all values to HEX
    """

    post["ttl"] = from_decimal(post["ttl"])
    post["workToProve"] = from_decimal(post.get("workToProve", 0))
    post["priority"] = from_decimal(post["priority"])

    if not is_list_like(post.get("topics")):
        post["topics"] = [post["topics"]] if post.get("topics") else []

    post["topics"] = [topic if is_0x_prefixed(topic) else encode_hex(topic)
                      for topic in post["topics"]]

    return post
def test_send_transaction_to_contract_with_array_address_arguments(
        runner, compiled_contracts_path, test_contract_address,
        test_contract_name):
    argument = f"{test_contract_address},{test_contract_address}"
    result = runner.invoke(
        main,
        (f"transact --compiled-contracts {compiled_contracts_path} "
         f"--jsonrpc test --gas-price 1 --contract-address {test_contract_address} "
         f"-- {test_contract_name} functionWithArrayArgument {argument}"),
    )
    assert result.exit_code == 0

    transaction_hash = result.output.splitlines()[-1]

    assert is_hex(transaction_hash)
    assert is_0x_prefixed(transaction_hash)
Exemple #38
0
    def _deserialize(self, value, attr, data):
        if not is_0x_prefixed(value):
            self.fail('missing_prefix')

        if not is_checksum_address(value):
            self.fail('invalid_checksum')

        try:
            value = to_canonical_address(value)
        except ValueError:
            self.fail('invalid_data')

        if len(value) != 20:
            self.fail('invalid_size')

        return value
Exemple #39
0
    def _deserialize(self, value, attr, data):
        if not is_0x_prefixed(value):
            self.fail('missing_prefix')

        if not is_checksum_address(value):
            self.fail('invalid_checksum')

        try:
            value = to_canonical_address(value)
        except ValueError:
            self.fail('invalid_data')

        if len(value) != 20:
            self.fail('invalid_size')

        return value
Exemple #40
0
def test_send_transaction_to_contract_from_compiled_contracts(
    runner, test_contract_address, test_contract_name, compiled_contracts_path
):
    result = runner.invoke(
        main,
        (
            f"transact --compiled-contracts {compiled_contracts_path} "
            f"--jsonrpc test --contract-address {test_contract_address} "
            f"-- {test_contract_name} set 1"
        ),
    )
    assert result.exit_code == 0

    transaction_hash = result.output.splitlines()[-1]

    assert is_hex(transaction_hash)
    assert is_0x_prefixed(transaction_hash)
Exemple #41
0
def eth_call(to, sig, data="0x"):
    if not is_0x_prefixed(sig):
        sig = to_hex(function_signature_to_4byte_selector(sig))
    if isinstance(data, bytes):
        data = to_hex(data)
    return requests.post(
        BASE_URL,
        json={
            "jsonrpc": "2.0",
            "method": "eth_call",
            "params": [{
                "to": to,
                "data": sig + data[2:]
            }, "latest"],
            "id": 12,
        },
    ).json()["result"]
Exemple #42
0
def data_decoder(data: str) -> bytes:
    assert is_0x_prefixed(data)
    data = decode_hex(data)
    return data