jsonrpc_factory.py (1035B)
1 # standard imports 2 import os 3 import sys 4 5 # local imports 6 from chainlib.jsonrpc import JSONRPCRequest 7 from chainlib.chain import ChainSpec 8 from chainlib.connection import ( 9 JSONRPCHTTPConnection, 10 RPCConnection, 11 ConnType, 12 ) 13 14 15 # set up node connection and execute rpc call 16 rpc_provider = os.environ.get('RPC_PROVIDER', 'http://localhost:8545') 17 RPCConnection.register_constructor(ConnType.HTTP, JSONRPCHTTPConnection) 18 19 tag = 'baz' 20 chain_spec = ChainSpec('foo', 'bar', 42, tag=tag) 21 RPCConnection.register_location(rpc_provider, chain_spec, tag='default') 22 conn = RPCConnection.connect(chain_spec, 'default') 23 24 # check the connection 25 if not conn.check(): 26 sys.stderr.write('node {} not usable\n'.format(rpc_provider)) 27 sys.exit(1) 28 29 # build and send rpc call 30 g = JSONRPCRequest() 31 o = g.template() 32 o['method'] = 'eth_blockNumber' 33 r = conn.do(o) 34 35 # interpret result for humans 36 try: 37 block_number = int(r, 10) 38 except ValueError: 39 block_number = int(r, 16) 40 41 print('block number {}'.format(block_number))