| 23 | return b''.join(pairList[::-1]).decode() |
| 24 | |
| 25 | class BitcoinRPC: |
| 26 | def __init__(self, host, port, username, password): |
| 27 | authpair = "%s:%s" % (username, password) |
| 28 | authpair = authpair.encode('utf-8') |
| 29 | self.authhdr = b"Basic " + base64.b64encode(authpair) |
| 30 | self.conn = HTTPConnection(host, port=port, timeout=30) |
| 31 | |
| 32 | def execute(self, obj): |
| 33 | try: |
| 34 | self.conn.request('POST', '/', json.dumps(obj), |
| 35 | { 'Authorization' : self.authhdr, |
| 36 | 'Content-type' : 'application/json' }) |
| 37 | except ConnectionRefusedError: |
| 38 | print('RPC connection refused. Check RPC settings and the server status.', |
| 39 | file=sys.stderr) |
| 40 | return None |
| 41 | |
| 42 | resp = self.conn.getresponse() |
| 43 | if resp is None: |
| 44 | print("JSON-RPC: no response", file=sys.stderr) |
| 45 | return None |
| 46 | |
| 47 | body = resp.read().decode('utf-8') |
| 48 | resp_obj = json.loads(body) |
| 49 | return resp_obj |
| 50 | |
| 51 | @staticmethod |
| 52 | def build_request(idx, method, params): |
| 53 | obj = { 'version' : '1.1', |
| 54 | 'method' : method, |
| 55 | 'id' : idx } |
| 56 | if params is None: |
| 57 | obj['params'] = [] |
| 58 | else: |
| 59 | obj['params'] = params |
| 60 | return obj |
| 61 | |
| 62 | @staticmethod |
| 63 | def response_is_error(resp_obj): |
| 64 | return 'error' in resp_obj and resp_obj['error'] is not None |
| 65 | |
| 66 | def get_block_hashes(settings, max_blocks_per_call=10000): |
| 67 | rpc = BitcoinRPC(settings['host'], settings['port'], |