rpc.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2026 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, host, port):
  24. #logging.info(f"trying to connect to {host}:{port}")
  25. reader, writer = await asyncio.open_connection(host, port)
  26. self.reader = reader
  27. self.writer = writer
  28. async def stop(self):
  29. self.writer.close()
  30. await self.writer.wait_closed()
  31. async def _make_request(self, method, params):
  32. ident = random.randint(0, 2**16)
  33. request = {
  34. "jsonrpc": "2.0",
  35. "method": method,
  36. "params": params,
  37. "id": ident,
  38. }
  39. message = json.dumps(request) + "\n"
  40. self.writer.write(message.encode())
  41. await self.writer.drain()
  42. data = await self.reader.readline()
  43. message = data.decode().strip()
  44. response = json.loads(message)
  45. return response
  46. async def _subscribe(self, method, params):
  47. ident = random.randint(0, 2**16)
  48. request = {
  49. "jsonrpc": "2.0",
  50. "method": method,
  51. "params": params,
  52. "id": ident,
  53. }
  54. message = json.dumps(request) + "\n"
  55. self.writer.write(message.encode())
  56. await self.writer.drain()
  57. logging.debug("Subscribed")
  58. async def ping(self):
  59. return await self._make_request("ping", [])
  60. async def dnet_switch(self, state):
  61. return await self._make_request("dnet.switch", [state])
  62. async def dnet_subscribe_events(self):
  63. return await self._subscribe("dnet.subscribe_events", [])