Merge pull request #1042 from Chaitanya-Keyal/op-return-push-opcode
What changed, and why it matters
This commit fixes how SeedSigner reads the extra data attached to OP_RETURN Bitcoin transaction outputs. Previously the code always assumed the data was introduced by OP_PUSHDATA1, which meant it would misread or crash on the more common direct-push encoding used for small payloads (75 bytes or fewer). The change teaches the parser to read the actual push opcode, handles larger OP_PUSHDATA2/OP_PUSHDATA4 payloads, and now rejects malformed scripts instead of silently misinterpreting them. It also adds a user-facing warning screen when this happens.
Reviewers should verify that _parse_op_return_payload correctly rejects all non-standard scripts, that the new PSBTMalformedOpReturnView cannot be bypassed to continue signing, and that existing OP_RETURN screenshots/tests still pass. Consider whether any downstream display code safely handles the returned raw bytes, including OP_0-OP_16 opcode bytes.
Security signals we found
Fixes incorrect parsing of OP_RETURN data due to assumed push opcode
Adds robust handling for direct push, OP_PUSHDATA1/2/4, and OP_0-OP_16
Introduces explicit malformed-script rejection instead of silent mis-parsing
Adds UI flow that aborts signing on malformed OP_RETURN
Includes unit and flow tests for parsing edge cases
Evidence from the diff
The patch replaces a hardcoded OP_RETURN parsing assumption in PSBTParser._parse_outputs. Before, it read script_pubkey.data[3:] after checking the first byte was OP_RETURN, implicitly assuming the layout OP_RETURN + OP_PUSHDATA1 + 1-byte length + payload. The new static method _parse_op_return_payload walks the script after OP_RETURN, interpreting direct pushes (0x01-0x4b), OP_PUSHDATA1/2/4, and the no-data pushes OP_0-OP_16. It raises PSBTMalformedOpReturnError for truncated length fields, pushes that overrun the script, or non-push opcodes. psbt_views.py catches that exception and routes to a new warning view that aborts signing. Tests cover all push encodings, malformed cases, and integration with the parser and signing flow.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pytests/psbt_testing_util.pytests/screenshot_generator/generator.pytests/test_flows_psbt.pytests/test_psbt_parser.pyInspect captured patch +375 / −15
### src/seedsigner/models/psbt_parser.py
@@ -15,7 +15,14 @@
class OPCODES:
OP_RETURN = 106
+
+ # Opcodes 0x01-0x4b are themselves the number of bytes to push, so 75 is the largest
+ # payload a direct push can carry.
+ OP_PUSHDATA_MAX_DIRECT = 75
OP_PUSHDATA1 = 76
+ OP_PUSHDATA2 = 77
+ OP_PUSHDATA4 = 78
+ OP_16 = 96
@@ -125,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.
@@ -510,6 +528,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict):
self.fee_amount = 0
self.destination_addresses = []
self.destination_amounts = []
+ self.op_return_data = None
# Asking the PSBT for its transaction rebuilds that entire transaction from
# scratch on every single request. The outputs are consulted a dozen times
@@ -719,9 +738,9 @@ def _parse_outputs(self, child_key_derivation_cache: dict):
# an omitted optional field is not a contradiction.
raise PSBTOutputOwnershipContradictionError(f"Output claims this seed at {bip32.path_to_str(verified_derivation_paths[0].derivation)} but its committed script contradicts that")
- if vout[i].script_pubkey.data[0] == OPCODES.OP_RETURN:
- # The data is written as: OP_RETURN + OP_PUSHDATA1 + len(payload) + payload
- self.op_return_data = vout[i].script_pubkey.data[3:]
+ script_data = vout[i].script_pubkey.data
+ if script_data[:1] == bytes([OPCODES.OP_RETURN]):
+ self.op_return_data = PSBTParser._parse_op_return_payload(script_data)
elif is_presumed_change:
# Remember that "change" in this function is ANY output coming back to our
@@ -782,6 +801,74 @@ def sig_count(tx):
return cnt
+ @staticmethod
+ def _parse_op_return_payload(script_data: bytes) -> bytes:
+ """
+ Extracts the data an OP_RETURN output carries, for every way the script can push
+ it.
+
+ Script pushes data with a variable-width opcode: opcodes 0x01 through 0x4b are
+ themselves the byte count, while OP_PUSHDATA1, 2, and 4 are followed by a 1, 2,
+ or 4 byte little-endian length. Bitcoin Core emits the minimal encoding, so a
+ payload of 75 bytes or fewer arrives as a direct push.
+
+ A script may hold more than one push after OP_RETURN. That is unusual but legal,
+ 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.
+
+ 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 = []
+
+ # Start after the OP_RETURN opcode itself
+ i = 1
+ while i < len(script_data):
+ opcode = script_data[i]
+
+ if 1 <= opcode <= OPCODES.OP_PUSHDATA_MAX_DIRECT:
+ # The opcode is itself the length; no separate length field follows
+ length_size = 0
+ elif opcode == OPCODES.OP_PUSHDATA1:
+ length_size = 1
+ elif opcode == OPCODES.OP_PUSHDATA2:
+ 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 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, 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
+ 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
+
+ return b"".join(pushes)
+
+
@staticmethod
def _get_script_type(scope, scriptpubkey) -> str:
"""Like script_type(), but tells nested segwit p2sh apart from legacy p2sh"""
### 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/psbt_testing_util.py
@@ -6,7 +6,9 @@
from embit.hashes import tagged_hash
from embit.networks import NETWORKS
from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope
+from embit.script import Script
+from seedsigner.models.psbt_parser import OPCODES
from seedsigner.models.seed import Seed
@@ -254,3 +256,59 @@ def claim_seed_owns_key(scope: InputScope | OutputScope, claimed_derivation_path
scope.taproot_bip32_derivations[public_key] = (leaf_hashes or [], derivation_path)
else:
scope.bip32_derivations[public_key] = derivation_path
+
+
+def op_return_script(payload: bytes) -> Script:
+ """
+ Build an OP_RETURN scriptPubKey carrying `payload`, using the minimal push encoding
+ that Bitcoin Core emits: a direct push for 75 bytes or fewer, OP_PUSHDATA1 up to 255,
+ OP_PUSHDATA2 up to 65535, and OP_PUSHDATA4 above that.
+ """
+ if len(payload) <= OPCODES.OP_PUSHDATA_MAX_DIRECT:
+ push = bytes([len(payload)])
+ elif len(payload) <= 0xff:
+ push = bytes([OPCODES.OP_PUSHDATA1, len(payload)])
+ elif len(payload) <= 0xffff:
+ push = bytes([OPCODES.OP_PUSHDATA2]) + len(payload).to_bytes(2, "little")
+ else:
+ push = bytes([OPCODES.OP_PUSHDATA4]) + len(payload).to_bytes(4, "little")
+
+ return Script(bytes([OPCODES.OP_RETURN]) + push + payload)
+
+
+def create_op_return_output(payload: bytes, value: int = 0, script_pubkey: Script = None) -> OutputScope:
+ """
+ Create an OP_RETURN OutputScope that can be appended to a PSBT's `outputs`.
+
+ Pass `script_pubkey` to supply a hand-built script (a bare OP_RETURN, several pushes,
+ a deliberately malformed one); otherwise `payload` is wrapped in a minimal push.
+
+ Note that the scriptPubKey and value have to be set on the OutputScope. `PSBT.tx`
+ rebuilds the whole transaction from the scopes on every access and `OutputScope.vout`
+ rebuilds its TransactionOutput, so assigning through `psbt.tx.vout[i]` is silently
+ discarded and would leave a test asserting against the fixture it meant to replace.
+ """
+ output = OutputScope()
+ output.script_pubkey = script_pubkey if script_pubkey is not None else op_return_script(payload)
+ output.value = value
+ return output
+
+
+def create_op_return_psbt(op_return_outputs: list) -> PSBT:
+ """
+ A single-sig native segwit psbt with one change output and the given OP_RETURN
+ OutputScopes (see `create_op_return_output`) appended after it, in order.
+
+ The change output gets whatever is left of the input after the OP_RETURN values and a
+ 5,000 sat fee.
+ """
+ psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT))
+ input_amount = sum([inp.utxo.value for inp in psbt.inputs])
+ op_return_amount = sum([output.value for output in op_return_outputs])
+ change_amount = input_amount - op_return_amount - 5_000
+
+ psbt.outputs.clear()
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE, change_amount))
+ for output in op_return_outputs:
+ psbt.outputs.append(output)
+ return psbt
### tests/screenshot_generator/generator.py
@@ -11,7 +11,6 @@
from PIL import ImageFont
from unittest.mock import Mock, patch, MagicMock
-from embit import compact
from embit.psbt import PSBT, OutputScope
from embit.script import Script
@@ -83,11 +82,13 @@ def test_generate_all(locale, target_locale):
seed_12b = Seed(mnemonic=mnemonic_12b, wordlist_language_code=SettingsConstants.WORDLIST_LANGUAGE__ENGLISH)
def add_op_return_to_psbt(psbt: PSBT, raw_payload_data: bytes):
- data = (compact.to_bytes(OPCODES.OP_RETURN) +
- compact.to_bytes(OPCODES.OP_PUSHDATA1) +
- compact.to_bytes(len(raw_payload_data)) +
- raw_payload_data)
- script = Script(data)
+ # Push the payload the way Bitcoin Core does: directly for 75 bytes or fewer, via
+ # OP_PUSHDATA1 above that.
+ if len(raw_payload_data) <= OPCODES.OP_PUSHDATA_MAX_DIRECT:
+ push = bytes([len(raw_payload_data)])
+ else:
+ push = bytes([OPCODES.OP_PUSHDATA1, len(raw_payload_data)])
+ script = Script(bytes([OPCODES.OP_RETURN]) + push + raw_payload_data)
output = OutputScope()
output.script_pubkey = script
output.value = 0
@@ -452,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
@@ -12,16 +12,17 @@
from embit.descriptor import Descriptor
from embit.script import Script
-from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError,
- PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError,
+from seedsigner.models.psbt_parser import (OPCODES, PSBTInputAmountVerificationError,
+ PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
PSBTSurplusDerivationPathsError)
from seedsigner.models.seed import Seed
from seedsigner.models.settings_definition import SettingsConstants
from psbt_testing_util import (NUMS_INTERNAL_KEY, PSBTTestData, claim_seed_owns_key,
- create_output, foreign_public_key, p2tr_with_script_tree, root_for_seed, tapleaf_hash)
+ create_op_return_output, create_op_return_psbt, create_output, foreign_public_key,
+ op_return_script, p2tr_with_script_tree, root_for_seed, tapleaf_hash)
@@ -2704,3 +2705,163 @@ def test__parse__accepts_a_zero_fee(self):
psbt.outputs[0].value = sum(inp.utxo.value for inp in psbt.inputs)
assert self._parse(psbt).fee_amount == 0
+
+
+
+def test_parse_op_return_payload_push_encodings():
+ """
+ Should extract the payload whichever push opcode carries it.
+
+ Opcodes 0x01-0x4b are themselves the byte count; OP_PUSHDATA1, 2, and 4 are
+ followed by a 1, 2, or 4 byte little-endian length. Bitcoin Core emits the
+ minimal encoding, so a payload of 75 bytes or fewer arrives as a direct push and
+ the push opcode has to be read rather than assumed. 75/76 is the boundary between
+ the two.
+ """
+ # Pin the constants: every assertion below is written in terms of them, so a typo
+ # 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])
+
+ # Direct push: the encoding Bitcoin Core produces for payloads up to 75 bytes
+ for length in [1, 2, 40, OPCODES.OP_PUSHDATA_MAX_DIRECT]:
+ payload = b"A" * length
+ assert PSBTParser._parse_op_return_payload(op_return + bytes([length]) + payload) == payload
+
+ # OP_PUSHDATA1 carries a 1-byte length; 76 is the first payload that needs it
+ for length in [76, 80, 0xff]:
+ payload = b"B" * length
+ script_data = op_return + bytes([OPCODES.OP_PUSHDATA1, length]) + payload
+ assert PSBTParser._parse_op_return_payload(script_data) == payload
+
+ # OP_PUSHDATA2 carries a 2-byte length. Now that Bitcoin Core v30 defaults
+ # `-datacarriersize` to 100,000 bytes this is an ordinary encoding, not an exotic one.
+ payload = b"C" * 300
+ script_data = op_return + bytes([OPCODES.OP_PUSHDATA2]) + len(payload).to_bytes(2, "little") + payload
+ assert PSBTParser._parse_op_return_payload(script_data) == payload
+
+ # OP_PUSHDATA4 carries a 4-byte length
+ payload = b"D" * 300
+ script_data = op_return + bytes([OPCODES.OP_PUSHDATA4]) + len(payload).to_bytes(4, "little") + payload
+ assert PSBTParser._parse_op_return_payload(script_data) == payload
+
+ # A non-minimal encoding is unusual but a coordinator is free to produce one
+ payload = b"E" * 10
+ script_data = op_return + bytes([OPCODES.OP_PUSHDATA2]) + len(payload).to_bytes(2, "little") + payload
+ assert PSBTParser._parse_op_return_payload(script_data) == payload
+
+ # Several pushes in one script are legal; they are concatenated
+ script_data = op_return + bytes([4]) + b"data" + bytes([4]) + b"more"
+ assert PSBTParser._parse_op_return_payload(script_data) == b"datamore"
+
+ # Bare OP_RETURN, nothing pushed
+ assert PSBTParser._parse_op_return_payload(op_return) == b""
+
+ # An empty scriptPubKey must not index past the end
+ assert PSBTParser._parse_op_return_payload(b"") == b""
+
+ # 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])
+
+
+
+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)
+
+
+
+def test_parse_op_return_content_direct_push():
+ """
+ Should parse an OP_RETURN whose payload uses a direct push.
+
+ This is the canonical encoding: `bitcoin-tx outdata=<hex>` and any Bitcoin Core
+ wallet produce it for payloads of 75 bytes or fewer.
+ """
+ message = "Chancellor on the brink of third bailout".encode()
+ assert len(message) <= OPCODES.OP_PUSHDATA_MAX_DIRECT
+
+ script_pubkey = op_return_script(message)
+ assert script_pubkey.data[:2] == bytes([OPCODES.OP_RETURN, len(message)])
+
+ psbt = create_op_return_psbt([create_op_return_output(message)])
+ psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST)
+
+ assert psbt_parser.op_return_data == message
+
+
+
+def test_parse_op_return_content_pushdata2():
+ """
+ Should parse an OP_RETURN payload large enough to require OP_PUSHDATA2.
+
+ Bitcoin Core v30 raised the default `-datacarriersize` to 100,000 bytes, so
+ payloads past the 255 bytes OP_PUSHDATA1 can describe now arrive from honest
+ coordinators. Consensus has never limited OP_RETURN data at all, so no payload
+ size can be assumed either way.
+ """
+ message = b"F" * 300
+
+ script_pubkey = op_return_script(message)
+ assert script_pubkey.data[:2] == bytes([OPCODES.OP_RETURN, OPCODES.OP_PUSHDATA2])
+
+ psbt = create_op_return_psbt([create_op_return_output(message)])
+ psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST)
+
+ assert psbt_parser.op_return_data == message
+
+
+
+def test_parse_op_return_with_no_payload():
+ """
+ A bare OP_RETURN output carries no data and must parse to empty, not crash.
+ """
+ psbt = create_op_return_psbt([
+ create_op_return_output(b"", script_pubkey=script.Script(bytes([OPCODES.OP_RETURN])))
+ ])
+ psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST)
+
+ assert psbt_parser.op_return_data == b""Why this scored 51/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.