Skip to content

Accept, display, and sign wsh() Miniscript wallet descriptors (e.g. Liana) - #1026

Open
SovereignGG wants to merge 16 commits into
SeedSigner:devfrom
SovereignGG:miniscript-wsh-policy-display
Open

SovereignGG wants to merge 16 commits into
SeedSigner:devfrom
SovereignGG:miniscript-wsh-policy-display

Conversation

@SovereignGG

@SovereignGG SovereignGG commented Aug 27, 2026 •

Copy link
Copy Markdown

Description

Problem or Issue being addressed

SeedSigner's ScanView.run() gates wallet-descriptor registration on
descriptor.is_basic_multisig, silently routing anything else — including
any Miniscript wsh()/tr() descriptor — to NotYetImplementedView. This
blocks using SeedSigner as a signer for any Miniscript-based wallet, most
concretely Liana's inheritance
policies (a primary key, plus a recovery key that activates after a
timelock).

This has been discussed here in #306 on and off since 2023. This PR targets
the "v1" scope multiple contributors converged on there: descriptor decode,
validation, and policy review, plus signing, for wsh() — no persistent
registration/proof-of-registration yet, taproot signing deferred.

Solution

  • New get_descriptor_policy_summary() / is_supported_wallet_descriptor()
    / can_derive_multisig_address() helpers in embit_utils.py — a
    recursive Miniscript-AST walker that turns any wsh()/tr() policy into
    a plain-English summary (e.g. (key ABCD1234) or ((key 5678EFGH) and (after 1000 blocks))), used in place of the old basic-multisig-only
    get_multisig_policy() at its call sites.
  • Wired into the existing ScanView, MultisigWalletDescriptorView,
    ToolsAddressExplorerAddressTypeView, and
    ToolsAddressExplorerAddressListView — the registration gate is loosened,
    no new views added.
  • decode_qr.py's QR-type detection had a second, earlier gate that's easy
    to miss: a plain-text wallet-descriptor QR was only classified as
    WALLET__GENERIC if it contained the literal substring "sortedmulti" —
    stricter than the registration view's own check, so a Miniscript
    descriptor QR could fail to even be recognized before ever reaching
    Descriptor.from_string(). Now matches on the descriptor's real top-level
    function (sh/wsh/tr/pkh/wpkh/combo); a merely descriptor-shaped
    string that isn't an actual valid descriptor is still rejected downstream
    by Descriptor.from_string() itself, so this doesn't loosen validation,
    just recognition.
  • MultisigWalletDescriptorScreen's policy line needed
    auto_line_break=True (its sibling "Signing Keys" line already has it) —
    Miniscript summaries run longer than the "2 of 3" string this screen was
    originally built for.
  • Two PSBTParser fixes, both found only once a real Liana PSBT was
    scanned on physical hardware:
    • _parse_multisig() raised an unhandled ValueError for any witness
      script that isn't bare OP_CHECKMULTISIG — i.e. any real Miniscript
      script. Now caught, degrading gracefully to a policy dict without
      m/n/cosigners, matching the existing swallowed-exception pattern
      the same function already uses one level up for _get_cosigners().
    • With that degraded policy, an output belonging to a different wallet
      (or any unrelated address) can share the same generic {"type": "p2wsh"} policy and reach change-reconstruction code with no
      witness_script populated — a real coordinator only fills that in for
      outputs it recognizes as its own — crashing in script.p2wsh(None).
      Now guarded: an output with no witness/redeem script populated is
      correctly treated as not belonging to the wallet.
  • The decode_qr.py prefix match above is validated with
    Descriptor.from_string() before the QR type is assigned. The prefix
    pattern is as short as tr( (3 bytes), and detect_segment_type()
    speculatively treats all scanned data as text — including binary formats
    that were never strings (CompactSeedQR entropy is matched further down, by
    byte length). Entropy that both survives that conversion and begins with a
    matching prefix would be misclassified as a descriptor; the old
    "sortedmulti" substring was long enough for that to be negligible, these
    prefixes are not. GenericWalletQrDecoder validates the same way
    downstream, but too late to help — by then detect_segment_type() has
    settled on a type with no path back to the seed checks. This is defensive
    hardening for a constructed case, not one observed in the wild.

Deliberately out of scope: taproot (tr()) address derivation and
signing remain unimplemented — pre-existing get_multisig_address() /
PSBTParser limitations, unchanged here. Only taproot policy display is
covered by this PR, and it's held to the same correctness bar as wsh(): a
hidden script-path recovery leaf is never described as "single signature."

Additional Information

Verified end-to-end on physical hardware, not just unit tests: created a
real Liana wallet on signet
(wsh(or_d(pk(seedsigner-key),and_v(v:pkh(recovery-key),older(4383))))),
registered it on a Pi Zero 1.3 running this branch, confirmed the policy
screen and a derived receive address matched Liana byte-for-byte, funded it
via the signet faucet, built a spend in Liana, signed it on-device, and
broadcast — confirmed independently by a third-party node
(mempool.space/signet), not just accepted locally. Txid:
94e5e8fe8809cf09e24a24eace18fc075676b2d87294bb2b5d382bb57424e7a1.

SeedSigner has no way to talk to Liana directly — no async-hwi driver, and
Liana's own airgap flow is file-based with no QR support at all. Signing was
done through a small standalone companion tool,
liana-seedsigner-bridge,
which reads/writes Liana's file-based PSBT/descriptor exports on one side
and speaks SeedSigner's existing UR2.0/Specter-JSON QR protocols on the
other, via a screen and webcam. It doesn't modify either project and isn't
part of this PR — linked for anyone who wants to reproduce the test.

Both PSBTParser fixes came from that hardware run, not code review — a
reminder that this class of bug (code implicitly assuming a witness script
is always bare OP_CHECKMULTISIG) is easy to miss without an actual
Miniscript PSBT to test against, and there may be more instances elsewhere
in the codebase.

Not included, left for follow-up: taproot address/signing support
(tracked as a known gap, not attempted here), the fingerprint-vs-xpub
alias/proof-of-registration design discussed later in #306 (this PR keeps
SeedSigner's existing rescan-every-session trust model rather than adding
persistent state), and a non-CLI version of the bridge tool for less
technical users.

Screenshots

Real device photo, MultisigWalletDescriptorScreen showing the registered
policy from the hardware run referenced above:

Screenshot 2026-08-27 at 10 24 57 PM

This pull request is categorized as a:

  • New feature
  • Bug fix
  • Code refactor
  • Documentation
  • Other

Checklist

I ran pytest locally

  • All tests passed before submitting the PR
  • I couldn't run the tests
  • N/A

217 passed (209 existing + 3 new regression tests: 2 for the PSBTParser
fixes and 1 for the decode_qr.py fix, plus 5 l10n tests that only pass
once the translation catalog is compiled locally — unrelated to this
change, and excluded on a dev machine without that step run).


I included screenshots of any new or modified screens

Should be part of the PR description above.

  • Yes
  • No
  • N/A

I added or updated tests

Any new or altered functionality should be covered in a unit test. Any new or updated sequences require FlowTests.

  • Yes
  • No, I'm a fool
  • N/A

New unit tests in test_embit_utils.py for the policy-summary/gate helpers,
new FlowStep sequences in test_flows_tools.py for the registration
gate, and new regression tests in test_psbt_parser.py and test_seedqr.py
for the fixes above (each confirmed to reproduce the failure against the
pre-fix code before being added).


I tested this PR hands-on on the following platform(s):

Pi Zero 1.3.


I have reviewed these notes:

  • Keep your changes limited in scope.
  • If you uncover other issues or improvements along the way, ideally submit those as a separate PR.
  • The more complicated the PR, the harder it is to review, test, and merge.
  • We appreciate your efforts, but we're a small team of volunteers so PR review can be a very slow process.
  • Please only "@" mention a contributor if their input is truly needed to enable further progress.
  • I understand

Thank you! Please join our Devs' Telegram group to get more involved.

@kdmukai

kdmukai commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

I appreciate the initiative here!

My branch from 2023 took a very opinionated stance of only supporting specific miniscript templates. By restricting it to specific templates, curated review screens could then be created to step the user through the policy's rules and phases.

My rationale is that SeedSigner goes through a LOT of effort to avoid footguns, but completely arbitrary miniscript is the worst kind of footgun:

  • A raw policy is essentially impossible for a person to adequately review, even someone with a programming background. Completely hopeless for a non-programmer.
  • Reviewing even a standard template as a raw policy is error prone.
  • Reviewing ANYTHING complex on SeedSigner's tiny screen is error prone.

The wording in your screenshot is an improvement over presenting raw miniscript, but it still requires the user to be careful about how the parentheses group the terms, otherwise they'll completely misunderstand the construction. And as the conditions get more complex, the parentheses hell will become completely incomprehensible.

Until this presentation issue is resolved, I would remain a concept NACK.


How I had tried to deal with this

At the time I was only focusing on Liana's basic degrading multisig. In my example, I had a 2-of-3 that degrades to any one of the original three keys.

wsh(
    or_d(
        multi(
            2,
            [0f889044/48'/1'/0'/2']tpubDFQDKbH2mDqNDPNaUVxM6R5mHhzC4u5F6mNnUkCf6gBMbcENMQ1ZGFLZc3QwgdEv2f34wkTvLMG5kD8AZEZRhat1HQDj42eVxQSxbcqxn31/<0;1>/*,
            [03cd0a2b/48'/1'/0'/2']tpubDEPEYgTj1ddmZqDdpiq5Gjttx3CnNSFppSaUa5eHAUVNMD2FE1ihGA2EMP92mzmSUGJsTAgMhBTACd9xsRDB5K4GKJH8RzbRuFUrmVVLR15/<0;1>/*,
            [3666c686/48'/1'/0'/2']tpubDERSdjUfKa7Qy6c7k3s1jcEcEUYudhy4WcEN1PDKtTVK7cPQVRQRSGdVDNDGiPGrQ1WT28Qws4zZ4bRj1LnpCgsiGkbqHkxMEdnsr9hS9sr/<0;1>/*
        ),
        and_v(
            v:thresh(
                1,
                pkh([0f889044/48'/1'/0'/2']tpubDFQDKbH2mDqNDPNaUVxM6R5mHhzC4u5F6mNnUkCf6gBMbcENMQ1ZGFLZc3QwgdEv2f34wkTvLMG5kD8AZEZRhat1HQDj42eVxQSxbcqxn31/<2;3>/*),
                a:pkh([03cd0a2b/48'/1'/0'/2']tpubDEPEYgTj1ddmZqDdpiq5Gjttx3CnNSFppSaUa5eHAUVNMD2FE1ihGA2EMP92mzmSUGJsTAgMhBTACd9xsRDB5K4GKJH8RzbRuFUrmVVLR15/<2;3>/*),
                a:pkh([3666c686/48'/1'/0'/2']tpubDERSdjUfKa7Qy6c7k3s1jcEcEUYudhy4WcEN1PDKtTVK7cPQVRQRSGdVDNDGiPGrQ1WT28Qws4zZ4bRj1LnpCgsiGkbqHkxMEdnsr9hS9sr/<2;3>/*)
            ),
            older(25920)
        )
    )
)#59wrkjh6

And I created these curated review screens:
MiniscriptDescriptorRecoveryTimelockView
MiniscriptDescriptorInitialPolicyView
MiniscriptDescriptorRecoveryPolicyView

Note that I'm not claiming these review screens are necessarily ideal or ready to ship. They were just my initial best efforts on a fun, short-term exploration.


That was my thinking in 2023-24 and I still think the curated template approach is the best starting point, though I haven't deeply explored how generalizable the presentation can be; as in: if you have enough curated presentation pieces, could ANY arbitrary policy be nicely presented piece-by-piece to the user? Probably not... but the universe of policies that COULD be supported that way is probably much broader than what I implemented (e.g. any m-of-n phase that degrades to X number of other k-of-j phases that might eventually degrade to 1-of-blah; each of those phases should be easy to clearly present. The main overview would just have to be more complicated than its current "Initial" vs "Recovery" phase labels).

I also haven't kept up with how people are thinking about registering policies (ala Ledger), though that remains somewhat irrelevant to a stateless SeedSigner. I think Salvatore has been doing some recent work to provide more standardization (perhaps more easily recognizable known templates???).


More recently I've become more open to fully supporting arbitrary policies, but only as an advanced Setting that would be initially disabled. But I think you'd need some sort of external policy decoder / reviewer / validator to pair with SeedSigner so that you're not just blindly accepting complex policies. Something like:

  • Scan in the complex policy
  • Hash it
  • Copy the policy from the coordinator into the companion decoder app
  • It reports the hash (now you know SeedSigner and the companion app are seeing the same thing)
  • Companion app does what it can to present the arbitrarily complex policy rules / phases
  • If you're satisfied, now go ahead and fund the new setup.
  • Preserve a copy of the policy as the "known-good" descriptor plus its hash.
  • When signing a tx or verifying a receive addr, scan the "known-good" descriptor back in. And feed it back into the companion app whenever you want to review the policy.

But I'm pretty out of date (and was never at full mastery to begin with) so some of this may be nonsense or there are already better solutions available.

@SovereignGG

SovereignGG commented Sep 3, 2026 •

Copy link
Copy Markdown
Author

Thanks for the thorough review, and for the 2023 context — the curated-template direction was the right call and I've reworked the PR around it.

What changed

Arbitrary policy support is gone. Previously this accepted any wsh()/tr() Miniscript and rendered it through a generic recursive AST-to-English summary. You were right that this is unsafe: a nested boolean expression makes the user track parenthesization to know which conditions apply together, and that doesn't survive contact with a 240×240 screen.

Miniscript is now template-gated. One shape is recognized — "spendable now by a key or quorum, or by a recovery key or quorum after a relative timelock" — and it gets dedicated structured fields. Everything else is refused exactly as before this PR, falling through to NotYetImplementedView: additional OR branches, multiple recovery tiers, thresh() legs carrying their own conditions, hash preimages, absolute after() timelocks. Your own 2023 example (2-of-3 degrading to any 1-of-3) is a case the template does now cover, since both paths reduce to key quorums.

It's opt-in. New Settings > Advanced > Miniscript wallets, disabled by default, matching the existing SETTING__MESSAGE_SIGNING / SETTING__ELECTRUM_SEEDS idiom and routing through the existing OptionDisabledView when off. Basic multisig and key-path-only taproot are untouched by this gate.

Screens

Registration, single-key primary:

1-registration-single-key

k-of-n primary (2-of-3 + timelocked recovery — the most common real configuration):

demo_2of3_address_explorer 2-registration-2of3

n-of-n primary (3-of-3):

3-registration-3of3

Thresholds fold into the field labels rather than taking their own line, so a quorum costs no vertical space beyond the extra fingerprints. A 1-of-1 path omits the threshold entirely.

Address Explorer, which needed the same treatment:

4-address-explorer

The settings gate, at its default:

6-option-disabled 5-settings-entry

Basic multisig, unchanged, for comparison:

7-basic-multisig-unchanged

All of these are wired into the screenshot generator and regenerate in CI, per your note about that.

A display-capacity limit, enforced at match time

Fingerprints render two per line, and there is room for four lines across both paths. Measured against the real screen: 3 primary lines + 1 recovery line ends at 178px against a 200px button top, while one more line reaches 199–201px.

Past that, the recovery section slides under the buttons and becomes invisible — hiding the timelocked path entirely. I found this by rendering a 9-key policy and looking at it. Since a screen showing half a policy is worse than no screen, policies needing more than four lines are refused at match time. This permits up to a 5-key primary with a 2-key recovery, comfortably beyond the 2-of-3 and 3-of-5 setups that dominate real use.

What Liana actually emits

Three structural forms, none of which I would have guessed correctly:

  • multi(k,...) for a k-of-n primary path
  • thresh(k,pkh(A),a:pkh(B)) for a k-of-n recovery path — the recovery branch sits under and_v and needs different type properties
  • or_i with the branches reversed and the keys chained through and_v for an n-of-n primary, because or_d(X,Z) requires X to be dissatisfiable and an and_v chain isn't

The first two came from descriptor vectors in Liana's own test suite; the third came from a real export that showed up as "Not Yet Implemented" on hardware. Rather than encode those as positional cases, the matcher now finds the branch carrying the timelock by inspection and takes the other as primary. That's also what keeps multi-tier recovery refused: when every branch is timelocked, nothing qualifies as "spendable now", so describing either as such would be false.

Bugs hardware testing found that unit tests did not

Three, all in code this PR touches:

  1. Change misclassified as an external payment. Liana doesn't populate witness_script on its own change outputs, so _parse_outputs() couldn't rebuild the scriptpubkey and counted change as money leaving. A 10,000 sat input paying 5,000 with 4,827 back displayed a 9,827 sat spend. It fails safe — nothing hidden, both addresses shown — but it denies the user any on-device confirmation that change is returning to them. My tests missed it because the fixture populated witness_script, an assumption I'd never checked against a real PSBT.

  2. Address Explorer overflow. A second call site still rendered the generic policy expression, and its text field had no line-wrapping, so it ran off the screen edge mid-word. Fixed inside get_descriptor_policy_summary() rather than at the call site, so no future caller can reintroduce it.

  3. "Signing Failed" on a successful signature. sig_count() counts partial_sigs entries, keyed by pubkey. Re-signing with a seed that already signed overwrites the entry rather than adding one — and embit's nonces are deterministic, so even the bytes match. The count is therefore identical whether a seed already signed or cannot sign at all, and both reported as failure. Now distinguished by re-deriving from the signing seed. This is pre-existing and affects basic multisig identically, but n-of-n makes it ordinary rather than unusual, since the same PSBT gets signed repeatedly with different seeds. Happy to split this into its own PR if you'd prefer it out of scope.

Verification

Hardware, Pi Zero 1.3, signet:

  • Single-key + recovery: registered, signed, broadcast
  • 3-of-3 + timelocked recovery: registered, signed with all three seeds, broadcast
  • Address Explorer receive addresses match Liana's character-for-character — this is what actually validates multi() and and_v-chain address derivation against real key material
  • Settings gate confirmed in both states
  • Animated multi-frame descriptor QR confirmed

Test suite: 228 passed. Every new or changed assertion was confirmed to fail against the prior commit before being added. Fixtures use descriptors copied verbatim from Liana's test suite, plus one real signet export, rather than reconstructions.

Deliberately not in this PR

The hash + companion decoder app idea for arbitrary policies. It's a much larger, separate feature and I'd rather not bolt it onto this one.

One concrete problem worth flagging for whenever that gets designed: hashing the descriptor text won't work as-is. ScanView.run() already regex-rewrites the scanned descriptor, turning /0/* wildcards into /{0,1}/* so change can be verified. So the string SeedSigner holds is not byte-identical to what the coordinator exported. Add multipath notation variants (/<0;1>/* vs /{0,1}/*) and BIP380 checksums, and a hash over the raw text would mismatch between device and companion app for the same wallet. That design needs a canonicalization step, or to hash a derived artifact — the first N scriptpubkeys, say — rather than the descriptor string.

Also still out of scope, unchanged: taproot address derivation and script-path signing, and any persistent registration / proof-of-registration. This keeps the existing rescan-every-session trust model.

SeedSigner currently rejects any wallet descriptor where
is_basic_multisig is False -- including general wsh() Miniscript
policies like Liana's or_d(pk(...),and_v(...)) recovery wallets --
silently routing them to NotYetImplementedView. This closes that gap
for descriptor registration and policy display:

- embit_utils.is_supported_wallet_descriptor() replaces the
  is_basic_multisig check in ScanView with a broader test that also
  accepts wsh() Miniscript and taproot descriptors (bare single-key
  wpkh()/pkh() descriptors remain excluded, unchanged).
- embit_utils.get_descriptor_policy_summary() recursively renders any
  parsed Miniscript fragment tree as plain English, driven by each
  fragment's own descriptor keyword rather than a fixed set of
  isinstance checks. For taproot, it always enumerates hidden
  script-path leaves when present, so a descriptor with a recovery
  leaf can never be summarized as plain single-signature.
- decode_qr.py's QR-type sniffer no longer requires the literal
  substring "sortedmulti" to recognize a wallet descriptor QR; it now
  matches on the descriptor's top-level script type, which also admits
  wsh()/tr() Miniscript.
- Address Explorer's address-listing gate is loosened from
  is_basic_multisig to the same capability check get_multisig_address()
  itself already uses (embit_utils.can_derive_multisig_address()) --
  which incidentally also unblocks taproot key-path address derivation,
  previously excluded by that gate even though it already worked.

Verified against a real Liana-style wsh() descriptor and a taproot
descriptor with a hidden recovery leaf, using the same known-good key
vectors as the existing multisig tests. Full test suite passes (209
passed; 5 pre-existing environmental l10n failures unrelated to this
change, present identically on a clean checkout of dev).

Scoped to registration/display/address-derivation only, matching the
v1 scope discussed in SeedSigner#306. PSBT signing against
these descriptors and taproot script-path signing are separate,
later work.
Miniscript policy summaries run much longer than the old "2 of 3"
basic-multisig string this screen was originally built for, and the
Policy IconTextLine was missing the auto_line_break=True its sibling
Signing Keys field already has -- confirmed on real hardware: a wsh()
Miniscript policy was silently clipped mid-string with no ellipsis.
_parse_multisig() raises ValueError for any witness script that isn't
bare OP_CHECKMULTISIG (e.g. a wsh() Miniscript script like Liana's
or_d(pk(...),and_v(...))), and that call was unprotected -- only the
subsequent _get_cosigners() call was wrapped in try/except. Confirmed
on real hardware: scanning a real Liana Miniscript PSBT crashed with
"Not a multisig script" instead of degrading policy to just {"type":
...} the way output/change classification already does.
With a degraded policy (no m/n/cosigners, as any Miniscript wsh()
policy now produces), out_policy == self.policy only proves the output
has the same script *type* as ours -- not that it belongs to our
wallet. The code's own comment assumed _parse_multisig/_get_cosigners
had already established ownership, which no longer holds. An unrelated
same-type output reaches the change reconstruction with witness_script
still None, crashing in script.p2wsh(). Confirmed on real hardware
signing a Liana PSBT: 'NoneType' object has no attribute 'data'.
Both bugs (d9122da, 86180e9) were only found by running a real Liana
PSBT through PSBTParser on physical hardware -- neither was caught by
the existing basic-multisig/single-sig fixtures, since both are
specific to a witness script that isn't bare OP_CHECKMULTISIG.

Confirmed these reproduce the exact real error against the pre-fix
code (ValueError: Not a multisig script) before adding them, so
they're not just plausible-looking tests that happen to pass.
Replacing the old `"sortedmulti" in s` check with a top-level-function
prefix match widened detection to Miniscript/tr() descriptors, but the
new pattern is as short as "tr(" (3 bytes). detect_segment_type()
speculatively treats all scanned data as text, including binary formats
never meant to be strings (CompactSeedQR entropy is matched further
down, by byte length), so random entropy that both survives that
conversion and begins with a matching prefix would be misclassified as
a descriptor. The old substring was long enough for this to be
negligible; these prefixes are not.

Validate the candidate as an actual descriptor -- checksum and all --
before committing to the classification. GenericWalletQrDecoder already
does this downstream, but too late to help: by then detect_segment_type
has settled on a QR type with no path back to the seed checks below.

Defensive hardening for a constructed case, not one observed in the
wild; the regression test says so explicitly rather than implying a
field report.
Liana does not populate witness_script on its own change outputs; it
supplies only bip32_derivations. The p2wsh branch of _parse_outputs
therefore could not rebuild the scriptpubkey, fell through to "not
change", and counted the change as money leaving the wallet.

Observed on hardware: a 10,000 sat input paying 5,000 out with 4,827
back as change displayed a 9,827 sat spend, listing the change as a
second external destination. It fails safe -- nothing is hidden and both
addresses are shown -- but it denies the user any on-device confirmation
that the change returns to them, which is a core reason to use a signer.

Fall back to checking whether an output references a key that provably
re-derives from this seed. Fingerprints are not consulted: 32 bits are
trivially grindable, so the full pubkey is compared instead. This
establishes only that our key is referenced, not that the scriptpubkey
encodes our policy -- a coordinator can attach a genuine derivation of
our pubkey to an output paying elsewhere. Ownership is still settled by
verify_multisig_output() against the registered descriptor.

For that check to actually run, add requires_descriptor_verification.
is_multisig is "m" in policy, which is False for Miniscript, so change
verification would have tried single-sig re-derivation -- impossible for
a wsh() script, and reported to the user as a suspicious transaction on a
valid one. Only wsh()/p2sh-p2wsh without m/n change behavior here;
single-sig and basic multisig resolve exactly as before.

The existing tests missed all of this because the fixture populated
witness_script on the change output, which real Liana does not do. New
tests model the real structure, including a hostile coordinator attaching
our derivation to a foreign script to confirm the candidate check is
never mistaken for ownership. Each new test was confirmed to fail against
the previous code.
…plate

kdmukai (maintainer) reviewed this PR as a concept NACK: a generic
recursive Miniscript-AST-to-English summary forces the user to mentally
track parenthesization to know which spending conditions actually apply
together, which gets unreadable fast on a 240x240 screen -- exactly the
class of footgun SeedSigner otherwise goes out of its way to avoid. His
own 2023 exploration took the opposite approach: recognize specific known
policy templates and give each one dedicated, structured review screens
instead of raw policy text.

This replaces the generic path with exactly that, scoped to the one
template this PR's actual use case (Liana's inheritance wallet) needs:
"spendable now by a primary key, or by a recovery key after a relative
timelock."

- embit_utils.match_liana_recovery_policy() recognizes that one shape --
  wsh(or_d(pk(primary),and_v(v:pkh(recovery),older(N)))) or its taproot
  equivalent -- structurally, by walking the parsed Miniscript AST rather
  than string-matching. Returns None for anything else: additional OR
  branches, thresh()/multi() nested inside, a different wrapper shape, or
  this exact shape with a BIP68 time-based (not block-based) timelock,
  which Liana has never been observed to produce for this policy.

- is_supported_wallet_descriptor() is narrowed to match: basic multisig is
  unaffected, taproot key-path-only (no hidden leaves -- trivially just one
  key) is still accepted generically, but wsh() Miniscript and taproot with
  script-path leaves are now accepted ONLY when they match the curated
  template. Arbitrary Miniscript -- including kdmukai's own more complex
  2023 example, a 2-of-3 multisig degrading to any 1-of-3 key -- is
  rejected exactly like it always was pre-PR, falling through to
  NotYetImplementedView.

- LianaRecoveryWalletScreen replaces the generic policy-string display for
  a template match: two separate labeled fields ("Spend now with" /
  "OR after N blocks with"), each a bare fingerprint, no expression to
  parse. Verified as an actual rendered 240x240 image, not just
  constructed -- see PR discussion.

- Miniscript support is gated behind a new Settings > Advanced > "Miniscript
  wallets" toggle, disabled by default, matching the existing
  SETTING__MESSAGE_SIGNING / SETTING__ELECTRUM_SEEDS idiom exactly
  (including routing through the existing OptionDisabledView when off).
  Unlike basic multisig, this is new, less-reviewed code; an explicit,
  off-by-default opt-in means a user who never turned it on can't be routed
  through it by an unexpected QR. Basic multisig and key-path-only taproot
  are long-established and are not gated by this setting.

Tests: match_liana_recovery_policy() covered directly (both curated shapes,
plus rejection of basic multisig, a bare single key, a superficially
similar 3-way OR, and a time-based timelock). is_supported_wallet_descriptor
gained a regression case using kdmukai's own complex example to confirm
it's now rejected. Flow tests updated for the new Settings gate, plus new
flow tests for the disabled-by-default default state and confirming basic
multisig is unaffected. Full suite: 223 passed (up from 217; the 6 new
Miniscript-scope tests), 1 pre-existing unrelated failure (macOS-only
libraqm/harfbuzz version-skew, confirmed identical without this change).
Each new/changed assertion was confirmed to fail against the prior commit
before being added.
Found in on-device testing: after registering a recovery wallet, Address
Explorer's one-line "Wallet descriptor" field still rendered the generic
policy expression -- "(key BCE87290) or ((key 36D9CF93) and (after 4383
blocks))" -- which ran off the right edge of the screen mid-word.

The curated screen replaced this on the registration view, but this second
call site was missed. Line-wrapping it would not have been a fix either:
the nested expression is the thing that's unsafe to show, not merely its
length.

Handled in get_descriptor_policy_summary() rather than at the call site, so
a descriptor matching the curated template now returns a short fixed name
("Recovery wallet") everywhere, and no current or future caller can
reintroduce the raw expression by accident. Policy details still live on
the curated review screen, as labeled fields.

Also adds auto_line_break to that field as defense in depth -- without it,
any over-long value is silently clipped at the screen edge rather than
wrapped, which is how this stayed invisible to the existing screenshot
coverage.

Tests assert on the absence of expression syntax rather than just on
length, so a change that merely shortens the expression still fails. The
taproot "never summarize a hidden recovery leaf as single-sig" requirement
is retested against a two-leaf taproot, which the curated matcher rejects
and which therefore still exercises the generic description path. New
screenshot config covers the Address Explorer screen that was broken.
A 2-of-3 primary path with a timelocked recovery key is Liana's flagship
configuration, not an edge case, so the curated template now covers key
quorums on either path rather than single keys only.

Matching is driven by descriptors copied verbatim from Liana's own test
suite (liana-gui/src/app/state/{receive,psbt}.rs), which revealed that
Liana emits two different multi-key forms: multi(k,...) for a quorum on
the primary path, but thresh(k,pkh(A),a:pkh(B)) for one on the recovery
path, since that branch sits under and_v and needs different miniscript
type properties. A matcher handling only multi() would have silently
rejected every multi-key recovery wallet.

Both paths are now represented uniformly as a threshold over a key list,
so a single key is simply 1-of-1 and the previously verified single-key
display is unchanged. Thresholds fold into the field labels ("Spend now,
2 of 3") rather than taking their own line, so a quorum costs no vertical
space beyond the extra fingerprints. A 1-of-1 path omits the threshold,
since "1 of 1" is noise.

Legs that are not plain keys are still refused: a leg carrying its own
nested condition, an absolute after() timelock where the screen says
"after N blocks" (relative), or a hash preimage requirement the two-path
screen has nowhere to show. Approximating any of those would understate
what is actually required to spend.

Adds a display-capacity limit, enforced at match time. Fingerprints render
two per line with room for four lines across both paths; measured against
the real screen, 3 primary lines + 1 recovery line ends at 178px against a
200px button top, while one more line reaches 199-201px. Past that the
recovery section slides under the buttons and becomes invisible, hiding
the timelocked path entirely -- strictly worse than declining the wallet,
so such policies are refused. This permits up to a 5-key primary with a
2-key recovery, well beyond the 2-of-3 and 3-of-5 setups seen in practice.

Screenshot config added for the 2-of-3 case. Full suite: 225 passed.
A real Liana export -- 3-of-3 primary plus a single timelocked recovery
key -- was refused, showing "Not Yet Implemented" on hardware. It differs
structurally from the k-of-n case in three ways, all downstream of one
fact: `or_d(X,Z)` requires X to be dissatisfiable, and an `and_v` chain is
not. So an all-keys-required primary compiles to `or_i` instead, with the
recovery branch first (the reverse of the or_d form), and the keys chained
through nested `and_v` rather than listed in `multi()`.

Rather than encode that as two positional special cases, the branch
carrying the timelock is now identified by inspection and the other is
taken as the primary. That handles both operators and both orderings, and
it is also what keeps multi-tier recovery policies refused: when Liana
defines several recovery paths, every branch is timelocked, so nothing
qualifies as the "Spend now" path and no match is returned. Describing a
timelocked branch as spendable now would be false.

An and_v chain is read as n-of-n, threshold equal to the key count. Getting
that wrong in the lenient direction would be the dangerous failure: showing
a 3-of-3 as "2 of 3" would tell the user their wallet tolerates the loss of
a key when it does not.

Test fixture is the real signet descriptor from that hardware run, rather
than a reconstruction. Note it also has the recovery key appearing among
the primary keys on a different derivation branch, which is legal and which
the display must not obscure. Full suite: 227 passed; the new n-of-n test
confirmed to fail against the previous commit.
Covers the or_i + and_v shape from the previous commit, so the case that
showed up as "Not Yet Implemented" on hardware now has a rendered screen in
CI alongside the single-key and k-of-n ones.

Uses the same neutral test keys as the other screenshot fixtures rather
than the real signet wallet the bug was found with -- the descriptor shape
is what matters here, and the real one is only needed in the matcher test
where its exact fingerprints and threshold are asserted.
Found on hardware with a 3-of-3 Liana wallet: a psbt exported after one key
had already signed, then offered to that same seed again, showed "Signing
Failed / Signing with this seed did not add a valid signature". The
signatures were valid and present; nothing had failed.

The signing flow judged success by whether sig_count() increased.
partial_sigs is keyed by pubkey, so re-signing overwrites the existing entry
rather than adding one -- and since embit's nonces are deterministic, even
the signature bytes are identical. The count is therefore unchanged both
when a seed cannot sign at all and when it has already signed, two
situations that warrant opposite responses.

has_signature_from_seed() tells them apart by re-deriving each candidate key
from the signing seed and comparing the serialized pubkey, rather than
trusting the psbt's claimed fingerprints, which are 32 bits and supplied by
the coordinator. This only selects which message is shown, so a wrong answer
would be cosmetic rather than dangerous, but deriving properly costs little
and keeps the claimed-vs-verified split this class documents intact.

Pre-existing behavior that applies to basic multisig too, but far more
reachable now: n-of-n and multisig wallets are signed repeatedly with
different seeds, so reaching for one that has already been used is an
ordinary mistake rather than an unusual one. The old message sent the user
looking for a signing bug that wasn't there.

The TODO at that call site asking whether failure scenarios could be
distinguished is now answered for this case and removed.
The two screens a user meets when Miniscript wallets is left at its default
of disabled: the OptionDisabledView shown on scanning a Miniscript
descriptor, and the settings entry itself. Both confirmed on hardware.

The settings entry screenshot is generated automatically for every
SettingsEntry, so only the OptionDisabledView variant needed wiring up.
Rebasing onto SeedSigner#1013 brought a canonical ownership check, so establish
ownership through that rather than deriving and comparing keys by hand.

Also records why this check stays necessary now that
_reject_if_seed_cannot_sign() exists: that guarantees the seed can sign
some input, which is not the same as the signing pass having added a
signature, so "already signed" is still worth asking directly rather than
inferring from the absence of a rejection.
@SovereignGG
SovereignGG force-pushed the miniscript-wsh-policy-display branch from d3fb4ce to e4a03df Compare September 3, 2026 22:26
Three screens that were being shown as hand-made renders rather than
generator output:

- A 2-of-3 primary with a 1-of-2 recovery quorum. Liana expresses a
  multi-key recovery path as thresh() with a: wrappers rather than
  multi(), so this covers a matcher branch no other fixture reaches.
- A 2-of-3 basic multisig, on both the registration screen and Address
  Explorer. The existing basic-multisig fixture is a 1-of-2, which reads
  oddly beside a 2-of-3 Miniscript policy, and Address Explorer is worth
  covering in particular since this PR modifies that shared screen.
@SovereignGG

Copy link
Copy Markdown
Author

Rebased onto dev now that #1013 has landed — the PR is mergeable again.

That merge overlapped this work directly, and in a useful way. Two changes here were doing by hand what seed_owns_pubkey() and verified_output_derivation_paths now do properly:

  • Change detection. I had a helper that re-derived keys from the signing seed to decide whether an output was a change candidate. _verify_claimed_derivation_paths() already establishes exactly that, before _parse_outputs() runs, so the helper is deleted and the fallback is now one line consulting verified_output_derivation_paths[i]. That's strictly better than what I had — it uses verified ownership rather than my own derivation, and the check now sits on top of your abstraction instead of beside it.
  • The already-signed check goes through seed_owns_pubkey() for the same reason.

One thing that did not become redundant: _get_policy() still calls _parse_multisig() unguarded, so a Miniscript witness script still raises there. That fix stays, and I've kept your new TODO about the bare except: swallowing everything.

Worth noting for whoever picks up that TODO: the degraded policy it describes — {"type": "p2wsh"} with no m/n or cosigners — is the normal state for a Miniscript wallet, not an anomaly. Two different wsh() wallets compare equal under it, which is why change detection here can't rely on policy comparison alone and needs the verified-ownership path.

PSBTSeedCannotSignError also improves the signing-error fix in this PR: with a wrong seed now rejected up front, "no new signature" is much closer to meaning "already signed". I kept the explicit check rather than inferring it from the absence of a rejection, since those aren't quite the same thing, but the ambiguity it resolves is narrower than it was.

Test suite is at 250 passing — your 19 new ownership tests and mine both green.

Re-verified end to end on hardware after the rebase (Pi Zero 1.3, signet), since this touched signing-adjacent code and picked up rejection paths that did not exist when I last tested:

  • 3-of-3 policy registers and displays correctly
  • Signing a fresh psbt: change still correctly identified, spend amount excludes change
  • Signing with a seed that already signed: reports "Already Signed" rather than a signing failure
  • Signing with a seed that is not in the wallet: now turned away up front by PSBTSeedCannotSignError, before the transaction is reviewed, rather than after approval
  • Address Explorer receive addresses still match Liana character-for-character

Also added generator coverage for a thresh() recovery quorum and for a 2-of-3 basic multisig on both the registration and Address Explorer screens, so every screen referenced above is reproducible from the screenshot generator rather than hand-made.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants