github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/test/litrpc.py (about) 1 #!/usr/bin/env python3 2 # Copyright (c) 2017 The lit developers 3 # Distributed under the MIT software license, see the accompanying 4 # file LICENSE or http://www.opensource.org/licenses/mit-license.php. 5 # 6 # Stolen from https://github.com/mit-dci/lit/blob/c565392054d2c2c1cf5d2917e40ab69188163808/cmd/litpy/litrpc.py 7 """Python interface to lit""" 8 9 import json 10 import logging 11 import random 12 import time 13 14 import requests # pip3 install requests 15 16 logger = logging.getLogger("testframework") 17 18 max_id = 10000 19 20 class LitClient(): 21 """A class representing a connection to a lit node.""" 22 def __init__(self, ip, port): 23 self.ip = ip 24 self.port = port 25 self.msg_id = random.randint(0, max_id) 26 27 def send_message(self, method, params): 28 """Sends a POST message to the lit node""" 29 logger.debug("Sending lit rpc message to %s:%s %s(%s)".format(self.ip, self.port, method, str(params))) 30 31 jsonreq = { 32 'method': "LitRPC.%s" % method, 33 'params': [params], 34 'jsonrpc': '2.0', 35 'id': self.msg_id 36 } 37 self.msg_id = (self.msg_id + 1) % max_id 38 39 req = requests.post('http://{}:{}/oneoff'.format(self.ip, self.port), json=jsonreq) 40 if req.status_code != 200: 41 raise AssertionError('RPC error: HTTP response code is ' + str(req.status_code)) 42 43 if req.json()['error'] is None: 44 resp = req.json()['result'] 45 logger.debug("Received rpc response from %s:%s method: %s Response: %s." % (self.ip, self.port, method, str(resp))) 46 return resp 47 else: 48 raise AssertionError('RPC call failed: ' + req.json()['error']) 49 50 def __getattr__(self, name): 51 """Dispatches any unrecognised messages to the websocket connection""" 52 def dispatcher(**kwargs): 53 return self.send_message(name, kwargs) 54 return dispatcher 55 56 def new_address(self): 57 """Add a new wallit address""" 58 return self.Address(NumToMake=1) 59 60 def balance(self): 61 """Get wallit balance""" 62 return self.Balance()['Balances']