コード例 #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)
コード例 #2
0
ファイル: test.py プロジェクト: sl4mmer/eth_rpc_api
tx = '0x27191ea9e8228c98bc4418fa60843540937b0c615b2db5e828756800f533f8cd'
print(c.eth_getTransactionReceipt(tx))

b = (246294, '0x3d596ca3c7b344419567957b41b2132bb339d365b6b6b3b6a7645e5444914a16')
index = 0
print(c.eth_getUncleByBlockHashAndIndex(b[1], index))

for x in ['earliest', 'latest', 'pending', b[0]]:
    print(c.eth_getUncleByBlockNumberAndIndex(b[0], index))

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

addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe'
for x in ['earliest', 'latest', 'pending', 150000]:
    print(c.eth_getBalance(addr, x))

addr = '0x407d73d8a49eeb85d32cf465507dd71d507100c1'
for x in ['earliest', 'latest', 'pending', 2]:
    print(c.eth_getStorageAt(addr, 0, x))

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

hash_rate = 1000000
client_id = '0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c'
print(c.eth_submitHashrate(hash_rate, client_id))

digest = c.web3_sha3('')
print(digest)
# keccak-256, not sha3-256
コード例 #3
0
ファイル: rpc_test.py プロジェクト: fruit37/Town-Crier
#! /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])
コード例 #4
0
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)

#curl -i http://localhost:5000/api/station/123
@app.route('/api/station/<int:id>', methods=['GET'])
def getStation(id):
コード例 #5
0
from ethjsonrpc.utils import wei_to_ether, ether_to_wei

c = EthJsonRpc('192.168.1.129', 8545)

from_address = "0x90b983390bef91b17f3a2f2d7eb9121c1214fc6b"
to_address = "0x16Ba1a0e4F6bA1E9B614ae8C25d101eA7441A0a1"

print c.net_version()

print c.web3_clientVersion()

print c.eth_gasPrice()

print c.eth_blockNumber()

print wei_to_ether(c.eth_getBalance(from_address))

print wei_to_ether(c.eth_getBalance(to_address))

# print c.web3_toWei(0.01, "ether")

amount = int(ether_to_wei(0.001))

print type(amount)

print amount

print hex(amount)

print c.transfer(from_address, to_address, amount)
コード例 #6
0
class EthDeploy:
    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._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(
                encode(privtoaddr(decode(self.private_key, 'hex')), '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))

    def is_address(self, string):
        return len(self.add_0x(string)) == 42

    @staticmethod
    def hex2int(_hex):
        return int(_hex, 16)

    @staticmethod
    def add_0x(string):
        if not string.startswith('0x'):
            return '0x' + string
        return string

    @staticmethod
    def strip_0x(string):
        if string.startswith('0x'):
            return string[2:]
        return string

    @staticmethod
    def log(string):
        logger.info(string)

    def format_reference(self, string):
        return self.add_0x(string) if self.is_address(string) else string

    def log_transaction_receipt(self, transaction_receipt):
        gas_used = self.hex2int(transaction_receipt['gasUsed'])
        self.total_gas += gas_used
        self.log(
            'Transaction receipt: {} block number, {} gas used, {} cumulative gas used'
            .format(self.hex2int(transaction_receipt['blockNumber']), gas_used,
                    self.hex2int(transaction_receipt['cumulativeGasUsed'])))

    def get_transaction_receipt(self, transaction_hash):
        return self.json_rpc.eth_getTransactionReceipt(
            transaction_hash)['result']

    def wait_for_transaction_receipt(self, transaction_hash):
        while self.get_transaction_receipt(transaction_hash) is None:
            self.log(
                'Waiting for transaction receipt {}'.format(transaction_hash))
            time.sleep(5)
        return self.get_transaction_receipt(transaction_hash)

    def replace_references(self, a):
        if isinstance(a, list):
            return [self.replace_references(i) for i in a]
        else:
            return self.references[a] if isinstance(
                a, basestring) and a in self.references else a

    def get_nonce(self):
        transaction_count = self.json_rpc.eth_getTransactionCount(
            self._from, default_block='pending')['result']
        return self.hex2int(self.strip_0x(transaction_count))

    def get_raw_transaction(self, to='', value=0, data=''):
        nonce = self.get_nonce()
        tx = Transaction(nonce, self.gas_price, self.gas, to, value,
                         decode(data, 'hex'))
        tx.sign(decode(self.private_key, 'hex'))
        return self.add_0x(encode(rlp.encode(tx), 'hex'))

    def compile_code(self, path):
        # create list of valid paths
        absolute_path = self.contract_dir if self.contract_dir.startswith(
            '/') else '{}/{}'.format(os.getcwd(), self.contract_dir)
        sub_dirs = [x[0] for x in os.walk(absolute_path)]
        extra_args = ' '.join(
            ['{}={}'.format(d.split('/')[-1], d) for d in sub_dirs])
        # compile code
        combined = _solidity.compile_last_contract(path,
                                                   libraries=self.references,
                                                   combined='bin,abi',
                                                   optimize=self.optimize,
                                                   extra_args=extra_args)
        bytecode = combined['bin_hex']
        abi = combined['abi']
        return bytecode, abi

    def deploy(self, _from, file_path, libraries, value, params, label):
        # replace library placeholders
        if libraries:
            for library_name, library_address in libraries.items():
                self.references[library_name] = self.replace_references(
                    self.strip_0x(library_address))
        if self.contract_dir:
            file_path = '{}/{}'.format(self.contract_dir, file_path)
        bytecode, abi = self.compile_code(file_path)
        if not label:
            label = file_path.split("/")[-1].split(".")[0]
        if params:
            translator = ContractTranslator(abi)
            # replace constructor placeholders
            params = [self.replace_references(p) for p in params]
            bytecode += encode(translator.encode_constructor_arguments(params),
                               'hex')
        # deploy contract
        self.log('Deployment transaction for {} sent'.format(
            label if label else 'unknown'))
        tx_response = None
        if self.private_key:
            raw_tx = self.get_raw_transaction(value=value, data=bytecode)
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Deploy failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendRawTransaction(raw_tx)
        else:
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Deploy failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendTransaction(
                    self.add_0x(_from if _from else self._from),
                    value=value,
                    data=self.add_0x(bytecode),
                    gas=self.gas,
                    gas_price=self.gas_price)
        transaction_receipt = self.wait_for_transaction_receipt(
            self.add_0x(tx_response['result']))
        contract_address = self.strip_0x(
            transaction_receipt['contractAddress'])
        self.references[label] = contract_address
        self.abis[contract_address] = abi
        self.log('Contract {} created at address {}'.format(
            label if label else 'unknown', self.add_0x(contract_address)))
        self.log_transaction_receipt(transaction_receipt)

    def send_transaction(self, _from, to, value, name, params, abi):
        reference = to
        to = self.replace_references(to)
        data = ''
        if name or abi:
            if not name:
                name = abi['name']
            abi = self.abis[to] if to in self.abis else [abi]
            translator = ContractTranslator(abi)
            data = encode(
                translator.encode(name, self.replace_references(params)),
                "hex")
        self.log('Transaction to {}{} sent'.format(
            self.format_reference(reference),
            ' calling {} function'.format(name) if name else ''))
        tx_response = None
        if self.private_key:
            raw_tx = self.get_raw_transaction(to=to, value=value, data=data)
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Transaction failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendRawTransaction(raw_tx)
        else:
            while tx_response is None or 'error' in tx_response:
                if tx_response and 'error' in tx_response:
                    self.log('Transaction failed with error {}'.format(
                        tx_response['error']['message']))
                    time.sleep(5)
                tx_response = self.json_rpc.eth_sendTransaction(
                    self.add_0x(_from if _from else self._from),
                    to_address=self.add_0x(to),
                    value=value,
                    data=self.add_0x(data),
                    gas=self.gas,
                    gas_price=self.gas_price)
        transaction_hash = tx_response['result']
        transaction_receipt = self.wait_for_transaction_receipt(
            self.add_0x(transaction_hash))
        self.log('Transaction to {}{} successful'.format(
            self.format_reference(reference),
            ' calling {} function'.format(name) if name else ''))
        self.log_transaction_receipt(transaction_receipt)

    def call(self, _from, to, value, name, params, label, assertion, abi):
        reference = to
        to = self.replace_references(to)
        if not name:
            name = abi['name']
        abi = self.abis[to] if to in self.abis else [abi]
        translator = ContractTranslator(abi)
        data = encode(translator.encode(name, self.replace_references(params)),
                      'hex')
        response = self.json_rpc.eth_call(
            self.add_0x(to),
            from_address=self.add_0x(_from if _from else self._from),
            value=value,
            data=self.add_0x(data),
            gas=self.gas,
            gas_price=self.gas_price)
        result = translator.decode(
            name, decode(self.strip_0x(response['result']), 'hex'))
        result = result if len(result) > 1 else result[0]
        if label:
            self.references[label] = result
        if assertion:
            expected_result = self.replace_references(assertion)
            if isinstance(expected_result, int) or isinstance(
                    expected_result, long):
                assert result == expected_result
            else:
                assert result.lower() == self.strip_0x(expected_result.lower())
            self.log('Assertion of {} at {} successful'.format(
                name, self.format_reference(reference)))
        else:
            self.log('Call to {} calling function {} successful'.format(
                self.format_reference(reference), name))

    def process(self, f):
        # read instructions file
        with open(f, 'r') as instructions_file:
            instructions = json.load(instructions_file)
        for i in instructions:
            if i['type'] == 'abi':
                for address in i['addresses']:
                    self.abis[self.strip_0x(address)] = i['abi']
            if i['type'] == 'deployment':
                self.deploy(i['from'] if 'from' in i else None,
                            i['file'] if 'file' in i else None,
                            i['libraries'] if 'libraries' in i else None,
                            i['value'] if 'value' in i else 0,
                            i['params'] if 'params' in i else (),
                            i['label'] if 'label' in i else None)
            elif i["type"] == "transaction":
                self.send_transaction(
                    i['from'] if 'from' in i else None,
                    i['to'] if 'to' in i else None,
                    i['value'] if 'value' in i else 0,
                    i['name'] if 'name' in i else None,
                    i['params'] if 'params' in i else (),
                    i['abi'] if 'abi' in i else None,
                )
            elif i["type"] == "call":
                self.call(
                    i['from'] if 'from' in i else None,
                    i['to'] if 'to' in i else None,
                    i['value'] if 'value' in i else 0,
                    i['name'] if 'name' in i else None,
                    i['params'] if 'params' in i else (),
                    i['label'] if 'label' in i else None,
                    i['assertion'] if 'assertion' in i else None,
                    i['abi'] if 'abi' in i else None,
                )
        self.log('-' * 96)
        self.log('Summary: {} gas used, {} Ether / {} Wei spent on gas'.format(
            self.total_gas, self.total_gas * self.gas_price / 10.0**18,
            self.total_gas * self.gas_price))
        for reference, value in self.references.items():
            self.log('{} references {}'.format(
                reference,
                self.add_0x(value) if isinstance(value, unicode) else value))
        self.log('-' * 96)
コード例 #7
0
class Deploy:
    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 = {}

    def wait_for_transaction_receipt(self, transaction_hash):
        while self.json_rpc.eth_getTransactionReceipt(
                transaction_hash)['result'] is None:
            logging.info(
                'Waiting for transaction receipt {}'.format(transaction_hash))
            time.sleep(5)

    def replace_address(self, a):
        return self.contract_addresses[a] if isinstance(
            a, basestring) and a in self.contract_addresses else a

    def get_nonce(self):
        return int(
            self.json_rpc.eth_getTransactionCount(
                self.user_address)["result"][2:], 16)

    def get_raw_transaction(self, data, contract_address=''):
        nonce = self.get_nonce()
        tx = Transaction(nonce, self.gas_price, self.gas, contract_address, 0,
                         data.decode('hex'))
        tx.sign(self.private_key.decode('hex'))
        return rlp.encode(tx).encode('hex')

    def code_is_valid(self, contract_address, compiled_code):
        deployed_code = self.json_rpc.eth_getCode(contract_address)["result"]
        locally_deployed_code_address = self.s.evm(
            compiled_code.decode("hex")).encode("hex")
        locally_deployed_code = self.s.block.get_code(
            locally_deployed_code_address).encode("hex")
        return deployed_code == "0x" + locally_deployed_code

    @staticmethod
    def compile_code(code, language):
        combined = languages[language].combined(code)
        compiled_code = combined[-1][1]["bin_hex"]
        abi = combined[-1][1]["abi"]
        return compiled_code, abi

    @staticmethod
    def replace_library_placeholders(bytecode, addresses):
        if addresses:
            for library_name, library_address in addresses.iteritems():
                bytecode = bytecode.replace(
                    "__{}{}".format(library_name,
                                    "_" * (38 - len(library_name))),
                    library_address[2:])
        return bytecode

    def deploy_code(self, file_path, params, addresses):
        if addresses:
            addresses = dict([(k, self.replace_address(v))
                              for k, v in addresses.iteritems()])
        language = "solidity" if file_path.endswith(".sol") else "serpent"
        code = self.pp.process(file_path,
                               add_dev_code=self.add_dev_code,
                               contract_dir=self.contract_dir,
                               addresses=addresses)
        # compile code
        bytecode, abi = self.compile_code(code, language)
        # replace library placeholders
        bytecode = self.replace_library_placeholders(bytecode, addresses)
        if params:
            translator = ContractTranslator(abi)
            # replace constructor placeholders
            params = [self.replace_address(p) for p in params]
            bytecode += translator.encode_constructor_arguments(params).encode(
                "hex")
        logging.info(
            'Try to create contract with length {} based on code in file: {}'.
            format(len(bytecode), file_path))
        if self.private_key:
            raw_tx = self.get_raw_transaction(bytecode)
            tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx)
            while "error" in tx_response:
                logging.info('Deploy failed with error {}. Retry!'.format(
                    tx_response['error']))
                time.sleep(5)
                tx_response = self.json_rpc.eth_sendRawTransaction("0x" +
                                                                   raw_tx)
        else:
            tx_response = self.json_rpc.eth_sendTransaction(
                self.user_address,
                data=bytecode,
                gas=self.gas,
                gas_price=self.gas_price)
            while "error" in tx_response:
                logging.info('Deploy failed with error {}. Retry!'.format(
                    tx_response['error']))
                time.sleep(5)
                tx_response = self.json_rpc.eth_sendTransaction(
                    self.user_address,
                    data=bytecode,
                    gas=self.gas,
                    gas_price=self.gas_price)
        transaction_hash = tx_response['result']
        self.wait_for_transaction_receipt(transaction_hash)
        contract_address = self.json_rpc.eth_getTransactionReceipt(
            transaction_hash)["result"]["contractAddress"]
        # Verify deployed code with locally deployed code
        if self.verify_code and not self.code_is_valid(contract_address,
                                                       bytecode):
            logging.info('Deploy of {} failed. Retry!'.format(file_path))
            self.deploy_code(file_path, params, addresses)
        contract_name = file_path.split("/")[-1].split(".")[0]
        self.contract_addresses[contract_name] = contract_address
        self.contract_abis[contract_name] = abi
        logging.info('Contract {} was created at address {}.'.format(
            file_path, contract_address))

    def send_transaction(self, contract, name, params):
        contract_address = self.replace_address(contract)
        contract_abi = self.contract_abis[contract]
        translator = ContractTranslator(contract_abi)
        data = translator.encode(name,
                                 [self.replace_address(p)
                                  for p in params]).encode("hex")
        logging.info('Try to send {} transaction to contract {}.'.format(
            name, contract))
        if self.private_key:
            raw_tx = self.get_raw_transaction(data, contract_address)
            tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx)
            while 'error' in tx_response:
                logging.info('Transaction failed with error {}. Retry!'.format(
                    tx_response['error']))
                time.sleep(5)
                tx_response = self.json_rpc.eth_sendRawTransaction("0x" +
                                                                   raw_tx)
        else:
            tx_response = self.json_rpc.eth_sendTransaction(
                self.user_address,
                to_address=contract_address,
                data=data,
                gas=self.gas,
                gas_price=self.gas_price)
            while 'error' in tx_response:
                logging.info('Transaction failed with error {}. Retry!'.format(
                    tx_response['error']))
                time.sleep(5)
                tx_response = self.json_rpc.eth_sendTransaction(
                    self.user_address,
                    to_address=contract_address,
                    data=data,
                    gas=self.gas,
                    gas_price=self.gas_price)
        transaction_hash = tx_response['result']
        self.wait_for_transaction_receipt(transaction_hash)
        logging.info('Transaction {} for contract {} completed.'.format(
            name, contract))

    def assert_call(self, contract, name, params, return_value):
        contract_address = self.replace_address(contract)
        return_value = self.replace_address(return_value)
        contract_abi = self.contract_abis[contract]
        translator = ContractTranslator(contract_abi)
        data = translator.encode(name,
                                 [self.replace_address(p)
                                  for p in params]).encode("hex")
        logging.info('Try to assert return value of {} in contract {}.'.format(
            name, contract))
        bc_return_val = self.json_rpc.eth_call(to_address=contract_address,
                                               data=data)["result"]
        result_decoded = translator.decode(name,
                                           bc_return_val[2:].decode("hex"))
        result_decoded = result_decoded if len(
            result_decoded) > 1 else result_decoded[0]
        assert result_decoded == return_value
        logging.info(
            'Assertion successful for return value of {} in contract {}.'.
            format(name, contract))

    def process(self, f):
        with open(f) as data_file:
            instructions = json.load(data_file)
            logging.info('Your address: {}'.format(self.user_address))
            for instruction in instructions:
                logging.info('Your balance: {} Wei'.format(
                    int(
                        self.json_rpc.eth_getBalance(
                            self.user_address)['result'], 16)))
                if instruction["type"] == "deployment":
                    self.deploy_code(
                        instruction["file"],
                        instruction["params"]
                        if "params" in instruction else None,
                        instruction["addresses"]
                        if "addresses" in instruction else None,
                    )
                elif instruction["type"] == "transaction":
                    self.send_transaction(
                        instruction["contract"],
                        instruction["name"],
                        instruction["params"]
                        if "params" in instruction else [],
                    )
                elif instruction["type"] == "assertion":
                    self.assert_call(
                        instruction["contract"], instruction["name"],
                        instruction["params"] if "params" in instruction else
                        [], instruction["return"])
            for contract_name, contract_address in self.contract_addresses.iteritems(
            ):
                logging.info('Contract {} was created at address {}.'.format(
                    contract_name, contract_address))
コード例 #8
0
import RPi.GPIO as GPIO ## Import GPIO library

## Use board pin numbering
GPIO.setmode(GPIO.BOARD) 

## Setup GPIO Pin 7 to OUT
GPIO.setup(7, GPIO.OUT) 

# Connect to Blockchain network
c = EthJsonRpc('192.168.1.20', 8101)

# Device account address to watch
account_to_watch = "0x0cafd203ca406bb39985d0f70d55b44b78d756eb"

# Get balance in the device account
balance = c.eth_getBalance(account_to_watch)
print "Starting Balance = " + str(balance)

# Switch is off initially
onStatus=False
GPIO.output(7,False) ## Turn off GPIO pin 7

while True:
    newbalance = c.eth_getBalance(account_to_watch)
    if onStatus==True:
        nowTime = datetime.datetime.now()
        timeElapsed = nowTime - onTime
        #print "Switch ON, Elapsed Time: " + str(timeElapsed.seconds)
        if timeElapsed.seconds >= 60:
            print "Switching OFF"
            onStatus=False
コード例 #9
0
        s = rpcaddr.split(":")
        netaddr = s[0]
        port = int(s[1])
    else:
        netaddr = rpcaddr
        port = ETH_PORT
    return (netaddr, port)


if __name__ == "__main__":
    # parse arguments
    parser = argparse.ArgumentParser(description='.')
    parser.add_argument("rpcaddr",
                        help="RPC address of an ethereum node",
                        default="127.0.0.1:8545")
    parser.add_argument("-w",
                        "--wallet",
                        help="etherbase/wallet address",
                        default="0")
    args = parser.parse_args()

    netaddr, port = parseRpcAddr(args.rpcaddr)
    eth_client = EthJsonRpc(netaddr, port)
    if args.wallet == "0":
        wallet = eth_client.eth_coinbase()
    else:
        wallet = args.wallet

    balance = eth_client.eth_getBalance(wallet)
    print balance
コード例 #10
0
ファイル: test.py プロジェクト: balakrishnan2/b
print c.eth_getTransactionReceipt(tx)

b = (246294,
     '0x3d596ca3c7b344419567957b41b2132bb339d365b6b6b3b6a7645e5444914a16')
index = 0
print c.eth_getUncleByBlockHashAndIndex(b[1], index)

for x in ['earliest', 'latest', 'pending', b[0]]:
    print c.eth_getUncleByBlockNumberAndIndex(b[0], index)

################################################################################
print '*' * 80

addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe'
for x in ['earliest', 'latest', 'pending', 150000]:
    print c.eth_getBalance(addr, x)

addr = '0x407d73d8a49eeb85d32cf465507dd71d507100c1'
for x in ['earliest', 'latest', 'pending', 2]:
    print c.eth_getStorageAt(addr, 0, x)

################################################################################
print '*' * 80

hash_rate = 1000000
client_id = '0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c'
print c.eth_submitHashrate(hash_rate, client_id)

digest = c.web3_sha3('')
print digest
# keccak-256, not sha3-256
コード例 #11
0
ファイル: test.py プロジェクト: DestinyTeam/ethjsonrpc
tx = '0x27191ea9e8228c98bc4418fa60843540937b0c615b2db5e828756800f533f8cd'
print c.eth_getTransactionReceipt(tx)

b = (246294, '0x3d596ca3c7b344419567957b41b2132bb339d365b6b6b3b6a7645e5444914a16')
index = 0
print c.eth_getUncleByBlockHashAndIndex(b[1], index)

for x in ['earliest', 'latest', 'pending', b[0]]:
    print c.eth_getUncleByBlockNumberAndIndex(b[0], index)

################################################################################
print '*' * 80

addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe'
for x in ['earliest', 'latest', 'pending', 150000]:
    print c.eth_getBalance(addr, x)

addr = '0x407d73d8a49eeb85d32cf465507dd71d507100c1'
for x in ['earliest', 'latest', 'pending', 2]:
    print c.eth_getStorageAt(addr, 0, x)

################################################################################
print '*' * 80

hash_rate = 1000000
client_id = '0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c'
print c.eth_submitHashrate(hash_rate, client_id)

digest = c.web3_sha3('')
print digest
# keccak-256, not sha3-256
コード例 #12
0
ファイル: client.py プロジェクト: chipyaya/Projects_exp
from ethjsonrpc import EthJsonRpc
c = EthJsonRpc('127.0.0.1', 8545)
print(c.eth_gasPrice())
addr_list = c.eth_accounts()
print(addr_list)
print(c.eth_getBalance(addr_list[0], 'latest'))
print(c.eth_getBalance(addr_list[1], 'latest'))
print(c.eth_getTransactionCount (addr_list[0], 'latest'))
#c.eth_sendTransaction(addr_list[0], addr_list[1], 30400, c.eth_gasPrice(), 1000000, 0)
#print(c.db_putString('testDB', 'myKey', 'myString'))
#print(c.db_getString('testDB', 'myKey'))


コード例 #13
0
ファイル: test.py プロジェクト: simonvadee/ethjsonrpc
print(geth_client.eth_getTransactionReceipt(tx))

b = (246294,
     '0x3d596ca3c7b344419567957b41b2132bb339d365b6b6b3b6a7645e5444914a16')
index = 0
print(geth_client.eth_getUncleByBlockHashAndIndex(b[1], index))

for x in ['earliest', 'latest', 'pending', b[0]]:
    print(geth_client.eth_getUncleByBlockNumberAndIndex(b[0], index))

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

addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe'
for x in ['earliest', 'latest', 'pending', 150000]:
    print(geth_client.eth_getBalance(addr, x))

addr = '0x407d73d8a49eeb85d32cf465507dd71d507100c1'
for x in ['earliest', 'latest', 'pending', 2]:
    print(geth_client.eth_getStorageAt(addr, 0, x))

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

hash_rate = 1000000
client_id = '0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c'
print(geth_client.eth_submitHashrate(hash_rate, client_id))

digest = geth_client.web3_sha3('')
print(digest)
# keccak-256, not sha3-256