Merge pull request #753 from Foundation-Devices/sft-8680-fail-to-sign-dynamic-taproot-qr-message
What changed, and why it matters
This commit adds support for signing BIP-322 message requests that wallets like Sparrow send as a PSBT (a Bitcoin transaction-like data format). It is a feature addition, not a reported vulnerability fix. The code includes careful validation: it checks the message matches the transaction, the address is Taproot, the derivation path is correct, and the signature hash type is safe. There is no direct evidence in the commit that this fixes an active security bug, but it does reduce the risk of a user being tricked into signing the wrong message or signing for the wrong address.
Treat as a normal feature/robustness update. Reviewers should verify the PSBT parser cannot be confused by duplicate keys, unknown global fields, or PSBTv2 markers, and that the signature insertion offset is always correct. Users on prior firmware should update if they need Sparrow-compatible BIP-322 signing.
Security signals we found
New input parser for externally supplied PSBT data with explicit structural validation
Rejects non-Taproot BIP-322 requests and unsafe sighash types
Binds the user-reviewed message and address to the transaction being signed
Adds tests for malformed, mismatched, and already-signed requests
Changes existing taproot simple signatures from SIGHASH_DEFAULT to SIGHASH_ALL for verifier compatibility
Evidence from the diff
The patch introduces a new BIP-322 PSBT-based signing path in Passport firmware. Key changes: (1) a new read_signing_request() parser that verifies the PSBT’s unsigned transaction equals the BIP-322 to_sign transaction for the claimed message and scriptPubKey; (2) enforcement of Taproot-only (P2TR) requests and only SIGHASH_DEFAULT/SIGHASH_ALL; (3) validation that the derived key owns the requested address; (4) signing returns the PSBT with a taproot key-path signature inserted. The previous text-only BIP-322 path is updated to use SIGHASH_ALL to match Sparrow’s requirements. Extensive unit tests cover malformed PSBTs, mismatched messages/addresses, wrong keys, and non-Taproot address rejection.
Changed components
Passport firmware message signing flowBIP-322 message signing modulePSBT parsing and validation taskQR scan/show flows for message signaturesInspect captured patch +722 / −30
### ports/stm32/boards/Passport/manifest.py
@@ -296,6 +296,7 @@
'tasks/set_initial_pin_task.py',
'tasks/sign_psbt_task.py',
'tasks/sign_text_file_task.py',
+ 'tasks/validate_bip322_request_task.py',
'tasks/validate_electrum_message_task.py',
'tasks/validate_psbt_task.py',
'tasks/verify_backup_task.py',
### ports/stm32/boards/Passport/modules/bip322.py
@@ -4,15 +4,25 @@
# bip322.py - BIP-322 message-signing helpers
from ubinascii import b2a_base64
-from ustruct import pack
+from uio import BytesIO
+from ustruct import pack, unpack, unpack_from
+from public_constants import MAX_PATH_DEPTH, PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE, PSBT_GLOBAL_UNSIGNED_TX
+from public_constants import PSBT_IN_SIGHASH_TYPE, PSBT_IN_TAP_BIP32_DERIVATION, PSBT_IN_TAP_KEY_SIG
+from public_constants import PSBT_IN_WITNESS_UTXO
from serializations import COutPoint, CTxIn, CTxOut
-from serializations import SIGHASH_DEFAULT, hash256, ser_compact_size, ser_string, ser_string_vector, sha256
+from serializations import SIGHASH_ALL, SIGHASH_DEFAULT, deser_compact_size, hash256, ser_compact_size
+from serializations import ser_string, ser_string_vector, sha256
from taproot import output_script, tagged_hash, taproot_sign_key
BIP322_SIMPLE_PREFIX = 'smp'
+PSBT_MAGIC = b'psbt\xff'
+INVALID_REQUEST = 'This is not a valid BIP-322 message request.'
+TAPROOT_ONLY = 'Passport can only sign BIP-322 message requests for Taproot addresses. ' \
+ 'For other addresses, choose the Electrum format in your wallet.'
+
def _serialize_virtual_transaction(txin, txout):
return pack('<i', 0) + \
@@ -41,15 +51,16 @@ def create_virtual_transactions(message, message_challenge):
return to_spend, to_sign
-def taproot_signature_hash(message, message_challenge):
+def taproot_signature_hash(message, message_challenge, hash_type=SIGHASH_DEFAULT):
"""Calculate the BIP-341 key-path sighash for a BIP-322 virtual spend."""
to_spend, _ = create_virtual_transactions(message, message_challenge)
outpoint = hash256(to_spend) + pack('<I', 0)
to_sign_output = CTxOut(0, b'\x6a')
# BIP-341 SigMsg: hash type, transaction fields, and aggregate input/output hashes.
- sigmsg = bytes([SIGHASH_DEFAULT])
+ # SIGHASH_DEFAULT and SIGHASH_ALL commit to the same fields and differ only in this byte.
+ sigmsg = bytes([hash_type])
sigmsg += pack('<i', 0)
sigmsg += pack('<I', 0)
sigmsg += sha256(outpoint)
@@ -68,9 +79,124 @@ def taproot_signature_hash(message, message_challenge):
def sign_taproot_simple(message, internal_pubkey, internal_seckey):
"""Create a textual BIP-322 simple signature for a P2TR key-path spend."""
message_challenge = output_script(internal_pubkey, None)
- sighash = taproot_signature_hash(message, message_challenge)
- signature = taproot_sign_key(None, internal_seckey, SIGHASH_DEFAULT, sighash)
+ # BIP-322 lets P2TR use SIGHASH_DEFAULT, but every verifier has to accept SIGHASH_ALL, and Sparrow only
+ # accepts SIGHASH_ALL.
+ sighash = taproot_signature_hash(message, message_challenge, SIGHASH_ALL)
+ signature = taproot_sign_key(None, internal_seckey, SIGHASH_ALL, sighash)
witness = ser_string_vector([signature])
encoded_witness = b2a_base64(witness).decode('ascii').strip()
return BIP322_SIMPLE_PREFIX + encoded_witness
+
+
+class SigningRequest:
+ """A BIP-322 message-signing request sent as a PSBT, as Sparrow builds it."""
+
+ def __init__(self, psbt, message, script_pubkey, xfp, path, hash_type, signature_offset):
+ self.psbt = psbt
+ self.message = message
+ self.script_pubkey = script_pubkey
+ self.xfp = xfp
+ self.path = path
+ self.hash_type = hash_type
+ # Where the input's signature goes: just before the input map's terminator.
+ self.signature_offset = signature_offset
+
+
+def _read_exact(fd, length):
+ data = fd.read(length)
+ if len(data) != length:
+ raise ValueError(INVALID_REQUEST)
+ return data
+
+
+def _read_map(fd):
+ # Read one PSBT key-value map. BIP-174 forbids duplicate keys.
+ entries = {}
+ while True:
+ key = _read_exact(fd, deser_compact_size(fd))
+ if not key:
+ return entries
+ if key in entries:
+ raise ValueError(INVALID_REQUEST)
+ entries[key] = _read_exact(fd, deser_compact_size(fd))
+
+
+def read_signing_request(psbt):
+ """Read a BIP-322 message-signing request sent as a PSBT.
+
+ The request is only accepted if its transaction is exactly the BIP-322 to_sign transaction for its own
+ message and address, so the message shown for review is the one the signature commits to.
+ """
+ try:
+ fd = BytesIO(psbt)
+ if fd.read(len(PSBT_MAGIC)) != PSBT_MAGIC:
+ raise ValueError(INVALID_REQUEST)
+
+ global_map = _read_map(fd)
+ input_map = _read_map(fd)
+ signature_offset = fd.seek(0, 1) - 1 # .tell() is missing
+ _read_map(fd)
+
+ # One input and one output, and nothing after them.
+ if fd.read(1):
+ raise ValueError(INVALID_REQUEST)
+ except Exception:
+ raise ValueError(INVALID_REQUEST)
+
+ unsigned_tx = global_map.get(bytes([PSBT_GLOBAL_UNSIGNED_TX]))
+ message = global_map.get(bytes([PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE]))
+ witness_utxo = input_map.get(bytes([PSBT_IN_WITNESS_UTXO]))
+ if unsigned_tx is None or witness_utxo is None:
+ raise ValueError(INVALID_REQUEST)
+ if message is None:
+ raise ValueError('This request does not include the message to sign.')
+
+ # The output being "spent" holds no value and pays to the address that signs.
+ script_pubkey = witness_utxo[9:]
+ if witness_utxo != pack('<q', 0) + ser_string(script_pubkey):
+ raise ValueError(INVALID_REQUEST)
+ if len(script_pubkey) != 34 or script_pubkey[:2] != b'\x51\x20':
+ raise ValueError(TAPROOT_ONLY)
+
+ _, to_sign = create_virtual_transactions(message, script_pubkey)
+ if unsigned_tx != to_sign:
+ raise ValueError('The transaction in this request does not match its message.')
+
+ if bytes([PSBT_IN_TAP_KEY_SIG]) in input_map:
+ raise ValueError('This message request is already signed.')
+
+ hash_type = input_map.get(bytes([PSBT_IN_SIGHASH_TYPE]))
+ if hash_type is None:
+ hash_type = SIGHASH_DEFAULT
+ elif len(hash_type) == 4:
+ hash_type = unpack('<I', hash_type)[0]
+ if hash_type not in (SIGHASH_DEFAULT, SIGHASH_ALL):
+ raise ValueError('Unsupported signature hash type.')
+
+ # Exactly one key-path derivation (no leaf hashes): the master fingerprint, then at least one step.
+ derivations = [value for key, value in input_map.items()
+ if key[0] == PSBT_IN_TAP_BIP32_DERIVATION and len(key) == 33]
+ if len(derivations) != 1:
+ raise ValueError(INVALID_REQUEST)
+ derivation = derivations[0]
+ count = (len(derivation) - 1) // 4
+ if not 2 <= count <= MAX_PATH_DEPTH or (len(derivation) - 1) % 4 or derivation[0] != 0:
+ raise ValueError(INVALID_REQUEST)
+ xfp_path = list(unpack_from('<%dI' % count, derivation, 1))
+
+ return SigningRequest(psbt, message, script_pubkey, xfp_path[0], xfp_path[1:], hash_type, signature_offset)
+
+
+def sign_taproot_request(request, internal_pubkey, internal_seckey):
+ """Sign a BIP-322 request and return its PSBT with the key-path signature added to the input."""
+ if output_script(internal_pubkey, None) != request.script_pubkey:
+ raise ValueError('The key does not match the address in the request.')
+
+ sighash = taproot_signature_hash(request.message, request.script_pubkey, request.hash_type)
+ signature = taproot_sign_key(None, internal_seckey, request.hash_type, sighash)
+
+ psbt = request.psbt
+ offset = request.signature_offset
+ return psbt[:offset] + ser_compact_size(1) + bytes([PSBT_IN_TAP_KEY_SIG]) + ser_string(signature) + \
+ psbt[offset:]
### ports/stm32/boards/Passport/modules/flows/sign_electrum_message_flow.py
@@ -1,13 +1,14 @@
# SPDX-FileCopyrightText: © 2023 Foundation Devices, Inc. <hello@foundation.xyz>
# SPDX-License-Identifier: GPL-3.0-or-later
#
-# sign_electrum_message_flow.py - Sign an electrum standard message via QR
+# sign_electrum_message_flow.py - Sign a message via QR, sent as text or as a BIP-322 request in a PSBT
from flows import Flow, ScanQRFlow
from pages import ErrorPage, LongTextPage, LongQuestionPage, ShowQRPage
-from tasks import sign_text_file_task, validate_electrum_message_task
+from tasks import sign_text_file_task, validate_bip322_request_task, validate_electrum_message_task
from utils import escape_text, message_review_warning, spinner_task, stylize_address
from data_codecs.qr_type import QRType
+from foundation import ur
import microns
from wallets.utils import get_addr_type_from_deriv
from public_constants import AF_CLASSIC, MARGIN_FOR_ADDRESSES
@@ -19,16 +20,25 @@ def __init__(self):
self.message = None
self.address = None
self.signature = None
+ self.psbt = None
+ self.bip322_request = None
super().__init__(initial_state=self.scan_message, name='SignElectrumMessageFlow')
async def scan_message(self):
- result = await ScanQRFlow(qr_types=[QRType.QR],
+ result = await ScanQRFlow(qr_types=[QRType.QR, QRType.UR2],
+ ur_types=[ur.Value.PSBT],
data_description='a message').run()
if result is None:
self.set_result(None)
return
+ if isinstance(result, ur.Value):
+ # Sparrow sends a BIP-322 request as a PSBT. Copy it, since the decoder reuses its storage.
+ self.psbt = bytes(result.unwrap_psbt())
+ self.goto(self.validate_bip322_request)
+ return
+
self.message = result
self.goto(self.validate_message)
@@ -48,6 +58,21 @@ async def validate_message(self):
self.goto(self.show_message)
+ async def validate_bip322_request(self):
+ (values, error) = await spinner_task('Validating Message',
+ validate_bip322_request_task,
+ args=[self.psbt])
+ self.psbt = None
+
+ if error:
+ await ErrorPage(error).show()
+ self.set_result(False)
+ return
+
+ (self.message, self.subpath, self.bip322_request) = values
+
+ self.goto(self.show_message)
+
async def show_message(self):
self.addr_format = get_addr_type_from_deriv(self.subpath)
@@ -83,7 +108,8 @@ async def show_message(self):
async def do_sign(self):
(sig, address, error) = await spinner_task('Signing message', sign_text_file_task,
- args=[self.message, self.subpath, self.addr_format, self.address])
+ args=[self.message, self.subpath, self.addr_format, self.address,
+ self.bip322_request])
if error is None:
self.signature = sig
self.goto(self.show_signed)
@@ -93,7 +119,15 @@ async def do_sign(self):
return
async def show_signed(self):
- result = await ShowQRPage(qr_data=self.signature,
+ qr_type = QRType.QR
+ qr_data = self.signature
+ if self.bip322_request is not None:
+ # Send the request back signed, as a PSBT like the one the wallet sent.
+ qr_type = QRType.UR2
+ qr_data = ur.new_psbt(self.signature)
+
+ result = await ShowQRPage(qr_type=qr_type,
+ qr_data=qr_data,
right_micron=microns.Checkmark).show()
self.set_result(result)
### ports/stm32/boards/Passport/modules/public_constants.py
@@ -82,6 +82,8 @@
#
PSBT_GLOBAL_UNSIGNED_TX = const(0)
PSBT_GLOBAL_XPUB = const(1)
+# Sparrow sends the message of a BIP-322 signing request in this global field.
+PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE = const(9)
PSBT_GLOBAL_VERSION = const(0xfb)
PSBT_IN_NON_WITNESS_UTXO = const(0)
### ports/stm32/boards/Passport/modules/tasks/__init__.py
@@ -49,6 +49,7 @@
from .save_seed_task import save_seed_task
from .set_initial_pin_task import set_initial_pin_task
from .sign_text_file_task import sign_text_file_task
+from .validate_bip322_request_task import validate_bip322_request_task
from .validate_electrum_message_task import validate_electrum_message_task
from .validate_psbt_task import validate_psbt_task
from .verify_firmware_signature_task import verify_firmware_signature_task
### ports/stm32/boards/Passport/modules/tasks/sign_text_file_task.py
@@ -16,7 +16,8 @@
from utils import sign_message_digest_recoverable
-async def sign_text_file_task(on_done, text, subpath, addr_fmt, expected_address=None):
+async def sign_text_file_task(on_done, text, subpath, addr_fmt, expected_address=None, bip322_request=None):
+ # With a BIP-322 request read from a PSBT, the result is that PSBT, signed, instead of a text signature.
with stash.SensitiveValues() as sv:
node = sv.derive_path(subpath)
@@ -28,13 +29,23 @@ async def sign_text_file_task(on_done, text, subpath, addr_fmt, expected_address
message = text.encode()
if addr_fmt == AF_P2TR:
- from bip322 import sign_taproot_simple
-
- with stash.SensitiveValues() as sv:
- node = sv.derive_path(subpath)
- private_key = node.private_key()
- sv.register(private_key)
- signature = sign_taproot_simple(message, node.public_key()[1:], private_key)
+ from bip322 import sign_taproot_request, sign_taproot_simple
+
+ try:
+ with stash.SensitiveValues() as sv:
+ node = sv.derive_path(subpath)
+ private_key = node.private_key()
+ sv.register(private_key)
+ if bip322_request is None:
+ signature = sign_taproot_simple(message, node.public_key()[1:], private_key)
+ else:
+ signature = sign_taproot_request(bip322_request, node.public_key()[1:], private_key)
+ except ValueError as e:
+ await on_done(None, None, str(e))
+ return
+ elif bip322_request is not None:
+ await on_done(None, None, 'BIP-322 requests can only be signed for Taproot addresses')
+ return
else:
digest = chains.current_chain().hash_message(message)
raw_signature = sign_message_digest_recoverable(digest, subpath)
### ports/stm32/boards/Passport/modules/tasks/validate_bip322_request_task.py
@@ -0,0 +1,54 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# validate_bip322_request_task.py - Task to read and validate a BIP-322 message request sent as a PSBT
+
+from utils import keypath_to_str, swab32, validate_sign_text
+
+
+async def validate_bip322_request_task(on_done, psbt):
+ import stash
+ from bip322 import TAPROOT_ONLY, read_signing_request
+ from common import settings
+ from public_constants import AF_P2TR
+ from taproot import output_script
+ from wallets.utils import get_addr_type_from_deriv
+
+ try:
+ request = read_signing_request(psbt)
+ except ValueError as e:
+ await on_done(None, str(e))
+ return
+
+ try:
+ message = str(request.message, 'utf-8')
+ except UnicodeError:
+ await on_done(None, 'Message is not valid text.')
+ return
+
+ xfp = settings.get('xfp', 0)
+ if request.xfp != xfp and request.xfp != swab32(xfp):
+ await on_done(None, 'This message request is for a different wallet.')
+ return
+
+ # Same checks as a message scanned as text.
+ (subpath, error) = validate_sign_text(message, keypath_to_str([request.xfp] + request.path),
+ space_limit=False, check_whitespace=False, allow_newlines=True)
+ if error:
+ await on_done(None, error)
+ return
+
+ # The review shows the address this path derives, so it must be the Taproot address that signs.
+ if get_addr_type_from_deriv(subpath) != AF_P2TR:
+ await on_done(None, TAPROOT_ONLY)
+ return
+
+ with stash.SensitiveValues() as sv:
+ node = sv.derive_path(subpath)
+ matches = output_script(node.public_key()[1:], None) == request.script_pubkey
+
+ if not matches:
+ await on_done(None, 'The address in this request does not match its derivation path.')
+ return
+
+ await on_done((message, subpath, request), None)
### ports/stm32/boards/Passport/modules/tests/test_unit.py
@@ -176,6 +176,10 @@ def test_bip322(test):
assert test('bip322.py') == b'OK'
+def test_bip322_request(test):
+ assert test('bip322_request.py') == b'OK'
+
+
def test_psbt_change_validation(test):
assert test('psbt_change_validation.py') == b'OK'
### ports/stm32/boards/Passport/modules/tests/unit/bip322.py
@@ -6,9 +6,12 @@
from foundation import secp256k1
from ubinascii import a2b_base64
from ubinascii import unhexlify as a2b_hex
+from uio import BytesIO
+from ustruct import pack
-from bip322 import create_virtual_transactions, sign_taproot_simple, taproot_signature_hash
-from serializations import hash256
+from bip322 import INVALID_REQUEST, TAPROOT_ONLY, create_virtual_transactions, read_signing_request
+from bip322 import sign_taproot_request, sign_taproot_simple, taproot_signature_hash
+from serializations import SIGHASH_ALL, SIGHASH_DEFAULT, deser_compact_size, hash256, ser_string
from taproot import output_script, tagged_hash
@@ -126,26 +129,191 @@ def bip340_verify(pubkey, signature, digest):
signature = sign_taproot_simple(message, internal_pubkey, private_key)
assert signature.startswith('smp')
+# Text signatures are SIGHASH_ALL, which every verifier must accept and the only type Sparrow accepts.
witness = a2b_base64(signature[3:])
-assert len(witness) == 66
-assert witness[:2] == b'\x01\x40'
+assert len(witness) == 67
+assert witness[:2] == b'\x01\x41'
+assert witness[66] == SIGHASH_ALL
-# The encoding checks above pass for any 64-byte signature, so verify the
+# SIGHASH_ALL changes the digest. The value comes from an implementation outside the firmware, checked against
+# the BIP-322 SIGHASH_DEFAULT vector above.
+sighash = taproot_signature_hash(message, message_challenge)
+sighash_all = taproot_signature_hash(message, message_challenge, SIGHASH_ALL)
+assert sighash_all == a2b_hex('f4ee2b0fa213cd562b51dcaa94cae4d16d39256ee52a754779222eaddf4184f3')
+
+# The encoding checks above pass for any 65-byte signature, so verify the
# signature cryptographically as well.
-schnorr_signature = witness[2:]
+schnorr_signature = witness[2:66]
output_pubkey = message_challenge[2:]
-sighash = taproot_signature_hash(message, message_challenge)
-assert bip340_verify(output_pubkey, schnorr_signature, sighash)
+assert bip340_verify(output_pubkey, schnorr_signature, sighash_all)
+assert not bip340_verify(output_pubkey, schnorr_signature, sighash)
# It must bind to the message.
-tampered_sighash = taproot_signature_hash(b'Tampered message', message_challenge)
-assert tampered_sighash != sighash
+tampered_sighash = taproot_signature_hash(b'Tampered message', message_challenge, SIGHASH_ALL)
+assert tampered_sighash != sighash_all
assert not bip340_verify(output_pubkey, schnorr_signature, tampered_sighash)
# And it must be made with the tweaked output key, not the internal key. Both
# are valid x-only keys, so only verification distinguishes them.
assert internal_pubkey != output_pubkey
-assert not bip340_verify(internal_pubkey, schnorr_signature, sighash)
+assert not bip340_verify(internal_pubkey, schnorr_signature, sighash_all)
+
+
+# BIP-322 requests sent as a PSBT, built the way Sparrow builds them: the to_sign transaction as a PSBTv0,
+# the message in global field 0x09, and an input carrying the zero-value UTXO, SIGHASH_ALL and the
+# key-path derivation.
+HARDENED = 0x80000000
+XFP = 0x78563412
+PATH = [86 | HARDENED, 1 | HARDENED, HARDENED, 0, 0]
+
+
+def derivation(path=PATH, leaves=0):
+ return bytes([leaves]) + b'\x11' * 32 * leaves + pack('<%dI' % (1 + len(path)), XFP, *path)
+
+
+def request_maps(message, script):
+ _, to_sign = create_virtual_transactions(message, script)
+ global_map = [(b'\x00', to_sign), (b'\x09', message)]
+ input_map = [(b'\x01', pack('<q', 0) + ser_string(script)),
+ (b'\x03', pack('<I', SIGHASH_ALL)),
+ (b'\x16' + internal_pubkey, derivation()),
+ (b'\x17', internal_pubkey)]
+ return global_map, input_map, []
+
+
+def serialize(maps, tail=b''):
+ out = b'psbt\xff'
+ for entries in maps:
+ for key, value in entries:
+ out += ser_string(key) + ser_string(value)
+ out += b'\x00'
+ return out + tail
+
+
+def read_maps(data):
+ fd = BytesIO(data)
+ assert fd.read(5) == b'psbt\xff'
+ maps = []
+ for _ in range(3):
+ entries = []
+ while True:
+ key = fd.read(deser_compact_size(fd))
+ if not key:
+ break
+ entries.append((key, fd.read(deser_compact_size(fd))))
+ maps.append(entries)
+ assert fd.read(1) == b''
+ return maps
+
+
+def rejected(psbt, error):
+ try:
+ read_signing_request(psbt)
+ except ValueError as e:
+ assert str(e) == error, str(e)
+ return
+ assert False, 'request was accepted'
+
+
+other_key = a2b_hex('01' * 32)
+other_pubkey = secp256k1.public_key_schnorr(other_key)
+
+# A request reads back with its message, address, key derivation and sighash type.
+maps = request_maps(message, message_challenge)
+psbt = serialize(maps)
+request = read_signing_request(psbt)
+assert request.message == message
+assert request.script_pubkey == message_challenge
+assert request.xfp == XFP
+assert request.path == PATH
+assert request.hash_type == SIGHASH_ALL
+
+# Signing adds the key-path signature to the input and changes nothing else.
+signed = read_maps(sign_taproot_request(request, internal_pubkey, private_key))
+assert signed[0] == maps[0]
+assert signed[1][:-1] == maps[1]
+assert signed[2] == maps[2]
+key, tap_key_sig = signed[1][-1]
+assert key == b'\x13'
+assert len(tap_key_sig) == 65
+assert tap_key_sig[64] == SIGHASH_ALL
+assert bip340_verify(output_pubkey, tap_key_sig[:64], sighash_all)
+assert not bip340_verify(output_pubkey, tap_key_sig[:64], sighash)
+rejected(serialize(signed), 'This message request is already signed.')
+
+# Without a sighash type, a request is signed with SIGHASH_DEFAULT, the Taproot default for PSBTs.
+global_map, input_map, output_map = request_maps(message, message_challenge)
+del input_map[1]
+request = read_signing_request(serialize((global_map, input_map, output_map)))
+assert request.hash_type == SIGHASH_DEFAULT
+tap_key_sig = read_maps(sign_taproot_request(request, internal_pubkey, private_key))[1][-1][1]
+assert len(tap_key_sig) == 64
+assert bip340_verify(output_pubkey, tap_key_sig, sighash)
+
+# A key that does not own the address does not sign.
+try:
+ sign_taproot_request(request, other_pubkey, other_key)
+ assert False, 'signed with the wrong key'
+except ValueError:
+ pass
+
+# The message under review must be the one the transaction commits to, and so must the address.
+MISMATCH = 'The transaction in this request does not match its message.'
+global_map, input_map, output_map = request_maps(message, message_challenge)
+global_map[1] = (b'\x09', b'Tampered message')
+rejected(serialize((global_map, input_map, output_map)), MISMATCH)
+
+global_map, input_map, output_map = request_maps(message, message_challenge)
+input_map[0] = (b'\x01', pack('<q', 0) + ser_string(output_script(other_pubkey, None)))
+rejected(serialize((global_map, input_map, output_map)), MISMATCH)
+
+# The output being spent holds no value.
+global_map, input_map, output_map = request_maps(message, message_challenge)
+input_map[0] = (b'\x01', pack('<q', 1) + ser_string(message_challenge))
+rejected(serialize((global_map, input_map, output_map)), INVALID_REQUEST)
+
+# Other address types are pointed to the Electrum format.
+p2wpkh_request = serialize(request_maps(b'Hello World', a2b_hex('00142b05d564e6a7a33c087f16e0f730d1440123799d')))
+rejected(p2wpkh_request, TAPROOT_ONLY)
+
+# The message has to be in the request.
+global_map, input_map, output_map = request_maps(message, message_challenge)
+del global_map[1]
+rejected(serialize((global_map, input_map, output_map)), 'This request does not include the message to sign.')
+
+# Only SIGHASH_DEFAULT and SIGHASH_ALL commit to the whole virtual transaction.
+for hash_type in (2, 3, 0x81):
+ global_map, input_map, output_map = request_maps(message, message_challenge)
+ input_map[1] = (b'\x03', pack('<I', hash_type))
+ rejected(serialize((global_map, input_map, output_map)), 'Unsupported signature hash type.')
+
+# Exactly one key-path derivation below a master fingerprint.
+for bad_derivation in (b'', b'\x00', derivation(leaves=1), derivation(path=[]), derivation()[:-2]):
+ global_map, input_map, output_map = request_maps(message, message_challenge)
+ input_map[2] = (input_map[2][0], bad_derivation)
+ rejected(serialize((global_map, input_map, output_map)), INVALID_REQUEST)
+
+global_map, input_map, output_map = request_maps(message, message_challenge)
+input_map.append((b'\x16' + other_pubkey, derivation()))
+rejected(serialize((global_map, input_map, output_map)), INVALID_REQUEST)
+
+global_map, input_map, output_map = request_maps(message, message_challenge)
+del input_map[2]
+rejected(serialize((global_map, input_map, output_map)), INVALID_REQUEST)
+
+# Malformed PSBTs: a duplicate key, an extra map, a truncated or mislabelled stream, and a PSBTv2 with no
+# unsigned transaction.
+global_map, input_map, output_map = request_maps(message, message_challenge)
+global_map.append(global_map[1])
+rejected(serialize((global_map, input_map, output_map)), INVALID_REQUEST)
+
+rejected(serialize(request_maps(message, message_challenge), tail=b'\x00'), INVALID_REQUEST)
+rejected(psbt[:-3], INVALID_REQUEST)
+rejected(b'psbu' + psbt[4:], INVALID_REQUEST)
+
+global_map, input_map, output_map = request_maps(message, message_challenge)
+global_map[0] = (b'\xfb', pack('<I', 2))
+rejected(serialize((global_map, input_map, output_map)), INVALID_REQUEST)
return_value.write(b'OK')
### ports/stm32/boards/Passport/modules/tests/unit/bip322_request.py
@@ -0,0 +1,290 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Route a BIP-322 request sent as a PSBT through the message flow, its validation and its signing, with a
+# stand-in keystore. tests/unit/bip322.py checks the request parsing and the signature itself.
+
+import uasyncio as asyncio
+from ubinascii import unhexlify as a2b_hex
+from ustruct import pack
+
+import common
+import stash
+import flows.sign_electrum_message_flow as electrum
+from bip322 import INVALID_REQUEST, TAPROOT_ONLY, create_virtual_transactions
+from data_codecs.qr_type import QRType
+from foundation import secp256k1, ur
+from public_constants import AF_P2TR, AF_P2WPKH
+from serializations import SIGHASH_ALL, ser_string
+from taproot import output_script
+from tasks.sign_text_file_task import sign_text_file_task
+from tasks.validate_bip322_request_task import validate_bip322_request_task
+from utils import swab32
+
+
+class MemorySettings:
+ def __init__(self):
+ self.values = {}
+
+ def get(self, key, default=None):
+ return self.values.get(key, default)
+
+ def set(self, key, value):
+ self.values[key] = value
+
+
+if common.settings is None:
+ common.settings = MemorySettings()
+
+HARDENED = 0x80000000
+XFP = 0x78563412
+PATH = [86 | HARDENED, 1 | HARDENED, HARDENED, 0, 0]
+SUBPATH = "m/86'/1'/0'/0/0"
+ADDRESS = 'tb1p-address'
+PRIVATE_KEY = a2b_hex('f805d22c9379f60b87770c8358c8fc2310b3e65d1c4555a51f58c912862b385b')
+INTERNAL_PUBKEY = secp256k1.public_key_schnorr(PRIVATE_KEY)
+SCRIPT = output_script(INTERNAL_PUBKEY, None)
+MESSAGE = 'Proof of reserves for tb1p'
+
+
+def request_psbt(message=MESSAGE.encode(), path=PATH, script=SCRIPT, derivation_value=None):
+ _, to_sign = create_virtual_transactions(message, script)
+ if derivation_value is None:
+ derivation_value = b'\x00' + pack('<%dI' % (1 + len(path)), XFP, *path)
+ entries = ((b'\x00', to_sign), (b'\x09', message), None,
+ (b'\x01', pack('<q', 0) + ser_string(script)),
+ (b'\x03', pack('<I', SIGHASH_ALL)),
+ (b'\x16' + INTERNAL_PUBKEY, derivation_value),
+ (b'\x17', INTERNAL_PUBKEY), None, None)
+ out = b'psbt\xff'
+ for entry in entries:
+ out += b'\x00' if entry is None else ser_string(entry[0]) + ser_string(entry[1])
+ return out
+
+
+class KeyNode:
+ public_key_bytes = b'\x02' + INTERNAL_PUBKEY
+
+ def public_key(self):
+ return self.public_key_bytes
+
+ def private_key(self):
+ return bytearray(PRIVATE_KEY)
+
+
+class KeyValues:
+ derived = []
+
+ def __enter__(self):
+ self.chain = self
+ return self
+
+ def __exit__(self, *args):
+ pass
+
+ def derive_path(self, path):
+ self.derived.append(path)
+ return KeyNode()
+
+ def address(self, node, addr_type):
+ return ADDRESS
+
+ def register(self, value):
+ pass
+
+
+async def validate(psbt):
+ results = []
+
+ async def on_done(value, error):
+ results.append((value, error))
+
+ await validate_bip322_request_task(on_done, psbt)
+ assert len(results) == 1
+ return results[0]
+
+
+async def sign(request, addr_fmt=AF_P2TR):
+ results = []
+
+ async def on_done(signature, address, error):
+ results.append((signature, address, error))
+
+ await sign_text_file_task(on_done, MESSAGE, SUBPATH, addr_fmt, ADDRESS, request)
+ assert len(results) == 1
+ return results[0]
+
+
+async def run_task_tests():
+ # A request from this wallet for a Taproot path is shown as text with its path.
+ psbt = request_psbt()
+ KeyValues.derived = []
+ value, error = await validate(psbt)
+ assert error is None, error
+ message, subpath, request = value
+ assert message == MESSAGE
+ assert subpath == SUBPATH
+ assert KeyValues.derived == [SUBPATH]
+
+ # Fingerprints are matched in either byte order, as when signing a transaction.
+ common.settings.set('xfp', swab32(XFP))
+ assert (await validate(psbt))[1] is None
+ common.settings.set('xfp', 0x01020304)
+ assert (await validate(psbt))[1] == 'This message request is for a different wallet.'
+ common.settings.set('xfp', XFP)
+
+ # The address shown comes from the path, so the path must be a Taproot one.
+ value, error = await validate(request_psbt(path=[84 | HARDENED, 1 | HARDENED, HARDENED, 0, 0]))
+ assert error == TAPROOT_ONLY
+
+ # The text checks are the ones a message scanned as text gets.
+ for message in (b'visible\x00hidden', b'visible\x1bhidden', b'caf\xc3\xa9', b'\xff\xfe'):
+ value, error = await validate(request_psbt(message=message))
+ assert value is None
+ assert error is not None
+
+ # A key at that path must own the address in the request.
+ KeyNode.public_key_bytes = b'\x02' + secp256k1.public_key_schnorr(a2b_hex('01' * 32))
+ try:
+ value, error = await validate(psbt)
+ assert error == 'The address in this request does not match its derivation path.'
+ finally:
+ KeyNode.public_key_bytes = b'\x02' + INTERNAL_PUBKEY
+
+ assert (await validate(b'psbt\xff'))[1] == INVALID_REQUEST
+ for derivation_value in (b'', b'\x00'):
+ assert await validate(request_psbt(derivation_value=derivation_value)) == (None, INVALID_REQUEST)
+
+ # Signing returns the request's PSBT with the key-path signature added to its input.
+ signed, address, error = await sign(request)
+ assert error is None, error
+ assert address == ADDRESS
+ offset = request.signature_offset
+ assert signed[:offset] == psbt[:offset]
+ assert signed[offset:offset + 3] == b'\x01\x13\x41'
+ assert signed[offset + 3 + 64] == SIGHASH_ALL
+ assert signed[offset + 3 + 65:] == psbt[offset:]
+
+ # A request is only signed with the Taproot key it names.
+ assert (await sign(request, addr_fmt=AF_P2WPKH))[2] is not None
+
+
+class MockScanQRFlow:
+ result = None
+ kwargs = None
+
+ def __init__(self, **kwargs):
+ MockScanQRFlow.kwargs = kwargs
+
+ async def run(self):
+ return MockScanQRFlow.result
+
+
+class MockShowQRPage:
+ shown = []
+
+ def __init__(self, qr_type, qr_data, right_micron):
+ self.shown.append((qr_type, qr_data))
+
+ async def show(self):
+ return True
+
+
+class MockFlow:
+ psbt = None
+ bip322_request = None
+ validate_message = 'validate-message'
+ validate_bip322_request = 'validate-bip322-request'
+ show_message = 'show-message'
+ show_signed = 'show-signed'
+
+ def goto(self, state, **kwargs):
+ self.next_state = state
+
+ def set_result(self, result):
+ self.result = result
+
+
+async def run_flow_tests():
+ psbt = request_psbt()
+
+ # A PSBT scanned in the message flow goes to BIP-322 validation; text still goes to message validation.
+ MockScanQRFlow.result = ur.new_psbt(psbt)
+ flow = MockFlow()
+ await electrum.SignElectrumMessageFlow.scan_message(flow)
+ assert QRType.UR2 in MockScanQRFlow.kwargs['qr_types']
+ assert MockScanQRFlow.kwargs['ur_types'] == [ur.Value.PSBT]
+ assert flow.next_state == flow.validate_bip322_request
+ assert flow.psbt == psbt
+
+ MockScanQRFlow.result = 'signmessage {} ascii:{}'.format(SUBPATH, MESSAGE)
+ flow = MockFlow()
+ await electrum.SignElectrumMessageFlow.scan_message(flow)
+ assert flow.next_state == flow.validate_message
+ assert flow.message == MockScanQRFlow.result
+
+ # Validation hands the review the message and path, and keeps the request for signing.
+ flow = MockFlow()
+ flow.psbt = psbt
+ await electrum.SignElectrumMessageFlow.validate_bip322_request(flow)
+ assert flow.next_state == flow.show_message
+ assert flow.message == MESSAGE
+ assert flow.subpath == SUBPATH
+ assert flow.bip322_request.message == MESSAGE.encode()
+ assert flow.psbt is None
+
+ # Signing passes the request along, and the result goes back as a PSBT.
+ flow.addr_format = AF_P2TR
+ flow.address = ADDRESS
+ await electrum.SignElectrumMessageFlow.do_sign(flow)
+ assert flow.next_state == flow.show_signed
+ MockShowQRPage.shown = []
+ await electrum.SignElectrumMessageFlow.show_signed(flow)
+ ((qr_type, qr_data),) = MockShowQRPage.shown
+ assert qr_type == QRType.UR2
+ assert qr_data.ur_type() == ur.Value.PSBT
+ assert bytes(qr_data.unwrap_psbt()) == flow.signature
+
+ # A text signature is still shown as plain text.
+ flow = MockFlow()
+ flow.signature = 'H1234='
+ MockShowQRPage.shown = []
+ await electrum.SignElectrumMessageFlow.show_signed(flow)
+ assert MockShowQRPage.shown == [(QRType.QR, 'H1234=')]
+
+
+async def run_spinner(label, task, args):
+ results = []
+
+ async def on_done(*values):
+ results.append(values)
+
+ await task(on_done, *args)
+ assert len(results) == 1
+ return results[0]
+
+
+async def run_tests():
+ original_xfp = common.settings.get('xfp')
+ original_sensitive_values = stash.SensitiveValues
+ original_scan = electrum.ScanQRFlow
+ original_show = electrum.ShowQRPage
+ original_spinner = electrum.spinner_task
+ try:
+ common.settings.set('xfp', XFP)
+ stash.SensitiveValues = KeyValues
+ electrum.ScanQRFlow = MockScanQRFlow
+ electrum.ShowQRPage = MockShowQRPage
+ electrum.spinner_task = run_spinner
+ await run_task_tests()
+ await run_flow_tests()
+ finally:
+ common.settings.set('xfp', original_xfp)
+ stash.SensitiveValues = original_sensitive_values
+ electrum.ScanQRFlow = original_scan
+ electrum.ShowQRPage = original_show
+ electrum.spinner_task = original_spinner
+
+
+asyncio.run(run_tests())
+return_value.write(b'OK')
### ports/stm32/boards/Passport/modules/tests/unit/message_display.py
@@ -55,6 +55,7 @@ class MockFlow:
sign_health_check = 'sign-microsd'
show_signed = 'show-signed'
format_signature = 'format-signature'
+ bip322_request = None
def goto(self, state, **kwargs):
self.next_state = stateWhy this scored 37/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.