Refuse an OP_RETURN that is not made of complete pushes
What changed, and why it matters
This commit changes how SeedSigner handles unusual OP_RETURN data in Bitcoin transactions. Previously, if the data after an OP_RETURN instruction was malformed, the app would still try to display whatever bytes remained. Now it stops and shows a plain 'Transaction Problem' warning, treating the transaction as malformed and discarding it. This aligns SeedSigner with how Bitcoin Core treats such transactions, and prevents a malformed or crafted OP_RETURN script from influencing what the user sees during transaction review.
Review the new PSBTMalformedOpReturnView wording to ensure users understand the transaction is malformed and cannot be signed. Consider whether any other script-parsing paths (e.g., non-OP_RETURN outputs) have similar 'best-effort display' behavior that could be tightened. Verify that the new exception is also handled in any other entry points that parse PSBTs.
Security signals we found
New exception class for malformed OP_RETURN scripts
Parser now rejects truncated pushes and non-push opcodes instead of surfacing raw bytes
UI redirects to a discard-only warning view on malformed OP_RETURN
Behavior aligned with Bitcoin Core standardness policy for OP_RETURN outputs
Tests added for malformed scripts and flow termination
Evidence from the diff
The parser in psbt_parser.py previously walked an OP_RETURN scriptPubKey, concatenating data pushes and appending any trailing or truncated bytes verbatim. The commit introduces PSBTMalformedOpReturnError and raises it when a push runs past the end of the script or when a non-push opcode appears after OP_RETURN. OP_0, OP_1NEGATE, OP_RESERVED, and OP_1 through OP_16 are still treated as pushes (matching Bitcoin Core’s standardness rules). The UI catches the new exception and routes to a warning view that only allows discarding the PSBT. Tests are added to cover malformed scripts and the signing-flow abort behavior.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pytests/test_psbt_parser.pytests/test_flows_psbt.pytests/screenshot_generator/generator.pyInspect captured patch +132 / −25
### src/seedsigner/models/psbt_parser.py
@@ -22,6 +22,7 @@ class OPCODES:
OP_PUSHDATA1 = 76
OP_PUSHDATA2 = 77
OP_PUSHDATA4 = 78
+ OP_16 = 96
@@ -131,6 +132,17 @@ class PSBTMissingInputUtxoError(PSBTVerificationError):
pass
+class PSBTMalformedOpReturnError(PSBTVerificationError):
+ """
+ An OP_RETURN output's script is not made of complete pushes: a push runs past the end
+ of the script, or an opcode is not a push at all.
+
+ This is a malformed psbt rather than a proven deception, so we do not treat it as an
+ attack.
+ """
+ pass
+
+
class PSBTSeedCannotSignError(PSBTVerificationError):
"""
The selected seed holds no key that could sign any input.
@@ -804,10 +816,12 @@ def _parse_op_return_payload(script_data: bytes) -> bytes:
and the pushes are concatenated here rather than returned separately, since where
the encoder chose to break the data into pushes carries no consensus meaning.
- Anything that is not a data push, and any push that claims more bytes than the
- script actually carries, ends the walk and the remaining bytes are appended
- verbatim, so no committed data is hidden from the review. The caller gets raw
- bytes and decides how to render them.
+ Bitcoin Core treats an OP_RETURN output as nonstandard unless everything after the
+ opcode is a push. Raises PSBTMalformedOpReturnError for a push that runs past the
+ end of the script or an opcode that is not a push. OP_0, OP_1NEGATE, OP_RESERVED,
+ and OP_1 through OP_16 carry no data bytes but Core still counts them as pushes,
+ so their opcode bytes are kept as-is. The caller gets raw bytes and decides how to
+ render them.
"""
pushes = []
@@ -825,28 +839,29 @@ def _parse_op_return_payload(script_data: bytes) -> bytes:
length_size = 2
elif opcode == OPCODES.OP_PUSHDATA4:
length_size = 4
+ elif opcode <= OPCODES.OP_16:
+ # No data bytes follow; keep the opcode byte itself so it is shown
+ pushes.append(script_data[i:i + 1])
+ i += 1
+ continue
else:
- # Not a data push (OP_0, a numeric opcode, anything else). Surface the
- # rest as-is rather than silently dropping it.
- pushes.append(script_data[i:])
- break
+ # Not a push, so the script cannot be read as OP_RETURN data
+ raise PSBTMalformedOpReturnError(f"OP_RETURN script holds non-push opcode 0x{opcode:02x}")
if length_size == 0:
length = opcode
else:
length_end = i + 1 + length_size
if length_end > len(script_data):
- # The length field itself is truncated
- pushes.append(script_data[i:])
- break
+ # The length field itself is truncated, so the push size is unknown
+ raise PSBTMalformedOpReturnError("OP_RETURN push length field is truncated")
length = int.from_bytes(script_data[i + 1:length_end], "little")
data_start = i + 1 + length_size
data_end = data_start + length
if data_end > len(script_data):
# The push claims more data than the script carries
- pushes.append(script_data[data_start:])
- break
+ raise PSBTMalformedOpReturnError(f"OP_RETURN push declares {length} bytes but only {len(script_data) - data_start} remain")
pushes.append(script_data[data_start:data_end])
i = data_end
### src/seedsigner/views/psbt_views.py
@@ -3,7 +3,7 @@
from gettext import gettext as _
from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError,
- PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError,
+ PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
PSBTSurplusDerivationPathsError)
@@ -128,6 +128,10 @@ def __init__(self):
self.set_redirect(Destination(PSBTMixedDerivationPathTypesView, clear_history=True))
return
+ except PSBTMalformedOpReturnError:
+ self.set_redirect(Destination(PSBTMalformedOpReturnView, clear_history=True))
+ return
+
except PSBTOutputOwnershipContradictionError:
self.set_redirect(Destination(PSBTOutputOwnershipContradictionView, clear_history=True))
return
@@ -644,6 +648,34 @@ def run(self):
+class PSBTMalformedOpReturnView(View):
+ """
+ Reached when an OP_RETURN output's script is not made of complete pushes (see
+ PSBTMalformedOpReturnError).
+
+ We view this as a malformed psbt and do not try to decide whether it is malicious. We
+ do not allow the user to continue, but only give this the "Warning" level.
+ """
+ DISCARD = ButtonOption("Discard transaction")
+
+ def run(self):
+ self.run_screen(
+ WarningScreen,
+ title=_("Transaction Problem"),
+ status_headline=None,
+ # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious.
+ text=_("This transaction's OP_RETURN data is malformed."),
+ button_data=[self.DISCARD],
+ show_back_button=False,
+ )
+
+ # We're done with this PSBT. Route back to MainMenuView, which clears all
+ # ephemeral data (except in-memory seeds).
+ # Set clear_history to disable returning via BACK button.
+ return Destination(MainMenuView, clear_history=True)
+
+
+
class PSBTOutputOwnershipContradictionView(View):
"""
Reached when the psbt's account of who an output pays contradicts the script that
### tests/screenshot_generator/generator.py
@@ -453,6 +453,7 @@ def mock_version_to_most_recent_release():
ScreenshotConfig(psbt_views.PSBTOpReturnView, screenshot_name="PSBTOpReturnView_raw_hex_data", mock_context_manager=mock_psbt_with_op_return_raw_bytes_loaded),
ScreenshotConfig(psbt_views.PSBTSurplusDerivationPathsView),
ScreenshotConfig(psbt_views.PSBTMixedDerivationPathTypesView),
+ ScreenshotConfig(psbt_views.PSBTMalformedOpReturnView),
ScreenshotConfig(psbt_views.PSBTOutputOwnershipContradictionView),
ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"),
ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"),
### tests/test_flows_psbt.py
@@ -4,12 +4,13 @@
from embit.psbt import PSBT, DerivationPath
from base import FlowTest, FlowStep
-from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output,
- foreign_public_key, root_for_seed)
+from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_op_return_output,
+ create_output, foreign_public_key, root_for_seed)
from seedsigner.controller import Controller
from seedsigner.views.view import MainMenuView
from seedsigner.views import scan_views, seed_views, psbt_views
+from seedsigner.models.psbt_parser import OPCODES
from seedsigner.models.seed import Seed
from seedsigner.models.settings import SettingsConstants
@@ -376,6 +377,25 @@ def test_missing_input_utxo_terminates_signing_flow(self):
])
+ def test_malformed_op_return_terminates_signing_flow(self):
+ """
+ An OP_RETURN push that claims more bytes than its script carries is malformed
+ rather than hostile, but it is still refused during the parse and routes to a
+ warning that aborts the signing flow.
+ """
+ psbt = self._psbt_with_change()
+ truncated_push = script.Script(bytes([OPCODES.OP_RETURN, 10]) + b"abc")
+ psbt.outputs.append(create_op_return_output(b"", script_pubkey=truncated_push))
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView, is_redirect=True),
+ FlowStep(psbt_views.PSBTMalformedOpReturnView, button_data_selection=psbt_views.PSBTMalformedOpReturnView.DISCARD),
+ FlowStep(MainMenuView),
+ ])
+
+
def test_wrong_seed_routes_back_to_seed_selection_flow(self):
"""
The wrong seed for a psbt redirects before any transaction detail is rendered and
### tests/test_psbt_parser.py
@@ -13,7 +13,7 @@
from embit.script import Script
from seedsigner.models.psbt_parser import (OPCODES, PSBTInputAmountVerificationError,
- PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError,
+ PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
PSBTSurplusDerivationPathsError)
@@ -2722,6 +2722,7 @@ def test_parse_op_return_payload_push_encodings():
# in one would otherwise make this test agree with the bug it is meant to catch.
assert (OPCODES.OP_RETURN, OPCODES.OP_PUSHDATA_MAX_DIRECT) == (0x6a, 0x4b)
assert (OPCODES.OP_PUSHDATA1, OPCODES.OP_PUSHDATA2, OPCODES.OP_PUSHDATA4) == (0x4c, 0x4d, 0x4e)
+ assert OPCODES.OP_16 == 0x60
op_return = bytes([OPCODES.OP_RETURN])
@@ -2762,16 +2763,54 @@ def test_parse_op_return_payload_push_encodings():
# An empty scriptPubKey must not index past the end
assert PSBTParser._parse_op_return_payload(b"") == b""
- # A push claiming more data than the script carries yields what is actually there,
- # rather than raising or returning nothing
- assert PSBTParser._parse_op_return_payload(op_return + bytes([10]) + b"abc") == b"abc"
+ # OP_0 through OP_16 carry no data bytes but still count as pushes. Their opcode bytes
+ # are kept, and the walk carries on past them.
+ assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 0x51])) == bytes([0x00, 0x51])
+ assert PSBTParser._parse_op_return_payload(op_return + bytes([0x4f, 0x50])) == bytes([0x4f, 0x50])
+ assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 4]) + b"data") == b"\x00data"
+ assert PSBTParser._parse_op_return_payload(op_return + bytes([OPCODES.OP_16])) == bytes([OPCODES.OP_16])
- # A truncated OP_PUSHDATA2 length field, same rule
- assert PSBTParser._parse_op_return_payload(op_return + bytes([OPCODES.OP_PUSHDATA2, 0x01])) == bytes([OPCODES.OP_PUSHDATA2, 0x01])
- # A leading opcode that is not a data push. The remaining bytes are still surfaced;
- # the user has to be able to see everything the transaction commits to.
- assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 0x51])) == bytes([0x00, 0x51])
+
+def test_parse_op_return_payload_rejects_malformed_scripts():
+ """
+ Should raise PSBTMalformedOpReturnError when the script after OP_RETURN is not made
+ of complete pushes, which Bitcoin Core treats as nonstandard.
+ """
+ op_return = bytes([OPCODES.OP_RETURN])
+
+ malformed_scripts = [
+ # A direct push claiming more data than the script carries
+ op_return + bytes([10]) + b"abc",
+
+ # An OP_PUSHDATA1 push claiming more data than the script carries
+ op_return + bytes([OPCODES.OP_PUSHDATA1, 80]) + b"abc",
+
+ # OP_PUSHDATA1 with no length byte at all
+ op_return + bytes([OPCODES.OP_PUSHDATA1]),
+
+ # A truncated OP_PUSHDATA2 length field
+ op_return + bytes([OPCODES.OP_PUSHDATA2, 0x01]),
+
+ # A truncated OP_PUSHDATA4 length field
+ op_return + bytes([OPCODES.OP_PUSHDATA4, 0x01, 0x00, 0x00]),
+
+ # The first opcode past OP_16 is not a push, and neither is anything above it
+ op_return + bytes([OPCODES.OP_16 + 1]),
+ op_return + bytes([0xff]),
+
+ # A non-push opcode after a valid push; the whole script is checked
+ op_return + bytes([4]) + b"data" + bytes([0xac]),
+ ]
+ for script_data in malformed_scripts:
+ with pytest.raises(PSBTMalformedOpReturnError):
+ PSBTParser._parse_op_return_payload(script_data)
+
+ # The parser refuses the whole psbt, rather than parsing the rest of it
+ truncated_push = script.Script(op_return + bytes([10]) + b"abc")
+ psbt = create_op_return_psbt([create_op_return_output(b"", script_pubkey=truncated_push)])
+ with pytest.raises(PSBTMalformedOpReturnError):
+ PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST)
Why this scored 52/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.