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))
Example #2
0
    def test_eth_syncing(self, web3):
        syncing = web3.eth.syncing

        assert is_boolean(syncing) or is_dict(syncing)

        if is_boolean(syncing):
            assert syncing is False
        elif is_dict(syncing):
            assert 'startingBlock' in syncing
            assert 'currentBlock' in syncing
            assert 'highestBlock' in syncing

            assert is_integer(syncing['startingBlock'])
            assert is_integer(syncing['currentBlock'])
            assert is_integer(syncing['highestBlock'])
Example #3
0
    def inject(self, element, name=None, layer=None):
        '''
        Inject a named element to an arbitrary layer in the onion.

        The current implementation only supports insertion at the innermost layer,
        or at the outermost layer. Note that inserting to the outermost is equivalent
        to calling :meth:`add` .
        '''
        if not is_integer(layer):
            raise TypeError("The layer for insertion must be an int.")
        elif layer != 0 and layer != len(self._queue):
            raise NotImplementedError(
                "You can only insert to the beginning or end of a %s, currently. "
                "You tried to insert to %d, but only 0 and %d are permitted. " % (
                    type(self),
                    layer,
                    len(self._queue),
                )
            )

        self.add(element, name=name)

        if layer == 0:
            if name is None:
                name = element
            self._queue.move_to_end(name, last=False)
        elif layer == len(self._queue):
            return
        else:
            raise AssertionError("Impossible to reach: earlier validation raises an error")
Example #4
0
    def test_eth_getBlockTransactionCountByNumber_block_with_txn(
            self, web3, block_with_txn):
        transaction_count = web3.eth.getBlockTransactionCount(
            block_with_txn['number'])

        assert is_integer(transaction_count)
        assert transaction_count >= 1
Example #5
0
    def test_eth_getBlockTransactionCountByNumber_empty_block(
            self, web3, empty_block):
        transaction_count = web3.eth.getBlockTransactionCount(
            empty_block['number'])

        assert is_integer(transaction_count)
        assert transaction_count == 0
Example #6
0
 def test_eth_estimateGas(self, web3, unlocked_account_dual_type):
     gas_estimate = web3.eth.estimateGas({
         'from': unlocked_account_dual_type,
         'to': unlocked_account_dual_type,
         'value': 1,
     })
     assert is_integer(gas_estimate)
     assert gas_estimate > 0
Example #7
0
    def test_eth_getBalance(self, web3):
        coinbase = web3.eth.coinbase

        with pytest.raises(InvalidAddress):
            web3.eth.getBalance(coinbase.lower())

        balance = web3.eth.getBalance(coinbase)

        assert is_integer(balance)
        assert balance >= 0
Example #8
0
def test_implicitcontract_call_default(math_contract, get_transaction_count):
    # When a function is called that defaults to call
    blocknum, starting_txns = get_transaction_count("pending")
    start_count = math_contract.counter()
    assert is_integer(start_count)
    # Check that a call was made and not a transact
    # (Auto-mining is enabled, so query by block number)
    assert get_transaction_count(blocknum) == starting_txns
    # Check that no blocks were mined
    assert get_transaction_count("pending") == (blocknum, 0)
Example #9
0
def test_implicitcontract_transact_default(web3, math_contract,
                                           get_transaction_count):
    # Use to verify correct operation later on
    start_count = math_contract.counter()
    assert is_integer(start_count)  # Verify correct type
    # When a function is called that defaults to transact
    blocknum, starting_txns = get_transaction_count("pending")
    math_contract.increment(transact={})
    # Check that a transaction was made and not a call
    assert math_contract.counter() - start_count == 1
    # (Auto-mining is enabled, so query by block number)
    assert get_transaction_count(blocknum) == starting_txns + 1
    # Check that only one block was mined
    assert get_transaction_count("pending") == (blocknum + 1, 0)
Example #10
0
def test_implicitcontract_transact_override(math_contract,
                                            get_transaction_count):
    # Use to verify correct operation later on
    start_count = math_contract.counter()
    assert is_integer(start_count)  # Verify correct type
    # When a function is called with call override that defaults to transact
    blocknum, starting_txns = get_transaction_count("pending")
    math_contract.increment(call={})
    # Check that a call was made and not a transact
    assert math_contract.counter() - start_count == 0
    # (Auto-mining is enabled, so query by block number)
    assert get_transaction_count(blocknum) == starting_txns
    # Check that no blocks were mined
    assert get_transaction_count("pending") == (blocknum, 0)
Example #11
0
def is_predefined_block_number(value):
    if is_text(value):
        value_text = value
    elif is_bytes(value):
        # `value` could either be random bytes or the utf-8 encoding of
        # one of the words in: {"latest", "pending", "earliest"}
        # We cannot decode the bytes as utf8, because random bytes likely won't be valid.
        # So we speculatively decode as 'latin-1', which cannot fail.
        value_text = value.decode('latin-1')
    elif is_integer(value):
        return False
    else:
        raise TypeError("unrecognized block reference: %r" % value)

    return value_text in {"latest", "pending", "earliest"}
Example #12
0
def to_text(primitive=None, hexstr=None, text=None):
    assert_one_val(primitive, hexstr=hexstr, text=text)

    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):
        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 or hexstr.")
Example #13
0
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
    if is_predefined_block_number(value):
        return if_predefined
    elif isinstance(value, bytes):
        return if_hash
    elif is_hex_encoded_block_hash(value):
        return if_hash
    elif is_integer(value) and (0 <= value < 2**256):
        return if_number
    elif is_hex_encoded_block_number(value):
        return if_number
    else:
        raise ValueError(
            "Value did not match any of the recognized block identifiers: {0}".format(value)
        )
Example #14
0
def to_bytes(primitive=None, hexstr=None, text=None):
    assert_one_val(primitive, hexstr=hexstr, text=text)

    if is_boolean(primitive):
        return b'\x01' if primitive else b'\x00'
    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:
            hexstr = '0x0' + remove_0x_prefix(hexstr)
        return decode_hex(hexstr)
    elif text is not None:
        return text.encode('utf-8')
    raise TypeError(
        "expected an int in first arg, or keyword of hexstr or text")
        def _get_block_by_number(method, params, block_info=_block_info):
            block_id = params[0]
            blocks = block_info['blocks']
            head_block_number = block_info['head_block_number']

            if block_id == 'latest':
                return blocks[head_block_number]
            elif block_id == 'pending':
                if head_block_number + 1 >= len(blocks):
                    raise ValueError("no pending block")
                return blocks[head_block_number + 1]
            elif block_id == 'earliest':
                return blocks[0]
            elif is_integer(block_id):
                if block_id <= head_block_number:
                    return blocks[block_id]
                else:
                    return None
            else:
                raise TypeError('Invalid type for block_id')
Example #16
0
    def test_net_peerCount(self, web3):
        peer_count = web3.net.peerCount

        assert is_integer(peer_count)
Example #17
0
    def test_eth_getUncleCountByBlockNumber(self, web3, empty_block):
        uncle_count = web3.eth.getUncleCount(empty_block['number'])

        assert is_integer(uncle_count)
        assert uncle_count == 0
Example #18
0
 def test_eth_hashrate(self, web3):
     hashrate = web3.eth.hashrate
     assert is_integer(hashrate)
     assert hashrate >= 0
Example #19
0
 def test_eth_gasPrice(self, web3):
     gas_price = web3.eth.gasPrice
     assert is_integer(gas_price)
     assert gas_price > 0
Example #20
0
 def test_eth_blockNumber(self, web3):
     block_number = web3.eth.blockNumber
     assert is_integer(block_number)
     assert block_number >= 0
Example #21
0
 def test_eth_getTransactionCount(self, web3, unlocked_account_dual_type):
     transaction_count = web3.eth.getTransactionCount(
         unlocked_account_dual_type)
     assert is_integer(transaction_count)
     assert transaction_count >= 0
Example #22
0
def validate_integer(value: Any) -> None:
    if not is_integer(value) or isinstance(value, bool):
        raise ValidationError("Value must be a an integer.  Got: {0}".format(
            type(value)))