Merge pull request #677 from Foundation-Devices/SFT-974-miniscript
What changed, and why it matters
This is a large feature commit that adds Miniscript wallet policy support to the Foundation Passport firmware. It introduces new modules for parsing and validating Miniscript policies, registering wallet policies via QR/microSD, deriving addresses, and signing PSBTs that use these policies. The changes also add UI flows, tests, and CI coverage. There is no indication in the commit message or diff that this is a security fix; it reads as a new feature implementation. No vulnerability is evident from the supplied materials.
No security action is indicated by the supplied commit. Treat this as a normal feature review; verify the new Miniscript parser and policy handling through the added test suite and code review if assessing the feature's security posture.
Security signals we found
No strong security signals were identified.
Evidence from the diff
Commit 1a10714f857f3a66fdfd87daf140b136f6f638c3 merges PR #677 (SFT-974: miniscript). It adds ~7,132 lines across 58 files, introducing: a Miniscript parser/analyzer/compiler (miniscript.py), wallet policy registry and transport (wallet_policy.py, policy_transport.py), policy display formatting (policy_display.py), error classes (policy_errors.py), an adapter for legacy multisig records (policy_multisig.py), PSBT signing integration (psbt.py, sign_psbt_common_flow.py, sign_psbt_task.py), address verification/explorer integration, menu entries, host/unit tests, and CI workflow additions. The code includes resource limits, checksum verification, and conservative policy validation. The commit does not describe any security bug or CVE, and no independent security references are supplied.
Changed components
Foundation Passport firmwareMiniscript policy parser and compilerWallet policy registration/import flowsPSBT signing flowAddress verification/explorer flowsLegacy multisig wallet adapterCI host testsInspect captured patch +7132 / −175
### .github/workflows/lint.yaml
@@ -79,6 +79,15 @@ jobs:
- run: sudo apt-get install -y pycodestyle
- run: pycodestyle --statistics ports/stm32/boards/Passport
+ wallet-policy-host-tests:
+ name: Wallet policy host tests pass?
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - run: python3 -m pip install pytest embit==0.8.0
+ - run: |
+ python3 -m pytest -q ports/stm32/boards/Passport/modules/tests/host
+
is-foundation-header-up-to-date:
name: Is foundation.h header file up to date?
needs: [rust-code-compiles]
### flake.nix
@@ -66,6 +66,17 @@
config.allowUnfree = true;
};
customPackages = self.packages.${system};
+ embit = pkgs.python3Packages.buildPythonPackage rec {
+ pname = "embit";
+ version = "0.8.0";
+ pyproject = true;
+ src = pkgs.fetchPypi {
+ inherit pname version;
+ hash = "sha256-i/SxAHPGdAA3DOUj+xbwNf51n2/dmHxXm9zCaNde13A=";
+ };
+ build-system = with pkgs.python3Packages; [ setuptools wheel ];
+ pythonImportsCheck = [ "embit.descriptor.arguments" ];
+ };
runtimeLibPath = with pkgs; pkgs.lib.makeLibraryPath [
stdenv.cc.cc.lib
glib
@@ -141,6 +152,7 @@
xterm
]
++ [
+ embit
customPackages.add-secrets
customPackages.cosign
customPackages.mpy-cross
### ports/stm32/boards/Passport/manifest.py
@@ -26,11 +26,19 @@
'keys.py',
'main.py',
'menus.py',
+ 'miniscript.py',
'multisig_wallet.py',
'opcodes.py',
'pincodes.py',
+ 'policy_display.py',
+ 'policy_errors.py',
+ 'policy_multisig.py',
+ 'policy_transport.py',
+ 'spend_plan.py',
+ 'wallet_policy.py',
'predictive_utils.py',
'psbt.py',
+ 'psbt_display.py',
'public_constants.py',
'schema_evolution.py',
'se_commands.py',
@@ -163,7 +171,8 @@
'flows/view_derived_key_details_flow.py',
'flows/view_dev_pubkey_flow.py',
'flows/view_multisig_details_flow.py',
- 'flows/view_seed_words_flow.py'))
+ 'flows/view_seed_words_flow.py',
+ 'flows/wallet_policy_flow.py'))
# Microns
freeze('$(MPY_DIR)/ports/stm32/boards/Passport/modules',
@@ -290,7 +299,8 @@
'tasks/validate_electrum_message_task.py',
'tasks/validate_psbt_task.py',
'tasks/verify_backup_task.py',
- 'tasks/verify_firmware_signature_task.py'))
+ 'tasks/verify_firmware_signature_task.py',
+ 'tasks/wallet_policy_task.py'))
# UI
freeze('$(MPY_DIR)/ports/stm32/boards/Passport/modules',
@@ -355,6 +365,7 @@
'wallets/fullynoded.py',
'wallets/generic_json_wallet.py',
'wallets/gordian.py',
+ 'wallets/liana.py',
'wallets/lily.py',
'wallets/multisig_import.py',
'wallets/multisig_json.py',
### ports/stm32/boards/Passport/modules/descriptor.py
@@ -66,4 +66,28 @@ def descriptor_checksum(desc):
def append_checksum(desc):
return desc + "#" + descriptor_checksum(desc)
+
+def split_checksum(desc, require=True):
+ """Split and verify a descriptor checksum.
+
+ The returned descriptor never includes the ``#checksum`` suffix. A
+ checksum mismatch is always an error; callers may opt into accepting a
+ missing checksum only for already-integrity-protected transports.
+ """
+ if not isinstance(desc, str):
+ raise ValueError('Descriptor must be text')
+ if desc.count('#') > 1:
+ raise ValueError('Descriptor contains multiple checksums')
+ if '#' not in desc:
+ if require:
+ raise ValueError('Descriptor checksum is required')
+ return desc, None
+ body, checksum = desc.rsplit('#', 1)
+ if len(checksum) != 8:
+ raise ValueError('Descriptor checksum must be 8 characters')
+ expected = descriptor_checksum(body)
+ if checksum != expected:
+ raise ValueError('Descriptor checksum does not match')
+ return body, checksum
+
# EOF
### ports/stm32/boards/Passport/modules/export.py
@@ -34,6 +34,19 @@ def ms_has_master_xfp(xpubs):
return False
+def policy_has_master_xfp(record):
+ from common import settings
+ from wallet_policy import MiniscriptPolicy
+ try:
+ policy = MiniscriptPolicy.deserialize(record)
+ owned = policy.keys[policy.owned_key_indexes[0]]
+ return owned.fingerprint == xfp2str(settings.get('xfp', None)).lower()
+ except BaseException:
+ # A malformed settings record must never be copied into a backup as if
+ # it were an approved wallet policy.
+ return False
+
+
def render_backup_contents():
# simple text format:
# key = value
@@ -113,6 +126,11 @@ def ADD(key, val):
# "Passphrase wallets? I don't have any passphrase wallets!"
# print('ms={}'.format(v))
v = list(filter(lambda ms: ms_has_master_xfp(ms[2]), v))
+ elif k == 'wallet_policies':
+ # As with legacy multisig, exclude policies belonging to a
+ # passphrase wallet from the base wallet's plausible-deniability
+ # backup.
+ v = list(filter(policy_has_master_xfp, v))
ADD('setting.' + k, v)
### ports/stm32/boards/Passport/modules/flows/address_explorer_flow.py
@@ -28,6 +28,7 @@ def __init__(self):
self.acct_num = self.account.get('acct_num')
self.sig_type = None
self.multisig_wallet = None
+ self.wallet_policy = None
self.is_multisig = False
self.addr_type = None
self.deriv_path = None
@@ -38,28 +39,38 @@ async def choose_sig_type(self):
from pages import SinglesigMultisigChooserPage
from multisig_wallet import MultisigWallet
from common import settings
+ from utils import xfp2str
+ from wallet_policy import WalletPolicyRegistry
import microns
xfp = settings.get('xfp')
multisigs = MultisigWallet.get_by_xfp(xfp)
+ policies = list(WalletPolicyRegistry(settings).iter_policies(xfp2str(xfp).lower()))
- if len(multisigs) == 0:
+ if len(multisigs) == 0 and len(policies) == 0:
self.sig_type = 'single-sig'
self.goto(self.choose_addr_type, save_curr=False) # Skipping this state
return
result = await SinglesigMultisigChooserPage(
initial_value=self.sig_type,
multisigs=multisigs,
+ policies=policies,
left_micron=microns.Back).show()
if result is None:
self.set_result(False)
return
- (self.sig_type, self.multisig_wallet) = result
+ (self.sig_type, selected_wallet) = result
+ if self.sig_type == 'policy':
+ self.wallet_policy = selected_wallet
+ self.multisig_wallet = None
+ else:
+ self.multisig_wallet = selected_wallet
+ self.wallet_policy = None
self.is_multisig = self.sig_type == 'multisig'
- if not self.is_multisig:
+ if self.sig_type == 'single-sig':
self.goto(self.choose_addr_type)
return
@@ -130,11 +141,14 @@ async def prepare(self):
self.xfp = settings.get('xfp')
self.chain = chains.current_chain()
- self.index = get_next_addr(self.acct_num,
- self.addr_type,
- self.xfp,
- self.chain.b44_cointype,
- self.is_change)
+ if self.wallet_policy:
+ self.index = 0
+ else:
+ self.index = get_next_addr(self.acct_num,
+ self.addr_type,
+ self.xfp,
+ self.chain.b44_cointype,
+ self.is_change)
self.goto(self.explore)
@@ -145,14 +159,18 @@ async def explore(self):
from public_constants import MARGIN_FOR_ADDRESSES
try:
- self.address = get_single_address(self.xfp,
- self.chain,
- self.index,
- self.is_multisig,
- self.multisig_wallet,
- self.is_change,
- self.deriv_path,
- self.addr_type)
+ if self.wallet_policy:
+ self.address = self.wallet_policy.derive(
+ 1 if self.is_change else 0, self.index, self.chain).address
+ else:
+ self.address = get_single_address(self.xfp,
+ self.chain,
+ self.index,
+ self.is_multisig,
+ self.multisig_wallet,
+ self.is_change,
+ self.deriv_path,
+ self.addr_type)
except Exception as e:
# TODO: make error page
self.set_result(False)
### ports/stm32/boards/Passport/modules/flows/connect_wallet_flow.py
@@ -565,7 +565,9 @@ async def show_rx_address(self):
self.goto(self.complete)
async def complete(self):
- await SuccessPage(text='Connection Complete').show()
+ await SuccessPage(
+ text=self.get_custom_text(
+ 'connection_complete', 'Connection Complete')).show()
self.set_result(True)
async def show_error(self):
### ports/stm32/boards/Passport/modules/flows/restore_backup_flow.py
@@ -18,7 +18,7 @@
YesNoChooserPage
)
from utils import spinner_task, get_backup_code_as_password, bind, show_card_missing
-from tasks import restore_backup_task, get_backup_code_task
+from tasks import get_backup_code_task
from errors import Error
import common
from files import CardMissingError
@@ -126,6 +126,7 @@ async def enter_backup_code(self):
self.back()
async def do_restore(self):
+ from tasks.restore_backup_task import restore_backup_task
from utils import start_task
from flows import AutoBackupFlow, BackupFlow
from pages import InfoPage
### ports/stm32/boards/Passport/modules/flows/sign_psbt_common_flow.py
@@ -14,7 +14,7 @@
import microns
from pages.chooser_page import ChooserPage
from styles.colors import HIGHLIGHT_TEXT_HEX, BLACK_HEX
-from tasks import sign_psbt_task, validate_psbt_task
+from tasks import validate_psbt_task
import gc
from utils import escape_text, spinner_task, recolor, stylize_address
@@ -29,17 +29,26 @@ def __init__(self, psbt_len):
self.header = 'Transaction Info'
async def validate_psbt(self):
- from pages import ErrorPage
-
(self.psbt, error_msg, error) = await spinner_task('Validating transaction', validate_psbt_task,
args=[self.psbt_len])
# print('psbt={} error_msg={} error={}'.format(self.psbt, error_msg, error))
if error is not None:
- await ErrorPage(error_msg).show()
+ await self.show_psbt_error(error_msg)
self.set_result(None)
else:
+ if self.psbt.active_policy:
+ self.header = 'Policy transaction'
self.goto(self.check_multisig_import)
+ async def show_psbt_error(self, error_msg):
+ from pages import ErrorPage
+ from psbt_display import format_psbt_error
+ friendly, technical = format_psbt_error(error_msg)
+ text = friendly
+ if technical:
+ text = [friendly, 'Technical details\n\n{}'.format(technical)]
+ await ErrorPage(text=text).show()
+
async def check_multisig_import(self):
from flows import ImportMultisigWalletFlow
from pages import ErrorPage
@@ -157,17 +166,67 @@ async def show_warnings(self):
if not result:
self.back()
else:
- self.goto(self.sign_transaction)
+ self.goto(self.show_policy_authorization)
else:
+ self.goto(self.show_policy_authorization)
+
+ async def show_policy_authorization(self):
+ policy = self.psbt.active_policy
+ if policy is None:
self.goto(self.sign_transaction)
+ return
+
+ from policy_display import compatible_path_indexes
+ compatible_sets = []
+ for input_index, txin in self.psbt.input_iter():
+ plan = self.psbt.inputs[input_index].policy_spend_plan
+ if plan and plan.policy_id == policy.policy_id:
+ compatible_sets.append(compatible_path_indexes(
+ policy, self.psbt.txn_version, self.psbt.lock_time,
+ txin.nSequence))
+ compatible = None
+ warning = None
+ if not compatible_sets:
+ warning = ('Spending paths could not be checked for this transaction. '
+ 'The following pages describe the full wallet policy.')
+ elif any(not paths for paths in compatible_sets):
+ compatible = ()
+ elif all(paths == compatible_sets[0] for paths in compatible_sets):
+ compatible = compatible_sets[0]
+ else:
+ warning = 'Inputs allow different spending paths. The following pages describe the full wallet policy.'
+
+ from flows import SeriesOfPagesFlow
+ from pages import LongTextPage
+ if warning:
+ texts = (warning,) + policy.format_review_pages()
+ else:
+ texts = policy.format_signing_pages(compatible)
+ page_args = [{
+ 'card_header': {'title': 'Policy transaction'},
+ 'text': text,
+ 'centered': True,
+ } for text in texts]
+ result = await SeriesOfPagesFlow(LongTextPage, page_args).run()
+ if result:
+ self.goto(self.sign_transaction)
+ else:
+ self.back()
async def sign_transaction(self):
+ from tasks.sign_psbt_task import sign_psbt_task
from utils import spinner_task
from pages import ErrorPage, QuestionPage
gc.collect()
- result = await QuestionPage(text='Sign transaction?', right_micron=microns.Sign).show() # Change to Sign icon
+ if self.psbt.active_policy:
+ from utils import escape_text
+ question = 'Sign with {}?'.format(
+ escape_text(self.psbt.active_policy.name))
+ else:
+ question = 'Sign transaction?'
+ result = await QuestionPage(text=question, right_micron=microns.Sign).show()
if not result:
options = [{'label': 'Cancel', 'value': True},
{'label': 'Review Details', 'value': False}]
@@ -182,7 +241,7 @@ async def sign_transaction(self):
sign_psbt_task, args=[self.psbt])
gc.collect()
if error is not None:
- await ErrorPage(error_msg).show()
+ await self.show_psbt_error(error_msg)
self.set_result(None)
return
### ports/stm32/boards/Passport/modules/flows/sign_psbt_microsd_flow.py
@@ -160,15 +160,13 @@ def write_final_fn(self, filename):
async def show_success(self):
import microns
from lvgl import LARGE_ICON_SUCCESS
+ from psbt_display import format_signed_psbt_message
from styles.colors import DEFAULT_LARGE_ICON_COLOR
- msg = "Updated PSBT is:\n\n%s" % self.out_fn
- if self.out2_fn:
- msg += '\n\nFinalized transaction (ready for broadcast):\n\n%s' % self.out2_fn
-
- if self.txid:
- msg += '\n\nFinal TXID:\n' + self.txid
+ msg = format_signed_psbt_message(self.out_fn, self.out2_fn,
+ self.txid if self.out2_fn else None)
await LongTextPage(text=msg, centered=True, left_micron=None,
+ card_header={'title': 'Signature added'},
right_micron=microns.Checkmark, icon=LARGE_ICON_SUCCESS,
icon_color=DEFAULT_LARGE_ICON_COLOR,).show()
self.set_result(self.psbt)
### ports/stm32/boards/Passport/modules/flows/sign_psbt_qr_flow.py
@@ -239,10 +239,12 @@ async def show_success(self):
from lvgl import LARGE_ICON_SUCCESS
from styles.colors import DEFAULT_LARGE_ICON_COLOR
from pages import LongTextPage
+ from psbt_display import format_signed_psbt_message
- msg = "Updated PSBT is:\n\n%s" % self.filename
+ msg = format_signed_psbt_message(self.filename)
result = await LongTextPage(text=msg,
centered=True,
+ card_header={'title': 'Signature added'},
left_micron=microns.ScanQR,
right_micron=microns.Checkmark,
icon=LARGE_ICON_SUCCESS,
### ports/stm32/boards/Passport/modules/flows/verify_address_flow.py
@@ -21,17 +21,25 @@
class VerifyAddressFlow(Flow):
- def __init__(self, sig_type=None, multisig_wallet=None):
+ def __init__(self, sig_type=None, multisig_wallet=None, wallet_policy=None):
if sig_type is not None:
initial_state = self.scan_address
else:
initial_state = self.choose_sig_type
super().__init__(initial_state=initial_state, name='VerifyAddressFlow')
self.account = ui.get_active_account()
- self.acct_num = self.account.get('acct_num')
+ # Wallet-policy addresses are derived from the registered descriptor,
+ # not from Passport's active singlesig account. Policy registration
+ # can therefore launch this flow while no account card is active.
+ if self.account is None and sig_type == 'policy':
+ self.acct_num = 0
+ else:
+ self.acct_num = self.account.get('acct_num')
self.sig_type = sig_type
- self.multisig_wallet = multisig_wallet
+ self.multisig_wallet = multisig_wallet if sig_type != 'policy' else None
+ self.wallet_policy = (wallet_policy if wallet_policy is not None else
+ multisig_wallet if sig_type == 'policy' else None)
self.is_multisig = False
self.found_addr_idx = None
self.found_is_change = False
@@ -49,22 +57,32 @@ async def choose_sig_type(self):
from pages import SinglesigMultisigChooserPage
from multisig_wallet import MultisigWallet
from common import settings
+ from utils import xfp2str
+ from wallet_policy import WalletPolicyRegistry
xfp = settings.get('xfp')
multisigs = MultisigWallet.get_by_xfp(xfp)
+ policies = list(WalletPolicyRegistry(settings).iter_policies(xfp2str(xfp).lower()))
- if len(multisigs) == 0:
+ if len(multisigs) == 0 and len(policies) == 0:
self.sig_type = 'single-sig'
self.goto(self.scan_address, save_curr=False) # Don't save this since we're skipping this state
else:
result = await SinglesigMultisigChooserPage(
- initial_value=self.sig_type, multisigs=multisigs).show()
+ initial_value=self.sig_type, multisigs=multisigs,
+ policies=policies).show()
if result is None:
if not self.back():
self.set_result(False)
return
- (self.sig_type, self.multisig_wallet) = result
+ (self.sig_type, selected_wallet) = result
+ if self.sig_type == 'policy':
+ self.wallet_policy = selected_wallet
+ self.multisig_wallet = None
+ else:
+ self.multisig_wallet = selected_wallet
+ self.wallet_policy = None
# print('sig_type={}'.format(self.sig_type))
# print('multisig_wallet={}'.format(self.multisig_wallet))
self.goto(self.scan_address)
@@ -98,24 +116,28 @@ async def scan_address(self):
return
# Get the address type from the address
- self.is_multisig = self.sig_type == 'multisig'
+ self.is_multisig = self.sig_type in ('multisig', 'policy')
# print('address={} acct_num={} is_multisig={}'.format(address, self.acct_num, is_multisig))
self.addr_type = get_addr_type_from_address(self.address, self.is_multisig)
- self.deriv_path = get_deriv_path_from_addr_type_and_acct(self.addr_type, self.acct_num, self.is_multisig)
+ self.deriv_path = None if self.wallet_policy else get_deriv_path_from_addr_type_and_acct(
+ self.addr_type, self.acct_num, self.is_multisig)
# Setup initial ranges
xfp = settings.get('xfp')
- a = [get_next_addr(self.acct_num,
- self.addr_type,
- xfp,
- chain.b44_cointype,
- False),
- get_next_addr(self.acct_num,
- self.addr_type,
- xfp,
- chain.b44_cointype,
- True)]
+ if self.wallet_policy:
+ a = [0, 0]
+ else:
+ a = [get_next_addr(self.acct_num,
+ self.addr_type,
+ xfp,
+ chain.b44_cointype,
+ False),
+ get_next_addr(self.acct_num,
+ self.addr_type,
+ xfp,
+ chain.b44_cointype,
+ True)]
self.low_range = [(a[_RECEIVE_ADDR], a[_RECEIVE_ADDR]), (a[_CHANGE_ADDR], a[_CHANGE_ADDR])]
self.high_range = [(a[_RECEIVE_ADDR], a[_RECEIVE_ADDR]), (a[_CHANGE_ADDR], a[_CHANGE_ADDR])]
@@ -127,7 +149,7 @@ def finalize(self, addr_idx, is_change):
self.goto(self.found)
async def search_for_address(self):
- from tasks import search_for_address_task
+ from tasks.search_for_address_task import search_for_address_task
from utils import get_prev_address_range, get_next_address_range, spinner_task
# Try next batch of addresses
@@ -151,7 +173,8 @@ async def search_for_address(self):
self.multisig_wallet,
is_change,
1,
- True])
+ True,
+ self.wallet_policy])
if addr_idx >= 0:
self.finalize(addr_idx, is_change)
@@ -172,7 +195,8 @@ async def search_for_address(self):
self.multisig_wallet,
is_change,
self.low_size[is_change],
- True])
+ True,
+ self.wallet_policy])
# Exit if already found
if addr_idx >= 0:
@@ -191,7 +215,8 @@ async def search_for_address(self):
self.multisig_wallet,
is_change,
self.high_size[is_change],
- True])
+ True,
+ self.wallet_policy])
if addr_idx >= 0:
break
@@ -235,12 +260,13 @@ async def found(self):
from views import VerifiedIcon
# Remember where to start from next time
- save_next_addr(self.acct_num,
- self.addr_type,
- self.found_addr_idx,
- settings.get('xfp'),
- chains.current_chain().b44_cointype,
- self.found_is_change)
+ if not self.wallet_policy:
+ save_next_addr(self.acct_num,
+ self.addr_type,
+ self.found_addr_idx,
+ settings.get('xfp'),
+ chains.current_chain().b44_cointype,
+ self.found_is_change)
address = stylize_address(self.address)
msg = '''{}
### ports/stm32/boards/Passport/modules/flows/wallet_policy_flow.py
@@ -0,0 +1,659 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+from flows import Flow, SaveToMicroSDFlow
+
+
+def _decode_policy(data):
+ import chains
+ import stash
+ from policy_transport import decode_policy_transport
+
+ chain = chains.current_chain()
+ with stash.SensitiveValues() as sv:
+ def derive_node(path):
+ node = sv.node.clone()
+ for element in path:
+ node.derive(element)
+ return node
+
+ return decode_policy_transport(data, chain, sv.get_xfp(), derive_node)
+
+
+def _verify_current_seed(policy, chain):
+ """Re-prove the complete registered xpub before an address response."""
+ import stash
+ with stash.SensitiveValues() as sv:
+ def derive_node(path):
+ node = sv.node.clone()
+ for element in path:
+ node.derive(element)
+ return node
+
+ policy.verify_owned_key(chain, derive_node)
+
+
+class ImportWalletPolicyFlow(Flow):
+ def __init__(self, policy):
+ self.policy = policy
+ self.error = None
+ self.key_names = list(policy.key_names)
+ self.external_key_indexes = tuple(
+ index for index in range(len(policy.keys))
+ if index not in policy.owned_key_indexes)
+ self.key_name_position = 0
+ super().__init__(initial_state=self.choose_name, name='ImportWalletPolicyFlow')
+
+ async def choose_name(self):
+ import microns
+ from pages import TextInputPage
+ from wallet_policy import MAX_POLICY_NAME_LENGTH
+
+ result = await TextInputPage(
+ title='Wallet Policy Name', initial_text=self.policy.name,
+ max_length=MAX_POLICY_NAME_LENGTH, left_micron=microns.Cancel,
+ right_micron=microns.Checkmark).show()
+ if result is None:
+ self.set_result(False)
+ return
+ try:
+ self.policy = self.policy.rename(result)
+ except BaseException as exc:
+ self.error = str(exc)
+ self.goto(self.show_error)
+ return
+ self.key_name_position = 0
+ self.goto(self.choose_key_name)
+
+ async def choose_key_name(self):
+ import microns
+ from pages import ErrorPage, TextInputPage
+ from policy_display import format_fingerprint, suggested_key_name
+ from wallet_policy import MAX_KEY_NAME_LENGTH
+
+ if self.key_name_position >= len(self.external_key_indexes):
+ try:
+ self.policy = self.policy.name_keys(self.key_names)
+ except BaseException as exc:
+ self.error = str(exc)
+ self.goto(self.show_error)
+ return
+ self.goto(self.show_overview)
+ return
+
+ key_index = self.external_key_indexes[self.key_name_position]
+ key = self.policy.keys[key_index]
+ initial = self.key_names[key_index] or suggested_key_name(self.policy, key_index)
+ result = await TextInputPage(
+ card_header={'title': 'Name Signer'},
+ title='Fingerprint\n{}'.format(format_fingerprint(key.fingerprint)),
+ initial_text=initial, max_length=MAX_KEY_NAME_LENGTH,
+ left_micron=microns.Back, right_micron=microns.Checkmark).show()
+ if result is None:
+ if self.key_name_position:
+ self.key_name_position -= 1
+ else:
+ self.back()
+ return
+ if not result:
+ await ErrorPage('Enter a name for this signer.').show()
+ return
+ self.key_names[key_index] = result
+ self.key_name_position += 1
+
+ async def show_overview(self):
+ from flows import SeriesOfPagesFlow
+ from pages import LongTextPage
+ page_args = [{
+ 'card_header': {'title': 'Wallet policy'},
+ 'text': text,
+ 'centered': not text.startswith('Path '),
+ } for text in self.policy.format_review_pages()]
+ result = await SeriesOfPagesFlow(LongTextPage, page_args).run()
+ if result:
+ self.goto(self.choose_technical_details)
+ else:
+ if self.external_key_indexes:
+ self.key_name_position = len(self.external_key_indexes) - 1
+ self.back()
+
+ async def choose_technical_details(self):
+ import microns
+ from pages import YesNoChooserPage
+ result = await YesNoChooserPage(
+ text='Review the raw descriptor and extended public keys?',
+ yes_text='Technical details', no_text='Continue',
+ initial_value=False, left_micron=microns.Back).show()
+ if result is None:
+ self.back()
+ elif result:
+ self.goto(self.show_details)
+ else:
+ self.goto(self.confirm_import)
+
+ async def show_details(self):
+ from pages import LongTextPage
+ result = await LongTextPage(
+ card_header={'title': 'Technical details'},
+ text=self.policy.format_details(), centered=False).show()
+ if result:
+ self.goto(self.confirm_import)
+ else:
+ self.back()
+
+ async def confirm_import(self):
+ from pages import LongQuestionPage
+ from styles.colors import HIGHLIGHT_TEXT_HEX
+ from utils import escape_text, recolor
+ 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()))
+ result = await LongQuestionPage(text=text).show()
+ if result:
+ self.goto(self.save_policy)
+ else:
+ self.set_result(False)
+
+ async def save_policy(self):
+ from common import settings
+ from errors import Error
+ from pages import ErrorPage, SuccessPage
+ from tasks.wallet_policy_task import save_wallet_policy_task
+ from utils import spinner_task
+ from wallet_policy import WalletPolicyRegistry
+
+ if WalletPolicyRegistry(settings).get(self.policy.policy_id):
+ await ErrorPage('This wallet policy is already registered.').show()
+ self.set_result(False)
+ return
+ error, = await spinner_task(
+ 'Saving wallet policy', save_wallet_policy_task, args=[self.policy])
+ if error is Error.USER_SETTINGS_FULL:
+ await ErrorPage('Not enough settings space to save this wallet policy.').show()
+ self.set_result(False)
+ return
+ if error is not None:
+ await ErrorPage('Unable to save wallet policy.').show()
+ self.set_result(False)
+ return
+ from flows import AutoBackupFlow
+ await AutoBackupFlow().run()
+ await SuccessPage('Wallet policy registered').show()
+ self.goto(self.choose_next_action)
+
+ async def choose_next_action(self):
+ import microns
+ from pages import ChooserPage
+ options = [
+ {'label': 'Verify an address', 'value': 'verify'},
+ {'label': 'Back up wallet policy', 'value': 'backup'},
+ ]
+ if self.external_key_indexes:
+ options.append({'label': 'Label signer keys', 'value': 'name_keys'})
+ options.extend([
+ {'label': 'View technical details', 'value': 'details'},
+ {'label': 'Finish', 'value': 'finish'},
+ ])
+ result = await ChooserPage(
+ card_header={'title': 'Wallet registered'},
+ text='Recommended next steps', options=options,
+ initial_value='verify', scroll_fix=True,
+ left_micron=microns.Back).show()
+ if result is None or result == 'finish':
+ self.set_result(True)
+ elif result == 'verify':
+ self.goto(self.verify_first_address)
+ elif result == 'backup':
+ self.goto(self.choose_backup_method)
+ elif result == 'name_keys':
+ self.goto(self.label_signer_keys)
+ else:
+ self.goto(self.view_registered_details)
+
+ async def verify_first_address(self):
+ from flows import VerifyAddressFlow
+ result = await VerifyAddressFlow(
+ sig_type='policy', wallet_policy=self.policy).run()
+ if result:
+ # Registration is complete and the receive address is verified.
+ # Exit the import flow so the parent Wallet Policies menu refreshes.
+ self.set_result(True)
+ else:
+ self.goto(self.choose_next_action, save_curr=False)
+
+ async def choose_backup_method(self):
+ import microns
+ from pages import YesNoChooserPage
+ result = await YesNoChooserPage(
+ text='How would you like to back up this wallet policy?',
+ yes_text='QR code', no_text='microSD',
+ initial_value=True, left_micron=microns.Back).show()
+ if result is None:
+ self.goto(self.choose_next_action, save_curr=False)
+ elif result:
+ self.goto(self.backup_via_qr)
+ else:
+ self.goto(self.backup_via_microsd)
+
+ async def backup_via_qr(self):
+ await ExportWalletPolicyQRFlow(context=self.policy.policy_id).run()
+ self.goto(self.choose_next_action, save_curr=False)
+
+ async def backup_via_microsd(self):
+ await ExportWalletPolicyMicroSDFlow(context=self.policy.policy_id).run()
+ self.goto(self.choose_next_action, save_curr=False)
+
+ async def label_signer_keys(self):
+ result = await NameWalletPolicyKeysFlow(context=self.policy.policy_id).run()
+ if result:
+ from common import settings
+ from wallet_policy import WalletPolicyRegistry
+ self.policy = WalletPolicyRegistry(settings).get(self.policy.policy_id)
+ self.goto(self.choose_next_action, save_curr=False)
+
+ async def view_registered_details(self):
+ import microns
+ from pages import LongTextPage
+ await LongTextPage(
+ card_header={'title': 'Technical details'},
+ text=self.policy.format_details(), centered=False,
+ right_micron=microns.Checkmark).show()
+ self.goto(self.choose_next_action, save_curr=False)
+
+ async def show_error(self):
+ from pages import ErrorPage
+ await ErrorPage(self.error).show()
+ self.set_result(False)
+
+
+class ImportWalletPolicyFromQRFlow(Flow):
+ def __init__(self):
+ self.error = None
+ super().__init__(initial_state=self.scan, name='ImportWalletPolicyFromQRFlow')
+
+ async def scan(self):
+ from data_codecs.qr_type import QRType
+ from flows import ScanQRFlow
+ from foundation import ur
+ from errors import Error
+
+ result = await ScanQRFlow(
+ qr_types=[QRType.QR, QRType.UR2], ur_types=[ur.Value.BYTES],
+ data_description='a wallet policy').run()
+ if result is None:
+ self.set_result(False)
+ return
+ if result in (Error.QR_TOO_LARGE, Error.PSBT_OVERSIZED):
+ self.error = 'Wallet policy QR code is too large. Import it from microSD instead.'
+ self.goto(self.show_error)
+ return
+ try:
+ data = result.unwrap_bytes() if hasattr(result, 'unwrap_bytes') else result
+ policy = _decode_policy(data)
+ except BaseException as exc:
+ self.error = str(exc) or 'Wallet Policy Import Error'
+ self.goto(self.show_error)
+ return
+ result = await ImportWalletPolicyFlow(policy).run()
+ self.set_result(result)
+
+ async def show_error(self):
+ from pages import ErrorPage
+ await ErrorPage(self.error).show()
+ self.error = None
+ self.reset(self.scan)
+
+
+class ImportWalletPolicyFromMicroSDFlow(Flow):
+ def __init__(self):
+ self.error = None
+ super().__init__(initial_state=self.choose_file,
+ name='ImportWalletPolicyFromMicroSDFlow')
+
+ async def choose_file(self):
+ from flows import FilePickerFlow
+ from tasks import read_file_task
+ from policy_transport import bounded_transport_read
+ from utils import spinner_task
+
+ result = await FilePickerFlow(show_folders=True).run()
+ if result is None:
+ self.set_result(False)
+ return
+ _, full_path, is_folder = result
+ if is_folder:
+ return
+ data, error = await spinner_task(
+ 'Reading policy', read_file_task, args=[full_path, True, bounded_transport_read])
+ if error is not None:
+ self.error = 'Unable to read wallet policy file.'
+ self.goto(self.show_error)
+ return
+ try:
+ policy = _decode_policy(data)
+ except BaseException as exc:
+ self.error = str(exc) or 'Wallet Policy Import Error'
+ self.goto(self.show_error)
+ return
+ result = await ImportWalletPolicyFlow(policy).run()
+ self.set_result(result)
+
+ async def show_error(self):
+ from pages import ErrorPage
+ await ErrorPage(self.error).show()
+ self.error = None
+ self.reset(self.choose_file)
+
+
+class ViewWalletPolicyFlow(Flow):
+ def __init__(self, context=None):
+ from common import settings
+ from wallet_policy import WalletPolicyRegistry
+ self.policy = WalletPolicyRegistry(settings).get(context)
+ super().__init__(initial_state=self.show_overview, name='ViewWalletPolicyFlow')
+
+ async def show_overview(self):
+ from flows import SeriesOfPagesFlow
+ from pages import ErrorPage, LongTextPage
+ if self.policy is None:
+ await ErrorPage('Wallet policy was not found.').show()
+ self.set_result(False)
+ return
+ page_args = [{
+ 'card_header': {'title': 'Wallet policy'},
+ 'text': text,
+ 'centered': not text.startswith('Path '),
+ } for text in self.policy.format_review_pages()]
+ result = await SeriesOfPagesFlow(LongTextPage, page_args).run()
+ if result:
+ self.goto(self.choose_technical_details)
+ else:
+ self.set_result(False)
+
+ async def choose_technical_details(self):
+ import microns
+ from pages import YesNoChooserPage
+ result = await YesNoChooserPage(
+ text='Review the raw descriptor and extended public keys?',
+ yes_text='Technical details', no_text='Done',
+ initial_value=False, left_micron=microns.Back).show()
+ if result is None:
+ self.back()
+ elif result:
+ self.goto(self.show_details)
+ else:
+ self.set_result(True)
+
+ async def show_details(self):
+ import microns
+ from pages import LongTextPage
+ result = await LongTextPage(
+ card_header={'title': 'Technical details'},
+ text=self.policy.format_details(), centered=False,
+ right_micron=microns.Checkmark).show()
+ if result:
+ self.set_result(True)
+ else:
+ self.back()
+
+
+class RenameWalletPolicyFlow(Flow):
+ def __init__(self, context=None):
+ from common import settings
+ from wallet_policy import WalletPolicyRegistry
+ self.policy = WalletPolicyRegistry(settings).get(context)
+ super().__init__(initial_state=self.choose_name, name='RenameWalletPolicyFlow')
+
+ async def choose_name(self):
+ import microns
+ from pages import ErrorPage, TextInputPage
+ from wallet_policy import MAX_POLICY_NAME_LENGTH
+ if self.policy is None:
+ await ErrorPage('Wallet policy was not found.').show()
+ self.set_result(False)
+ return
+ result = await TextInputPage(
+ title='Wallet Policy Name', initial_text=self.policy.name,
+ max_length=MAX_POLICY_NAME_LENGTH, left_micron=microns.Cancel,
+ right_micron=microns.Checkmark).show()
+ if result is None:
+ self.set_result(False)
+ return
+ from tasks.wallet_policy_task import rename_wallet_policy_task
+ from utils import spinner_task
+ error, = await spinner_task(
+ 'Renaming policy', rename_wallet_policy_task,
+ args=[self.policy.policy_id, result])
+ if error is not None:
+ await ErrorPage('Unable to rename wallet policy.').show()
+ self.set_result(False)
+ return
+ from flows import AutoBackupFlow
+ from pages import SuccessPage
+ await SuccessPage('Wallet policy renamed').show()
+ await AutoBackupFlow().run()
+ self.set_result(True)
+
+
+class NameWalletPolicyKeysFlow(Flow):
+ def __init__(self, context=None):
+ from common import settings
+ from wallet_policy import WalletPolicyRegistry
+ self.policy = WalletPolicyRegistry(settings).get(context)
+ self.key_names = list(self.policy.key_names) if self.policy else []
+ self.external_key_indexes = tuple(
+ index for index in range(len(self.policy.keys))
+ if index not in self.policy.owned_key_indexes) if self.policy else ()
+ self.key_name_position = 0
+ super().__init__(initial_state=self.choose_key_name,
+ name='NameWalletPolicyKeysFlow')
+
+ async def choose_key_name(self):
+ import microns
+ from pages import ErrorPage, TextInputPage
+ from policy_display import format_fingerprint, suggested_key_name
+ from wallet_policy import MAX_KEY_NAME_LENGTH
+
+ if self.policy is None:
+ await ErrorPage('Wallet policy was not found.').show()
+ self.set_result(False)
+ return
+ if not self.external_key_indexes:
+ await ErrorPage('This wallet policy has no external signers.').show()
+ self.set_result(False)
+ return
+ if self.key_name_position >= len(self.external_key_indexes):
+ self.goto(self.save_key_names)
+ return
+
+ key_index = self.external_key_indexes[self.key_name_position]
+ key = self.policy.keys[key_index]
+ initial = self.key_names[key_index] or suggested_key_name(self.policy, key_index)
+ result = await TextInputPage(
+ card_header={'title': 'Name Signer'},
+ title='Fingerprint\n{}'.format(format_fingerprint(key.fingerprint)),
+ initial_text=initial, max_length=MAX_KEY_NAME_LENGTH,
+ left_micron=microns.Back, right_micron=microns.Checkmark).show()
+ if result is None:
+ if self.key_name_position:
+ self.key_name_position -= 1
+ else:
+ self.set_result(False)
+ return
+ if not result:
+ await ErrorPage('Enter a name for this signer.').show()
+ return
+ self.key_names[key_index] = result
+ self.key_name_position += 1
+
+ async def save_key_names(self):
+ from flows import AutoBackupFlow
+ from pages import ErrorPage, SuccessPage
+ from tasks.wallet_policy_task import rename_wallet_policy_keys_task
+ from utils import spinner_task
+
+ error, = await spinner_task(
+ 'Saving signer names', rename_wallet_policy_keys_task,
+ args=[self.policy.policy_id, self.key_names])
+ if error is not None:
+ await ErrorPage('Unable to save signer names.').show()
+ self.set_result(False)
+ return
+ await SuccessPage('Signer names saved').show()
+ await AutoBackupFlow().run()
+ self.set_result(True)
+
+
+class DeleteWalletPolicyFlow(Flow):
+ def __init__(self, context=None):
+ from common import settings
+ from wallet_policy import WalletPolicyRegistry
+ self.policy = WalletPolicyRegistry(settings).get(context)
+ super().__init__(initial_state=self.confirm, name='DeleteWalletPolicyFlow')
+
+ async def confirm(self):
+ from pages import ErrorPage, QuestionPage
+ if self.policy is None:
+ await ErrorPage('Wallet policy was not found.').show()
+ self.set_result(False)
+ return
+ result = await QuestionPage(
+ 'Delete wallet policy?\n\n{}\n\nPassport will not sign it until reimported.'.format(
+ self.policy.name)).show()
+ if not result:
+ self.set_result(False)
+ return
+ from tasks.wallet_policy_task import delete_wallet_policy_task
+ from utils import spinner_task
+ error, = await spinner_task(
+ 'Deleting policy', delete_wallet_policy_task,
+ args=[self.policy.policy_id])
+ if error is not None:
+ await ErrorPage('Unable to delete wallet policy.').show()
+ self.set_result(False)
+ return
+ from flows import AutoBackupFlow
+ from pages import SuccessPage
+ await SuccessPage('Wallet policy deleted').show()
+ await AutoBackupFlow().run()
+ self.set_result(True)
+
+
+class ExportWalletPolicyQRFlow(Flow):
+ def __init__(self, context=None):
+ from common import settings
+ from wallet_policy import WalletPolicyRegistry
+ self.policy = WalletPolicyRegistry(settings).get(context)
+ super().__init__(initial_state=self.show_qr, name='ExportWalletPolicyQRFlow')
+
+ async def show_qr(self):
+ from data_codecs.qr_type import QRType
+ from foundation import ur
+ from pages import ErrorPage, ShowQRPage
+ from policy_transport import encode_policy_transport
+ if self.policy is None:
+ await ErrorPage('Wallet policy was not found.').show()
+ self.set_result(False)
+ return
+ data = encode_policy_transport(self.policy).encode('utf-8')
+ await ShowQRPage(qr_type=QRType.UR2, qr_data=ur.new_bytes(data)).show()
+ self.set_result(True)
+
+
+class ExportWalletPolicyMicroSDFlow(SaveToMicroSDFlow):
+ def __init__(self, context=None):
+ from common import settings
+ from policy_transport import encode_policy_transport
+ from public_constants import DIR_WALLET_CONFIGS
+ from utils import get_folder_path
+ from wallet_policy import WalletPolicyRegistry
+ policy = WalletPolicyRegistry(settings).get(context)
+ if policy is None:
+ raise ValueError('Wallet policy was not found')
+ safe_name = ''.join(ch if ('0' <= ch <= '9' or 'a' <= ch <= 'z' or
+ 'A' <= ch <= 'Z' or ch in '-_') else '_'
+ for ch in policy.name)
+ super().__init__(
+ filename='{}-policy.json'.format(safe_name),
+ path=get_folder_path(DIR_WALLET_CONFIGS),
+ data=encode_policy_transport(policy), success_text='wallet policy')
+
+
+class VerifyWalletPolicyRequestFlow(Flow):
+ """Derive a bound Liana address request and return a confirmation QR."""
+
+ def __init__(self, context=None):
+ self.expected_policy_id = context
+ self.request = None
+ self.policy = None
+ self.address = None
+ self.error = None
+ super().__init__(initial_state=self.scan, name='VerifyWalletPolicyRequestFlow')
+
+ async def scan(self):
+ import chains
+ from common import settings
+ from data_codecs.qr_type import QRType
+ from flows import ScanQRFlow
+ from foundation import ur
+ from policy_transport import decode_address_request
+ from wallet_policy import WalletPolicyRegistry
+
+ result = await ScanQRFlow(
+ qr_types=[QRType.UR2], ur_types=[ur.Value.BYTES],
+ data_description='a Liana address request').run()
+ if result is None:
+ self.set_result(False)
+ return
+ try:
+ data = result.unwrap_bytes() if hasattr(result, 'unwrap_bytes') else result
+ self.request, self.policy, self.address = decode_address_request(
+ data, chains.current_chain(), WalletPolicyRegistry(settings),
+ self.expected_policy_id)
+ _verify_current_seed(self.policy, chains.current_chain())
+ except BaseException as exc:
+ self.error = str(exc) or 'Address Verification Error'
+ self.goto(self.show_error)
+ return
+ self.goto(self.confirm)
+
+ async def confirm(self):
+ import microns
+ from pages import LongQuestionPage
+ from styles.colors import HIGHLIGHT_TEXT_HEX
+ from utils import recolor, stylize_address
+ branch = 'Receive' if self.request['branch'] == 0 else 'Change'
+ text = '{}\n\n{} address #{}\n\nPolicy checksum\n{}\n\n{}'.format(
+ self.policy.name, branch, self.request['index'],
+ recolor(HIGHLIGHT_TEXT_HEX, self.policy.descriptor_check()),
+ stylize_address(self.address))
+ result = await LongQuestionPage(
+ card_header={'title': 'Verify Liana Address'}, text=text,
+ left_micron=microns.Back).show()
+ if result:
+ self.goto(self.show_response)
+ else:
+ self.back()
+
+ async def show_response(self):
+ from common import settings
+ from data_codecs.qr_type import QRType
+ from foundation import ur
+ from pages import ShowQRPage
+ from policy_transport import encode_address_response
+ from utils import xfp2str
+ data = encode_address_response(
+ self.request, self.address,
+ xfp2str(settings.get('xfp')).lower()).encode('utf-8')
+ await ShowQRPage(
+ qr_type=QRType.UR2, qr_data=ur.new_bytes(data),
+ caption='Scan this verified address in Liana').show()
+ self.set_result(True)
+
+ async def show_error(self):
+ from pages import ErrorPage
+ await ErrorPage(self.error).show()
+ self.error = None
+ self.reset(self.scan)
### ports/stm32/boards/Passport/modules/menus.py
@@ -312,6 +312,8 @@ def bitcoin_menu():
return [
{'icon': 'ICON_BITCOIN', 'label': 'Units', 'page': UnitsSettingPage, 'is_visible': is_logged_in},
{'icon': 'ICON_TWO_KEYS', 'label': 'Multisig', 'submenu': multisig_menu, 'is_visible': has_seed},
+ {'icon': 'ICON_TWO_KEYS', 'label': 'Wallet Policies', 'submenu': wallet_policy_menu,
+ 'is_visible': has_seed},
{'icon': 'ICON_NETWORK', 'label': 'Network', 'flow': SetChainFlow, 'statusbar': {},
'is_visible': is_logged_in},
]
@@ -394,6 +396,66 @@ def multisig_menu():
return items
+def wallet_policy_item_menu():
+ from flows.wallet_policy_flow import (
+ DeleteWalletPolicyFlow, ExportWalletPolicyMicroSDFlow,
+ ExportWalletPolicyQRFlow, NameWalletPolicyKeysFlow, RenameWalletPolicyFlow,
+ VerifyWalletPolicyRequestFlow, 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,
+ 'exit_on_success': True},
+ {'icon': 'ICON_TWO_KEYS', 'label': 'Name Signers',
+ 'flow': NameWalletPolicyKeysFlow, 'exit_on_success': True},
+ {'icon': 'ICON_CANCEL', 'label': 'Delete', 'flow': DeleteWalletPolicyFlow,
+ 'exit_on_success': True},
+ ]
+
+
+def wallet_policy_menu():
+ from common import settings
+ from flows.wallet_policy_flow import (ImportWalletPolicyFromMicroSDFlow,
+ ImportWalletPolicyFromQRFlow)
+ from pages import ErrorPage
+ from utils import escape_text, xfp2str
+ from wallet_policy import WalletPolicyRegistry
+
+ fingerprint = xfp2str(settings.get('xfp')).lower()
+ policies = list(WalletPolicyRegistry(settings).iter_policies(fingerprint))
+ if policies:
+ items = []
+ for policy in policies:
+ items.append({
+ 'icon': 'ICON_TWO_KEYS',
+ 'label': escape_text(policy.name),
+ 'submenu': wallet_policy_item_menu,
+ 'args': {'context': policy.policy_id},
+ })
+ else:
+ items = [{
+ 'icon': 'ICON_TWO_KEYS',
+ 'label': '(None registered)',
+ 'page': ErrorPage,
+ 'args': {'text': "You haven't registered any wallet policies yet."},
+ }]
+ items.append({
+ 'icon': 'ICON_SCAN_QR', 'label': 'Import from QR',
+ 'flow': ImportWalletPolicyFromQRFlow, 'statusbar': {'title': 'IMPORT'},
+ })
+ items.append({
+ 'icon': 'ICON_MICROSD', 'label': 'Import from microSD',
+ 'flow': ImportWalletPolicyFromMicroSDFlow, 'statusbar': {'title': 'IMPORT'},
+ })
+ return items
+
+
def developer_pubkey_menu():
from utils import has_dev_pubkey
from flows import InstallDevPubkeyFlow, ViewDevPubkeyFlow, RemoveDevPubkeyFlow
### ports/stm32/boards/Passport/modules/miniscript.py
@@ -0,0 +1,749 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Bounded Miniscript parsing, analysis, and script compilation.
+
+This module deliberately has no UI, settings, or secret-key dependencies. It
+implements the BIP379 grammar and a conservative registered-policy profile.
+Only the native SegWit P2WSH context is supported.
+"""
+
+try:
+ from ubinascii import unhexlify
+except ImportError: # pragma: no cover - CPython host tests
+ from binascii import unhexlify
+
+from policy_errors import (PolicyParseError, PolicyResourceError,
+ PolicyTypeError, UnsupportedPolicyError)
+
+
+MAX_TEMPLATE_LENGTH = 512
+MAX_PARSE_DEPTH = 16
+MAX_AST_NODES = 128
+MAX_THRESH_ITEMS = 24
+MAX_KEYS = 15
+MAX_P2WSH_SCRIPT_SIZE = 3600
+MAX_P2WSH_OPS = 201
+
+
+# Script opcodes used by BIP379. Keeping them local makes the pure policy
+# module importable under both MicroPython and CPython.
+OP_0 = 0x00
+OP_1 = 0x51
+OP_16 = 0x60
+OP_IF = 0x63
+OP_NOTIF = 0x64
+OP_ELSE = 0x67
+OP_ENDIF = 0x68
+OP_VERIFY = 0x69
+OP_TOALTSTACK = 0x6b
+OP_FROMALTSTACK = 0x6c
+OP_IFDUP = 0x73
+OP_DUP = 0x76
+OP_SWAP = 0x7c
+OP_SIZE = 0x82
+OP_EQUAL = 0x87
+OP_EQUALVERIFY = 0x88
+OP_0NOTEQUAL = 0x92
+OP_ADD = 0x93
+OP_BOOLAND = 0x9a
+OP_BOOLOR = 0x9b
+OP_NUMEQUAL = 0x9c
+OP_NUMEQUALVERIFY = 0x9d
+OP_RIPEMD160 = 0xa6
+OP_SHA256 = 0xa8
+OP_HASH160 = 0xa9
+OP_HASH256 = 0xaa
+OP_CHECKSIG = 0xac
+OP_CHECKSIGVERIFY = 0xad
+OP_CHECKMULTISIG = 0xae
+OP_CHECKMULTISIGVERIFY = 0xaf
+OP_CHECKLOCKTIMEVERIFY = 0xb1
+OP_CHECKSEQUENCEVERIFY = 0xb2
+
+
+def _is_ascii_digit(ch):
+ return len(ch) == 1 and '0' <= ch <= '9'
+
+
+def _is_ascii_alpha(ch):
+ return len(ch) == 1 and ('a' <= ch <= 'z' or 'A' <= ch <= 'Z')
+
+
+def _is_ascii_alnum(ch):
+ return _is_ascii_alpha(ch) or _is_ascii_digit(ch)
+
+
+class PolicyKey:
+ __slots__ = ('index', 'branches')
+
+ def __init__(self, index, branches=(0, 1)):
+ self.index = index
+ self.branches = branches
+
+ def identity(self):
+ return self.index, self.branches[0], self.branches[1]
+
+ def __repr__(self):
+ if self.branches == (0, 1):
+ return '@{}/**'.format(self.index)
+ return '@{}/<{};{}>/*'.format(self.index, self.branches[0], self.branches[1])
+
+
+class Node:
+ __slots__ = ('kind', 'args', 'value')
+
+ def __init__(self, kind, args=(), value=None):
+ self.kind = kind
+ self.args = args
+ self.value = value
+
+ def __repr__(self):
+ return 'Node({!r}, {!r}, {!r})'.format(self.kind, self.args, self.value)
+
+
+class TypeInfo:
+ __slots__ = ('basic', 'z', 'o', 'n', 'd', 'u', 's', 'f', 'e', 'locks')
+
+ def __init__(self, basic, z=False, o=False, n=False, d=False, u=False,
+ s=False, f=False, e=False, locks=0):
+ self.basic = basic
+ self.z = z
+ self.o = o
+ self.n = n
+ self.d = d
+ self.u = u
+ self.s = s
+ self.f = f
+ self.e = e
+ self.locks = locks
+
+ def is_type(self, basic, *properties):
+ if self.basic != basic:
+ return False
+ return all(getattr(self, prop) for prop in properties)
+
+
+class Parser:
+ _WRAPPERS = 'asctdvjnlu'
+
+ def __init__(self, text, max_depth=MAX_PARSE_DEPTH, max_nodes=MAX_AST_NODES,
+ max_keys=MAX_KEYS):
+ if not isinstance(text, str):
+ raise PolicyParseError('Policy template must be text')
+ if len(text) > MAX_TEMPLATE_LENGTH:
+ raise PolicyResourceError('Policy template exceeds {} characters'.format(MAX_TEMPLATE_LENGTH))
+ try:
+ text.encode('ascii')
+ except UnicodeError:
+ raise PolicyParseError('Policy template must contain ASCII only')
+ if '\x00' in text:
+ raise PolicyParseError('Policy template contains a NUL character')
+ self.text = text
+ self.length = len(text)
+ self.pos = 0
+ self.max_depth = max_depth
+ self.max_nodes = max_nodes
+ self.max_keys = max_keys
+ self.node_count = 0
+
+ def _error(self, message):
+ raise PolicyParseError(message, self.pos)
+
+ def _node(self, kind, args=(), value=None):
+ self.node_count += 1
+ if self.node_count > self.max_nodes:
+ raise PolicyResourceError('Policy contains more than {} expressions'.format(self.max_nodes))
+ return Node(kind, args, value)
+
+ def _peek(self):
+ if self.pos >= self.length:
+ return ''
+ return self.text[self.pos]
+
+ def _take(self, expected=None):
+ if self.pos >= self.length:
+ self._error('Unexpected end of policy')
+ ch = self.text[self.pos]
+ if expected is not None and ch != expected:
+ self._error("Expected '{}'".format(expected))
+ self.pos += 1
+ return ch
+
+ def _identifier(self):
+ start = self.pos
+ while _is_ascii_alnum(self._peek()) or self._peek() == '_':
+ self.pos += 1
+ if self.pos == start:
+ self._error('Expected expression name')
+ return self.text[start:self.pos]
+
+ def _number(self):
+ start = self.pos
+ while _is_ascii_digit(self._peek()):
+ self.pos += 1
+ if self.pos == start:
+ self._error('Expected decimal number')
+ token = self.text[start:self.pos]
+ if len(token) > 1 and token[0] == '0':
+ self._error('Decimal numbers must not have leading zeroes')
+ if len(token) > 10:
+ raise PolicyResourceError('Decimal number is too large')
+ value = int(token)
+ if value > 0xffffffff:
+ raise PolicyResourceError('Decimal number is too large')
+ return value
+
+ def _hex(self, expected_bytes):
+ start = self.pos
+ expected_chars = expected_bytes * 2
+ end = start + expected_chars
+ if end > self.length:
+ self._error('Hash value is truncated')
+ token = self.text[start:end]
+ for ch in token:
+ if ch not in '0123456789abcdefABCDEF':
+ self._error('Hash value is not hexadecimal')
+ self.pos = end
+ return token.lower()
+
+ def _key(self):
+ self._take('@')
+ index = self._number()
+ if index >= self.max_keys:
+ raise PolicyResourceError('Key index exceeds {}'.format(self.max_keys - 1))
+ self._take('/')
+ if self.text[self.pos:self.pos + 2] == '**':
+ self.pos += 2
+ return PolicyKey(index)
+ self._take('<')
+ first = self._number()
+ self._take(';')
+ second = self._number()
+ self._take('>')
+ self._take('/')
+ self._take('*')
+ if first == second:
+ self._error('Receive and change branches must be different')
+ if first >= 0x80000000 or second >= 0x80000000:
+ raise PolicyResourceError('Policy branches must be unhardened')
+ return PolicyKey(index, (first, second))
+
+ def parse(self):
+ node = self._expr(0)
+ if self.pos != self.length:
+ self._error('Unexpected trailing characters')
+ return node
+
+ def _expr(self, depth):
+ if depth > self.max_depth:
+ raise PolicyResourceError('Policy nesting exceeds {}'.format(self.max_depth))
+
+ # Wrappers can be combined before a single colon, for example sln:X.
+ start = self.pos
+ while _is_ascii_alpha(self._peek()):
+ self.pos += 1
+ if self._peek() == ':':
+ wrappers = self.text[start:self.pos]
+ if not wrappers or any(ch not in self._WRAPPERS for ch in wrappers):
+ self._error('Unknown Miniscript wrapper')
+ self.pos += 1
+ child = self._expr(depth + 1)
+ for wrapper in reversed(wrappers):
+ child = self._apply_wrapper(wrapper, child)
+ return child
+ self.pos = start
+
+ if self._peek() in ('0', '1'):
+ ch = self._take()
+ if _is_ascii_digit(self._peek()) or self._peek() == '(':
+ self._error('Invalid constant')
+ return self._node(ch)
+
+ name = self._identifier()
+ self._take('(')
+
+ if name in ('pk', 'pkh', 'pk_k', 'pk_h'):
+ key = self._key()
+ self._take(')')
+ base = self._node('pk_k' if name in ('pk', 'pk_k') else 'pk_h', value=key)
+ if name in ('pk', 'pkh'):
+ return self._node('c', (base,))
+ return base
+
+ if name in ('older', 'after'):
+ value = self._number()
+ self._take(')')
+ return self._node(name, value=value)
+
+ if name in ('sha256', 'hash256'):
+ value = self._hex(32)
+ self._take(')')
+ return self._node(name, value=value)
+
+ if name in ('ripemd160', 'hash160'):
+ value = self._hex(20)
+ self._take(')')
+ return self._node(name, value=value)
+
+ if name in ('and_v', 'and_b', 'and_n', 'or_b', 'or_c', 'or_d', 'or_i'):
+ left = self._expr(depth + 1)
+ self._take(',')
+ right = self._expr(depth + 1)
+ self._take(')')
+ if name == 'and_n':
+ return self._node('andor', (left, right, self._node('0')))
+ return self._node(name, (left, right))
+
+ if name == 'andor':
+ first = self._expr(depth + 1)
+ self._take(',')
+ second = self._expr(depth + 1)
+ self._take(',')
+ third = self._expr(depth + 1)
+ self._take(')')
+ return self._node(name, (first, second, third))
+
+ if name == 'thresh':
+ threshold = self._number()
+ children = []
+ while self._peek() == ',':
+ self.pos += 1
+ if len(children) >= MAX_THRESH_ITEMS:
+ raise PolicyResourceError('Threshold contains too many expressions')
+ children.append(self._expr(depth + 1))
+ self._take(')')
+ return self._node(name, tuple(children), threshold)
+
+ if name == 'multi':
+ threshold = self._number()
+ keys = []
+ while self._peek() == ',':
+ self.pos += 1
+ key_limit = 20 if name == 'multi' else MAX_THRESH_ITEMS
+ if len(keys) >= key_limit:
+ raise PolicyResourceError('{} contains too many keys'.format(name))
+ keys.append(self._key())
+ self._take(')')
+ return self._node(name, tuple(keys), threshold)
+
+ self._error("Unknown Miniscript fragment '{}'".format(name))
+
+ def _apply_wrapper(self, wrapper, child):
+ if wrapper == 't':
+ return self._node('and_v', (child, self._node('1')))
+ if wrapper == 'l':
+ return self._node('or_i', (self._node('0'), child))
+ if wrapper == 'u':
+ return self._node('or_i', (child, self._node('0')))
+ return self._node(wrapper, (child,))
+
+
+def _require(condition, message):
+ if not condition:
+ raise PolicyTypeError(message)
+
+
+def analyze(node, context='wsh'):
+ """Return BIP379 correctness/malleability properties for an AST."""
+ _require(context == 'wsh', 'Only P2WSH Miniscript is supported')
+ kind = node.kind
+ args = node.args
+
+ if kind == '0':
+ return TypeInfo('B', z=True, u=True, d=True, s=True, e=True)
+ if kind == '1':
+ return TypeInfo('B', z=True, u=True, f=True)
+ if kind == 'pk_k':
+ return TypeInfo('K', o=True, n=True, d=True, u=True, s=True, e=True)
+ if kind == 'pk_h':
+ _require(context == 'wsh', 'pk_h is only valid in P2WSH')
+ return TypeInfo('K', n=True, d=True, u=True, s=True, e=True)
+ if kind in ('older', 'after'):
+ _require(1 <= node.value < 0x80000000, '{} value is outside BIP379 range'.format(kind))
+ if kind == 'older':
+ # BIP68 only assigns the low 16 bits and the type flag. Accepting
+ # reserved bits would make the number shown in a descriptor differ
+ # from the relative delay actually enforced by consensus.
+ allowed = 0xffff | (1 << 22)
+ _require(not (node.value & ~allowed),
+ 'older exceeds the BIP68 relative timelock limit or uses reserved bits')
+ _require(node.value & 0xffff,
+ 'older value must encode a non-zero relative delay')
+ if kind == 'after':
+ lock = 1 if node.value < 500000000 else 2
+ else:
+ lock = 4 if not (node.value & (1 << 22)) else 8
+ return TypeInfo('B', z=True, f=True, locks=lock)
+ if kind in ('sha256', 'hash256', 'ripemd160', 'hash160'):
+ return TypeInfo('B', o=True, n=True, d=True, u=True)
+ if kind == 'multi':
+ count = len(args)
+ _require(1 <= node.value <= count, '{} threshold is invalid'.format(kind))
+ _require(count <= 20, 'P2WSH multi is limited to 20 keys')
+ return TypeInfo('B', n=True, d=True, u=True, s=True, e=True)
+
+ children = [analyze(child, context) for child in args]
+ locks = 0
+ for child in children:
+ locks |= child.locks
+
+ if kind == 'andor':
+ x, y, zed = children
+ _require(x.is_type('B', 'd', 'u'), 'andor first argument must be Bdu')
+ _require(y.basic in ('B', 'K', 'V') and y.basic == zed.basic,
+ 'andor branches must have the same B, K, or V type')
+ _require(x.e and (x.s or y.s or zed.s), 'andor is malleable')
+ return TypeInfo(y.basic,
+ z=x.z and y.z and zed.z,
+ o=(x.z and y.o and zed.o) or (x.o and y.z and zed.z),
+ u=y.u and zed.u, d=zed.d,
+ s=zed.s and (x.s or y.s),
+ f=zed.f and (x.s or y.f),
+ e=zed.e and (x.s or y.f), locks=locks)
+
+ if kind == 'and_v':
+ x, y = children
+ _require(x.basic == 'V' and y.basic in ('B', 'K', 'V'),
+ 'and_v requires V followed by B, K, or V')
+ return TypeInfo(y.basic, z=x.z and y.z,
+ o=(x.z and y.o) or (y.z and x.o),
+ n=x.n or (x.z and y.n), u=y.u,
+ s=x.s or y.s, f=x.s or y.f, locks=locks)
+
+ if kind == 'and_b':
+ x, y = children
+ _require(x.basic == 'B' and y.basic == 'W', 'and_b requires B and W')
+ return TypeInfo('B', z=x.z and y.z,
+ o=(x.z and y.o) or (y.z and x.o),
+ n=x.n or (x.z and y.n), d=x.d and y.d, u=True,
+ s=x.s or y.s,
+ f=(x.f and y.f) or (x.s and x.f) or (y.s and y.f),
+ e=x.e and y.e and x.s and y.s, locks=locks)
+
+ if kind == 'or_b':
+ x, zed = children
+ _require(x.is_type('B', 'd') and zed.is_type('W', 'd'),
+ 'or_b requires Bd and Wd')
+ _require(x.e and zed.e and (x.s or zed.s), 'or_b is malleable')
+ return TypeInfo('B', z=x.z and zed.z,
+ o=(x.z and zed.o) or (zed.z and x.o),
+ d=True, u=True, s=x.s and zed.s, e=True, locks=locks)
+
+ if kind == 'or_c':
+ x, zed = children
+ _require(x.is_type('B', 'd', 'u') and zed.basic == 'V',
+ 'or_c requires Bdu and V')
+ _require(x.e and (x.s or zed.s), 'or_c is malleable')
+ return TypeInfo('V', z=x.z and zed.z, o=x.o and zed.z,
+ s=x.s and zed.s, f=True, locks=locks)
+
+ if kind == 'or_d':
+ x, zed = children
+ _require(x.is_type('B', 'd', 'u') and zed.basic == 'B',
+ 'or_d requires Bdu and B')
+ _require(x.e and (x.s or zed.s), 'or_d is malleable')
+ return TypeInfo('B', z=x.z and zed.z, o=x.o and zed.z,
+ d=zed.d, u=zed.u, s=x.s and zed.s,
+ f=zed.f, e=zed.e, locks=locks)
+
+ if kind == 'or_i':
+ x, zed = children
+ _require(x.basic in ('B', 'K', 'V') and x.basic == zed.basic,
+ 'or_i branches must have the same B, K, or V type')
+ _require(x.s or zed.s, 'or_i is malleable')
+ return TypeInfo(x.basic, o=x.z and zed.z, u=x.u and zed.u,
+ d=x.d or zed.d, s=x.s and zed.s,
+ f=x.f and zed.f,
+ e=(x.e and zed.f) or (zed.e and x.f), locks=locks)
+
+ if kind == 'thresh':
+ _require(1 <= node.value <= len(children), 'thresh threshold is invalid')
+ _require(children and children[0].is_type('B', 'd', 'u'),
+ 'thresh first argument must be Bdu')
+ for child in children[1:]:
+ _require(child.is_type('W', 'd', 'u'),
+ 'thresh arguments after the first must be Wdu')
+ non_signed = sum(1 for child in children if not child.s)
+ _require(all(child.e for child in children) and non_signed <= node.value,
+ 'thresh is malleable')
+ zero_count = sum(1 for child in children if child.z)
+ one_count = sum(1 for child in children if child.o)
+ return TypeInfo('B', z=zero_count == len(children),
+ o=one_count == 1 and zero_count == len(children) - 1,
+ d=True, u=True, s=non_signed <= node.value - 1,
+ e=all(child.s for child in children), locks=locks)
+
+ if kind in ('a', 's', 'c', 'd', 'v', 'j', 'n'):
+ x = children[0]
+ if kind == 'a':
+ _require(x.basic == 'B', 'a: requires B')
+ return TypeInfo('W', d=x.d, u=x.u, s=x.s, f=x.f, e=x.e, locks=locks)
+ if kind == 's':
+ _require(x.is_type('B', 'o'), 's: requires Bo')
+ return TypeInfo('W', d=x.d, u=x.u, s=x.s, f=x.f, e=x.e, locks=locks)
+ if kind == 'c':
+ _require(x.basic == 'K', 'c: requires K')
+ return TypeInfo('B', o=x.o, n=x.n, d=x.d, u=True,
+ s=True, f=x.f, e=x.e, locks=locks)
+ if kind == 'd':
+ _require(x.is_type('V', 'z'), 'd: requires Vz')
+ return TypeInfo('B', o=True, n=True, d=True, s=x.s, e=True, locks=locks)
+ if kind == 'v':
+ _require(x.basic == 'B', 'v: requires B')
+ return TypeInfo('V', z=x.z, o=x.o, n=x.n, s=x.s, f=True, locks=locks)
+ if kind == 'j':
+ _require(x.is_type('B', 'n'), 'j: requires Bn')
+ return TypeInfo('B', o=x.o, n=True, d=True, u=x.u,
+ s=x.s, e=x.f, locks=locks)
+ _require(x.basic == 'B', 'n: requires B')
+ return TypeInfo('B', z=x.z, o=x.o, n=x.n, d=x.d, u=True,
+ s=x.s, f=x.f, e=x.e, locks=locks)
+
+ raise PolicyTypeError("Unsupported AST node '{}'".format(kind))
+
+
+def _walk(node):
+ yield node
+ for arg in node.args:
+ if isinstance(arg, Node):
+ for child in _walk(arg):
+ yield child
+
+
+def iter_policy_keys(node):
+ """Yield key expressions in descriptor traversal order."""
+ for item in _walk(node):
+ if item.kind in ('pk_k', 'pk_h'):
+ yield item.value
+ elif item.kind == 'multi':
+ for key in item.args:
+ yield key
+
+
+def policy_timelocks(node):
+ return tuple((item.kind, item.value) for item in _walk(node)
+ if item.kind in ('older', 'after'))
+
+
+def validate(node, context='wsh', require_signed=True, allow_hashlocks=False):
+ info = analyze(node, context)
+ _require(info.basic == 'B', 'Top-level Miniscript must have type B')
+ if require_signed:
+ _require(info.s, 'Every valid satisfaction must require a signature')
+
+ if (info.locks & 1) and (info.locks & 2):
+ raise UnsupportedPolicyError('Mixing height and time absolute locks is not supported')
+ if (info.locks & 4) and (info.locks & 8):
+ raise UnsupportedPolicyError('Mixing height and time relative locks is not supported')
+
+ seen = set()
+ branches_by_key = {}
+ for item in _walk(node):
+ if item.kind in ('sha256', 'hash256', 'ripemd160', 'hash160') and not allow_hashlocks:
+ raise UnsupportedPolicyError('Hashlock policies are not supported')
+ for key in iter_policy_keys(node):
+ ident = key.identity()
+ if ident in seen:
+ raise PolicyTypeError('A key expression is repeated in the policy')
+ seen.add(ident)
+ branch_set = set(key.branches)
+ previous = branches_by_key.get(key.index, set())
+ if previous.intersection(branch_set):
+ raise PolicyTypeError('Derivation branches overlap for key @{}'.format(key.index))
+ branches_by_key[key.index] = previous.union(branch_set)
+ return info
+
+
+def _push_data(data):
+ size = len(data)
+ if size < 0x4c:
+ return bytes([size]) + data
+ if size <= 0xff:
+ return b'\x4c' + bytes([size]) + data
+ if size <= 0xffff:
+ return b'\x4d' + bytes([size & 0xff, size >> 8]) + data
+ raise PolicyResourceError('Script push is too large')
+
+
+def _script_num(value):
+ if value == 0:
+ return b'\x00'
+ if 1 <= value <= 16:
+ return bytes([OP_1 + value - 1])
+ result = bytearray()
+ while value:
+ result.append(value & 0xff)
+ value >>= 8
+ if result[-1] & 0x80:
+ result.append(0)
+ return _push_data(bytes(result))
+
+
+def _default_hash160(data):
+ try:
+ import trezorcrypto
+ first = trezorcrypto.sha256(data).digest()
+ return trezorcrypto.ripemd160(first).digest()
+ except ImportError: # pragma: no cover - CPython host tests
+ import hashlib
+ first = hashlib.sha256(data).digest()
+ return hashlib.new('ripemd160', first).digest()
+
+
+def _verify_last(script):
+ replacements = {
+ OP_EQUAL: OP_EQUALVERIFY,
+ OP_CHECKSIG: OP_CHECKSIGVERIFY,
+ OP_CHECKMULTISIG: OP_CHECKMULTISIGVERIFY,
+ OP_NUMEQUAL: OP_NUMEQUALVERIFY,
+ }
+ if script and script[-1] in replacements:
+ return script[:-1] + bytes([replacements[script[-1]]])
+ return script + bytes([OP_VERIFY])
+
+
+def _count_non_push_ops(script):
+ """Count static opcodes, including those in unexecuted branches."""
+ position = 0
+ count = 0
+ length = len(script)
+ while position < length:
+ opcode = script[position]
+ position += 1
+ if opcode <= 0x4b:
+ push_length = opcode
+ elif opcode == 0x4c:
+ if position >= length:
+ raise PolicyTypeError('Compiled script contains a truncated push')
+ push_length = script[position]
+ position += 1
+ elif opcode == 0x4d:
+ if position + 2 > length:
+ raise PolicyTypeError('Compiled script contains a truncated push')
+ push_length = script[position] | (script[position + 1] << 8)
+ position += 2
+ else:
+ push_length = 0
+ if opcode > OP_16:
+ count += 1
+ position += push_length
+ if position > length:
+ raise PolicyTypeError('Compiled script contains a truncated push')
+ return count
+
+
+def _max_multisig_ops(node):
+ """Bound the additional CHECKMULTISIG key charge on any execution path.
+
+ Both successful and failed signature checks pay this charge. Alternative
+ IF branches cannot both execute; other combinations conservatively sum
+ their children, including dissatisfactions used by thresholds and ORs.
+ Wrappers retain the charge even when they can skip their child.
+ """
+ if node.kind == 'multi':
+ return len(node.args)
+ costs = [_max_multisig_ops(arg) for arg in node.args if isinstance(arg, Node)]
+ if node.kind == 'or_i':
+ return max(costs)
+ if node.kind == 'andor':
+ return costs[0] + max(costs[1], costs[2])
+ return sum(costs)
+
+
+def compile_miniscript(node, key_resolver, branch, address_index, context='wsh',
+ hash160_fn=None, max_script_size=MAX_P2WSH_SCRIPT_SIZE):
+ """Compile a validated AST.
+
+ key_resolver is called as ``resolver(key_index, child_branch, index)`` and
+ must return a compressed 33-byte key for P2WSH.
+ """
+ if branch not in (0, 1):
+ raise ValueError('branch must be receive (0) or change (1)')
+ if not 0 <= address_index < 0x80000000:
+ raise ValueError('address index must be unhardened')
+ validate(node, context)
+ hash160_fn = hash160_fn or _default_hash160
+
+ def key_bytes(key):
+ result = key_resolver(key.index, key.branches[branch], address_index)
+ expected = 33
+ if not isinstance(result, (bytes, bytearray)) or len(result) != expected:
+ raise PolicyTypeError('Key resolver returned an invalid public key')
+ return bytes(result)
+
+ def emit(item):
+ kind = item.kind
+ if kind == '0':
+ return bytes([OP_0])
+ if kind == '1':
+ return bytes([OP_1])
+ if kind == 'pk_k':
+ return _push_data(key_bytes(item.value))
+ if kind == 'pk_h':
+ key = key_bytes(item.value)
+ return bytes([OP_DUP, OP_HASH160]) + _push_data(hash160_fn(key)) + bytes([OP_EQUALVERIFY])
+ if kind == 'older':
+ return _script_num(item.value) + bytes([OP_CHECKSEQUENCEVERIFY])
+ if kind == 'after':
+ return _script_num(item.value) + bytes([OP_CHECKLOCKTIMEVERIFY])
+ if kind in ('sha256', 'hash256', 'ripemd160', 'hash160'):
+ opcode = {
+ 'sha256': OP_SHA256, 'hash256': OP_HASH256,
+ 'ripemd160': OP_RIPEMD160, 'hash160': OP_HASH160,
+ }[kind]
+ return (bytes([OP_SIZE]) + _script_num(32) + bytes([OP_EQUALVERIFY, opcode]) +
+ _push_data(unhexlify(item.value)) + bytes([OP_EQUAL]))
+ if kind == 'andor':
+ x, y, zed = item.args
+ return emit(x) + bytes([OP_NOTIF]) + emit(zed) + bytes([OP_ELSE]) + emit(y) + bytes([OP_ENDIF])
+ if kind == 'and_v':
+ return emit(item.args[0]) + emit(item.args[1])
+ if kind == 'and_b':
+ return emit(item.args[0]) + emit(item.args[1]) + bytes([OP_BOOLAND])
+ if kind == 'or_b':
+ return emit(item.args[0]) + emit(item.args[1]) + bytes([OP_BOOLOR])
+ if kind == 'or_c':
+ return emit(item.args[0]) + bytes([OP_NOTIF]) + emit(item.args[1]) + bytes([OP_ENDIF])
+ if kind == 'or_d':
+ return emit(item.args[0]) + bytes([OP_IFDUP, OP_NOTIF]) + emit(item.args[1]) + bytes([OP_ENDIF])
+ if kind == 'or_i':
+ return bytes([OP_IF]) + emit(item.args[0]) + bytes([OP_ELSE]) + emit(item.args[1]) + bytes([OP_ENDIF])
+ if kind == 'thresh':
+ script = emit(item.args[0])
+ for child in item.args[1:]:
+ script += emit(child) + bytes([OP_ADD])
+ return script + _script_num(item.value) + bytes([OP_EQUAL])
+ if kind == 'multi':
+ script = _script_num(item.value)
+ for key in item.args:
+ script += _push_data(key_bytes(key))
+ return script + _script_num(len(item.args)) + bytes([OP_CHECKMULTISIG])
+ if kind == 'a':
+ return bytes([OP_TOALTSTACK]) + emit(item.args[0]) + bytes([OP_FROMALTSTACK])
+ if kind == 's':
+ return bytes([OP_SWAP]) + emit(item.args[0])
+ if kind == 'c':
+ return emit(item.args[0]) + bytes([OP_CHECKSIG])
+ if kind == 'd':
+ return bytes([OP_DUP, OP_IF]) + emit(item.args[0]) + bytes([OP_ENDIF])
+ if kind == 'v':
+ return _verify_last(emit(item.args[0]))
+ if kind == 'j':
+ return bytes([OP_SIZE, OP_0NOTEQUAL, OP_IF]) + emit(item.args[0]) + bytes([OP_ENDIF])
+ if kind == 'n':
+ return emit(item.args[0]) + bytes([OP_0NOTEQUAL])
+ raise PolicyTypeError("Cannot compile '{}'".format(kind))
+
+ script = emit(node)
+ if len(script) > max_script_size:
+ raise PolicyResourceError('Compiled script exceeds {} bytes'.format(max_script_size))
+ if _count_non_push_ops(script) + _max_multisig_ops(node) > MAX_P2WSH_OPS:
+ raise PolicyResourceError('Compiled P2WSH script exceeds {} opcodes'.format(MAX_P2WSH_OPS))
+ return script
+
+
+def parse_miniscript(text, context='wsh'):
+ node = Parser(text).parse()
+ validate(node, context)
+ return node
### ports/stm32/boards/Passport/modules/pages/singlesig_multisig_chooser_page.py
@@ -9,13 +9,17 @@
class SinglesigMultisigChooserPage(ChooserPage):
def __init__(self, multisigs, card_header={'title': 'Single/Multisig'}, initial_value=None,
- left_micron=None, right_micron=None):
+ left_micron=None, right_micron=None, policies=()):
options = [{'label': 'Single-sig', 'value': ('single-sig', None)}]
for ms in multisigs:
label = '%d/%d: %s' % (ms.M, ms.N, ms.name)
options.append({'label': label, 'value': ('multisig', ms)})
+ for policy in policies:
+ options.append({'label': 'Policy: {}'.format(policy.name),
+ 'value': ('policy', policy)})
+
super().__init__(
card_header=card_header,
options=options,
### ports/stm32/boards/Passport/modules/policy_display.py
@@ -0,0 +1,729 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Human-readable, bounded presentation of registered wallet policies.
+
+The strings in this module are derived exclusively from the policy AST that
+Passport already validated. Coordinator-supplied descriptions must never be
+used in place of this analysis: a hostile description could otherwise conceal
+different spending conditions in the descriptor.
+"""
+
+from miniscript import iter_policy_keys, policy_timelocks
+
+
+_WRAPPERS = ('a', 's', 'c', 'd', 'v', 'j', 'n')
+_AND = ('and_v', 'and_b')
+_OR = ('or_b', 'or_c', 'or_d', 'or_i')
+
+
+def _highlight(text):
+ """Use Passport's standard teal emphasis, with a host-test fallback.
+
+ The monochrome palette maps HIGHLIGHT_TEXT_HEX to black, so these markers
+ preserve the existing readable hierarchy without adding a color-only cue.
+ """
+ try:
+ from styles.colors import HIGHLIGHT_TEXT_HEX
+ except ImportError: # pragma: no cover - CPython host tests have no LVGL
+ HIGHLIGHT_TEXT_HEX = 0x00bdcd
+ return '#{:06x} {}#'.format(HIGHLIGHT_TEXT_HEX, text)
+
+
+def _group_number(value):
+ text = str(value)
+ parts = []
+ while len(text) > 3:
+ parts.insert(0, text[-3:])
+ text = text[:-3]
+ parts.insert(0, text)
+ return ','.join(parts)
+
+
+def format_fingerprint(fingerprint):
+ text = fingerprint.upper()
+ return ' '.join(text[index:index + 4] for index in range(0, len(text), 4))
+
+
+def _escape(text):
+ # LVGL uses # as an inline recolor delimiter. Signer names are local and
+ # validated, but still need escaping before they enter a recolor-enabled label.
+ return text.replace('#', '##')
+
+
+def _plural(value, singular, plural=None):
+ return '{} {}'.format(value, singular if value == 1 else (plural or singular + 's'))
+
+
+def _about_duration(seconds):
+ # These are intentionally approximate. Block-based locks are not wall-clock
+ # guarantees, and time-based BIP68 locks are quantized in 512-second units.
+ units = (
+ (31557600, 'year'),
+ (2629800, 'month'),
+ (604800, 'week'),
+ (86400, 'day'),
+ (3600, 'hour'),
+ (60, 'minute'),
+ )
+ for position, (size, name) in enumerate(units):
+ if seconds >= size:
+ count = seconds // size
+ parts = [_plural(count, name)]
+ if position + 1 < len(units):
+ next_size, next_name = units[position + 1]
+ remainder = seconds - count * size
+ next_count = int((remainder + next_size // 2) // next_size)
+ if next_count:
+ # Carry a rounded sub-unit into the primary unit. This is
+ # especially important for 11 months 29 days -> 1 year.
+ ratio = int((size + next_size // 2) // next_size)
+ if next_count >= ratio:
+ count += 1
+ parts = [_plural(count, name)]
+ else:
+ parts.append(_plural(next_count, next_name))
+ return 'about ' + ' '.join(parts)
+ return _plural(seconds, 'second')
+
+
+def _utc_date(timestamp):
+ # Bitcoin uses Unix seconds, while STM32 utime starts in 2000. Convert
+ # directly so dates before 2000 also work on ports with unsigned time_t.
+ # BIP379 limits absolute locks to signed 31-bit values (through 2038).
+ if not 0 <= timestamp < 0x80000000:
+ return None
+ days = timestamp // 86400
+ year = 1970
+ while True:
+ leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
+ year_days = 366 if leap else 365
+ if days < year_days:
+ break
+ days -= year_days
+ year += 1
+ month = 1
+ for month_days in (31, 29 if leap else 28, 31, 30, 31, 30,
+ 31, 31, 30, 31, 30, 31):
+ if days < month_days:
+ break
+ days -= month_days
+ month += 1
+ return '{:04d}-{:02d}-{:02d} UTC'.format(year, month, days + 1)
+
+
+def describe_timelock(kind, value):
+ """Return (short description, exact value, explanatory detail)."""
+ if kind == 'older':
+ if value & (1 << 22):
+ units = value & 0xffff
+ seconds = units * 512
+ exact = '{} seconds ({} x 512)'.format(
+ _group_number(seconds), _group_number(units))
+ if value != ((1 << 22) | units):
+ exact += ' (encoded as older({}))'.format(value)
+ return (
+ _about_duration(seconds),
+ exact,
+ 'The timer starts separately when each coin confirms.',
+ )
+ blocks = value & 0xffff
+ exact = '{} {}'.format(_group_number(blocks),
+ 'block' if blocks == 1 else 'blocks')
+ if value != blocks:
+ exact += ' (encoded as older({}))'.format(value)
+ return (
+ _about_duration(blocks * 600),
+ exact,
+ 'The timer starts separately when each coin confirms.',
+ )
+ if value < 500000000:
+ return (
+ 'block {}'.format(_group_number(value)),
+ 'absolute block height',
+ 'This condition uses a blockchain height, not the age of each coin.',
+ )
+ date = _utc_date(value)
+ return (
+ date or 'Unix time {}'.format(_group_number(value)),
+ 'Unix timestamp {}'.format(_group_number(value)),
+ 'This condition uses an absolute time, not the age of each coin.',
+ )
+
+
+def _unwrap(node):
+ while node.kind in _WRAPPERS and len(node.args) == 1:
+ node = node.args[0]
+ return node
+
+
+def _split_alternatives(node):
+ node = _unwrap(node)
+ if node.kind in _OR:
+ result = []
+ for child in node.args:
+ result.extend(_split_alternatives(child))
+ return result
+ return [node]
+
+
+def _key_indexes(node):
+ result = []
+ for key in iter_policy_keys(node):
+ if key.index not in result:
+ result.append(key.index)
+ return tuple(result)
+
+
+def _can_satisfy_without_key(node, key_index):
+ """Whether a positive satisfaction can omit key_index.
+
+ ``None`` means the conditional structure cannot be summarized safely. The
+ UI reports that uncertainty instead of claiming Passport is required.
+ """
+ node = _unwrap(node)
+ kind = node.kind
+ if kind in ('pk_k', 'pk_h'):
+ return node.value.index != key_index
+ if kind in ('older', 'after', '1'):
+ return True
+ if kind == '0':
+ return False
+ if kind == 'multi':
+ available = sum(1 for key in node.args if key.index != key_index)
+ return available >= node.value
+ if kind in _AND:
+ values = [_can_satisfy_without_key(child, key_index) for child in node.args]
+ if False in values:
+ return False
+ if None in values:
+ return None
+ return True
+ if kind in _OR:
+ values = [_can_satisfy_without_key(child, key_index) for child in node.args]
+ if True in values:
+ return True
+ if None in values:
+ return None
+ return False
+ if kind == 'thresh':
+ values = [_can_satisfy_without_key(child, key_index) for child in node.args]
+ possible = sum(1 for value in values if value is True)
+ unknown = sum(1 for value in values if value is None)
+ if possible >= node.value:
+ return True
+ if possible + unknown < node.value:
+ return False
+ return None
+ if kind == 'andor':
+ # Correctly describing the dissatisfaction branch requires more than a
+ # Boolean authorization tree. Keep the display structural and cautious.
+ return None
+ return None
+
+
+def _simple_requirements(node):
+ """Flatten a path made only from AND, keys, and timelocks."""
+ node = _unwrap(node)
+ if node.kind in _AND:
+ result = []
+ for child in node.args:
+ flattened = _simple_requirements(child)
+ if flattened is None:
+ return None
+ result.extend(flattened)
+ return result
+ if node.kind in ('pk_k', 'pk_h', 'older', 'after'):
+ return [node]
+ return None
+
+
+def _key_line(policy, key_index, recovery=False):
+ return '{} - {}'.format(
+ _key_role(policy, key_index, recovery),
+ format_fingerprint(policy.keys[key_index].fingerprint))
+
+
+def _key_role(policy, key_index, recovery=False):
+ if key_index in policy.owned_key_indexes:
+ role = 'This Passport'
+ elif policy.key_names[key_index]:
+ role = _escape(policy.key_names[key_index])
+ elif recovery:
+ role = 'Recovery key'
+ else:
+ role = 'Key {}'.format(key_index + 1)
+ return role
+
+
+def _format_condition(node, policy, depth=0, recovery=False):
+ node = _unwrap(node)
+ indent = ' ' * min(depth, 4)
+ child_indent = ' ' * min(depth + 1, 4)
+ kind = node.kind
+
+ if kind in ('pk_k', 'pk_h'):
+ return [indent + _key_line(policy, node.value.index, recovery)]
+ if kind in ('older', 'after'):
+ short, exact, _ = describe_timelock(kind, node.value)
+ prefix = 'Wait ' if kind == 'older' else 'After '
+ return [indent + prefix + short,
+ child_indent + '(' + exact + ')']
+ if kind == 'multi':
+ lines = [indent + '{} of {} keys'.format(node.value, len(node.args))]
+ for key in node.args:
+ lines.append(child_indent + '- ' + _key_line(policy, key.index, recovery))
+ return lines
+ if kind in _AND:
+ lines = [indent + 'All of']
+ for child in node.args:
+ child_lines = _format_condition(child, policy, depth + 1, recovery)
+ if child_lines:
+ child_lines[0] = child_indent + '- ' + child_lines[0].lstrip()
+ lines.extend(child_lines)
+ return lines
+ if kind in _OR:
+ lines = [indent + 'Any one of']
+ for child in node.args:
+ child_lines = _format_condition(child, policy, depth + 1, recovery)
+ if child_lines:
+ child_lines[0] = child_indent + '- ' + child_lines[0].lstrip()
+ lines.extend(child_lines)
+ return lines
+ if kind == 'thresh':
+ lines = [indent + '{} of {} conditions'.format(
+ node.value, len(node.args))]
+ for child in node.args:
+ child_lines = _format_condition(child, policy, depth + 1, recovery)
+ if child_lines:
+ child_lines[0] = child_indent + '- ' + child_lines[0].lstrip()
+ lines.extend(child_lines)
+ return lines
+ if kind == 'andor':
+ lines = [indent + 'Conditional path', child_indent + 'If']
+ lines.extend(_format_condition(node.args[0], policy, depth + 2, recovery))
+ lines.append(child_indent + 'Then also')
+ lines.extend(_format_condition(node.args[1], policy, depth + 2, recovery))
+ lines.append(child_indent + 'Otherwise')
+ lines.extend(_format_condition(node.args[2], policy, depth + 2, recovery))
+ return lines
+ if kind == '1':
+ return [indent + 'No additional condition']
+ if kind == '0':
+ return [indent + 'Unavailable branch']
+ # This should be unreachable for the currently accepted profile. Keeping a
+ # precise fragment name is safer than silently omitting a future fragment.
+ return [indent + 'Advanced condition: ' + kind]
+
+
+def _make_path(node):
+ # Only locks in the outer conjunction are unconditionally required.
+ # Nested alternatives and thresholds stay structural; enumerating all
+ # satisfactions could grow exponentially with the policy size.
+ locks = tuple((item.kind, item.value) for item in _flatten_conjunction(node)
+ if item.kind in ('older', 'after'))
+ return {
+ 'node': node,
+ 'keys': _key_indexes(node),
+ 'locks': locks,
+ 'conditional_locks': locks != tuple(policy_timelocks(node)),
+ }
+
+
+def policy_paths(policy):
+ paths = [_make_path(node) for node in _split_alternatives(policy.miniscript)]
+ # Descriptors preserve script order, not human priority. Coordinators such
+ # as Liana may serialize a delayed recovery branch before the immediately
+ # available branch. Keep each group stable, but review paths without
+ # unconditional locks before paths gated by a timelock.
+ return tuple(sorted(paths, key=lambda path: 1 if path['locks'] else 0))
+
+
+def _classify_simple_inheritance(policy, paths):
+ script_paths = paths
+ if len(script_paths) != 2:
+ return None
+ owned = policy.owned_key_indexes[0]
+ primary = None
+ recovery = None
+ for path in script_paths:
+ requirements = _simple_requirements(path['node'])
+ if requirements is None:
+ return None
+ keys = [item.value.index for item in requirements
+ if item.kind in ('pk_k', 'pk_h')]
+ locks = [(item.kind, item.value) for item in requirements
+ if item.kind in ('older', 'after')]
+ if keys == [owned] and not locks:
+ primary = path
+ elif len(keys) == 1 and keys[0] != owned and len(locks) == 1 and locks[0][0] == 'older':
+ recovery = path
+ if primary is None or recovery is None:
+ return None
+ return primary, recovery
+
+
+def _script_type(policy):
+ return 'Native SegWit (P2WSH)'
+
+
+def _network_name(policy):
+ return 'Bitcoin' if policy.network == 'BTC' else 'Bitcoin Testnet'
+
+
+def _path_requires_passport(policy, path):
+ result = _can_satisfy_without_key(path['node'], policy.owned_key_indexes[0])
+ if result is None:
+ return None
+ return not result
+
+
+def _simple_path_pages(policy, simple):
+ primary, recovery = simple
+ owned = policy.keys[policy.owned_key_indexes[0]]
+ recovery_index = recovery['keys'][0]
+ recovery_key = policy.keys[recovery_index]
+ lock_kind, lock_value = recovery['locks'][0]
+ short, exact, detail = describe_timelock(lock_kind, lock_value)
+ recovery_name = _escape(policy.key_names[recovery_index]) or 'Recovery key'
+ primary_page = (
+ '{}\n\n'
+ 'Passport can authorize spending by itself.\n'
+ 'No recovery delay is required.\n\n'
+ '{}\n{}\n\n'
+ 'This key matches the seed currently loaded on Passport.'
+ ).format('Spend with Passport', 'Passport key',
+ format_fingerprint(owned.fingerprint))
+ recovery_page = (
+ '{}\n\n'
+ '{} can spend by itself\n{}\nafter each coin confirms.\n\n'
+ '{}\n{}\n\n'
+ 'Passport can still spend by itself after the recovery key becomes available.\n\n'
+ '{}\n{}'
+ ).format('Spend with the recovery key', recovery_name, _highlight(short),
+ _highlight('Exact delay'), exact, 'Recovery key',
+ format_fingerprint(recovery_key.fingerprint))
+ timing_page = (
+ '{}\n\n'
+ '{}\n\n'
+ 'Block timing varies. Spending and returning change creates a new coin and restarts its timer.'
+ ).format('How the recovery delay works', detail)
+ return (primary_page, recovery_page, timing_page)
+
+
+def suggested_key_name(policy, key_index):
+ paths = policy_paths(policy)
+ simple = _classify_simple_inheritance(policy, paths)
+ if simple and key_index == simple[1]['keys'][0]:
+ return 'Recovery key'
+ return 'Key {}'.format(key_index + 1)
+
+
+def _flatten_conjunction(node):
+ """Return top-level AND requirements without changing their meaning."""
+ node = _unwrap(node)
+ if node.kind not in _AND:
+ return [node]
+ result = []
+ for child in node.args:
+ result.extend(_flatten_conjunction(child))
+ return result
+
+
+def _key_threshold(node):
+ """Return (required, key indexes) for a keys-only threshold."""
+ node = _unwrap(node)
+ if node.kind in ('pk_k', 'pk_h'):
+ return 1, (node.value.index,)
+ if node.kind == 'multi':
+ return node.value, tuple(key.index for key in node.args)
+ if node.kind == 'thresh':
+ indexes = []
+ for child in node.args:
+ child = _unwrap(child)
+ if child.kind not in ('pk_k', 'pk_h'):
+ return None
+ indexes.append(child.value.index)
+ return node.value, tuple(indexes)
+ return None
+
+
+def _path_key_threshold(path):
+ """Return a simple threshold for the path, when it has one."""
+ requirements = _flatten_conjunction(path['node'])
+ key_groups = []
+ for requirement in requirements:
+ requirement = _unwrap(requirement)
+ if requirement.kind in ('older', 'after'):
+ continue
+ threshold = _key_threshold(requirement)
+ if threshold is None:
+ return None
+ key_groups.append(threshold)
+
+ if not key_groups:
+ return None
+
+ # Separate ANDed key checks are equivalent to requiring every listed key.
+ if len(key_groups) > 1:
+ if any(required != 1 or len(indexes) != 1
+ for required, indexes in key_groups):
+ return None
+ indexes = tuple(indexes[0] for _, indexes in key_groups)
+ required = len(indexes)
+ else:
+ required, indexes = key_groups[0]
+
+ return required, indexes
+
+
+def _friendly_key_path(policy, path):
+ """Summarize common key thresholds without parser-shaped indentation."""
+ threshold = _path_key_threshold(path)
+ if threshold is None:
+ return None
+ required, indexes = threshold
+
+ if required == len(indexes) == 2:
+ summary = 'Both keys must sign'
+ elif required == len(indexes):
+ summary = 'All {} keys must sign'.format(len(indexes))
+ elif required == 1:
+ summary = 'Any 1 of {} keys must sign'.format(len(indexes))
+ else:
+ summary = 'Any {} of {} keys must sign'.format(required, len(indexes))
+
+ lines = [summary]
+ for key_index in indexes:
+ lines.extend([
+ '',
+ _key_role(policy, key_index),
+ format_fingerprint(policy.keys[key_index].fingerprint),
+ ])
+ return lines
+
+
+def _path_name(path):
+ if path['conditional_locks']:
+ name = 'Conditional timing'
+ elif len(path['locks']) == 1:
+ name = 'After {}'.format(describe_timelock(*path['locks'][0])[0])
+ elif path['locks']:
+ name = 'Delayed spending'
+ else:
+ name = 'Spend now'
+
+ threshold = _path_key_threshold(path)
+ if threshold is not None:
+ required, indexes = threshold
+ name += ' ({}-of-{})'.format(required, len(indexes))
+ return name
+
+
+def compatible_path_indexes(policy, tx_version, lock_time, sequence):
+ """Return paths whose timelocks are permitted by the transaction fields.
+
+ This does not claim that a timelock has matured. It only rules out paths
+ whose unconditional locks the signed transaction cannot satisfy. Nested
+ conditional locks are shown structurally and do not exclude the whole path.
+ """
+ compatible = []
+ for index, path in enumerate(policy_paths(policy)):
+ allowed = True
+ for kind, value in path['locks']:
+ if kind == 'older':
+ # BIP68/112: version 2, disable flag clear, matching time or
+ # height units, and a sequence value at least as large.
+ if tx_version < 2 or sequence & (1 << 31):
+ allowed = False
+ break
+ type_flag = 1 << 22
+ if sequence & type_flag != value & type_flag or \
+ sequence & 0xffff < value & 0xffff:
+ allowed = False
+ break
+ elif kind == 'after':
+ # BIP65: a final sequence disables locktime, and height/time
+ # lock types cannot be mixed.
+ if sequence == 0xffffffff or \
+ (lock_time < 500000000) != (value < 500000000) or \
+ lock_time < value:
+ allowed = False
+ break
+ if allowed:
+ compatible.append(index)
+ return tuple(compatible)
+
+
+def _generic_path_page(policy, path):
+ requires = _path_requires_passport(policy, path)
+ locks = path['locks']
+ conditional = path['conditional_locks']
+ if conditional:
+ heading = 'Conditional timing'
+ elif locks:
+ heading = 'Delayed spending'
+ else:
+ heading = 'Spend now'
+ lines = [_highlight(heading) if not locks and not conditional else heading, '']
+
+ if conditional:
+ lines.extend(['Timing depends on the branch used.',
+ 'Review all conditions below.', ''])
+ elif locks:
+ for lock_position, (kind, value) in enumerate(locks):
+ short, exact, _ = describe_timelock(kind, value)
+ if lock_position:
+ lines.append('')
+ lines.extend([
+ 'Available after',
+ _highlight(short),
+ '',
+ _highlight('Exact delay' if kind == 'older'
+ else 'Exact condition'),
+ exact,
+ ])
+ friendly = _friendly_key_path(policy, path)
+ if locks:
+ lines.append('')
+ if friendly is None:
+ lines.extend(_format_condition(path['node'], policy))
+ else:
+ lines.extend(friendly)
+ if requires is False:
+ lines.append('')
+ if any(key_index in policy.owned_key_indexes for key_index in path['keys']):
+ lines.append('This Passport is optional.')
+ else:
+ lines.append('This Passport is not used.')
+ elif requires is True and friendly is None:
+ lines.extend(['', 'This Passport must sign.'])
+ else:
+ if friendly is None:
+ lines.extend(['', 'Review the conditional branches carefully.'])
+ return '\n'.join(lines)
+
+
+def format_review_pages(policy):
+ paths = policy_paths(policy)
+ simple = _classify_simple_inheritance(policy, paths)
+ kind = 'Simple inheritance' if simple else 'Custom wallet policy'
+ overview = (
+ '{}\n{}\n\n{}\n\n{}\n\n{}\n{}\n\n{} {}'
+ ).format(_highlight('Policy Name'), _escape(policy.name), kind,
+ _network_name(policy), _highlight('Script Type'),
+ _script_type(policy), _highlight(str(len(paths))),
+ 'way to spend' if len(paths) == 1 else 'ways to spend')
+
+ pages = [overview]
+ if simple:
+ pages.extend(_simple_path_pages(policy, simple))
+ else:
+ for path in paths:
+ pages.append(_generic_path_page(policy, path))
+
+ 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 = '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))
+
+ pages.append((
+ '{}\n\n'
+ 'Your seed recovers this Passport key, not the policy.\n\n'
+ 'Keep a separate copy.'
+ ).format('Back up this policy'))
+ return tuple(pages)
+
+
+def format_confirmation(policy):
+ paths = policy_paths(policy)
+ simple = _classify_simple_inheritance(policy, paths)
+ if simple:
+ _, recovery = simple
+ key = policy.keys[recovery['keys'][0]]
+ short, _, _ = describe_timelock(*recovery['locks'][0])
+ return (
+ 'Passport can spend by itself with no recovery delay.\n\n'
+ '{} {}\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)
+ text = _plural(len(paths), 'spending path')
+ if bypass:
+ text += '\n{} without Passport'.format(bypass)
+ return text
+
+
+def format_signing_pages(policy, compatible_indexes=None):
+ all_paths = policy_paths(policy)
+ paths = all_paths
+ if compatible_indexes is not None:
+ filtered = tuple(all_paths[index] for index in compatible_indexes
+ if 0 <= index < len(all_paths))
+ if not filtered:
+ return (('Wallet\n{}\n\n'
+ 'At least one input has no spending path compatible with this transaction.\n\n'
+ 'Signing does not make it spendable. Check the transaction in your wallet app.')
+ .format(_escape(policy.name)),)
+ paths = filtered
+ simple = _classify_simple_inheritance(policy, paths)
+ owned = policy.keys[policy.owned_key_indexes[0]]
+ if simple:
+ return ((
+ 'Signing path\n\n'
+ 'Wallet\n{}\n\n'
+ 'Passport is authorizing this transaction with its own key.\n'
+ 'No recovery delay is required.\n\n'
+ 'Passport key\n{}\n\n'
+ 'The recovery key is not being used.'
+ ).format(_escape(policy.name), format_fingerprint(owned.fingerprint)),)
+
+ if len(paths) == 1 and policy.owned_key_indexes[0] in paths[0]['keys']:
+ friendly = _friendly_key_path(policy, paths[0])
+ if friendly is not None:
+ return (('\n'.join([
+ 'Wallet',
+ _escape(policy.name),
+ '',
+ _path_name(paths[0]),
+ '',
+ ] + friendly)),)
+
+ roles = []
+ for path in paths:
+ if policy.owned_key_indexes[0] in path['keys']:
+ requires = _path_requires_passport(policy, path)
+ if requires is True:
+ role = 'required'
+ elif requires is False:
+ role = 'optional'
+ else:
+ role = 'may be required'
+ roles.append('{}: {}'.format(_path_name(path), role))
+ summary = (
+ 'Wallet\n{}\n\n'
+ 'This Passport will sign:\n{}\n\n'
+ 'Key: {}\n\n'
+ 'Your wallet app chooses which valid option completes the transaction.'
+ ).format(_escape(policy.name), '\n'.join(roles),
+ format_fingerprint(owned.fingerprint))
+ conditional_pages = tuple(_generic_path_page(policy, path) for path in paths
+ if path['conditional_locks'] and
+ policy.owned_key_indexes[0] in path['keys'])
+ return (summary,) + conditional_pages
### ports/stm32/boards/Passport/modules/policy_errors.py
@@ -0,0 +1,42 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+
+class WalletPolicyError(ValueError):
+ """Base class for policy failures that are safe to show to the user."""
+
+ def __init__(self, code, message, position=None):
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.position = position
+
+ def __str__(self):
+ if self.position is None:
+ return self.message
+ return '{} at character {}'.format(self.message, self.position)
+
+
+class PolicyParseError(WalletPolicyError):
+ def __init__(self, message, position=None):
+ super().__init__('parse_error', message, position)
+
+
+class PolicyTypeError(WalletPolicyError):
+ def __init__(self, message):
+ super().__init__('type_error', message)
+
+
+class UnsupportedPolicyError(WalletPolicyError):
+ def __init__(self, message):
+ super().__init__('unsupported_policy', message)
+
+
+class PolicyResourceError(WalletPolicyError):
+ def __init__(self, message):
+ super().__init__('resource_limit', message)
+
+
+class PolicyMismatchError(WalletPolicyError):
+ def __init__(self, message):
+ super().__init__('policy_mismatch', message)
### ports/stm32/boards/Passport/modules/policy_multisig.py
@@ -0,0 +1,81 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""WalletPolicy adapter for Passport's existing MultisigWallet records."""
+
+from policy_errors import PolicyMismatchError
+from wallet_policy import DerivedPolicyOutput
+
+
+def _sha256(data):
+ try:
+ import trezorcrypto
+ return trezorcrypto.sha256(data).digest()
+ except ImportError: # pragma: no cover - CPython host tests
+ import hashlib
+ return hashlib.sha256(data).digest()
+
+
+def _hash160(data):
+ try:
+ import trezorcrypto
+ first = trezorcrypto.sha256(data).digest()
+ return trezorcrypto.ripemd160(first).digest()
+ except ImportError: # pragma: no cover - CPython host tests
+ import hashlib
+ first = hashlib.sha256(data).digest()
+ return hashlib.new('ripemd160', first).digest()
+
+
+class StandardMultisigPolicy:
+ """Expose legacy M-of-N records through the wallet-policy derivation API."""
+
+ __slots__ = ('wallet', 'name', 'network', 'policy_id', 'kind')
+
+ def __init__(self, wallet):
+ self.wallet = wallet
+ self.name = wallet.name
+ self.network = wallet.chain_type
+ self.policy_id = 'legacy-multisig:{}'.format(wallet.id)
+ self.kind = 'standard_multisig'
+
+ def derive(self, branch, index, chain=None, key_resolver=None):
+ if branch not in (0, 1):
+ raise ValueError('branch must be receive (0) or change (1)')
+ chain = chain or self.wallet.chain
+ if getattr(chain, 'ctype', None) != self.network:
+ raise PolicyMismatchError('Multisig network does not match the active network')
+ derived_index, _, address, script = next(
+ self.wallet.yield_addresses(index, 1, change_idx=branch))
+ if derived_index != index:
+ raise PolicyMismatchError('Multisig address derivation returned the wrong index')
+
+ from public_constants import AF_P2SH, AF_P2WSH, AF_P2WSH_P2SH
+ address_format = self.wallet.addr_fmt
+ if address_format == AF_P2WSH:
+ witness_script = script
+ redeem_script = None
+ script_pubkey = b'\x00\x20' + _sha256(script)
+ elif address_format == AF_P2WSH_P2SH:
+ witness_script = script
+ redeem_script = b'\x00\x20' + _sha256(script)
+ script_pubkey = b'\xa9\x14' + _hash160(redeem_script) + b'\x87'
+ elif address_format == AF_P2SH:
+ witness_script = None
+ redeem_script = script
+ script_pubkey = b'\xa9\x14' + _hash160(script) + b'\x87'
+ else:
+ raise PolicyMismatchError('Unsupported legacy multisig address format')
+ return DerivedPolicyOutput(self.policy_id, branch, index, witness_script,
+ script_pubkey, address, redeem_script)
+
+ def match_scripts(self, branch, index, utxo_script_pubkey,
+ witness_script=None, redeem_script=None, chain=None):
+ derived = self.derive(branch, index, chain)
+ if bytes(utxo_script_pubkey) != derived.script_pubkey:
+ raise PolicyMismatchError('UTXO script does not match the registered multisig wallet')
+ if witness_script is not None and bytes(witness_script) != derived.witness_script:
+ raise PolicyMismatchError('Witness script does not match the registered multisig wallet')
+ if redeem_script is not None and bytes(redeem_script) != derived.redeem_script:
+ raise PolicyMismatchError('Redeem script does not match the registered multisig wallet')
+ return derived
### ports/stm32/boards/Passport/modules/policy_transport.py
@@ -0,0 +1,201 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Versioned QR/microSD transport for registered wallet policies."""
+
+try:
+ import ujson as json
+except ImportError: # pragma: no cover - CPython host tests
+ import json
+
+try:
+ from ubinascii import hexlify
+except ImportError: # pragma: no cover - CPython host tests
+ from binascii import hexlify
+
+from policy_errors import PolicyMismatchError, PolicyParseError, PolicyResourceError
+from wallet_policy import (KeyInfo, MiniscriptPolicy,
+ descriptor_to_policy_template)
+
+
+TRANSPORT_FORMAT = 'passport-wallet-policy'
+TRANSPORT_VERSION = 1
+MAX_TRANSPORT_LENGTH = 4096
+ADDRESS_FORMAT = 'passport-address-verification'
+ADDRESS_RESPONSE_FORMAT = 'passport-address-verification-response'
+MAX_ADDRESS_INDEX = 0x7fffffff
+
+
+def bounded_transport_read(fd):
+ """Bound a policy/address microSD read before allocating its contents."""
+ return fd.read(MAX_TRANSPORT_LENGTH + 1)
+
+
+def _fingerprint_text(master_xfp):
+ return hexlify(master_xfp.to_bytes(4, 'little')).decode('ascii')
+
+
+def discover_owned_key(keys, chain, master_xfp, derive_node):
+ expected_fingerprint = _fingerprint_text(master_xfp)
+ matches = []
+ from public_constants import AF_P2SH
+ for index, key in enumerate(keys):
+ if key.fingerprint != expected_fingerprint:
+ continue
+ node = derive_node(key.path)
+ try:
+ if chain.serialize_public(node, AF_P2SH) == key.xpub:
+ matches.append(index)
+ finally:
+ try:
+ from stash import blank_object
+ blank_object(node)
+ except ImportError: # pragma: no cover - CPython host tests
+ pass
+ if len(matches) != 1:
+ raise PolicyMismatchError(
+ 'Policy must contain exactly one extended key belonging to this Passport')
+ return tuple(matches)
+
+
+def _infer_standard_xpub_network(keys):
+ networks = set()
+ for key in keys:
+ if key.xpub.startswith('xpub'):
+ networks.add('BTC')
+ elif key.xpub.startswith('tpub'):
+ networks.add('TBTC')
+ if len(networks) > 1:
+ raise PolicyParseError('Wallet policy mixes mainnet and testnet extended keys')
+ return next(iter(networks)) if networks else None
+
+
+def _network_mismatch_message(network):
+ name = 'Bitcoin mainnet' if network == 'BTC' else 'Bitcoin Testnet'
+ return 'This wallet is for {}. Switch Passport to that network before importing.'.format(name)
+
+
+def _transport_text(data, invalid_utf8_message):
+ # Foundation's UR `bytes` registry binding unwraps to a MicroPython
+ # bytearray backed by the decoded value. microSD reads return bytes. Treat
+ # both transports identically before applying the bounded text parser.
+ if isinstance(data, bytearray):
+ data = bytes(data)
+ if isinstance(data, bytes):
+ try:
+ return data.decode('utf-8')
+ except UnicodeError:
+ raise PolicyParseError(invalid_utf8_message)
+ return data
+
+
+def decode_policy_transport(data, chain, master_xfp, derive_node,
+ default_name='Wallet Policy'):
+ 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')
+
+ policy_id = None
+ if data.startswith('{'):
+ try:
+ envelope = json.loads(data)
+ except BaseException:
+ raise PolicyParseError('Wallet policy JSON is invalid')
+ if not isinstance(envelope, dict):
+ raise PolicyParseError('Wallet policy JSON must be an object')
+ if envelope.get('format') != TRANSPORT_FORMAT or envelope.get('version') != TRANSPORT_VERSION:
+ raise PolicyParseError('Unsupported wallet policy transport version')
+ name = envelope.get('name', default_name)
+ network = envelope.get('network')
+ template = envelope.get('template')
+ if not all(isinstance(value, str) for value in (name, network, template)):
+ raise PolicyParseError('Wallet policy name, network and template must be text')
+ name = name or default_name
+ raw_keys = envelope.get('keys')
+ if not isinstance(raw_keys, list):
+ raise PolicyParseError('Wallet policy key vector is missing')
+ keys = tuple(KeyInfo.parse(value) for value in raw_keys)
+ policy_id = envelope.get('policy_id')
+ 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)
+
+ 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)
+ policy.validate_extended_keys(chain)
+ policy.verify_owned_key(chain, derive_node)
+ if policy_id is not None and policy_id != policy.policy_id:
+ raise PolicyParseError('Transport policy identity does not match its contents')
+ return policy
+
+
+def encode_policy_transport(policy):
+ return json.dumps({
+ 'format': TRANSPORT_FORMAT,
+ 'version': TRANSPORT_VERSION,
+ 'name': policy.name,
+ 'network': policy.network,
+ 'template': policy.template,
+ 'keys': [key.canonical() for key in policy.keys],
+ 'policy_id': policy.policy_id,
+ })
+
+
+def decode_address_request(data, chain, registry, expected_policy_id=None):
+ data = _transport_text(data, 'Address verification request is not UTF-8 text')
+ if not isinstance(data, str) or not data or len(data) > MAX_TRANSPORT_LENGTH:
+ raise PolicyResourceError('Address verification request is empty or too large')
+ try:
+ request = json.loads(data)
+ except BaseException:
+ raise PolicyParseError('Address verification request JSON is invalid')
+ expected_fields = {
+ 'format', 'version', 'network', 'policy_id',
+ 'descriptor_checksum', 'branch', 'index'}
+ if not isinstance(request, dict) or set(request.keys()) != expected_fields:
+ raise PolicyParseError('Address verification request fields are invalid')
+ if request.get('format') != ADDRESS_FORMAT or request.get('version') != TRANSPORT_VERSION:
+ raise PolicyParseError('Unsupported address verification request version')
+ network = request.get('network')
+ if network != getattr(chain, 'ctype', None):
+ raise PolicyMismatchError(_network_mismatch_message(network))
+ policy_id = request.get('policy_id')
+ if expected_policy_id is not None and policy_id != expected_policy_id:
+ raise PolicyMismatchError('Address request is for a different wallet policy')
+ policy = registry.get(policy_id)
+ if policy is None:
+ raise PolicyMismatchError('Wallet policy is not registered on this Passport')
+ checksum = request.get('descriptor_checksum')
+ if not isinstance(checksum, str) or checksum.lower() != policy.descriptor_check().lower():
+ raise PolicyMismatchError('Policy checksum does not match the registered wallet')
+ branch = request.get('branch')
+ index = request.get('index')
+ if branch not in (0, 1) or isinstance(branch, bool):
+ raise PolicyParseError('Address branch must be receive (0) or change (1)')
+ if not isinstance(index, int) or isinstance(index, bool) or not 0 <= index <= MAX_ADDRESS_INDEX:
+ raise PolicyParseError('Address index is outside the supported range')
+ derived = policy.derive(branch, index, chain)
+ if not derived.address:
+ raise PolicyMismatchError('Passport could not derive this policy address')
+ return request, policy, derived.address
+
+
+def encode_address_response(request, address, fingerprint):
+ return json.dumps({
+ 'format': ADDRESS_RESPONSE_FORMAT,
+ 'version': TRANSPORT_VERSION,
+ 'network': request['network'],
+ 'policy_id': request['policy_id'],
+ 'descriptor_checksum': request['descriptor_checksum'].lower(),
+ 'branch': request['branch'],
+ 'index': request['index'],
+ 'address': address,
+ 'fingerprint': fingerprint.lower(),
+ })
### ports/stm32/boards/Passport/modules/psbt.py
@@ -307,8 +307,12 @@ def parse_subpaths(self, my_xfp):
# parse leaf hashes and path
v = self.get(self.tap_subpaths[pk])
(num_tap_hashes, compact_length) = deser_compact_size_bytes(v)
- tap_hashes = [uint256_from_bytes(v[i * 32:(i + 1) * 32]) for i in range(0, num_tap_hashes)]
- v = v[(num_tap_hashes * 32 + compact_length):]
+ hashes_start = compact_length
+ hashes_end = hashes_start + num_tap_hashes * 32
+ assert hashes_end <= len(v), 'corrupt taproot leaf hashes'
+ tap_hashes = [v[hashes_start + i * 32:hashes_start + (i + 1) * 32]
+ for i in range(num_tap_hashes)]
+ v = v[hashes_end:]
vl = len(v)
# Master key can be used if there is no tapscript tree
@@ -336,10 +340,11 @@ def parse_subpaths(self, my_xfp):
# Track details of each output of PSBT
#
class psbtOutputProxy(psbtProxy):
- no_keys = {PSBT_OUT_REDEEM_SCRIPT, PSBT_OUT_WITNESS_SCRIPT}
+ no_keys = {PSBT_OUT_REDEEM_SCRIPT, PSBT_OUT_WITNESS_SCRIPT,
+ PSBT_OUT_TAP_INTERNAL_KEY, PSBT_OUT_TAP_TREE}
blank_flds = ('unknowns', 'subpaths', 'redeem_script', 'witness_script',
'is_change', 'num_our_keys', 'tap_internal_key', 'tap_tree',
- 'tap_subpaths')
+ 'tap_subpaths', 'policy_branch', 'policy_address_index')
def __init__(self, fd, idx):
super().__init__()
@@ -403,7 +408,7 @@ def wr(*a):
for k in self.unknowns:
self.write(out_fd, k[0], self.unknowns[k], k[1:], raw=True)
- def validate(self, out_idx, txo, my_xfp, active_multisig):
+ def validate(self, out_idx, txo, my_xfp, active_multisig, active_policy=None):
# Do things make sense for this output?
# NOTE: We might think it's a change output just because the PSBT
@@ -426,6 +431,13 @@ def validate(self, out_idx, txo, my_xfp, active_multisig):
# - must match expected address for this output, coming from unsigned txn
addr_type, addr_or_pubkey, is_segwit = txo.get_address()
+ if active_policy and not (active_policy.context == 'wsh' and
+ addr_type == 'p2sh' and is_segwit):
+ # Owning a destination key does not preserve the policy's spending
+ # conditions. Only an exact policy match may be hidden as change.
+ self.is_change = False
+ return
+
if self.subpaths and len(self.subpaths) == 1:
# p2pk, p2pkh, p2wpkh cases
expect_pubkey, = self.subpaths.keys()
@@ -439,7 +451,9 @@ def validate(self, out_idx, txo, my_xfp, active_multisig):
expected_addr_format = expected_single_sig_addr_format(tap_path)
is_script_wallet_path = False
else:
- # p2wsh/p2sh cases need full set of pubkeys, and therefore redeem script
+ # P2WSH/P2SH cases need the full set of pubkeys. Registered wallet
+ # policies can reconstruct the output script from those exact
+ # derivations; legacy multisig still needs the PSBT script field.
expect_pubkey = None
expected_addr_format = None
is_script_wallet_path = False
@@ -470,9 +484,31 @@ def validate(self, out_idx, txo, my_xfp, active_multisig):
redeem_script = self.get(self.redeem_script) if self.redeem_script else None
witness_script = self.get(self.witness_script) if self.witness_script else None
+ if is_segwit and active_policy:
+ # Registered wallet policies are authoritative. Re-derive the
+ # complete script and every key path. A coordinator may omit
+ # PSBT_OUT_WITNESS_SCRIPT for change; the stored policy plus the
+ # complete derivation map is sufficient to verify the output.
+ # If a witness script is present, match_derivations also checks
+ # it exactly.
+ from policy_errors import WalletPolicyError
+ try:
+ import chains
+ derived, _, _ = active_policy.match_derivations(
+ self.subpaths, txo.scriptPubKey, witness_script,
+ chains.current_chain(), my_xfp)
+ except (WalletPolicyError, ValueError, TypeError, KeyError) as exc:
+ raise FraudulentChangeOutput(
+ out_idx, "Wallet policy change output does not match: %s" % exc)
+ self.policy_branch = derived.branch
+ self.policy_address_index = derived.index
+ # branch is the multipath index, so /<2;3>/* uses 1 for change.
+ self.is_change = derived.branch == 1
+ return
+
if not redeem_script and not witness_script:
- # Perhaps an omission, so let's not call fraud on it
- # But definitely required, else we don't know what script we're sending to.
+ # Legacy P2SH/P2WSH validation cannot reconstruct an arbitrary
+ # script from derivations alone.
raise FatalPSBTIssue("Missing redeem/witness script for output #%d" % out_idx)
if not is_segwit and redeem_script and \
@@ -583,7 +619,9 @@ class psbtInputProxy(psbtProxy):
'redeem_script', 'witness_script', 'fully_signed',
'is_segwit', 'is_multisig', 'is_p2sh', 'num_our_keys',
'required_key', 'scriptSig', 'amount', 'scriptCode', 'added_sig',
- 'tap_internal_key', 'tap_key_sig', 'tap_merkle_root')
+ 'added_sigs',
+ 'tap_internal_key', 'tap_key_sig', 'tap_merkle_root',
+ 'policy_spend_plan')
def __init__(self, fd, idx):
super().__init__()
@@ -762,6 +800,7 @@ def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt):
self.is_multisig = False
self.is_p2sh = False
which_key = None
+ matched_policy = False
addr_type, addr_or_pubkey, addr_is_segwit = utxo.get_address()
if addr_is_segwit and not self.is_segwit:
@@ -835,38 +874,86 @@ def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt):
elif addr_type == 'p2tr':
# input is an x-only public key or merkle tree root
- # TODO: handle tapscript tree
self.scriptSig = utxo.scriptPubKey
if len(self.tap_subpaths) == 1: # No script path
subpath = list(self.tap_subpaths.items())[0]
pubkey, (path, tap_hashes) = subpath
- tweaked_pubkey = output_script(pubkey, None)[2:]
- if path[0] == my_xfp and tweaked_pubkey == addr_or_pubkey:
+ tweaked_pubkey = output_script(pubkey, None)[2:] if not tap_hashes else None
+ if not self.tap_leaf_scripts and path and path[0] == my_xfp and \
+ tweaked_pubkey == addr_or_pubkey:
which_key = pubkey
+
+ if self.tap_leaf_scripts or any(hashes for _, hashes in self.tap_subpaths.values()):
+ raise FatalPSBTIssue('Taproot script-path signing is not supported')
else:
# we don't know how to "solve" this type of input
pass
- if self.is_multisig and which_key:
+ if addr_is_segwit and self.witness_script and self.is_multisig and which_key:
+ # Native P2WSH registered policies are matched before the legacy
+ # CHECKMULTISIG disassembler. Only an immutable SpendPlan crosses
+ # from policy parsing into the signing task.
+ from common import settings
+ policy_records = settings.get('wallet_policies', [])
+ if policy_records:
+ from wallet_policy import WalletPolicyRegistry
+ import chains
+ matches = []
+ for policy in WalletPolicyRegistry(settings).iter_policies(xfp2str(my_xfp).lower()):
+ try:
+ plan = policy.make_spend_plan(
+ my_idx, self.subpaths, utxo.scriptPubKey,
+ redeem_script, chains.current_chain(), my_xfp,
+ self.sighash)
+ matches.append((policy, plan))
+ except MemoryError:
+ raise
+ except Exception:
+ pass
+ if len(matches) > 1:
+ raise FatalPSBTIssue('Input #%d matches multiple wallet policies' % my_idx)
+ if matches:
+ policy, plan = matches[0]
+ if psbt.active_multisig:
+ raise FatalPSBTIssue('Cannot mix registered wallet policy and legacy multisig inputs')
+ if psbt.active_policy and psbt.active_policy.policy_id != policy.policy_id:
+ raise FatalPSBTIssue('Cannot sign inputs from multiple wallet policies')
+ psbt.active_policy = policy
+ self.policy_spend_plan = plan
+ unsigned_keys = set(plan.expected_pubkeys) - set(self.part_sig)
+ which_key = unsigned_keys or None
+ matched_policy = True
+
+ if not matched_policy:
+ from opcodes import OP_CHECKMULTISIG
+ if not redeem_script or redeem_script[-1] != OP_CHECKMULTISIG:
+ raise FatalPSBTIssue('Unknown registered wallet policy for input #%d' % my_idx)
+
+ if self.is_multisig and which_key and not matched_policy:
# We will be signing this input, so
# - find which wallet it is or
# - check it's the right M/N to match redeem script
# print("redeem: %s" % b2a_hex(redeem_script))
M, N = disassemble_multisig_mn(redeem_script)
+ assert 1 <= M <= N <= MAX_SIGNERS, 'M/N range'
xfp_paths = sorted(self.subpaths.values())
if not psbt.active_multisig:
- # search for multisig wallet
- wal = MultisigWallet.find_match(M, N, xfp_paths)
- if not wal:
+ if psbt.active_policy:
+ raise FatalPSBTIssue('Cannot mix legacy multisig and registered wallet policy inputs')
+ # Only activate/import a legacy wallet after exact registered
+ # policy matching has declined this input.
+ if psbt.xpubs:
+ psbt.handle_xpubs(M, N)
+ if not psbt.active_multisig:
+ psbt.active_multisig = MultisigWallet.find_match(M, N, xfp_paths)
+ if not psbt.active_multisig:
raise FatalPSBTIssue('Unknown multisig wallet')
- psbt.active_multisig = wal
- else:
- # check consistent w/ already selected wallet
- psbt.active_multisig.assert_matching(M, N, xfp_paths)
+ # Check the actual input even when global XPUBs selected the wallet.
+ psbt.active_multisig.assert_matching(M, N, xfp_paths)
# validate redeem script, by disassembling it and checking all pubkeys
try:
@@ -993,6 +1080,9 @@ def wr(*a):
if self.added_sig:
pubkey, sig = self.added_sig
wr(PSBT_IN_PARTIAL_SIG, sig, pubkey)
+ if self.added_sigs:
+ for pubkey, sig in self.added_sigs.items():
+ wr(PSBT_IN_PARTIAL_SIG, sig, pubkey)
if self.sighash is not None:
wr(PSBT_IN_SIGHASH_TYPE, pack('<I', self.sighash))
@@ -1009,12 +1099,22 @@ def wr(*a):
if self.tap_key_sig:
wr(PSBT_IN_TAP_KEY_SIG, self.tap_key_sig)
+ for k in self.tap_script_sigs:
+ wr(PSBT_IN_TAP_SCRIPT_SIG, self.tap_script_sigs[k], k)
+
+ for control_block in self.tap_leaf_scripts:
+ wr(PSBT_IN_TAP_LEAF_SCRIPT, self.tap_leaf_scripts[control_block],
+ control_block)
+
for k in self.tap_subpaths:
wr(PSBT_IN_TAP_BIP32_DERIVATION, self.tap_subpaths[k], k)
if self.tap_internal_key:
wr(PSBT_IN_TAP_INTERNAL_KEY, self.tap_internal_key)
+ if self.tap_merkle_root:
+ wr(PSBT_IN_TAP_MERKLE_ROOT, self.tap_merkle_root)
+
for k in self.unknowns:
self.write(out_fd, k[0], self.unknowns[k], k[1:], raw=True)
@@ -1066,6 +1166,7 @@ def __init__(self):
# this points to a MS wallet, during operation
# - we are only supporting a single multisig wallet during signing
self.active_multisig = None
+ self.active_policy = None
self.warnings = []
@@ -1201,33 +1302,11 @@ def input_witness_iter(self):
for in_idx in range(self.num_inputs):
yield in_idx, CTxInWitness()
- def guess_M_of_N(self):
- # Peek at the inputs to see if we can guess M/N value. Just takes
- # first one it finds.
- #
- from opcodes import OP_CHECKMULTISIG
- for i in self.inputs:
- ks = i.witness_script or i.redeem_script
- if not ks:
- continue
-
- rs = i.get(ks)
- if rs[-1] != OP_CHECKMULTISIG:
- continue
-
- M, N = disassemble_multisig_mn(rs)
- assert 1 <= M <= N <= MAX_SIGNERS
-
- return (M, N)
-
- # not multisig, probably
- return None, None
-
- async def handle_xpubs(self):
- # Lookup correct wallet based on xpubs in globals
- # - only happens if they volunteered this 'extra' data
- # - do not assume multisig
+ def handle_xpubs(self, M, N):
+ # Discover a legacy wallet for an input that did not match a registered
+ # policy. Global metadata alone must never activate a legacy wallet.
assert not self.active_multisig
+ assert not self.active_policy
xfp_paths = []
has_mine = 0
@@ -1248,15 +1327,6 @@ async def handle_xpubs(self):
# exact match (by xfp+deriv set) .. normal case
self.active_multisig = candidates[0]
else:
- # don't want to guess M if not needed, but we need it
- M, N = self.guess_M_of_N()
-
- if not N:
- # not multisig, but we can still verify:
- # - XFP should be one of ours (checked above).
- # - too slow to re-derive it here, so nothing more to validate at this point
- return
-
assert N == len(xfp_paths)
for c in candidates:
@@ -1314,12 +1384,6 @@ async def validate(self):
assert len(self.inputs) == self.num_inputs, 'ni mismatch'
- # if multisig xpub details provided, they better be right and/or offer import
- # print('self.xpubs={}'.format(self.xpubs))
- if self.xpubs:
- # print('calling self.handle_xpubs()')
- await self.handle_xpubs()
-
gc.collect()
assert self.num_outputs >= 1, 'need outs'
@@ -1339,7 +1403,8 @@ def consider_outputs(self):
total_change = 0
# print('len(self.outputs)={}'.format(len(self.outputs)))
for idx, txo in self.output_iter():
- self.outputs[idx].validate(idx, txo, self.my_xfp, self.active_multisig)
+ self.outputs[idx].validate(idx, txo, self.my_xfp, self.active_multisig,
+ self.active_policy)
if self.outputs[idx].is_change:
total_change += txo.nValue
@@ -1450,6 +1515,13 @@ def hard_bits(p):
for nout, out in enumerate(self.outputs):
if not out.is_change:
continue
+ if self.active_policy is not None and out.policy_branch is not None:
+ # validate() has already reconstructed this output from the
+ # registered descriptor and compared its complete script and
+ # derivation map. That exact check is stronger than the legacy
+ # {0,1}/index-gap heuristic below and also supports multipath
+ # policies such as Liana's {0,1} and {2,3} branches.
+ continue
# it's a change output, okay if a p2sh change; we're looking at paths
paths = []
if out.subpaths:
@@ -1834,7 +1906,8 @@ def make_txn_segwit_sighash(self, replace_idx, replacement, amount, scriptCode,
# double SHA256
return trezorcrypto.sha256(rv.digest()).digest()
- def make_txn_taproot_sighash(self, input_idx, sighash_type, annex=None, ext_flag=0):
+ def make_txn_taproot_sighash(self, input_idx, sighash_type, annex=None,
+ ext_flag=0):
# Implement BIP 341 hashing algo for signature of segwit programs.
# see <https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#signature-validation-rules>
@@ -1845,6 +1918,7 @@ def make_txn_taproot_sighash(self, input_idx, sighash_type, annex=None, ext_flag
# its leading hash_type byte below, and taproot_sign_key() appends it to the
# signature for anything but SIGHASH_DEFAULT (BIP-341)
assert sighash_type in VALID_SIGHASHES, 'Unsupported sighash type for taproot input'
+ assert ext_flag == 0, 'Taproot script-path signing is not supported'
if self.tap_hashPrevouts is None:
# First time thru, we'll need to hash up this stuff.
@@ -1896,9 +1970,6 @@ def make_txn_taproot_sighash(self, input_idx, sighash_type, annex=None, ext_flag
if annex is not None:
data += trezorcrypto.sha256(ser_string(annex)).digest()
- # TODO: support bip342 script extensions:
- # see <https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#common-signature-message-extension>
-
fd.seek(old_pos)
return tagged_hash('TapSighash', bytes([0]) + data)
### ports/stm32/boards/Passport/modules/psbt_display.py
@@ -0,0 +1,95 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""User-facing PSBT messages kept separate from parser diagnostics."""
+
+
+def format_psbt_error(message):
+ """Return a friendly explanation and, when useful, the original detail."""
+ message = str(message or 'Unknown PSBT error')
+ lower = message.lower()
+
+ if ('missing redeem/witness script' in lower or
+ 'need witness script' in lower):
+ if 'output' in lower:
+ friendly = (
+ 'This PSBT is missing information Passport needs to verify a change output.\n\n'
+ 'Re-export it from your wallet coordinator with the complete witness or redeem script.'
+ )
+ else:
+ friendly = (
+ 'This PSBT is missing information Passport needs to verify how an input can be spent.\n\n'
+ 'Re-export it from your wallet coordinator with the complete witness or redeem script.'
+ )
+ return friendly, message
+
+ if 'unknown registered wallet policy' in lower:
+ return (
+ 'Passport cannot match this transaction to a registered wallet policy.\n\n'
+ 'Register the exact policy used by your wallet coordinator, then try again.',
+ message,
+ )
+
+ if 'wallet policy change output does not match' in lower:
+ return (
+ 'A change output does not match the registered wallet policy.\n\n'
+ 'Do not sign. Check the wallet in your coordinator and create the transaction again.',
+ message,
+ )
+
+ if ('does not match the registered policy' in lower or
+ 'do not match the registered policy' in lower or
+ 'registered policy belongs to another seed' in lower or
+ 'matches multiple wallet policies' in lower):
+ return (
+ 'This transaction does not match the registered wallet policy and Passport key.\n\n'
+ 'Do not sign. Check the policy in your wallet coordinator and on Passport, then '
+ 'create the transaction again.',
+ message,
+ )
+
+ if ('multiple wallet policies' in lower or
+ 'mix registered wallet policy' in lower or
+ 'mix legacy multisig and registered wallet policy' in lower):
+ return (
+ 'This transaction combines inputs from incompatible wallet configurations.\n\n'
+ 'Create a transaction using one registered wallet policy and try again.',
+ message,
+ )
+
+ if lower.startswith('invalid psbt:'):
+ return (
+ 'Passport could not read this PSBT.\n\n'
+ 'Create a new PSBT in your wallet coordinator and try again.',
+ message,
+ )
+
+ return message, None
+
+
+def format_signed_psbt_message(updated_path, finalized_path=None, txid=None):
+ """Explain exactly what Passport produced and what the user should do next."""
+ lines = [
+ 'Passport signature added',
+ '',
+ 'Updated PSBT',
+ str(updated_path),
+ '',
+ ]
+ if finalized_path:
+ lines.extend([
+ 'Next step',
+ 'Return the updated PSBT to your wallet coordinator to finalize and broadcast.',
+ '',
+ 'Passport also saved a finalized transaction that is ready to broadcast.',
+ str(finalized_path),
+ ])
+ if txid:
+ lines.extend(['', 'Transaction ID', str(txid)])
+ else:
+ lines.extend([
+ 'Next step',
+ 'Return the updated PSBT to your wallet coordinator to collect any remaining signatures, '
+ 'finalize, and broadcast.',
+ ])
+ return '\n'.join(lines)
### ports/stm32/boards/Passport/modules/spend_plan.py
@@ -0,0 +1,69 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Validated, immutable instructions passed from policy matching to signing."""
+
+
+class SpendPlan:
+ __slots__ = ('policy_id', 'input_index', 'branch', 'address_index',
+ 'script_context', 'owned_key_path', 'expected_pubkey',
+ 'owned_key_paths', 'expected_pubkeys',
+ 'sighash_type', 'script_pubkey', 'witness_script',
+ 'timelocks', '_locked')
+
+ def __init__(self, policy_id, input_index, branch, address_index,
+ script_context, owned_key_path, expected_pubkey,
+ sighash_type, script_pubkey=None, witness_script=None,
+ timelocks=(), owned_signing_keys=None):
+ object.__setattr__(self, '_locked', False)
+ self.policy_id = policy_id
+ self.input_index = input_index
+ self.branch = branch
+ self.address_index = address_index
+ self.script_context = script_context
+ self.owned_key_path = tuple(owned_key_path)
+ self.expected_pubkey = bytes(expected_pubkey)
+ if owned_signing_keys is None:
+ signing_keys = ((self.owned_key_path, self.expected_pubkey),)
+ else:
+ signing_keys = tuple((tuple(path), bytes(pubkey))
+ for path, pubkey in owned_signing_keys)
+ if not signing_keys or signing_keys[0] != (
+ self.owned_key_path, self.expected_pubkey):
+ raise ValueError('Primary signing key must match the spend plan')
+ self.owned_key_paths = tuple(path for path, _ in signing_keys)
+ self.expected_pubkeys = tuple(pubkey for _, pubkey in signing_keys)
+ if len(set(self.expected_pubkeys)) != len(self.expected_pubkeys):
+ raise ValueError('Spend plan signing keys must be distinct')
+ self.sighash_type = sighash_type
+ self.script_pubkey = bytes(script_pubkey) if script_pubkey is not None else None
+ self.witness_script = bytes(witness_script) if witness_script is not None else None
+ self.timelocks = tuple(timelocks)
+ object.__setattr__(self, '_locked', True)
+
+ def __setattr__(self, name, value):
+ if getattr(self, '_locked', False):
+ raise AttributeError('SpendPlan is immutable')
+ object.__setattr__(self, name, value)
+
+ def assert_p2wsh_scope(self, input_index, subpaths, script_pubkey,
+ witness_script, sighash_type, required_keys,
+ existing_signatures=()):
+ """Revalidate the security boundary immediately before signing."""
+ if self.script_context != 'p2wsh' or input_index != self.input_index:
+ raise ValueError('Wallet policy spend plan is for another input')
+ if sighash_type != self.sighash_type:
+ raise ValueError('Wallet policy sighash changed after validation')
+ if bytes(script_pubkey) != self.script_pubkey:
+ raise ValueError('Wallet policy UTXO changed after validation')
+ if bytes(witness_script) != self.witness_script:
+ raise ValueError('Wallet policy witness script changed after validation')
+ expected_required = set(self.expected_pubkeys) - set(existing_signatures)
+ if set(required_keys) != expected_required:
+ raise ValueError('Wallet policy signing key changed after validation')
+ for path, pubkey in zip(self.owned_key_paths, self.expected_pubkeys):
+ if pubkey not in subpaths:
+ raise ValueError('Wallet policy signing derivation is missing')
+ if tuple(subpaths[pubkey]) != path:
+ raise ValueError('Wallet policy signing derivation changed after validation')
+ return True
### ports/stm32/boards/Passport/modules/tasks/__init__.py
@@ -43,14 +43,11 @@
from .rename_account_task import rename_account_task
from .rename_derived_key_task import rename_derived_key_task
from .rename_multisig_task import rename_multisig_task
-from .restore_backup_task import restore_backup_task
from .save_multisig_wallet_task import save_multisig_wallet_task
from .save_new_account_task import save_new_account_task
from .save_new_derived_key_task import save_new_derived_key_task
from .save_seed_task import save_seed_task
-from .search_for_address_task import search_for_address_task
from .set_initial_pin_task import set_initial_pin_task
-from .sign_psbt_task import sign_psbt_task
from .sign_text_file_task import sign_text_file_task
from .validate_electrum_message_task import validate_electrum_message_task
from .validate_psbt_task import validate_psbt_task
### ports/stm32/boards/Passport/modules/tasks/restore_backup_task.py
@@ -117,6 +117,29 @@ async def restore_backup_task(on_done, decryption_password, backup_file_path):
await on_done(Error.CORRUPT_BACKUP_FILE)
return
+ # Wallet policies are security-critical and cannot be restored as
+ # opaque settings. Validate their identity, xpub encodings, network,
+ # and declared Passport-owned key against the backup's root node before
+ # changing the Secure Element secret.
+ policy_records = vals.get('setting.wallet_policies', [])
+ if policy_records:
+ from utils import xfp2str
+ from wallet_policy import validate_backup_policy_records
+ expected_fingerprint = xfp2str(node.my_fingerprint()).lower()
+
+ def derive_policy_node(path):
+ child = node.clone()
+ for element in path:
+ child.derive(element)
+ return child
+
+ vals['setting.wallet_policies'] = validate_backup_policy_records(
+ policy_records, expected_fingerprint, derive_policy_node,
+ chains.get_chain)
+ elif not isinstance(policy_records, list):
+ await on_done(Error.CORRUPT_BACKUP_FILE)
+ return
+
except Exception as e:
await on_done(Error.CORRUPT_BACKUP_FILE)
return
### ports/stm32/boards/Passport/modules/tasks/search_for_address_task.py
@@ -19,15 +19,28 @@ async def search_for_address_task(
multisig_wallet,
is_change,
max_to_check,
- reverse):
+ reverse,
+ wallet_policy=None):
import stash
from errors import Error
from uasyncio import sleep_ms
try:
with stash.SensitiveValues() as sv:
- if multisig_wallet:
+ if wallet_policy:
+ import chains
+ chain = chains.current_chain()
+ indexes = range(start_address_idx, start_address_idx + max_to_check)
+ if reverse:
+ indexes = reversed(indexes)
+ for curr_idx in indexes:
+ derived = wallet_policy.derive(1 if is_change else 0, curr_idx, chain)
+ if derived.address == address:
+ await on_done(curr_idx, wallet_policy.name, None)
+ return
+ await sleep_ms(1)
+ elif multisig_wallet:
# NOTE: Can't easily reverse order here, so this is slightly less efficient
for (curr_idx, paths, curr_address, script) in multisig_wallet.yield_addresses(
start_address_idx,
### ports/stm32/boards/Passport/modules/tasks/sign_psbt_task.py
@@ -13,6 +13,7 @@
async def sign_psbt_task(on_done, psbt):
from exceptions import FraudulentChangeOutput, FatalPSBTIssue
from errors import Error
+ from utils import keypath_to_str
from serializations import ser_sig_der
import stash
import gc
@@ -58,6 +59,14 @@ async def sign_psbt_task(on_done, psbt):
if inp.is_segwit:
history.verify_amount(txi.prevout, inp.amount, in_idx)
+ if inp.policy_spend_plan:
+ utxo = inp.get_utxo(txi.prevout.n)
+ inp.policy_spend_plan.assert_p2wsh_scope(
+ in_idx, inp.subpaths, utxo.scriptPubKey,
+ inp.get(inp.witness_script), inp.sighash,
+ inp.required_key, inp.part_sig)
+ del utxo
+
if not inp.is_segwit:
# Hash by serializing/blanking various subparts of the transaction
digest = psbt.make_txn_sighash(in_idx, txi, inp.sighash)
@@ -69,38 +78,55 @@ async def sign_psbt_task(on_done, psbt):
digest = psbt.make_txn_segwit_sighash(in_idx, txi,
inp.amount, inp.scriptCode, inp.sighash)
- node, which_key = inp.get_signing_node(sv, psbt.my_xfp, in_idx)
-
- # The precious private key we need
- pk = node.private_key()
-
- # print("privkey %s" % b2a_hex(pk).decode('ascii'))
- # print(" pubkey %s" % b2a_hex(which_key).decode('ascii'))
- # print(" digest %s" % b2a_hex(digest).decode('ascii'))
-
- # Do the ACTUAL signature ... finally!!!
- if len(inp.tap_subpaths) > 0:
- # TODO: handle taproot scripts
- inp.tap_key_sig = taproot_sign_key(None, pk, inp.sighash, digest)
+ policy_multisig = inp.is_multisig and inp.policy_spend_plan is not None
+ if policy_multisig:
+ signing_keys = tuple(sorted(inp.required_key))
else:
- result = secp256k1.sign_ecdsa(digest, pk)
-
- # convert signature to DER format
- if len(result) != 64:
- raise AssertionError('Incorrect signature length.')
-
- r = result[0:32]
- s = result[32:64]
-
- inp.added_sig = (which_key, ser_sig_der(r, s, inp.sighash))
-
- # Memory cleanup
- del result, r, s
-
- # private key no longer required
- stash.blank_object(pk)
- stash.blank_object(node)
- del pk, node
+ # Existing wallet types keep their ownership-based key selection.
+ signing_keys = (None,)
+
+ for which_key in signing_keys:
+ if policy_multisig:
+ # The spend plan above binds every required key to its path.
+ skp = keypath_to_str(inp.subpaths[which_key])
+ node = sv.derive_path(skp, register=True)
+ else:
+ node, which_key = inp.get_signing_node(sv, psbt.my_xfp, in_idx)
+
+ try:
+ if policy_multisig and node.public_key() != which_key:
+ raise AssertionError(
+ "Path (%s) led to wrong pubkey for input #%d" % (skp, in_idx))
+
+ pk = node.private_key()
+ try:
+ if len(inp.tap_subpaths) > 0:
+ # BIP86 Taproot key-path signature.
+ inp.tap_key_sig = taproot_sign_key(
+ None, pk, inp.sighash, digest)
+ else:
+ result = secp256k1.sign_ecdsa(digest, pk)
+ try:
+ if len(result) != 64:
+ raise AssertionError('Incorrect signature length.')
+ der_sig = ser_sig_der(
+ result[0:32], result[32:64], inp.sighash)
+ if policy_multisig:
+ if not inp.added_sigs:
+ inp.added_sigs = {}
+ if which_key in inp.added_sigs:
+ raise AssertionError(
+ 'This multisig key has already been signed')
+ inp.added_sigs[which_key] = der_sig
+ else:
+ inp.added_sig = (which_key, der_sig)
+ finally:
+ del result
+ finally:
+ stash.blank_object(pk)
+ finally:
+ stash.blank_object(node)
+ del pk, node
# print("result %s" % b2a_hex(result).decode('ascii'))
### ports/stm32/boards/Passport/modules/tasks/wallet_policy_task.py
@@ -0,0 +1,93 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+
+async def save_wallet_policy_task(on_done, policy):
+ from common import settings
+ from errors import Error
+ from ext_settings import SettingsOutOfSpace
+ from wallet_policy import POLICY_STORAGE_KEY, WalletPolicyRegistry
+
+ original = list(settings.get(POLICY_STORAGE_KEY, []))
+ try:
+ WalletPolicyRegistry(settings).save(policy)
+ settings.save()
+ except BaseException as exc:
+ try:
+ settings.set(POLICY_STORAGE_KEY, original)
+ settings.save()
+ except BaseException:
+ pass
+ error = Error.USER_SETTINGS_FULL if isinstance(exc, SettingsOutOfSpace) else Error.USER_SETTINGS_SAVE_FAILED
+ await on_done(error)
+ return
+ await on_done(None)
+
+
+async def delete_wallet_policy_task(on_done, policy_id):
+ from common import settings
+ from errors import Error
+ from ext_settings import SettingsOutOfSpace
+ from wallet_policy import POLICY_STORAGE_KEY, WalletPolicyRegistry
+
+ original = list(settings.get(POLICY_STORAGE_KEY, []))
+ try:
+ registry = WalletPolicyRegistry(settings)
+ if registry.get(policy_id) is None:
+ raise ValueError('Wallet policy not found')
+ registry.delete(policy_id)
+ settings.save()
+ except BaseException as exc:
+ try:
+ settings.set(POLICY_STORAGE_KEY, original)
+ settings.save()
+ except BaseException:
+ pass
+ error = Error.USER_SETTINGS_FULL if isinstance(exc, SettingsOutOfSpace) else Error.USER_SETTINGS_SAVE_FAILED
+ await on_done(error)
+ return
+ await on_done(None)
+
+
+async def rename_wallet_policy_task(on_done, policy_id, name):
+ from common import settings
+ from errors import Error
+ from ext_settings import SettingsOutOfSpace
+ from wallet_policy import POLICY_STORAGE_KEY, WalletPolicyRegistry
+
+ original = list(settings.get(POLICY_STORAGE_KEY, []))
+ try:
+ WalletPolicyRegistry(settings).rename(policy_id, name)
+ settings.save()
+ except BaseException as exc:
+ try:
+ settings.set(POLICY_STORAGE_KEY, original)
+ settings.save()
+ except BaseException:
+ pass
+ error = Error.USER_SETTINGS_FULL if isinstance(exc, SettingsOutOfSpace) else Error.USER_SETTINGS_SAVE_FAILED
+ await on_done(error)
+ return
+ await on_done(None)
+
+
+async def rename_wallet_policy_keys_task(on_done, policy_id, names):
+ from common import settings
+ from errors import Error
+ from ext_settings import SettingsOutOfSpace
+ from wallet_policy import POLICY_STORAGE_KEY, WalletPolicyRegistry
+
+ original = list(settings.get(POLICY_STORAGE_KEY, []))
+ try:
+ WalletPolicyRegistry(settings).rename_keys(policy_id, names)
+ settings.save()
+ except BaseException as exc:
+ try:
+ settings.set(POLICY_STORAGE_KEY, original)
+ settings.save()
+ except BaseException:
+ pass
+ error = Error.USER_SETTINGS_FULL if isinstance(exc, SettingsOutOfSpace) else Error.USER_SETTINGS_SAVE_FAILED
+ await on_done(error)
+ return
+ await on_done(None)
### ports/stm32/boards/Passport/modules/tests/host/fixtures/liana-multisig-policy.txt
@@ -0,0 +1 @@
+wsh(or_i(and_v(v:thresh(2,pkh([9f141cf0/48'/1'/0'/2']tpubDFnReAwXvYd6RA46X55HuFpmvZsLanDrwHAUsdYEGEpNGTRnCdbDRXJGLTwDeqKURCPZUDgdkuuu9dYkuBNQHmSNBUu7V2CdLKwpJjx2JuC/<2;3>/*),a:pkh([daba2d5f/48'/1'/0'/2']tpubDDwKEc4i4k8rBgVLGxytHrP13VVYucUGmL2cadux7AfMwMnRHKcw1YZKt9SMB4fWut7ZAiZqPefzm3BBCNXLZMxDrWJ4Q6VA1AFB6b8GzbT/<2;3>/*),a:pkh([141cfdf4/48'/1'/0'/2']tpubDEnYysximqdZkZnW5W9gYc7N3sxizKyqfdJfZ2qRfwNvSv6E11yDgyLTAnWQqDmVJ7oQ3h3ui59RQm1qmGxMm4jinq5wvSzyueKgrLJj5Cy/<0;1>/*)),older(52596)),and_v(v:pk([9f141cf0/48'/1'/0'/2']tpubDFnReAwXvYd6RA46X55HuFpmvZsLanDrwHAUsdYEGEpNGTRnCdbDRXJGLTwDeqKURCPZUDgdkuuu9dYkuBNQHmSNBUu7V2CdLKwpJjx2JuC/<0;1>/*),pk([daba2d5f/48'/1'/0'/2']tpubDDwKEc4i4k8rBgVLGxytHrP13VVYucUGmL2cadux7AfMwMnRHKcw1YZKt9SMB4fWut7ZAiZqPefzm3BBCNXLZMxDrWJ4Q6VA1AFB6b8GzbT/<0;1>/*))))#u768v50p
### ports/stm32/boards/Passport/modules/tests/host/fixtures/liana-multisig-policy.txt.license
@@ -0,0 +1,2 @@
+SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+SPDX-License-Identifier: GPL-3.0-or-later
### ports/stm32/boards/Passport/modules/tests/host/test_constrained_sflash.py
@@ -0,0 +1,32 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import importlib.util
+from pathlib import Path
+
+
+PROJECT_ROOT_PARENT_INDEX = 7
+ROOT = Path(__file__).resolve().parents[PROJECT_ROOT_PARENT_INDEX]
+
+
+def test_sparse_flash_partial_and_repeated_programming(tmp_path, monkeypatch):
+ path = ROOT / 'simulator/sim_modules/constrained_sflash.py'
+ spec = importlib.util.spec_from_file_location(path.stem, path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ monkeypatch.setattr(module, '_BACKING_FILE', str(tmp_path / 'flash.bin'))
+ flash = module.SPIFlash()
+ try:
+ flash.write(17, b'\xf0\x55')
+ page = bytearray(256)
+ flash.read(0, page)
+ assert page == b'\xff' * 17 + b'\xf0\x55' + b'\xff' * 237
+ flash.write(17, b'\x0f\xff')
+ flash.read(0, page)
+ assert page[17:19] == b'\x00\x55'
+ flash.sector_erase(0)
+ flash.write(20, b'\xaa')
+ flash.read(0, page)
+ assert page == b'\xff' * 20 + b'\xaa' + b'\xff' * 235
+ finally:
+ flash._file.close()
### ports/stm32/boards/Passport/modules/tests/host/test_liana_export.py
@@ -0,0 +1,130 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Host tests for Liana's file-based descriptor-key export."""
+
+import runpy
+import sys
+import types
+from pathlib import Path
+
+import pytest
+from embit.descriptor.arguments import Key
+
+
+MODULES = Path(__file__).resolve().parents[2]
+
+
+class _Node:
+ pass
+
+
+class _SensitiveValues:
+ def __init__(self, expected_deriv, xpub):
+ self.expected_deriv = expected_deriv
+ self.xpub = xpub
+ self.chain = types.SimpleNamespace(serialize_public=self.serialize_public)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ return False
+
+ def derive_path(self, deriv):
+ assert deriv == self.expected_deriv
+ return _Node()
+
+ def serialize_public(self, node, addr_type):
+ assert isinstance(node, _Node)
+ assert addr_type == 1
+ return self.xpub
+
+
+@pytest.mark.parametrize(
+ 'coin_type,acct_num,expected_deriv,xpub', [
+ (1, 0, "m/48'/1'/0'/2'",
+ 'tpubDEhFJsryccF9b2PaR3mgUBVfoYbpVaXsmpK6sonC8cysYcpJzYsZfiwkR9Ja'
+ 'oiNWCT9o1HN2bFccb2wMnAXGdKpW6nYQukZMZXfF32RnS6y'),
+ (0, 7, "m/48'/0'/7'/2'",
+ 'xpub6Eak7S2MQqvUkxQ7MCf6hFRYyQ8tK9iaUsRm1nkNshKWvbhCysH83byA6akg'
+ 'm2ZjCvCLjco2XcwYDqNpBYdV5StSWMAEe12FaVsT8bTJBJC'),
+ ])
+def test_liana_export_is_a_raw_descriptor_key(
+ monkeypatch, coin_type, acct_num, expected_deriv, xpub):
+ chains = types.ModuleType('chains')
+ chains.current_chain = lambda: types.SimpleNamespace(
+ b44_cointype=coin_type)
+
+ stash = types.ModuleType('stash')
+ stash.SensitiveValues = lambda: _SensitiveValues(expected_deriv, xpub)
+
+ common = types.ModuleType('common')
+ common.settings = types.SimpleNamespace(get=lambda key: 0xA1B2C3D4)
+
+ public_constants = types.ModuleType('public_constants')
+ public_constants.AF_CLASSIC = 1
+ public_constants.AF_P2WSH = 2
+
+ utils = types.ModuleType('utils')
+ utils.xfp2str = lambda value: 'A1B2C3D4'
+
+ monkeypatch.setitem(sys.modules, 'chains', chains)
+ monkeypatch.setitem(sys.modules, 'stash', stash)
+ monkeypatch.setitem(sys.modules, 'common', common)
+ monkeypatch.setitem(sys.modules, 'public_constants', public_constants)
+ monkeypatch.setitem(sys.modules, 'utils', utils)
+
+ namespace = runpy.run_path(str(MODULES / 'wallets/liana.py'))
+ export, account_info = namespace['create_liana_export'](
+ acct_num=acct_num)
+
+ expected_origin = expected_deriv[2:]
+ assert export == '[a1b2c3d4/{}]{}\n'.format(expected_origin, xpub)
+ # Liana parses this file as a raw descriptor public key before trying its
+ # Coldcard-specific JSON formats.
+ assert Key.from_string(export.strip()) is not None
+ assert account_info == [{
+ 'fmt': 2,
+ 'deriv': expected_deriv,
+ 'acct': acct_num,
+ 'xfp': 'a1b2c3d4',
+ }]
+
+
+def test_liana_crypto_account_matches_cross_implementation_vector(monkeypatch):
+ stash = types.ModuleType('stash')
+ common = types.ModuleType('common')
+ common.settings = types.SimpleNamespace(get=lambda key: 0xA1B2C3D4)
+ public_constants = types.ModuleType('public_constants')
+ public_constants.AF_CLASSIC = 1
+ public_constants.AF_P2WSH = 2
+ utils = types.ModuleType('utils')
+ utils.xfp2str = lambda value: 'A1B2C3D4'
+
+ monkeypatch.setitem(sys.modules, 'stash', stash)
+ monkeypatch.setitem(sys.modules, 'common', common)
+ monkeypatch.setitem(sys.modules, 'public_constants', public_constants)
+ monkeypatch.setitem(sys.modules, 'utils', utils)
+
+ namespace = runpy.run_path(str(MODULES / 'wallets/liana.py'))
+
+ class PublicNode:
+ def public_key(self):
+ return bytes.fromhex(
+ '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798')
+
+ def chain_code(self):
+ return bytes(range(32))
+
+ def fingerprint(self):
+ return 0x11223344
+
+ encoded = namespace['create_liana_crypto_account'](
+ 0xA1B2C3D4, PublicNode(), 0, 7)
+ assert encoded.hex() == (
+ 'a2011aa1b2c3d40281d90134d90191d9019ad9012fa602f40358210279be667e'
+ 'f9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179804582000'
+ '0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f05'
+ 'd99d71a20100020006d99d70a301881830f500f507f502f5021aa1b2c3d40304'
+ '081a11223344')
### ports/stm32/boards/Passport/modules/tests/host/test_miniscript.py
@@ -0,0 +1,220 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import hashlib
+import os
+import sys
+
+import pytest
+
+
+MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+if MODULES not in sys.path:
+ sys.path.insert(0, MODULES)
+
+from miniscript import (Parser, _count_non_push_ops, analyze, # noqa: E402
+ compile_miniscript, validate)
+from policy_errors import (PolicyParseError, PolicyResourceError, # noqa: E402
+ PolicyTypeError, UnsupportedPolicyError)
+
+
+KEYS = tuple(bytes.fromhex(key) for key in (
+ '031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f',
+ '024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766',
+ '02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337',
+ '03462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b',
+))
+
+
+def resolve(index, branch, address_index):
+ assert branch in (0, 1)
+ assert address_index == 0
+ return KEYS[index]
+
+
+GOLDEN_SCRIPTS = (
+ (
+ 'multi(2,@0/**,@1/**,@2/**,@3/**)',
+ '5221031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f'
+ '21024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766'
+ '2102531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337'
+ '2103462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b54ae',
+ ),
+ (
+ 'or_d(pk(@0/**),and_v(v:multi(2,@1/**,@2/**,@3/**),older(65535)))',
+ '21031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078fac736452'
+ '21024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766'
+ '2102531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337'
+ '2103462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b53af'
+ '03ffff00b268',
+ ),
+ (
+ 'thresh(2,pk(@0/**),s:pk(@1/**),sln:older(12960))',
+ '21031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078fac'
+ '7c21024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766ac93'
+ '7c63006702a032b29268935287',
+ ),
+)
+
+
+@pytest.mark.parametrize('expression, expected', GOLDEN_SCRIPTS)
+def test_compile_matches_independent_golden_vectors(expression, expected):
+ node = Parser(expression).parse()
+ info = validate(node)
+ assert info.basic == 'B'
+ assert info.s
+ assert compile_miniscript(node, resolve, 0, 0).hex() == expected
+
+
+def test_explicit_receive_change_branches_are_passed_to_resolver():
+ calls = []
+
+ def tracking_resolver(index, branch, address_index):
+ calls.append((index, branch, address_index))
+ return KEYS[index]
+
+ node = Parser('multi(2,@0/<4;9>/*,@1/<5;8>/*)').parse()
+ compile_miniscript(node, tracking_resolver, 1, 7)
+ assert calls == [(0, 9, 7), (1, 8, 7)]
+
+
+@pytest.mark.parametrize('expression', (
+ '',
+ 'pk(@0/**)garbage',
+ 'pk(@0/0/*)',
+ 'pk(@0/<0;0>/*)',
+ 'pk(@00/**)',
+ 'unknown(@0/**)',
+ 'older(0)',
+ 'older(2147483648)',
+ 'multi(0,@0/**)',
+ 'multi(2,@0/**)',
+))
+def test_malformed_or_invalid_policies_fail(expression):
+ with pytest.raises((PolicyParseError, PolicyTypeError, PolicyResourceError)):
+ node = Parser(expression).parse()
+ validate(node)
+
+
+def test_hashlocks_are_valid_syntax_but_not_in_phase_a_profile():
+ node = Parser('and_v(v:pk(@0/**),sha256(' + '11' * 32 + '))').parse()
+ with pytest.raises(UnsupportedPolicyError, match='Hashlock'):
+ validate(node)
+
+
+def test_overlapping_derivation_branches_are_rejected():
+ node = Parser('multi(1,@0/<0;1>/*,@0/<1;2>/*)').parse()
+ with pytest.raises(PolicyTypeError, match='overlap'):
+ validate(node)
+
+
+def test_disjoint_derivation_branches_for_same_xpub_are_allowed():
+ node = Parser('multi(1,@0/<0;1>/*,@0/<2;3>/*)').parse()
+ assert analyze(node).basic == 'B'
+ validate(node)
+
+
+def test_duplicate_key_expression_is_rejected():
+ node = Parser('multi(1,@0/**,@0/**)').parse()
+ with pytest.raises(PolicyTypeError, match='repeated'):
+ validate(node)
+
+
+def test_parser_depth_and_size_are_bounded():
+ with pytest.raises(PolicyResourceError):
+ Parser('v:' * 18 + 'pk(@0/**)').parse()
+ with pytest.raises(PolicyResourceError):
+ Parser('pk(@0/**)' + 'x' * 513).parse()
+
+
+def test_key_resolver_must_return_compressed_p2wsh_key():
+ node = Parser('pk(@0/**)').parse()
+ with pytest.raises(PolicyTypeError, match='invalid public key'):
+ compile_miniscript(node, lambda *_: bytes(32), 0, 0)
+
+
+def test_opcode_counter_ignores_pushed_bytes():
+ script = bytes([33]) + KEYS[0] + bytes([0xac, 2, 0xac, 0xac, 0x69])
+ assert _count_non_push_ops(script) == 2
+
+
+@pytest.mark.parametrize('wrappers, key_count, verify, allowed', (
+ (49, 1, False, True),
+ (50, 1, False, False),
+ (49, 4, False, True), # 196 static wrapper ops + CHECKMULTISIG + 4 = 201.
+ (49, 5, False, False),
+ (49, 4, True, True),
+ (49, 5, True, False),
+))
+def test_multisig_opcode_budget_boundary(wrappers, key_count, verify, allowed):
+ keys = ','.join('@0/<{};{}>/*'.format(2 * i, 2 * i + 1)
+ for i in range(key_count))
+ expression = 'j' * wrappers + ('tv' if verify else '') + ':multi(1,{})'.format(keys)
+ node = Parser(expression).parse()
+ if allowed:
+ script = compile_miniscript(node, lambda *_: KEYS[0], 0, 0)
+ assert _count_non_push_ops(script) + key_count <= 201
+ else:
+ with pytest.raises(PolicyResourceError, match='201 opcodes'):
+ compile_miniscript(node, lambda *_: KEYS[0], 0, 0)
+
+
+def test_opcode_budget_counts_only_one_if_branch_multisig_charge():
+ # All 197 static operations count, but at most four keys are charged.
+ expression = ('or_i(' + 'j' * 48 + ':multi(1,@0/**),'
+ 'multi(1,@1/**,@1/<2;3>/*,@1/<4;5>/*,@1/<6;7>/*))')
+ script = compile_miniscript(Parser(expression).parse(), lambda *_: KEYS[0], 0, 0)
+ assert _count_non_push_ops(script) == 197
+
+
+def test_opcode_budget_includes_dissatisfied_multisig_checks(monkeypatch):
+ import miniscript
+ # or_b executes both multisigs, even though only one needs to succeed.
+ expression = 'or_b(multi(1,@0/**),a:multi(1,@1/**,@2/**,@3/**))'
+ monkeypatch.setattr(miniscript, 'MAX_P2WSH_OPS', 8)
+ with pytest.raises(PolicyResourceError, match='8 opcodes'):
+ compile_miniscript(Parser(expression).parse(), resolve, 0, 0)
+ monkeypatch.setattr(miniscript, 'MAX_P2WSH_OPS', 9)
+ assert compile_miniscript(Parser(expression).parse(), resolve, 0, 0)
+
+
+# Independently cross-checked against Bitcoin Core's Miniscript implementation
+# and embit. Hashes keep the additional wrapper/fragment vectors compact.
+CROSS_IMPLEMENTATION_VECTORS = (
+ ('pkh(@0/**)', 25, '6f1b349d7fed5240ad719948529e8b06abf038438f9b523820489375af513a3f'),
+ ('and_v(v:pk(@0/**),pk(@1/**))', 70,
+ 'b0eaafe0b01383e92f7b3c9643d4da835943440b897bcb44fbbbd4b0b957b69a'),
+ ('or_i(pk(@0/**),pk(@1/**))', 73,
+ '24b1fdb679c11186fc70cd17d82bd5e8fae3148dce7614379c793f0f5a5badd9'),
+ ('andor(pk(@0/**),pk(@1/**),pk(@2/**))', 108,
+ '103d50da989a23cb5282db73c209ea067338c4bd7fe7e5a6d1e821d5bfaa161d'),
+ ('and_b(pk(@0/**),a:pk(@1/**))', 73,
+ '09f13aaaf994c1d804f2b54d046533f4d41b4f74bf1c460c8d0f21662785b7e1'),
+ ('or_b(pk(@0/**),a:pk(@1/**))', 73,
+ '8b8918ece3065e4c19b2a12f1d259d49db8dfdfd6c5a06eb5b7a640fc3da5283'),
+ ('t:or_c(pk(@0/**),v:pk(@1/**))', 73,
+ '5605ce9b362bd078da557895e086f51a703dca71e6ef2b5d5ef950d613e3e31e'),
+ ('thresh(2,pk(@0/**),s:pk(@1/**),a:pk(@2/**))', 112,
+ '373f8dbe10414589afcd76526cd8b754035d6ee038b38d5d5691545801b0b45e'),
+ ('j:and_v(v:pk(@0/**),older(2016))', 43,
+ '13f2f90e699ab9798a7833197c266b15c8eacf333ea73aa14937d9651ab62140'),
+ ('c:and_v(v:older(16),pk_k(@0/**))', 38,
+ '4fb1e1b5ea866245f6ffd23721d8d39540fc942b86a416c2e65c3b1dc9902570'),
+ ('c:or_i(pk_k(@0/**),pk_k(@1/**))', 72,
+ '061a8d8a21ac89746425b8ec00fd6bac5f79641ac12155288e32a7a1fa17c797'),
+)
+
+
+@pytest.mark.parametrize('expression, expected_length, expected_hash',
+ CROSS_IMPLEMENTATION_VECTORS)
+def test_compile_matches_cross_implementation_vectors(
+ expression, expected_length, expected_hash):
+ script = compile_miniscript(Parser(expression).parse(), resolve, 0, 0)
+ assert len(script) == expected_length
+ assert hashlib.sha256(script).hexdigest() == expected_hash
+
+
+@pytest.mark.parametrize('expression', ['pk(@0/**)', 'multi_a(1,@0/**)'])
+def test_tapscript_context_is_unsupported(expression):
+ with pytest.raises((PolicyParseError, PolicyTypeError)):
+ compile_miniscript(Parser(expression).parse(), resolve, 0, 0, context='tr')
### ports/stm32/boards/Passport/modules/tests/host/test_policy_boundary.py
@@ -0,0 +1,117 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import builtins
+import hashlib
+import os
+import sys
+import types
+
+import pytest
+
+
+MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+if MODULES not in sys.path:
+ sys.path.insert(0, MODULES)
+
+# Passport's frozen modules provide const as a built-in under MicroPython.
+if not hasattr(builtins, 'const'):
+ builtins.const = lambda value: value
+
+sys.modules.setdefault('public_constants', types.SimpleNamespace(
+ AF_P2SH=8, AF_P2WSH=14, AF_P2WSH_P2SH=26))
+
+from policy_errors import PolicyMismatchError # noqa: E402
+from policy_multisig import StandardMultisigPolicy # noqa: E402
+from spend_plan import SpendPlan # noqa: E402
+
+
+SCRIPT = bytes.fromhex('5221' + '02' + '11' * 32 + '51ae')
+
+
+class MockChain:
+ ctype = 'BTC'
+
+
+class MockMultisigWallet:
+ name = 'Legacy'
+ chain_type = 'BTC'
+ id = 42
+ chain = MockChain()
+
+ def __init__(self, address_format):
+ self.addr_fmt = address_format
+
+ @staticmethod
+ def yield_addresses(start, count, change_idx=0):
+ assert count == 1
+ yield start, (), 'legacy-address', SCRIPT
+
+
+@pytest.mark.parametrize('address_format, expected_script', (
+ (14, b'\x00\x20' + hashlib.sha256(SCRIPT).digest()),
+ (26, b'\xa9\x14' + hashlib.new(
+ 'ripemd160', hashlib.sha256(b'\x00\x20' + hashlib.sha256(SCRIPT).digest()).digest()
+ ).digest() + b'\x87'),
+ (8, b'\xa9\x14' + hashlib.new('ripemd160', hashlib.sha256(SCRIPT).digest()).digest() + b'\x87'),
+))
+def test_legacy_multisig_adapter_derives_exact_scriptpubkey(address_format, expected_script):
+ policy = StandardMultisigPolicy(MockMultisigWallet(address_format))
+ result = policy.derive(1, 7)
+ assert result.policy_id == 'legacy-multisig:42'
+ assert result.branch == 1
+ assert result.index == 7
+ assert result.script_pubkey == expected_script
+ assert policy.match_scripts(1, 7, expected_script,
+ result.witness_script, result.redeem_script) is not None
+ with pytest.raises(PolicyMismatchError):
+ policy.match_scripts(1, 7, bytes(len(expected_script)))
+
+
+def test_spend_plan_is_immutable_after_validation():
+ plan = SpendPlan('policy', 0, 0, 12, 'p2wsh', (1, 2, 3),
+ bytes(33), 1, script_pubkey=b'output',
+ witness_script=b'script')
+ assert plan.address_index == 12
+ with pytest.raises(AttributeError, match='immutable'):
+ plan.address_index = 13
+
+
+def test_spend_plan_rechecks_complete_signing_scope():
+ pubkey = bytes.fromhex('02' + '11' * 32)
+ path = (0x12345678, 0x80000030, 0, 4)
+ plan = SpendPlan('policy', 2, 0, 4, 'p2wsh', path, pubkey, 1,
+ script_pubkey=b'output', witness_script=b'script')
+ assert plan.assert_p2wsh_scope(
+ 2, {pubkey: path}, b'output', b'script', 1, {pubkey})
+
+ mutations = (
+ (3, {pubkey: path}, b'output', b'script', 1, {pubkey}),
+ (2, {pubkey: path}, b'changed', b'script', 1, {pubkey}),
+ (2, {pubkey: path}, b'output', b'changed', 1, {pubkey}),
+ (2, {pubkey: path}, b'output', b'script', 0, {pubkey}),
+ (2, {pubkey: path[:-1] + (5,)}, b'output', b'script', 1, {pubkey}),
+ (2, {pubkey: path}, b'output', b'script', 1, {bytes(33)}),
+ )
+ for mutation in mutations:
+ with pytest.raises(ValueError):
+ plan.assert_p2wsh_scope(*mutation)
+
+
+def test_spend_plan_binds_multiple_owned_signing_keys():
+ first = bytes.fromhex('02' + '11' * 32)
+ second = bytes.fromhex('03' + '22' * 32)
+ first_path = (0x12345678, 0x80000030, 0, 4)
+ second_path = (0x12345678, 0x80000030, 2, 4)
+ plan = SpendPlan(
+ 'policy', 2, 0, 4, 'p2wsh', first_path, first, 1,
+ script_pubkey=b'output', witness_script=b'script',
+ owned_signing_keys=((first_path, first), (second_path, second)))
+ subpaths = {first: first_path, second: second_path}
+ assert plan.assert_p2wsh_scope(
+ 2, subpaths, b'output', b'script', 1, {first, second})
+ assert plan.assert_p2wsh_scope(
+ 2, subpaths, b'output', b'script', 1, {second}, {first})
+ with pytest.raises(ValueError, match='signing key'):
+ plan.assert_p2wsh_scope(
+ 2, subpaths, b'output', b'script', 1, {first}, {first})
### ports/stm32/boards/Passport/modules/tests/host/test_policy_display.py
@@ -0,0 +1,470 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import ast
+import builtins
+import inspect
+import os
+import re
+import sys
+import types
+
+import pytest
+
+
+MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+if MODULES not in sys.path:
+ sys.path.insert(0, MODULES)
+
+if not hasattr(builtins, 'const'):
+ builtins.const = lambda value: value
+sys.modules.setdefault('public_constants', types.SimpleNamespace(
+ AF_P2SH=8, AF_P2WSH=14, AF_P2WSH_P2SH=26))
+
+from descriptor import append_checksum # noqa: E402
+import policy_display # noqa: E402
+from policy_display import compatible_path_indexes, describe_timelock # noqa: E402
+from wallet_policy import MiniscriptPolicy # noqa: E402
+
+
+XPUB = ('xpub6Br37sWxruYfT8ASpCjVHKGwgdnYFEn98DwiN76i2oyY6fgH1LAPmmDcF46x'
+ 'jxJr22gw4jmVjTE2E3URMnRPEPYyo1zoPSUba563ESMXCeb')
+
+
+def without_recolor(text):
+ """Remove LVGL recolor delimiters while preserving escaped hashes."""
+ output = []
+ position = 0
+ colored = False
+ while position < len(text):
+ if not colored:
+ marker = re.match(r'#[0-9a-fA-F]{6} ', text[position:])
+ if marker:
+ position += len(marker.group(0))
+ colored = True
+ continue
+ elif text[position] == '#':
+ if position + 1 < len(text) and text[position + 1] == '#':
+ output.append('##')
+ position += 2
+ continue
+ position += 1
+ colored = False
+ continue
+ output.append(text[position])
+ position += 1
+ return ''.join(output)
+
+
+def plain_review_pages(policy):
+ return tuple(without_recolor(page) for page in policy.format_review_pages())
+
+
+def key_info(index, purpose=48):
+ fingerprint = '{:08x}'.format(0x6738736c + index)
+ suffix = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'[index]
+ return "[{}/{}'/0'/0'/2']{}{}".format(
+ fingerprint, purpose, XPUB[:-1], suffix)
+
+
+def test_liana_inheritance_is_explained_as_two_alternative_spend_paths():
+ policy = MiniscriptPolicy(
+ 'Liana Test', 'TBTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pkh(@1/**),older(52596))))',
+ (key_info(0), key_info(1)), (0,))
+
+ pages = plain_review_pages(policy)
+ review = '\n'.join(pages)
+ assert 'Simple inheritance' in pages[0]
+ assert '2 ways to spend' in pages[0]
+ assert pages[0].startswith('Policy Name\nLiana Test\n\nSimple inheritance')
+ assert 'Script Type\nNative SegWit (P2WSH)' in pages[0]
+ assert 'Spend with Passport' in review
+ assert 'Passport can authorize spending by itself' in review
+ assert 'No recovery delay is required' in review
+ assert '6738 736C' in review
+ assert 'Spend with the recovery key' in review
+ assert ('Recovery key can spend by itself\nabout 1 year\n'
+ 'after each coin confirms' in review)
+ assert 'Passport can still spend by itself after the recovery key becomes available' in review
+ assert '52,596 blocks' in review
+ assert '6738 736D' in review
+ assert 'How the recovery delay works' in review
+ assert 'matches the seed currently loaded on Passport' in review
+ assert 'restarts its timer' in review
+ assert pages[-1].startswith('Back up this policy')
+ assert 'Your seed recovers this Passport key, not the policy' in pages[-1]
+ assert pages[-1].endswith('Keep a separate copy.')
+ assert ('Recovery 6738 736D\ncan spend by itself about 1 year after each coin confirms'
+ in policy.format_confirmation())
+
+
+def test_review_highlights_only_short_verification_fields():
+ policy = MiniscriptPolicy(
+ 'Liana Test', 'TBTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pkh(@1/**),older(52596))))',
+ (key_info(0), key_info(1)), (0,))
+
+ pages = policy.format_review_pages()
+ overview, primary, recovery, timing = pages[:4]
+ backup = pages[-1]
+
+ assert overview.startswith('#00bdcd Policy Name#\nLiana Test')
+ assert '#00bdcd Script Type#\nNative SegWit (P2WSH)' in overview
+ assert '#00bdcd 2# ways to spend' in overview
+ assert '#00bdcd Simple inheritance#' not in overview
+ assert '#00bdcd Bitcoin Testnet#' not in overview
+ assert '#00bdcd Native SegWit (P2WSH)#' not in overview
+
+ assert '#00bdcd ' not in primary
+ assert '#00bdcd about 1 year#' in recovery
+ assert '#00bdcd Exact delay#\n52,596 blocks' in recovery
+ assert '#00bdcd 52,596 blocks#' not in recovery
+ assert '#00bdcd ' not in timing
+ assert '#00bdcd ' not in backup
+
+ review = '\n'.join(pages)
+ assert '#00bdcd Passport can authorize spending by itself.#' not in review
+ assert '#00bdcd Your seed recovers this Passport key, not the policy.#' not in review
+
+
+def test_local_signer_name_is_used_and_escaped_without_changing_policy_semantics():
+ policy = MiniscriptPolicy(
+ 'Liana Test', 'TBTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pkh(@1/**),older(52596))))',
+ (key_info(0), key_info(1)), (0,), ('', 'Family ## Vault'))
+
+ review = '\n'.join(plain_review_pages(policy))
+ assert 'Family #### Vault can spend by itself' in review
+ assert '6738 736D' in review
+
+
+def test_simple_policy_signing_review_states_exact_passport_authority():
+ policy = MiniscriptPolicy(
+ 'Liana Test', 'TBTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pkh(@1/**),older(52596))))',
+ (key_info(0), key_info(1)), (0,), ('', 'Recovery key'))
+ signing = '\n'.join(policy.format_signing_pages())
+ assert 'Signing path' in signing
+ assert 'Wallet\nLiana Test' in signing
+ assert 'Passport is authorizing this transaction with its own key' in signing
+ assert 'No recovery delay is required' in signing
+ assert 'Passport key\n6738 736C' in signing
+ assert 'The recovery key is not being used' in signing
+
+
+def test_canonical_full_descriptor_and_short_check_are_available_for_comparison():
+ policy = MiniscriptPolicy(
+ 'Check', 'BTC', 'wsh(pk(@0/**))', (key_info(0),), (0,))
+ expected = append_checksum('wsh(pk({}/**))'.format(key_info(0)))
+ assert policy.full_descriptor() == expected
+ assert policy.descriptor_check() == expected[-8:].upper()
+ details = policy.format_details()
+ assert expected in details
+ assert 'Internal policy ID' in details
+
+
+def test_threshold_tree_does_not_expand_combinations_and_flags_passport_bypass():
+ policy = MiniscriptPolicy(
+ 'Team Recovery', 'BTC',
+ 'wsh(or_d(multi(2,@0/**,@1/**,@2/**),'
+ 'and_v(v:pk(@3/**),older(1008))))',
+ tuple(key_info(index) for index in range(4)), (0,))
+ review = '\n'.join(plain_review_pages(policy))
+ assert 'Custom wallet policy' in review
+ assert 'Any 2 of 3 keys must sign' in review
+ assert 'This Passport\n6738 736C' in review
+ assert 'Key 2\n6738 736D' in review
+ assert 'Available after\nabout 1 week' in review
+ assert 'Key 4\n6738 736F' in review
+ assert 'Recovery key\n6738 736F' not in review
+ # The other two primary keys can satisfy the 2-of-3 without Passport.
+ assert review.count('This Passport is optional.') == 1
+ assert review.count('This Passport is not used.') == 1
+ assert 'Spend now (2-of-3)\nOptional' in review
+ assert 'After about 1 week (1-of-1)\nNot used' in review
+
+
+def test_maximum_key_threshold_stays_linear_and_names_every_signer():
+ key_count = 15
+ template = 'wsh(multi(8,{}))'.format(','.join(
+ '@{}/**'.format(index) for index in range(key_count)))
+ policy = MiniscriptPolicy(
+ 'Maximum Signers', 'BTC', template,
+ tuple(key_info(index) for index in range(key_count)), (0,))
+
+ pages = plain_review_pages(policy)
+ review = '\n'.join(pages)
+ assert 'Any 8 of 15 keys must sign' in review
+ for index in range(key_count):
+ assert '{:04X} {:04X}'.format(
+ (0x6738736c + index) >> 16,
+ (0x6738736c + index) & 0xffff) in review
+ # The review lists each signer once; it never enumerates C(15, 8) paths.
+ assert len(review) < 1600
+ assert 'This Passport is optional.' in review
+
+
+def test_threshold_conditions_are_rendered_without_opaque_miniscript():
+ policy = MiniscriptPolicy(
+ 'Condition Threshold', 'BTC',
+ 'wsh(thresh(2,pk(@0/**),s:pk(@1/**),a:pk(@2/**)))',
+ tuple(key_info(index) for index in range(3)), (0,))
+ review = '\n'.join(plain_review_pages(policy))
+ assert 'Any 2 of 3 keys must sign' in review
+ assert 'Advanced condition' not in review
+
+
+def test_liana_multisig_shows_immediate_path_first_with_compact_key_blocks():
+ policy = MiniscriptPolicy(
+ 'Liana Multisig', 'TBTC',
+ 'wsh(or_i('
+ 'and_v(v:thresh(2,pkh(@0/<2;3>/*),a:pkh(@1/<2;3>/*),'
+ 'a:pkh(@2/<0;1>/*)),older(52596)),'
+ 'and_v(v:pk(@0/<0;1>/*),pk(@1/<0;1>/*))))',
+ tuple(key_info(index) for index in range(3)), (0,),
+ ('', 'HOT KEY', 'BACKUP PASSPORT'))
+
+ pages = plain_review_pages(policy)
+ immediate = pages[1]
+ delayed = pages[2]
+
+ assert immediate.startswith('Spend now')
+ assert 'Both keys must sign' in immediate
+ assert 'This Passport\n6738 736C' in immediate
+ assert 'HOT KEY\n6738 736D' in immediate
+
+ assert delayed.startswith('Delayed spending')
+ assert 'Available after\nabout 1 year' in delayed
+ assert 'Exact delay\n52,596 blocks' in delayed
+ assert 'Any 2 of 3 keys must sign' in delayed
+ assert 'BACKUP PASSPORT\n6738 736E' in delayed
+ assert 'All of' not in delayed
+ assert 'conditions' not in delayed
+ assert '- This Passport -' not in delayed
+ assert '- HOT KEY -' not in delayed
+ assert '- BACKUP PASSPORT -' not in delayed
+ assert 'Wait about' not in delayed
+ assert 'This path does not require Passport' not in delayed
+ assert 'This Passport is optional.' in delayed
+
+ passport_role = pages[3]
+ assert passport_role == (
+ 'This Passport\n\nSpend now (2-of-2)\nMust sign\n\n'
+ 'After about 1 year (2-of-3)\nOptional')
+ # These labels are built without CPython-only str.capitalize(), which is
+ # unavailable in Passport's MicroPython runtime.
+ tree = ast.parse(inspect.getsource(policy_display))
+ assert not any(isinstance(node, ast.Call) and
+ isinstance(node.func, ast.Attribute) and
+ node.func.attr == 'capitalize' for node in ast.walk(tree))
+
+ signing = policy.format_signing_pages()[0]
+ assert signing.startswith('Wallet\nLiana Multisig')
+ assert ('This Passport will sign:\nSpend now (2-of-2): required\n'
+ 'After about 1 year (2-of-3): optional') in signing
+ assert 'Key: 6738 736C' in signing
+ assert 'Your wallet app chooses which valid option completes the transaction.' in signing
+ assert 'reviewed paths' not in signing
+ assert 'wallet coordinator' not in signing
+
+ # The final sequence used by ordinary RBF transactions disables BIP68, so
+ # the 52,596-block recovery branch cannot finalize this transaction.
+ immediate_only = compatible_path_indexes(
+ policy, tx_version=2, lock_time=0, sequence=0xfffffffd)
+ assert immediate_only == (0,)
+ selected = policy.format_signing_pages(immediate_only)[0]
+ assert 'Spend now (2-of-2)' in selected
+ assert 'Both keys must sign' in selected
+ assert 'This Passport\n6738 736C' in selected
+ assert 'HOT KEY\n6738 736D' in selected
+ assert 'After about 1 year' not in selected
+ assert 'optional' not in selected
+
+ # A version-2 transaction with a matching height sequence leaves both the
+ # immediate and delayed branches available until witness finalization.
+ assert compatible_path_indexes(
+ policy, tx_version=2, lock_time=0, sequence=52596) == (0, 1)
+ assert compatible_path_indexes(
+ policy, tx_version=1, lock_time=0, sequence=52596) == (0,)
+
+
+def test_multisig_path_uses_teal_only_for_short_section_labels():
+ policy = MiniscriptPolicy(
+ 'Liana Multisig', 'TBTC',
+ 'wsh(or_i('
+ 'and_v(v:thresh(2,pkh(@0/<2;3>/*),a:pkh(@1/<2;3>/*),'
+ 'a:pkh(@2/<0;1>/*)),older(52596)),'
+ 'and_v(v:pk(@0/<0;1>/*),pk(@1/<0;1>/*))))',
+ tuple(key_info(index) for index in range(3)), (0,),
+ ('', 'HOT KEY', 'BACKUP PASSPORT'))
+
+ pages = policy.format_review_pages()
+ immediate = pages[1]
+ delayed = pages[2]
+
+ assert immediate.startswith('#00bdcd Spend now#\n\nBoth keys must sign')
+ assert '#00bdcd Both keys must sign#' not in immediate
+ assert '#00bdcd This Passport#' not in immediate
+ assert '#00bdcd 6738 736C#' not in immediate
+ assert '#00bdcd HOT KEY#' not in immediate
+ assert '#00bdcd 6738 736D#' not in immediate
+
+ assert '#00bdcd Delayed spending#' not in delayed
+ assert 'Available after\n#00bdcd about 1 year#' in delayed
+ assert '#00bdcd Exact delay#' in delayed
+ assert '#00bdcd 52,596 blocks#' not in delayed
+ assert '#00bdcd Any 2 of 3 keys must sign#' not in delayed
+ assert '#00bdcd BACKUP PASSPORT#' not in delayed
+ assert delayed.count('#00bdcd ') == 2
+
+
+def test_conditional_policy_is_rendered_structurally_without_false_simplification():
+ policy = MiniscriptPolicy(
+ 'Conditional', 'BTC',
+ 'wsh(andor(pk(@0/**),pk(@1/**),pk(@2/**)))',
+ tuple(key_info(index) for index in range(3)), (0,))
+ review = '\n'.join(plain_review_pages(policy))
+ assert 'Conditional path' in review
+ assert '\n If\n' in review
+ assert '\n Then also\n' in review
+ assert '\n Otherwise\n' in review
+ assert 'Review the conditional branches carefully' in review
+
+
+def test_height_and_time_locks_get_human_and_exact_descriptions():
+ short, exact, detail = describe_timelock('older', 52596)
+ assert short == 'about 1 year'
+ assert exact == '52,596 blocks'
+ assert 'each coin confirms' in detail
+
+ short, exact, detail = describe_timelock('older', (1 << 22) | 1182)
+ assert short == 'about 1 week'
+ assert exact == '605,184 seconds (1,182 x 512)'
+ assert 'each coin confirms' in detail
+
+ assert describe_timelock('after', 840000)[:2] == (
+ 'block 840,000', 'absolute block height')
+ assert describe_timelock('after', 1700000000)[:2] == (
+ '2023-11-14 UTC', 'Unix timestamp 1,700,000,000')
+
+ assert 'encoded as older(65537)' in describe_timelock('older', 65537)[1]
+
+
+@pytest.mark.parametrize(('blocks', 'short', 'exact'), (
+ (1, 'about 10 minutes', '1 block'),
+ (6, 'about 1 hour', '6 blocks'),
+ (144, 'about 1 day', '144 blocks'),
+ (1008, 'about 1 week', '1,008 blocks'),
+ (26298, 'about 6 months', '26,298 blocks'),
+ (52596, 'about 1 year', '52,596 blocks'),
+ (65535, 'about 1 year 3 months', '65,535 blocks'),
+))
+def test_relative_block_delays_scale_from_one_block_to_consensus_maximum(
+ blocks, short, exact):
+ assert describe_timelock('older', blocks)[:2] == (short, exact)
+
+
+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)')
+ assert describe_timelock('older', (1 << 22) | 65535)[:2] == (
+ 'about 1 year 1 month', '33,553,920 seconds (65,535 x 512)')
+ assert describe_timelock('after', 1798761600)[:2] == (
+ '2027-01-01 UTC', 'Unix timestamp 1,798,761,600')
+
+
+@pytest.mark.parametrize('epoch_offset', (0, 946684800))
+@pytest.mark.parametrize('timestamp, expected', (
+ (500000000, '1985-11-05 UTC'),
+ (946684799, '1999-12-31 UTC'),
+ (946684800, '2000-01-01 UTC'),
+ (951782400, '2000-02-29 UTC'),
+ (1709251200, '2024-03-01 UTC'),
+ (1798761600, '2027-01-01 UTC'),
+ (2147483647, '2038-01-19 UTC'),
+))
+def test_absolute_dates_are_independent_of_runtime_epoch(
+ monkeypatch, epoch_offset, timestamp, expected):
+ import time
+
+ def gmtime(seconds):
+ # Model STM32's unsigned seconds since 2000 as well as the host epoch.
+ if epoch_offset and seconds < 0:
+ raise OverflowError('unsigned time_t')
+ return time.gmtime(seconds + epoch_offset)
+
+ monkeypatch.setitem(sys.modules, 'utime', types.SimpleNamespace(gmtime=gmtime))
+ assert describe_timelock('after', timestamp)[0] == expected
+
+
+def test_absolute_path_compatibility_requires_matching_locktime_and_sequence():
+ policy = MiniscriptPolicy(
+ 'Absolute Recovery', 'BTC',
+ 'wsh(or_i(pk(@0/**),and_v(v:pk(@1/**),after(840000))))',
+ (key_info(0), key_info(1)), (0,))
+
+ # The immediate path remains possible in every case. The absolute path is
+ # excluded until nLockTime reaches its height and an input is non-final.
+ assert compatible_path_indexes(policy, 2, 839999, 0xfffffffe) == (0,)
+ assert compatible_path_indexes(policy, 2, 840000, 0xffffffff) == (0,)
+ assert compatible_path_indexes(policy, 2, 840000, 0xfffffffe) == (0, 1)
+ # A timestamp locktime cannot satisfy a block-height policy.
+ assert compatible_path_indexes(policy, 2, 1700000000, 0xfffffffe) == (0,)
+
+
+def test_relative_path_compatibility_rejects_unit_and_value_mismatches():
+ policy = MiniscriptPolicy(
+ 'Relative Recovery', 'BTC',
+ 'wsh(or_i(pk(@0/**),and_v(v:pk(@1/**),older(1008))))',
+ (key_info(0), key_info(1)), (0,))
+
+ assert compatible_path_indexes(policy, 2, 0, 1007) == (0,)
+ assert compatible_path_indexes(policy, 2, 0, 1008) == (0, 1)
+ assert compatible_path_indexes(policy, 2, 0, (1 << 22) | 1008) == (0,)
+
+
+@pytest.mark.parametrize('lock', ['older(10)', 'after(840000)'])
+@pytest.mark.parametrize(('template', 'structure'), [
+ ('wsh(and_v(v:pk(@0/**),or_i(pk(@1/**),and_v(v:pk(@2/**),{lock}))))',
+ 'Any one of'),
+ ('wsh(andor(pk(@0/**),and_v(v:pk(@1/**),{lock}),pk(@2/**)))',
+ 'Conditional path'),
+ ('wsh(thresh(2,pk(@0/**),s:pk(@1/**),sjn:and_v(v:pk(@2/**),{lock})))',
+ '2 of 3 conditions'),
+])
+def test_nested_timing_remains_structural_in_registration_and_signing(template, structure, lock):
+ policy = MiniscriptPolicy(
+ 'Conditional timing', 'BTC', template.format(lock=lock),
+ tuple(key_info(index) for index in range(3)), (0,))
+
+ # A valid authorization remains available without executing the optional lock.
+ compatible = compatible_path_indexes(policy, 2, 0, 0xffffffff)
+ assert compatible == (0,)
+ review = '\n'.join(plain_review_pages(policy))
+ signing = '\n'.join(without_recolor(page) for page in policy.format_signing_pages(compatible))
+ for text in (review, signing):
+ assert 'Conditional timing' in text
+ assert 'Timing depends on the branch used.' in text
+ assert structure in text
+ assert ('10 blocks' if lock.startswith('older') else '840,000') in text
+ assert 'Available after' not in text
+ assert 'Delayed spending' not in text
+ assert 'Spend now' not in text
+ assert 'This Passport will sign:\nConditional timing:' in signing
+
+
+def test_unconditional_lock_still_filters_a_path_with_nested_optional_timing():
+ policy = MiniscriptPolicy(
+ 'Mixed timing', 'BTC',
+ 'wsh(and_v(v:older(5),and_v(v:pk(@0/**),'
+ 'or_i(pk(@1/**),and_v(v:pk(@2/**),older(10))))))',
+ tuple(key_info(index) for index in range(3)), (0,))
+
+ assert compatible_path_indexes(policy, 2, 0, 4) == ()
+ assert compatible_path_indexes(policy, 2, 0, 5) == (0,)
+ assert compatible_path_indexes(policy, 2, 0, 10) == (0,)
+ review = '\n'.join(plain_review_pages(policy))
+ assert '5 blocks' in review
+ assert '10 blocks' in review
+ assert 'Available after' not in review
### ports/stm32/boards/Passport/modules/tests/host/test_psbt_display.py
@@ -0,0 +1,67 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import os
+import sys
+
+
+MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+if MODULES not in sys.path:
+ sys.path.insert(0, MODULES)
+
+from psbt_display import format_psbt_error, format_signed_psbt_message # noqa: E402
+
+
+def test_missing_input_script_explains_coordinator_action_before_technical_detail():
+ technical = 'Missing redeem/witness script for input #0'
+ friendly, detail = format_psbt_error(technical)
+ assert 'missing information Passport needs to verify how an input can be spent' in friendly
+ assert 'Re-export it from your wallet coordinator' in friendly
+ assert 'witness or redeem script' in friendly
+ assert detail == technical
+ assert technical not in friendly
+
+
+def test_missing_output_script_explains_change_verification():
+ technical = 'Missing redeem/witness script for output #1'
+ friendly, detail = format_psbt_error(technical)
+ assert 'verify a change output' in friendly
+ assert detail == technical
+
+
+def test_registered_policy_mismatch_tells_user_not_to_sign():
+ technical = 'Wallet policy change output does not match: script mismatch'
+ friendly, detail = format_psbt_error(technical)
+ assert 'Do not sign' in friendly
+ assert 'create the transaction again' in friendly
+ assert detail == technical
+
+
+def test_input_policy_mismatch_gets_the_same_fail_closed_guidance():
+ technical = 'Input #0: PSBT scripts and derivations do not match the registered policy'
+ friendly, detail = format_psbt_error(technical)
+ assert 'does not match the registered wallet policy and Passport key' in friendly
+ assert 'Do not sign' in friendly
+ assert detail == technical
+
+
+def test_unmapped_error_is_preserved_without_redundant_details_page():
+ assert format_psbt_error('Transaction is already fully signed.') == (
+ 'Transaction is already fully signed.', None)
+
+
+def test_partial_psbt_success_explains_the_coordinator_handoff():
+ text = format_signed_psbt_message('/card/payment-part.psbt')
+ assert text.startswith('Passport signature added')
+ assert 'Updated PSBT\n/card/payment-part.psbt' in text
+ assert 'collect any remaining signatures, finalize, and broadcast' in text
+ assert 'finalized transaction' not in text
+
+
+def test_complete_psbt_success_distinguishes_psbt_from_final_transaction():
+ text = format_signed_psbt_message(
+ '/card/payment-signed.psbt', '/card/payment-final.txn', 'abc123')
+ assert 'Return the updated PSBT to your wallet coordinator to finalize and broadcast' in text
+ assert 'also saved a finalized transaction that is ready to broadcast' in text
+ assert '/card/payment-final.txn' in text
+ assert 'Transaction ID\nabc123' in text
### ports/stm32/boards/Passport/modules/tests/host/test_review_regressions.py
@@ -0,0 +1,373 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""SFT-974 review regressions; assertions describe the required behavior.
+
+Run with the other host tests. Hardware/UI adapters are replaced, while the
+policy parser, output validator and signing task are the production code.
+All keys are derived from synthetic, public test seeds.
+"""
+
+import ast
+import asyncio
+import base64
+import builtins
+import collections
+import hashlib
+import io
+import runpy
+import struct
+import sys
+import types
+from pathlib import Path
+
+import pytest
+from embit import bip32, ec, script
+
+
+MODULES = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(MODULES)) if str(MODULES) not in sys.path else None
+
+
+def test_keys(count):
+ result = []
+ for index in range(count):
+ root = bip32.HDKey.from_seed(bytes([index + 1]) * 32)
+ account = root.derive("m/48h/0h/0h/2h").to_public()
+ result.append("[{} /48'/0'/0'/2']{}".format(
+ root.my_fingerprint.hex(), account.to_base58()).replace(' ', ''))
+ return result
+
+
+test_keys.__test__ = False
+
+
+@pytest.fixture
+def psbt_module(monkeypatch):
+ """Load actual PSBT code with only platform dependencies adapted."""
+ monkeypatch.setattr(builtins, 'const', lambda value: value, raising=False)
+
+ def module(name, **attrs):
+ value = types.ModuleType(name)
+ value.__dict__.update(attrs)
+ monkeypatch.setitem(sys.modules, name, value)
+ return value
+
+ for name, value in (('ustruct', struct), ('uio', io),
+ ('ucollections', collections)):
+ monkeypatch.setitem(sys.modules, name, value)
+ import binascii
+ monkeypatch.setitem(sys.modules, 'ubinascii', binascii)
+ module('trezorcrypto', sha256=hashlib.sha256,
+ ripemd160=lambda data: hashlib.new('ripemd160', data))
+ module('utils', xfp2str=lambda value: value.to_bytes(4, 'little').hex(),
+ B2A=lambda value: value.hex(), bytes_to_hex_str=lambda value: value.hex(),
+ keypath_to_str=lambda value: tuple(value), swab32=lambda value: value,
+ get_accounts_by_xfp=None, get_derived_keys=None)
+ module('chains')
+ module('common')
+ module('history', verify_amount=lambda *args: None,
+ OutptValueCache=types.SimpleNamespace(record_amount=lambda *args: None))
+ module('sffile', SizerFile=object)
+ module('passport', mem=types.SimpleNamespace())
+ module('constants', PSBT_MAX_SIZE=1024 * 1024)
+ module('multisig_wallet', MultisigWallet=object,
+ disassemble_multisig_mn=lambda _: (1, 2))
+ module('taproot', output_script=lambda *args: b'', tagged_hash=lambda *args: b'')
+ for name in ('public_constants', 'serializations', 'exceptions'):
+ loaded = module(name)
+ loaded.__dict__.update(runpy.run_path(str(MODULES / (name + '.py'))))
+ wallet_utils = module('wallets.utils')
+ wallet_utils.__dict__.update(runpy.run_path(str(MODULES / 'wallets/utils.py')))
+ return types.SimpleNamespace(**runpy.run_path(str(MODULES / 'psbt.py')))
+
+
+@pytest.mark.parametrize('output_kind', ['p2pkh', 'p2wpkh', 'p2sh-p2wpkh'])
+@pytest.mark.parametrize('registered_policy', [True, False])
+@pytest.mark.parametrize('derivation_kind', ['policy', 'singlesig'])
+def test_policy_funds_sent_to_singlesig_are_not_hidden_as_change(
+ monkeypatch, psbt_module, output_kind, registered_policy, derivation_kind):
+ from wallet_policy import MiniscriptPolicy
+ policy = MiniscriptPolicy('Two signers', 'BTC',
+ 'wsh(multi(2,@0/**,@1/**))', test_keys(2), (0,))
+ root = bip32.HDKey.from_seed(bytes([1]) * 32)
+ if derivation_kind == 'policy':
+ derivation = bip32.parse_path('m/48h/0h/0h/2h/1/7')
+ else:
+ purpose = {'p2pkh': 44, 'p2wpkh': 84, 'p2sh-p2wpkh': 49}[output_kind]
+ derivation = bip32.parse_path('m/{}h/0h/0h/1/7'.format(purpose))
+ child = root.derive(derivation)
+ pubkey = child.get_public_key()
+ xfp = int.from_bytes(root.my_fingerprint, 'little')
+ path = [xfp] + derivation
+ redeem_script = script.p2wpkh(pubkey).data if output_kind == 'p2sh-p2wpkh' else b''
+ output_script = script.p2sh(script.Script(redeem_script)).data if redeem_script else \
+ getattr(script, output_kind)(pubkey).data
+ txo = sys.modules['serializations'].CTxOut(10000, output_script)
+ output = psbt_module.psbtOutputProxy(io.BytesIO(b'\x00'), 0)
+ # Exercise the production derivation decoder using its file-offset values.
+ derivation_bytes = struct.pack('<{}I'.format(len(path)), *path)
+ output.fd = io.BytesIO(derivation_bytes + redeem_script)
+ output.subpaths = {pubkey.sec(): (0, len(derivation_bytes))}
+ if redeem_script:
+ output.redeem_script = (len(derivation_bytes), len(redeem_script))
+ output.validate(0, txo, xfp, None, policy if registered_policy else None)
+ # The final ownership check also passes: this really is Passport's key,
+ # but the output has removed the other signer's authorization requirement.
+
+ class Values:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def derive_path(self, path):
+ return types.SimpleNamespace(public_key=lambda: pubkey.sec())
+
+ monkeypatch.setitem(sys.modules, 'stash', types.SimpleNamespace(SensitiveValues=Values))
+ monkeypatch.setitem(sys.modules, 'errors', types.SimpleNamespace(Error=object))
+ results = []
+
+ async def done(message, code):
+ results.append((message, code))
+
+ check = runpy.run_path(str(MODULES / 'tasks/double_check_psbt_change_task.py'))[
+ 'double_check_psbt_change_task']
+ asyncio.run(check(done, types.SimpleNamespace(outputs=[output], my_xfp=xfp)))
+ assert results == [(None, None)]
+ if registered_policy or derivation_kind == 'policy':
+ assert not output.is_change, 'An output outside the registered policy must be displayed'
+ else:
+ assert output.is_change, 'Ordinary singlesig change must still be recognized'
+
+
+def test_nested_optional_timelock_does_not_hide_immediate_authorization():
+ from wallet_policy import MiniscriptPolicy
+ from policy_display import compatible_path_indexes, policy_paths
+ policy = MiniscriptPolicy(
+ 'Nested alternatives', 'BTC',
+ 'wsh(or_i(and_v(v:pk(@0/**),or_i(pk(@1/**),'
+ 'and_v(v:pk(@2/**),older(10)))),pk(@3/**)))', test_keys(4), (0,))
+ paths = policy_paths(policy)
+ compatible = compatible_path_indexes(policy, 2, 0, 0xffffffff)
+ # Passport + key 1 satisfy the first outer branch without executing CSV.
+ assert any(0 in paths[index]['keys'] for index in compatible), (
+ 'A satisfiable Passport authorization disappeared from the signing review: ' +
+ repr(policy.format_signing_pages(compatible)))
+
+
+@pytest.fixture
+def multi_policy_input(monkeypatch, psbt_module):
+ from wallet_policy import MiniscriptPolicy
+
+ class Node:
+ def __init__(self, xpub):
+ self.node = bip32.HDKey.from_base58(xpub)
+
+ def depth(self):
+ return self.node.depth
+
+ def derive(self, index, public=False):
+ self.node = self.node.child(index)
+
+ def public_key(self):
+ return self.node.get_public_key().sec()
+
+ chain = types.SimpleNamespace(
+ ctype='BTC', deserialize_node=lambda xpub, fmt: Node(xpub),
+ p2sh_address=lambda fmt, witness: script.p2wsh(script.Script(witness)).address())
+ monkeypatch.setitem(sys.modules, 'chains', types.SimpleNamespace(current_chain=lambda: chain))
+ policy = MiniscriptPolicy('Registered multi', 'BTC',
+ 'wsh(multi(2,@0/**,@1/**))', test_keys(2), (0,))
+ derived, paths, _ = policy._derive_with_paths(0, 7, chain)
+ settings = {'wallet_policies': [policy.serialize()]}
+ monkeypatch.setitem(sys.modules, 'common', types.SimpleNamespace(settings=settings))
+ xfp = int.from_bytes(bytes.fromhex(policy.keys[0].fingerprint), 'little')
+
+ def make_input(registered=True, include_global_xpubs=True):
+ settings['wallet_policies'] = [policy.serialize()] if registered else []
+ inp = psbt_module.psbtInputProxy(io.BytesIO(b'\x00'), 0)
+ inp.fd = io.BytesIO(derived.witness_script)
+ inp.witness_script = (0, len(derived.witness_script))
+ inp.subpaths = paths
+ inp.sighash = 1
+ psbt = object.__new__(psbt_module.psbtObject)
+ psbt.inputs = [inp]
+ psbt.my_xfp = xfp
+ psbt.active_policy = None
+ psbt.active_multisig = None
+ psbt.multisig_import_needs_approval = False
+ psbt.xpubs = {(struct.pack('<5I', int.from_bytes(bytes.fromhex(key.fingerprint), 'little'),
+ *key.path), bytes([index])): None
+ for index, key in enumerate(policy.keys)} if include_global_xpubs else {}
+ txo = sys.modules['serializations'].CTxOut(10000, derived.script_pubkey)
+ return psbt, inp, txo
+
+ return policy, make_input
+
+
+@pytest.mark.parametrize('include_global_xpubs', [False, True])
+def test_registered_multi_policy_is_not_preempted_by_global_xpubs(
+ monkeypatch, psbt_module, multi_policy_input, include_global_xpubs):
+ policy, make_input = multi_policy_input
+ psbt, inp, txo = make_input(include_global_xpubs=include_global_xpubs)
+
+ def forbidden_discovery(*args):
+ pytest.fail('Registered policy triggered legacy discovery/import')
+
+ monkeypatch.setitem(psbt_module.psbtObject.handle_xpubs.__globals__, 'MultisigWallet',
+ types.SimpleNamespace(find_candidates=forbidden_discovery,
+ import_from_psbt=forbidden_discovery))
+ # Exercise initial validation too: it must not activate a wallet from
+ # global metadata before the real per-input policy matcher gets a turn.
+ psbt.txn = (0, 64)
+ psbt.num_inputs = 1
+ psbt.num_outputs = 1
+ monkeypatch.setattr(psbt_module.psbtObject, 'input_iter', lambda self: iter([(0, None)]))
+ monkeypatch.setattr(psbt_module.psbtInputProxy, 'validate', lambda *args: None)
+ asyncio.run(psbt.validate())
+ inp.determine_my_signing_key(0, txo, psbt.my_xfp, psbt)
+ assert psbt.active_policy.policy_id == policy.policy_id
+ assert inp.policy_spend_plan is not None
+ assert psbt.active_multisig is None
+ assert not psbt.multisig_import_needs_approval
+
+
+@pytest.mark.parametrize('discovery', ['stored', 'import', 'no_global_xpubs'])
+def test_legacy_multisig_discovery_still_validates_and_requests_approval(
+ monkeypatch, psbt_module, multi_policy_input, discovery):
+ _, make_input = multi_policy_input
+ psbt, inp, txo = make_input(registered=False, include_global_xpubs=discovery != 'no_global_xpubs')
+ calls = []
+
+ def assert_matching(m, n, paths):
+ assert (m, n) == (2, 2)
+ assert paths == sorted(inp.subpaths.values())
+ calls.append('match')
+
+ def validate_script(witness, subpaths):
+ assert witness == inp.get(inp.witness_script)
+ assert subpaths == inp.subpaths
+ calls.append('script')
+
+ legacy = types.SimpleNamespace(
+ M=2, N=2, assert_matching=assert_matching, validate_script=validate_script,
+ validate_psbt_xpubs=lambda value: calls.append('xpubs'))
+
+ def import_wallet(m, n, xpubs):
+ assert (m, n) == (2, 2)
+ assert xpubs == psbt.xpubs
+ calls.append('import')
+ return legacy, True
+
+ namespace = psbt_module.psbtObject.handle_xpubs.__globals__
+ monkeypatch.setitem(namespace, 'disassemble_multisig_mn', lambda _: (2, 2))
+ monkeypatch.setitem(namespace, 'MultisigWallet', types.SimpleNamespace(
+ find_candidates=lambda paths: [legacy] if discovery == 'stored' else [],
+ import_from_psbt=import_wallet, find_match=lambda *args: legacy))
+ inp.determine_my_signing_key(0, txo, psbt.my_xfp, psbt)
+ assert psbt.active_multisig is legacy
+ assert psbt.active_policy is None
+ assert inp.policy_spend_plan is None
+ assert inp.required_key
+ assert psbt.multisig_import_needs_approval == (discovery == 'import')
+ assert calls == ({'stored': ['xpubs', 'match', 'script'],
+ 'import': ['import', 'match', 'script'],
+ 'no_global_xpubs': ['match', 'script']}[discovery])
+
+
+@pytest.mark.parametrize('policy_first', [False, True])
+def test_actual_mixed_policy_and_legacy_inputs_still_fail(
+ monkeypatch, psbt_module, multi_policy_input, policy_first):
+ policy, make_input = multi_policy_input
+ psbt, inp, txo = make_input(registered=not policy_first)
+ if policy_first:
+ psbt.active_policy = policy
+ else:
+ psbt.active_multisig = object()
+ namespace = psbt_module.psbtObject.handle_xpubs.__globals__
+ monkeypatch.setitem(namespace, 'disassemble_multisig_mn', lambda _: (2, 2))
+ with pytest.raises(sys.modules['exceptions'].FatalPSBTIssue, match='Cannot mix'):
+ inp.determine_my_signing_key(1, txo, psbt.my_xfp, psbt)
+
+
+@pytest.mark.parametrize('collision', [False, True])
+def test_legacy_multisig_ignores_a_nonowned_fingerprint_collision(monkeypatch, psbt_module, collision):
+ owned = ec.PrivateKey(bytes([1]) * 32)
+ foreign = ec.PrivateKey(bytes([2]) * 32)
+ owned_pub = owned.get_public_key().sec()
+ foreign_pub = foreign.get_public_key().sec()
+ xfp = 0x12345678
+
+ class Node:
+ def public_key(self):
+ return owned_pub
+
+ def private_key(self):
+ return bytearray(owned.secret)
+
+ class Values:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def derive_path(self, *args, **kwargs):
+ return Node()
+
+ monkeypatch.setitem(sys.modules, 'stash', types.SimpleNamespace(
+ SensitiveValues=Values, blank_object=lambda value: None))
+ monkeypatch.setitem(sys.modules, 'errors', types.SimpleNamespace(
+ Error=types.SimpleNamespace(PSBT_FATAL_ERROR=1, PSBT_FRAUDULENT_CHANGE_ERROR=2,
+ OUT_OF_MEMORY_ERROR=3)))
+ monkeypatch.setitem(sys.modules, 'foundation', types.SimpleNamespace(
+ secp256k1=types.SimpleNamespace(sign_ecdsa=lambda *args: bytes([1]) * 64)))
+ monkeypatch.setattr(sys.modules['taproot'], 'taproot_sign_key', lambda *args: None,
+ raising=False)
+ inp = types.SimpleNamespace(
+ has_utxo=lambda: True,
+ required_key={owned_pub, foreign_pub} if collision else {owned_pub}, fully_signed=False,
+ scriptSig=b'script', policy_spend_plan=None, is_segwit=True, is_multisig=True,
+ tap_subpaths={}, amount=10000, scriptCode=b'script', sighash=1,
+ subpaths={owned_pub: [xfp, 0], foreign_pub: [xfp, 0]}, added_sigs=None,
+ added_sig=None, tap_key_sig=None)
+ # The integrated signer delegates legacy candidate selection to this helper.
+ inp.get_signing_node = types.MethodType(psbt_module.psbtInputProxy.get_signing_node, inp)
+ psbt = types.SimpleNamespace(
+ inputs=[inp], my_xfp=xfp,
+ input_iter=lambda: iter([(0, types.SimpleNamespace(prevout=object()))]),
+ make_txn_segwit_sighash=lambda *args: bytes(32))
+ results = []
+
+ async def done(message, code):
+ results.append((message, code))
+
+ task = runpy.run_path(str(MODULES / 'tasks/sign_psbt_task.py'))['sign_psbt_task']
+ asyncio.run(task(done, psbt))
+ assert results == [(None, None)], results
+ signatures = dict(inp.added_sigs or {})
+ if inp.added_sig:
+ signatures[inp.added_sig[0]] = inp.added_sig[1]
+ assert set(signatures) == {owned_pub}
+
+
+def _liana_fixture_constants():
+ tree = ast.parse((MODULES / 'tests/unit/wallet_policy_psbt.py').read_text())
+ return {node.targets[0].id: ast.literal_eval(node.value)
+ for node in tree.body if isinstance(node, ast.Assign) and
+ isinstance(node.targets[0], ast.Name) and
+ node.targets[0].id in ('LIANA_DESCRIPTOR', 'LIANA_PSBT_BASE64')}
+
+
+def test_liana_simulator_descriptor_fixture_is_loadable():
+ from wallet_policy import MiniscriptPolicy
+ descriptor = _liana_fixture_constants()['LIANA_DESCRIPTOR']
+ policy = MiniscriptPolicy.from_multipath_descriptor('Liana', 'TBTC', descriptor, (0,))
+ assert policy.context == 'wsh'
+
+
+def test_liana_simulator_psbt_fixture_is_strict_base64():
+ encoded = _liana_fixture_constants()['LIANA_PSBT_BASE64']
+ assert base64.b64decode(encoded, validate=True).startswith(b'psbt\xff')
### ports/stm32/boards/Passport/modules/tests/host/test_startup_imports.py
@@ -0,0 +1,78 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Regression tests for Passport's startup import budget.
+
+The Color device has a small MicroPython heap. Importing transaction and
+wallet-policy implementation modules from the package aggregators can exhaust
+that heap before LVGL replaces the bootloader splash screen.
+"""
+
+import ast
+from pathlib import Path
+
+
+MODULES = Path(__file__).resolve().parents[2]
+MANIFEST = MODULES.parent / 'manifest.py'
+
+
+def _top_level_imports(relative_path):
+ tree = ast.parse((MODULES / relative_path).read_text())
+ imports = set()
+ for node in tree.body:
+ if isinstance(node, ast.ImportFrom):
+ imports.add(node.module or '')
+ elif isinstance(node, ast.Import):
+ imports.update(alias.name for alias in node.names)
+ return imports
+
+
+def _nested_imports(relative_path):
+ tree = ast.parse((MODULES / relative_path).read_text())
+ top_level_ids = {id(node) for node in tree.body}
+ imports = set()
+ for node in ast.walk(tree):
+ if id(node) in top_level_ids:
+ continue
+ if isinstance(node, ast.ImportFrom):
+ imports.add(node.module or '')
+ elif isinstance(node, ast.Import):
+ imports.update(alias.name for alias in node.names)
+ return imports
+
+
+def test_heavy_policy_tasks_are_not_imported_during_boot():
+ imports = _top_level_imports('tasks/__init__.py')
+ assert not {
+ 'restore_backup_task',
+ 'search_for_address_task',
+ 'sign_psbt_task',
+ 'wallet_policy_task',
+ } & imports
+
+
+def test_wallet_policy_flow_is_not_imported_during_boot():
+ assert 'wallet_policy_flow' not in _top_level_imports('flows/__init__.py')
+
+
+def test_heavy_tasks_are_loaded_only_when_their_flows_need_them():
+ assert 'tasks.restore_backup_task' in _nested_imports('flows/restore_backup_flow.py')
+ assert 'tasks.sign_psbt_task' in _nested_imports('flows/sign_psbt_common_flow.py')
+ assert 'tasks.search_for_address_task' in _nested_imports('flows/verify_address_flow.py')
+
+
+def test_wallet_policy_ui_is_loaded_only_when_its_menu_is_opened():
+ assert 'flows.wallet_policy_flow' not in _top_level_imports('menus.py')
+ assert 'flows.wallet_policy_flow' in _nested_imports('menus.py')
+
+
+def test_liana_exporter_is_loaded_only_when_selected():
+ assert 'liana' not in _top_level_imports('wallets/sw_wallets.py')
+ assert 'liana' in _nested_imports('wallets/sw_wallets.py')
+
+
+def test_lazily_imported_wallet_policy_helpers_are_frozen():
+ manifest = MANIFEST.read_text()
+ assert "'psbt_display.py'" in manifest
+ assert "'tasks/search_for_address_task.py'" in manifest
+ assert "'wallets/liana.py'" in manifest
### ports/stm32/boards/Passport/modules/tests/host/test_verify_address_flow.py
@@ -0,0 +1,84 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Host regressions for launching wallet-policy address verification."""
+
+import asyncio
+import builtins
+import runpy
+import sys
+import types
+from pathlib import Path
+
+
+MODULES = Path(__file__).resolve().parents[2]
+
+
+def test_policy_verification_does_not_require_an_active_account(monkeypatch):
+ flows = types.ModuleType('flows')
+
+ class Flow:
+ def __init__(self, initial_state=None, name=None):
+ self.state = initial_state
+ self.name = name
+
+ flows.Flow = Flow
+
+ common = types.ModuleType('common')
+ common.ui = types.SimpleNamespace(get_active_account=lambda: None)
+
+ microns = types.ModuleType('microns')
+
+ monkeypatch.setitem(sys.modules, 'flows', flows)
+ monkeypatch.setitem(sys.modules, 'common', common)
+ monkeypatch.setitem(sys.modules, 'microns', microns)
+ monkeypatch.setattr(builtins, 'const', lambda value: value, raising=False)
+
+ namespace = runpy.run_path(str(MODULES / 'flows/verify_address_flow.py'))
+ verify_flow = namespace['VerifyAddressFlow'](
+ sig_type='policy', wallet_policy=object())
+
+ assert verify_flow.acct_num == 0
+
+
+def test_successful_post_import_verification_exits_to_policy_menu(monkeypatch):
+ flows = types.ModuleType('flows')
+
+ class Flow:
+ pass
+
+ class VerifyAddressFlow:
+ result = True
+
+ def __init__(self, sig_type=None, wallet_policy=None):
+ assert sig_type == 'policy'
+ assert wallet_policy is not None
+
+ async def run(self):
+ return self.result
+
+ flows.Flow = Flow
+ flows.SaveToMicroSDFlow = type('SaveToMicroSDFlow', (), {})
+ flows.VerifyAddressFlow = VerifyAddressFlow
+ monkeypatch.setitem(sys.modules, 'flows', flows)
+
+ namespace = runpy.run_path(str(MODULES / 'flows/wallet_policy_flow.py'))
+ flow_class = namespace['ImportWalletPolicyFlow']
+
+ flow = object.__new__(flow_class)
+ flow.policy = object()
+ results = []
+ destinations = []
+ flow.set_result = results.append
+ flow.goto = lambda state, save_curr=True: destinations.append(
+ (state, save_curr))
+
+ asyncio.run(flow.verify_first_address())
+ assert results == [True]
+ assert destinations == []
+
+ VerifyAddressFlow.result = False
+ results.clear()
+ asyncio.run(flow.verify_first_address())
+ assert results == []
+ assert destinations == [(flow.choose_next_action, False)]
### ports/stm32/boards/Passport/modules/tests/host/test_wallet_policy.py
@@ -0,0 +1,520 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import hashlib
+import json
+import builtins
+import os
+import sys
+import types
+
+import pytest
+
+
+MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+if MODULES not in sys.path:
+ sys.path.insert(0, MODULES)
+
+if not hasattr(builtins, 'const'):
+ builtins.const = lambda value: value
+sys.modules.setdefault('public_constants', types.SimpleNamespace(
+ AF_P2SH=8, AF_P2WSH=14, AF_P2WSH_P2SH=26))
+
+from descriptor import append_checksum, split_checksum # noqa: E402
+from policy_errors import (PolicyMismatchError, PolicyParseError, # noqa: E402
+ PolicyResourceError, PolicyTypeError)
+from wallet_policy import (KeyInfo, MAX_ORIGIN_DEPTH, MiniscriptPolicy, # noqa: E402
+ WalletPolicyRegistry,
+ descriptor_to_policy_template,
+ validate_backup_policy_records)
+from policy_transport import (bounded_transport_read, # noqa: E402
+ decode_address_request,
+ decode_policy_transport,
+ encode_address_response,
+ encode_policy_transport)
+
+
+XPUB = ('xpub6Br37sWxruYfT8ASpCjVHKGwgdnYFEn98DwiN76i2oyY6fgH1LAPmmDcF46x'
+ 'jxJr22gw4jmVjTE2E3URMnRPEPYyo1zoPSUba563ESMXCeb')
+KEY_INFO = "[6738736c/84'/0'/0']" + XPUB
+PUBKEY = bytes.fromhex(
+ '031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f')
+
+
+class StubChain:
+ ctype = 'BTC'
+
+ @staticmethod
+ def p2sh_address(addr_format, witness_script):
+ return 'test-address-' + hashlib.sha256(witness_script).hexdigest()[:8]
+
+
+class MockNode:
+ def __init__(self, xpub, depth):
+ self.xpub = xpub
+ self._depth = depth
+ self.path = []
+
+ def depth(self):
+ return self._depth
+
+ def derive(self, value, public=False):
+ assert public
+ self.path.append(value)
+
+ def public_key(self):
+ digest = hashlib.sha256((self.xpub + repr(self.path)).encode()).digest()
+ return bytes([2 + (digest[0] & 1)]) + digest
+
+
+class DerivationChain(StubChain):
+ @staticmethod
+ def deserialize_node(xpub, address_format):
+ assert address_format == 8
+ return MockNode(xpub, 3)
+
+ @staticmethod
+ def serialize_public(node, address_format):
+ assert address_format == 8
+ return node.xpub
+
+
+class OwnedNode:
+ def __init__(self, xpub):
+ self.xpub = xpub
+
+
+class MockSettings:
+ def __init__(self, maximum=8192 - 32):
+ self.current = {'_revision': 1}
+ self.temporary_settings = {}
+ self.temporary_mode = False
+ self.max_json_len = maximum
+
+ def get(self, key, default=None):
+ return self.current.get(key, default)
+
+ def set(self, key, value):
+ self.current[key] = value
+
+
+def test_multisig_opcode_budget_is_checked_before_registration_and_derivation():
+ with pytest.raises(PolicyResourceError, match='201 opcodes'):
+ MiniscriptPolicy('Budget', 'BTC', 'wsh(' + 'j' * 50 + ':multi(1,@0/**))',
+ (KEY_INFO,), (0,))
+
+ policy = MiniscriptPolicy('Budget', 'BTC', 'wsh(' + 'j' * 49 + ':multi(1,@0/**))',
+ (KEY_INFO,), (0,))
+ result = policy.derive(0, 0, StubChain(), lambda *_: PUBKEY)
+ assert result.address.startswith('test-address-')
+
+
+def make_policy(name='Recovery'):
+ return MiniscriptPolicy(
+ name,
+ 'BTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pk(@1/**),older(65535))))',
+ (KEY_INFO, KEY_INFO.replace(XPUB[-1], '1')),
+ (0,),
+ )
+
+
+def convert_xpub_version(xpub, version):
+ alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
+ number = 0
+ for char in xpub:
+ number = number * 58 + alphabet.index(char)
+ raw = number.to_bytes((number.bit_length() + 7) // 8, 'big')
+ raw = b'\0' * (len(xpub) - len(xpub.lstrip('1'))) + raw
+ payload = version + raw[4:-4]
+ checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
+ number = int.from_bytes(payload + checksum, 'big')
+ encoded = ''
+ while number:
+ number, remainder = divmod(number, 58)
+ encoded = alphabet[remainder] + encoded
+ return '1' * (len(payload + checksum) - len((payload + checksum).lstrip(b'\0'))) + encoded
+
+
+def test_descriptor_checksum_is_required_and_verified():
+ body = 'wsh(pk(@0/**))'
+ checksummed = append_checksum(body)
+ assert split_checksum(checksummed) == (body, checksummed[-8:])
+ with pytest.raises(ValueError, match='required'):
+ split_checksum(body)
+ with pytest.raises(ValueError, match='does not match'):
+ split_checksum(checksummed[:-1] + ('q' if checksummed[-1] != 'q' else 'p'))
+
+
+def test_key_information_is_canonical_and_bounded():
+ key = KeyInfo.parse(KEY_INFO)
+ assert key.fingerprint == '6738736c'
+ assert key.path == (0x80000054, 0x80000000, 0x80000000)
+ assert key.canonical() == KEY_INFO
+ assert KeyInfo.parse(KEY_INFO.replace("'", 'h')).canonical() == KEY_INFO
+ with pytest.raises(PolicyParseError):
+ KeyInfo.parse('[xyz/0]' + XPUB)
+ with pytest.raises(PolicyParseError):
+ KeyInfo.parse('[6738736c/00]' + XPUB)
+
+
+@pytest.mark.parametrize('name', (' Recovery', 'Recovery ', 'Bad\nName', 'Bad\x00Name'))
+def test_policy_name_rejects_ambiguous_display_text(name):
+ with pytest.raises(PolicyParseError, match='printable ASCII'):
+ MiniscriptPolicy(name, 'BTC', 'wsh(pk(@0/**))', (KEY_INFO,), (0,))
+
+
+def test_full_multipath_descriptor_converts_to_canonical_policy():
+ second = KEY_INFO.replace(XPUB[-1], '1')
+ full = ('wsh(or_d(pk(' + KEY_INFO + '/<0;1>/*),and_v(v:pk(' +
+ second.replace("'", 'H') + '/<0;1>/*),older(65535))))')
+ template, keys = descriptor_to_policy_template(append_checksum(full))
+ assert template == 'wsh(or_d(pk(@0/<0;1>/*),and_v(v:pk(@1/<0;1>/*),older(65535))))'
+ assert keys == (KEY_INFO, second)
+ policy = MiniscriptPolicy.from_multipath_descriptor(
+ 'Imported', 'BTC', append_checksum(full), (0,))
+ assert policy.template == template
+ assert [key.canonical() for key in policy.keys] == list(keys)
+
+
+@pytest.mark.parametrize('descriptor', (
+ 'wsh(pk(' + KEY_INFO + '/0/*))',
+ 'wsh(pk(' + KEY_INFO + '/<0;0>/*))',
+ 'wsh(pk(' + KEY_INFO + '/<0;1;2>/*))',
+ 'sh(wsh(pk(' + KEY_INFO + '/<0;1>/*)))',
+))
+def test_full_descriptor_converter_rejects_non_bip388_derivation(descriptor):
+ with pytest.raises(PolicyParseError):
+ descriptor_to_policy_template(append_checksum(descriptor))
+
+
+def test_policy_id_is_stable_across_rename_but_contents_are_validated():
+ policy = make_policy()
+ renamed = policy.rename('Inheritance')
+ assert renamed.policy_id == policy.policy_id
+ record = policy.serialize()
+ assert MiniscriptPolicy.deserialize(record).policy_id == policy.policy_id
+ record['t'] = 'wsh(pk(@0/**))'
+ with pytest.raises(PolicyParseError):
+ MiniscriptPolicy.deserialize(record)
+
+
+def test_local_key_names_are_migration_safe_and_do_not_change_policy_identity():
+ policy = make_policy()
+ legacy_record = policy.serialize()
+ assert 'kn' not in legacy_record
+ migrated = MiniscriptPolicy.deserialize(legacy_record)
+ assert migrated.key_names == ('', '')
+
+ named = migrated.name_keys(('', 'Family Recovery'))
+ assert named.policy_id == policy.policy_id
+ assert named.serialize()['kn'] == ['', 'Family Recovery']
+ assert MiniscriptPolicy.deserialize(named.serialize()).key_names == (
+ '', 'Family Recovery')
+ with pytest.raises(PolicyParseError, match='printable ASCII'):
+ migrated.name_key(1, ' Bad label')
+
+
+def test_policy_requires_complete_placeholder_vector_in_first_use_order():
+ with pytest.raises(PolicyParseError, match='@0, @1 order'):
+ MiniscriptPolicy('Bad', 'BTC', 'wsh(multi(1,@1/**,@0/**))',
+ (KEY_INFO, KEY_INFO.replace(XPUB[-1], '1')), (0,))
+ with pytest.raises(PolicyParseError, match='every key'):
+ MiniscriptPolicy('Bad', 'BTC', 'wsh(pk(@0/**))',
+ (KEY_INFO, KEY_INFO.replace(XPUB[-1], '1')), (0,))
+
+
+def test_phase_a_rejects_two_signing_keys_from_owned_xpub():
+ with pytest.raises(PolicyParseError, match='more than one Passport signature'):
+ MiniscriptPolicy(
+ 'Bad', 'BTC',
+ 'wsh(and_v(v:pk(@0/<0;1>/*),pk(@0/<2;3>/*)))',
+ (KEY_INFO,), (0,))
+
+
+def test_liana_multisig_allows_owned_xpub_in_exclusive_paths():
+ fixture = os.path.join(os.path.dirname(__file__), 'fixtures',
+ 'liana-multisig-policy.txt')
+ with open(fixture, 'r', encoding='ascii') as source:
+ descriptor = source.read().strip()
+
+ class LianaChain(DerivationChain):
+ ctype = 'TBTC'
+
+ @staticmethod
+ def deserialize_node(xpub, address_format):
+ assert address_format == 8
+ return MockNode(xpub, 4)
+
+ chain = LianaChain()
+ my_xfp = int.from_bytes(bytes.fromhex('9f141cf0'), 'little')
+ owned_xpub = descriptor.split(']', 1)[1].split('/', 1)[0]
+ policy = decode_policy_transport(
+ descriptor, chain, my_xfp, lambda path: OwnedNode(owned_xpub),
+ default_name='Liana Multisig')
+ review_pages = policy.format_review_pages()
+ assert review_pages
+ assert any('Passport' in page for page in review_pages)
+
+ derived, expected_paths, expected_indexes = policy._derive_with_paths(
+ 0, 12, chain)
+ plan = policy.make_spend_plan(
+ 3, expected_paths, derived.script_pubkey, derived.witness_script,
+ chain, my_xfp, 1)
+ owned_pubkeys = tuple(
+ pubkey for pubkey, key_index in expected_indexes.items()
+ if key_index == policy.owned_key_indexes[0])
+ assert set(plan.expected_pubkeys) == set(owned_pubkeys)
+ assert len(plan.expected_pubkeys) == 2
+ assert {path[-2] for path in plan.owned_key_paths} == {0, 2}
+ assert plan.assert_p2wsh_scope(
+ 3, expected_paths, derived.script_pubkey, derived.witness_script, 1,
+ set(owned_pubkeys))
+
+ already_signed = {owned_pubkeys[0]}
+ assert plan.assert_p2wsh_scope(
+ 3, expected_paths, derived.script_pubkey, derived.witness_script, 1,
+ set(owned_pubkeys) - already_signed, already_signed)
+
+
+def test_policy_derivation_and_exact_script_matching():
+ policy = MiniscriptPolicy('Simple', 'BTC', 'wsh(pk(@0/**))', (KEY_INFO,), (0,))
+ chain = StubChain()
+ derived = policy.derive(0, 7, chain, lambda *_: PUBKEY)
+ assert derived.witness_script == bytes.fromhex(
+ '21031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078fac')
+ assert derived.script_pubkey == b'\x00\x20' + hashlib.sha256(derived.witness_script).digest()
+ assert policy.match_scripts(0, 7, chain, derived.script_pubkey,
+ derived.witness_script, lambda *_: PUBKEY) is not None
+ with pytest.raises(PolicyMismatchError, match='UTXO'):
+ policy.match_scripts(0, 7, chain, bytes(34), derived.witness_script,
+ lambda *_: PUBKEY)
+ with pytest.raises(PolicyMismatchError, match='witness'):
+ policy.match_scripts(0, 7, chain, derived.script_pubkey, b'wrong',
+ lambda *_: PUBKEY)
+
+
+def test_psbt_derivations_produce_immutable_spend_plan():
+ policy = make_policy()
+ chain = DerivationChain()
+ derived, expected_paths, _ = policy._derive_with_paths(0, 12, chain)
+ plan = policy.make_spend_plan(3, expected_paths, derived.script_pubkey,
+ derived.witness_script, chain,
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'), 1)
+ assert plan.policy_id == policy.policy_id
+ assert plan.input_index == 3
+ assert plan.branch == 0
+ assert plan.address_index == 12
+ assert plan.script_context == 'p2wsh'
+ assert plan.timelocks == (('older', 65535),)
+ assert plan.expected_pubkey in expected_paths
+
+ # A registered policy can safely reconstruct a change output's witness
+ # script when a coordinator omits PSBT_OUT_WITNESS_SCRIPT. The complete
+ # derivation map and scriptPubKey must still match exactly.
+ matched, matched_paths, _ = policy.match_derivations(
+ expected_paths, derived.script_pubkey, None, chain,
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'))
+ assert matched.witness_script == derived.witness_script
+ assert matched_paths == expected_paths
+
+ with pytest.raises(PolicyMismatchError, match='do not match'):
+ policy.match_derivations(
+ expected_paths, bytes(34), None, chain,
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'))
+
+ wrong_paths = dict(expected_paths)
+ wrong_key = next(iter(wrong_paths))
+ wrong_paths[wrong_key] = list(wrong_paths[wrong_key][:-1]) + [13]
+ with pytest.raises(PolicyMismatchError, match='do not match'):
+ policy.make_spend_plan(3, wrong_paths, derived.script_pubkey,
+ derived.witness_script, chain,
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'), 1)
+ with pytest.raises(PolicyMismatchError, match='do not match'):
+ policy.match_derivations(
+ wrong_paths, derived.script_pubkey, None, chain,
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'))
+
+
+def test_spend_plan_rejects_non_all_sighash():
+ policy = make_policy()
+ with pytest.raises(PolicyMismatchError, match='SIGHASH_ALL'):
+ policy.make_spend_plan(0, {}, bytes(34), b'', DerivationChain(),
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'), 0)
+
+
+def test_network_mismatch_fails_closed():
+ policy = MiniscriptPolicy('Simple', 'TBTC', 'wsh(pk(@0/**))', (KEY_INFO,), (0,))
+ with pytest.raises(PolicyMismatchError, match='network'):
+ policy.derive(0, 0, StubChain(), lambda *_: PUBKEY)
+
+
+def test_relative_timelock_rejects_values_that_consensus_would_mask():
+ with pytest.raises(PolicyTypeError, match='BIP68 relative timelock limit'):
+ MiniscriptPolicy(
+ 'Too Long', 'BTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pk(@1/**),older(78894))))',
+ (KEY_INFO, KEY_INFO.replace(XPUB[-1], '1')), (0,))
+
+
+def test_registry_validates_records_and_quarantines_corruption():
+ settings = MockSettings()
+ registry = WalletPolicyRegistry(settings)
+ policy = make_policy()
+ registry.save(policy)
+ assert registry.get(policy.policy_id).name == policy.name
+ with pytest.raises(PolicyParseError, match='already'):
+ registry.save(policy)
+
+ settings.current['wallet_policies'].append({'v': 99})
+ assert [item.policy_id for item in registry.iter_policies()] == [policy.policy_id]
+ assert len(registry.invalid_records) == 1
+
+ registry.rename(policy.policy_id, 'New Name')
+ assert registry.get(policy.policy_id).name == 'New Name'
+ registry.rename_keys(policy.policy_id, ('', 'Family Recovery'))
+ assert registry.get(policy.policy_id).key_names == ('', 'Family Recovery')
+ registry.delete(policy.policy_id)
+ assert registry.get(policy.policy_id) is None
+
+
+def test_registry_preserves_settings_headroom():
+ settings = MockSettings(maximum=900)
+ registry = WalletPolicyRegistry(settings)
+ with pytest.raises(PolicyResourceError, match='space'):
+ registry.save(make_policy())
+
+
+def test_backup_restore_validates_each_policy_on_its_declared_network():
+ tpub = convert_xpub_version(XPUB, bytes.fromhex('043587cf'))
+ mainnet = MiniscriptPolicy(
+ 'Mainnet', 'BTC', 'wsh(pk(@0/**))', (KEY_INFO,), (0,))
+ testnet_key = "[6738736c/84'/1'/0']" + tpub
+ testnet = MiniscriptPolicy(
+ 'Testnet', 'TBTC', 'wsh(pk(@0/**))', (testnet_key,), (0,))
+
+ class TestnetChain(DerivationChain):
+ ctype = 'TBTC'
+
+ selected_networks = []
+
+ def chain_lookup(network):
+ selected_networks.append(network)
+ return DerivationChain() if network == 'BTC' else TestnetChain()
+
+ def derive_node(path):
+ coin_type = path[1] & 0x7fffffff
+ return OwnedNode(XPUB if coin_type == 0 else tpub)
+
+ restored = validate_backup_policy_records(
+ [mainnet.serialize(), testnet.serialize()], '6738736c', derive_node,
+ chain_lookup)
+
+ assert selected_networks == ['BTC', 'TBTC']
+ assert [record['net'] for record in restored] == ['BTC', 'TBTC']
+
+
+def test_policy_transport_round_trip_rediscovers_owned_key():
+ policy = make_policy()
+ encoded = encode_policy_transport(policy)
+ decoded = decode_policy_transport(
+ encoded, DerivationChain(),
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'),
+ lambda path: OwnedNode(XPUB))
+ assert decoded.policy_id == policy.policy_id
+ assert decoded.owned_key_indexes == (0,)
+
+
+def test_policy_transport_accepts_ur_bytearray():
+ policy = make_policy()
+ encoded = bytearray(encode_policy_transport(policy), 'utf-8')
+ decoded = decode_policy_transport(
+ encoded, DerivationChain(),
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'),
+ lambda path: OwnedNode(XPUB))
+ assert decoded.policy_id == policy.policy_id
+
+
+def test_policy_transport_rejects_tampered_identity():
+ policy = make_policy()
+ encoded = encode_policy_transport(policy).replace(policy.policy_id, '00' * 32)
+ with pytest.raises(PolicyParseError, match='identity'):
+ decode_policy_transport(
+ encoded, DerivationChain(),
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'),
+ lambda path: OwnedNode(XPUB))
+
+
+def test_raw_descriptor_reports_testnet_mismatch_before_key_ownership():
+ tpub = convert_xpub_version(XPUB, bytes.fromhex('043587cf'))
+ descriptor = append_checksum('wsh(pk({}/**))'.format(
+ KEY_INFO.replace(XPUB, tpub).replace("/84'/0'/0'", "/84'/1'/0'")))
+ with pytest.raises(PolicyMismatchError, match='Bitcoin Testnet.*Switch Passport'):
+ decode_policy_transport(
+ descriptor, DerivationChain(),
+ int.from_bytes(bytes.fromhex('6738736c'), 'little'),
+ lambda path: (_ for _ in ()).throw(AssertionError('ownership ran first')))
+
+
+def test_transport_does_not_treat_local_signer_names_as_coordinator_data():
+ policy = make_policy().name_keys(('', 'Family Recovery'))
+ encoded = encode_policy_transport(policy)
+ assert 'Family Recovery' not in encoded
+
+
+def test_address_request_derives_independently_and_response_is_bound():
+ import json
+ policy = make_policy()
+ registry = types.SimpleNamespace(get=lambda policy_id:
+ policy if policy_id == policy.policy_id else None)
+ request = {
+ 'format': 'passport-address-verification',
+ 'version': 1,
+ 'network': 'BTC',
+ 'policy_id': policy.policy_id,
+ 'descriptor_checksum': policy.descriptor_check().lower(),
+ 'branch': 0,
+ 'index': 7,
+ }
+ decoded, selected, address = decode_address_request(
+ bytearray(json.dumps(request), 'utf-8'), DerivationChain(), registry,
+ policy.policy_id)
+ assert selected is policy
+ assert address.startswith('test-address-')
+ response = json.loads(encode_address_response(decoded, address, '6738736c'))
+ assert response['address'] == address
+ assert response['branch'] == 0
+ assert response['index'] == 7
+ assert response['policy_id'] == policy.policy_id
+ assert response['fingerprint'] == '6738736c'
+
+ request['index'] = True
+ with pytest.raises(PolicyParseError, match='index'):
+ decode_address_request(json.dumps(request), DerivationChain(), registry)
+
+
+def test_policy_microsd_read_is_bounded_before_json_decode():
+ import io
+ assert len(bounded_transport_read(io.BytesIO(b'x' * 8192))) == 4097
+
+
+def test_key_origin_depth_bound():
+ at_limit = KeyInfo.parse('[6738736c' + '/0' * MAX_ORIGIN_DEPTH + ']' + XPUB)
+ assert len(at_limit.path) == MAX_ORIGIN_DEPTH
+ with pytest.raises(PolicyResourceError) as raised:
+ KeyInfo.parse('[6738736c' + '/0' * (MAX_ORIGIN_DEPTH + 1) + ']' + XPUB)
+ assert str(MAX_ORIGIN_DEPTH) in str(raised.value)
+
+
+@pytest.mark.parametrize('field', ['name', 'network', 'template'])
+@pytest.mark.parametrize('value', [None, 0, [], {}])
+def test_transport_field_types_rejected_before_derivation(field, value):
+ envelope = dict(format='passport-wallet-policy', version=1, name='Test', network='BTC',
+ template='wsh(pk(@0/**))', keys=[KEY_INFO])
+ envelope[field] = value
+
+ def derive(path):
+ pytest.fail('Malformed transport reached key derivation')
+
+ with pytest.raises(PolicyParseError):
+ decode_policy_transport(json.dumps(envelope), StubChain(), 0, derive)
### ports/stm32/boards/Passport/modules/tests/host/test_wallet_policy_flows.py
@@ -0,0 +1,197 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import ast
+import asyncio
+import importlib.util
+import io
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from test_wallet_policy import KEY_INFO
+from policy_errors import PolicyResourceError
+from wallet_policy import MiniscriptPolicy, POLICY_STORAGE_KEY
+
+
+MODULES_PARENT_INDEX = 2
+MODULES = Path(__file__).resolve().parents[MODULES_PARENT_INDEX]
+
+
+def load_module(path):
+ spec = importlib.util.spec_from_file_location(path.stem, path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+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 = {}
+ exec(compile(ast.Module(body=[method], type_ignores=[]), filename, 'exec'), namespace)
+ return namespace[method_name]
+
+
+@pytest.mark.parametrize('compatible_sets,expected', [
+ ([], 'could not be checked'),
+ ([()], 'no spending path compatible'),
+ ([(0,), ()], 'no spending path compatible'),
+ ([(0,), (1,)], 'Inputs allow different spending paths'),
+ ([(0,), (0,)], 'Spend now (1-of-1)'),
+])
+def test_authorization_preserves_path_results(monkeypatch, compatible_sets, expected):
+ import policy_display
+ policy = MiniscriptPolicy('Test', 'BTC', 'wsh(pk(@0/**))', (KEY_INFO,), (0,))
+ monkeypatch.setattr(policy_display, 'compatible_path_indexes', lambda policy, version, lock, seq:
+ compatible_sets[seq])
+ pages = []
+
+ class Series:
+ def __init__(self, page_type, args):
+ pages.extend(arg['text'] for arg in args)
+
+ async def run(self):
+ return True
+
+ monkeypatch.setitem(sys.modules, 'flows', SimpleNamespace(SeriesOfPagesFlow=Series))
+ monkeypatch.setitem(sys.modules, 'pages', SimpleNamespace(LongTextPage=object))
+ states = []
+ flow = SimpleNamespace(psbt=SimpleNamespace(
+ active_policy=policy, txn_version=2, lock_time=0,
+ inputs=[SimpleNamespace(policy_spend_plan=SimpleNamespace(policy_id=policy.policy_id))
+ for _ in compatible_sets],
+ input_iter=lambda: enumerate(SimpleNamespace(nSequence=i) for i in range(len(compatible_sets)))),
+ sign_transaction='sign', goto=states.append)
+ asyncio.run(flow_method('sign_psbt_common_flow.py', 'SignPsbtCommonFlow', 'show_policy_authorization')(flow))
+ assert expected in '\n'.join(pages)
+ assert states == ['sign']
+ if not compatible_sets or compatible_sets == [(0,), (1,)]:
+ assert 'Policy Name' in '\n'.join(pages[1:])
+ if any(not paths for paths in compatible_sets):
+ assert 'Spend now (1-of-1)' not in '\n'.join(pages)
+
+
+@pytest.mark.parametrize('task_name,args', [
+ ('save_wallet_policy_task', ('policy',)),
+ ('delete_wallet_policy_task', ('id',)),
+ ('rename_wallet_policy_task', ('id', 'name')),
+ ('rename_wallet_policy_keys_task', ('id', ['name'])),
+])
+@pytest.mark.parametrize('failure', ['capacity', 'io', 'callback'])
+def test_policy_save_errors_and_success_callback(monkeypatch, task_name, args, failure):
+ class SettingsOutOfSpace(Exception):
+ pass
+
+ original = ['original']
+ current = list(original)
+ saves = []
+
+ def save():
+ saves.append(list(current))
+ if len(saves) == 1 and failure in ('capacity', 'io'):
+ raise SettingsOutOfSpace() if failure == 'capacity' else OSError()
+
+ def set_value(key, value):
+ assert key == POLICY_STORAGE_KEY
+ current[:] = value
+
+ settings = SimpleNamespace(get=lambda key, default: current, set=set_value, save=save)
+
+ class Registry:
+ def __init__(self, settings):
+ pass
+
+ def get(self, policy_id):
+ return None if failure == 'missing' else object()
+
+ def change(self, *args):
+ current[:] = ['changed']
+
+ save = delete = rename = rename_keys = change
+
+ errors = SimpleNamespace(USER_SETTINGS_FULL='full', USER_SETTINGS_SAVE_FAILED='failed')
+ monkeypatch.setitem(sys.modules, 'common', SimpleNamespace(settings=settings))
+ monkeypatch.setitem(sys.modules, 'errors', SimpleNamespace(Error=errors))
+ monkeypatch.setitem(sys.modules, 'ext_settings', SimpleNamespace(SettingsOutOfSpace=SettingsOutOfSpace))
+ import wallet_policy
+ monkeypatch.setattr(wallet_policy, 'WalletPolicyRegistry', Registry)
+ task = getattr(load_module(MODULES / 'tasks/wallet_policy_task.py'), task_name)
+ results = []
+
+ async def on_done(error):
+ results.append(error)
+ if failure == 'callback':
+ raise RuntimeError('callback failed')
+
+ if failure == 'callback':
+ with pytest.raises(RuntimeError):
+ asyncio.run(task(on_done, *args))
+ assert current == ['changed']
+ assert len(saves) == 1
+ assert results == [None]
+ else:
+ asyncio.run(task(on_done, *args))
+ assert current == original
+ assert results == ['full' if failure == 'capacity' else 'failed']
+
+
+def test_missing_policy_deletion_reports_save_failure(monkeypatch):
+ test_policy_save_errors_and_success_callback(monkeypatch, 'delete_wallet_policy_task', ('id',), 'missing')
+
+
+def test_microsd_import_bounds_read_before_decode(monkeypatch):
+ data = io.BytesIO(b'x' * 8192)
+
+ class Picker:
+ def __init__(self, **kwargs):
+ pass
+
+ async def run(self):
+ return 'policy', 'policy.txt', False
+
+ async def spinner(label, task, args):
+ path, binary, read_fn = args
+ assert path == 'policy.txt' and binary
+ return read_fn(data), None
+
+ monkeypatch.setitem(sys.modules, 'flows', SimpleNamespace(FilePickerFlow=Picker))
+ monkeypatch.setitem(sys.modules, 'tasks', SimpleNamespace(read_file_task=object()))
+ monkeypatch.setitem(sys.modules, 'utils', SimpleNamespace(spinner_task=spinner))
+ method = flow_method('wallet_policy_flow.py', 'ImportWalletPolicyFromMicroSDFlow', 'choose_file')
+
+ def decode(value):
+ assert len(value) == 4097
+ assert data.tell() == 4097
+ raise PolicyResourceError('too large')
+
+ method.__globals__['_decode_policy'] = decode
+ states = []
+ flow = SimpleNamespace(show_error='error', goto=states.append)
+ asyncio.run(method(flow))
+ assert states == ['error']
+ assert flow.error == 'too large'
+
+
+@pytest.mark.parametrize('scan_result', ['qr-too-large', 'psbt-too-large'])
+def test_qr_import_reports_microsd_fallback(monkeypatch, scan_result):
+ class Scanner:
+ def __init__(self, **kwargs):
+ pass
+
+ async def run(self):
+ return scan_result
+
+ monkeypatch.setitem(sys.modules, 'flows', SimpleNamespace(ScanQRFlow=Scanner))
+ monkeypatch.setitem(sys.modules, 'data_codecs.qr_type', SimpleNamespace(QRType=SimpleNamespace(QR=1, UR2=2)))
+ monkeypatch.setitem(sys.modules, 'foundation', SimpleNamespace(ur=SimpleNamespace(Value=SimpleNamespace(BYTES=1))))
+ monkeypatch.setitem(sys.modules, 'errors', SimpleNamespace(Error=SimpleNamespace(
+ QR_TOO_LARGE='qr-too-large', PSBT_OVERSIZED='psbt-too-large')))
+ states = []
+ flow = SimpleNamespace(show_error='error', goto=states.append)
+ asyncio.run(flow_method('wallet_policy_flow.py', 'ImportWalletPolicyFromQRFlow', 'scan')(flow))
+ assert states == ['error']
+ assert 'microSD' in flow.error
### ports/stm32/boards/Passport/modules/tests/host/test_wallet_policy_release.py
@@ -0,0 +1,67 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import os
+import json
+import sys
+
+import pytest
+
+MODULES = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
+if MODULES not in sys.path:
+ sys.path.insert(0, MODULES)
+
+from policy_errors import UnsupportedPolicyError # noqa: E402
+from policy_transport import decode_policy_transport # noqa: E402
+from test_wallet_policy import DerivationChain, MockSettings, OwnedNode, KEY_INFO # noqa: E402
+from descriptor import append_checksum # noqa: E402
+from wallet_policy import (MiniscriptPolicy, WalletPolicyRegistry, # noqa: E402
+ validate_backup_policy_records)
+
+
+MY_XFP = int.from_bytes(bytes.fromhex('6738736c'), 'little')
+TEMPLATE = 'tr(79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,pk(@0/**))'
+
+
+@pytest.fixture
+def experimental_policy():
+ # Historical experimental records must stay unavailable after removing
+ # their implementation, without deleting the user's stored data.
+ record = {'v': 1, 'id': 'unsupported-taproot-policy', 'n': 'Tap Recovery',
+ 'net': 'BTC', 't': TEMPLATE, 'k': [KEY_INFO], 'o': [0]}
+ transport = json.dumps({'format': 'passport-wallet-policy', 'version': 1,
+ 'name': record['n'], 'network': 'BTC',
+ 'template': TEMPLATE, 'keys': [KEY_INFO]})
+ descriptor = append_checksum(TEMPLATE.replace('@0', KEY_INFO))
+ return descriptor, record, transport
+
+
+@pytest.mark.parametrize('transport_kind', ['descriptor', 'json', 'bytes', 'bytearray'])
+def test_release_rejects_policy_import(experimental_policy, transport_kind):
+ descriptor, _, transport = experimental_policy
+ payload = {'descriptor': descriptor, 'json': transport,
+ 'bytes': transport.encode(), 'bytearray': bytearray(transport.encode())}[transport_kind]
+ with pytest.raises(UnsupportedPolicyError, match='wsh'):
+ decode_policy_transport(payload, DerivationChain(), MY_XFP,
+ lambda path: OwnedNode(KEY_INFO.split(']')[1]))
+
+
+def test_release_rejects_backup_and_existing_records(experimental_policy):
+ _, record, _ = experimental_policy
+ with pytest.raises(UnsupportedPolicyError):
+ MiniscriptPolicy.deserialize(record)
+ with pytest.raises(UnsupportedPolicyError):
+ validate_backup_policy_records([record], '6738736c', None, None)
+ settings = MockSettings()
+ settings.set('wallet_policies', [record])
+ registry = WalletPolicyRegistry(settings)
+ assert list(registry.iter_policies()) == []
+ assert len(registry.invalid_records) == 1
+ assert registry.get(record['id']) is None
+ assert settings.get('wallet_policies') == [record]
+
+
+@pytest.mark.parametrize('template', [TEMPLATE, 'tr(@0/**,pk(@1/**))'])
+def test_taproot_policy_construction_is_unsupported(template):
+ with pytest.raises(UnsupportedPolicyError):
+ MiniscriptPolicy('Unsupported', 'BTC', template, [KEY_INFO], [0])
### ports/stm32/boards/Passport/modules/tests/startup_stubs/sflash.py
@@ -0,0 +1,6 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Select the sparse flash model before the regular simulator model."""
+
+from constrained_sflash import SPIFlash
### ports/stm32/boards/Passport/modules/tests/test_wallet_policy_simulator.py
@@ -0,0 +1,16 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+from pathlib import Path
+
+from fixtures.simulator import exec_file, simulator # noqa: F401
+
+
+def test_registered_policy_psbt_matches_in_micropython(exec_file):
+ script = Path(__file__).parent / 'unit' / 'wallet_policy_psbt.py'
+ exec_file(script)
+
+
+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)
### ports/stm32/boards/Passport/modules/tests/unit/one_of_n_warning.py
@@ -25,6 +25,7 @@ def validate(self, *args):
class MockPSBT:
+ active_policy = None
my_xfp = 123
total_value_out = 1000
fee_is_verified = True
@@ -59,7 +60,7 @@ def render_value(self, value):
class MockFlow:
chain = MockChain()
header = 'Transaction Info'
- sign_transaction = 'sign'
+ show_policy_authorization = 'authorize'
render_warnings = SignPsbtCommonFlow.render_warnings
def __init__(self, psbt):
@@ -81,7 +82,8 @@ def goto(self, state):
assert len(psbt.outputs) == (1 if change is None else 2)
for index, output in enumerate(psbt.outputs):
assert len(output.validations) == 1
- idx, txo, xfp, wallet = output.validations[0]
+ idx, txo, xfp, wallet, active_policy = output.validations[0]
+ assert active_policy is None
assert idx == index and txo.nValue == psbt.values[index]
assert xfp == psbt.my_xfp and wallet is psbt.active_multisig
assert psbt.change_checks == [psbt.my_xfp]
@@ -120,7 +122,7 @@ async def run_tests():
MockPage.flow = flow
MockPage.approve = approve
await SignPsbtCommonFlow.show_warnings(flow)
- assert flow.events == ['review', 'sign' if approve else 'back']
+ assert flow.events == ['review', 'authorize' if approve else 'back']
finally:
pages.LongTextPage = original_page
### ports/stm32/boards/Passport/modules/tests/unit/psbt_change_validation.py
@@ -101,6 +101,7 @@ def __init__(self, inputs, outputs):
self.inputs = inputs
self.outputs = outputs
self.warnings = []
+ self.active_policy = None
class OneOfOneMultisig:
### ports/stm32/boards/Passport/modules/tests/unit/psbt_fee.py
@@ -107,7 +107,7 @@ def derive_path(path, register=True):
class MockSigningInput:
- pass
+ policy_spend_plan = None
class MockInputPSBT:
@@ -186,7 +186,7 @@ def input_iter(self):
class MockOutputProxy:
is_change = False
- def validate(self, _idx, _txout, _xfp, _active_multisig):
+ def validate(self, _idx, _txout, _xfp, _active_multisig, _active_policy):
pass
@@ -200,6 +200,7 @@ def __init__(self, fee_is_verified):
self.warnings = []
self.my_xfp = 0
self.active_multisig = None
+ self.active_policy = None
def output_iter(self):
yield 0, CTxOut(self.total_value_out, P2WPKH_SCRIPT)
### ports/stm32/boards/Passport/modules/tests/unit/psbt_multisig_approval.py
@@ -7,6 +7,7 @@
import flows
import pages
import stash
+import tasks.sign_psbt_task as sign_psbt_task_module
import utils
import uasyncio as asyncio
from exceptions import CHANGE_ADDRESS_NOT_OURS
@@ -46,6 +47,7 @@ class MockPsbt:
def __init__(self, needs_approval):
self.multisig_import_needs_approval = needs_approval
self.active_multisig = 'proposed-wallet'
+ self.active_policy = None
self.my_xfp = MY_XFP
self.outputs = []
@@ -158,7 +160,7 @@ async def run_tests():
(stash, 'SensitiveValues', MockSensitiveValues),
(utils, 'spinner_task', mock_spinner_task),
(sign_psbt_common_flow, 'spinner_task', mock_spinner_task),
- (sign_psbt_common_flow, 'sign_psbt_task', mock_sign_psbt_task),
+ (sign_psbt_task_module, 'sign_psbt_task', mock_sign_psbt_task),
)
originals = [(module, name, getattr(module, name)) for module, name, _ in replacements]
### ports/stm32/boards/Passport/modules/tests/unit/wallet_policy_psbt.py
@@ -0,0 +1,245 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""MicroPython integration smoke test for registered P2WSH policy matching."""
+
+import uasyncio
+from ubinascii import a2b_base64, unhexlify
+from uio import BytesIO
+
+import common
+import history
+import stash
+from exceptions import FatalPSBTIssue, FraudulentChangeOutput
+from psbt import psbtObject
+from wallet_policy import MiniscriptPolicy
+
+
+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()
+
+
+class FixturePublicValues:
+ """Stand in for the keystore using the fixture's owned account xpub."""
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def derive_path(self, path, register=True):
+ import chains
+ from public_constants import AF_CLASSIC
+ from utils import str_to_keypath
+
+ policy = MiniscriptPolicy.deserialize(common.settings.get('wallet_policies')[0])
+ key = policy.keys[policy.owned_key_indexes[0]]
+ numeric_path = str_to_keypath(0, path)[1:]
+ assert tuple(numeric_path[:len(key.path)]) == key.path
+ node = chains.current_chain().deserialize_node(key.xpub, AF_CLASSIC)
+ for index in numeric_path[len(key.path):]:
+ node.derive(index, True)
+ return node
+
+
+OWNED_KEY = (
+ "[4ba43603/84'/0'/0']"
+ 'xpub6CFtfy4QXsEUW5CtgE7mZe1Lvs15Yw7ctjdyaDRy89JdhtyM1wFf8uY2BdyJ3JmAFfrHdw77hEit1ebVXxB2dytGAvq9mmQJ2c83G1q8P7A'
+)
+FOREIGN_KEY = (
+ "[8dfc9b34/84'/0'/0']"
+ 'xpub6DCej1mg88MtuioUhGkKje5aJMMFbUswXEcrqt46xGCtwy48Q6D5YaFrhWykLp4ZeqM6XpeXxWuudr7EZkmMT4abxjZRMEhFRBw4SRmjTzY'
+)
+PSBT_BASE64 = (
+ 'cHNidP8BAH0CAAAAARERERERERERERERERERERERERERERERERERERERERERAAAAAAD+////AkCcAAAAAAAAFgAU+VKOB0Yx'
+ 'CX/JIFOUnH4pv76pmxt45gAAAAAAACIAIBQNx0qU+iLrkj8cwktB0/JDXPxgHaxHJwQE4AX2biNHAAAAAAABASughgEAAAAA'
+ 'ACIAIL1vQENUdKouleK1JZzGQSakjVf6Edv+C09oOEzkGPG7AQVLIQIE4W+zgtYA9gyHBVoH0QTwDeJv4cIajiUN0zWuRHEp'
+ 'RqxzZCEDSfcwW2+LRqxR53wkQyso0V56ZmcmEN1Bu9w0JUgxjnmtWrJoIgYCBOFvs4LWAPYMhwVaB9EE8A3ib+HCGo4lDdM1'
+ 'rkRxKUYYS6Q2A1QAAIAAAACAAAAAgAAAAAAFAAAAIgYDSfcwW2+LRqxR53wkQyso0V56ZmcmEN1Bu9w0JUgxjnkYjfybNFQA'
+ 'AIAAAACAAAAAgAAAAAAFAAAAAAABAUshApWOxM8od+Dx3R9ioG/Vi/Iebvd7cMCz/x1xixzhgZj6rHNkIQPVlFife7kL+nve'
+ 'D8adbK1Lq/DMwLoDlx/GFT0kj8ql/q1asmgiAgKVjsTPKHfg8d0fYqBv1YvyHm73e3DAs/8dcYsc4YGY+hhLpDYDVAAAgAAA'
+ 'AIAAAACAAQAAAAYAAAAiAgPVlFife7kL+nveD8adbK1Lq/DMwLoDlx/GFT0kj8ql/hiN/Js0VAAAgAAAAIAAAACAAQAAAAYA'
+ 'AAAA'
+)
+
+
+async def run_test():
+ policy = MiniscriptPolicy(
+ 'Recovery', 'BTC',
+ 'wsh(or_d(pk(@0/**),and_v(v:pk(@1/**),older(10))))',
+ (OWNED_KEY, FOREIGN_KEY), (0,))
+ common.settings.set('chain', 'BTC')
+ common.settings.set('xfp', 53912651)
+ common.settings.set('wallet_policies', [policy.serialize()])
+
+ parsed = psbtObject.read_psbt(BytesIO(a2b_base64(PSBT_BASE64)))
+ await parsed.validate()
+ history.verify_amount = lambda *args: None
+ parsed.consider_inputs()
+ parsed.consider_keys()
+ parsed.consider_outputs()
+
+ assert parsed.active_policy.policy_id == policy.policy_id
+ plan = parsed.inputs[0].policy_spend_plan
+ assert plan.policy_id == policy.policy_id
+ assert plan.branch == 0 and plan.address_index == 5
+ assert parsed.inputs[0].required_key == {plan.expected_pubkey}
+ assert parsed.outputs[1].is_change
+ assert parsed.outputs[1].policy_branch == 1
+ assert parsed.outputs[1].policy_address_index == 6
+
+ # Liana includes complete output derivations but may omit the change
+ # output's witness script. The registered policy must reconstruct and
+ # verify it rather than rejecting an otherwise complete PSBT.
+ omitted_output_script = psbtObject.read_psbt(BytesIO(a2b_base64(PSBT_BASE64)))
+ await omitted_output_script.validate()
+ omitted_output_script.consider_inputs()
+ omitted_output_script.outputs[1].witness_script = None
+ omitted_output_script.consider_outputs()
+ assert omitted_output_script.outputs[1].is_change
+ assert omitted_output_script.outputs[1].policy_branch == 1
+ assert omitted_output_script.outputs[1].policy_address_index == 6
+
+ # An altered input derivation must fail policy matching before signing.
+ tampered_input = psbtObject.read_psbt(BytesIO(a2b_base64(PSBT_BASE64)))
+ await tampered_input.validate()
+ for path in tampered_input.inputs[0].subpaths.values():
+ if path[0] == 53912651:
+ path[-1] = 7
+ try:
+ tampered_input.consider_inputs()
+ assert False, 'Tampered policy input was accepted'
+ except FatalPSBTIssue:
+ pass
+
+ # Input matching can succeed while independently altered change metadata
+ # must still be rejected as fraudulent change.
+ tampered_change = psbtObject.read_psbt(BytesIO(a2b_base64(PSBT_BASE64)))
+ await tampered_change.validate()
+ tampered_change.consider_inputs()
+ tampered_change.outputs[1].parse_subpaths(53912651)
+ for path in tampered_change.outputs[1].subpaths.values():
+ if path[0] == 53912651:
+ path[-1] = 8
+ try:
+ tampered_change.consider_outputs()
+ assert False, 'Tampered policy change was accepted'
+ except FraudulentChangeOutput:
+ pass
+
+ # Resource failures must reach the out-of-memory handler rather than be
+ # reported as fraudulent change. Actual matching errors still fail closed.
+ from policy_errors import WalletPolicyError
+ original_match = MiniscriptPolicy.match_derivations
+ for failure in (MemoryError, WalletPolicyError, ValueError, TypeError, KeyError):
+ resource_failure = psbtObject.read_psbt(BytesIO(a2b_base64(PSBT_BASE64)))
+ await resource_failure.validate()
+ resource_failure.consider_inputs()
+
+ def fail_match(*args):
+ raise failure('policy matching failed')
+
+ MiniscriptPolicy.match_derivations = fail_match
+ try:
+ try:
+ resource_failure.consider_outputs()
+ assert False, 'Policy matching failure was accepted'
+ except MemoryError:
+ assert failure is MemoryError
+ except FraudulentChangeOutput:
+ assert failure is not MemoryError
+ finally:
+ MiniscriptPolicy.match_derivations = original_match
+
+
+LIANA_DESCRIPTOR = (
+ "wsh(or_i(and_v(v:thresh(2,pkh([9f141cf0/48'/1'/0'/2']tpubDFnReAwXvYd6RA46X55HuFpmvZsLanD"
+ "rwHAUsdYEGEpNGTRnCdbDRXJGLTwDeqKURCPZUDgdkuuu9dYkuBNQHmSNBUu7V2CdLKwpJjx2JuC/<2;3>/*),a:pkh([daba2d5"
+ "f/48'/1'/0'/2']tpubDDwKEc4i4k8rBgVLGxytHrP13VVYucUGmL2cadux7AfMwMnRHKcw1YZKt9SMB4fWut7ZAiZqPefzm3BBC"
+ "NXLZMxDrWJ4Q6VA1AFB6b8GzbT/<2;3>/*),a:pkh([141cfdf4/48'/1'/0'/2']tpubDEnYysximqdZkZnW5W9gYc7N3sxizKy"
+ "qfdJfZ2qRfwNvSv6E11yDgyLTAnWQqDmVJ7oQ3h3ui59RQm1qmGxMm4jinq5wvSzyueKgrLJj5Cy/<0;1>/*)),older(52596))"
+ ",and_v(v:pk([9f141cf0/48'/1'/0'/2']tpubDFnReAwXvYd6RA46X55HuFpmvZsLanDrwHAUsdYEGEpNGTRnCdbDRXJGLTwDe"
+ "qKURCPZUDgdkuuu9dYkuBNQHmSNBUu7V2CdLKwpJjx2JuC/<0;1>/*),pk([daba2d5f/48'/1'/0'/2']tpubDDwKEc4i4k8rBg"
+ "VLGxytHrP13VVYucUGmL2cadux7AfMwMnRHKcw1YZKt9SMB4fWut7ZAiZqPefzm3BBCNXLZMxDrWJ4Q6VA1AFB6b8GzbT/<0;1>/"
+ "*))))#u768v50p"
+)
+
+LIANA_PSBT_BASE64 = (
+ "cHNidP8BAKYCAAAAAvNn4zZUC29NiwkzkxHgIy5Owh1JKht7kTQ5a7GqX/U5AAAAAAD9////oymcqrmdGTlK5FrMFweECn+qu1YG"
+ "Lra+/zXkBLIbK0YAAAAAAP3///8CkNADAAAAAAAWABRN+N+zosfu3RKfSgihx9rP8SmxtfVhAQAAAAAAIgAgiErAFCKcEol7d9la"
+ "fCtDvxxugveuUEYMdUnTA9gfRr73QQIAAAEA6gIAAAAAAQGjKZyquZ0ZOUrkWswXB4QKf6q7VgYutr7/NeQEshsrRgEAAAAA/f//"
+ "/wLNgQEAAAAAACIAIFYIyCkKltovlrojAOWXbxfhHf8UznTJcn+O5ewQ695czCwgAAAAAAAWABQMNA6KM0EJLayCJIv00yATrcOB"
+ "1wJHMEQCIHE35IkYAUCplc+d77JPwMG4YSD1zxEVb45JseEY+q/yAiBaYSY6qjgM2LtQjkIsvtTp1XfI6d1zGPcJ3f6JI1xR3wEh"
+ "AiuVcjM/zIonIEmafwmk1mZrjCo53OBxWfPph5yp1DRb60ECAAEBK82BAQAAAAAAIgAgVgjIKQqW2i+WuiMA5ZdvF+Ed/xTOdMly"
+ "f47l7BDr3lwBBaFjdqkUr4e3+fSjzbYj8kpP0PP4s7WUH/WIrGt2qRTjNNKdhGViqb11NRCfxR9sxJfdMYisbJNrdqkUqAHrGM0x"
+ "gJRFAasW6cIjNgM2IE6IrGyTUogDdM0AsmchA1EG7ucxW5mV/YuQcUpjaVzTbleSmiFH2mC3hYpC9WOrrSECAhYrmj2AgSHe9D4x"
+ "dPcZCP7Zi/SgX3PddrGKLoOVYoSsaCIGAgIWK5o9gIEh3vQ+MXT3GQj+2Yv0oF9z3Xaxii6DlWKEHNq6LV8wAACAAQAAgAAAAIAC"
+ "AACAAAAAAAUAAAAiBgKi5HAja57rdRJES8UuJU6iDPuzZ93cYCVPHRwEonZT1RwUHP30MAAAgAEAAIAAAACAAgAAgAAAAAAFAAAA"
+ "IgYDNNe4agqboLEk614IcTYvC8vUsSchc6WeGNEdtIGXDBcc2rotXzAAAIABAACAAAAAgAIAAIACAAAABQAAACIGA1EG7ucxW5mV"
+ "/YuQcUpjaVzTbleSmiFH2mC3hYpC9WOrHJ8UHPAwAACAAQAAgAAAAIACAACAAAAAAAUAAAAiBgOitlzAOu6hNGg2Ji3QMSzfroXb"
+ "tNfkZPRSBRjJMuO3QByfFBzwMAAAgAEAAIAAAACAAgAAgAIAAAAFAAAAAAEA6gIAAAAAAQH2KU1vpUDwLQur5wFv0yu+A/SzFmuF"
+ "2xXvZAqfoBfRYgEAAAAA/f///wJMvQMAAAAAACIAIOLQPgUAniw1zfxa+JfNnYZ5hWTdaLqACnwNwIFwbVf997IhAAAAAAAWABQu"
+ "7IOUSpKpRnuirv2v08xMdeDC1AJHMEQCIEMkkJCR98JzD4LRAxFq3V5sFKYD8p8FYBZQlclquC7gAiA/hAyRi4SBahHVGf4mZQVo"
+ "SytIcjoimDNIQ25Y3RP5PwEhAihDcHfMNqJPBh6JUk0Vtlhe0CuyJG0ZUV92LOaOnrpK60ECAAEBK0y9AwAAAAAAIgAg4tA+BQCe"
+ "LDXN/Fr4l82dhnmFZN1ouoAKfA3AgXBtV/0BBaFjdqkUzKID+e89UqS4cqp3JN4N/SjXmeaIrGt2qRTX/1fwVXrtmzbma8QdxI3I"
+ "fFubtoisbJNrdqkUiHD8XK57PBKa0wAFRDd/uyzH+4+IrGyTUogDdM0AsmchAh9GJb6YDE+RUCQF2xgS5H3kqx+PVOz1PZRhUiYL"
+ "f/HWrSEDrnX4MkC+Wd07+uocrr3/S1oyfgcHGoG5lO8mXwAosHKsaCIGAh9GJb6YDE+RUCQF2xgS5H3kqx+PVOz1PZRhUiYLf/HW"
+ "HJ8UHPAwAACAAQAAgAAAAIACAACAAAAAAAQAAAAiBgJUffN3hCvhBNKfuFBptCbSdKU7u0DzGjaZxnBy58yyqRwUHP30MAAAgAEA"
+ "AIAAAACAAgAAgAAAAAAEAAAAIgYCZVp8vmDyFAK/qiFxS6pBLRVjHvxI1a2ekgGTR2qFKqkc2rotXzAAAIABAACAAAAAgAIAAIAC"
+ "AAAABAAAACIGA5H4jKaEfUOZFze7rkOPu3NW07MJ7T2zHU3mw9oWah6PHJ8UHPAwAACAAQAAgAAAAIACAACAAgAAAAQAAAAiBgOu"
+ "dfgyQL5Z3Tv66hyuvf9LWjJ+BwcagbmU7yZfACiwchzaui1fMAAAgAEAAIAAAACAAgAAgAAAAAAEAAAAAAAiAgJGeB+BjEPU6ABt"
+ "gzQWiLKit5c+Hb93aRCUrEAT2T7jpRzaui1fMAAAgAEAAIAAAACAAgAAgAMAAAABAAAAIgICtgNaqpOzry6iC3uwQAdHesBedOQT"
+ "sSA2GwSOhfVmhXscnxQc8DAAAIABAACAAAAAgAIAAIADAAAAAQAAACICAvYxxE7nPGwcict0xAjs6mJQPBVkP7EpNYvXfdv6kgbV"
+ "HBQc/fQwAACAAQAAgAAAAIACAACAAQAAAAEAAAAiAgMCQx8P+16DiDUMSkg+XtmNMVbIiUO3AnpbaVgAxYABHxzaui1fMAAAgAEA"
+ "AIAAAACAAgAAgAEAAAABAAAAIgIDvIxNjkHn4rPllL9D4uF8SPvfDJITwxu/UIOkF/ltIfEcnxQc8DAAAIABAACAAAAAgAIAAIAB"
+ "AAAAAQAAAAA="
+)
+
+
+async def run_liana_multipath_change_test():
+ policy = MiniscriptPolicy.from_multipath_descriptor(
+ 'Liana Multisig', 'TBTC', LIANA_DESCRIPTOR, (0,))
+ my_xfp = int.from_bytes(unhexlify('9f141cf0'), 'little')
+ common.settings.set('chain', 'TBTC')
+ common.settings.set('xfp', my_xfp)
+ common.settings.set('wallet_policies', [policy.serialize()])
+
+ parsed = psbtObject.read_psbt(BytesIO(a2b_base64(LIANA_PSBT_BASE64)))
+ await parsed.validate()
+ parsed.consider_inputs()
+ parsed.consider_keys()
+ parsed.consider_outputs()
+
+ assert parsed.active_policy.policy_id == policy.policy_id
+ assert parsed.calculate_fee() == 3220
+ assert not parsed.outputs[0].is_change
+ assert parsed.outputs[1].is_change
+ assert parsed.outputs[1].policy_branch == 1
+ assert parsed.outputs[1].policy_address_index == 1
+ assert not any(title == 'Suspicious Change Outputs'
+ for title, _ in parsed.warnings)
+
+
+async def run_all():
+ await run_test()
+ await run_liana_multipath_change_test()
+
+
+original_sensitive_values = stash.SensitiveValues
+stash.SensitiveValues = FixturePublicValues
+try:
+ uasyncio.run(run_all())
+finally:
+ stash.SensitiveValues = original_sensitive_values
### ports/stm32/boards/Passport/modules/tests/unit/wallet_policy_taproot_psbt.py
@@ -0,0 +1,160 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Reject Taproot script-path policies and preserve BIP86 signing."""
+
+import uasyncio
+from ubinascii import a2b_base64, unhexlify
+from uio import BytesIO
+
+import common
+import history
+import stash
+from exceptions import FatalPSBTIssue
+from psbt import psbtObject
+from tasks.sign_psbt_task import sign_psbt_task
+from wallet_policy import KeyInfo
+
+
+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()
+
+
+class FixturePublicValues:
+ """Stand in for the keystore using the fixture's owned account xpub."""
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def derive_path(self, path, register=True):
+ import chains
+ from public_constants import AF_CLASSIC
+ from utils import str_to_keypath
+
+ key = KeyInfo.parse(OWNED_KEY)
+ numeric_path = str_to_keypath(0, path)[1:]
+ assert tuple(numeric_path[:len(key.path)]) == key.path
+ node = chains.current_chain().deserialize_node(key.xpub, AF_CLASSIC)
+ for index in numeric_path[len(key.path):]:
+ node.derive(index, True)
+ return node
+
+
+OWNED_KEY = (
+ "[5a3469b6/86'/0'/0']"
+ 'xpub6Cx47kkB7dkMy515HJa3WH2iRSqqScxnsstoSqF1NEyjXKC7N2vTBqVjx1LZ'
+ 'Ab6hVhEdunJYTxNShqgo9rZ4DEV7rWGazkkzck7vjxjKdLu'
+)
+KEY_PATH_PRIVATE_KEY = unhexlify(
+ '523dcb3ce6a2802987e5df1e6beb14057b311c0eaa9779355817bcc593a45a57')
+KEY_PATH_PUBKEY = unhexlify(
+ '15935d7f96add7901be6451be8e1037071da1b95d45c56155448700227f163e9')
+KEY_PATH_DIGEST = unhexlify(
+ 'b00a9cac35d66d9f277987b776bb78069384344ce3c579622b5108251822c71b')
+PSBT_BASE64 = (
+ 'cHNidP8BAH0CAAAAARERERERERERERERERERERERERERERERERERERERERERAAAAAAD+////ApBfAQAAAAAAFgAUVLa1Ho5v'
+ 't/N4um+vD82arsZZH+MoIwAAAAAAACJRIEVz5qpI3J5RutKQoUrN75B+kEjlJkjB3rYNI1M4iY11AAAAAAABASughgEAAAAA'
+ 'ACJRIGjZ8StNc9kVB8bWEPA7kflWi59g73D1w6nQGbhubbB0IhXAeb5mfvncu6xVoGKVzocLBwKb/NstzijZWfKBWxb4F5'
+ 'gjIA4D0nc6v/yD2GZZJlrNW0B19F8h7h2S0kBafGiWfqkxrMAhFg4D0nc6v/yD2GZZJlrNW0B19F8h7h2S0kBafGiWfqkx'
+ 'OQFFQzGr8V4kxuZDLRG3tQePZR5tLGWVfPpM741TLzCsPFo0abZWAACAAAAAgAAAAIAAAAAABQAAAAEXIHm+Zn753LusVaBi'
+ 'lc6HCwcCm/zbLc4o2VnygVsW+BeYARggRUMxq/FeJMbmQy0Rt7UHj2UebSxllXz6TO+NUy8wrDwAAQYlAMAiINZluScGyEB'
+ 'SObx+96oxmOUWwPVVLbM7MQvoVUl7/kwYrAABBSB5vmZ++dy7rFWgYpXOhwsHApv82y3OKNlZ8oFbFvgXmCEH1mW5JwbIQ'
+ 'FI5vH73qjGY5RbA9VUtszsxC+hVSXv+TBg5AYy9eilgnkg4nY6kSUC/rxSebzjtDHQMNYgUyTAp9tOsWjRptlYAAIAAAACA'
+ 'AAAAgAEAAAAGAAAAAQYlAMAiINZluScGyEBSObx+96oxmOUWwPVVLbM7MQvoVUl7/kwYrAA='
+)
+KEY_PATH_PSBT_BASE64 = (
+ 'cHNidP8BAFICAAAAASIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiAQAAAAD9////AWi/AAAAAAAAFgAU9ZNq0AVK'
+ 'dnF4n/pYyvTKWK7JMqEAAAAAAAEBK1DDAAAAAAAAIlEgsQCqISnbf8Y1iBjWxeSsmAv6Re+Vd3z+4stdzJqaA5YhFhWTXX+W'
+ 'rdeQG+ZFG+jhA3Bx2huV1FxWFVRIcAIn8WPpGQBaNGm2VgAAgAAAAIAAAACAAAAAAAcAAAABFyAVk11/lq3XkBvmRRvo4QNw'
+ 'cdobldRcVhVUSHACJ/Fj6QAA'
+)
+
+
+async def run_test():
+ common.settings.set('chain', 'BTC')
+ common.settings.set('xfp', 3060347994)
+ common.settings.set('wallet_policies', [])
+ history.verify_amount = lambda *args: None
+
+ # Script-path PSBTs remain unsupported even with valid scripts/derivations.
+ parsed = psbtObject.read_psbt(BytesIO(a2b_base64(PSBT_BASE64)))
+ await parsed.validate()
+ try:
+ parsed.consider_inputs()
+ assert False, 'Taproot script-path input was accepted'
+ except FatalPSBTIssue as exc:
+ assert 'script-path signing is not supported' in str(exc)
+
+ original_sensitive_values = stash.SensitiveValues
+ original_blank_object = stash.blank_object
+
+ # Existing BIP86 key-path detection, sighash, and signing remain supported.
+ key_path = psbtObject.read_psbt(BytesIO(a2b_base64(KEY_PATH_PSBT_BASE64)))
+ await key_path.validate()
+ key_path.consider_inputs()
+ key_path.consider_keys()
+ key_input = key_path.inputs[0]
+ assert key_path.active_policy is None
+ assert key_input.policy_spend_plan is None
+ assert key_input.required_key == KEY_PATH_PUBKEY
+ assert not key_input.is_multisig
+ assert key_path.make_txn_taproot_sighash(0, 0) == KEY_PATH_DIGEST
+
+ class KeyPathNode:
+ def public_key(self):
+ return b'\x02' + KEY_PATH_PUBKEY
+
+ def private_key(self):
+ return bytearray(KEY_PATH_PRIVATE_KEY)
+
+ class KeyPathValues(FixturePublicValues):
+ def derive_path(self, path, register=False):
+ return KeyPathNode()
+
+ key_path_result = []
+
+ async def key_path_done(error_msg, error_code):
+ key_path_result.append((error_msg, error_code))
+
+ stash.SensitiveValues = KeyPathValues
+ stash.blank_object = lambda value: None
+ original_cache = history.OutptValueCache
+ recorded_amounts = []
+
+ class MockValueCache:
+ @staticmethod
+ def record_amount(prevout, amount, in_idx):
+ recorded_amounts.append((amount, in_idx))
+
+ history.OutptValueCache = MockValueCache
+ try:
+ await sign_psbt_task(key_path_done, key_path)
+ finally:
+ stash.SensitiveValues = original_sensitive_values
+ stash.blank_object = original_blank_object
+ history.OutptValueCache = original_cache
+ assert key_path_result == [(None, None)]
+ assert recorded_amounts == [(key_input.amount, 0)]
+ assert len(key_input.tap_key_sig) == 64
+
+
+original_sensitive_values = stash.SensitiveValues
+stash.SensitiveValues = FixturePublicValues
+try:
+ uasyncio.run(run_test())
+finally:
+ stash.SensitiveValues = original_sensitive_values
### ports/stm32/boards/Passport/modules/wallet_policy.py
@@ -0,0 +1,767 @@
+# SPDX-FileCopyrightText: 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Registered wallet-policy model shared by address and PSBT workflows."""
+
+try:
+ import ujson as json
+except ImportError: # pragma: no cover - CPython host tests
+ import json
+
+try:
+ from ubinascii import hexlify, unhexlify
+except ImportError: # pragma: no cover - CPython host tests
+ from binascii import hexlify, unhexlify
+
+from descriptor import split_checksum
+from miniscript import (MAX_KEYS, MAX_TEMPLATE_LENGTH, Parser,
+ compile_miniscript, iter_policy_keys, validate)
+from policy_errors import (PolicyMismatchError, PolicyParseError,
+ PolicyResourceError, UnsupportedPolicyError, WalletPolicyError)
+
+
+POLICY_FORMAT_VERSION = 1
+POLICY_STORAGE_KEY = 'wallet_policies'
+MAX_POLICY_NAME_LENGTH = 20
+MAX_KEY_NAME_LENGTH = 20
+MAX_POLICY_RECORD_LENGTH = 3072
+SETTINGS_HEADROOM = 768
+# Levels allowed in a key origin path. Each one costs a BIP32 derivation during
+# ownership discovery, and nothing real goes beyond six. Distinct from
+# miniscript's MAX_PARSE_DEPTH, which bounds AST recursion and shares the value
+# only by coincidence.
+MAX_ORIGIN_DEPTH = 16
+BASE58_CHARS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
+
+
+def validate_backup_policy_records(records, expected_fingerprint, derive_node,
+ chain_lookup):
+ """Validate and canonicalize wallet policies restored from a backup.
+
+ A backup may contain policies for both Bitcoin mainnet and testnet,
+ regardless of the device's currently selected network. Validate each
+ policy using the network declared by that policy instead of applying the
+ backup's active chain to every record.
+ """
+ if not isinstance(records, list):
+ raise PolicyParseError('Wallet-policy backup records must be a list')
+
+ expected_fingerprint = expected_fingerprint.lower()
+ validated_records = []
+ policy_ids = set()
+ for record in records:
+ policy = MiniscriptPolicy.deserialize(record)
+ policy_chain = chain_lookup(policy.network)
+ policy.validate_extended_keys(policy_chain)
+ owned_key = policy.keys[policy.owned_key_indexes[0]]
+ if owned_key.fingerprint != expected_fingerprint:
+ raise PolicyMismatchError('Wallet policy belongs to another seed')
+ policy.verify_owned_key(policy_chain, derive_node)
+ if policy.policy_id in policy_ids:
+ raise PolicyParseError('Duplicate wallet policy in backup')
+ policy_ids.add(policy.policy_id)
+ validated_records.append(policy.serialize())
+ return validated_records
+
+
+def _max_key_uses_per_path(node, key_index):
+ """Conservatively count key uses in any one executable WSH path.
+
+ ``or_i`` selects exactly one child at execution time, so repeated key
+ expressions on opposite sides are mutually exclusive. For every other
+ fragment, summing child occurrences is deliberately conservative: a
+ policy is rejected unless Passport can prove that no spending path needs
+ more than one signature from its owned xpub.
+ """
+ if node.kind in ('pk_k', 'pk_h'):
+ return 1 if node.value.index == key_index else 0
+ if node.kind == 'multi':
+ return sum(1 for key in node.args if key.index == key_index)
+ child_counts = [_max_key_uses_per_path(child, key_index)
+ for child in node.args if hasattr(child, 'kind')]
+ if node.kind == 'or_i':
+ return max(child_counts) if child_counts else 0
+ return sum(child_counts)
+
+
+def _is_decimal(text):
+ return bool(text) and all('0' <= ch <= '9' for ch in text)
+
+
+def _sha256(data):
+ try:
+ import trezorcrypto
+ return trezorcrypto.sha256(data).digest()
+ except ImportError: # pragma: no cover - CPython host tests
+ import hashlib
+ return hashlib.sha256(data).digest()
+
+
+def _compact_size(value):
+ if value < 253:
+ return bytes([value])
+ if value < 0x10000:
+ return b'\xfd' + bytes([value & 0xff, value >> 8])
+ if value < 0x100000000:
+ return b'\xfe' + bytes([
+ value & 0xff, (value >> 8) & 0xff,
+ (value >> 16) & 0xff, (value >> 24) & 0xff,
+ ])
+ raise PolicyResourceError('Canonical policy field is too large')
+
+
+def _encode_field(value):
+ encoded = value.encode('ascii')
+ return _compact_size(len(encoded)) + encoded
+
+
+def _fingerprint_int(fingerprint):
+ return int.from_bytes(unhexlify(fingerprint), 'little')
+
+
+class KeyInfo:
+ __slots__ = ('fingerprint', 'path', 'xpub')
+
+ def __init__(self, fingerprint, path, xpub):
+ self.fingerprint = fingerprint
+ self.path = tuple(path)
+ self.xpub = xpub
+
+ @classmethod
+ def parse(cls, text):
+ if not isinstance(text, str):
+ raise PolicyParseError('Key information must be text')
+ try:
+ text.encode('ascii')
+ except UnicodeError:
+ raise PolicyParseError('Key information must contain ASCII only')
+ if not text.startswith('['):
+ raise PolicyParseError('Key origin information is required')
+ close = text.find(']')
+ if close < 0:
+ raise PolicyParseError('Key origin is missing closing bracket')
+ origin = text[1:close]
+ if origin.count('/') > MAX_ORIGIN_DEPTH:
+ raise PolicyResourceError(
+ 'Key origin path exceeds {} levels'.format(MAX_ORIGIN_DEPTH))
+ xpub = text[close + 1:]
+ parts = origin.split('/')
+ fingerprint = parts[0]
+ if len(fingerprint) != 8 or any(ch not in '0123456789abcdefABCDEF' for ch in fingerprint):
+ raise PolicyParseError('Key fingerprint must be exactly 8 hexadecimal characters')
+ if not 100 <= len(xpub) <= 120 or any(ch not in BASE58_CHARS for ch in xpub):
+ raise PolicyParseError('Extended public key encoding is invalid')
+
+ path = []
+ for element in parts[1:]:
+ if not element:
+ raise PolicyParseError('Key origin contains an empty path element')
+ hardened = element[-1:] in ("'", 'h', 'H')
+ number = element[:-1] if hardened else element
+ if not _is_decimal(number) or (len(number) > 1 and number[0] == '0'):
+ raise PolicyParseError('Key origin contains an invalid path element')
+ if len(number) > 10 or int(number) >= 0x80000000:
+ raise PolicyResourceError('Key origin path element is too large')
+ value = int(number)
+ if hardened:
+ value |= 0x80000000
+ path.append(value)
+ return cls(fingerprint.lower(), path, xpub)
+
+ def canonical(self):
+ result = '[' + self.fingerprint
+ for value in self.path:
+ hardened = bool(value & 0x80000000)
+ result += '/' + str(value & 0x7fffffff) + ("'" if hardened else '')
+ return result + ']' + self.xpub
+
+
+def descriptor_to_policy_template(descriptor, require_checksum=True):
+ """Convert a checksummed full multipath descriptor to BIP388 form.
+
+ Only the deliberately narrow registered-policy key grammar is accepted. The
+ resulting template is reparsed by ``MiniscriptPolicy`` before it can be
+ stored or used.
+ """
+ body, _ = split_checksum(descriptor, require=require_checksum)
+ if body.startswith('tr('):
+ raise UnsupportedPolicyError('Only native SegWit (wsh) wallet policies are supported')
+ if not (body.startswith('wsh(') and body.endswith(')')):
+ raise PolicyParseError('Imports require a top-level wsh descriptor')
+ try:
+ body.encode('ascii')
+ except UnicodeError:
+ raise PolicyParseError('Descriptor must contain ASCII only')
+
+ output = []
+ key_values = []
+ position = 0
+ length = len(body)
+ while position < length:
+ if body[position] != '[':
+ output.append(body[position])
+ position += 1
+ continue
+
+ close = body.find(']', position + 1)
+ if close < 0:
+ raise PolicyParseError('Descriptor key origin is missing closing bracket')
+ xpub_start = close + 1
+ xpub_end = xpub_start
+ while xpub_end < length and body[xpub_end] in BASE58_CHARS:
+ xpub_end += 1
+ if xpub_end == xpub_start:
+ raise PolicyParseError('Descriptor key origin is not followed by an extended key')
+ key_info = KeyInfo.parse(body[position:xpub_end]).canonical()
+
+ if body[xpub_end:xpub_end + 3] == '/**':
+ suffix = '/**'
+ next_position = xpub_end + 3
+ elif body[xpub_end:xpub_end + 2] == '/<':
+ suffix_end = body.find('>/*', xpub_end + 2)
+ if suffix_end < 0:
+ raise PolicyParseError('Multipath key suffix is incomplete')
+ branch_text = body[xpub_end + 2:suffix_end]
+ branch_parts = branch_text.split(';')
+ if len(branch_parts) != 2:
+ raise PolicyParseError('Exactly two multipath branches are required')
+ branch_values = []
+ for part in branch_parts:
+ if not _is_decimal(part) or (len(part) > 1 and part[0] == '0'):
+ raise PolicyParseError('Multipath branch is not canonical')
+ if len(part) > 10 or int(part) >= 0x80000000:
+ raise PolicyResourceError('Multipath branch is too large')
+ branch_values.append(int(part))
+ if branch_values[0] == branch_values[1]:
+ raise PolicyParseError('Receive and change branches must be different')
+ suffix = '/<{};{}>/*'.format(branch_values[0], branch_values[1])
+ next_position = suffix_end + 3
+ else:
+ raise PolicyParseError('Extended keys must end in /** or /<M;N>/*')
+
+ if key_info not in key_values:
+ if len(key_values) >= MAX_KEYS:
+ raise PolicyResourceError('Descriptor contains too many extended keys')
+ key_values.append(key_info)
+ key_index = key_values.index(key_info)
+ output.append('@{}{}'.format(key_index, suffix))
+ position = next_position
+
+ template = ''.join(output)
+ return template, tuple(key_values)
+
+
+class DerivedPolicyOutput:
+ __slots__ = ('policy_id', 'branch', 'index', 'witness_script',
+ 'redeem_script', 'script_pubkey', 'address')
+
+ def __init__(self, policy_id, branch, index, witness_script,
+ script_pubkey, address, redeem_script=None):
+ self.policy_id = policy_id
+ self.branch = branch
+ self.index = index
+ self.witness_script = witness_script
+ self.redeem_script = redeem_script
+ self.script_pubkey = script_pubkey
+ self.address = address
+
+
+class MiniscriptPolicy:
+ __slots__ = ('name', 'network', 'template', 'keys', 'owned_key_indexes',
+ 'miniscript', 'context',
+ 'policy_id', 'key_names')
+
+ def __init__(self, name, network, template, keys, owned_key_indexes,
+ key_names=None):
+ if not isinstance(name, str) or not name or len(name) > MAX_POLICY_NAME_LENGTH:
+ raise PolicyParseError('Policy name must contain 1 to {} characters'.format(MAX_POLICY_NAME_LENGTH))
+ try:
+ name.encode('ascii')
+ except UnicodeError:
+ raise PolicyParseError('Policy name must contain ASCII only')
+ if name != name.strip() or any(ord(ch) < 32 or ord(ch) > 126 for ch in name):
+ raise PolicyParseError('Policy name must use printable ASCII without outer whitespace')
+ if network not in ('BTC', 'TBTC'):
+ raise PolicyParseError('Unsupported policy network')
+ if not isinstance(template, str) or len(template) > MAX_TEMPLATE_LENGTH:
+ raise PolicyParseError('Policy must use a bounded descriptor template')
+ try:
+ template.encode('ascii')
+ except UnicodeError:
+ raise PolicyParseError('Policy template must contain ASCII only')
+
+ 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,
+ hash160_fn=lambda _: bytes(20))
+ key_expressions = list(iter_policy_keys(miniscript))
+ else:
+ raise UnsupportedPolicyError('Only native SegWit (wsh) wallet policies are supported')
+
+ if not 1 <= len(keys) <= MAX_KEYS:
+ raise PolicyResourceError('Policy must contain between 1 and {} keys'.format(MAX_KEYS))
+ parsed_keys = tuple(key if isinstance(key, KeyInfo) else KeyInfo.parse(key) for key in keys)
+ canonical_keys = [key.canonical() for key in parsed_keys]
+ if len(set(canonical_keys)) != len(canonical_keys):
+ raise PolicyParseError('Policy key information entries must be distinct')
+
+ indexes = [key.index for key in key_expressions]
+ expected = list(range(len(parsed_keys)))
+ first_seen = []
+ for index in indexes:
+ if index not in first_seen:
+ first_seen.append(index)
+ if first_seen != expected or set(indexes) != set(expected):
+ raise PolicyParseError('Key placeholders must reference every key in @0, @1 order')
+
+ owned = tuple(owned_key_indexes)
+ if len(owned) != 1 or owned[0] not in expected:
+ raise PolicyParseError('Policies require exactly one Passport-owned policy key')
+ if _max_key_uses_per_path(miniscript, owned[0]) > 1:
+ raise PolicyParseError(
+ 'A spending path cannot require more than one Passport signature')
+ if key_names is None:
+ names = ('',) * len(parsed_keys)
+ else:
+ names = tuple(key_names)
+ if len(names) != len(parsed_keys):
+ raise PolicyParseError('Policy key names do not match its key vector')
+ for key_name in names:
+ if not isinstance(key_name, str) or len(key_name) > MAX_KEY_NAME_LENGTH:
+ raise PolicyParseError(
+ 'Key names may contain up to {} characters'.format(
+ MAX_KEY_NAME_LENGTH))
+ try:
+ key_name.encode('ascii')
+ except UnicodeError:
+ raise PolicyParseError('Key names must contain ASCII only')
+ if key_name != key_name.strip() or any(
+ ord(char) < 32 or ord(char) > 126 for char in key_name):
+ raise PolicyParseError(
+ 'Key names must use printable ASCII without outer whitespace')
+
+ self.name = name
+ self.network = network
+ self.template = template
+ self.keys = parsed_keys
+ self.owned_key_indexes = owned
+ self.miniscript = miniscript
+ self.context = context
+ self.key_names = names
+ self.policy_id = self.calculate_id()
+
+ record_len = len(json.dumps(self.serialize()))
+ if record_len > MAX_POLICY_RECORD_LENGTH:
+ raise PolicyResourceError('Serialized policy exceeds {} bytes'.format(MAX_POLICY_RECORD_LENGTH))
+
+ @classmethod
+ def from_descriptor(cls, name, network, descriptor, keys, owned_key_indexes,
+ require_checksum=True):
+ body, _ = split_checksum(descriptor, require=require_checksum)
+ return cls(name, network, body, keys, owned_key_indexes)
+
+ @classmethod
+ def from_multipath_descriptor(cls, name, network, descriptor,
+ owned_key_indexes, require_checksum=True):
+ template, keys = descriptor_to_policy_template(descriptor, require_checksum)
+ return cls(name, network, template, keys, owned_key_indexes)
+
+ def validate_extended_keys(self, chain):
+ """Decode all xpubs and verify network, depth, and public-key uniqueness."""
+ if getattr(chain, 'ctype', None) != self.network:
+ raise PolicyMismatchError('Policy network does not match the active network')
+ from public_constants import AF_P2SH
+ public_keys = set()
+ for key in self.keys:
+ try:
+ node = chain.deserialize_node(key.xpub, AF_P2SH)
+ except BaseException:
+ raise PolicyParseError('Extended public key could not be decoded for this network')
+ if node.depth() != len(key.path):
+ raise PolicyParseError('Extended key depth does not match its origin path')
+ public_key = bytes(node.public_key())
+ if public_key in public_keys:
+ raise PolicyParseError('Extended public keys resolve to duplicate public keys')
+ public_keys.add(public_key)
+ return True
+
+ def verify_owned_key(self, chain, derive_node):
+ """Prove the declared owned xpub against the current seed.
+
+ ``derive_node`` receives the numeric origin path and must return the
+ current seed's HD node at that path. The complete serialized xpub is
+ compared; a fingerprint match alone is never sufficient.
+ """
+ from public_constants import AF_P2SH
+ owned_index = self.owned_key_indexes[0]
+ key = self.keys[owned_index]
+ node = derive_node(key.path)
+ try:
+ derived_xpub = chain.serialize_public(node, AF_P2SH)
+ finally:
+ try:
+ from stash import blank_object
+ blank_object(node)
+ except ImportError: # pragma: no cover - CPython host tests
+ pass
+ if derived_xpub != key.xpub:
+ raise PolicyMismatchError('Passport-owned extended key does not match the current seed')
+ return True
+
+ @classmethod
+ def deserialize(cls, record):
+ if not isinstance(record, dict) or record.get('v') != POLICY_FORMAT_VERSION:
+ raise PolicyParseError('Unsupported wallet-policy record version')
+ policy = cls(record.get('n'), record.get('net'), record.get('t'),
+ record.get('k', ()), record.get('o', ()),
+ record.get('kn'))
+ stored_id = record.get('id')
+ if stored_id != policy.policy_id:
+ raise PolicyParseError('Stored policy identity does not match its contents')
+ 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))
+ for key in self.keys:
+ payload += _encode_field(key.canonical())
+ return hexlify(_sha256(payload)).decode('ascii')
+
+ def serialize(self):
+ record = {
+ 'v': POLICY_FORMAT_VERSION,
+ 'id': self.policy_id,
+ 'n': self.name,
+ 'net': self.network,
+ 't': self.template,
+ 'k': [key.canonical() for key in self.keys],
+ 'o': list(self.owned_key_indexes),
+ }
+ if any(self.key_names):
+ record['kn'] = list(self.key_names)
+ return record
+
+ def format_overview(self):
+ # Kept as a compact compatibility entry point for callers that only
+ # support one page. Import and view flows use all semantic review pages.
+ return self.format_review_pages()[0]
+
+ @staticmethod
+ def _format_origin_path(path):
+ result = 'm'
+ for value in path:
+ result += '/{}{}'.format(value & 0x7fffffff,
+ "'" if value & 0x80000000 else '')
+ return result
+
+ def format_details(self):
+ lines = ['Technical details',
+ 'Full descriptor\n' + self.full_descriptor()]
+ for index, key in enumerate(self.keys):
+ if index in self.owned_key_indexes:
+ role = 'This Passport'
+ elif self.key_names[index]:
+ role = self.key_names[index].replace('#', '##')
+ else:
+ role = 'External key'
+ lines.append('Key {} - {}\nFingerprint {}\nPath {}\n{}'.format(
+ index + 1, role, key.fingerprint.upper(),
+ self._format_origin_path(key.path), key.xpub))
+ 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())
+ if with_checksum:
+ from descriptor import append_checksum
+ return append_checksum(descriptor)
+ return descriptor
+
+ def descriptor_check(self):
+ return self.full_descriptor().rsplit('#', 1)[1].upper()
+
+ def format_review_pages(self):
+ from policy_display import format_review_pages
+ return format_review_pages(self)
+
+ def format_confirmation(self):
+ from policy_display import format_confirmation
+ return format_confirmation(self)
+
+ def format_signing_pages(self, compatible_indexes=None):
+ from policy_display import format_signing_pages
+ return format_signing_pages(self, compatible_indexes)
+
+ def rename(self, name):
+ return MiniscriptPolicy(name, self.network, self.template, self.keys,
+ self.owned_key_indexes, self.key_names)
+
+ def name_key(self, key_index, name):
+ if key_index < 0 or key_index >= len(self.keys):
+ raise PolicyParseError('Policy key index is outside the key vector')
+ names = list(self.key_names)
+ names[key_index] = name
+ return MiniscriptPolicy(self.name, self.network, self.template, self.keys,
+ self.owned_key_indexes, names)
+
+ def name_keys(self, names):
+ return MiniscriptPolicy(self.name, self.network, self.template, self.keys,
+ self.owned_key_indexes, names)
+
+ def _key_expressions(self):
+ return iter_policy_keys(self.miniscript)
+
+ def _resolver(self, chain):
+ def resolve(key_index, branch, address_index):
+ from public_constants import AF_P2SH
+ key = self.keys[key_index]
+ # AF_P2SH selects the standard xpub/tpub version rather than a
+ # script-specific SLIP132 serialization.
+ node = chain.deserialize_node(key.xpub, AF_P2SH)
+ if node.depth() != len(key.path):
+ raise PolicyMismatchError('Extended key depth does not match its origin path')
+ node.derive(branch, True)
+ node.derive(address_index, True)
+ public_key = bytes(node.public_key())
+ return public_key if self.context == 'wsh' else public_key[1:]
+ return resolve
+
+ def _derive_with_paths(self, branch, index, chain):
+ """Derive the script and the exact PSBT derivation map it requires."""
+ from public_constants import AF_P2SH
+ expected_paths = {}
+ expected_key_indexes = {}
+
+ def resolve(key_index, child_branch, address_index):
+ key = self.keys[key_index]
+ node = chain.deserialize_node(key.xpub, AF_P2SH)
+ if node.depth() != len(key.path):
+ raise PolicyMismatchError('Extended key depth does not match its origin path')
+ node.derive(child_branch, True)
+ node.derive(address_index, True)
+ public_key = bytes(node.public_key())
+ path = [_fingerprint_int(key.fingerprint)] + list(key.path)
+ path.extend((child_branch, address_index))
+ if public_key in expected_paths and expected_paths[public_key] != path:
+ raise PolicyMismatchError('Policy derives a repeated public key')
+ expected_paths[public_key] = path
+ expected_key_indexes[public_key] = key_index
+ return public_key
+
+ return self.derive(branch, index, chain, resolve), expected_paths, expected_key_indexes
+
+ def match_derivations(self, subpaths, utxo_script_pubkey, witness_script,
+ chain, my_xfp):
+ """Resolve branch/index and exactly match a P2WSH PSBT scope."""
+ if self.context != 'wsh':
+ raise PolicyMismatchError('P2WSH derivations require a wsh policy')
+ owned_index = self.owned_key_indexes[0]
+ owned_key = self.keys[owned_index]
+ owned_fingerprint = _fingerprint_int(owned_key.fingerprint)
+ if owned_fingerprint != my_xfp:
+ raise PolicyMismatchError('Registered policy belongs to another seed')
+
+ owned_expressions = [key for key in iter_policy_keys(self.miniscript)
+ if key.index == owned_index]
+ candidates = set()
+ prefix = [owned_fingerprint] + list(owned_key.path)
+ for public_key, path in subpaths.items():
+ if len(path) != len(prefix) + 2 or list(path[:len(prefix)]) != prefix:
+ continue
+ child_branch, address_index = path[-2:]
+ if child_branch >= 0x80000000 or address_index >= 0x80000000:
+ continue
+ for expression in owned_expressions:
+ for branch in (0, 1):
+ if expression.branches[branch] == child_branch:
+ candidates.add((branch, address_index))
+
+ matches = []
+ for branch, address_index in candidates:
+ try:
+ derived, expected_paths, expected_key_indexes = self._derive_with_paths(
+ branch, address_index, chain)
+ if derived.script_pubkey != bytes(utxo_script_pubkey):
+ continue
+ if witness_script is not None and \
+ derived.witness_script != bytes(witness_script):
+ continue
+ if set(expected_paths) != set(subpaths):
+ continue
+ if any(expected_paths[key] != list(subpaths[key]) for key in expected_paths):
+ continue
+ matches.append((derived, expected_paths, expected_key_indexes))
+ except (WalletPolicyError, ValueError, TypeError):
+ continue
+
+ if not matches:
+ raise PolicyMismatchError('PSBT scripts and derivations do not match the registered policy')
+ if len(matches) != 1:
+ raise PolicyMismatchError('PSBT derivation matches the policy ambiguously')
+ return matches[0]
+
+ def make_spend_plan(self, input_index, subpaths, utxo_script_pubkey,
+ witness_script, chain, my_xfp, sighash_type):
+ if self.context != 'wsh':
+ raise PolicyMismatchError('P2WSH spend matching requires a wsh policy')
+ if sighash_type != 1:
+ raise PolicyMismatchError('P2WSH wallet policies require SIGHASH_ALL')
+ derived, expected_paths, expected_key_indexes = self.match_derivations(
+ subpaths, utxo_script_pubkey, witness_script, chain, my_xfp)
+ owned_index = self.owned_key_indexes[0]
+ owned_pubkeys = [public_key for public_key, key_index in expected_key_indexes.items()
+ if key_index == owned_index]
+ if not owned_pubkeys:
+ raise PolicyMismatchError('Policy did not derive a Passport signing key')
+ owned_signing_keys = tuple(
+ (expected_paths[public_key], public_key) for public_key in owned_pubkeys)
+ owned_path, owned_pubkey = owned_signing_keys[0]
+ from miniscript import policy_timelocks
+ from spend_plan import SpendPlan
+ return SpendPlan(
+ self.policy_id, input_index, derived.branch, derived.index, 'p2wsh',
+ owned_path, owned_pubkey, sighash_type,
+ script_pubkey=derived.script_pubkey,
+ witness_script=derived.witness_script,
+ timelocks=policy_timelocks(self.miniscript),
+ owned_signing_keys=owned_signing_keys)
+
+ def derive(self, branch, index, chain, key_resolver=None):
+ if getattr(chain, 'ctype', None) != self.network:
+ raise PolicyMismatchError('Policy network does not match the active network')
+ resolver = key_resolver or self._resolver(chain)
+ witness_script = compile_miniscript(
+ self.miniscript, resolver, branch, index, 'wsh')
+ digest = _sha256(witness_script)
+ script_pubkey = b'\x00\x20' + digest
+ try:
+ from public_constants import AF_P2WSH
+ address = chain.p2sh_address(AF_P2WSH, witness_script)
+ except ImportError: # Host tests may use a minimal chain stub.
+ address = None
+ return DerivedPolicyOutput(self.policy_id, branch, index, witness_script,
+ script_pubkey, address)
+
+ def match_scripts(self, branch, index, chain, utxo_script_pubkey,
+ witness_script=None, key_resolver=None):
+ derived = self.derive(branch, index, chain, key_resolver)
+ if bytes(utxo_script_pubkey) != derived.script_pubkey:
+ raise PolicyMismatchError('UTXO script does not match the registered policy')
+ if self.context == 'wsh' and witness_script is not None and \
+ bytes(witness_script) != derived.witness_script:
+ raise PolicyMismatchError('PSBT witness script does not match the registered policy')
+ return derived
+
+
+class WalletPolicyRegistry:
+ """Validated storage facade; corrupt records are quarantined, never used."""
+
+ def __init__(self, settings=None):
+ if settings is None:
+ from common import settings as global_settings
+ settings = global_settings
+ self.settings = settings
+ self.invalid_records = []
+
+ def _records(self):
+ records = self.settings.get(POLICY_STORAGE_KEY, [])
+ return records if isinstance(records, list) else []
+
+ def iter_policies(self, fingerprint=None):
+ self.invalid_records = []
+ for record in self._records():
+ try:
+ policy = MiniscriptPolicy.deserialize(record)
+ if fingerprint is not None:
+ owned = policy.keys[policy.owned_key_indexes[0]].fingerprint
+ if owned.lower() != fingerprint.lower():
+ continue
+ yield policy
+ except (WalletPolicyError, TypeError, KeyError, ValueError) as exc:
+ self.invalid_records.append((record, str(exc)))
+
+ def iter_all(self, fingerprint=None, include_legacy=True):
+ for policy in self.iter_policies(fingerprint):
+ yield policy
+ if include_legacy:
+ from multisig_wallet import MultisigWallet
+ from policy_multisig import StandardMultisigPolicy
+ if fingerprint is None:
+ wallets = MultisigWallet.iter_wallets()
+ else:
+ from utils import str2xfp
+ wallets = MultisigWallet.get_by_xfp(str2xfp(fingerprint))
+ for wallet in wallets:
+ yield StandardMultisigPolicy(wallet)
+
+ def get(self, policy_id):
+ for policy in self.iter_policies():
+ if policy.policy_id == policy_id:
+ return policy
+ return None
+
+ def _preflight(self, records):
+ current = (self.settings.temporary_settings if getattr(self.settings, 'temporary_mode', False)
+ else self.settings.current)
+ candidate = dict(current)
+ candidate[POLICY_STORAGE_KEY] = records
+ encoded_len = len(json.dumps(candidate))
+ maximum = getattr(self.settings, 'max_json_len', 8192 - 32)
+ if encoded_len > maximum - SETTINGS_HEADROOM:
+ raise PolicyResourceError('Not enough settings space to store this policy safely')
+
+ def save(self, policy):
+ records = list(self._records())
+ if any(record.get('id') == policy.policy_id for record in records if isinstance(record, dict)):
+ raise PolicyParseError('This wallet policy is already registered')
+ records.append(policy.serialize())
+ self._preflight(records)
+ self.settings.set(POLICY_STORAGE_KEY, records)
+
+ def delete(self, policy_id):
+ records = [record for record in self._records()
+ if not isinstance(record, dict) or record.get('id') != policy_id]
+ self._preflight(records)
+ self.settings.set(POLICY_STORAGE_KEY, records)
+
+ def rename(self, policy_id, name):
+ records = list(self._records())
+ for position, record in enumerate(records):
+ if isinstance(record, dict) and record.get('id') == policy_id:
+ records[position] = MiniscriptPolicy.deserialize(record).rename(name).serialize()
+ self._preflight(records)
+ self.settings.set(POLICY_STORAGE_KEY, records)
+ return
+ raise PolicyParseError('Wallet policy was not found')
+
+ def rename_key(self, policy_id, key_index, name):
+ records = list(self._records())
+ for position, record in enumerate(records):
+ if isinstance(record, dict) and record.get('id') == policy_id:
+ policy = MiniscriptPolicy.deserialize(record).name_key(key_index, name)
+ records[position] = policy.serialize()
+ self._preflight(records)
+ self.settings.set(POLICY_STORAGE_KEY, records)
+ return
+ raise PolicyParseError('Wallet policy was not found')
+
+ def rename_keys(self, policy_id, names):
+ records = list(self._records())
+ for position, record in enumerate(records):
+ if isinstance(record, dict) and record.get('id') == policy_id:
+ policy = MiniscriptPolicy.deserialize(record).name_keys(names)
+ records[position] = policy.serialize()
+ self._preflight(records)
+ self.settings.set(POLICY_STORAGE_KEY, records)
+ return
+ raise PolicyParseError('Wallet policy was not found')
### ports/stm32/boards/Passport/modules/wallets/liana.py
@@ -0,0 +1,132 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Liana wallet key export."""
+
+import stash
+
+from common import settings
+from public_constants import AF_CLASSIC, AF_P2WSH
+from utils import xfp2str
+
+
+def _cbor_head(major, value):
+ """Encode one definite-length CBOR head without pulling in a large codec."""
+ if value < 24:
+ return bytes([(major << 5) | value])
+ if value <= 0xff:
+ return bytes([(major << 5) | 24, value])
+ if value <= 0xffff:
+ return bytes([(major << 5) | 25, value >> 8, value & 0xff])
+ if value <= 0xffffffff:
+ return bytes([(major << 5) | 26,
+ (value >> 24) & 0xff, (value >> 16) & 0xff,
+ (value >> 8) & 0xff, value & 0xff])
+ raise ValueError('CBOR integer is too large')
+
+
+def _cbor_uint(value):
+ return _cbor_head(0, value)
+
+
+def _cbor_bytes(value):
+ return _cbor_head(2, len(value)) + bytes(value)
+
+
+def _cbor_tag(value):
+ return _cbor_head(6, value)
+
+
+def create_liana_crypto_account(master_fingerprint, node, coin_type, acct_num):
+ """Build the narrow BCR-2020-015 account profile accepted by Liana."""
+ if coin_type not in (0, 1):
+ raise ValueError('Liana supports only Bitcoin mainnet or test networks')
+
+ # crypto-hdkey map fields: private, key, chain, use-info, origin, parent-fp.
+ hdkey = bytearray(_cbor_head(5, 6))
+ hdkey.extend(_cbor_uint(2))
+ hdkey.append(0xf4) # false: this is public key material
+ hdkey.extend(_cbor_uint(3))
+ hdkey.extend(_cbor_bytes(node.public_key()))
+ hdkey.extend(_cbor_uint(4))
+ hdkey.extend(_cbor_bytes(node.chain_code()))
+ hdkey.extend(_cbor_uint(5))
+ hdkey.extend(_cbor_tag(40305)) # crypto-coin-info
+ hdkey.extend(_cbor_head(5, 2))
+ hdkey.extend(_cbor_uint(1))
+ hdkey.extend(_cbor_uint(0)) # Bitcoin
+ hdkey.extend(_cbor_uint(2))
+ hdkey.extend(_cbor_uint(0 if coin_type == 0 else 1))
+ hdkey.extend(_cbor_uint(6))
+ hdkey.extend(_cbor_tag(40304)) # crypto-keypath
+ hdkey.extend(_cbor_head(5, 3))
+ hdkey.extend(_cbor_uint(1))
+ hdkey.extend(_cbor_head(4, 8))
+ for component in (48, coin_type, acct_num, 2):
+ hdkey.extend(_cbor_uint(component))
+ hdkey.append(0xf5) # hardened
+ hdkey.extend(_cbor_uint(2))
+ hdkey.extend(_cbor_uint(master_fingerprint))
+ hdkey.extend(_cbor_uint(3))
+ hdkey.extend(_cbor_uint(4))
+ hdkey.extend(_cbor_uint(8))
+ hdkey.extend(_cbor_uint(node.fingerprint()))
+
+ # crypto-account {master-fingerprint, [wsh(cosigner(crypto-hdkey))]}.
+ account = bytearray(_cbor_head(5, 2))
+ account.extend(_cbor_uint(1))
+ account.extend(_cbor_uint(master_fingerprint))
+ account.extend(_cbor_uint(2))
+ account.extend(_cbor_head(4, 1))
+ account.extend(_cbor_tag(308)) # crypto-output
+ account.extend(_cbor_tag(401)) # wsh
+ account.extend(_cbor_tag(410)) # cosigner
+ account.extend(_cbor_tag(303)) # crypto-hdkey
+ account.extend(hdkey)
+ return bytes(account)
+
+
+def create_liana_export(sw_wallet=None,
+ addr_type=None,
+ acct_num=0,
+ multisig=False,
+ legacy=False,
+ export_mode='microsd',
+ qr_type=None):
+ """Export the native-SegWit BIP48 key accepted by Liana.
+
+ Liana uses the same descriptor key for single-key and multisig policy
+ branches. The threshold belongs to the completed wallet policy, not to an
+ individual signer's extended public key.
+ """
+ import chains
+
+ chain = chains.current_chain()
+ deriv = "m/48'/{coin_type}'/{acct}'/2'".format(
+ coin_type=chain.b44_cointype, acct=acct_num)
+ master_xfp = xfp2str(settings.get('xfp')).lower()
+
+ with stash.SensitiveValues() as sv:
+ node = sv.derive_path(deriv)
+ xpub = sv.chain.serialize_public(node, AF_CLASSIC)
+ if export_mode == 'qr':
+ from foundation import ur
+ account = create_liana_crypto_account(
+ int(master_xfp, 16), node, chain.b44_cointype, acct_num)
+ qr_account = ur.new_raw('crypto-account', account)
+
+ descriptor_key = '[{xfp}/{deriv}]{xpub}\n'.format(
+ xfp=master_xfp,
+ deriv=deriv[2:],
+ xpub=xpub)
+ acct_info = [{
+ 'fmt': AF_P2WSH,
+ 'deriv': deriv,
+ 'acct': acct_num,
+ 'xfp': master_xfp,
+ }]
+
+ if export_mode == 'qr':
+ return (qr_account, acct_info)
+
+ return (descriptor_key, acct_info)
### ports/stm32/boards/Passport/modules/wallets/sw_wallets.py
@@ -28,6 +28,54 @@
from .theya import TheyaWallet
from .unchained import UnchainedWallet
from .zeus import ZeusWallet
+from data_codecs.qr_type import QRType
+
+
+def create_liana_export(*args, **kwargs):
+ # Keep the exporter off the startup import path. Connect Wallet's registry
+ # is loaded during boot, when the MicroPython heap is at its tightest.
+ from .liana import create_liana_export as export
+ return export(*args, **kwargs)
+
+
+LianaWallet = {
+ 'label': 'Liana',
+ # Liana policy keys always use the BIP48 native-SegWit branch. Treat this
+ # as multisig inside ConnectWalletFlow so it does not attempt single-sig
+ # address verification before Liana has constructed the complete policy.
+ 'sig_types': [{
+ 'id': 'multisig',
+ 'label': 'Wallet policy',
+ 'addr_type': None,
+ 'create_wallet': create_liana_export,
+ }],
+ 'export_modes': [
+ {
+ 'id': 'qr',
+ 'label': 'QR Code',
+ 'qr_type': QRType.UR2,
+ },
+ {
+ 'id': 'microsd',
+ 'label': 'microSD',
+ 'filename_pattern_multisig': '{xfp}-liana-account-{acct}.txt',
+ 'ext_multisig': '.txt',
+ },
+ ],
+ 'skip_multisig_import': True,
+ 'skip_address_validation': True,
+ 'custom_text': {
+ 'pairing_qr':
+ 'Passport will display an animated account QR.\n\n'
+ 'Scan it when adding this Passport in Liana.',
+ 'pairing_microsd':
+ 'Passport will save a key file to microSD.\n\n'
+ 'Import it when adding this Passport in Liana.',
+ 'connection_complete':
+ 'Liana key exported. After creating the wallet in Liana, export '
+ 'its descriptor and register it under Wallet Policies.',
+ },
+}
# Array of all supported software wallets and their attributes.
# Used to build wallet menus and drive their behavior.
@@ -47,6 +95,7 @@
# DuxReserveWallet,
ElectrumWallet,
FullyNodedWallet,
+ LianaWallet,
# GordianWallet,
# LilyWallet,
NunchukWallet,
### simulator/sim_boot.py
@@ -80,6 +80,14 @@ def simulator_socket_task():
socket.sendto(sender, 'excp', value.getvalue().encode('utf-8'))
+if '--constrained-startup' in sys.argv:
+ # A frozen simulator build contains the hardware sflash module, which has
+ # precedence over MICROPYPATH. Install the low-heap simulator model before
+ # importing the frozen application entry point.
+ import constrained_sflash
+ sys.modules['sflash'] = constrained_sflash
+
+
if '--unit-test' in sys.argv:
simulator_socket_task()
else:
### simulator/sim_modules/constrained_sflash.py
@@ -0,0 +1,99 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+"""Low-heap SPI flash model for constrained simulator startup tests.
+
+The regular simulator keeps the complete 8 MiB flash in a Python bytearray.
+That is convenient for interactive use, but it makes the simulator unable to
+exercise Passport's real 276 KiB MicroPython heap. This model stores written
+pages in a sparse host file and keeps only a one-bit-per-page allocation map in
+the garbage-collected heap.
+"""
+
+_SIZE = 8 * 1024 * 1024
+_PAGE_SIZE = 256
+_PAGE_COUNT = _SIZE // _PAGE_SIZE
+_BACKING_FILE = 'spi_flash_sparse.bin'
+
+
+class SPIFlash:
+ PAGE_SIZE = _PAGE_SIZE
+ SECTOR_SIZE = 4096
+ BLOCK_SIZE = 65536
+
+ _written_pages = bytearray(_PAGE_COUNT // 8)
+ _file = None
+
+ def __init__(self):
+ if SPIFlash._file is None:
+ SPIFlash._file = open(_BACKING_FILE, 'w+b')
+
+ @staticmethod
+ def default():
+ return SPIFlash()
+
+ @classmethod
+ def _is_written(cls, page):
+ return cls._written_pages[page >> 3] & (1 << (page & 7))
+
+ @classmethod
+ def _mark_written(cls, page):
+ cls._written_pages[page >> 3] |= 1 << (page & 7)
+
+ @classmethod
+ def _mark_erased(cls, page):
+ cls._written_pages[page >> 3] &= ~(1 << (page & 7))
+
+ def read(self, address, buf, **kw):
+ assert 0 <= address <= _SIZE - len(buf)
+ offset = 0
+ while offset < len(buf):
+ absolute = address + offset
+ page = absolute // self.PAGE_SIZE
+ in_page = absolute % self.PAGE_SIZE
+ count = min(len(buf) - offset, self.PAGE_SIZE - in_page)
+ if self._is_written(page):
+ self._file.seek(absolute)
+ buf[offset:offset + count] = self._file.read(count)
+ else:
+ for i in range(offset, offset + count):
+ buf[i] = 0xff
+ offset += count
+
+ def write(self, address, buf):
+ assert 1 <= len(buf) <= self.PAGE_SIZE
+ assert 0 <= address <= _SIZE - len(buf)
+ assert address // self.PAGE_SIZE == (address + len(buf) - 1) // self.PAGE_SIZE
+ page = address // self.PAGE_SIZE
+ start = page * self.PAGE_SIZE
+ data = bytearray(self.PAGE_SIZE)
+ self.read(start, data)
+ offset = address - start
+ for index, value in enumerate(buf):
+ data[offset + index] &= value
+ self._file.seek(start)
+ self._file.write(data)
+ self._mark_written(page)
+
+ def is_busy(self):
+ return False
+
+ def wait_done(self):
+ return
+
+ def chip_erase(self):
+ for i in range(len(self._written_pages)):
+ self._written_pages[i] = 0
+
+ def _erase_pages(self, address, size):
+ assert address % size == 0
+ first = address // self.PAGE_SIZE
+ count = size // self.PAGE_SIZE
+ for page in range(first, first + count):
+ self._mark_erased(page)
+
+ def sector_erase(self, address):
+ self._erase_pages(address, self.SECTOR_SIZE)
+
+ def block_erase(self, address):
+ self._erase_pages(address, self.BLOCK_SIZE)
### simulator/sim_modules/passport/__init__.py
@@ -10,6 +10,7 @@
IS_COLOR = sys.argv[6] == 'color'
IS_DEV = True
HAS_FUEL_GAUGE = False
+CONSTRAINED_STARTUP = '--constrained-startup' in sys.argv
class Noise:
@@ -94,6 +95,14 @@ def get_device_hash(self, hash_buf):
hash_buf[i] = self.device_hash[i]
return None
+ def dispatch(self, _command, buf, _arg2):
+ # The frozen hardware PinAttempt implementation checks the bricked flag
+ # with a null buffer before attempting a Secure Element exchange. Let
+ # that check pass, then take main.py's existing simulator fallback.
+ if buf is None:
+ return 0
+ raise RuntimeError('Secure Element dispatch is unavailable in simulator')
+
def reset(self):
sys.exit()
@@ -128,7 +137,8 @@ def validate_firmware_header(self, buf):
return (True, '2.0.1', None, False)
def enable_lv_refresh(self, enable):
- pass
+ if CONSTRAINED_STARTUP and enable:
+ print('Constrained startup reached UI')
# Always "passes"
### simulator/sim_modules/passport/camera.py
@@ -3,14 +3,17 @@
#
import sys
+from passport import CONSTRAINED_STARTUP
HOR_RES = 396
VER_RES = 330
FRAMEBUFFER_SIZE = HOR_RES * VER_RES * 2
cam_cmd_wx = open(int(sys.argv[4]), 'wb')
cam_img_rx = open(int(sys.argv[5]), 'rb')
-_framebuffer = bytearray(FRAMEBUFFER_SIZE)
+# On hardware this buffer is statically allocated outside the MicroPython GC
+# heap. Avoid charging it to the heap in constrained startup simulations.
+_framebuffer = bytearray(1 if CONSTRAINED_STARTUP else FRAMEBUFFER_SIZE)
is_enabled = False
### simulator/sim_modules/passport/mem.py
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: © 2021 Foundation Devices, Inc. <hello@foundation.xyz>
# SPDX-License-Identifier: GPL-3.0-or-later
+from passport import CONSTRAINED_STARTUP
+
MAX_QR_VERSION = 13
@@ -14,7 +16,9 @@ def _qr_buffer_size_for_version(version):
def _alloc(ln):
- return bytearray(ln)
+ # These buffers live in statically allocated MCU memory on a real Passport,
+ # rather than in the MicroPython garbage-collected heap.
+ return bytearray(1 if CONSTRAINED_STARTUP else ln)
psbt_output = _alloc(26 * 1024)
@@ -27,4 +31,4 @@ def _alloc(ln):
def qrcode_buffer_clear():
global qrcode_buffer
- qrcode_buffer[2 * 4:] = b'\x00' * (240 * 240)
\ No newline at end of file
+ qrcode_buffer[2 * 4:] = b'\x00' * (240 * 240)Why this scored 15/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.