PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/electrumx_rpc.py

https://bitbucket.org/arfonzo/electrumx4egc
Python | 93 lines | 63 code | 19 blank | 11 comment | 13 complexity | 8f6893dd4ee6ad065b8fdf2fe5354515 MD5 | raw file
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2016, Neil Booth
  4. #
  5. # All rights reserved.
  6. #
  7. # See the file "LICENCE" for information about the copyright
  8. # and warranty status of this software.
  9. '''Script to send RPC commands to a running ElectrumX server.'''
  10. import argparse
  11. import asyncio
  12. import json
  13. from functools import partial
  14. from os import environ
  15. from lib.jsonrpc import JSONSession, JSONRPCv2
  16. from server.controller import Controller
  17. class RPCClient(JSONSession):
  18. def __init__(self):
  19. super().__init__(version=JSONRPCv2)
  20. self.max_send = 0
  21. self.max_buffer_size = 5*10**6
  22. async def wait_for_response(self):
  23. await self.items_event.wait()
  24. await self.process_pending_items()
  25. def send_rpc_request(self, method, params):
  26. handler = partial(self.handle_response, method)
  27. self.send_request(handler, method, params)
  28. def handle_response(self, method, result, error):
  29. if method in ('groups', 'peers', 'sessions') and not error:
  30. lines_func = getattr(Controller, '{}_text_lines'.format(method))
  31. for line in lines_func(result):
  32. print(line)
  33. elif error:
  34. print('error: {} (code {:d})'
  35. .format(error['message'], error['code']))
  36. else:
  37. print(json.dumps(result, indent=4, sort_keys=True))
  38. def rpc_send_and_wait(port, method, params, timeout=15):
  39. loop = asyncio.get_event_loop()
  40. coro = loop.create_connection(RPCClient, 'localhost', port)
  41. try:
  42. transport, rpc_client = loop.run_until_complete(coro)
  43. rpc_client.send_rpc_request(method, params)
  44. try:
  45. coro = rpc_client.wait_for_response()
  46. loop.run_until_complete(asyncio.wait_for(coro, timeout))
  47. except asyncio.TimeoutError:
  48. print('request timed out after {}s'.format(timeout))
  49. except OSError:
  50. print('cannot connect - is ElectrumX catching up, not running, or '
  51. 'is {:d} the wrong RPC port?'.format(port))
  52. finally:
  53. loop.close()
  54. def main():
  55. '''Send the RPC command to the server and print the result.'''
  56. parser = argparse.ArgumentParser('Send electrumx an RPC command')
  57. parser.add_argument('-p', '--port', metavar='port_num', type=int,
  58. help='RPC port number')
  59. parser.add_argument('command', nargs=1, default=[],
  60. help='command to send')
  61. parser.add_argument('param', nargs='*', default=[],
  62. help='params to send')
  63. args = parser.parse_args()
  64. port = args.port
  65. if port is None:
  66. port = int(environ.get('RPC_PORT', 8000))
  67. # Get the RPC request.
  68. method = args.command[0]
  69. params = args.param
  70. if method in ('log', 'disconnect'):
  71. params = [params]
  72. rpc_send_and_wait(port, method, params)
  73. if __name__ == '__main__':
  74. main()