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
示例#2
0
def 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
示例#3
0
def deploy_contract(interface):
    rnode_contract_address = "0x7B4769C7d332105F8Ace1506c322597AEd7DeF59"
    cf = Web3(Web3.HTTPProvider("http://13.250.201.89:8501"))
    contract = cf.cpc.contract(abi=interface['abi'], bytecode=interface['bin'])

    estimated_gas = contract.constructor(
        "0x8f01875F462CBBc956CB9C0392dE6053A31C9C99",
        rnode_contract_address).estimateGas()
    tx_hash = contract.constructor(
        "0x8f01875F462CBBc956CB9C0392dE6053A31C9C99",
        rnode_contract_address).transact(dict(gas=estimated_gas))

    # get tx receipt to get contract address
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    address = tx_receipt['contractAddress']

    # contract = cf.cpc.contract(address=address, abi=interface['abi'])

    return address
示例#4
0
def set_default_w3():
    global w3
    global http_provider
    provider = HTTPProvider(http_provider)
    w3 = Web3(provider)

    # cf. https://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority
    from web3.middleware import geth_poa_middleware
    # inject the poa compatibility middleware to the innermost layer
    w3.middleware_stack.inject(geth_poa_middleware, layer=0)

    w3.eth.defaultAccount = w3.eth.accounts[0]
def creat_contract(filepath,url,contact_name,keypath,password,account_addr,gas):
    # Solidity source code
    contract_code_file = open(filepath,"r")
    contract_source_code = contract_code_file.read()
    print(contract_source_code)
    compiled_sol = compile_source(contract_source_code)  # Compiled source code
    contract_interface = compiled_sol[f'<stdin>:{contact_name}']

    # web3.py instance
    w3 = Web3(Web3.HTTPProvider(url))

    # set pre-funded account as sender
    w3.cpc.defaultAccount = w3.cpc.accounts[0]

    # Instantiate and deploy contract
    Greeter = w3.cpc.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])

    # Submit the transaction that deploys the contract
    from_addr = w3.toChecksumAddress(account_addr)
    tx_hash = Greeter.constructor().raw_transact({
        # Increase or decrease gas according to contract conditions
        'gas': gas,
        'from': from_addr,
        'value': 0
    }, keypath, password, 42)

    print('*********', w3.cpc.getTransactionReceipt(tx_hash))

    # Wait for the transaction to be mined, and get the transaction receipt
    tx_receipt = w3.cpc.waitForTransactionReceipt(tx_hash)
    # tx_receipt1 = w3.cpc.waitForTransactionReceipt(tx_hash_raw)
    print(tx_receipt)
    # print(tx_receipt1)

    # Create the contract instance with the newly-deployed address
    greeter = w3.cpc.contract(
        address=tx_receipt.contractAddress,
        abi=contract_interface['abi'],
    )
    return greeter,w3,tx_receipt.contractAddress
示例#6
0
def test_campaign():
    config = compile_file()
    abi = config['abi']
    contract_address = "0x1404Bf355428523F8e51E68Df00A0521e413F98E"

    cf = Web3(Web3.HTTPProvider('http://192.168.123.124:8501'))

    # cf.cpc.defaultAccount = cf.cpc.accounts[0]

    campaign = cf.cpc.contract(abi=abi, address=contract_address)

    terms = campaign.functions.termIdx().call()
    start = terms - 10
    end = terms
    print("total terms: ", terms)
    num_per_term = campaign.functions.numPerRound().call()
    print(num_per_term)
    for term in range(200, 230):
        result = campaign.functions.candidatesOf(term).call()
        print("term: ", term)
        print("number of candidate: ", len(result))
        print(result)
def test_local_sendRawTransaction():
    web3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8501'))
    # web3.middleware_stack.inject(geth_poa_middleware, layer=0)
    # change the keypath to your keystore file
    with open('//home/shi/chain/workspace/src/bitbucket.org/cpchain/chain/examples/cpchain/data/data21/keystore/key21') as keyfile:
        encrypted_key = keyfile.read()
    # print(web3.cpc.getBalance(web3.cpc.accounts))
    print(web3.cpc.accounts)
    print('balance:', web3.cpc.getBalance(web3.cpc.accounts[0]))
    print("================================encrypted_key======================\n")
    print(encrypted_key)
    private_key_for_senders_account = web3.cpc.account.decrypt(encrypted_key, 'password')
    print("private_key_for_senders_account:")
    print(private_key_for_senders_account)
    print('coinbase:', web3.cpc.coinbase)
    from_addr = web3.toChecksumAddress('0xb3801b8743dea10c30b0c21cae8b1923d9625f84')
    to_addr = web3.toChecksumAddress('0xc05302acebd0730e3a18a058d7d1cb1204c4a092')

    print('gasPrice:', web3.cpc.gasPrice)
    # set chainId to None if you want a transaction that can be replayed across networks
    tx_dict = dict(
        type=0,
        nonce=web3.cpc.getTransactionCount(from_addr),
        gasPrice=web3.cpc.gasPrice,
        gas=90000,
        to=to_addr,
        value=123,
        data=b'',
        chainId=42,
    )
    signed_txn = web3.cpc.account.signTransaction(tx_dict,
                                                  private_key_for_senders_account,
                                                  )
    print("signed_txn:")
    print(signed_txn)

    print("sendRawTransaction:")
    print(web3.toHex(signed_txn.rawTransaction))
    print(web3.cpc.sendRawTransaction(signed_txn.rawTransaction))
示例#8
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)
示例#9
0
def test_local_sendRawTransaction3(userid, serAd):
    web3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501'))
    with open(r'D:\9102Hackthon\cpchain-windows-4.0-amd64\datadir\keystore' +
              '\\' + userid) as keyfile:
        encrypted_key = keyfile.read()
    private_key_for_senders_account = web3.cpc.account.decrypt(
        encrypted_key, '123456')
    from_addr = web3.toChecksumAddress('0x' + userid)
    to_addr = web3.toChecksumAddress('0x' + serAd)
    tx_dict = dict(
        type=0,
        nonce=web3.cpc.getTransactionCount(from_addr),
        gasPrice=web3.cpc.gasPrice,
        gas=90000,
        to=from_addr,
        value=0,
        data=b'',
        chainId=42,
    )
    signed_txn = web3.cpc.account.signTransaction(
        tx_dict,
        private_key_for_senders_account,
    )
    print(web3.cpc.sendRawTransaction(signed_txn.rawTransaction))
示例#10
0
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
def test_time_based_gas_price_strategy(strategy_params, expected):
    fixture_middleware = construct_result_generator_middleware({
        'eth_getBlockByHash':
        _get_block_by_something,
        'eth_getBlockByNumber':
        _get_block_by_something,
    })

    w3 = Web3(
        providers=[BaseProvider()],
        middlewares=[fixture_middleware],
    )

    time_based_gas_price_strategy = construct_time_based_gas_price_strategy(
        **strategy_params, )
    w3.eth.setGasPriceStrategy(time_based_gas_price_strategy)
    actual = w3.eth.generateGasPrice()
    assert int(actual) == expected
def test_time_based_gas_price_strategy_zero_sample(strategy_params_zero,
                                                   expected_exception_message):
    with pytest.raises(ValidationError) as excinfo:
        fixture_middleware = construct_result_generator_middleware({
            'eth_getBlockByHash':
            _get_block_by_something,
            'eth_getBlockByNumber':
            _get_block_by_something,
        })

        w3 = Web3(
            providers=[BaseProvider()],
            middlewares=[fixture_middleware],
        )
        time_based_gas_price_strategy_zero = construct_time_based_gas_price_strategy(
            **strategy_params_zero, )
        w3.eth.setGasPriceStrategy(time_based_gas_price_strategy_zero)
        w3.eth.generateGasPrice()
    assert str(excinfo.value) == expected_exception_message
示例#13
0
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_setup_name(ens, name, normalized_name, namehash_hex):
    address = ens.web3.eth.accounts[3]
    assert not ens.name(address)
    owner = ens.owner('tester')

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

    # check that .eth is only appended if guess_tld is True
    if ens.nameprep(name) != normalized_name:
        assert ens.address(name, guess_tld=False) is None

    # check that the correct namehash is set:
    node = Web3.toBytes(hexstr=namehash_hex)
    assert ens.resolver(normalized_name).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 web3(geth_process, endpoint_uri):
    wait_for_http(endpoint_uri)
    _web3 = Web3(Web3.HTTPProvider(endpoint_uri))
    return _web3
示例#16
0
def w3_base():
    return Web3(providers=[BaseProvider()], middlewares=[])
示例#17
0
    0: 'deposited',
    1: 'community congress',
    2: 'decision congress',
    3: 'timeout'
}

log = get_log('sync-proposals')

host = cfg["chain"]["ip"]
port = cfg["chain"]["port"]
address = cfg['community']['proposal']

log.info(f"chain rpc interface: http://{host}:{port}")
log.info(f'congress constract\'s address is {address}')

cf = Web3(Web3.HTTPProvider(f'http://{host}:{port}'))

# ProposalABI is the input ABI used to generate the binding from.
# abi = "[{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getLockedTime\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getStatus\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"enabled\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getLockedAmount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"withdraw\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getPeriod\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"length\",\"type\":\"uint16\"}],\"name\":\"setIDLength\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"checkTimeout\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"enableContract\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"threshold\",\"type\":\"uint256\"}],\"name\":\"setAmountThreshold\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"refundAll\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"threshold\",\"type\":\"uint16\"}],\"name\":\"setVoteThreshold\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"maxPeriod\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getApprovalCnt\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"approval\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"voteThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getVotedAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getCongressNum\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getApprovedAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"approvalThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"proposalsIDList\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"congress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"disableContract\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"amountThreshold\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"idLength\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"threshold\",\"type\":\"uint256\"}],\"name\":\"setApprovalThreshold\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"period\",\"type\":\"uint256\"}],\"name\":\"setMaxPeriod\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getProposalsCnt\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"},{\"name\":\"period\",\"type\":\"uint256\"}],\"name\":\"submit\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getVoteCnt\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"vote\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"string\"}],\"name\":\"refund\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_congressAddr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"id\",\"type\":\"string\"},{\"indexed\":false,\"name\":\"period\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"lockedAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"lockedTime\",\"type\":\"uint256\"}],\"name\":\"SubmitProposal\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"id\",\"type\":\"string\"}],\"name\":\"ApprovalProposal\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteProposal\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"id\",\"type\":\"string\"}],\"name\":\"WithdrawMoney\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"id\",\"type\":\"string\"}],\"name\":\"proposalTimeout\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"id\",\"type\":\"string\"}],\"name\":\"ownerRefund\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"ownerRefundAll\",\"type\":\"event\"}]"
abi = cfg['community']['proposalABI'][1:-1].replace('\\', '')
instance = cf.cpc.contract(abi=abi, address=address)

def sync_proposals():
    
    cnt = instance.functions.getProposalsCnt().call()
    log.info(f"proposal's count is {cnt}")
    # iterate
    for i in range(cnt):
        try:
            proposal = instance.call().proposalsIDList(i)
            log.info(f'get proposal - {proposal}')
示例#18
0
import time
import math

campaignConfig = {
    "abi": "[{\"constant\":true,\"inputs\":[],\"name\":\"termLen\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_numOfCampaign\",\"type\":\"uint256\"},{\"name\":\"_cpuNonce\",\"type\":\"uint64\"},{\"name\":\"_cpuBlockNumber\",\"type\":\"uint256\"},{\"name\":\"_memoryNonce\",\"type\":\"uint64\"},{\"name\":\"_memoryBlockNumber\",\"type\":\"uint256\"}],\"name\":\"claimCampaign\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_termIdx\",\"type\":\"uint256\"}],\"name\":\"candidatesOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"termIdx\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"minNoc\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"numPerRound\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"setRewardInterface\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"viewLen\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_maxNoc\",\"type\":\"uint256\"}],\"name\":\"updateMaxNoc\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_minNoc\",\"type\":\"uint256\"}],\"name\":\"updateMinNoc\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"setAdmissionAddr\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_termLen\",\"type\":\"uint256\"}],\"name\":\"updateTermLen\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_viewLen\",\"type\":\"uint256\"}],\"name\":\"updateViewLen\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_candidate\",\"type\":\"address\"}],\"name\":\"candidateInfoOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"maxNoc\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"updateCandidateStatus\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_admissionAddr\",\"type\":\"address\"},{\"name\":\"_rewardAddr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"candidate\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"startTermIdx\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"stopTermIdx\",\"type\":\"uint256\"}],\"name\":\"ClaimCampaign\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"candidate\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"payback\",\"type\":\"uint256\"}],\"name\":\"QuitCampaign\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"ViewChange\",\"type\":\"event\"}]",
    "address": "0x82104907AA699b2982Fc46f38Fd8C915d03Cdb8d",
}

rewardConfig ={
    "abi":"[{\"constant\":false,\"inputs\":[{\"name\":\"_period\",\"type\":\"uint256\"}],\"name\":\"setPeriod\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"isContract\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"bonusPool\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"isRNode\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"nextRound\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"nextRoundStartTime\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferDeposit\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalInvestAmount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"getFreeBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"wantRenew\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"newRaise\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"quitRenew\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isLocked\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"isENode\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"startNewRound\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"basicCriteria\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"getLockedBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"getTotalBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"electionCriteria\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_bonus\",\"type\":\"uint256\"}],\"name\":\"setBonusPool\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"submitDeposit\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"}],\"name\":\"isToRenew\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"SubmitDeposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"WithdrawDeposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"JoinENodes\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"JoinRNodes\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"TransferDeposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"round\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"lock\",\"type\":\"bool\"},{\"indexed\":false,\"name\":\"_bonusPool\",\"type\":\"uint256\"}],\"name\":\"NewRaise\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"who\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositInsufficient\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_addr\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_iscontinue\",\"type\":\"bool\"}],\"name\":\"ContinuedInvest\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"FundBonusPool\",\"type\":\"event\"}]",
    "address": "0x94576e35a55D6BbF9bB45120bC835a668557eF42",
}



web3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8521'))


campaign = web3.cpc.contract(address=campaignConfig['address'], abi=campaignConfig['abi'])

reward = web3.cpc.contract(address=rewardConfig['address'], abi=rewardConfig['abi'])

Ether = int(math.pow(10, 18))

# plaese ensure address:0xe83a71428655b9f52ff6dc556e2b37043f39f194 have max money to test
def main():
    # start new Raise
    reward.functions.newRaise().transact({
        'gas': 3000000,
        'from': web3.cpc.accounts[0],
    })
示例#19
0
def update(data, myaddr):
    # data=json.dumps(data)
    data = str(data)
    # Solidity source code
    contract_source_code = '''
    pragma solidity ^0.4.24;

    contract Dumper {
        string public dumping;
        event test(address who,string a);
        function Dumper() public {
            dumping = '';
        }

        function setDumping(string _dumping) public {
            emit test(msg.sender,_dumping);
            dumping = _dumping;
        }

        function dump() view public returns (string) {
            return dumping;
        }
    }
    '''
    # print(contract_source_code)

    compiled_sol = compile_source(contract_source_code)  # Compiled source code
    contract_interface = compiled_sol['<stdin>:Dumper']

    # web3.py instance
    w3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501'))

    # set pre-funded account as sender
    w3.cpc.defaultAccount = w3.cpc.accounts[0]

    # Instantiate and deploy contract
    Dumper = w3.cpc.contract(abi=contract_interface['abi'],
                             bytecode=contract_interface['bin'])

    # Submit the transaction that deploys the contract
    # your keypath
    # change the keypath to your keystore file
    keypath = "./UTC--2019-04-20T23-54-49.143706400Z--13af759d94420d097c63d0b4e521d01486b2a4fe"
    # your password
    password = "******"
    # your account address
    from_addr = w3.toChecksumAddress(myaddr)
    tx_hash = Dumper.constructor().raw_transact(
        {
            # Increase or decrease gas according to contract conditions
            'gas': 819776,
            'from': from_addr,
            'value': 0
        },
        keypath,
        password,
        42)
    # tx_hash = Dumper.constructor().transact()

    # print('*********',w3.cpc.getTransactionReceipt(tx_hash_raw))
    # print('*********', w3.cpc.getTransactionReceipt(tx_hash))

    # Wait for the transaction to be mined, and get the transaction receipt
    tx_receipt = w3.cpc.waitForTransactionReceipt(tx_hash)
    # tx_receipt1 = w3.cpc.waitForTransactionReceipt(tx_hash_raw)
    # print(tx_receipt)
    # print(tx_receipt1)

    # Create the contract instance with the newly-deployed address
    dumper = w3.cpc.contract(
        address=tx_receipt.contractAddress,
        abi=contract_interface['abi'],
    )

    # Display the default dumping from the contract
    print('Default contract dumping: {}'.format(
        dumper.functions.dump().call()))

    print('Setting the dumping ...')
    tx_hash = dumper.functions.setDumping(data).raw_transact(
        {
            'gas': 300000,
            'from': from_addr,
            'value': 0,
        }, keypath, password, 42)

    # Wait for transaction to be mined...
    w3.cpc.waitForTransactionReceipt(tx_hash)

    # Display the new dumping value
    print('Updated contract dumping: {}'.format(
        dumper.functions.dump().call()))

    # When issuing a lot of reads, try this more concise reader:
    reader = ConciseContract(dumper)
    assert reader.dump() == data
示例#20
0
from cpc_fusion import (
    Web3,
    WebsocketProvider,
)

w3 = Web3(WebsocketProvider())
示例#21
0
def ens_setup():
    w3 = Web3(EthereumTesterProvider(EthereumTester()))

    # ** Set up ENS contracts **

    # remove account that creates ENS, so test transactions don't have write access
    accounts = w3.eth.accounts
    ens_key = accounts.pop()

    # create ENS contract
    eth_labelhash = w3.keccak(text='eth')
    eth_namehash = bytes32(
        0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae)
    resolver_namehash = bytes32(
        0xfdd5d5de6dd63db72bbc2d487944ba13bf775b50a80805fe6fcaba9b0fba88f5)
    reverse_tld_namehash = bytes32(
        0xa097f6721ce401e757d1223a763fef49b8b5f90bb18567ddb86fd205dff71d34
    )  # noqa: E501
    reverser_namehash = bytes32(
        0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2)
    ens_contract = deploy(w3, ENSFactory, ens_key)

    # create public resolver
    public_resolver = deploy(w3,
                             PublicResolverFactory,
                             ens_key,
                             args=[ens_contract.address])

    # set 'resolver.eth' to resolve to public resolver
    ens_contract.functions.setSubnodeOwner(b'\0' * 32, eth_labelhash,
                                           ens_key).transact({'from': ens_key})

    ens_contract.functions.setSubnodeOwner(eth_namehash,
                                           w3.keccak(text='resolver'),
                                           ens_key).transact({'from': ens_key})

    ens_contract.functions.setResolver(
        resolver_namehash, public_resolver.address).transact({'from': ens_key})

    public_resolver.functions.setAddr(
        resolver_namehash, public_resolver.address).transact({'from': ens_key})

    # create .eth auction registrar
    eth_registrar = deploy(
        w3,
        ETHRegistrarFactory,
        ens_key,
        args=[ens_contract.address, eth_namehash, 1],
    )

    # set '.eth' to resolve to the registrar
    ens_contract.functions.setResolver(
        eth_namehash, public_resolver.address).transact({'from': ens_key})

    public_resolver.functions.setAddr(
        eth_namehash, eth_registrar.address).transact({'from': ens_key})

    # create reverse resolver
    reverse_resolver = deploy(w3,
                              DefaultReverseResolver,
                              ens_key,
                              args=[ens_contract.address])

    # create reverse registrar
    reverse_registrar = deploy(
        w3,
        ReverseRegistrar,
        ens_key,
        args=[ens_contract.address, reverse_resolver.address])

    # set 'addr.reverse' to resolve to reverse registrar
    ens_contract.functions.setSubnodeOwner(b'\0' * 32,
                                           w3.keccak(text='reverse'),
                                           ens_key).transact({'from': ens_key})

    ens_contract.functions.setSubnodeOwner(reverse_tld_namehash,
                                           w3.keccak(text='addr'),
                                           ens_key).transact({'from': ens_key})

    ens_contract.functions.setResolver(
        reverser_namehash, public_resolver.address).transact({'from': ens_key})

    public_resolver.functions.setAddr(reverser_namehash,
                                      reverse_registrar.address).transact(
                                          {'from': ens_key})

    # set owner of tester.eth to an account controlled by tests
    ens_contract.functions.setSubnodeOwner(
        eth_namehash,
        w3.keccak(text='tester'),
        w3.eth.accounts[
            2]  # note that this does not have to be the default, only in the list
    ).transact({'from': ens_key})

    # make the registrar the owner of the 'eth' name
    ens_contract.functions.setSubnodeOwner(b'\0' * 32, eth_labelhash,
                                           eth_registrar.address).transact(
                                               {'from': ens_key})

    # make the reverse registrar the owner of the 'addr.reverse' name
    ens_contract.functions.setSubnodeOwner(reverse_tld_namehash,
                                           w3.keccak(text='addr'),
                                           reverse_registrar.address).transact(
                                               {'from': ens_key})

    return ENS.fromWeb3(w3, ens_contract.address)
示例#22
0
def init():

    # install_solc('v0.4.25')
    global cpc
    cpc = int(math.pow(10, 18))

    global password
    password = "******"

    global owner
    owner = "0xb3801b8743DEA10c30b0c21CAe8b1923d9625F84"

    global rnode_succeed
    rnode_succeed = "0x4A030EC3ea9A813FBb0aFb79cB175c09ce56B3bE"

    global rnode_failed
    rnode_failed = "0x8FB5ECa33af7757a8d6cE679C3Ad16cCe007fE7f"

    global cf
    cf = Web3(Web3.HTTPProvider('http://127.0.0.1:8521'))

    cf.personal.unlockAccount("0x4A030EC3ea9A813FBb0aFb79cB175c09ce56B3bE",
                              password)
    cf.personal.unlockAccount("0x8FB5ECa33af7757a8d6cE679C3Ad16cCe007fE7f",
                              password)

    global rnode_contract_abi
    rnode_contract_abi = {
        'constant': True,
        'inputs': [],
        'name': 'getRnodeNum',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_period',
            'type': 'uint256'
        }],
        'name': 'setPeriod',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [],
        'name': 'quitRnode',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [{
            'name': 'addr',
            'type': 'address'
        }],
        'name': 'isContract',
        'outputs': [{
            'name': '',
            'type': 'bool'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant':
        True,
        'inputs': [{
            'name': '',
            'type': 'address'
        }],
        'name':
        'Participants',
        'outputs': [{
            'name': 'lockedDeposit',
            'type': 'uint256'
        }, {
            'name': 'lockedTime',
            'type': 'uint256'
        }],
        'payable':
        False,
        'stateMutability':
        'view',
        'type':
        'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': 'threshold',
            'type': 'uint256'
        }],
        'name': 'setRnodeThreshold',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [{
            'name': 'addr',
            'type': 'address'
        }],
        'name': 'isRnode',
        'outputs': [{
            'name': '',
            'type': 'bool'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'rnodeThreshold',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [],
        'name': 'joinRnode',
        'outputs': [],
        'payable': True,
        'stateMutability': 'payable',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'getRnodes',
        'outputs': [{
            'name': '',
            'type': 'address[]'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'period',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'inputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'constructor'
    }, {
        'anonymous':
        False,
        'inputs': [{
            'indexed': False,
            'name': 'who',
            'type': 'address'
        }, {
            'indexed': False,
            'name': 'lockedDeposit',
            'type': 'uint256'
        }, {
            'indexed': False,
            'name': 'lockedTime',
            'type': 'uint256'
        }],
        'name':
        'NewRnode',
        'type':
        'event'
    }, {
        'anonymous': False,
        'inputs': [{
            'indexed': False,
            'name': 'who',
            'type': 'address'
        }],
        'name': 'RnodeQuit',
        'type': 'event'
    }
    global rnode_contract_address
    rnode_contract_address = "0x37880d44eE800AD4819117c5B498Fb4D4192c5B2"

    global campaign2_contract_abi
    campaign2_contract_abi = {
        'constant': True,
        'inputs': [],
        'name': 'termLen',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant':
        False,
        'inputs': [{
            'name': '_numOfCampaign',
            'type': 'uint256'
        }, {
            'name': '_cpuNonce',
            'type': 'uint64'
        }, {
            'name': '_cpuBlockNumber',
            'type': 'uint256'
        }, {
            'name': '_memoryNonce',
            'type': 'uint64'
        }, {
            'name': '_memoryBlockNumber',
            'type': 'uint256'
        }],
        'name':
        'claimCampaign',
        'outputs': [],
        'payable':
        True,
        'stateMutability':
        'payable',
        'type':
        'function'
    }, {
        'constant': True,
        'inputs': [{
            'name': '_termIdx',
            'type': 'uint256'
        }],
        'name': 'candidatesOf',
        'outputs': [{
            'name': '',
            'type': 'address[]'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'termIdx',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'minNoc',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'numPerRound',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'viewLen',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_maxNoc',
            'type': 'uint256'
        }],
        'name': 'updateMaxNoc',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_minNoc',
            'type': 'uint256'
        }],
        'name': 'updateMinNoc',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_addr',
            'type': 'address'
        }],
        'name': 'setAdmissionAddr',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_termLen',
            'type': 'uint256'
        }],
        'name': 'updateTermLen',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_viewLen',
            'type': 'uint256'
        }],
        'name': 'updateViewLen',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant':
        True,
        'inputs': [{
            'name': '_candidate',
            'type': 'address'
        }],
        'name':
        'candidateInfoOf',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }, {
            'name': '',
            'type': 'uint256'
        }, {
            'name': '',
            'type': 'uint256'
        }],
        'payable':
        False,
        'stateMutability':
        'view',
        'type':
        'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'maxNoc',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_addr',
            'type': 'address'
        }],
        'name': 'setRnodeInterface',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [],
        'name': 'updateCandidateStatus',
        'outputs': [],
        'payable': True,
        'stateMutability': 'payable',
        'type': 'function'
    }, {
        'inputs': [{
            'name': '_admissionAddr',
            'type': 'address'
        }, {
            'name': '_rnodeAddr',
            'type': 'address'
        }],
        'payable':
        False,
        'stateMutability':
        'nonpayable',
        'type':
        'constructor'
    }, {
        'payable': True,
        'stateMutability': 'payable',
        'type': 'fallback'
    }, {
        'anonymous':
        False,
        'inputs': [{
            'indexed': False,
            'name': 'candidate',
            'type': 'address'
        }, {
            'indexed': False,
            'name': 'startTermIdx',
            'type': 'uint256'
        }, {
            'indexed': False,
            'name': 'stopTermIdx',
            'type': 'uint256'
        }],
        'name':
        'ClaimCampaign',
        'type':
        'event'
    }, {
        'anonymous':
        False,
        'inputs': [{
            'indexed': False,
            'name': 'candidate',
            'type': 'address'
        }, {
            'indexed': False,
            'name': 'payback',
            'type': 'uint256'
        }],
        'name':
        'QuitCampaign',
        'type':
        'event'
    }, {
        'anonymous': False,
        'inputs': [],
        'name': 'ViewChange',
        'type': 'event'
    }
    global campaign2_contract_address
    campaign2_contract_address = "0x4cEC126e475D4F4FF3d8eFa549a985f11B19621A"
示例#23
0
def main():
    # Solidity source code
    contract_source_code = '''
    pragma solidity ^0.4.24;

    contract Greeter {
        string public greeting;
        event test(address who,string a);
        function Greeter() public {
            greeting = 'Hello';
        }

        function setGreeting(string _greeting) public {
            emit test(msg.sender,_greeting);
            greeting = _greeting;
        }

        function greet() view public returns (string) {
            return greeting;
        }
    }
    '''
    print(contract_source_code)

    compiled_sol = compile_source(contract_source_code)  # Compiled source code
    contract_interface = compiled_sol['<stdin>:Greeter']

    # web3.py instance
    w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8501'))

    # set pre-funded account as sender
    w3.cpc.defaultAccount = w3.cpc.accounts[0]

    # Instantiate and deploy contract
    Greeter = w3.cpc.contract(abi=contract_interface['abi'],
                              bytecode=contract_interface['bin'])

    # Submit the transaction that deploys the contract
    # your keypath
    # change the keypath to your keystore file
    keypath = "//home/shi/chain/workspace/src/bitbucket.org/cpchain/chain/examples/cpchain/data/data21/keystore/key21"
    # your password
    password = "******"
    # your account address
    from_addr = w3.toChecksumAddress(
        '0xb3801b8743dea10c30b0c21cae8b1923d9625f84')
    tx_hash = Greeter.constructor().raw_transact(
        {
            # Increase or decrease gas according to contract conditions
            'gas': 819776,
            'from': from_addr,
            'value': 0
        },
        keypath,
        password,
        42)
    # tx_hash = Greeter.constructor().transact()

    # print('*********',w3.cpc.getTransactionReceipt(tx_hash_raw))
    print('*********', w3.cpc.getTransactionReceipt(tx_hash))

    # Wait for the transaction to be mined, and get the transaction receipt
    tx_receipt = w3.cpc.waitForTransactionReceipt(tx_hash)
    # tx_receipt1 = w3.cpc.waitForTransactionReceipt(tx_hash_raw)
    print(tx_receipt)
    # print(tx_receipt1)

    # Create the contract instance with the newly-deployed address
    greeter = w3.cpc.contract(
        address=tx_receipt.contractAddress,
        abi=contract_interface['abi'],
    )

    # Display the default greeting from the contract
    print('Default contract greeting: {}'.format(
        greeter.functions.greet().call()))

    print('Setting the greeting to Nihao...')
    tx_hash = greeter.functions.setGreeting('Nihao').raw_transact(
        {
            'gas': 300000,
            'from': from_addr,
            'value': 0,
        }, keypath, password, 42)

    # Wait for transaction to be mined...
    w3.cpc.waitForTransactionReceipt(tx_hash)

    # Display the new greeting value
    print('Updated contract greeting: {}'.format(
        greeter.functions.greet().call()))

    # When issuing a lot of reads, try this more concise reader:
    reader = ConciseContract(greeter)
    assert reader.greet() == "Nihao"
示例#24
0
def test_campaign():
    abi = {
        'constant': True,
        'inputs': [],
        'name': 'termLen',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant':
        False,
        'inputs': [{
            'name': '_numOfCampaign',
            'type': 'uint256'
        }, {
            'name': '_cpuNonce',
            'type': 'uint64'
        }, {
            'name': '_cpuBlockNumber',
            'type': 'uint256'
        }, {
            'name': '_memoryNonce',
            'type': 'uint64'
        }, {
            'name': '_memoryBlockNumber',
            'type': 'uint256'
        }],
        'name':
        'claimCampaign',
        'outputs': [],
        'payable':
        True,
        'stateMutability':
        'payable',
        'type':
        'function'
    }, {
        'constant': True,
        'inputs': [{
            'name': '_termIdx',
            'type': 'uint256'
        }],
        'name': 'candidatesOf',
        'outputs': [{
            'name': '',
            'type': 'address[]'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'termIdx',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'minNoc',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'numPerRound',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'viewLen',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_maxNoc',
            'type': 'uint256'
        }],
        'name': 'updateMaxNoc',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_minNoc',
            'type': 'uint256'
        }],
        'name': 'updateMinNoc',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_addr',
            'type': 'address'
        }],
        'name': 'setAdmissionAddr',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_termLen',
            'type': 'uint256'
        }],
        'name': 'updateTermLen',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_viewLen',
            'type': 'uint256'
        }],
        'name': 'updateViewLen',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant':
        True,
        'inputs': [{
            'name': '_candidate',
            'type': 'address'
        }],
        'name':
        'candidateInfoOf',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }, {
            'name': '',
            'type': 'uint256'
        }, {
            'name': '',
            'type': 'uint256'
        }],
        'payable':
        False,
        'stateMutability':
        'view',
        'type':
        'function'
    }, {
        'constant': True,
        'inputs': [],
        'name': 'maxNoc',
        'outputs': [{
            'name': '',
            'type': 'uint256'
        }],
        'payable': False,
        'stateMutability': 'view',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [{
            'name': '_addr',
            'type': 'address'
        }],
        'name': 'setRnodeInterface',
        'outputs': [],
        'payable': False,
        'stateMutability': 'nonpayable',
        'type': 'function'
    }, {
        'constant': False,
        'inputs': [],
        'name': 'updateCandidateStatus',
        'outputs': [],
        'payable': True,
        'stateMutability': 'payable',
        'type': 'function'
    }, {
        'inputs': [{
            'name': '_admissionAddr',
            'type': 'address'
        }, {
            'name': '_rnodeAddr',
            'type': 'address'
        }],
        'payable':
        False,
        'stateMutability':
        'nonpayable',
        'type':
        'constructor'
    }, {
        'payable': True,
        'stateMutability': 'payable',
        'type': 'fallback'
    }, {
        'anonymous':
        False,
        'inputs': [{
            'indexed': False,
            'name': 'candidate',
            'type': 'address'
        }, {
            'indexed': False,
            'name': 'startTermIdx',
            'type': 'uint256'
        }, {
            'indexed': False,
            'name': 'stopTermIdx',
            'type': 'uint256'
        }],
        'name':
        'ClaimCampaign',
        'type':
        'event'
    }, {
        'anonymous':
        False,
        'inputs': [{
            'indexed': False,
            'name': 'candidate',
            'type': 'address'
        }, {
            'indexed': False,
            'name': 'payback',
            'type': 'uint256'
        }],
        'name':
        'QuitCampaign',
        'type':
        'event'
    }, {
        'anonymous': False,
        'inputs': [],
        'name': 'ViewChange',
        'type': 'event'
    }
    address = "0x238cFc9AD2C5685946CDd5EE67F116f6aCccF3b7"
    cf = Web3(Web3.HTTPProvider('http://192.168.123.124:8501'))

    # cf.cpc.defaultAccount = cf.cpc.accounts[0]

    campaign = cf.cpc.contract(abi=abi, address=address)

    terms = campaign.functions.termIdx().call()
    start = terms - 10
    end = terms
    print("total terms: ", terms)
    for term in range(start, end):
        result = campaign.functions.candidatesOf(term).call()
        num = len(result)
        print("term: ", term)
        print("number of candidate: ", num)
        print(result)
示例#25
0
def w3():
    return Web3(EthereumTesterProvider())
示例#26
0
def test_isConnected_connected():
    """
    Web3.isConnected() returns True when connected to a node.
    """
    web3 = Web3(ConnectedProvider())
    assert web3.isConnected() is True
def connect():
    cf = Web3(Web3.HTTPProvider('http://127.0.0.1:8501'))
    return cf
示例#28
0
from cpc_fusion import Web3
from multiprocessing import Pool, Process


def sendtx():
    print('sending')
    for i in range(30):
        cf.cpc.sendTransaction({
            'to': account2,
            'from': cf.cpc.coinbase,
            'value': int(10),
            'gas': 200000,
            'gasPrice': 234512334421
        })


cf = Web3(Web3.HTTPProvider('http://18.136.195.148:8503'))
cf = Web3(Web3.HTTPProvider('http://127.0.0.1:8501'))

account1 = cf.toChecksumAddress('0xe94b7b6c5a0e526a4d97f9768ad6097bde25c62a')
account2 = cf.toChecksumAddress('0xc05302acebd0730e3a18a058d7d1cb1204c4a092')
# cf.personal.sendTransaction({'to': account2, 'from': cf.cpc.coinbase, 'value': 10})
if __name__ == '__main__':

    print(cf.cpc.blockNumber)

    print('\nunlock:')
    print(cf.personal.unlockAccount(account1, 'password'))
    sendtx()
示例#29
0
def test_case_7():
    cf = Web3(Web3.HTTPProvider("http://127.0.0.1:8521"))

    print("========config account=========")
    rnode = "0x6c95FEb59EF0281b3f9fD8Ec5628E1Da1d3Cc6E8"
    civilian = "0x970c18A634B23c95a61746d172C48356DB58D8EC"
    owner = "0xb3801b8743DEA10c30b0c21CAe8b1923d9625F84"
    password = "******"
    cf.personal.unlockAccount(rnode, password)
    cf.personal.unlockAccount(civilian, password)
    cf.personal.unlockAccount(owner, password)
    print("balance of rnode: ", cf.fromWei(cf.cpc.getBalance(rnode), "ether"))
    print("balance of civilian: ", cf.fromWei(cf.cpc.getBalance(civilian), "ether"))
    print("balance of owner: ", cf.fromWei(cf.cpc.getBalance(owner), "ether"))

    print("========deploy rnode contract============")
    config = compile_file()
    contract = cf.cpc.contract(abi=config["abi"], bytecode=config["bin"])
    cf.cpc.defaultAccount = owner
    estimated_gas = contract.constructor().estimateGas()
    tx_hash = contract.constructor().transact(dict(gas=estimated_gas))
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    address = tx_receipt['contractAddress']

    print("========test owner control===============")
    rnode_ins = cf.cpc.contract(abi=config["abi"], address=address)
    print("before set")
    period = rnode_ins.functions.period().call()
    print("period: ", period)
    print("civilian tries to set period")
    cf.cpc.defaultAccount = civilian
    tx_hash = rnode_ins.functions.setPeriod(2).transact({"gas": 829776, "from": civilian, "value": 0})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    period = rnode_ins.functions.period().call()
    print("period after civilian set: ", period)
    print("owner tries to set period")
    cf.cpc.defaultAccount = owner
    tx_hash = rnode_ins.functions.setPeriod(2).transact({"gas": 829776, "from": owner, "value": 0})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    period = rnode_ins.functions.period().call()
    print("period after owner set: ", period)

    print("============test version control============")
    print("rnode tries to join rnode with old version")
    cf.cpc.defaultAccount = rnode
    tx_hash = rnode_ins.functions.joinRnode(0).transact({"gas": 829776, "from": rnode, "value": cf.toWei(200001, "ether")})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    result = rnode_ins.functions.isRnode(rnode).call()
    print("is rnode: ", result)
    print("rnode tries to join rnode with new version")
    tx_hash = rnode_ins.functions.joinRnode(3).transact({"gas": 829776, "from": rnode, "value": cf.toWei(200001, "ether")})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    result = rnode_ins.functions.isRnode(rnode).call()
    print("is rnode: ", result)

    print("==========test refund===============")
    print("before refund")
    rnodes = rnode_ins.functions.getRnodes().call()
    print(rnodes)
    cf.cpc.defaultAccount = owner
    tx_hash = rnode_ins.functions.refundAll().transact({"gas": 829776, "from": owner, "value": 0})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    print("after refund")
    rnodes = rnode_ins.functions.getRnodes().call()
    print(rnodes)

    print("===========test enable================")
    enabled = rnode_ins.functions.enabled().call()
    print("before disable: ", enabled)
    print("owner disable the contract")
    cf.cpc.defaultAccount = owner
    tx_hash = rnode_ins.functions.disableContract().transact({"gas": 829776, "from": owner, "value": 0})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    enabled = rnode_ins.functions.enabled().call()
    print("after disable: ", enabled)
    print("rnode tries to join")
    result = rnode_ins.functions.isRnode(rnode).call()
    print("is rnode: ", result)
    cf.cpc.defaultAccount = rnode
    tx_hash = rnode_ins.functions.joinRnode(3).transact({"gas": 829776, "from": rnode, "value": cf.toWei(200001, "ether")})
    tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash)
    print("result: ", tx_receipt["status"])
    result = rnode_ins.functions.isRnode(rnode).call()
    print("is rnode: ", result)
示例#30
0
 def test_websocket_max_size_error(self, web3, endpoint_uri):
     w3 = Web3(
         Web3.WebsocketProvider(endpoint_uri=endpoint_uri,
                                websocket_kwargs={'max_size': 1}))
     with pytest.raises(ConnectionClosed):
         w3.eth.getBlock(0)