Example #1
0
def construct_event_topic_set(event_abi, arguments=None):
    if arguments is None:
        arguments = {}
    if isinstance(arguments, (list, tuple)):
        if len(arguments) != len(event_abi['inputs']):
            raise ValueError(
                "When passing an argument list, the number of arguments must "
                "match the event constructor.")
        arguments = {
            arg['name']: [arg_value]
            for arg, arg_value in zip(event_abi['inputs'], arguments)
        }

    normalized_args = {
        key: value if is_list_like(value) else [value]
        for key, value in arguments.items()
    }

    event_topic = encode_hex(event_abi_to_log_topic(event_abi))
    indexed_args = get_indexed_event_inputs(event_abi)
    zipped_abi_and_args = [(arg, normalized_args.get(arg['name'], [None]))
                           for arg in indexed_args]
    encoded_args = [[
        None if option is None else encode_hex(
            encode_single(arg['type'], option)) for option in arg_options
    ] for arg, arg_options in zipped_abi_and_args]

    topics = list(normalize_topic_list([event_topic] + encoded_args))
    return topics
def _generate_random_private_key():
    """
    WARNING: This is not a secure way to generate private keys and should only
    be used for testing purposes.
    """
    return encode_hex(
        bytes(bytearray((random.randint(0, 255) for _ in range(32)))))
Example #3
0
def construct_event_data_set(event_abi, arguments=None):
    if arguments is None:
        arguments = {}
    if isinstance(arguments, (list, tuple)):
        if len(arguments) != len(event_abi['inputs']):
            raise ValueError(
                "When passing an argument list, the number of arguments must "
                "match the event constructor.")
        arguments = {
            arg['name']: [arg_value]
            for arg, arg_value in zip(event_abi['inputs'], arguments)
        }

    normalized_args = {
        key: value if is_list_like(value) else [value]
        for key, value in arguments.items()
    }

    non_indexed_args = exclude_indexed_event_inputs(event_abi)
    zipped_abi_and_args = [(arg, normalized_args.get(arg['name'], [None]))
                           for arg in non_indexed_args]
    encoded_args = [[
        None if option is None else encode_hex(
            encode_single(arg['type'], option)) for option in arg_options
    ] for arg, arg_options in zipped_abi_and_args]

    data = [
        list(permutation) if any(value is not None
                                 for value in permutation) else []
        for permutation in itertools.product(*encoded_args)
    ]
    return data
Example #4
0
def hex_encode_abi_type(abi_type, value, force_size=None):
    """
    Encodes value into a hex string in format of abi_type
    """
    validate_abi_type(abi_type)
    validate_abi_value(abi_type, value)

    data_size = force_size or size_of_type(abi_type)
    if is_array_type(abi_type):
        sub_type = sub_type_of_array_type(abi_type)
        return "".join([
            remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256))
            for v in value
        ])
    elif is_bool_type(abi_type):
        return to_hex_with_size(value, data_size)
    elif is_uint_type(abi_type):
        return to_hex_with_size(value, data_size)
    elif is_int_type(abi_type):
        return to_hex_twos_compliment(value, data_size)
    elif is_address_type(abi_type):
        return pad_hex(value, data_size)
    elif is_bytes_type(abi_type):
        if is_bytes(value):
            return encode_hex(value)
        else:
            return value
    elif is_string_type(abi_type):
        return to_hex(text=value)
    else:
        raise ValueError("Unsupported ABI type: {0}".format(abi_type))
Example #5
0
def to_4byte_hex(hex_or_str_or_bytes):
    size_of_4bytes = 4 * 8
    byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes)
    if len(byte_str) > 4:
        raise ValueError('expected value of size 4 bytes. Got: %d bytes' %
                         len(byte_str))
    hex_str = encode_hex(byte_str)
    return pad_hex(hex_str, size_of_4bytes)
Example #6
0
def validate_compressed_public_key_bytes(value: Any) -> None:
    validate_bytes(value)
    validate_bytes_length(value, 33, "compressed public key")
    first_byte = value[0:1]
    if first_byte not in (b"\x02", b"\x03"):
        raise ValidationError(
            "Unexpected compressed public key format: Must start with 0x02 or 0x03, but starts "
            "with {first_byte}".format(first_byte=encode_hex(first_byte), ))
Example #7
0
def test_contract_constructor_encoding_encoding(
        WithConstructorArgumentsContract, bytes_arg):
    deploy_data = WithConstructorArgumentsContract._encode_constructor_data(
        [1234, bytes_arg])
    encoded_args = '0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000'  # noqa: E501
    expected_ending = encode_hex(
        encode_abi(['uint256', 'bytes32'], [1234, b'abcd']))
    assert expected_ending == encoded_args
    assert deploy_data.endswith(remove_0x_prefix(expected_ending))
Example #8
0
def get_function_info(fn_name,
                      contract_abi=None,
                      fn_abi=None,
                      args=None,
                      kwargs=None):
    if args is None:
        args = tuple()
    if kwargs is None:
        kwargs = {}

    if fn_abi is None:
        fn_abi = find_matching_fn_abi(contract_abi, fn_name, args, kwargs)

    fn_selector = encode_hex(function_abi_to_4byte_selector(fn_abi))

    fn_arguments = merge_args_and_kwargs(fn_abi, args, kwargs)

    return fn_abi, fn_selector, fn_arguments
def encode_hex_no_prefix(value):
    return remove_0x_prefix(encode_hex(value))
Example #10
0
def get_fallback_function_info(contract_abi=None, fn_abi=None):
    if fn_abi is None:
        fn_abi = get_fallback_func_abi(contract_abi)
    fn_selector = encode_hex(b'')
    fn_arguments = tuple()
    return fn_abi, fn_selector, fn_arguments
Example #11
0
def encode_abi(web3, abi, arguments, vmtype, data=None, setabi=None):
    arguments = list(arguments)
    if vmtype == 1:
        inputlength = len(abi['inputs'])
        if inputlength == len(arguments):
            if arguments:
                arrinputs = abi['inputs']
                paramabi = encodeparameters(arrinputs, arguments, setabi)
            else:
                paramabi = []
        else:
            raise Exception(
                'The number of arguments is not matching the methods required number.'
                'You need to pass {} arguments.'.format(inputlength))
        magicnum = ['00', '61', '73', '6d']
        paramabi.insert(0, fnv1_64(bytes(abi['name'], 'utf8')))
        if abi['type'] == 'constructor':
            if data:
                data1 = bytes.fromhex(str(data, encoding='utf8'))
                deploydata = rlp.encode([data1, rlp.encode(paramabi)])
                encodata = ''.join(magicnum) + deploydata.hex()
                return '0x' + encodata
            else:
                return '0x' + rlp.encode(paramabi).hex()
        else:
            encodata = rlp.encode(paramabi).hex()
            return '0x' + encodata

    else:
        argument_types = get_abi_input_types(abi)
        for j in range(len(argument_types)):
            if argument_types[j]:
                if argument_types[j] == 'address':
                    hrpgot, data1 = bech32.decode(arguments[j][:3],
                                                  arguments[j])
                    addr = to_checksum_address(bytes(data1))
                    arguments[j] = addr  # .split(",")
                elif argument_types[j] == 'address[]':
                    for i in range(len(arguments[j])):
                        hrpgot, data1 = bech32.decode(arguments[j][i][:3],
                                                      arguments[j][i])
                        addr = to_checksum_address(bytes(data1))
                        arguments[j][i] = addr

        if not check_if_arguments_can_be_encoded(abi, arguments, {}):
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type.  Expected types are: {0}".format(
                    ', '.join(argument_types), ))

        try:
            normalizers = [
                abi_ens_resolver(web3),
                abi_address_to_hex,
                abi_bytes_to_bytes,
                abi_string_to_text,
            ]
            normalized_arguments = map_abi_data(
                normalizers,
                argument_types,
                arguments,
            )
            encoded_arguments = eth_abi_encode_abi(
                argument_types,
                normalized_arguments,
            )
        except EncodingError as e:
            raise TypeError(
                "One or more arguments could not be encoded to the necessary "
                "ABI type: {0}".format(str(e)))

        if data:
            return to_hex(HexBytes(data) + encoded_arguments)
        else:
            return encode_hex(encoded_arguments)
class LogTopics:
    LogAnonymous = encode_hex(event_signature_to_log_topic("LogAnonymous()"))
    LogNoArguments = encode_hex(
        event_signature_to_log_topic("LogNoArguments()"))
    LogSingleArg = encode_hex(
        event_signature_to_log_topic("LogSingleArg(uint256)"))
    LogSingleAnonymous = encode_hex(
        event_signature_to_log_topic("LogSingleAnonymous(uint256)"))
    LogSingleWithIndex = encode_hex(
        event_signature_to_log_topic("LogSingleWithIndex(uint256)"))
    LogDoubleArg = encode_hex(
        event_signature_to_log_topic("LogDoubleArg(uint256,uint256)"))
    LogDoubleAnonymous = encode_hex(
        event_signature_to_log_topic(
            "LogDoubleAnonymous(uint256,uint256)"))  # noqa: E501
    LogDoubleWithIndex = encode_hex(
        event_signature_to_log_topic(
            "LogDoubleWithIndex(uint256,uint256)"))  # noqa: E501
    LogTripleArg = encode_hex(
        event_signature_to_log_topic("LogTripleArg(uint256,uint256,uint256)"))
    LogTripleWithIndex = encode_hex(
        event_signature_to_log_topic(
            "LogTripleWithIndex(uint256,uint256,uint256)"))  # noqa: E501
    LogQuadrupleArg = encode_hex(
        event_signature_to_log_topic(
            "LogQuadrupleArg(uint256,uint256,uint256,uint256)"))  # noqa: E501
    LogQuadrupleWithIndex = encode_hex(
        event_signature_to_log_topic(
            "LogQuadrupleWithIndex(uint256,uint256,uint256,uint256)")
    )  # noqa: E501
    LogBytes = encode_hex(event_signature_to_log_topic("LogBytes(bytes)"))
    LogString = encode_hex(event_signature_to_log_topic("LogString(string)"))
    LogDynamicArgs = encode_hex(
        event_signature_to_log_topic("LogDynamicArgs(string,string)"))
    LogListArgs = encode_hex(
        event_signature_to_log_topic("LogListArgs(bytes2[],bytes2[])"))
    LogAddressIndexed = encode_hex(
        event_signature_to_log_topic("LogAddressIndexed(address,address)"))
    LogAddressNotIndexed = encode_hex(
        event_signature_to_log_topic("LogAddressNotIndexed(address,address)"))
Example #13
0
 def to_hex(self) -> str:
     return encode_hex(self.to_bytes())