Exemplo n.º 1
0
    from web3 import Web3  # noqa: F401
    from web3.module import Module  # noqa: F401
    from web3.eth import Eth  # noqa: F401


def bytes_to_ascii(value: bytes) -> str:
    return codecs.decode(value, 'ascii')


to_ascii_if_bytes = apply_formatter_if(is_bytes, bytes_to_ascii)
to_integer_if_hex = apply_formatter_if(is_string, hex_to_integer)
to_hex_if_integer = apply_formatter_if(is_integer, integer_to_hex)

is_false = partial(operator.is_, False)

is_not_false = complement(is_false)
is_not_null = complement(is_null)


@curry
def to_hexbytes(num_bytes: int,
                val: Union[str, int, bytes],
                variable_length: bool = False) -> HexBytes:
    if isinstance(val, (str, int, bytes)):
        result = HexBytes(val)
    else:
        raise TypeError("Cannot convert %r to HexBytes" % val)

    extra_bytes = len(result) - num_bytes
    if extra_bytes == 0 or (variable_length and extra_bytes < 0):
        return result
Exemplo n.º 2
0
    complement,
    compose,
    curry,
    dissoc,
)
from hexbytes import (
    HexBytes, )

from web3.exceptions import (
    ValidationError, )
from web3.middleware.formatting import (
    construct_web3_formatting_middleware, )

MAX_EXTRADATA_LENGTH = 32

is_not_null = complement(is_null)


@curry
def validate_chain_id(web3, chain_id):
    if int(chain_id) == web3.eth.chainId:
        return chain_id
    else:
        raise ValidationError("The transaction declared chain ID %r, "
                              "but the connected node is on %r" % (
                                  chain_id,
                                  web3.eth.chainId,
                              ))


def check_extradata_length(val):
Exemplo n.º 3
0
        index -= 1
    return seq[:index]


normalize_topic_list = compose(
    remove_trailing_from_seq(remove_value=None),
    pop_singlets,)


def is_indexed(arg: Any) -> bool:
    if isinstance(arg, TopicArgumentFilter) is True:
        return True
    return False


is_not_indexed = complement(is_indexed)


class EventFilterBuilder:
    formatter = None
    _fromBlock = None
    _toBlock = None
    _address = None
    _immutable = False

    def __init__(
        self, event_abi: ABIEvent, abi_codec: ABICodec, formatter: EventData=None
    ) -> None:
        self.event_abi = event_abi
        self.abi_codec = abi_codec
        self.formatter = formatter
Exemplo n.º 4
0
    q = TaskQueue(order_fn=order_fn)

    # this just needs to not crash, when testing sortability
    await wait(q.add((1, )))


@pytest.mark.asyncio
@pytest.mark.parametrize(
    'order_fn',
    (
        # a basic object is not sortable
        lambda x: object(),
        # If comparison rules create an invalid result (like an element not equal to itself), crash.
        # The following are subclasses of SortableInt that have an intentionally broken comparitor:
        type('invalid_eq', (SortableInt, ),
             dict(__eq__=curry(complement(SortableInt.__eq__)))),
        type('invalid_lt', (SortableInt, ),
             dict(__lt__=curry(complement(SortableInt.__lt__)))),
        type('invalid_gt', (SortableInt, ),
             dict(__gt__=curry(complement(SortableInt.__gt__)))),
    ),
)
async def test_invalid_priority_order(order_fn):
    q = TaskQueue(order_fn=order_fn)

    with pytest.raises(ValidationError):
        await wait(q.add((1, )))


@pytest.mark.asyncio
async def test_cannot_add_single_non_tuple_task():
Exemplo n.º 5
0
    from web3 import (  # noqa: F401
        Web3,
    )


def is_named_block(value: Any) -> bool:
    return value in {"latest", "earliest", "pending"}


def is_hexstr(value: Any) -> bool:
    return is_string(value) and is_hex(value)


to_integer_if_hex = apply_formatter_if(is_hexstr, hex_to_integer)

is_not_named_block = complement(is_named_block)


# --- Request Mapping --- #

TRANSACTION_REQUEST_KEY_MAPPING = {
    'gasPrice': 'gas_price',
    'maxFeePerGas': 'max_fee_per_gas',
    'maxPriorityFeePerGas': 'max_priority_fee_per_gas',
    'accessList': 'access_list',
}
transaction_request_remapper = apply_key_map(TRANSACTION_REQUEST_KEY_MAPPING)


TRANSACTION_REQUEST_FORMATTERS = {
    'gas': to_integer_if_hex,
Exemplo n.º 6
0
        self.data_filter_set = data_filter_set
        if any(data_filter_set):
            self.data_filter_set_function = match_fn(self.eth_module.codec,
                                                     data_filter_set)

    def is_valid_entry(self, entry: LogReceipt) -> bool:
        if not self.data_filter_set:
            return True
        return bool(self.data_filter_set_function(entry['data']))


def decode_utf8_bytes(value: bytes) -> str:
    return value.decode("utf-8")


not_text = complement(is_text)
normalize_to_text = apply_formatter_if(not_text, decode_utf8_bytes)


def normalize_data_values(type_string: TypeStr, data_value: Any) -> Any:
    """Decodes utf-8 bytes to strings for abi string values.

    eth-abi v1 returns utf-8 bytes for string values.
    This can be removed once eth-abi v2 is required.
    """
    _type = parse_type_string(type_string)
    if _type.base == "string":
        if _type.arrlist is not None:
            return tuple((normalize_to_text(value) for value in data_value))
        else:
            return normalize_to_text(data_value)
Exemplo n.º 7
0
from .formatting import (
    construct_formatting_middleware, )


def bytes_to_ascii(value):
    return codecs.decode(value, 'ascii')


to_ascii_if_bytes = apply_formatter_if(is_bytes, bytes_to_ascii)
to_integer_if_hex = apply_formatter_if(is_string, hex_to_integer)
block_number_formatter = apply_formatter_if(is_integer, integer_to_hex)

is_false = partial(operator.is_, False)

is_not_false = complement(is_false)
is_not_null = complement(is_null)


@curry
def to_hexbytes(num_bytes, val, variable_length=False):
    if isinstance(val, (str, int, bytes)):
        result = HexBytes(val)
    else:
        raise TypeError("Cannot convert %r to HexBytes" % val)

    extra_bytes = len(result) - num_bytes
    if extra_bytes == 0 or (variable_length and extra_bytes < 0):
        return result
    elif all(byte == 0 for byte in result[:extra_bytes]):
        return HexBytes(result[extra_bytes:])
async def test_valid_priority_order(order_fn):
    q = TaskQueue(order_fn=order_fn)

    # this just needs to not crash, when testing sortability
    await wait(q.add((1, )))


@pytest.mark.asyncio
@pytest.mark.parametrize(
    'order_fn',
    (
        # a basic object is not sortable
        lambda x: object(),
        # If comparison rules create an invalid result (like an element not equal to itself), crash.
        # The following are subclasses of SortableInt that have an intentionally broken comparitor:
        type('invalid_eq', (SortableInt, ), dict(__eq__=curry(complement(SortableInt.__eq__)))),
        type('invalid_lt', (SortableInt, ), dict(__lt__=curry(complement(SortableInt.__lt__)))),
        type('invalid_gt', (SortableInt, ), dict(__gt__=curry(complement(SortableInt.__gt__)))),
    ),
)
async def test_invalid_priority_order(order_fn):
    q = TaskQueue(order_fn=order_fn)

    with pytest.raises(ValidationError):
        await wait(q.add((1, )))


@pytest.mark.asyncio
async def test_cannot_add_single_non_tuple_task():
    q = TaskQueue()
    with pytest.raises(ValidationError):
    stream = ContextFramesBytesIO(stream_bytes)

    decoder = StringDecoder()

    if len(padded_bytes) < ceil32(len(_strings.encode("utf-8"))):
        with pytest.raises(InsufficientDataBytes):
            decoder(stream)
        return

    decoded_value = decoder(stream)
    assert decoded_value == _strings


@settings(max_examples=250)
@given(
    _bytes=st.binary(min_size=0, max_size=256).filter(complement(is_utf8_decodable)),
    pad_size=st.integers(min_value=0, max_value=32),
)
def test_decode_strings_raises(_bytes, pad_size):
    size_bytes = zpad32(int_to_big_endian(len(_bytes)))
    padded_bytes = _bytes + b'\x00' * pad_size
    stream_bytes = size_bytes + padded_bytes
    stream = ContextFramesBytesIO(stream_bytes)

    decoder = StringDecoder()

    if len(padded_bytes) < ceil32(len(_bytes)):
        with pytest.raises(InsufficientDataBytes):
            decoder(stream)
        return
Exemplo n.º 10
0
    decoder = StringDecoder()

    if len(padded_bytes) < ceil32(len(_strings.encode("utf-8"))):
        with pytest.raises(InsufficientDataBytes):
            decoder(stream)
        return

    decoded_value = decoder(stream)
    assert decoded_value == _strings


@settings(max_examples=250)
@given(
    _bytes=st.binary(min_size=0,
                     max_size=256).filter(complement(is_utf8_decodable)),
    pad_size=st.integers(min_value=0, max_value=32),
)
def test_decode_strings_raises(_bytes, pad_size):
    size_bytes = zpad32(int_to_big_endian(len(_bytes)))
    padded_bytes = _bytes + b'\x00' * pad_size
    stream_bytes = size_bytes + padded_bytes
    stream = ContextFramesBytesIO(stream_bytes)

    decoder = StringDecoder()

    if len(padded_bytes) < ceil32(len(_bytes)):
        with pytest.raises(InsufficientDataBytes):
            decoder(stream)
        return