fix: defensive RPC response handling (#2546)

Co-authored-by: al-munazzim <al-munazzim@users.noreply.github.com>
This commit is contained in:
al-munazzim 2026-03-19 09:47:12 -03:00 committed by GitHub
parent 8ebeb5f3e0
commit 7fa79ed5f5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -465,6 +465,10 @@ class BitcoinRPC:
"Server responded with error code %d: %s" % (r.status_code, r.text), r
)
r = r.json()
# Bitcoin Core should return a list for batch requests, but some
# implementations or proxies may return a single object instead.
if isinstance(r, dict):
r = [r]
return r
@classmethod
@ -505,9 +509,19 @@ class BitcoinRPC:
def __getattr__(self, method):
def fn(*args, **kwargs):
r = self.multi([(method, *args)], **kwargs)[0]
if r.get("error") is not None:
error = r.get("error")
if error is not None:
if isinstance(error, dict):
error_msg = error.get("message", str(error))
else:
error_msg = str(error)
raise RpcError(
f"Request error for method {method}{args}: {r['error']['message']}",
f"Request error for method {method}{args}: {error_msg}",
r,
)
if "result" not in r:
raise RpcError(
f"Unexpected RPC response for method {method}{args}: missing 'result' key",
r,
)
return r["result"]