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 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))
Beispiel #2
0
 def filter(self, filter_params=None, filter_id=None):
     if filter_id and filter_params:
         raise TypeError(
             "Ambiguous invocation: provide either a `filter_params` or a `filter_id` argument. "
             "Both were supplied.")
     if is_string(filter_params):
         if filter_params == "latest":
             filter_id = self.web3.manager.request_blocking(
                 "platon_newBlockFilter",
                 [],
             )
             return BlockFilter(self.web3, filter_id)
         elif filter_params == "pending":
             filter_id = self.web3.manager.request_blocking(
                 "platon_newPendingTransactionFilter",
                 [],
             )
             return TransactionFilter(self.web3, filter_id)
         else:
             raise ValueError(
                 "The filter API only accepts the values of `pending` or "
                 "`latest` for string based filters")
     elif isinstance(filter_params, dict):
         _filter_id = self.web3.manager.request_blocking(
             "platon_newFilter",
             [filter_params],
         )
         return LogFilter(self.web3, _filter_id)
     elif filter_id and not filter_params:
         return LogFilter(self.web3, filter_id)
     else:
         raise TypeError(
             "Must provide either filter_params as a string or "
             "a valid filter object, or a filter_id as a string "
             "or hex.")
Beispiel #3
0
    def test_eth_uninstallFilter(self, web3):
        filter = web3.eth.filter({})
        assert is_string(filter.filter_id)

        success = web3.eth.uninstallFilter(filter.filter_id)
        assert success is True

        failure = web3.eth.uninstallFilter(filter.filter_id)
        assert failure is False
Beispiel #4
0
    def validate(iban_address):
        if not is_string(iban_address):
            return False

        if re.match(r"^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$", iban_address) and \
                mod9710(iso13616Prepare(iban_address)) == 1:
            return True

        return False
def is_hex_encoded_block_number(value):
    if not is_string(value):
        return False
    elif is_hex_encoded_block_hash(value):
        return False
    try:
        value_as_int = int(value, 16)
    except ValueError:
        return False
    return 0 <= value_as_int < 2**256
def construct_event_filter_params(event_abi,
                                  contract_address=None,
                                  argument_filters=None,
                                  topics=None,
                                  fromBlock=None,
                                  toBlock=None,
                                  address=None):
    filter_params = {}
    topic_set = construct_event_topic_set(event_abi, argument_filters)

    if topics is not None:
        if len(topic_set) > 1:
            raise TypeError(
                "Merging the topics argument with topics generated "
                "from argument_filters is not supported.")
        topic_set = topics

    if len(topic_set) == 1 and is_list_like(topic_set[0]):
        filter_params['topics'] = topic_set[0]
    else:
        filter_params['topics'] = topic_set

    if address and contract_address:
        if is_list_like(address):
            filter_params['address'] = address + [contract_address]
        elif is_string(address):
            filter_params['address'] = [address, contract_address]
        else:
            raise ValueError(
                "Unsupported type for `address` parameter: {0}".format(
                    type(address)))
    elif address:
        filter_params['address'] = address
    elif contract_address:
        filter_params['address'] = contract_address

    if 'address' not in filter_params:
        pass
    elif is_list_like(filter_params['address']):
        for addr in filter_params['address']:
            validate_address(addr)
    else:
        validate_address(filter_params['address'])

    if fromBlock is not None:
        filter_params['fromBlock'] = fromBlock

    if toBlock is not None:
        filter_params['toBlock'] = toBlock

    data_filters_set = construct_event_data_set(event_abi, argument_filters)

    return data_filters_set, filter_params
def normalize_keys(keyfile_json):
    for key, value in keyfile_json.items():
        if is_string(key):
            norm_key = key.lower()
        else:
            norm_key = key

        if is_dict(value):
            norm_value = normalize_keys(value)
        else:
            norm_value = value

        yield norm_key, norm_value
def map_collection(func, collection):
    '''
    Apply func to each element of a collection, or value of a dictionary.
    If the value is not a collection, return it unmodified
    '''
    datatype = type(collection)
    if isinstance(collection, Mapping):
        return datatype((key, func(val)) for key, val in collection.items())
    if is_string(collection):
        return collection
    elif isinstance(collection, Iterable):
        return datatype(map(func, collection))
    else:
        return collection
Beispiel #9
0
 def test_eth_call_with_0_result(self, web3, math_contract):
     coinbase = web3.eth.coinbase
     txn_params = math_contract._prepare_transaction(
         fn_name='add',
         fn_args=(0, 0),
         transaction={
             'from': coinbase,
             'to': math_contract.address
         },
     )
     call_result = web3.eth.call(txn_params)
     assert is_string(call_result)
     result = decode_single('uint256', call_result)
     assert result == 0
Beispiel #10
0
    def test_eth_newPendingTransactionFilter(self, web3):
        filter = web3.eth.filter('pending')
        assert is_string(filter.filter_id)

        changes = web3.eth.getFilterChanges(filter.filter_id)
        assert is_list_like(changes)
        assert not changes

        # TODO: figure out why this fails in go-ethereum
        # logs = web3.eth.getFilterLogs(filter.filter_id)
        # assert is_list_like(logs)
        # assert not logs

        result = web3.eth.uninstallFilter(filter.filter_id)
        assert result is True
Beispiel #11
0
    def __init__(self,
                 backend: 'Union[BaseECCBackend, Type[BaseECCBackend], str, None]' = None,
                 ) -> None:
        from client_sdk_python.packages.platon_keys.backends.base import (  # noqa: F811
            BaseECCBackend,
        )

        if backend is None:
            pass
        elif isinstance(backend, BaseECCBackend):
            pass
        elif isinstance(backend, type) and issubclass(backend, BaseECCBackend):
            backend = backend()
        elif is_string(backend):
            backend = self.get_backend(backend)
        else:
            raise ValueError(
                "Unsupported format for ECC backend.  Must be an instance or "
                "subclass of `platon_keys.backends.BaseECCBackend` or a string of "
                "the dot-separated import path for the desired backend class"
            )

        self.backend = backend
Beispiel #12
0
    def test_net_version(self, web3):
        version = web3.net.version

        assert is_string(version)
        assert version.isdigit()
def is_hex_encoded_block_hash(value):
    if not is_string(value):
        return False
    return len(remove_0x_prefix(value)) == 64 and is_hex(value)
def load_keyfile(path_or_file_obj):
    if is_string(path_or_file_obj):
        with open(path_or_file_obj) as keyfile_file:
            return json.load(keyfile_file)
    else:
        return json.load(path_or_file_obj)
def is_array_of_strings(value):
    if not is_list_like(value):
        return False
    return all((is_string(item) for item in value))
Beispiel #16
0
    def test_eth_protocolVersion(self, web3):
        protocol_version = web3.version.ethereum

        assert is_string(protocol_version)
        assert protocol_version.isdigit()
def is_hexstr(value):
    return is_string(value) and is_hex(value)