Skip to content

Commit cd81db6

Browse files
committed
handle non-standard RPC responses
Sometimes there is a need to issue RPC commands to the services that just pretend to be bitcoind, by emulating some of its commands. These services might not follow the same protocol for error reporting as bitcoind does. An example of such service would be feesim (https://github.com/bitcoinfees/feesim, Model-based Bitcoin fee estimation) With these changes, we can handle non-standard error responses gracefully.
1 parent 05cbb3c commit cd81db6

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

bitcoin/rpc.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,13 @@ def _call(self, service_name, *args):
227227
self.__conn.request('POST', self.__url.path, postdata, headers)
228228

229229
response = self._get_response()
230-
if response['error'] is not None:
231-
raise JSONRPCError(response['error'])
230+
err = response.get('error')
231+
if err is not None:
232+
if isinstance(err, dict):
233+
raise JSONRPCError(
234+
{'code': err.get('code', -345),
235+
'message': err.get('message', 'error message not specified')})
236+
raise JSONRPCError({'code': -344, 'message': str(err)})
232237
elif 'result' not in response:
233238
raise JSONRPCError({
234239
'code': -343, 'message': 'missing JSON-RPC result'})
@@ -256,8 +261,15 @@ def _get_response(self):
256261
raise JSONRPCError({
257262
'code': -342, 'message': 'missing HTTP response from server'})
258263

259-
return json.loads(http_response.read().decode('utf8'),
260-
parse_float=decimal.Decimal)
264+
rdata = http_response.read().decode('utf8')
265+
try:
266+
return json.loads(rdata, parse_float=decimal.Decimal)
267+
except Exception:
268+
raise JSONRPCError({
269+
'code': -342,
270+
'message': ('non-JSON HTTP response with \'%i %s\' from server: \'%.20s%s\''
271+
% (http_response.status, http_response.reason,
272+
rdata, '...' if len(rdata) > 20 else ''))})
261273

262274
def close(self):
263275
if self.__conn is not None:

0 commit comments

Comments
 (0)