예제 #1
0
파일: signing.py 프로젝트: miohtama/web3.py
    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 != "eth_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(
                "eth_sendRawTransaction",
                [raw_tx])

        return middleware
예제 #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 != "eth_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.hex()

            return make_request(
                "eth_sendRawTransaction",
                [raw_tx])

        return middleware
예제 #3
0
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))
        )
예제 #4
0
 def factory(cls, *args, **kwargs):
     return compose(cls, Contract.factory(*args, **kwargs))
예제 #5
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': static_return('1'),
        'peerCount': static_return(0),
        'listening': static_return(False),
    },
    'eth': {
        'protocolVersion': static_return(63),
        'syncing': static_return(False),
        'coinbase': compose(
            operator.itemgetter(0),
            call_eth_tester('get_accounts'),
        ),
예제 #6
0
def apply_formatters_to_args(*formatters):
    return compose(*(
        apply_formatter_at_index(formatter, index)
        for index, formatter
        in enumerate(formatters)
    ))
예제 #7
0
파일: signing.py 프로젝트: miohtama/web3.py
    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
        return

예제 #8
0
파일: events.py 프로젝트: ymcareer/web3.py
@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,
)


def is_indexed(arg):
    if isinstance(arg, TopicArgumentFilter) is True:
        return True
    return False


is_not_indexed = complement(is_indexed)


class EventFilterBuilder:
    formatter = None
    _fromBlock = None
예제 #9
0
from eth_utils.curried import (
    apply_formatters_to_dict,
    apply_key_map,
)
from hexbytes import (
    HexBytes, )

from web3._utils.toolz import (
    compose, )
from web3.middleware.formatting import (
    construct_formatting_middleware, )

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={
    'eth_getBlockByHash':
    geth_poa_cleanup,
    'eth_getBlockByNumber':
    geth_poa_cleanup,
}, )

@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)>'
        ]),
        ('get_function_by_signature', ('identity(uint256,bool)', ), repr,
         '<Function identity(uint256,bool)>'),
        ('find_functions_by_name', ('identity', ), map_repr, [
            '<Function identity(uint256,bool)>',
            '<Function identity(int256,bool)>'
예제 #11
0
    apply_formatters_to_dict,
    apply_key_map,
)
from hexbytes import (
    HexBytes,
)

from web3._utils.toolz import (
    compose,
)
from web3.middleware.formatting import (
    construct_formatting_middleware,
)

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={
        'eth_getBlockByHash': geth_poa_cleanup,
        'eth_getBlockByNumber': geth_poa_cleanup,
    },
)
예제 #12
0
파일: tester.py 프로젝트: whoerau/web3.py

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),
예제 #13
0

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,
}
예제 #14
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'),
        ),
예제 #15
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),
예제 #16
0
def chain_id_validator(web3):
    return compose(
        apply_formatter_at_index(transaction_normalizer, 0),
        transaction_param_validator(web3)
    )
예제 #17
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': static_return('1'),
        'peerCount': static_return(0),
        'listening': static_return(False),
    },
    'eth': {
        'protocolVersion':
        static_return(63),
        'syncing':
        static_return(False),
        'coinbase':
        compose(
예제 #18
0
파일: events.py 프로젝트: miohtama/web3.py
@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,)


def is_indexed(arg):
    if isinstance(arg, TopicArgumentFilter) is True:
        return True
    return False


is_not_indexed = complement(is_indexed)


class EventFilterBuilder:
    formatter = None
    _fromBlock = None
예제 #19
0
파일: tester.py 프로젝트: miohtama/web3.py

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),
예제 #20
0
 def factory(cls, *args, **kwargs):
     return compose(cls, Contract.factory(*args, **kwargs))
예제 #21
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,
}
예제 #22
0
from web3._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
예제 #23
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),