github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/test/btcrpc.py (about)

     1  
     2  import json
     3  import logging
     4  
     5  import requests
     6  
     7  logger = logging.getLogger("testframework")
     8  
     9  class BtcClient():
    10  
    11      def __init__(self, ip, port, username, userpw):
    12          self.msg_id = 0
    13          self.rpc_url = "http://" + username + ":" + userpw + "@" + ip + ":" + str(port) + "/"
    14  
    15      def send_message(self, method, pos_args, named_args):
    16          if pos_args and named_args:
    17              raise AssertionError("RPCs must not use a mix of positional and named arguments")
    18          elif named_args:
    19              params = named_args
    20          else:
    21              params = list(pos_args)
    22  
    23          logger.debug("Sending bitcoind rpc message to %s:%s %s(%s)".format(self.ip, self.port, method, str(params)))
    24  
    25          self.msg_id += 1
    26          reqbody = {
    27              "method": method,
    28              "params": params,
    29              "jsonrpc": "2.0",
    30              "id": str(self.msg_id)
    31          }
    32  
    33          req = requests.post(self.rpc_url, headers={"Content-type": "application/json"}, data=json.dumps(reqbody))
    34          if req.status_code != 200:
    35              raise AssertionError('RPC error: HTTP response code is ' + str(req.status_code))
    36  
    37          if req.json()['error'] is None:
    38              resp = req.json()['result']
    39              logger.debug("Received rpc response from %s:%s method: %s Response: %s." % (self.ip, self.port, method, str(resp)))
    40              return resp
    41          else:
    42              raise AssertionError('RPC call failed: ' + str(req.json()['error']))
    43  
    44      def __getattr__(self, name):
    45          def dispatcher(*args, **kwargs):
    46              return self.send_message(name, args, kwargs)
    47          return dispatcher