def validate_abi(abi):
    """
    Helper function for validating an ABI
    """
    if not is_list_like(abi):
        raise ValueError("'abi' is not a list")

    if not all(is_dict(e) for e in abi):
        raise ValueError("'abi' is not a list of dictionaries")

    functions = filter_by_type('function', abi)
    selectors = groupby(compose(encode_hex, function_abi_to_4byte_selector),
                        functions)
    duplicates = valfilter(lambda funcs: len(funcs) > 1, selectors)
    if duplicates:
        raise ValueError('Abi contains functions with colliding selectors. '
                         'Functions {0}'.format(
                             _prepare_selector_collision_msg(duplicates)))
Exemplo n.º 2
0
    def sign_and_send_raw_middleware(make_request, w3):

        format_and_fill_tx = compose(format_transaction,
                                     fill_transaction_defaults(w3),
                                     fill_nonce(w3))

        def middleware(method, params):
            if method != "platon_sendTransaction":
                return make_request(method, params)
            else:
                transaction = format_and_fill_tx(params[0])

            if 'from' not in transaction:
                return make_request(method, params)
            elif transaction.get('from') not in accounts:
                return make_request(method, params)

            account = accounts[transaction['from']]
            raw_tx = account.signTransaction(transaction).rawTransaction

            return make_request("platon_sendRawTransaction", [raw_tx])

        return middleware
Exemplo n.º 3
0
from client_sdk_python.utils.transactions import (
    fill_nonce,
    fill_transaction_defaults,
)

from .abi import (
    STANDARD_NORMALIZERS, )

to_hexstr_from_eth_key = operator.methodcaller('to_hex')


def is_eth_key(value):
    return isinstance(value, PrivateKey)


key_normalizer = compose(
    apply_formatter_if(is_eth_key, to_hexstr_from_eth_key), )


@to_dict
def gen_normalized_accounts(val):
    if isinstance(val, (
            list,
            tuple,
            set,
    )):
        for i in val:
            account = to_account(i)
            yield account.address, account
    else:
        account = to_account(val)
        yield account.address, account
Exemplo n.º 4
0
SYNCING_FORMATTERS = {
    'startingBlock': to_integer_if_hex,
    'currentBlock': to_integer_if_hex,
    'highestBlock': to_integer_if_hex,
    'knownStates': to_integer_if_hex,
    'pulledStates': to_integer_if_hex,
}


syncing_formatter = apply_formatters_to_dict(SYNCING_FORMATTERS)


TRANSACTION_POOL_CONTENT_FORMATTERS = {
    'pending': compose(
        keymap(to_ascii_if_bytes),
        valmap(transaction_formatter),
    ),
    'queued': compose(
        keymap(to_ascii_if_bytes),
        valmap(transaction_formatter),
    ),
}


transaction_pool_content_formatter = apply_formatters_to_dict(
    TRANSACTION_POOL_CONTENT_FORMATTERS
)


TRANSACTION_POOL_INSPECT_FORMATTERS = {
    'pending': keymap(to_ascii_if_bytes),
Exemplo n.º 5
0

def is_testrpc_available():
    try:
        import testrpc  # noqa: F401
        return True
    except ImportError:
        return False


to_integer_if_hex = apply_formatter_if(is_string, hex_to_integer)


TRANSACTION_FORMATTERS = {
    'to': apply_formatter_if(
        compose(complement(bool), decode_hex),
        static_return(None),
    ),
}


def ethtestrpc_string_middleware(make_request, web3):
    def middleware(method, params):
        return valmap(to_text, make_request(method, params))
    return middleware


ethtestrpc_middleware = construct_formatting_middleware(
    request_formatters={
        'eth_uninstallFilter': apply_formatter_at_index(to_integer_if_hex, 0),
        'eth_getFilterChanges': apply_formatter_at_index(to_integer_if_hex, 0),
Exemplo n.º 6
0
from eth_utils.curried import (
    apply_formatters_to_dict,
    apply_key_map,
)
from hexbytes import (
    HexBytes, )

from client_sdk_python.middleware.formatting import (
    construct_formatting_middleware, )
from client_sdk_python.utils.toolz import (
    compose, )

remap_geth_poa_fields = apply_key_map({
    'extraData': 'proofOfAuthorityData',
})

pythonic_geth_poa = apply_formatters_to_dict({
    'proofOfAuthorityData': HexBytes,
})

geth_poa_cleanup = compose(pythonic_geth_poa, remap_geth_poa_fields)

geth_poa_middleware = construct_formatting_middleware(result_formatters={
    'platon_getBlockByHash':
    geth_poa_cleanup,
    'platon_getBlockByNumber':
    geth_poa_cleanup,
}, )
Exemplo n.º 7
0
def apply_formatters_to_args(*formatters):
    return compose(*(apply_formatter_at_index(formatter, index)
                     for index, formatter in enumerate(formatters)))
Exemplo n.º 8
0
def chain_id_validator(web3):
    return compose(apply_formatter_at_index(transaction_normalizer, 0),
                   transaction_param_validator(web3))
Exemplo n.º 9
0
        eth_tester.unlock_account(transaction['from'], password)
        transaction_hash = eth_tester.send_transaction(transaction)
    finally:
        eth_tester.lock_account(transaction['from'])

    return transaction_hash


API_ENDPOINTS = {
    'web3': {
        'clientVersion':
        client_version,
        'sha3':
        compose(
            encode_hex,
            keccak,
            decode_hex,
            without_eth_tester(operator.itemgetter(0)),
        ),
    },
    'net': {
        'version': not_implemented,
        'peerCount': not_implemented,
        'listening': not_implemented,
    },
    'eth': {
        'protocolVersion':
        not_implemented,
        'syncing':
        not_implemented,
        'coinbase':
        compose(
Exemplo n.º 10
0
    event_data = {
        'args': event_args,
        'event': event_abi['name'],
        'logIndex': log_entry['logIndex'],
        'transactionIndex': log_entry['transactionIndex'],
        'transactionHash': log_entry['transactionHash'],
        'address': log_entry['address'],
        'blockHash': log_entry['blockHash'],
        'blockNumber': log_entry['blockNumber'],
    }

    return AttributeDict.recursive(event_data)


@to_tuple
def pop_singlets(seq):
    yield from (i[0] if is_list_like(i) and len(i) == 1 else i for i in seq)


@curry
def remove_trailing_from_seq(seq, remove_value=None):
    index = len(seq)
    while index > 0 and seq[index - 1] == remove_value:
        index -= 1
    return seq[:index]


normalize_topic_list = compose(
    remove_trailing_from_seq(remove_value=None),
    pop_singlets,)
Exemplo n.º 11
0
TRANSACTION_PARAMS_MAPPING = {
    'gasPrice': 'gas_price',
}

transaction_params_remapper = apply_key_map(TRANSACTION_PARAMS_MAPPING)

TRANSACTION_PARAMS_FORMATTERS = {
    'gas': to_integer_if_hex,
    'gasPrice': to_integer_if_hex,
    'value': to_integer_if_hex,
    # 'nonce': to_integer_if_hex,
}

transaction_params_formatter = compose(
    # remove nonce for now due to issue https://github.com/ethereum/eth-tester/issues/80
    remove_key_if('nonce', lambda _: True),
    apply_formatters_to_dict(TRANSACTION_PARAMS_FORMATTERS),
)

FILTER_PARAMS_MAPPINGS = {
    'fromBlock': 'from_block',
    'toBlock': 'to_block',
}

filter_params_remapper = apply_key_map(FILTER_PARAMS_MAPPINGS)

FILTER_PARAMS_FORMATTERS = {
    'fromBlock': to_integer_if_hex,
    'toBlock': to_integer_if_hex,
}
Exemplo n.º 12
0
    try:
        eth_tester.unlock_account(transaction['from'], password)
        transaction_hash = eth_tester.send_transaction(transaction)
    finally:
        eth_tester.lock_account(transaction['from'])

    return transaction_hash


API_ENDPOINTS = {
    'web3': {
        'clientVersion': client_version,
        'sha3': compose(
            encode_hex,
            keccak,
            decode_hex,
            without_eth_tester(operator.itemgetter(0)),
        ),
    },
    'net': {
        'version': not_implemented,
        'peerCount': not_implemented,
        'listening': not_implemented,
    },
    'eth': {
        'protocolVersion': not_implemented,
        'syncing': not_implemented,
        'coinbase': compose(
            operator.itemgetter(0),
            call_eth_tester('get_accounts'),
        ),
]


@pytest.fixture()
def string_contract(web3, StringContract, address_conversion_func):
    deploy_txn = StringContract.constructor("Caqalai").transact()
    deploy_receipt = web3.eth.waitForTransactionReceipt(deploy_txn)
    assert deploy_receipt is not None
    contract_address = address_conversion_func(deploy_receipt['contractAddress'])
    contract = StringContract(address=contract_address)
    assert contract.address == contract_address
    assert len(web3.eth.getCode(contract.address)) > 0
    return contract


map_repr = compose(list, curry(map, repr))


@pytest.mark.parametrize(
    'method,args,repr_func,expected',
    (
        (
            'all_functions',
            (),
            map_repr,
            [
                '<Function blockHashAmphithyronVersify(uint256)>',
                '<Function identity(uint256,bool)>',
                '<Function identity(int256,bool)>'
            ]
        ),