rpc.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2023 Dyne.org foundation
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import json
  18. import time
  19. import random
  20. import logging
  21. import asyncio
  22. class JsonRpc:
  23. async def start(self, server, port):
  24. reader, writer = await asyncio.open_connection(server, port)
  25. self.reader = reader
  26. self.writer = writer
  27. async def stop(self):
  28. self.writer.close()
  29. await self.writer.wait_closed()
  30. async def _make_request(self, method, params):
  31. ident = random.randint(0, 2**16)
  32. request = {
  33. "jsonrpc": "2.0",
  34. "method": method,
  35. "params": params,
  36. "id": ident,
  37. }
  38. message = json.dumps(request) + "\n"
  39. self.writer.write(message.encode())
  40. await self.writer.drain()
  41. data = await self.reader.readline()
  42. message = data.decode().strip()
  43. response = json.loads(message)
  44. return response
  45. async def _subscribe(self, method, params):
  46. ident = random.randint(0, 2**16)
  47. request = {
  48. "jsonrpc": "2.0",
  49. "method": method,
  50. "params": params,
  51. "id": ident,
  52. }
  53. message = json.dumps(request) + "\n"
  54. self.writer.write(message.encode())
  55. await self.writer.drain()
  56. logging.debug("Subscribed")
  57. async def ping(self):
  58. return await self._make_request("ping", [])
  59. async def dnet_switch(self, state):
  60. return await self._make_request("dnet.switch", [state])
  61. async def dnet_subscribe_events(self):
  62. return await self._subscribe("dnet.subscribe_events", [])