main.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2025 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 asyncio, json, random, sys, time
  18. class JsonRpc:
  19. async def start(self, server, port):
  20. try:
  21. reader, writer = await asyncio.open_connection(server, port)
  22. self.reader = reader
  23. self.writer = writer
  24. except ConnectionRefusedError:
  25. print(f"Error: Connection Refused to '{server}:{port}'")
  26. sys.exit(-1)
  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. print(ident)
  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. print(response)
  46. return response
  47. async def _subscribe(self, method, params):
  48. ident = random.randint(0, 2**16)
  49. request = {
  50. "jsonrpc": "2.0",
  51. "method": method,
  52. "params": params,
  53. "id": ident,
  54. }
  55. message = json.dumps(request) + "\n"
  56. self.writer.write(message.encode())
  57. await self.writer.drain()
  58. print("Subscribed")
  59. async def ping(self):
  60. return await self._make_request("ping", [])
  61. async def dnet_switch(self, state):
  62. return await self._make_request("dnet.switch", [state])
  63. async def dnet_subscribe_events(self):
  64. return await self._subscribe("dnet.subscribe_events", [])
  65. async def send(self, message):
  66. return await self._make_request("send", [message])
  67. async def recv(self):
  68. return await self._make_request("recv", [])
  69. async def main(argv):
  70. endpoint = "localhost:51054"
  71. for i in range(1, len(argv)):
  72. if argv[i] == "-e":
  73. endpoint = argv[i+1]
  74. del argv[i]
  75. del argv[i]
  76. break
  77. if len(argv) == 1 or any(x in ["h", "-h", "--help", "help"] for x in argv):
  78. print('''USAGE
  79. python main.py [OPTIONS] [SUBCOMMAND]
  80. OPTIONS:
  81. -h, --help Print help information
  82. -e RPC endpoint [default: localhost:51345]
  83. SUBCOMMANDS:
  84. send Send a message
  85. recv Receive messages
  86. ping Send ping
  87. help show this help text
  88. Examples:
  89. python main.py -e localhost:52345 send "Hello"
  90. python main.py send "Hello World!"
  91. python main.py recv
  92. python main.py ping
  93. ''')
  94. return 0
  95. server, port = endpoint.split(":")
  96. rpc = JsonRpc()
  97. await rpc.start(server, port)
  98. if argv[1] == "send":
  99. if len(argv) > 2:
  100. await rpc.send(argv[2])
  101. else:
  102. print("Error: send subcommand needs a message")
  103. elif argv[1] == "recv":
  104. await rpc.recv()
  105. elif argv[1] == "ping":
  106. await rpc.ping()
  107. else:
  108. print(f"Error: Unknown subcommand : {argv[1]}")
  109. await rpc.stop()
  110. asyncio.run(main(sys.argv))