Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Feb 5, 2026

BitcoinRPC.__getattr__ crashes with KeyError: 'error' when Bitcoin Core returns malformed JSON-RPC responses. The code blindly accessed r['error']['message'] without validating response structure.

Changes

RPC error handling (rpc.py)

  • Validate response is dict before accessing keys
  • Handle error field as non-dict (e.g., plain strings)
  • Handle missing 'message' key in error dicts
  • Check 'result' field exists before access
  • Fix RpcError.init_via_response() to handle both Response objects and dicts

Test coverage (test_rpc.py)

  • Add test_BitcoinRpc_malformed_response covering 6 malformed response scenarios

Example

Before:

# Crashes with KeyError if response = {"error": "Connection refused"}
r = self.multi([(method, *args)], **kwargs)[0]
if r.get("error") is not None:
    raise RpcError(f"...: {r['error']['message']}", r)  # KeyError

After:

if not isinstance(r, dict):
    raise RpcError(f"Invalid response format (expected dict, got {type(r).__name__})", ...)

error = r.get("error")
if error is not None:
    error_message = error.get("message", str(error)) if isinstance(error, dict) else str(error)
    raise RpcError(f"...: {error_message}", r)

All valid JSON-RPC 2.0 responses continue to work unchanged.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • esm.ubuntu.com
    • Triggering command: /usr/lib/apt/methods/https /usr/lib/apt/methods/https tgresql cal/bin/rustc ver -plu�� hon3.12 -plugin-opt=/usr/libexec/gcc/x86_64-linux-gnu/13/lto-wrapper de/node/bin/bash -plugin-opt=-pascut tgresql -plugin-opt=-pass-through=-lc /x86_64-linux-gnu/13/cc1 -I xml2 hon3.12 p/bin/git -I -x86_64-cpython--rs tgresql as (dns block)
  • httpbin.org
    • Triggering command: /usr/bin/python3 python3 /usr/include/pos--force-confdef -I as ctly�� /usr/include/pyt--print-foreign-architectures -I nfig/composer/vendor/bin/lsb_release -I /usr/include/pos-x -I hg root�� p/specter-desktop/.git --gdwarf-5 lsb_release -o build/temp.linux--listfiles /tmp/cc4LLc0S.s git (dns block)
    • Triggering command: /usr/bin/python3 python3 /usr/include/pos--force-confdef -I as -I rd -I k/_temp/ghcca-no--force-confdef -I /usr/include/pos--fsys-tarfile -I git rev-�� p/specter-desktop/.git --gdwarf-5 ame -o e response struccall /tmp/ccna9yb6.s bash (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>Exception Error</issue_title>
<issue_description>Details

version: v2.0.5
Traceback (most recent call last):
File "flask/app.py", line 1823, in full_dispatch_request
File "flask/app.py", line 1799, in dispatch_request
File "flask_login/utils.py", line 290, in decorated_view
File "cryptoadvance/specter/server_endpoints/nodes.py", line 68, in node_settings_new_node_get
File "cryptoadvance/specter/node.py", line 348, in from_json
File "cryptoadvance/specter/node.py", line 327, in init
File "cryptoadvance/specter/node.py", line 395, in _get_rpc
File "cryptoadvance/specter/rpc.py", line 219, in autodetect_rpc_confs
File "cryptoadvance/specter/rpc.py", line 508, in fn
KeyError: 'error'

This is what it says when I connected to bitcoin core. How do fix this?</issue_description>

<agent_instructions>Improve error management more or less as described and check how we can potentially test it within the existing test framework.</agent_instructions>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@netlify
Copy link

netlify bot commented Feb 5, 2026

Deploy Preview for specter-desktop-docs canceled.

Name Link
🔨 Latest commit 8a32b8f
🔍 Latest deploy log https://app.netlify.com/projects/specter-desktop-docs/deploys/6984401d4e42f40008ebdaac

Copilot AI and others added 4 commits February 5, 2026 06:55
- Add defensive checks in __getattr__ to validate response structure
- Handle non-dict responses gracefully
- Handle error responses that aren't properly formatted dicts
- Handle missing 'message' key in error dicts
- Handle responses missing 'result' field
- Fix RpcError.init_via_response to handle both Response objects and dicts
- Add comprehensive test coverage for malformed response scenarios

Co-authored-by: k9ert <[email protected]>
- Move unittest.mock import to top of file
- Replace try/except blocks with pytest.raises() context manager
- Make test code more idiomatic and maintainable

Co-authored-by: k9ert <[email protected]>
Copilot AI changed the title [WIP] Fix exception error handling in node settings Fix KeyError on malformed Bitcoin Core RPC responses Feb 5, 2026
Copilot AI requested a review from k9ert February 5, 2026 07:03
Copy link
Contributor

@al-munazzim al-munazzim left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ LGTM - solid defensive coding.

The KeyError crash when Bitcoin Core returns malformed responses is a real issue. This PR:

  1. ✅ Validates response is a dict before accessing keys
  2. ✅ Handles error field as non-dict (e.g., plain strings)
  3. ✅ Handles missing message key in error dicts
  4. ✅ Good test coverage with 6 malformed response scenarios

The error messages are now informative instead of cryptic KeyErrors. Good work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exception Error

3 participants