Exemple #1
0
def setup(f, host, port, add_dev_code, contract_dir, gas, gas_price,
          private_key):
    with open(f) as data_file:
        instructions = json.load(data_file)
    json_rpc = EthJsonRpc(host, port)
    coinbase = json_rpc.eth_coinbase()["result"]
    if private_key:
        print "Your address for your private key: {}".format(
            privtoaddr(private_key.decode('hex')).encode('hex'))
    else:
        print "Your coinbase: {}".format(coinbase)
    for instruction in instructions:
        print 'Your balance: {} Wei'.format(
            int(json_rpc.eth_getBalance(coinbase)['result'], 16))
        if instruction["type"] == "deployment":
            deploy_code(
                json_rpc, coinbase, instruction["file"],
                instruction["constructorParams"]
                if "constructorParams" in instruction else None,
                instruction["addresses"] if "addresses" in instruction else
                None, add_dev_code == "true", contract_dir, int(gas),
                int(gas_price), private_key)
        elif instruction["type"] == "transaction":
            do_transaction(json_rpc, coinbase, instruction["contract"],
                           instruction["name"], instruction["params"],
                           int(gas), int(gas_price), private_key)
        elif instruction["type"] == "assertion":
            do_assertion(json_rpc, instruction["contract"],
                         instruction["name"], instruction["params"],
                         instruction["return"])
    for contract_name, contract_address in addresses.iteritems():
        print 'Contract {} was created at address {}.'.format(
            contract_name, contract_address)
Exemple #2
0
def eth_json_rpc(eth_rpc_host, eth_rpc_port):
    """
    An instance of EthJsonRpc that uses the host and port specified with
    the `--rpc-host` and `--rpc-port` flags (or an ephemeral testrpc instance if
    `--rpc-port` is not given)
    """
    return EthJsonRpc(eth_rpc_host, eth_rpc_port)
Exemple #3
0
def credits():
    reward = BLOCK_REWARD - FEE
    accounts = {}
    totshare = 0
    worker = {}
    c = EthJsonRpc('localhost', 8545)
    posts = c.eth_accounts()
    conn = sqlite3.connect(DBSHARE_FILE)
    db = conn.cursor()
    for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
        accounts[row[0]] = row[1]
        totshare += row[1]
    for row in db.execute('SELECT miner, worker FROM share GROUP BY miner'):
        worker[row[0]] = row[1]
    for acc in accounts:
        racc = accounts[acc] * reward / float(totshare)
    conn.commit()
    conn.close()
    return render_template('credits.html',
                           cround=cround,
                           worker=worker,
                           accounts=accounts,
                           posts=posts,
                           totshare=totshare,
                           server=SERVER_POOL)
Exemple #4
0
 def setUp(self):
     with open('compiled.evm') as f:
         compiled = f.read().rstrip()
     self.c = EthJsonRpc()
     self.c._call('evm_reset')
     self.cb = self.c.eth_coinbase()
     self.contract_addr = self.AddressToIPv4(self.cb, compiled)
Exemple #5
0
def check_anything_deployed(address):
    from ethjsonrpc import EthJsonRpc
    c = EthJsonRpc(DEFAULT_RPC_HOST, DEFAULT_RPC_PORT)
    if c.eth_getCode(address) == '0x0':
        print('NOTHING DEPLOYED AT SPECIFIED ADDRESS:', address)
        return False
    return True
Exemple #6
0
def test_getters():
    minimal_code = \
    """
    pragma solidity ^0.4.6;
    contract Test {
      uint256 public the_var = 5;
    }
    """
    from ethjsonrpc import EthJsonRpc
    c = EthJsonRpc('127.0.0.1', 9999)
    xx = c.eth_compileSolidity(minimal_code)
    compiled = xx['code']
    contract_tx = c.create_contract(
        c.eth_coinbase(),
        compiled,
        gas=3000000,
    )
    contract_address = str(c.get_contract_address(contract_tx))

    rr = c.call(
        address=contract_address,
        sig='the_var()',
        args=[],
        result_types=['uint256'],
    )

    assert rr[0] == 5, rr
    print('PASSED')
Exemple #7
0
 def __init__(self, *args, **kwargs):
     super(EthLocust, self).__init__(*args, **kwargs)
     server, port = self.host.split(':')
     if int(port) == 443:
         tls_flag = True
     else:
         tls_flag = False
     self.client = EthJsonRpc(server, port, tls=tls_flag)
def main():
    #
    # create rpc interface
    #
    try:
        rpc = EthJsonRpc(RPC_HOST, RPC_PORT)
    except:
        print('unable to connect to rpc server at {}:{}'.format(
            RPC_HOST, RPC_PORT))
        sys.exit(-1)

    method = sys.argv[1]

    if method == "newContract":
        owner = sys.argv[2]
        partner = sys.argv[3]
        text = sys.argv[4]

        tx = rpc.call_with_transaction(owner,
                                       CONTRACT_STORAGE_ADDRESS,
                                       'createNewContract(string,string)',
                                       [partner, text],
                                       gas=GAS)
        print(format(tx))

    elif method == "contractData":
        trans_addr = sys.argv[2]
        trans = rpc.eth_getTransactionByHash(trans_addr)
        res = Decoder.decodeABI(trans['input'],
                                'createNewContract(string,string)',
                                ['string', 'string'])
        print(res)

    elif method == "newUser":
        address = sys.argv[2]
        dataString = sys.argv[3]

        tx = rpc.call_with_transaction(address,
                                       USER_STORAGE_ADDRESS,
                                       'setUserIdentityDocs(string)',
                                       [dataString],
                                       gas=GAS)

    elif method == "identification":
        account_addr = sys.argv[2]
        transactionHashes, identityDocuments = rpc.call(
            USER_STORAGE_ADDRESS, 'getUser(address)', [account_addr],
            ['string', 'string'])
        print(identityDocuments)

    elif method == "accounts":
        account_id = sys.argv[2]
        print(rpc.eth_accounts()[int(account_id)])

    else:
        print("method not recognized!")
Exemple #9
0
def get_eth(key_from, task_price):
    # Тут стучимся в эфир
    compiled = u"0x6060604052341561000f57600080fd5b5b61099c8061001f6000396000f30060606040523615610076576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063095ea7b31461007b57806318160ddd146100d557806323b872dd146100fe57806370a0823114610177578063a9059cbb146101c4578063dd62ed3e1461021e575b600080fd5b341561008657600080fd5b6100bb600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061028a565b604051808215151515815260200191505060405180910390f35b34156100e057600080fd5b6100e8610412565b6040518082815260200191505060405180910390f35b341561010957600080fd5b61015d600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610418565b604051808215151515815260200191505060405180910390f35b341561018257600080fd5b6101ae600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506106c9565b6040518082815260200191505060405180910390f35b34156101cf57600080fd5b610204600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610713565b604051808215151515815260200191505060405180910390f35b341561022957600080fd5b610274600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108af565b6040518082815260200191505060405180910390f35b60008082148061031657506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054145b151561032157600080fd5b81600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490506104ec83600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061058183600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506105d7838261095690919063ffffffff16565b600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3600191505b509392505050565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b600061076782600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506107fc82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b92915050565b600080828401905083811015151561094b57fe5b8091505b5092915050565b600082821115151561096457fe5b81830390505b929150505600a165627a7a72305820555bd5fd700426621f595ca4d327cb2441e425da32bc02af1980faedabc29e880029"
    c = EthJsonRpc('127.0.0.1', 8545)
    c.net_version()
    # continued from above
    contract_tx = c.create_contract(settings.GENERAL_KEY, compiled, gas=300000)
    contract_addr = c.get_contract_address(contract_tx)
    value = task_price/(10**18)
    tx = c.call_with_transaction(settings.GENERAL_KEY, contract_addr, 'transferFrom({0}, {1}, {2})'.format( settings.GENERAL_KEY, key_from, value), ['Hello, world'])
    return tx
Exemple #10
0
def main01():
    load_dotenv()
    eth_host = os.environ.get('ETH_HOST')
    eth_port = os.environ.get('ETH_PORT')
    contract_addr = os.environ.get('CONTRACT_ADDR')
    c = EthJsonRpc(eth_host, eth_port)
    # data = c.call(contract_addr, 'rooms(uint256)', [0], ['Room'])
    # print(data)

    data = c.call(contract_addr, 'name()', [], ['string'])
    print(decode(data, 'string'))
Exemple #11
0
 def __init__(self, ip='127.0.0.1', port=8545, contract_id=None):
     self.connection = EthJsonRpc(ip, port)
     self.contract_id = contract_id
     self.abi_def = [{
         "constant":
         False,
         "inputs": [],
         "name":
         "dumpSaltedHashArray",
         "outputs": [{
             "name": "Hashes",
             "type": "bytes32[]"
         }, {
             "name": "Salts",
             "type": "bytes32[]"
         }, {
             "name": "Timestamps",
             "type": "uint256[]"
         }],
         "payable":
         False,
         "type":
         "function"
     }, {
         "constant":
         False,
         "inputs": [{
             "name": "Hash",
             "type": "bytes32"
         }, {
             "name": "Salt",
             "type": "bytes32"
         }],
         "name":
         "addHash",
         "outputs": [],
         "payable":
         False,
         "type":
         "function"
     }, {
         "inputs": [{
             "name": "Hash",
             "type": "bytes32"
         }, {
             "name": "Salt",
             "type": "bytes32"
         }],
         "payable":
         False,
         "type":
         "constructor"
     }]
Exemple #12
0
def index():
    # price курс BTC_ETH
    ticker = polo.api('returnTicker')
    allprice = (ticker['BTC_ETH'])
    price1 = allprice['last']
    price = price1[0:6]
    # priceUSD курс USDT_ETH
    ticker2 = polo.api('returnTicker')
    allprice2 = (ticker2['USDT_ETH'])
    price2 = allprice2['last']
    priceUSD = price2[0:5]
    accounts = {}
    totshare = 0
    reward = BLOCK_REWARD - FEE
    c = EthJsonRpc('localhost', 8545)
    posts = c.eth_accounts()
    conn = sqlite3.connect(DBSHARE_FILE)
    db = conn.cursor()
    for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
        accounts[row[0]] = row[1]
        totshare += row[1]
    for acc in accounts:
        racc = accounts[acc] * reward / float(totshare)
    conn.commit()
    conn.close()
    # запрос хэшрейтинга пула и количества блоков сети
    c = EthJsonRpc('localhost', 8545)
    Hashrate = c.eth_hashrate()
    Blocks = c.eth_blockNumber()
    return render_template('index.html',
                           price=price,
                           priceUSD=priceUSD,
                           Blocks=Blocks,
                           accounts=accounts,
                           Hashrate=Hashrate,
                           totshare=totshare,
                           cround=cround,
                           server=SERVER_POOL)
Exemple #13
0
def get_lang_version():
    minimal_code = \
    """
    pragma solidity ^0.4.6;
    contract CCCoin {
        event MainLog(bytes);
        function addLog(bytes val) { 
            MainLog(val);
        }
    }
    """
    from ethjsonrpc import EthJsonRpc
    c = EthJsonRpc('127.0.0.1', 9999)
    c.eth_compileSolidity(minimal_code)['info']['compilerVersion']
def send_payment(command):

    to_address = command["data"]["to_address"]
    from_address = command["data"]["from_address"]

    amount = float(command["data"]["amount"])

    amount_wei = int(ether_to_wei(amount))

    print "Sending {0} ETH {1} Wei to {2}".format(amount, amount_wei,
                                                  to_address)

    client = EthJsonRpc(geth_rpc_ip, 8545)

    print client.transfer(from_address, to_address, amount_wei)
Exemple #15
0
def index():
	# price курс BTC_ETH

	# priceUSD курс USDT_ETH

	accounts = {}
	totshare = 0
	reward = BLOCK_REWARD - FEE
	c = EthJsonRpc('172.16.0.7', 8545)
	posts = c.eth_accounts()
	conn = sqlite3.connect(DBSHARE_FILE)
	db = conn.cursor()
	for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
	 	accounts [row [0]] = row [1]
		totshare += row [1]
	for acc in accounts:
		racc = accounts[acc] * reward / float (totshare)
	conn.commit ()
	conn.close ()
	# запрос хэшрейтинга пула и количества блоков сети
	c = EthJsonRpc('172.16.0.7', 8545)
	Hashrate = c.eth_hashrate()
	Blocks = c.eth_blockNumber()
	return render_template('index.html', Blocks=Blocks, accounts=accounts, Hashrate=Hashrate, totshare=totshare, cround=cround, server=SERVER_POOL)
Exemple #16
0
def miner():
    # ЧТО НЕ СДЕЛАНО!
    # Необходимо вывести количество workers, общий хэшрейт майнера
    # Необходимо сформировать таблицу название workers,, хэшрейт workers, усреднённый хэшрейт workers, шары workers
    address = request.form['address'].replace('0x', '')
    payouts = []
    paylock.acquire()
    reward = BLOCK_REWARD - FEE
    accounts = {}
    totshare = 0
    worker = {}
    c = EthJsonRpc('localhost', 8545)
    posts = c.eth_accounts()
    conn = sqlite3.connect(DBSHARE_FILE)
    db = conn.cursor()
    for row in db.execute('SELECT miner, sum(diff) FROM share GROUP BY miner'):
        accounts[row[0]] = row[1]
        totshare += row[1]
    for row in db.execute('SELECT miner, worker FROM share GROUP BY miner'):
        worker[row[0]] = row[1]

    for acc in accounts:
        workers = worker[acc]
        racc = accounts[acc] * reward / float(totshare)
    conn.commit()
    conn.close()
    conn2 = sqlite3.connect(DBPAYOUT_FILE)
    db2 = conn2.cursor()

    for row in db2.execute('SELECT * FROM payout WHERE miner=?', [address]):
        payouts.append(row)

    conn2.commit()
    conn2.close()
    paylock.release()

    if address in cround['accounts']:
        rshare = cround['accounts'][address]
    else:
        rshare = 0
    print rshare, cround
    return render_template('miner.html',
                           address=address,
                           workers=workers,
                           payouts=payouts,
                           shares=rshare)
Exemple #17
0
def get_ethclient(host):
    if host == "":
        return None
    if "https" in host:
        _port = 443
        _host = host.split(':')[1].split('//')[1]
    else:
        _port = host.split(':')[2]
        _host = host.split(':')[1].split('//')[1]
    try:
        client = EthJsonRpc(host=_host, port=_port, tls=True)
    except Exception as e:
        QMessageBox.information(self,"Information",str(e))
        return
    if client.net_listening():
        return client
    else:
        return
Exemple #18
0
 def get_ethclient(self):
     host = self.comboBox_webNo.text()
     if host == "":
         return None
     if "https" in host:
         _port = 443
         _host = host.split(':')[1].split('//')[1]
     else:
         _port = host.split(':')[2]
         _host = host.split(':')[1].split('//')[1]
     try:
         self.client = EthJsonRpc(host=_host, port=_port, tls=True)
     except Exception as e:
         QMessageBox.information(self, "Information", str(e))
         return
     if self.client.net_listening():
         return self.client
     else:
         QMessageBox.warning("Warning", "节点链接失败,请检查节点")
Exemple #19
0
def synchronize(backend,
                strategy,
                user,
                response,
                is_new=False,
                *args,
                **kwargs):
    compiled = u"0x6060604052341561000f57600080fd5b5b61099c8061001f6000396000f30060606040523615610076576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063095ea7b31461007b57806318160ddd146100d557806323b872dd146100fe57806370a0823114610177578063a9059cbb146101c4578063dd62ed3e1461021e575b600080fd5b341561008657600080fd5b6100bb600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061028a565b604051808215151515815260200191505060405180910390f35b34156100e057600080fd5b6100e8610412565b6040518082815260200191505060405180910390f35b341561010957600080fd5b61015d600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610418565b604051808215151515815260200191505060405180910390f35b341561018257600080fd5b6101ae600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506106c9565b6040518082815260200191505060405180910390f35b34156101cf57600080fd5b610204600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610713565b604051808215151515815260200191505060405180910390f35b341561022957600080fd5b610274600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108af565b6040518082815260200191505060405180910390f35b60008082148061031657506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054145b151561032157600080fd5b81600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490506104ec83600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061058183600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506105d7838261095690919063ffffffff16565b600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3600191505b509392505050565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b600061076782600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506107fc82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b92915050565b600080828401905083811015151561094b57fe5b8091505b5092915050565b600082821115151561096457fe5b81830390505b929150505600a165627a7a72305820555bd5fd700426621f595ca4d327cb2441e425da32bc02af1980faedabc29e880029"
    c = EthJsonRpc('127.0.0.1', 8545)
    c.net_version()
    # continued from above
    contract_tx = c.create_contract(settings.GENERAL_KEY, compiled, gas=300000)
    contract_addr = c.get_contract_address(contract_tx)
    balans = c.call_with_transaction(
        settings.GENERAL_KEY, contract_addr,
        'eth.getBalance("{0}")'.format(settings.GENERAL_KEY), ['Hello, world'])

    user.balans = balans
    user.save()
    return True
Exemple #20
0
 def __init__(self, protocol, host, port, add_dev_code, verify_code,
              contract_dir, gas, gas_price, private_key):
     self.pp = PreProcessor()
     self.s = t.state()
     self.s.block.number = 1150000  # Homestead
     t.gas_limit = int(gas)
     self.json_rpc = EthJsonRpc(protocol=protocol, host=host, port=port)
     if private_key:
         self.user_address = '0x' + privtoaddr(
             private_key.decode('hex')).encode('hex')
     else:
         self.user_address = self.json_rpc.eth_coinbase()["result"]
     self.add_dev_code = add_dev_code == 'true'
     self.verify_code = verify_code == 'true'
     self.contract_dir = contract_dir
     self.gas = int(gas)
     self.gas_price = int(gas_price)
     self.private_key = private_key
     self.contract_addresses = {}
     self.contract_abis = {}
Exemple #21
0
def setup(host, port, contract, gas, gas_price, private_key):
    gas = int(gas)
    gas_price = int(gas_price)
    json_rpc = EthJsonRpc(host, port)
    coinbase = json_rpc.eth_coinbase()["result"]
    if private_key:
        print "Your address for your private key: {}".format(
            privtoaddr(private_key.decode('hex')).encode('hex'))
    else:
        print "Your coinbase: {}".format(coinbase)
    contract_abi = json.loads(
        '[{"inputs": [], "constant": true, "type": "function", "name": "startDate", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "CROWDFUNDING_PERIOD", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "emergencyCall", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [{"type": "address", "name": "singularDTVFundAddress"}, {"type": "address", "name": "singularDTVTokenAddress"}], "constant": false, "type": "function", "name": "setup", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "withdrawFunding", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "fundBalance", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "singularDTVFund", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "baseValue", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "TOKEN_TARGET", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "singularDTVToken", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "owner", "outputs": [{"type": "address", "name": ""}]}, {"inputs": [{"type": "uint256", "name": "valueInWei"}], "constant": false, "type": "function", "name": "changeBaseValue", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [{"type": "address", "name": ""}], "constant": true, "type": "function", "name": "investments", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "fund", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "stage", "outputs": [{"type": "uint8", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "updateStage", "outputs": [{"type": "uint8", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "valuePerShare", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "TOKEN_LOCKING_PERIOD", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "campaignEndedSuccessfully", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "workshopWaited2Years", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "constant": true, "type": "function", "name": "CAP", "outputs": [{"type": "uint256", "name": ""}]}, {"inputs": [], "constant": false, "type": "function", "name": "withdrawForWorkshop", "outputs": [{"type": "bool", "name": ""}]}, {"inputs": [], "type": "constructor"}]'
    )
    translator = ContractTranslator(contract_abi)
    data = translator.encode("emergencyCall", ()).encode("hex")
    bc_return_val = json_rpc.eth_call(to_address=contract, data=data)["result"]
    result_decoded = translator.decode("emergencyCall",
                                       bc_return_val[2:].decode("hex"))[0]
    if result_decoded:
        if private_key:
            address = privtoaddr(private_key.decode('hex'))
            nonce = int(
                json_rpc.eth_getTransactionCount('0x' + address.encode('hex'))
                ["result"][2:], 16)
            tx = Transaction(nonce, gas_price, gas, contract, 0,
                             data.decode('hex'))
            tx.sign(private_key.decode('hex'))
            raw_tx = rlp.encode(tx).encode('hex')
            transaction_hash = json_rpc.eth_sendRawTransaction(
                "0x" + raw_tx)["result"]
        else:
            transaction_hash = json_rpc.eth_sendTransaction(
                coinbase,
                to_address=contract,
                data=data,
                gas=gas,
                gas_price=gas_price)["result"]
        wait_for_transaction_receipt(json_rpc, transaction_hash)
        print 'Transaction {} for contract {} completed.'.format(
            "emergencyCall", contract)
Exemple #22
0
    def __init__(self,
                 the_code = False,
                 the_sig = None,
                 the_args = None,
                 the_address = False,
                 rpc_host = DEFAULT_RPC_HOST,
                 rpc_port = DEFAULT_RPC_PORT,
                 background_thread_sleep_time = 1.0,
                 ):
        
        self.con = EthJsonRpc(rpc_host, rpc_port)
        
        self.the_code = the_code
        self.the_sig = the_sig
        self.the_args = the_args
        
        self.contract_address = the_address
        
        assert self.the_code or self.contract_address
        
        self.loop_once_started = False
        
        self.sig_to_topic_id_cache = {}
        
        self.send_transaction_queue = Queue()
        
        self.background_thread_sleep_time = background_thread_sleep_time

        self.pending_transactions = {}  ## {tx:callback}
        
        self.is_deployed = False
        
        if the_address:
            assert self.check_anything_deployed(the_address), ('NOTHING DEPLOYED AT SPECIFIED ADDRESS:', the_address)
            self.is_deployed = True
        elif the_code:
            if auto_deploy:
                self.deploy()
 def __init__(self, protocol, host, port, gas, gas_price, contract_dir,
              optimize, account, private_key_path):
     # establish rpc connection
     self.json_rpc = EthJsonRpc(protocol=protocol, host=host, port=port)
     self.solidity = _solidity.solc_wrapper()
     self._from = None
     self.private_key = None
     # set sending account
     if account:
         self._from = self.add_0x(account)
     elif private_key_path:
         with open(private_key_path, 'r') as private_key_file:
             self.private_key = private_key_file.read().strip()
         self._from = self.add_0x(
             privtoaddr(self.private_key.decode('hex')).encode('hex'))
     else:
         accounts = self.json_rpc.eth_accounts()['result']
         if len(accounts) == 0:
             raise ValueError('No account unlocked')
         self._from = self.add_0x(accounts[0])
     # account address in right format
     if not self.is_address(self._from):
         raise ValueError('Account address is wrong')
     self.optimize = optimize
     self.contract_dir = contract_dir
     self.gas = gas
     self.gas_price = gas_price
     # references dict maps labels to addresses
     self.references = {}
     # abis dict maps addresses to abis
     self.abis = {}
     # total consumed gas
     self.total_gas = 0
     self.log('Instructions are sent from address: {}'.format(self._from))
     balance = self.hex2int(
         self.json_rpc.eth_getBalance(self._from)['result'])
     self.log('Address balance: {} Ether / {} Wei'.format(
         balance / 10.0**18, balance))
Exemple #24
0
    def __init__(
        self,
        the_code=False,
        the_sig=None,
        the_args=None,
        the_address=False,
        events_callback=False,
        deploy_callback=False,
        blocking_sleep_time=0.1,
        rpc_host=DEFAULT_RPC_HOST,
        rpc_port=DEFAULT_RPC_PORT,
        settings_confirm_states={},
        contract_address=False,
        start_at_current_block=False,
        auto_deploy=True,
        contract_thread_sleep_time=1.0,
        reorg_callback=False,
    ):
        """
        Simple contract wrapper, assists with deploying contract, sending transactions, and tracking event logs.
        
        Args:
        - the_code: solidity code for contract that should be deployed, prior to any operations.
        - the_address: address of already-deployed main contract.
        - contract_address: contract address, from previous `deploy()` call.
        - the_sig: optional constructor signature.
        - the_args: optional constructor args.
        - events_callback: callback for event messages e.g. `TheLog()`, `MintEvent()`, `LockupTokEvent()`, `TransferTokEvent()`.
        - deploy_callback: callback for contract deploys.
        - blocking_sleep_time: time to sleep when blocking and polling for a transaction receipt.
        """

        self.block_details = {}

        self.reorg_callback = reorg_callback
        self.confirmation_tracker = {
        }  ## {'block_hash':{'prev_block_hash':xx, 'block_num':yy}}

        self.done_block_nums = {}  ## {confirm_state:set()}
        self.done_transactions = {}  ## {confirm_state:set()}
        self.prev_block_num = {}  ## {confirm_state:set()}

        self.blocking_sleep_time = blocking_sleep_time

        self.c = EthJsonRpc(rpc_host, rpc_port)

        self.contract_thread_sleep_time = contract_thread_sleep_time

        self.start_at_current_block = start_at_current_block

        self.current_block_at_init = self.c.eth_blockNumber()

        if self.start_at_current_block:
            self.last_incoming_block = max(0, self.current_block_at_init - 1)
        else:
            self.last_incoming_block = 0

        self.starting_block_num = self.last_incoming_block

        self.msgs = {}  ## {block_num:[msg, msg, msg]}

        self.the_code = the_code
        self.the_sig = the_sig
        self.the_args = the_args

        self.contract_address = the_address

        assert self.the_code or self.contract_address

        self.loop_block_num = -1

        self.confirm_states = settings_confirm_states

        self.events_callback = events_callback

        self.pending_transactions = {}  ## {tx:callback}
        self.pending_logs = {}
        self.latest_block_num = -1

        self.latest_block_num_done = 0

        self.send_transaction_queue = Queue()

        self.is_deployed = False

        if auto_deploy:
            if the_address:
                assert self.check_anything_deployed(the_address), (
                    'NOTHING DEPLOYED AT SPECIFIED ADDRESS:', the_address)
                self.is_deployed = True
            elif the_code:
                self.deploy()
Exemple #25
0
    'eth_syncing',
    'eth_coinbase',
    'eth_mining',
    'eth_hashrate',
    'eth_gasPrice',
    'eth_accounts',
    'eth_blockNumber',
    'eth_getCompilers',
    'eth_newPendingTransactionFilter',
    'eth_getWork',
    #    'shh_version',
    #    'shh_newIdentity',
    #    'shh_newGroup',
]

c = EthJsonRpc()
print(len(methods))
for m in methods:
    meth = getattr(c, m)
    result = meth()
    print('%s: %s (%s)' % (m, result, type(result)))

################################################################################
print('*' * 80)

addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe'
for x in ['earliest', 'latest', 'pending', 150000]:
    result = c.eth_getTransactionCount(addr, x)
    print('eth_getTransactionCount: %s (%s)' % (result, type(result)))

b = (231301, '0x9476018748ba1dae5bdf5e3725f8966df1fa127d49f58e66f621bf6868a23c85')
def main():
    #
    # check
    #
    assert os.path.isfile(CONTRACT) and 'contract file not found'

    #
    # now, just connect to our own blockchain node via rpc interface
    #
    try:
        rpc = EthJsonRpc(RPC_HOST, RPC_PORT)
        print('-' * 80)
        print('client software: {}'.format(rpc.web3_clientVersion()))
        print('block: {}'.format(rpc.eth_blockNumber()))
        print('address: {}'.format(rpc.eth_coinbase()))
    except:
        print('unable to connect to rpc server at {}:{}'.format(
            RPC_HOST, RPC_PORT))
        sys.exit(-1)

    #
    # compile contract
    #
    print('-' * 80)
    print('compiling contract...')
    os.system('solcjs --bin {} > /dev/null'.format(CONTRACT))
    with open(CONTRACT_COMPILED, 'r') as f:
        contract_bin = f.read()
    print(contract_bin)

    #
    # create contract
    #
    print('-' * 80)
    lastBlock = rpc.eth_blockNumber()
    contract_tx = rpc.create_contract(
        rpc.eth_coinbase(), contract_bin,
        gas=GAS)  #send to address 0 by default to create contract
    print('contract sent, waiting for it to be mined...')
    #
    # get current block count
    #
    numTry = 0
    contract_addr = None
    while True:
        curBlock = rpc.eth_blockNumber()
        if curBlock > lastBlock:
            lastBlock = curBlock
            numTry += 1
            try:
                contract_addr = rpc.get_contract_address(contract_tx)
                if rpc.eth_getCode(
                        contract_addr
                ) == '0x0':  #it means the binary code of the contract is stil under compiling
                    raise Exception()
                print('contract mined (block: {})'.format(curBlock))
                break
            except:
                print('new block detected, but contract not mined')
                print('number of trying: {}'.format(numTry))
                if numTry == WAIT_BLOCKS:
                    print('publishing contract failed')
                    sys.exit(-1)
        time.sleep(1)
    #
    # return contract addr
    #
    print('-' * 80)
    print('contract_address:\n\n\n--> {} <--\n\n'.format(contract_addr))
    print('-' * 80)
def main():
    #
    # receive contract addr
    #
    if len(sys.argv) != 3:
        print('Usage:\npython user.py <contract addr> <account addr>')
        sys.exit(-1)
    contract_addr = sys.argv[1]
    account_addr = sys.argv[2]

    #
    # create rpc interface
    #
    try:
        print('-' * 80)
        rpc = EthJsonRpc(RPC_HOST, RPC_PORT)
        print('client software: {}'.format(rpc.web3_clientVersion()))
        print('block: {}'.format(rpc.eth_blockNumber()))
        print('address: {}'.format(rpc.eth_coinbase()))
    except:
        print('unable to connect to rpc server at {}:{}'.format(
            RPC_HOST, RPC_PORT))
        sys.exit(-1)

    #
    # check contract is online
    #
    print('-' * 80)
    if rpc.eth_getCode(contract_addr) == '0x0':
        print('!!! contract code not available on blockchain !!!')
        sys.exit(-1)
    print('found contract on blockchain!')

    #
    # console
    #
    topics = []
    print('-' * 80)
    print('starting chat command line...')
    while True:
        #
        # simply read input
        #
        sys.stdout.write('>> ')
        command = sys.stdin.readline()

        #
        # quit?
        #
        if 'q' in command:
            sys.exit(0)

        #
        # show help
        #
        elif command == '\n' or 'help' in command:
            print('commands: help, send, status, topics, search, listen')

        #
        # compose new message
        #
        elif 'send' in command:
            print('-' * 80)
            print('[composing new message]')
            sys.stdout.write('message....: ')
            msg = sys.stdin.readline().strip()
            sys.stdout.write('image file.: ')
            img = sys.stdin.readline().strip()
            sys.stdout.write('custom tags: ')
            tag = sys.stdin.readline().strip()
            print('-' * 80)
            print('sending...')
            # loading image
            try:
                image = Image.open(img)
            except Exception as e:
                print('loading {} failed'.format(img))
                continue
            # prediction
            print('precessing image...')
            label = ImageClassifier.predict(img)
            if label is None:
                print('classification failed')
                continue
            print('label: {}'.format(label))
            tag += ' #' + label
            bs = ImageHelper.imgToBytes(image)
            tx = rpc.call_with_transaction(
                account_addr,
                contract_addr,
                'setNewUserState(string,bytes,string)', [msg, bs, tag],
                gas=GAS)
            print('done, transaction id: {}'.format(tx))

        #
        # get own last post
        #
        elif 'status' in command:
            print('-' * 80)
            print('[receiving last post]')
            userMessage, userImage, userTags = rpc.call(
                contract_addr, 'getUserState(address)', [account_addr],
                ['string', 'bytes', 'string'])
            if not userMessage:
                print('nothing posted yet')
                continue
            print('  content: {}'.format(userMessage))
            print('  tags...: {}'.format(userTags))
            ImageHelper.bytesToImg(userImage).show()

        #
        # set tag filters
        #
        elif 'topics' in command:
            topics = [t.strip() for t in command.split()[1:]]
            if len(topics) == 0:
                print('please provide actual topics after <topics> command')
                continue
            print('filter set for messages on topics: {}'.format(topics))

        #
        # search complete blockchain for messages with certain tags
        #
        elif 'search' in command:
            if len(topics) == 0:
                print('call topics first')
                continue
            curBlock = rpc.eth_blockNumber()
            for i in range(curBlock + 1):
                for trans in rpc.eth_getBlockByNumber(i)['transactions']:
                    res = Decoder.decodeABI(trans['input'])
                    if res is None:
                        continue
                    msg, code, tags = res
                    if all(t not in tags for t in topics):
                        continue
                    print('-' * 80)
                    print('message from user {} (block {}):'.format(
                        trans['from'], i))
                    print('  content: {}'.format(msg))
                    print('  tags...: {}'.format(tags))
                    ImageHelper.bytesToImg(code).show(title='{}'.format(tags))

        #
        # start listening for messages
        #
        elif 'listen' in command:
            if len(topics) == 0:
                print('call topics first')
                continue
            global LISTENING
            LISTENING = True
            curBlock = rpc.eth_blockNumber()
            while LISTENING:
                newBlock = rpc.eth_blockNumber()
                if newBlock > curBlock:
                    print('new block detected ({})'.format(newBlock))
                    curBlock = newBlock
                    for trans in rpc.eth_getBlockByNumber(
                            newBlock)['transactions']:
                        res = Decoder.decodeABI(trans['input'])
                        if res is None:
                            continue
                        msg, code, tags = res
                        if all(t not in tags for t in topics):
                            continue
                        print('-' * 80)
                        print('message from user {} (block {}):'.format(
                            trans['from'], newBlock))
                        print('  content: {}'.format(msg))
                        print('  tags...: {}'.format(tags))
                        ImageHelper.bytesToImg(code).show(
                            title='{}'.format(tags))
                time.sleep(1)

        #
        # default response
        #
        else:
            print('command not recognized')
Exemple #28
0
#! /bin/env python

#pip install ethjsonrpc

from ethjsonrpc import EthJsonRpc

c = EthJsonRpc('127.0.0.1', 8545)
print c.web3_clientVersion()

accounts = c.eth_accounts()
print c.eth_getBalance(address=accounts[0])
Exemple #29
0
from ethjsonrpc import EthJsonRpc

c = EthJsonRpc('172.17.0.26', 8545)

print 'Net Version', c.net_version()
print 'web3 client version', c.web3_clientVersion()
print 'gas price', c.eth_gasPrice()
print 'block number', c.eth_blockNumber()
print 'eth syncing', c.eth_syncing()
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
#!flask/bin/python
from flask import Flask, jsonify, abort, 
        request, make_response, url_for

from ethjsonrpc import EthJsonRpc
import time
import datetime

c = EthJsonRpc('127.0.0.1', 8101)

contract_addr = "0xdd44F726FDd682c20857e9CD37F0dA8bf78518D7"
stationID = [123]
balance = c.eth_getBalance(contract_addr)
print "Starting Balance = " + str(balance)
    
      
app = Flask(__name__, static_url_path="")

#curl -i http://localhost:5000/api/stationstate/123
@app.route('/api/stationstate/<int:id>', methods=['GET'])
def getStationState(id):
    result = c.call(contract_addr, 'getStationState(uint256)', 
                    [id], ['bool'])
    return jsonify(result)