def test_transacting_with_contract_respects_explicit_gas(web3,
                                                         STRING_CONTRACT,
                                                         skip_if_testrpc,
                                                         wait_for_block,
                                                         call,
                                                         transact):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.constructor("Caqalai").transact()
    deploy_receipt = web3.eth.waitForTransactionReceipt(deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = transact(contract=string_contract,
                        contract_function='setValue',
                        func_args=[to_bytes(text="ÄLÄMÖLÖ")],
                        tx_kwargs={'gas': 200000})
    txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash, 30)
    assert txn_receipt is not None

    final_value = call(contract=string_contract,
                       contract_function='getValue')
    assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == 200000
def test_auto_gas_computation_when_transacting(web3,
                                               STRING_CONTRACT,
                                               skip_if_testrpc,
                                               wait_for_block,
                                               call,
                                               transact):
    skip_if_testrpc(web3)

    wait_for_block(web3)

    StringContract = web3.eth.contract(**STRING_CONTRACT)

    deploy_txn = StringContract.constructor("Caqalai").transact()
    deploy_receipt = web3.eth.waitForTransactionReceipt(deploy_txn, 30)
    assert deploy_receipt is not None
    string_contract = StringContract(address=deploy_receipt['contractAddress'])

    gas_estimate = string_contract.functions.setValue(to_bytes(text="ÄLÄMÖLÖ")).estimateGas()

    # eth_abi will pass as raw bytes, no encoding
    # unless we encode ourselves
    txn_hash = transact(contract=string_contract,
                        contract_function="setValue",
                        func_args=[to_bytes(text="ÄLÄMÖLÖ")])
    txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash, 30)
    assert txn_receipt is not None

    final_value = call(contract=string_contract,
                       contract_function='getValue')
    assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ")

    txn = web3.eth.getTransaction(txn_hash)
    assert txn['gas'] == gas_estimate + 100000
Esempio n. 3
0
def generate_cache_key(value):
    """
    Generates a cache key for the *args and **kwargs
    """
    if is_bytes(value):
        return hashlib.md5(value).hexdigest()
    elif is_text(value):
        return generate_cache_key(to_bytes(text=value))
    elif is_boolean(value) or is_null(value) or is_number(value):
        return generate_cache_key(repr(value))
    elif is_dict(value):
        return generate_cache_key((
            (key, value[key])
            for key
            in sorted(value.keys())
        ))
    elif is_list_like(value) or isinstance(value, Generator):
        return generate_cache_key("".join((
            generate_cache_key(item)
            for item
            in value
        )))
    else:
        raise TypeError("Cannot generate cache key for value {0} of type {1}".format(
            value,
            type(value),
        ))
Esempio n. 4
0
def is_encodable(_type, value):
    try:
        base, sub, arrlist = _type
    except ValueError:
        base, sub, arrlist = process_type(_type)

    if arrlist:
        if not is_list_like(value):
            return False
        if arrlist[-1] and len(value) != arrlist[-1][0]:
            return False
        sub_type = (base, sub, arrlist[:-1])
        return all(is_encodable(sub_type, sub_value) for sub_value in value)
    elif base == 'address' and is_ens_name(value):
        # ENS names can be used anywhere an address is needed
        # Web3.py will resolve the name to an address before encoding it
        return True
    elif base == 'bytes' and isinstance(value, str):
        # Hex-encoded bytes values can be used anywhere a bytes value is needed
        if is_hex(value) and len(value) % 2 == 0:
            # Require hex-encoding of full bytes (even length)
            bytes_val = to_bytes(hexstr=value)
            return eth_abi_is_encodable(_type, bytes_val)
        else:
            return False
    elif base == 'string' and isinstance(value, bytes):
        # bytes that were encoded with utf-8 can be used anywhere a string is needed
        try:
            string_val = to_text(value)
        except UnicodeDecodeError:
            return False
        else:
            return eth_abi_is_encodable(_type, string_val)
    else:
        return eth_abi_is_encodable(_type, value)
Esempio n. 5
0
 def encode_rpc_request(self, method, params):
     rpc_dict = {
         "jsonrpc": "2.0",
         "method": method,
         "params": params or [],
         "id": next(self.request_counter),
     }
     encoded = FriendlyJsonSerde().json_encode(rpc_dict)
     return to_bytes(text=encoded)
Esempio n. 6
0
def defunct_hash_message(primitive=None, hexstr=None, text=None):
    '''
    Convert the provided message into a message hash, to be signed.
    This provides the same prefix and hashing approach as
    :meth:`w3.eth.sign() <web3.eth.Eth.sign>`. That means that the
    message will automatically be prepended with text
    defined in EIP-191 as version 'E': ``b'\\x19awake006 Signed Message:\\n'``
    concatenated with the number of bytes in the message.

    Awkwardly, the number of bytes in the message is encoded in decimal ascii. So
    if the message is 'abcde', then the length is encoded as the ascii
    character '5'. This is one of the reasons that this message format is not preferred.
    There is ambiguity when the message '00' is encoded, for example.
    Only use this method if you must have compatibility with
    :meth:`w3.eth.sign() <web3.eth.Eth.sign>`.

    Supply exactly one of the three arguments:
    bytes, a hex string, or a unicode string.

    :param primitive: the binary message to be signed
    :type primitive: bytes or int
    :param str hexstr: the message encoded as hex
    :param str text: the message as a series of unicode characters (a normal Py3 str)
    :returns: The hash of the message, after adding the prefix
    :rtype: ~hexbytes.main.HexBytes

    .. code-block:: python

        >>> from client_sdk_python.packages.platon_account.messages import defunct_hash_message

        >>> msg = "I♥SF"
        >>> defunct_hash_message(text=msg)
        HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750')

        # these four also produce the same hash:
        >>> defunct_hash_message(w3.toBytes(text=msg))
        HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750')

        >>> defunct_hash_message(bytes(msg, encoding='utf-8'))
        HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750')

        >>> Web3.toHex(text=msg)
        '0x49e299a55346'
        >>> defunct_hash_message(hexstr='0x49e299a55346')
        HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750')

        >>> defunct_hash_message(0x49e299a55346)
        HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750')
    '''
    message_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
    recovery_hasher = compose(HexBytes, keccak, signature_wrapper)
    return recovery_hasher(message_bytes)
Esempio n. 7
0
def sign_message_hash(key, msg_hash, mode='ECDSA'):
    if mode == 'ECDSA':
        signature = key.sign_msg_hash(msg_hash)
        (v_raw, r, s) = signature.vrs
    elif mode == 'SM':
        privatekey = key.to_bytes()
        SMC = sm2.CryptSM2(privatekey.hex(), 1)
        rand = func.random_hex(SMC.para_len)
        (r, s, v_raw) = SMC.sign(msg_hash, rand)

    v = to_eth_v(v_raw)
    eth_signature_bytes = to_bytes32(r) + to_bytes32(s) + to_bytes(v)
    return (v, r, s, eth_signature_bytes)
Esempio n. 8
0
def hex_to_bytes(s):
    return to_bytes(hexstr=s)
Esempio n. 9
0
    construct_sign_and_send_raw_middleware,
)
from client_sdk_python.middleware.signing import (
    gen_normalized_accounts, )
from client_sdk_python.providers import (
    BaseProvider, )
from client_sdk_python.providers.eth_tester import (
    EthereumTesterProvider, )
from client_sdk_python.utils.toolz import (
    identity,
    merge,
    valfilter,
)

PRIVATE_KEY_1 = to_bytes(
    hexstr='0x6a8b4de52b288e111c14e1c4b868bc125d325d40331d86d875a3467dd44bf829'
)

ADDRESS_1 = '0x634743b15C948820069a43f6B361D03EfbBBE5a8'

PRIVATE_KEY_2 = to_bytes(
    hexstr='0xbf963e13b164c2100795f53e5590010f76b7a91b5a78de8e2b97239c8cfca8e8'
)

ADDRESS_2 = '0x91eD14b5956DBcc1310E65DC4d7E82f02B95BA46'

KEY_FUNCS = (
    eth_keys.keys.PrivateKey,
    eth_account.Account.privateKeyToAccount,
    HexBytes,
    to_hex,
import pytest
from unittest.mock import (
    Mock,
)

from client_sdk_python.packages.eth_utils import (
    to_bytes,
)

ABI = [{}]
ADDRESS = '0xd3CdA913deB6f67967B99D67aCDFa1712C293601'
BYTES_ADDRESS = to_bytes(hexstr=ADDRESS)
NON_CHECKSUM_ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'


@pytest.mark.parametrize(
    'args,kwargs,expected',
    (
        ((ADDRESS,), {}, None),
        ((BYTES_ADDRESS,), {}, None),
        ((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
        ((NON_CHECKSUM_ADDRESS,), {}, ValueError),
        ((), {'address': ADDRESS}, None),
        ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
        ((), {'address': NON_CHECKSUM_ADDRESS}, ValueError),
    )
)
def test_contract_address_validation(web3, args, kwargs, expected):
    if isinstance(expected, type) and issubclass(expected, Exception):
        with pytest.raises(expected):
Esempio n. 11
0
    ens.setup_address(name, TEST_ADDRESS)
    assert is_same_address(ens.address(name), TEST_ADDRESS)
    assert is_same_address(ens.address(equivalent), TEST_ADDRESS)

    ens.setup_address(name, None)
    assert ens.address(name) is None


@pytest.mark.parametrize(
    'set_address',
    [
        # since the test uses getTransactionCount,
        # using a same address converted to bytes and hex will error with same count,
        # use two different addresses of each type (hex, bytes)
        "0x000000000000000000000000000000000000dEaD",
        to_bytes(hexstr="0x5B2063246F2191f18F2675ceDB8b28102e957458"),
        EMPTY_ADDR_HEX,
        None,
        '',
    ],
)
def test_set_address_noop(ens, set_address):
    eth = ens.web3.eth
    owner = ens.owner('tester.eth')
    ens.setup_address('noop.tester.eth', set_address)
    starting_transactions = eth.getTransactionCount(owner)

    # do not issue transaction if address is already set
    ens.setup_address('noop.tester.eth', set_address)
    assert eth.getTransactionCount(owner) == starting_transactions
Esempio n. 12
0
def to_standard_signature_bytes(awake006_signature_bytes,mode='ECDSA'):
    rs = awake006_signature_bytes[:-1]
    v = to_int(awake006_signature_bytes[-1])
    standard_v = to_standard_v(v,mode)
    return rs + to_bytes(standard_v)
Esempio n. 13
0
def to_standard_signature_bytes(awake006_signature_bytes):
    rs = awake006_signature_bytes[:-1]
    v = to_int(awake006_signature_bytes[-1])
    standard_v = to_standard_v(v)
    return rs + to_bytes(standard_v)
Esempio n. 14
0
def sign_message_hash(key, msg_hash):
    signature = key.sign_msg_hash(msg_hash)
    (v_raw, r, s) = signature.vrs
    v = to_eth_v(v_raw)
    eth_signature_bytes = to_bytes32(r) + to_bytes32(s) + to_bytes(v)
    return (v, r, s, eth_signature_bytes)