SFT-974: improved miniscript UI, working on OOM issues
What changed, and why it matters
This commit is a routine feature and stability patch for the Passport hardware wallet's miniscript wallet-policy support. It improves on-screen descriptions of wallet policies, adds explicit memory cleanup (garbage collection) during policy import/export to avoid out-of-memory crashes, and replaces a 'Verify Liana Address' menu item with a generic 'Verify Address' flow. There is no direct evidence in the commit of a security vulnerability being fixed; the changes are framed by the vendor as user-interface and memory-management improvements.
No immediate security action required. Treat as a normal firmware update. If deploying, verify that the new VerifyWalletPolicyAddressFlow behaves equivalently to the replaced Liana-specific flow and that memory cleanup does not introduce use-after-free or stale-reference issues in MicroPython.
Security signals we found
Memory pressure mitigation via explicit garbage collection during policy operations
New verify-address flow for registered wallet policies
UI clarity improvements for timelock and signer-role descriptions
Evidence from the diff
The diff touches wallet-policy UI flows, policy display/transport, and tests. Key changes: (1) insertion of gc.collect() calls around policy decode, review, confirmation, QR export, and file import to reduce peak RAM usage; (2) deletion of intermediate objects (data, result, policy) before launching import flows; (3) UI text refinements in timelock descriptions and policy role summaries; (4) addition of VerifyWalletPolicyAddressFlow and replacement of VerifyWalletPolicyRequestFlow in the wallet-policy menu; (5) new simulator/unit tests for QR backup rendering. No cryptographic checks, parsing bounds, or authorization logic are altered in a security-relevant way based on the diff alone.
Changed components
ports/stm32/boards/Passport/modules/flows/wallet_policy_flow.pyports/stm32/boards/Passport/modules/policy_transport.pyports/stm32/boards/Passport/modules/policy_display.pyports/stm32/boards/Passport/modules/menus.pyports/stm32/boards/Passport/modules/wallet_policy.pyInspect captured patch +255 / −32
### 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):
@@ -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/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
@@ -98,6 +100,7 @@ def decode_policy_transport(data, chain, master_xfp, derive_node,
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,20 @@ 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)
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_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,45 @@ 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']
### 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
@@ -473,6 +473,11 @@ 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)
Why this scored 20/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.