rpc.py
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 18 import json 19 import time 20 import random 21 import logging 22 import asyncio 23 24 25 class JsonRpc: 26 27 async def start(self, host, port): 28 #logging.info(f"trying to connect to {host}:{port}") 29 reader, writer = await asyncio.open_connection(host, port) 30 self.reader = reader 31 self.writer = writer 32 33 async def stop(self): 34 self.writer.close() 35 await self.writer.wait_closed() 36 37 async def _make_request(self, method, params): 38 ident = random.randint(0, 2**16) 39 request = { 40 "jsonrpc": "2.0", 41 "method": method, 42 "params": params, 43 "id": ident, 44 } 45 46 message = json.dumps(request) + "\n" 47 self.writer.write(message.encode()) 48 await self.writer.drain() 49 data = await self.reader.readline() 50 message = data.decode().strip() 51 response = json.loads(message) 52 return response 53 54 async def _subscribe(self, method, params): 55 ident = random.randint(0, 2**16) 56 request = { 57 "jsonrpc": "2.0", 58 "method": method, 59 "params": params, 60 "id": ident, 61 } 62 63 message = json.dumps(request) + "\n" 64 self.writer.write(message.encode()) 65 await self.writer.drain() 66 logging.debug("Subscribed") 67 68 async def ping(self): 69 return await self._make_request("ping", []) 70 71 async def dnet_switch(self, state): 72 return await self._make_request("dnet.switch", [state]) 73 74 async def dnet_subscribe_events(self): 75 return await self._subscribe("dnet.subscribe_events", [])