Merge pull request #731 from Foundation-Devices/SFT-974-miniscript-ui-followup
What changed, and why it matters
This commit is a follow-up to the miniscript wallet-policy user interface. It mostly fixes UI wording, memory cleanup, and policy display logic. The only potentially security-relevant change is that wallet policy IDs are now computed with an incremental SHA-256 digest instead of a single buffer, and a few validation steps were removed or reordered. There is no direct evidence of an exploitable vulnerability in the diff, but the change is large enough that a subtle bug could hide in the new policy import/backup flows.
Treat as a normal feature/bugfix follow-up. Review the incremental SHA-256 implementation for correctness, confirm that removing `validate()` does not allow invalid miniscript contexts to reach compilation, and run the new simulator and host tests before release. No emergency response is indicated by the diff alone.
Security signals we found
Incremental SHA-256 digest used for policy ID computation
Removal of explicit `validate(miniscript, context)` call before compilation
New default-name derivation from descriptor checksum
Memory cleanup (`gc.collect()`) added around sensitive policy operations
New wallet-policy QR backup simulator test
Evidence from the diff
The merge adds UI polish and memory-pressure improvements (gc.collect() calls) to the Passport miniscript wallet-policy flows. It introduces VerifyWalletPolicyAddressFlow, renames menu labels, changes timelock display text, and refactors _walk to an iterative traversal. The policy ID calculation in wallet_policy.py was switched from a single accumulated payload buffer to an incremental sha256 digest object, which is functionally equivalent if implemented correctly. A call to validate(miniscript, context) was removed before compile_miniscript, but compile-time checks remain. decode_policy_transport now derives a default name from the descriptor checksum when none is supplied. No explicit security bug is visible in the diff, but the breadth of the change warrants normal regression testing.
Changed components
ports/stm32/boards/Passport/modules/wallet_policy.pyports/stm32/boards/Passport/modules/policy_transport.pyports/stm32/boards/Passport/modules/miniscript.pyports/stm32/boards/Passport/modules/policy_display.pyports/stm32/boards/Passport/modules/flows/wallet_policy_flow.pyports/stm32/boards/Passport/modules/menus.pyInspect captured patch +415 / −53
### ports/stm32/boards/Passport/modules/flows/scan_qr_flow.py
@@ -115,7 +115,7 @@ async def handle_ur(self):
async def handle_qr(self):
if QRType.QR not in self.qr_types and QRType.QR != self.explicit_type:
- await ErrorPage(text='Scan. failed.\n'
+ await ErrorPage(text='Scan failed.\n'
'Expected to scan a Uniform Resource containing '
'{}.'.format(self.data_description)).show()
self.set_result(None)
### ports/stm32/boards/Passport/modules/flows/wallet_policy_flow.py
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
# SPDX-License-Identifier: GPL-3.0-or-later
+import gc
+
from flows import Flow, SaveToMicroSDFlow
@@ -9,6 +11,7 @@ def _decode_policy(data):
import stash
from policy_transport import decode_policy_transport
+ gc.collect()
chain = chains.current_chain()
with stash.SensitiveValues() as sv:
def derive_node(path):
@@ -17,7 +20,9 @@ def derive_node(path):
node.derive(element)
return node
- return decode_policy_transport(data, chain, sv.get_xfp(), derive_node)
+ policy = decode_policy_transport(data, chain, sv.get_xfp(), derive_node)
+ gc.collect()
+ return policy
def _verify_current_seed(policy, chain):
@@ -63,7 +68,7 @@ async def choose_name(self):
self.goto(self.show_error)
return
self.key_name_position = 0
- self.goto(self.choose_key_name)
+ self.goto(self.choose_key_name if self.external_key_indexes else self.show_overview)
async def choose_key_name(self):
import microns
@@ -104,11 +109,13 @@ async def choose_key_name(self):
async def show_overview(self):
from flows import SeriesOfPagesFlow
from pages import LongTextPage
+ gc.collect()
page_args = [{
'card_header': {'title': 'Wallet policy'},
'text': text,
'centered': not text.startswith('Path '),
} for text in self.policy.format_review_pages()]
+ gc.collect()
result = await SeriesOfPagesFlow(LongTextPage, page_args).run()
if result:
self.goto(self.choose_technical_details)
@@ -145,11 +152,13 @@ async def confirm_import(self):
from pages import LongQuestionPage
from styles.colors import HIGHLIGHT_TEXT_HEX
from utils import escape_text, recolor
+ gc.collect()
text = 'Register {}?\n\n{}\n\n{}\n{}'.format(
recolor(HIGHLIGHT_TEXT_HEX, escape_text(self.policy.name)),
self.policy.format_confirmation(),
recolor(HIGHLIGHT_TEXT_HEX, 'Policy checksum'),
recolor(HIGHLIGHT_TEXT_HEX, self.policy.descriptor_check()))
+ gc.collect()
result = await LongQuestionPage(text=text).show()
if result:
self.goto(self.save_policy)
@@ -296,7 +305,11 @@ async def scan(self):
self.error = str(exc) or 'Wallet Policy Import Error'
self.goto(self.show_error)
return
- result = await ImportWalletPolicyFlow(policy).run()
+ flow = ImportWalletPolicyFlow(policy)
+ # Import buffers would otherwise stay live throughout registration.
+ del data, result, policy
+ gc.collect()
+ result = await flow.run()
self.set_result(result)
async def show_error(self):
@@ -337,7 +350,10 @@ async def choose_file(self):
self.error = str(exc) or 'Wallet Policy Import Error'
self.goto(self.show_error)
return
- result = await ImportWalletPolicyFlow(policy).run()
+ flow = ImportWalletPolicyFlow(policy)
+ del data, policy
+ gc.collect()
+ result = await flow.run()
self.set_result(result)
async def show_error(self):
@@ -361,11 +377,13 @@ async def show_overview(self):
await ErrorPage('Wallet policy was not found.').show()
self.set_result(False)
return
+ gc.collect()
page_args = [{
'card_header': {'title': 'Wallet policy'},
'text': text,
'centered': not text.startswith('Path '),
} for text in self.policy.format_review_pages()]
+ gc.collect()
result = await SeriesOfPagesFlow(LongTextPage, page_args).run()
if result:
self.goto(self.choose_technical_details)
@@ -549,6 +567,7 @@ def __init__(self, context=None):
super().__init__(initial_state=self.show_qr, name='ExportWalletPolicyQRFlow')
async def show_qr(self):
+ gc.collect()
from data_codecs.qr_type import QRType
from foundation import ur
from pages import ErrorPage, ShowQRPage
@@ -557,8 +576,13 @@ async def show_qr(self):
await ErrorPage('Wallet policy was not found.').show()
self.set_result(False)
return
+ gc.collect()
data = encode_policy_transport(self.policy).encode('utf-8')
- await ShowQRPage(qr_type=QRType.UR2, qr_data=ur.new_bytes(data)).show()
+ gc.collect()
+ # The UR value borrows data, so retain it until the QR page closes.
+ page = ShowQRPage(qr_type=QRType.UR2, qr_data=ur.new_bytes(data))
+ gc.collect()
+ await page.show()
self.set_result(True)
@@ -581,6 +605,25 @@ def __init__(self, context=None):
data=encode_policy_transport(policy), success_text='wallet policy')
+class VerifyWalletPolicyAddressFlow(Flow):
+ def __init__(self, context=None):
+ self.policy_id = context
+ super().__init__(initial_state=self.verify, name='VerifyWalletPolicyAddressFlow')
+
+ async def verify(self):
+ from common import settings
+ from flows import VerifyAddressFlow
+ from pages import ErrorPage
+ from wallet_policy import WalletPolicyRegistry
+
+ policy = WalletPolicyRegistry(settings).get(self.policy_id)
+ if policy is None:
+ await ErrorPage('Wallet policy was not found.').show()
+ self.set_result(False)
+ return
+ self.set_result(await VerifyAddressFlow(sig_type='policy', wallet_policy=policy).run())
+
+
class VerifyWalletPolicyRequestFlow(Flow):
"""Derive a bound Liana address request and return a confirmation QR."""
### ports/stm32/boards/Passport/modules/menus.py
@@ -400,17 +400,17 @@ def wallet_policy_item_menu():
from flows.wallet_policy_flow import (
DeleteWalletPolicyFlow, ExportWalletPolicyMicroSDFlow,
ExportWalletPolicyQRFlow, NameWalletPolicyKeysFlow, RenameWalletPolicyFlow,
- VerifyWalletPolicyRequestFlow, ViewWalletPolicyFlow)
+ VerifyWalletPolicyAddressFlow, ViewWalletPolicyFlow)
return [
{'icon': 'ICON_TWO_KEYS', 'label': 'View Details', 'flow': ViewWalletPolicyFlow},
{'icon': 'ICON_SCAN_QR', 'label': 'Export via QR', 'flow': ExportWalletPolicyQRFlow,
'statusbar': {'title': 'EXPORT'}},
{'icon': 'ICON_MICROSD', 'label': 'Export via microSD',
'flow': ExportWalletPolicyMicroSDFlow, 'statusbar': {'title': 'EXPORT'}},
- {'icon': 'ICON_SCAN_QR', 'label': 'Verify Liana Address',
- 'flow': VerifyWalletPolicyRequestFlow, 'statusbar': {'title': 'VERIFY'}},
- {'icon': 'ICON_SIGN', 'label': 'Rename', 'flow': RenameWalletPolicyFlow,
+ {'icon': 'ICON_SCAN_QR', 'label': 'Verify Address',
+ 'flow': VerifyWalletPolicyAddressFlow, 'statusbar': {'title': 'VERIFY'}},
+ {'icon': 'ICON_SIGN', 'label': 'Rename Policy', 'flow': RenameWalletPolicyFlow,
'exit_on_success': True},
{'icon': 'ICON_TWO_KEYS', 'label': 'Name Signers',
'flow': NameWalletPolicyKeysFlow, 'exit_on_success': True},
### ports/stm32/boards/Passport/modules/miniscript.py
@@ -504,11 +504,14 @@ def analyze(node, context='wsh'):
def _walk(node):
- yield node
- for arg in node.args:
- if isinstance(arg, Node):
- for child in _walk(arg):
- yield child
+ pending = [node]
+ while pending:
+ node = pending.pop()
+ yield node
+ for index in range(len(node.args) - 1, -1, -1):
+ child = node.args[index]
+ if isinstance(child, Node):
+ pending.append(child)
def iter_policy_keys(node):
### ports/stm32/boards/Passport/modules/policy_display.py
@@ -118,8 +118,7 @@ def describe_timelock(kind, value):
if value & (1 << 22):
units = value & 0xffff
seconds = units * 512
- exact = '{} seconds ({} x 512)'.format(
- _group_number(seconds), _group_number(units))
+ exact = '{} seconds'.format(_group_number(seconds))
if value != ((1 << 22) | units):
exact += ' (encoded as older({}))'.format(value)
return (
@@ -378,6 +377,17 @@ def _path_requires_passport(policy, path):
return not result
+def _passport_role(policy, path):
+ requires = _path_requires_passport(policy, path)
+ if requires is True:
+ return 'required'
+ if requires is None:
+ return 'review details'
+ if any(index in policy.owned_key_indexes for index in path['keys']):
+ return 'optional'
+ return 'not used'
+
+
def _simple_path_pages(policy, simple):
primary, recovery = simple
owned = policy.keys[policy.owned_key_indexes[0]]
@@ -484,7 +494,9 @@ def _friendly_key_path(policy, path):
return None
required, indexes = threshold
- if required == len(indexes) == 2:
+ if required == len(indexes) == 1:
+ summary = 'This key must sign'
+ elif required == len(indexes) == 2:
summary = 'Both keys must sign'
elif required == len(indexes):
summary = 'All {} keys must sign'.format(len(indexes))
@@ -625,20 +637,9 @@ def format_review_pages(policy):
if not simple and len(paths) > 1:
lines = ['This Passport']
for path in paths:
- requires = _path_requires_passport(policy, path)
- if requires is True:
+ role = _passport_role(policy, path)
+ if role == 'required':
role = 'must sign'
- elif requires is False:
- if any(key_index in policy.owned_key_indexes
- for key_index in path['keys']):
- role = 'optional'
- else:
- role = 'not used'
- else:
- role = 'review details'
- # MicroPython does not provide str.capitalize(). Keep this simple
- # transformation within the subset shared by host Python and the
- # firmware runtime.
display_role = role[0].upper() + role[1:]
lines.extend(['', _path_name(path), display_role])
pages.append('\n'.join(lines))
@@ -663,10 +664,16 @@ def format_confirmation(policy):
'{} {}\ncan spend by itself {} after each coin confirms.'
).format(_escape(policy.key_names[recovery['keys'][0]]) or 'Recovery',
format_fingerprint(key.fingerprint), short)
- bypass = sum(1 for path in paths if _path_requires_passport(policy, path) is False)
+ roles = {'required': 0, 'optional': 0, 'not used': 0, 'review details': 0}
+ for path in paths:
+ role = _passport_role(policy, path)
+ roles[role] += 1
text = _plural(len(paths), 'spending path')
- if bypass:
- text += '\n{} without Passport'.format(bypass)
+ for role in ('not used', 'optional', 'required'):
+ if roles[role]:
+ text += '\nPassport {} in {}'.format(role, roles[role])
+ if roles['review details']:
+ text += '\nReview Passport role in {}'.format(roles['review details'])
return text
### ports/stm32/boards/Passport/modules/policy_transport.py
@@ -3,6 +3,8 @@
"""Versioned QR/microSD transport for registered wallet policies."""
+import gc
+
try:
import ujson as json
except ImportError: # pragma: no cover - CPython host tests
@@ -15,7 +17,7 @@
from policy_errors import PolicyMismatchError, PolicyParseError, PolicyResourceError
from wallet_policy import (KeyInfo, MiniscriptPolicy,
- descriptor_to_policy_template)
+ descriptor_to_policy_template, format_policy_descriptor)
TRANSPORT_FORMAT = 'passport-wallet-policy'
@@ -90,14 +92,15 @@ def _transport_text(data, invalid_utf8_message):
def decode_policy_transport(data, chain, master_xfp, derive_node,
- default_name='Wallet Policy'):
+ default_name=''):
data = _transport_text(data, 'Wallet policy file is not UTF-8 text')
if not isinstance(data, str):
raise PolicyParseError('Wallet policy transport must be text')
data = data.strip()
if not data or len(data) > MAX_TRANSPORT_LENGTH:
raise PolicyResourceError('Wallet policy transport is empty or too large')
+ gc.collect()
policy_id = None
if data.startswith('{'):
try:
@@ -119,16 +122,23 @@ def decode_policy_transport(data, chain, master_xfp, derive_node,
raise PolicyParseError('Wallet policy key vector is missing')
keys = tuple(KeyInfo.parse(value) for value in raw_keys)
policy_id = envelope.get('policy_id')
+ del envelope
else:
name = default_name
template, raw_keys = descriptor_to_policy_template(data, require_checksum=True)
keys = tuple(KeyInfo.parse(value) for value in raw_keys)
network = _infer_standard_xpub_network(keys) or getattr(chain, 'ctype', None)
+ del data, raw_keys
+ gc.collect()
if network != getattr(chain, 'ctype', None):
raise PolicyMismatchError(_network_mismatch_message(network))
owned = discover_owned_key(keys, chain, master_xfp, derive_node)
+ if not name:
+ from descriptor import descriptor_checksum
+ name = descriptor_checksum(format_policy_descriptor(template, keys)).upper()
policy = MiniscriptPolicy(name, network, template, keys, owned)
+ gc.collect()
policy.validate_extended_keys(chain)
policy.verify_owned_key(chain, derive_node)
if policy_id is not None and policy_id != policy.policy_id:
### ports/stm32/boards/Passport/modules/tests/host/test_policy_display.py
@@ -340,7 +340,7 @@ def test_height_and_time_locks_get_human_and_exact_descriptions():
short, exact, detail = describe_timelock('older', (1 << 22) | 1182)
assert short == 'about 1 week'
- assert exact == '605,184 seconds (1,182 x 512)'
+ assert exact == '605,184 seconds'
assert 'each coin confirms' in detail
assert describe_timelock('after', 840000)[:2] == (
@@ -367,9 +367,9 @@ def test_relative_block_delays_scale_from_one_block_to_consensus_maximum(
def test_time_based_relative_delay_and_absolute_date_are_unambiguous():
assert describe_timelock('older', (1 << 22) | 1)[:2] == (
- 'about 8 minutes', '512 seconds (1 x 512)')
+ 'about 8 minutes', '512 seconds')
assert describe_timelock('older', (1 << 22) | 65535)[:2] == (
- 'about 1 year 1 month', '33,553,920 seconds (65,535 x 512)')
+ 'about 1 year 1 month', '33,553,920 seconds')
assert describe_timelock('after', 1798761600)[:2] == (
'2027-01-01 UTC', 'Unix timestamp 1,798,761,600')
@@ -468,3 +468,36 @@ def test_unconditional_lock_still_filters_a_path_with_nested_optional_timing():
assert '5 blocks' in review
assert '10 blocks' in review
assert 'Available after' not in review
+
+
+@pytest.mark.parametrize('owned, expected', [
+ (2, 'Passport not used in 1\nPassport optional in 1'),
+ (0, 'Passport optional in 2'),
+])
+def test_confirmation_distinguishes_optional_and_absent_passport(owned, expected):
+ policy = MiniscriptPolicy(
+ 'Recovery', 'BTC',
+ 'wsh(or_i(multi(1,@0/<2;3>/*,@1/<2;3>/*),and_v(v:multi(1,@0/**,@1/**,@2/**),after(1795046400))))',
+ tuple(key_info(index) for index in range(3)), (owned,))
+ assert policy.format_confirmation() == '2 spending paths\n' + expected
+
+
+def test_confirmation_preserves_required_and_unknown_roles():
+ policy = MiniscriptPolicy('Required', 'BTC', 'wsh(pk(@0/**))', (key_info(0),), (0,))
+ assert policy.format_confirmation() == '1 spending path\nPassport required in 1'
+ conditional = MiniscriptPolicy(
+ 'Conditional', 'BTC', 'wsh(andor(pk(@0/**),pk(@1/**),pk(@2/**)))',
+ tuple(key_info(index) for index in range(3)), (0,))
+ assert conditional.format_confirmation() == '1 spending path\nReview Passport role in 1'
+
+
+def test_single_key_time_delay_keeps_encoding_in_technical_details():
+ policy = MiniscriptPolicy(
+ 'Time delay', 'BTC', 'wsh(and_v(v:pk(@0/**),older(4194305)))',
+ (key_info(0),), (0,))
+ review = '\n'.join(plain_review_pages(policy))
+ assert '512 seconds' in review
+ assert 'x 512' not in review
+ assert 'This key must sign' in review
+ assert 'All 1 keys' not in review
+ assert 'older(4194305): 1 x 512 = 512 seconds' in policy.format_details()
### ports/stm32/boards/Passport/modules/tests/host/test_wallet_policy.py
@@ -6,6 +6,7 @@
import builtins
import os
import sys
+import struct
import types
import pytest
@@ -190,6 +191,7 @@ def test_full_descriptor_converter_rejects_non_bip388_derivation(descriptor):
def test_policy_id_is_stable_across_rename_but_contents_are_validated():
policy = make_policy()
+ assert policy.policy_id == '938faed5cd17836ad2a5642d2227e304bc93aa2fb98f16f5e5c3932c49995323'
renamed = policy.rename('Inheritance')
assert renamed.policy_id == policy.policy_id
record = policy.serialize()
@@ -199,6 +201,22 @@ def test_policy_id_is_stable_across_rename_but_contents_are_validated():
MiniscriptPolicy.deserialize(record)
+def test_policy_identity_preserves_compact_size_for_long_templates():
+ template = 'wsh(' + 'and_v(v:older(16),' * 14 + 'pk(@0/**)' + ')' * 14 + ')'
+ assert 253 <= len(template) <= 512
+ policy = MiniscriptPolicy('Long template', 'BTC', template, (KEY_INFO,), (0,))
+ payload = (b'Passport Wallet Policy\x00\x01\x03BTC' +
+ b'\xfd' + struct.pack('<H', len(template)) + template.encode('ascii') +
+ b'\x01' + bytes([len(KEY_INFO)]) + KEY_INFO.encode('ascii'))
+ assert policy.policy_id == hashlib.sha256(payload).hexdigest()
+
+
+def test_registration_rejects_unsigned_policy():
+ with pytest.raises(PolicyTypeError, match='require a signature'):
+ MiniscriptPolicy('Unsigned', 'BTC', 'wsh(or_i(pk(@0/**),older(10)))',
+ (KEY_INFO,), (0,))
+
+
def test_local_key_names_are_migration_safe_and_do_not_change_policy_identity():
policy = make_policy()
legacy_record = policy.serialize()
@@ -252,6 +270,7 @@ def deserialize_node(xpub, address_format):
policy = decode_policy_transport(
descriptor, chain, my_xfp, lambda path: OwnedNode(owned_xpub),
default_name='Liana Multisig')
+ assert policy.name == 'Liana Multisig'
review_pages = policy.format_review_pages()
assert review_pages
assert any('Passport' in page for page in review_pages)
@@ -422,9 +441,30 @@ def test_policy_transport_round_trip_rediscovers_owned_key():
int.from_bytes(bytes.fromhex('6738736c'), 'little'),
lambda path: OwnedNode(XPUB))
assert decoded.policy_id == policy.policy_id
+ assert decoded.name == policy.name
assert decoded.owned_key_indexes == (0,)
+@pytest.mark.parametrize('transport', ('descriptor', 'missing-name', 'empty-name'))
+def test_unnamed_policy_import_uses_descriptor_checksum(transport):
+ policy = make_policy()
+ if transport == 'descriptor':
+ data = policy.full_descriptor()
+ else:
+ envelope = json.loads(encode_policy_transport(policy))
+ if transport == 'missing-name':
+ del envelope['name']
+ else:
+ envelope['name'] = ''
+ data = json.dumps(envelope)
+ decoded = decode_policy_transport(
+ data, DerivationChain(),
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'),
+ lambda path: OwnedNode(XPUB))
+ assert decoded.name == decoded.descriptor_check() == policy.descriptor_check()
+ assert decoded.policy_id == policy.policy_id
+
+
def test_policy_transport_accepts_ur_bytearray():
policy = make_policy()
encoded = bytearray(encode_policy_transport(policy), 'utf-8')
### ports/stm32/boards/Passport/modules/tests/host/test_wallet_policy_flows.py
@@ -3,6 +3,7 @@
import ast
import asyncio
+import gc
import importlib.util
import io
from pathlib import Path
@@ -31,7 +32,7 @@ def flow_method(filename, class_name, method_name):
tree = ast.parse((MODULES / 'flows' / filename).read_text())
cls = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == class_name)
method = next(node for node in cls.body if isinstance(node, ast.AsyncFunctionDef) and node.name == method_name)
- namespace = {}
+ namespace = {'gc': gc}
exec(compile(ast.Module(body=[method], type_ignores=[]), filename, 'exec'), namespace)
return namespace[method_name]
@@ -196,3 +197,129 @@ async def run(self):
asyncio.run(flow_method('wallet_policy_flow.py', 'ImportWalletPolicyFromQRFlow', 'scan')(flow))
assert states == ['error']
assert 'microSD' in flow.error
+
+
+@pytest.mark.parametrize('exists, result', [(True, True), (True, False), (False, False)])
+def test_policy_menu_verifies_selected_policy(monkeypatch, exists, result):
+ policy = object() if exists else None
+ settings = object()
+ calls = []
+
+ class MockRegistry:
+ def __init__(self, actual_settings):
+ assert actual_settings is settings
+
+ def get(self, policy_id):
+ assert policy_id == 'selected-policy'
+ return policy
+
+ class MockVerifyAddressFlow:
+ def __init__(self, sig_type, wallet_policy):
+ assert sig_type == 'policy'
+ assert wallet_policy is policy
+ calls.append('verify')
+
+ async def run(self):
+ return result
+
+ class MockErrorPage:
+ def __init__(self, message):
+ assert message == 'Wallet policy was not found.'
+ calls.append('missing')
+
+ async def show(self):
+ pass
+
+ monkeypatch.setitem(sys.modules, 'common', SimpleNamespace(settings=settings))
+ monkeypatch.setitem(sys.modules, 'flows', SimpleNamespace(VerifyAddressFlow=MockVerifyAddressFlow))
+ monkeypatch.setitem(sys.modules, 'pages', SimpleNamespace(ErrorPage=MockErrorPage))
+ monkeypatch.setattr('wallet_policy.WalletPolicyRegistry', MockRegistry)
+ results = []
+ flow = SimpleNamespace(policy_id='selected-policy', set_result=results.append)
+ asyncio.run(flow_method('wallet_policy_flow.py', 'VerifyWalletPolicyAddressFlow', 'verify')(flow))
+ assert results == [result]
+ assert calls == ['verify' if exists else 'missing']
+
+
+@pytest.mark.parametrize('key_count', [1, 2])
+def test_policy_import_starts_with_wallet_name_prompt(monkeypatch, key_count):
+ class Flow:
+ def __init__(self, initial_state, name):
+ self.state = initial_state
+
+ monkeypatch.setitem(sys.modules, 'flows', SimpleNamespace(Flow=Flow, SaveToMicroSDFlow=object))
+ module = load_module(MODULES / 'flows' / 'wallet_policy_flow.py')
+ policy = SimpleNamespace(keys=[None] * key_count, key_names=[''] * key_count,
+ owned_key_indexes=(0,))
+ flow = module.ImportWalletPolicyFlow(policy)
+ assert flow.state.__name__ == 'choose_name'
+
+
+def test_policy_import_can_go_back_from_review_without_external_signers(monkeypatch):
+ class Series:
+ def __init__(self, *args):
+ pass
+
+ async def run(self):
+ return False
+
+ monkeypatch.setitem(sys.modules, 'flows', SimpleNamespace(SeriesOfPagesFlow=Series))
+ monkeypatch.setitem(sys.modules, 'pages', SimpleNamespace(LongTextPage=object))
+ results = []
+ flow = SimpleNamespace(policy=SimpleNamespace(format_review_pages=lambda: ['Review']),
+ external_key_indexes=(), back=lambda: results.append('back'))
+ asyncio.run(flow_method('wallet_policy_flow.py', 'ImportWalletPolicyFlow', 'show_overview')(flow))
+ assert results == ['back']
+
+
+def test_policy_import_can_go_back_from_first_signer_name(monkeypatch):
+ class TextInputPage:
+ def __init__(self, **kwargs):
+ pass
+
+ async def show(self):
+ return None
+
+ monkeypatch.setitem(sys.modules, 'microns', SimpleNamespace(Back=None, Checkmark=None))
+ monkeypatch.setitem(sys.modules, 'pages', SimpleNamespace(ErrorPage=object, TextInputPage=TextInputPage))
+ monkeypatch.setitem(sys.modules, 'policy_display', SimpleNamespace(
+ format_fingerprint=lambda value: value, suggested_key_name=lambda policy, index: 'Signer'))
+ results = []
+ flow = SimpleNamespace(policy=SimpleNamespace(keys=[SimpleNamespace(fingerprint='12345678')]),
+ external_key_indexes=(0,), key_names=[''], key_name_position=0,
+ back=lambda: results.append('back'))
+ asyncio.run(flow_method('wallet_policy_flow.py', 'ImportWalletPolicyFlow', 'choose_key_name')(flow))
+ assert results == ['back']
+
+
+@pytest.mark.parametrize('name,response', [
+ ('HQ3FM2R2', 'HQ3FM2R2'),
+ ('Supplied name', 'Supplied name'),
+ ('HQ3FM2R2', 'My wallet'),
+ ('HQ3FM2R2', None),
+])
+@pytest.mark.parametrize('external_keys', [(), (1,)])
+def test_policy_name_prompt_preserves_prefill_editing_and_cancel(monkeypatch, name, response, external_keys):
+ class TextInputPage:
+ def __init__(self, **kwargs):
+ assert kwargs['initial_text'] == name
+
+ async def show(self):
+ return response
+
+ monkeypatch.setitem(sys.modules, 'microns', SimpleNamespace(Cancel=None, Checkmark=None))
+ monkeypatch.setitem(sys.modules, 'pages', SimpleNamespace(TextInputPage=TextInputPage))
+ policy = MiniscriptPolicy(name, 'BTC', 'wsh(pk(@0/**))', (KEY_INFO,), (0,))
+ states = []
+ results = []
+ flow = SimpleNamespace(policy=policy, external_key_indexes=external_keys,
+ choose_key_name='signers', show_overview='overview',
+ goto=states.append, set_result=results.append)
+ asyncio.run(flow_method('wallet_policy_flow.py', 'ImportWalletPolicyFlow', 'choose_name')(flow))
+ if response is None:
+ assert results == [False]
+ assert states == []
+ else:
+ assert flow.policy.name == response
+ assert flow.policy.policy_id == policy.policy_id
+ assert states == ['signers' if external_keys else 'overview']
### ports/stm32/boards/Passport/modules/tests/test_wallet_policy_simulator.py
@@ -14,3 +14,12 @@ def test_registered_policy_psbt_matches_in_micropython(exec_file):
def test_taproot_script_path_rejection_and_bip86_signing_in_micropython(exec_file):
script = Path(__file__).parent / 'unit' / 'wallet_policy_taproot_psbt.py'
exec_file(script)
+
+
+def test_registered_policy_qr_backup_renders_and_returns(simulator):
+ tests = Path(__file__).parent
+ descriptor = (tests / 'host/fixtures/liana-multisig-policy.txt').read_text()
+ script = (tests / 'unit/wallet_policy_qr.py').read_text()
+ command, result = simulator.exec('POLICY_DESCRIPTOR = ' + repr(descriptor) + '\n' + script)
+ assert command == 'resp', result.decode()
+ assert result == b'OK'
### ports/stm32/boards/Passport/modules/tests/unit/wallet_policy_qr.py
@@ -0,0 +1,76 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import common
+import gc
+import uasyncio as asyncio
+from display import Display
+from keypad import Keypad
+from keypad_manager import KeypadManager
+from screens import MainScreen
+from ui.ui import UI
+from pages import ChooserPage, YesNoChooserPage, ShowQRPage
+from passport import System
+
+
+class MockSettings:
+ 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
+
+ def set_volatile(self, key, value):
+ pass
+
+ def clear_volatile(self, key):
+ pass
+
+
+common.settings = MockSettings()
+common.system = System()
+common.display = Display()
+common.keypad = Keypad()
+common.keypad_manager = KeypadManager()
+common.ui = UI(MainScreen())
+common.ui.create_single_card(None)
+
+
+async def run():
+ chooser = ChooserPage(card_header={'title': 'Wallet registered'}, options=[
+ {'label': 'Back up wallet policy', 'value': 'backup'}])
+ await chooser.display()
+ chooser.restore_statusbar_and_card_header()
+ backup = YesNoChooserPage(text='How would you like to back up this wallet policy?',
+ yes_text='QR code', no_text='microSD')
+ await backup.display()
+ backup.restore_statusbar_and_card_header()
+ from flows.wallet_policy_flow import ImportWalletPolicyFlow
+ from wallet_policy import descriptor_to_policy_template
+ from wallet_policy import MiniscriptPolicy
+ descriptor = POLICY_DESCRIPTOR
+ template, keys = descriptor_to_policy_template(descriptor.strip(), require_checksum=True)
+ policy = MiniscriptPolicy('QR test', 'TBTC', template, keys, (0,))
+ common.settings.set('wallet_policies', [policy.serialize()])
+ flow = ImportWalletPolicyFlow(policy)
+
+ async def close_qr():
+ await asyncio.sleep_ms(50)
+ page = common.ui.get_active_page()
+ assert isinstance(page, ShowQRPage)
+ from policy_transport import encode_policy_transport
+ gc.collect()
+ assert page.qr_data.unwrap_bytes() == encode_policy_transport(policy).encode('utf-8')
+ page.update()
+ page.set_result(True)
+ asyncio.create_task(close_qr())
+ await flow.backup_via_qr()
+ assert flow.state.__name__ == 'choose_next_action'
+ await ChooserPage(options=[{'label': 'Finish', 'value': 'finish'}]).display()
+ assert not common.showing_qr
+ return_value.write(b'OK')
+
+asyncio.run(run())
### ports/stm32/boards/Passport/modules/wallet_policy.py
@@ -15,7 +15,7 @@
from descriptor import split_checksum
from miniscript import (MAX_KEYS, MAX_TEMPLATE_LENGTH, Parser,
- compile_miniscript, iter_policy_keys, validate)
+ compile_miniscript, iter_policy_keys)
from policy_errors import (PolicyMismatchError, PolicyParseError,
PolicyResourceError, UnsupportedPolicyError, WalletPolicyError)
@@ -251,6 +251,14 @@ def descriptor_to_policy_template(descriptor, require_checksum=True):
return template, tuple(key_values)
+def format_policy_descriptor(template, keys):
+ """Expand a policy template into a full descriptor without its checksum."""
+ # Replace higher indexes first so @1 cannot match the start of @10.
+ for index in range(len(keys) - 1, -1, -1):
+ template = template.replace('@{}'.format(index), keys[index].canonical())
+ return template
+
+
class DerivedPolicyOutput:
__slots__ = ('policy_id', 'branch', 'index', 'witness_script',
'redeem_script', 'script_pubkey', 'address')
@@ -293,7 +301,6 @@ def __init__(self, name, network, template, keys, owned_key_indexes,
if template.startswith('wsh(') and template.endswith(')'):
context = 'wsh'
miniscript = Parser(template[4:-1]).parse()
- validate(miniscript, context)
# Script size and opcode costs do not depend on derived key bytes.
# Reject unsafe policies before registration, not just at derivation.
compile_miniscript(miniscript, lambda *_: b'\x02' + bytes(32), 0, 0,
@@ -425,13 +432,19 @@ def deserialize(cls, record):
return policy
def calculate_id(self):
- payload = b'Passport Wallet Policy\x00' + bytes([POLICY_FORMAT_VERSION])
- payload += _encode_field(self.network)
- payload += _encode_field(self.template)
- payload += _compact_size(len(self.keys))
+ try:
+ from trezorcrypto import sha256
+ except ImportError: # pragma: no cover - CPython host tests
+ from hashlib import sha256
+
+ digest = sha256(b'Passport Wallet Policy\x00')
+ digest.update(bytes([POLICY_FORMAT_VERSION]))
+ digest.update(_encode_field(self.network))
+ digest.update(_encode_field(self.template))
+ digest.update(_compact_size(len(self.keys)))
for key in self.keys:
- payload += _encode_field(key.canonical())
- return hexlify(_sha256(payload)).decode('ascii')
+ digest.update(_encode_field(key.canonical()))
+ return hexlify(digest.digest()).decode('ascii')
def serialize(self):
record = {
@@ -473,15 +486,16 @@ def format_details(self):
lines.append('Key {} - {}\nFingerprint {}\nPath {}\n{}'.format(
index + 1, role, key.fingerprint.upper(),
self._format_origin_path(key.path), key.xpub))
+ from miniscript import policy_timelocks
+ for kind, value in policy_timelocks(self.miniscript):
+ if kind == 'older' and value & (1 << 22):
+ units = value & 0xffff
+ lines.append('older({}): {} x 512 = {} seconds'.format(value, units, units * 512))
lines.append('Internal policy ID\n' + self.policy_id)
return '\n\n'.join(lines)
def full_descriptor(self, with_checksum=True):
- descriptor = self.template
- # Replace higher indexes first so @1 cannot match the start of @10.
- for index in range(len(self.keys) - 1, -1, -1):
- descriptor = descriptor.replace('@{}'.format(index),
- self.keys[index].canonical())
+ descriptor = format_policy_descriptor(self.template, self.keys)
if with_checksum:
from descriptor import append_checksum
return append_checksum(descriptor)Why this scored 21/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.