Exemplo n.º 1
0
def init_web3(providers=default):
    from newchain_web3 import Web3

    if providers is default:
        w3 = Web3(ens=None)
    else:
        w3 = Web3(providers, ens=None)

    return customize_web3(w3)
Exemplo n.º 2
0
def setup_w3():
    genesis_overrides = {"gas_limit": 5500000}
    custom_genesis_params = PyEVMBackend._generate_genesis_params(
        overrides=genesis_overrides)
    pyevm_backend = PyEVMBackend(genesis_parameters=custom_genesis_params)
    t = EthereumTester(backend=pyevm_backend)
    w3 = Web3(Web3.EthereumTesterProvider(ethereum_tester=t))
    w3.eth.defaultAccount = w3.eth.accounts[0]
    w3.eth.defaultContractFactory = LinkableContract
    w3.enable_unstable_package_management_api()
    return w3
Exemplo n.º 3
0
    def test_solidityKeccak_ens(self, web3, types, values, expected):
        with ens_addresses(web3, {
            'one.eth': "0x49EdDD3769c0712032808D86597B84ac5c2F5614",
            'two.eth': "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5",
        }):
            # when called as class method, any name lookup attempt will fail
            with pytest.raises(InvalidAddress):
                Web3.solidityKeccak(types, values)

            # when called as instance method, ens lookups can succeed
            actual = web3.solidityKeccak(types, values)
            assert actual == expected
def generate_go_ethereum_fixture(destination_dir):
    with contextlib.ExitStack() as stack:
        datadir = stack.enter_context(tempdir())

        keystore_dir = os.path.join(datadir, 'keystore')
        ensure_path_exists(keystore_dir)
        keyfile_path = os.path.join(keystore_dir, KEYFILE_FILENAME)
        with open(keyfile_path, 'w') as keyfile:
            keyfile.write(KEYFILE_DATA)
        genesis_file_path = os.path.join(datadir, 'genesis.json')
        with open(genesis_file_path, 'w') as genesis_file:
            genesis_file.write(json.dumps(GENESIS_DATA))

        geth_ipc_path_dir = stack.enter_context(tempdir())
        geth_ipc_path = os.path.join(geth_ipc_path_dir, 'geth.ipc')

        geth_port = get_open_port()
        geth_binary = get_geth_binary()

        with get_geth_process(geth_binary=geth_binary,
                              datadir=datadir,
                              genesis_file_path=genesis_file_path,
                              geth_ipc_path=geth_ipc_path,
                              geth_port=geth_port):

            wait_for_socket(geth_ipc_path)
            web3 = Web3(Web3.IPCProvider(geth_ipc_path))
            chain_data = setup_chain_state(web3)
            # close geth by exiting context
            # must be closed before copying data dir
            verify_chain_state(web3, chain_data)

        # verify that chain state is still valid after closing
        # and re-opening geth
        with get_geth_process(geth_binary=geth_binary,
                              datadir=datadir,
                              genesis_file_path=genesis_file_path,
                              geth_ipc_path=geth_ipc_path,
                              geth_port=geth_port):

            wait_for_socket(geth_ipc_path)
            web3 = Web3(Web3.IPCProvider(geth_ipc_path))
            verify_chain_state(web3, chain_data)

        static_data = {
            'raw_txn_account': RAW_TXN_ACCOUNT,
            'keyfile_pw': KEYFILE_PW,
        }
        config = merge(chain_data, static_data)
        pprint.pprint(config)
        write_config_json(config, datadir)

        shutil.copytree(datadir, destination_dir)
def test_isConnected_disconnected():
    """
    Web3.isConnected() returns False when configured with a provider
    that's not connected to a node.
    """
    web3 = Web3(DisconnectedProvider())
    assert web3.isConnected() is False
Exemplo n.º 6
0
def web3(request):
    use_filter_middleware = request.param
    provider = EthereumTesterProvider()
    w3 = Web3(provider)
    if use_filter_middleware:
        w3.middleware_onion.add(local_filter_middleware)
    return w3
def w3(open_port, start_websocket_server):
    # need new event loop as the one used by server is already running
    event_loop = asyncio.new_event_loop()
    endpoint_uri = 'ws://127.0.0.1:{}'.format(open_port)
    event_loop.run_until_complete(wait_for_ws(endpoint_uri, event_loop))
    provider = WebsocketProvider(endpoint_uri, websocket_timeout=0.01)
    return Web3(provider)
Exemplo n.º 8
0
def balance(address, rpc):
    """Get the balance of the address"""
    web3 = Web3(HTTPProvider(rpc))
    a = web3.toChecksumAddress(address)
    balance_wei = web3.eth.getBalance(a)
    b = web3.fromWei(balance_wei, 'ether')
    print("The balance of {} is {} NEW.".format(a, b))
Exemplo n.º 9
0
def test_auto_provider_none():
    # init without provider succeeds, even when no provider available
    w3 = Web3()

    # non-node requests succeed
    w3.toHex(0) == '0x0'

    type(w3.provider) == AutoProvider
Exemplo n.º 10
0
def test_labelhash(ens, label, expected_hash):
    if isinstance(expected_hash, type):
        with pytest.raises(expected_hash):
            ens.labelhash(label)
    else:
        labelhash = ens.labelhash(label)
        assert isinstance(labelhash, bytes)
        hash_hex = Web3.toHex(labelhash)
        assert hash_hex == expected_hash
Exemplo n.º 11
0
def bytes32(val):
    if isinstance(val, int):
        result = Web3.toBytes(val)
    else:
        raise TypeError('val %r could not be converted to bytes')
    if len(result) < 32:
        return result.rjust(32, b'\0')
    else:
        return result
Exemplo n.º 12
0
def normal_name_to_hash(name):
    node = EMPTY_SHA3_BYTES
    if name:
        labels = name.split(".")
        for label in reversed(labels):
            labelhash = label_to_hash(label)
            assert isinstance(labelhash, bytes)
            assert isinstance(node, bytes)
            node = Web3().keccak(node + labelhash)
    return node
Exemplo n.º 13
0
def convert(address, rpc):
    """Convert address of NEW"""
    web3 = Web3(HTTPProvider(rpc))
    chain_id = int(web3.net.version)
    if utils.is_address(address):
        print(hex_to_new(address, chain_id), address)
    elif is_new_address(address):
        print(address, new_to_hex(address, chain_id))
    else:
        print("Address invalid")
Exemplo n.º 14
0
def generate_go_ethereum_fixture(destination_dir):
    with contextlib.ExitStack() as stack:
        datadir = stack.enter_context(common.tempdir())

        keystore_dir = os.path.join(datadir, 'keystore')
        common.ensure_path_exists(keystore_dir)
        keyfile_path = os.path.join(keystore_dir, common.KEYFILE_FILENAME)
        with open(keyfile_path, 'w') as keyfile:
            keyfile.write(common.KEYFILE_DATA)
        genesis_file_path = os.path.join(datadir, 'genesis.json')
        with open(genesis_file_path, 'w') as genesis_file:
            genesis_file.write(json.dumps(common.GENESIS_DATA))

        geth_ipc_path_dir = stack.enter_context(common.tempdir())
        geth_ipc_path = os.path.join(geth_ipc_path_dir, 'geth.ipc')

        geth_port = get_open_port()
        geth_binary = common.get_geth_binary()

        geth_proc = stack.enter_context(
            common.get_geth_process(  # noqa: F841
                geth_binary=geth_binary,
                datadir=datadir,
                genesis_file_path=genesis_file_path,
                ipc_path=geth_ipc_path,
                port=geth_port,
                networkid=str(common.GENESIS_DATA['config']['chainId'])))

        common.wait_for_socket(geth_ipc_path)
        web3 = Web3(Web3.IPCProvider(geth_ipc_path))
        chain_data = setup_chain_state(web3)
        static_data = {
            'raw_txn_account': common.RAW_TXN_ACCOUNT,
            'keyfile_pw': common.KEYFILE_PW,
        }
        pprint.pprint(merge(chain_data, static_data))

        shutil.copytree(datadir, destination_dir)
Exemplo n.º 15
0
def pay(path, src, dest, value, data, rpc, password):
    """Pay NEW to address"""
    web3 = Web3(HTTPProvider(rpc))
    src = web3.toChecksumAddress(src)
    dest = web3.toChecksumAddress(dest)
    value = web3.toWei(value, "ether")
    if data is not None:
        data = data.encode('utf-8')
    else:
        data = b''

    json_value = get_address_from_wallet(src, path)
    if json_value == "":
        print("No from address")
        return

    nonce = web3.eth.getTransactionCount(src)
    chain_id = int(web3.net.version)
    gas_price = web3.eth.gasPrice
    tx = {
        'to': dest,
        'value': value,
        'gas': 0,
        'gasPrice': gas_price,
        'nonce': nonce,
        'chainId': chain_id,
        'data': data,
    }
    gas = web3.eth.estimateGas(tx)
    tx['gas'] = gas

    if password is None:
        password = click.prompt("Enter the password of the keystore",
                                hide_input=True)

    Account.chain_id = chain_id

    try:
        a = Account.privateKeyToAccount(
            Account.decrypt(json_value, password.encode('utf-8')))

        sign_tx = a.signTransaction(tx)
        tx_hash = web3.eth.sendRawTransaction(sign_tx.rawTransaction)
        print(tx_hash.hex())
    except ValueError:
        print("error")
        pass
def test_eth_account_sign_transaction_from_eth_test(acct, transaction_info):
    expected_raw_txn = transaction_info['signed']
    key = transaction_info['key']

    transaction = dissoc(transaction_info, 'signed', 'key', 'unsigned')

    # validate r, in order to validate the transaction hash
    # There is some ambiguity about whether `r` will always be deterministically
    # generated from the transaction hash and private key, mostly due to code
    # author's ignorance. The example test fixtures and implementations seem to agree, so far.
    # See ecdsa_raw_sign() in /eth_keys/backends/native/ecdsa.py
    signed = acct.signTransaction(transaction, key)
    assert signed.r == Web3.toInt(hexstr=expected_raw_txn[-130:-66])

    # confirm that signed transaction can be recovered to the sender
    expected_sender = acct.privateKeyToAccount(key).address
    assert acct.recoverTransaction(signed.rawTransaction) == expected_sender
Exemplo n.º 17
0
def test_setup_name(ens, name, normalized_name, namehash_hex):
    address = ens.web3.eth.accounts[3]
    assert not ens.name(address)
    owner = ens.owner('tester.eth')

    ens.setup_name(name, address)
    assert ens.name(address) == normalized_name

    # check that the correct namehash is set:
    node = Web3.toBytes(hexstr=namehash_hex)
    assert ens.resolver(normalized_name).caller.addr(node) == address

    # check that the correct owner is set:
    assert ens.owner(name) == owner

    ens.setup_name(None, address)
    ens.setup_address(name, None)
    assert not ens.name(address)
    assert not ens.address(name)
def test_autoprovider_detection():
    def no_provider():
        return None

    def must_not_call():
        assert False

    auto = AutoProvider([
        no_provider,
        DisconnectedProvider,
        ConnectedProvider,
        must_not_call,
    ])

    w3 = Web3(auto)

    assert w3.isConnected()

    assert isinstance(auto._active_provider, ConnectedProvider)
def test_set_address(ens, name, full_name, namehash_hex, TEST_ADDRESS):
    assert ens.address(name) is None
    owner = ens.owner('tester.eth')

    ens.setup_address(name, TEST_ADDRESS)
    assert is_same_address(ens.address(name), TEST_ADDRESS)

    namehash = Web3.toBytes(hexstr=namehash_hex)
    normal_name = ens.nameprep(full_name)
    assert is_same_address(ens.address(name), TEST_ADDRESS)

    # check that the correct namehash is set:
    assert is_same_address(
        ens.resolver(normal_name).caller.addr(namehash), TEST_ADDRESS)

    # check that the correct owner is set:
    assert ens.owner(name) == owner

    ens.setup_address(name, None)
    assert ens.address(name) is None
Exemplo n.º 20
0
def blocking_w3():
    return Web3(EthereumTesterProvider(),
                modules={
                    'blocking_version': BlockingVersion,
                    'legacy_version': Version
                })
Exemplo n.º 21
0
def web3(parity_process, endpoint_uri, event_loop):
    event_loop.run_until_complete(wait_for_ws(endpoint_uri, event_loop))
    _web3 = Web3(Web3.WebsocketProvider(endpoint_uri))
    return _web3
Exemplo n.º 22
0
from newchain_web3 import (
    Web3,
    WebsocketProvider,
)

w3 = Web3(WebsocketProvider())
Exemplo n.º 23
0
from newchain_web3 import Web3
from newchain_web3.providers.auto import (
    load_provider_from_uri, )

from .endpoints import (
    INFURA_MAINNET_DOMAIN,
    build_infura_url,
)

_infura_url = build_infura_url(INFURA_MAINNET_DOMAIN)

w3 = Web3(load_provider_from_uri(_infura_url))
Exemplo n.º 24
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Tang Smith
@software: PyCharm
@time: 2019-04-01 21:51
@copyright: 2018-2019 Newton Foundation. All rights reserved.
"""

import base58
import json
from newchain_web3 import Web3, HTTPProvider

w3 = Web3(HTTPProvider('https://rpc1.newchain.newtonproject.org/'))

ClientVersion = int(w3.net.version)
print("Client Version: %s" % ClientVersion)

from web3.middleware import geth_poa_middleware
w3.middleware_onion.inject(geth_poa_middleware, layer=0)


def NewToEth(str):
    print("Str: 0x%s" % base58.b58decode_check(str[3:]).hex().lower()[6:])
    return "0x%s" % base58.b58decode_check(str[3:]).hex().lower()[6:]


From = w3.toChecksumAddress(
    NewToEth("NEW17zDT6sQYPCATtJZ3QpPoR2yW8aGBc2hS3MT"))  #/tmp/wallet
To = w3.toChecksumAddress(NewToEth("NEW17zNNCR9ouLnVMktE8iHBwaPZJh14iK3ghGU"))
print("Gas Price: %s" % w3.eth.gasPrice)
Exemplo n.º 25
0
from newchain_web3 import Web3

w3 = Web3()
Exemplo n.º 26
0
from newchain_web3 import (
    IPCProvider,
    Web3,
)

w3 = Web3(IPCProvider())
Exemplo n.º 27
0
from newchain_web3 import (
    HTTPProvider,
    Web3,
)

w3 = Web3(HTTPProvider())
Exemplo n.º 28
0
def fresh_w3():
    w3 = Web3(Web3.EthereumTesterProvider())
    w3.eth.defaultAccount = w3.eth.accounts[0]
    w3.eth.defaultContractFactory = LinkableContract
    w3.enable_unstable_package_management_api()
    return w3
Exemplo n.º 29
0
def w3_base():
    return Web3(provider=DummyProvider(), middlewares=[])
Exemplo n.º 30
0
def async_w3():
    return Web3(AsyncEthereumTesterProvider(),
                middlewares=[],
                modules={
                    'async_version': AsyncVersion,
                })