Repository navigation
Accept, display, and sign wsh() Miniscript wallet descriptors (e.g. Liana) - #1026
SovereignGG wants to merge 16 commits into
Conversation
|
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:
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 thisAt 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. And I created these curated review screens: 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:
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. |
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.
d3fb4ce to
e4a03df
Compare
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.
|
Rebased onto That merge overlapped this work directly, and in a useful way. Two changes here were doing by hand what
One thing that did not become redundant: Worth noting for whoever picks up that TODO: the degraded policy it describes —
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:
Also added generator coverage for a |











Description
Problem or Issue being addressed
SeedSigner's
ScanView.run()gates wallet-descriptor registration ondescriptor.is_basic_multisig, silently routing anything else — includingany Miniscript
wsh()/tr()descriptor — toNotYetImplementedView. Thisblocks 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 persistentregistration/proof-of-registration yet, taproot signing deferred.
Solution
get_descriptor_policy_summary()/is_supported_wallet_descriptor()/
can_derive_multisig_address()helpers inembit_utils.py— arecursive Miniscript-AST walker that turns any
wsh()/tr()policy intoa plain-English summary (e.g.
(key ABCD1234) or ((key 5678EFGH) and (after 1000 blocks))), used in place of the old basic-multisig-onlyget_multisig_policy()at its call sites.ScanView,MultisigWalletDescriptorView,ToolsAddressExplorerAddressTypeView, andToolsAddressExplorerAddressListView— the registration gate is loosened,no new views added.
decode_qr.py's QR-type detection had a second, earlier gate that's easyto miss: a plain-text wallet-descriptor QR was only classified as
WALLET__GENERICif 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-levelfunction (
sh/wsh/tr/pkh/wpkh/combo); a merely descriptor-shapedstring 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 neededauto_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.
PSBTParserfixes, both found only once a real Liana PSBT wasscanned on physical hardware:
_parse_multisig()raised an unhandledValueErrorfor any witnessscript that isn't bare
OP_CHECKMULTISIG— i.e. any real Miniscriptscript. Now caught, degrading gracefully to a policy dict without
m/n/cosigners, matching the existing swallowed-exception patternthe same function already uses one level up for
_get_cosigners().(or any unrelated address) can share the same generic
{"type": "p2wsh"}policy and reach change-reconstruction code with nowitness_scriptpopulated — a real coordinator only fills that in foroutputs 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.
decode_qr.pyprefix match above is validated withDescriptor.from_string()before the QR type is assigned. The prefixpattern is as short as
tr((3 bytes), anddetect_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, theseprefixes are not.
GenericWalletQrDecodervalidates the same waydownstream, but too late to help — by then
detect_segment_type()hassettled 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 andsigning remain unimplemented — pre-existing
get_multisig_address()/PSBTParserlimitations, unchanged here. Only taproot policy display iscovered by this PR, and it's held to the same correctness bar as
wsh(): ahidden 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-hwidriver, andLiana'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
PSBTParserfixes came from that hardware run, not code review — areminder that this class of bug (code implicitly assuming a witness script
is always bare
OP_CHECKMULTISIG) is easy to miss without an actualMiniscript 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,
MultisigWalletDescriptorScreenshowing the registeredpolicy from the hardware run referenced above:
This pull request is categorized as a:
Checklist
I ran
pytestlocally217 passed (209 existing + 3 new regression tests: 2 for the
PSBTParserfixes and 1 for the
decode_qr.pyfix, plus 5l10ntests that only passonce 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.
I added or updated tests
Any new or altered functionality should be covered in a unit test. Any new or updated sequences require FlowTests.
New unit tests in
test_embit_utils.pyfor the policy-summary/gate helpers,new
FlowStepsequences intest_flows_tools.pyfor the registrationgate, and new regression tests in
test_psbt_parser.pyandtest_seedqr.pyfor 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:
Thank you! Please join our Devs' Telegram group to get more involved.