From 4c8b6c72267004be9527a0a9427900beb7f3763c Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Thu, 6 Aug 2026 18:05:15 +0200 Subject: [PATCH 01/26] coldcard: improve return type annotations --- hwilib/devices/coldcard.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/hwilib/devices/coldcard.py b/hwilib/devices/coldcard.py index df8b61b92..63ad02f6a 100644 --- a/hwilib/devices/coldcard.py +++ b/hwilib/devices/coldcard.py @@ -116,10 +116,10 @@ def __init__(self, path: str, password: Optional[str] = None, expert: bool = Fal device.open_path(path.encode()) self.device = ColdcardDevice(dev=device) - self._is_edge = None + self._is_edge: Optional[bool] = None @property - def is_edge(self): + def is_edge(self) -> bool: """ Cached property, no need to ask device more than once :return: bool @@ -131,7 +131,7 @@ def is_edge(self): # silent fail, normal firmware is implied pass - return self._is_edge + return bool(self._is_edge) def _supports_psbt_v2(self) -> bool: if self.device.is_simulator or self.is_edge: @@ -376,10 +376,12 @@ def display_bip388_policy_address( or not isinstance(descriptor.subdescriptors[0], MultisigDescriptor) ): raise BadArgumentError("Coldcard only supports wsh(sortedmulti()) policies") - return self.display_multisig_address( + address = self.display_multisig_address( AddressType.WIT, descriptor.subdescriptors[0], ) + assert isinstance(address, str) + return address def setup_device(self, label: str = "", passphrase: str = "") -> bool: """ @@ -473,7 +475,7 @@ def can_sign_taproot(self) -> bool: Only COLDCARD EDGE support taproot. :returns: Whether Taproot is supported """ - return self.is_edge + return bool(self.is_edge) @coldcard_exception def register_descriptor(self, name: str, descriptor: 'Descriptor') -> RegisteredDescriptor: From 416ef037fc5082a8a8a81f41e413d6673e6c7dbc Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 11:48:50 +0200 Subject: [PATCH 02/26] ledger: decode MuSig2 signing yields Decode tagged public nonces and partial signatures returned by the Bitcoin app while preserving the existing signature format. Add focused unit tests. https://github.com/LedgerHQ/app-bitcoin/commit/acc0530c23fcd0fa84f428968fae7ede3c1b0742 Co-authored-by: Salvatore Ingala <6681844+bigspider@users.noreply.github.com> --- hwilib/devices/ledger_bitcoin/client.py | 68 +++++++++++++--- hwilib/devices/ledger_bitcoin/client_base.py | 35 ++++++++- .../devices/ledger_bitcoin/client_command.py | 3 + test/run_tests.py | 2 + test/test_ledger_bitcoin.py | 78 +++++++++++++++++++ 5 files changed, 175 insertions(+), 11 deletions(-) create mode 100644 test/test_ledger_bitcoin.py diff --git a/hwilib/devices/ledger_bitcoin/client.py b/hwilib/devices/ledger_bitcoin/client.py index 406760b95..d4bfdd8a8 100644 --- a/hwilib/devices/ledger_bitcoin/client.py +++ b/hwilib/devices/ledger_bitcoin/client.py @@ -4,8 +4,19 @@ from .command_builder import BitcoinCommandBuilder, BitcoinInsType from ...common import Chain -from .client_command import ClientCommandInterpreter -from .client_base import Client, PartialSignature, SignPsbtYieldedObject, TransportClient +from .client_command import ( + CCMD_YIELD_MUSIG_PARTIALSIGNATURE_TAG, + CCMD_YIELD_MUSIG_PUBNONCE_TAG, + ClientCommandInterpreter, +) +from .client_base import ( + Client, + MusigPartialSignature, + MusigPubNonce, + PartialSignature, + SignPsbtYieldedObject, + TransportClient, +) from .client_legacy import LegacyClient from .errors import UnknownDeviceError from .exception import DeviceException, NotSupportedError @@ -51,18 +62,55 @@ def _make_partial_signature(pubkey_augm: bytes, signature: bytes) -> PartialSign def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObject]: res_buffer = BytesIO(res) input_index_or_tag = read_varint(res_buffer) + if input_index_or_tag == CCMD_YIELD_MUSIG_PUBNONCE_TAG: + input_index = read_varint(res_buffer) + pubnonce = res_buffer.read(66) + participant_pk = res_buffer.read(33) + agg_xonlykey = res_buffer.read(32) + tapleaf_hash = res_buffer.read() + if len(tapleaf_hash) == 0: + tapleaf_hash = None + + return ( + input_index, + MusigPubNonce( + participant_pubkey=participant_pk, + agg_xonlykey=agg_xonlykey, + tapleaf_hash=tapleaf_hash, + pubnonce=pubnonce + ) + ) + elif input_index_or_tag == CCMD_YIELD_MUSIG_PARTIALSIGNATURE_TAG: + input_index = read_varint(res_buffer) + partial_signature = res_buffer.read(32) + participant_pk = res_buffer.read(33) + agg_xonlykey = res_buffer.read(32) + tapleaf_hash = res_buffer.read() + if len(tapleaf_hash) == 0: + tapleaf_hash = None + + return ( + input_index, + MusigPartialSignature( + participant_pubkey=participant_pk, + agg_xonlykey=agg_xonlykey, + tapleaf_hash=tapleaf_hash, + partial_signature=partial_signature + ) + ) + else: + # other values follow an encoding without an explicit tag, where the + # first element is the input index. All the signature types are implemented + # by the PartialSignature type (not to be confused with the musig Partial Signature). + input_index = input_index_or_tag - # values follow an encoding without an explicit tag, where the - # first element is the input index. All the signature types are implemented - # by the PartialSignature type (not to be confused with the musig Partial Signature). - input_index = input_index_or_tag + pubkey_augm_len = read_uint(res_buffer, 8) + pubkey_augm = res_buffer.read(pubkey_augm_len) - pubkey_augm_len = read_uint(res_buffer, 8) - pubkey_augm = res_buffer.read(pubkey_augm_len) + signature = res_buffer.read() - signature = res_buffer.read() + return (input_index, _make_partial_signature(pubkey_augm, signature)) - return((input_index, _make_partial_signature(pubkey_augm, signature))) def read_uint(buf: BytesIO, bit_len: int, diff --git a/hwilib/devices/ledger_bitcoin/client_base.py b/hwilib/devices/ledger_bitcoin/client_base.py index a0a57af62..6297b4b29 100644 --- a/hwilib/devices/ledger_bitcoin/client_base.py +++ b/hwilib/devices/ledger_bitcoin/client_base.py @@ -65,7 +65,40 @@ class PartialSignature: tapleaf_hash: Optional[bytes] = None -SignPsbtYieldedObject = Union[PartialSignature] +@dataclass(frozen=True) +class MusigPubNonce: + """Represents a pubnonce returned by sign_psbt during the first round of a Musig2 signing session. + + It always contains + - the participant_pubkey, a 33-byte compressed pubkey; + - agg_xonlykey, the 32-byte x-only key that is the aggregate and tweaked key present in the script; + - the 66-byte pubnonce. + + The tapleaf_hash is also filled if signing for a tapscript; `None` otherwise. + """ + participant_pubkey: bytes + agg_xonlykey: bytes + tapleaf_hash: Optional[bytes] + pubnonce: bytes + + +@dataclass(frozen=True) +class MusigPartialSignature: + """Represents a partial signature returned by sign_psbt during the second round of a Musig2 signing session. + + It always contains + - the participant_pubkey, a 33-byte compressed pubkey; + - agg_xonlykey, the 32-byte x-only key that is the aggregate and tweaked key present in the script; + - the partial_signature, the 32-byte partial signature for this participant. + + The tapleaf_hash is also filled if signing for a tapscript; `None` otherwise + """ + participant_pubkey: bytes + agg_xonlykey: bytes + tapleaf_hash: Optional[bytes] + partial_signature: bytes + +SignPsbtYieldedObject = Union[PartialSignature, MusigPubNonce, MusigPartialSignature] class Client: def __init__(self, transport_client: TransportClient, chain: Chain = Chain.MAIN) -> None: diff --git a/hwilib/devices/ledger_bitcoin/client_command.py b/hwilib/devices/ledger_bitcoin/client_command.py index 9fd57c464..c6b017775 100644 --- a/hwilib/devices/ledger_bitcoin/client_command.py +++ b/hwilib/devices/ledger_bitcoin/client_command.py @@ -46,6 +46,9 @@ class ClientCommandCode(IntEnum): GET_MERKLE_LEAF_INDEX = 0x42 GET_MORE_ELEMENTS = 0xA0 +CCMD_YIELD_MUSIG_PUBNONCE_TAG = 0xFFFFFFFF +CCMD_YIELD_MUSIG_PARTIALSIGNATURE_TAG = 0xFFFFFFFE + class ClientCommand: def execute(self, request: bytes) -> bytes: diff --git a/test/run_tests.py b/test/run_tests.py index 28d8f7a95..a90a42b57 100755 --- a/test/run_tests.py +++ b/test/run_tests.py @@ -13,6 +13,7 @@ from test_psbt import TestPSBT from test_trezor import trezor_test_suite from test_ledger import ledger_test_suite +from test_ledger_bitcoin import TestLedgerBitcoinClient from test_digitalbitbox import digitalbitbox_test_suite from test_keepkey import keepkey_test_suite from test_jade import jade_test_suite @@ -90,6 +91,7 @@ suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestBase58)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestBIP32)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestColdcardFirmware)) + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestLedgerBitcoinClient)) if sys.platform.startswith("linux"): suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestUdevRulesInstaller)) success = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful() diff --git a/test/test_ledger_bitcoin.py b/test/test_ledger_bitcoin.py new file mode 100644 index 000000000..9dd1275b8 --- /dev/null +++ b/test/test_ledger_bitcoin.py @@ -0,0 +1,78 @@ +#! /usr/bin/env python3 + +import unittest + +from hwilib._serialize import ser_compact_size +from hwilib.devices.ledger_bitcoin.client import _decode_signpsbt_yielded_value +from hwilib.devices.ledger_bitcoin.client_base import ( + MusigPartialSignature, + MusigPubNonce, + PartialSignature, +) +from hwilib.devices.ledger_bitcoin.client_command import ( + CCMD_YIELD_MUSIG_PARTIALSIGNATURE_TAG, + CCMD_YIELD_MUSIG_PUBNONCE_TAG, +) + + +class TestLedgerBitcoinClient(unittest.TestCase): + PARTICIPANT_PUBKEY = bytes.fromhex("02" + "11" * 32) + AGG_XONLYKEY = bytes.fromhex("22" * 32) + TAPLEAF_HASH = bytes.fromhex("33" * 32) + + def test_decode_partial_signature(self): + pubkey = bytes.fromhex("02" + "44" * 32) + signature = bytes.fromhex("55" * 64) + result = _decode_signpsbt_yielded_value( + ser_compact_size(3) + bytes([len(pubkey)]) + pubkey + signature + ) + self.assertEqual(result, (3, PartialSignature(pubkey, signature))) + + def test_decode_musig_pubnonce(self): + pubnonce = bytes.fromhex("66" * 66) + result = _decode_signpsbt_yielded_value( + ser_compact_size(CCMD_YIELD_MUSIG_PUBNONCE_TAG) + + ser_compact_size(4) + + pubnonce + + self.PARTICIPANT_PUBKEY + + self.AGG_XONLYKEY + + self.TAPLEAF_HASH + ) + self.assertEqual( + result, + ( + 4, + MusigPubNonce( + participant_pubkey=self.PARTICIPANT_PUBKEY, + agg_xonlykey=self.AGG_XONLYKEY, + tapleaf_hash=self.TAPLEAF_HASH, + pubnonce=pubnonce, + ), + ), + ) + + def test_decode_musig_partial_signature(self): + partial_signature = bytes.fromhex("77" * 32) + result = _decode_signpsbt_yielded_value( + ser_compact_size(CCMD_YIELD_MUSIG_PARTIALSIGNATURE_TAG) + + ser_compact_size(5) + + partial_signature + + self.PARTICIPANT_PUBKEY + + self.AGG_XONLYKEY + ) + self.assertEqual( + result, + ( + 5, + MusigPartialSignature( + participant_pubkey=self.PARTICIPANT_PUBKEY, + agg_xonlykey=self.AGG_XONLYKEY, + tapleaf_hash=None, + partial_signature=partial_signature, + ), + ), + ) + + +if __name__ == "__main__": + unittest.main() From 95ed48bfc0a81eabfff6cbced33c71bf2df481b7 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 11:49:28 +0200 Subject: [PATCH 03/26] ledger: decode compressed MuSig2 aggregate pubkeys The Bitcoin app now yields the 33-byte compressed aggregate public key instead of its 32-byte x-only form. Match the current protocol. https://github.com/LedgerHQ/app-bitcoin/commit/41be6f1e4beb90b36fcc4ba3fee40d0256a844d7 Co-authored-by: Salvatore Ingala <6681844+bigspider@users.noreply.github.com> --- hwilib/devices/ledger_bitcoin/client.py | 8 ++++---- hwilib/devices/ledger_bitcoin/client_base.py | 10 ++++++---- test/test_ledger_bitcoin.py | 10 +++++----- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/hwilib/devices/ledger_bitcoin/client.py b/hwilib/devices/ledger_bitcoin/client.py index d4bfdd8a8..734d06330 100644 --- a/hwilib/devices/ledger_bitcoin/client.py +++ b/hwilib/devices/ledger_bitcoin/client.py @@ -66,7 +66,7 @@ def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObje input_index = read_varint(res_buffer) pubnonce = res_buffer.read(66) participant_pk = res_buffer.read(33) - agg_xonlykey = res_buffer.read(32) + aggregate_pubkey = res_buffer.read(33) tapleaf_hash = res_buffer.read() if len(tapleaf_hash) == 0: tapleaf_hash = None @@ -75,7 +75,7 @@ def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObje input_index, MusigPubNonce( participant_pubkey=participant_pk, - agg_xonlykey=agg_xonlykey, + aggregate_pubkey=aggregate_pubkey, tapleaf_hash=tapleaf_hash, pubnonce=pubnonce ) @@ -84,7 +84,7 @@ def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObje input_index = read_varint(res_buffer) partial_signature = res_buffer.read(32) participant_pk = res_buffer.read(33) - agg_xonlykey = res_buffer.read(32) + aggregate_pubkey = res_buffer.read(33) tapleaf_hash = res_buffer.read() if len(tapleaf_hash) == 0: tapleaf_hash = None @@ -93,7 +93,7 @@ def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObje input_index, MusigPartialSignature( participant_pubkey=participant_pk, - agg_xonlykey=agg_xonlykey, + aggregate_pubkey=aggregate_pubkey, tapleaf_hash=tapleaf_hash, partial_signature=partial_signature ) diff --git a/hwilib/devices/ledger_bitcoin/client_base.py b/hwilib/devices/ledger_bitcoin/client_base.py index 6297b4b29..6020043eb 100644 --- a/hwilib/devices/ledger_bitcoin/client_base.py +++ b/hwilib/devices/ledger_bitcoin/client_base.py @@ -71,13 +71,14 @@ class MusigPubNonce: It always contains - the participant_pubkey, a 33-byte compressed pubkey; - - agg_xonlykey, the 32-byte x-only key that is the aggregate and tweaked key present in the script; + - aggregate_pubkey, the 33-byte compressed pubkey key that is the aggregate of all the participant + pubkeys, with the necessary tweaks; its x-only version is the key present in the Script; - the 66-byte pubnonce. The tapleaf_hash is also filled if signing for a tapscript; `None` otherwise. """ participant_pubkey: bytes - agg_xonlykey: bytes + aggregate_pubkey: bytes tapleaf_hash: Optional[bytes] pubnonce: bytes @@ -88,13 +89,14 @@ class MusigPartialSignature: It always contains - the participant_pubkey, a 33-byte compressed pubkey; - - agg_xonlykey, the 32-byte x-only key that is the aggregate and tweaked key present in the script; + - aggregate_pubkey, the 33-byte compressed pubkey key that is the aggregate of all the participant + pubkeys, with the necessary tweaks; its x-only version is the key present in the Script; - the partial_signature, the 32-byte partial signature for this participant. The tapleaf_hash is also filled if signing for a tapscript; `None` otherwise """ participant_pubkey: bytes - agg_xonlykey: bytes + aggregate_pubkey: bytes tapleaf_hash: Optional[bytes] partial_signature: bytes diff --git a/test/test_ledger_bitcoin.py b/test/test_ledger_bitcoin.py index 9dd1275b8..b5615f72c 100644 --- a/test/test_ledger_bitcoin.py +++ b/test/test_ledger_bitcoin.py @@ -17,7 +17,7 @@ class TestLedgerBitcoinClient(unittest.TestCase): PARTICIPANT_PUBKEY = bytes.fromhex("02" + "11" * 32) - AGG_XONLYKEY = bytes.fromhex("22" * 32) + AGGREGATE_PUBKEY = bytes.fromhex("03" + "22" * 32) TAPLEAF_HASH = bytes.fromhex("33" * 32) def test_decode_partial_signature(self): @@ -35,7 +35,7 @@ def test_decode_musig_pubnonce(self): + ser_compact_size(4) + pubnonce + self.PARTICIPANT_PUBKEY - + self.AGG_XONLYKEY + + self.AGGREGATE_PUBKEY + self.TAPLEAF_HASH ) self.assertEqual( @@ -44,7 +44,7 @@ def test_decode_musig_pubnonce(self): 4, MusigPubNonce( participant_pubkey=self.PARTICIPANT_PUBKEY, - agg_xonlykey=self.AGG_XONLYKEY, + aggregate_pubkey=self.AGGREGATE_PUBKEY, tapleaf_hash=self.TAPLEAF_HASH, pubnonce=pubnonce, ), @@ -58,7 +58,7 @@ def test_decode_musig_partial_signature(self): + ser_compact_size(5) + partial_signature + self.PARTICIPANT_PUBKEY - + self.AGG_XONLYKEY + + self.AGGREGATE_PUBKEY ) self.assertEqual( result, @@ -66,7 +66,7 @@ def test_decode_musig_partial_signature(self): 5, MusigPartialSignature( participant_pubkey=self.PARTICIPANT_PUBKEY, - agg_xonlykey=self.AGG_XONLYKEY, + aggregate_pubkey=self.AGGREGATE_PUBKEY, tapleaf_hash=None, partial_signature=partial_signature, ), From 6d01fb8b69473c6ba01f17a381fdf39913ff27aa Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 11:50:25 +0200 Subject: [PATCH 04/26] ledger: parse unknown sign_psbt yield tags Return an opaque object for future app tags instead of treating the tag as an enormous input index. Add focused unit coverage. https://github.com/LedgerHQ/app-bitcoin/commit/027541a436d994925da46d465d5c507cf15284a0 Co-authored-by: Salvatore Ingala <6681844+bigspider@users.noreply.github.com> --- hwilib/devices/ledger_bitcoin/client.py | 6 ++++++ hwilib/devices/ledger_bitcoin/client_base.py | 18 +++++++++++++++++- test/test_ledger_bitcoin.py | 14 ++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/hwilib/devices/ledger_bitcoin/client.py b/hwilib/devices/ledger_bitcoin/client.py index 734d06330..7e5392a3d 100644 --- a/hwilib/devices/ledger_bitcoin/client.py +++ b/hwilib/devices/ledger_bitcoin/client.py @@ -16,6 +16,7 @@ PartialSignature, SignPsbtYieldedObject, TransportClient, + UnknownSignPsbtYieldedObject, ) from .client_legacy import LegacyClient from .errors import UnknownDeviceError @@ -98,6 +99,11 @@ def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObje partial_signature=partial_signature ) ) + elif input_index_or_tag >= 0x80000000: + # This is certainly an unknown tag added by a future version of the app. + # The first element is the input index; the remaining data is opaque. + input_index = read_varint(res_buffer) + return input_index, UnknownSignPsbtYieldedObject(input_index_or_tag, res_buffer.read()) else: # other values follow an encoding without an explicit tag, where the # first element is the input index. All the signature types are implemented diff --git a/hwilib/devices/ledger_bitcoin/client_base.py b/hwilib/devices/ledger_bitcoin/client_base.py index 6020043eb..fcf4b85e3 100644 --- a/hwilib/devices/ledger_bitcoin/client_base.py +++ b/hwilib/devices/ledger_bitcoin/client_base.py @@ -100,7 +100,23 @@ class MusigPartialSignature: tapleaf_hash: Optional[bytes] partial_signature: bytes -SignPsbtYieldedObject = Union[PartialSignature, MusigPubNonce, MusigPartialSignature] + +@dataclass(frozen=True) +class UnknownSignPsbtYieldedObject: + """Represents an unknown object returned by sign_psbt, for forward compatibility. + + It contains the tag and the opaque bytes returned by the device. + """ + tag: int + data: bytes + + +SignPsbtYieldedObject = Union[ + PartialSignature, + MusigPubNonce, + MusigPartialSignature, + UnknownSignPsbtYieldedObject, +] class Client: def __init__(self, transport_client: TransportClient, chain: Chain = Chain.MAIN) -> None: diff --git a/test/test_ledger_bitcoin.py b/test/test_ledger_bitcoin.py index b5615f72c..fef14fa37 100644 --- a/test/test_ledger_bitcoin.py +++ b/test/test_ledger_bitcoin.py @@ -8,6 +8,7 @@ MusigPartialSignature, MusigPubNonce, PartialSignature, + UnknownSignPsbtYieldedObject, ) from hwilib.devices.ledger_bitcoin.client_command import ( CCMD_YIELD_MUSIG_PARTIALSIGNATURE_TAG, @@ -73,6 +74,19 @@ def test_decode_musig_partial_signature(self): ), ) + def test_decode_unknown_yielded_object(self): + tag = 0x80000001 + opaque_data = bytes.fromhex("deadbeef") + result = _decode_signpsbt_yielded_value( + ser_compact_size(tag) + + ser_compact_size(6) + + opaque_data + ) + self.assertEqual( + result, + (6, UnknownSignPsbtYieldedObject(tag, opaque_data)), + ) + if __name__ == "__main__": unittest.main() From 3cbd7fb88cf139bfc9122b8704f9b2f66cff8357 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 13:35:14 +0200 Subject: [PATCH 05/26] descriptor: tighten key expression parsing Reject malformed ranged derivation suffixes such as /0*, which were silently misparsed as /*, as well as empty key expressions and trailing commas, which raised IndexError or were silently dropped. Move the ranged suffix parsing into a shared helper. --- hwilib/descriptor.py | 35 +++++++++++++++++++++++++++++------ test/test_descriptor.py | 9 +++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index 1373ad2d2..b621717aa 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -106,6 +106,28 @@ def AddChecksum(desc: str) -> str: return desc + "#" + DescriptorChecksum(desc) +def _parse_ranged_deriv_path(path_str: str) -> Tuple[Optional[List[List[int]]], bool]: + """ + :meta private: + + Parse a derivation path suffix that may end with a ``/*`` range marker. + + :param path_str: The derivation path, without the leading ``/`` that separates it from the key + :return: The multipath derivation path, or ``None`` if there is none, and whether the path is ranged + :raises: ValueError: if the derivation path is malformed + """ + ranged = path_str.endswith("*") + if ranged: + if path_str == "*": + path_str = "" + elif path_str.endswith("/*"): + path_str = path_str[:-2] + else: + raise ValueError(f"Invalid ranged derivation path: /{path_str}") + deriv_path = parse_multipath(path_str) if path_str else None + return deriv_path, ranged + + class PubkeyProvider(object): """ A public key expression in a descriptor. @@ -155,6 +177,8 @@ def parse(cls, s: str, key_expr_index: int) -> 'PubkeyProvider': deriv_path = None ranged = False + if not s: + raise ValueError("Empty key expression") if s[0] == "[": end = s.index("]") origin = KeyOriginInfo.from_string(s[1:end]) @@ -164,12 +188,7 @@ def parse(cls, s: str, key_expr_index: int) -> 'PubkeyProvider': slash_idx = s.find("/") if slash_idx != -1: pubkey = s[:slash_idx] - path_str = s[slash_idx + 1:] - ranged = path_str.endswith("*") - if ranged: - path_str = path_str[:-2] - if len(path_str) > 0: - deriv_path = parse_multipath(path_str) + deriv_path, ranged = _parse_ranged_deriv_path(s[slash_idx + 1:]) return cls(origin, pubkey, deriv_path, key_expr_index, ranged) @@ -558,6 +577,8 @@ def _get_const(s: str, const: str) -> str: :return: The remainder of the string without the constant character :raises: ValueError: if the first character is not the constant character """ + if not s: + raise ValueError(f"Expected '{const}' but reached the end") if s[0] != const: raise ValueError(f"Expected '{const}' but got '{s[0]}'") return s[1:] @@ -599,6 +620,8 @@ def parse_pubkey(expr: str, key_expr_index: int) -> Tuple['PubkeyProvider', str, if comma_idx != -1: end = comma_idx next_expr = expr[end + 1:] + if not next_expr: + raise ValueError("Trailing comma after key expression") return PubkeyProvider.parse(expr[:end], key_expr_index), next_expr, (key_expr_index + 1) diff --git a/test/test_descriptor.py b/test/test_descriptor.py index dca4fbe80..7b495ec20 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -165,6 +165,15 @@ def test_parse_descriptor_with_key_at_end_without_origin(self): def test_parse_empty_descriptor(self): self.assertRaises(ValueError, parse_descriptor, "") + def test_parse_invalid_key_expressions(self): + xpub = "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B" + with self.assertRaisesRegex(ValueError, "Invalid ranged derivation path"): + parse_descriptor(f"wpkh({xpub}/0*)") + with self.assertRaisesRegex(ValueError, "Empty key expression"): + parse_descriptor(f"wsh(multi(1,{xpub}/0/*,,{xpub}/1/*))") + with self.assertRaisesRegex(ValueError, "Trailing comma"): + parse_descriptor(f"wsh(multi(1,{xpub}/0/*,))") + def test_parse_descriptor_replace_h(self): d = "wpkh([00000001/84h/1h/0h]tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/0/0)" desc = parse_descriptor(d) From d1f64422192fc07fa4e6ca1f63a2b141213d4fbf Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 14:40:26 +0200 Subject: [PATCH 06/26] descriptor: deduplicate BIP 388 key information A key that appears more than once in a descriptor, e.g. with different derivation path suffixes, must use a single entry in the BIP 388 Key information vector. Assign key placeholder indexes accordingly after parsing and return each key once from get_pubkey_providers(). Derivation-related callers use the new get_derivation_providers(), which still returns every appearance of a key. --- hwilib/descriptor.py | 45 ++++++++++++++++++++++++++++++++--------- test/test_descriptor.py | 20 +++++++++++++++--- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index b621717aa..3353185ac 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -32,6 +32,7 @@ from enum import Enum from io import BufferedReader, BytesIO from typing import ( + Dict, List, Optional, Tuple, @@ -146,7 +147,8 @@ def __init__( :param origin: The key origin if one is available :param pubkey: The public key. Either a hex string or a serialized extended pubkey :param deriv_path: Additional derivation path if the pubkey is an extended pubkey - :param expr_index: The position of this key within the descriptor + :param expr_index: The index of this key in the BIP 388 Key information vector. + A key that appears multiple times in a descriptor uses the same index everywhere. """ self.origin = origin self.pubkey = pubkey @@ -357,23 +359,39 @@ def get_bip388_template(self) -> str: ) def get_pubkey_providers(self) -> list['PubkeyProvider']: + r""" + Get the individual pubkey expressions contained in this descriptor, in the order in + which they first appear in the descriptor string. A key that appears more than once + is returned only once, matching the BIP 388 Key information vector, so these can be + used with :func:`get_bip388_template` to get a full BIP 388 Wallet Policy for this + descriptor. + + :return: List of :class:`PubkeyProvider`\ s """ - Get the strings of all pubkey expressions contained in this descriptor, - in the same order that they appear in the descriptor string. These can be used with - :func:`get_bip388_template` to get a full BIP 388 Wallet Policy for this descriptor. + out: Dict[str, 'PubkeyProvider'] = {} + for pubkey in self.get_derivation_providers(): + out.setdefault(pubkey.get_bip388_key_info(), pubkey) + return list(out.values()) + + def get_derivation_providers(self) -> list['PubkeyProvider']: + r""" + Get the key expressions contained in this descriptor whose derivation path suffixes + belong to the descriptor, in the same order that they appear in the descriptor + string. Unlike :func:`get_pubkey_providers`, a key that appears more than once is + returned once for each appearance. - :return: List of pubkey expression strings + :return: List of :class:`PubkeyProvider`\ s """ - out = [p for p in self.pubkeys] - for s in self.subdescriptors: - out.extend(s.get_pubkey_providers()) + out = list(self.pubkeys) + for subdescriptor in self.subdescriptors: + out.extend(subdescriptor.get_derivation_providers()) return out def derive(self, pos: int, multipath_index: int = 0) -> 'Descriptor': """Select a multipath entry and address index from a ranged descriptor.""" descriptor = deepcopy(self) - for pubkey in descriptor.get_pubkey_providers(): + for pubkey in descriptor.get_derivation_providers(): path = pubkey.get_deriv_path(pos, multipath_index) pubkey.deriv_path = [[step] for step in path] or None pubkey.ranged = False @@ -785,7 +803,14 @@ def parse_descriptor(desc: str) -> 'Descriptor': computed = DescriptorChecksum(desc) if computed != checksum: raise ValueError("The checksum does not match; Got {}, expected {}".format(checksum, computed)) - return _parse_descriptor(desc, _ParseDescriptorContext.TOP, 0)[0] + descriptor = _parse_descriptor(desc, _ParseDescriptorContext.TOP, 0)[0] + + # A key that appears more than once must use a single index in the + # BIP 388 Key information vector. + indexes: Dict[str, int] = {} + for pubkey in descriptor.get_derivation_providers(): + pubkey.expr_index = indexes.setdefault(pubkey.get_bip388_key_info(), len(indexes)) + return descriptor class RegisteredDescriptor: """ diff --git a/test/test_descriptor.py b/test/test_descriptor.py index 7b495ec20..acec00a98 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -174,6 +174,19 @@ def test_parse_invalid_key_expressions(self): with self.assertRaisesRegex(ValueError, "Trailing comma"): parse_descriptor(f"wsh(multi(1,{xpub}/0/*,))") + def test_bip388_key_deduplication(self): + key = "[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw" + other = "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7" + descriptor = parse_descriptor(f"wsh(multi(2,{key}/<0;1>/*,{other}/<0;1>/*,{key}/<2;3>/*))") + self.assertEqual( + descriptor.get_bip388_template(), + "wsh(multi(2,@0/<0;1>/*,@1/<0;1>/*,@0/<2;3>/*))", + ) + self.assertEqual( + [provider.get_bip388_key_info() for provider in descriptor.get_pubkey_providers()], + [key, other], + ) + def test_parse_descriptor_replace_h(self): d = "wpkh([00000001/84h/1h/0h]tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/0/0)" desc = parse_descriptor(d) @@ -224,10 +237,11 @@ def test_tr_descriptor(self): self.assertEqual(desc.pubkeys[0].pubkey, "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B") self.assertEqual(desc.pubkeys[0].deriv_path, [[0], [0]]) self.assertEqual(desc.pubkeys[0].expr_index, 0) + # The same key is used in all four leaves, so it shares one BIP 388 key index self.assertEqual(desc.subdescriptors[0].pubkeys[0].expr_index, 1) - self.assertEqual(desc.subdescriptors[1].pubkeys[0].expr_index, 2) - self.assertEqual(desc.subdescriptors[2].pubkeys[0].expr_index, 3) - self.assertEqual(desc.subdescriptors[3].pubkeys[0].expr_index, 4) + self.assertEqual(desc.subdescriptors[1].pubkeys[0].expr_index, 1) + self.assertEqual(desc.subdescriptors[2].pubkeys[0].expr_index, 1) + self.assertEqual(desc.subdescriptors[3].pubkeys[0].expr_index, 1) self.assertEqual(desc.depths, [1, 3, 3, 2]) self.assertEqual(desc.to_string_no_checksum(), d) From 925b4ac181d96fbeebaf03692f7887290cc373a1 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 14:08:48 +0200 Subject: [PATCH 07/26] descriptor: split BIP 388 placeholder checks from serialization Move the derivation path checks into _check_bip388_deriv_path() and the suffix serialization into _get_bip388_deriv_suffix(), so key expression types with a different placeholder prefix can reuse them. No behavior change. --- hwilib/descriptor.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index 3353185ac..73648a694 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -264,16 +264,34 @@ def get_bip388_placeholder(self) -> str: - All multipath specifiers must be exactly 2 items. :return: The key placeholder expression + :raises InvalidPolicyError: If the pubkey does not meet the requirements for a wallet policy as specified in BIP 388 + """ + self._check_bip388_deriv_path() + return f"@{self.expr_index}{self._get_bip388_deriv_suffix()}" + + def _check_bip388_deriv_path(self) -> None: + """ + :meta private: + + Check the BIP 388 requirements on this pubkey's derivation path. + :raises InvalidPolicyError: If the pubkey does not meet the requirements for a wallet policy as specified in BIP 388 """ if not self.ranged: raise InvalidPolicyError("BIP 388 requires all pubkeys to be ranged") if self.multipath_len > 2: raise InvalidPolicyError("BIP 388 requires all multipath specifiers to be exactly 2 elements") + + def _get_bip388_deriv_suffix(self) -> str: + """ + :meta private: + + Get the derivation path suffix for this pubkey's BIP 388 key placeholder expression. + + :return: The derivation path suffix, including the ``/*`` range marker + """ deriv_path = multipath_to_string(self.deriv_path, hardened_char="'") if self.deriv_path else "" - if self.ranged: - deriv_path += "/*" - return f"@{self.expr_index}{deriv_path}" + return deriv_path + "/*" def get_bip388_key_info(self) -> str: """ From 1cfc828e9cc38b20314bd6d643b14eab7ac607cb Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 14:09:12 +0200 Subject: [PATCH 08/26] descriptor: parse tr() internal key with _get_expr parse_pubkey() splits at the first comma, which cannot handle key expressions that themselves contain commas. No behavior change for valid descriptors. --- hwilib/descriptor.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index 73648a694..56542bc39 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -755,12 +755,15 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: if ctx != _ParseDescriptorContext.TOP: raise ValueError("Can only have tr at top level") multipath_len = None - internal_key, expr, key_expr_index = parse_pubkey(expr, key_expr_index) + internal_expr, expr = _get_expr(expr) + internal_key = PubkeyProvider.parse(internal_expr, key_expr_index) + key_expr_index += 1 if internal_key.multipath_len > 1: multipath_len = internal_key.multipath_len subscripts = [] depths = [] if expr: + expr = _get_const(expr, ",") # Path from top of the tree to what we're currently processing. # branches[i] == False: left branch in the i'th step from the top # branches[i] == true: right branch From 5c8a38a1adb3719ebd5aae192ae5deff3d2603b3 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:19:11 +0200 Subject: [PATCH 09/26] descriptor: parse Segwit Miniscript policies Registered descriptor policies may contain Miniscript expressions in P2WSH. Parse their structure so keys land in the BIP 388 key information vector and the same policy validation applies as for other descriptors. Miniscript type checking remains the responsibility of the device. --- hwilib/descriptor.py | 193 +++++++++++++++++++++++++++++++++++++++- test/test_descriptor.py | 56 ++++++++++++ 2 files changed, 247 insertions(+), 2 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index 56542bc39..359210e42 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -32,16 +32,25 @@ from enum import Enum from io import BufferedReader, BytesIO from typing import ( + Callable, Dict, List, Optional, Tuple, + Union, ) MAX_TAPROOT_NODES = 128 +_MINISCRIPT_WRAPPERS = set("acdjlnstuv") +_MINISCRIPT_KEY_FRAGMENTS = {"pk", "pk_k", "pk_h", "pkh"} +_MINISCRIPT_TIMELOCK_FRAGMENTS = {"older", "after"} +_MINISCRIPT_HASH_FRAGMENTS = {"sha256": 64, "hash256": 64, "ripemd160": 40, "hash160": 40} +_MINISCRIPT_BINARY_FRAGMENTS = {"and_v", "and_b", "and_n", "or_b", "or_c", "or_d", "or_i"} + + def PolyMod(c: int, val: int) -> int: """ :meta private: @@ -587,6 +596,54 @@ def get_bip388_template(self) -> str: return r +class MiniscriptDescriptor(Descriptor): + """ + A Miniscript expression contained in a descriptor + """ + + def __init__( + self, + wrappers: str, + name: str, + args: List[Union[str, 'PubkeyProvider', 'MiniscriptDescriptor']] + ) -> None: + """ + :param wrappers: The Miniscript wrappers applied to this fragment, without the ``:`` separator + :param name: The name of the Miniscript fragment + :param args: The fragment arguments: key expressions, nested Miniscript expressions, + and verbatim strings for numbers and hashes + """ + pubkeys = [arg for arg in args if isinstance(arg, PubkeyProvider)] + subdescriptors: List[Descriptor] = [arg for arg in args if isinstance(arg, MiniscriptDescriptor)] + super().__init__(pubkeys, subdescriptors, name) + self.wrappers = wrappers + self.args = args + + def _serialize(self, serialize_arg: Callable[[Union[str, 'PubkeyProvider', 'MiniscriptDescriptor']], str]) -> str: + prefix = f"{self.wrappers}:" if self.wrappers else "" + if not self.args: + return prefix + self.name + return "{}{}({})".format(prefix, self.name, ",".join(serialize_arg(arg) for arg in self.args)) + + def to_string_no_checksum(self, hardened_char: str = "h") -> str: + def serialize_arg(arg: Union[str, 'PubkeyProvider', 'MiniscriptDescriptor']) -> str: + if isinstance(arg, MiniscriptDescriptor): + return arg.to_string_no_checksum(hardened_char) + if isinstance(arg, PubkeyProvider): + return arg.to_string(hardened_char) + return arg + return self._serialize(serialize_arg) + + def get_bip388_template(self) -> str: + def serialize_arg(arg: Union[str, 'PubkeyProvider', 'MiniscriptDescriptor']) -> str: + if isinstance(arg, MiniscriptDescriptor): + return arg.get_bip388_template() + if isinstance(arg, PubkeyProvider): + return arg.get_bip388_placeholder() + return arg + return self._serialize(serialize_arg) + + def _get_func_expr(s: str) -> Tuple[str, str]: """ Get the function name and then the expression inside @@ -682,6 +739,133 @@ class _ParseDescriptorContext(Enum): """Within a ``tr()`` descriptor""" +class _MiniscriptContext(Enum): + """ + :meta private: + + Enum representing the script version used to interpret a Miniscript expression. + """ + + SEGWIT_V0 = 1 + """A Segwit v0 witness script""" + + +def _parse_miniscript_num(name: str, arg: str) -> int: + if not arg.isdigit(): + raise ValueError(f"{name}() argument must be a number, got {arg}") + return int(arg) + + +def _parse_miniscript( + expr: str, + key_expr_index: int, + ctx: '_MiniscriptContext', +) -> Tuple['MiniscriptDescriptor', int]: + """ + :meta private: + + Parse a Miniscript expression. Only the structure of the expression is + validated; Miniscript type checking is left to the device. + + :param expr: The Miniscript expression to parse + :param key_expr_index: The position of the next key expression within the descriptor + :param ctx: The script version used to interpret the Miniscript expression + :return: The parsed :class:`MiniscriptDescriptor` and the position of the next key expression + :raises: ValueError: if the Miniscript expression is malformed + """ + wrappers = "" + paren_idx = expr.find("(") + colon_idx = expr.find(":") + if colon_idx != -1 and (paren_idx == -1 or colon_idx < paren_idx): + wrappers = expr[:colon_idx] + expr = expr[colon_idx + 1:] + if not wrappers: + raise ValueError("Missing Miniscript wrapper before ':'") + for wrapper in wrappers: + if wrapper not in _MINISCRIPT_WRAPPERS: + raise ValueError(f"Unknown Miniscript wrapper: {wrapper}") + paren_idx = expr.find("(") + + if expr in ("0", "1"): + return MiniscriptDescriptor(wrappers, expr, []), key_expr_index + + if paren_idx == -1 or not expr.endswith(")"): + raise ValueError(f"Invalid Miniscript expression: {expr}") + name = expr[:paren_idx] + + arg_strs = [] + rest = expr[paren_idx + 1:-1] + while rest: + arg, rest = _get_expr(rest) + if not arg: + raise ValueError(f"Empty argument in {name}()") + arg_strs.append(arg) + if rest: + rest = _get_const(rest, ",") + if not rest: + raise ValueError(f"Trailing comma in {name}()") + + args: List[Union[str, 'PubkeyProvider', 'MiniscriptDescriptor']] = [] + if name in _MINISCRIPT_KEY_FRAGMENTS: + if len(arg_strs) != 1: + raise ValueError(f"{name}() takes exactly one key expression") + args.append(PubkeyProvider.parse(arg_strs[0], key_expr_index)) + key_expr_index += 1 + elif name == "multi": + if ctx != _MiniscriptContext.SEGWIT_V0: + raise ValueError("multi() is only allowed in Segwit v0 Miniscript") + if len(arg_strs) < 2: + raise ValueError("multi() takes a threshold and at least one key expression") + if len(arg_strs) - 1 > 20: + raise ValueError("multi() supports at most 20 keys") + thresh = _parse_miniscript_num(name, arg_strs[0]) + if not 1 <= thresh <= len(arg_strs) - 1: + raise ValueError("multi() threshold must be between 1 and the number of keys") + args.append(arg_strs[0]) + for arg_str in arg_strs[1:]: + args.append(PubkeyProvider.parse(arg_str, key_expr_index)) + key_expr_index += 1 + elif name in _MINISCRIPT_TIMELOCK_FRAGMENTS: + if len(arg_strs) != 1: + raise ValueError(f"{name}() takes exactly one number") + locktime = _parse_miniscript_num(name, arg_strs[0]) + if not 1 <= locktime < 2**31: + raise ValueError(f"{name}() locktime must be between 1 and 2**31 - 1") + args.append(arg_strs[0]) + elif name in _MINISCRIPT_HASH_FRAGMENTS: + if len(arg_strs) != 1: + raise ValueError(f"{name}() takes exactly one hash") + hash_len = _MINISCRIPT_HASH_FRAGMENTS[name] + try: + hash_bytes = unhexlify(arg_strs[0]) + except Exception: + raise ValueError(f"{name}() takes a {hash_len} character hex string") + if len(hash_bytes) * 2 != hash_len: + raise ValueError(f"{name}() takes a {hash_len} character hex string") + args.append(arg_strs[0]) + elif name == "andor" or name in _MINISCRIPT_BINARY_FRAGMENTS: + num_args = 3 if name == "andor" else 2 + if len(arg_strs) != num_args: + raise ValueError(f"{name}() takes exactly {num_args} Miniscript expressions") + for arg_str in arg_strs: + sub, key_expr_index = _parse_miniscript(arg_str, key_expr_index, ctx) + args.append(sub) + elif name == "thresh": + if len(arg_strs) < 2: + raise ValueError("thresh() takes a threshold and at least one Miniscript expression") + thresh = _parse_miniscript_num(name, arg_strs[0]) + if not 1 <= thresh <= len(arg_strs) - 1: + raise ValueError("thresh() threshold must be between 1 and the number of subexpressions") + args.append(arg_strs[0]) + for arg_str in arg_strs[1:]: + sub, key_expr_index = _parse_miniscript(arg_str, key_expr_index, ctx) + args.append(sub) + else: + raise ValueError(f"Unknown Miniscript fragment: {name}") + + return MiniscriptDescriptor(wrappers, name, args), key_expr_index + + def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: int) -> Tuple['Descriptor', int]: """ :meta private: @@ -695,7 +879,12 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: :return: The parsed descriptor as the first item, and the index of the next key expression as the second. :raises: ValueError: if the descriptor is malformed """ - func, expr = _get_func_expr(desc) + try: + func, expr = _get_func_expr(desc) + except ValueError: + if ctx == _ParseDescriptorContext.P2WSH: + return _parse_miniscript(desc, key_expr_index, _MiniscriptContext.SEGWIT_V0) + raise if func == "pk": pubkey, expr, key_expr_index = parse_pubkey(expr, key_expr_index) if expr: @@ -804,7 +993,7 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: if ctx == _ParseDescriptorContext.P2SH: raise ValueError("A function is needed within P2SH") elif ctx == _ParseDescriptorContext.P2WSH: - raise ValueError("A function is needed within P2WSH") + return _parse_miniscript(desc, key_expr_index, _MiniscriptContext.SEGWIT_V0) raise ValueError("{} is not a valid descriptor function".format(func)) diff --git a/test/test_descriptor.py b/test/test_descriptor.py index acec00a98..69291b1f8 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -1,6 +1,7 @@ #! /usr/bin/env python3 from hwilib.descriptor import ( + MiniscriptDescriptor, parse_descriptor, MultisigDescriptor, SHDescriptor, @@ -15,6 +16,61 @@ import unittest class TestDescriptor(unittest.TestCase): + def test_segwit_miniscript_policy(self): + key_0 = "[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw" + key_1 = "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7" + multipath = "<0;1>/*" + descriptor = ( + f"wsh(and_v(v:pk({key_0}/{multipath})," + f"or_d(pk({key_1}/{multipath}),older(12960))))" + ) + parsed = parse_descriptor(descriptor) + self.assertIsInstance(parsed, WSHDescriptor) + self.assertIsInstance(parsed.subdescriptors[0], MiniscriptDescriptor) + self.assertEqual(parsed.to_string_no_checksum(hardened_char="'"), descriptor) + self.assertEqual( + parsed.get_bip388_template(), + "wsh(and_v(v:pk(@0/<0;1>/*),or_d(pk(@1/<0;1>/*),older(12960))))", + ) + self.assertEqual( + [provider.get_bip388_key_info() for provider in parsed.get_pubkey_providers()], + [key_0, key_1], + ) + + def test_invalid_segwit_miniscript(self): + key = "[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw" + multipath = "<0;1>/*" + with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: unknown"): + parse_descriptor(f"wsh(unknown({key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: Pk"): + parse_descriptor(f"wsh(Pk({key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "Unknown Miniscript wrapper: x"): + parse_descriptor(f"wsh(x:pk({key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "Invalid Miniscript expression"): + parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),older(1)") + with self.assertRaisesRegex(ValueError, "takes exactly one number"): + parse_descriptor("wsh(older(1,2))") + with self.assertRaisesRegex(ValueError, "argument must be a number"): + parse_descriptor("wsh(older(-1))") + with self.assertRaisesRegex(ValueError, "character hex string"): + parse_descriptor("wsh(sha256(abcd))") + with self.assertRaisesRegex(ValueError, "threshold must be between"): + parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),multi(2,{key}/{multipath})))") + with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: multi_a"): + parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),multi_a(1,{key}/{multipath})))") + with self.assertRaisesRegex(ValueError, "Empty argument"): + parse_descriptor("wsh(and_v(,older(1)))") + + # A non-ranged key parses, but is not a valid BIP 388 policy. + non_ranged = parse_descriptor(f"wsh(and_v(v:pk({key}),older(1)))") + with self.assertRaisesRegex(InvalidPolicyError, "ranged"): + non_ranged.get_bip388_template() + + # Segwit v0 limits multi() to 20 keys. + keys = ",".join([f"{key}/{multipath}"] * 21) + with self.assertRaisesRegex(ValueError, "at most 20 keys"): + parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),multi(1,{keys})))") + def test_derive(self): xpub = "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B" descriptor_str = "wsh(multi(1,{0}/<0;1;2>/*,{0}/<10;11;12>/*))".format(xpub) From 6a51e26cc3bd15c790890c6d1d410f8b61be8c34 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:21:25 +0200 Subject: [PATCH 10/26] test: display Segwit Miniscript addresses --- test/test_bitbox02.py | 3 ++ test/test_coldcard.py | 3 ++ test/test_device.py | 62 ++++++++++++++++++++++++++++++++++++++ test/test_digitalbitbox.py | 1 + test/test_jade.py | 3 ++ test/test_keepkey.py | 1 + test/test_ledger.py | 3 ++ test/test_trezor.py | 1 + 8 files changed, 77 insertions(+) diff --git a/test/test_bitbox02.py b/test/test_bitbox02.py index 6dae9a907..cb8939d3d 100644 --- a/test/test_bitbox02.py +++ b/test/test_bitbox02.py @@ -19,6 +19,7 @@ TestGetKeypool, TestGetDescriptors, TestRegisterDescriptor, + TestSegwitMiniscriptDisplay, TestSignTx, ) @@ -40,6 +41,7 @@ def __init__(self, simulator): self.supports_xpub_ms_display = False self.supports_unsorted_ms = False self.supports_taproot = False + self.supports_segwit_miniscript = True self.strict_bip48 = False self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -138,6 +140,7 @@ def bitbox02_test_suite(simulator, bitcoind, interface): sorted=False, supports_multiple_policies=False, )) + suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_coldcard.py b/test/test_coldcard.py index db978e41e..74948f2b8 100755 --- a/test/test_coldcard.py +++ b/test/test_coldcard.py @@ -22,6 +22,7 @@ TestGetKeypool, TestGetDescriptors, TestRegisterDescriptor, + TestSegwitMiniscriptDisplay, TestSignMessage, TestSignTx, ) @@ -63,6 +64,7 @@ def __init__(self, simulator, is_edge=False): self.supports_xpub_ms_display = False self.supports_unsorted_ms = False self.supports_taproot = is_edge + self.supports_segwit_miniscript = is_edge self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -208,6 +210,7 @@ def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False): returns_registration=False, supports_multiple_policies=is_edge, )) + suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) if is_edge: suite.addTest(DeviceTestCase.parameterize(TestColdcardEdgeDisplayAddress, bitcoind, emulator=dev_emulator, interface=interface)) diff --git a/test/test_device.py b/test/test_device.py index 4c09c548a..641a363ae 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -33,6 +33,7 @@ def __init__(self): self.supports_xpub_ms_display = None self.supports_unsorted_ms = None self.supports_taproot = None + self.supports_segwit_miniscript = None self.strict_bip48 = None self.include_xpubs = None self.supports_device_multiple_multisig = None @@ -49,6 +50,7 @@ def start(self): assert self.supports_ms_display is not None assert self.supports_xpub_ms_display is not None assert self.supports_unsorted_ms is not None + assert self.supports_segwit_miniscript is not None assert self.strict_bip48 is not None assert self.include_xpubs is not None assert self.supports_device_multiple_multisig is not None @@ -964,3 +966,63 @@ def test_sign_multiple_registered_descriptors(self): "--registration", registrations[1], ) + + +class PolicyDisplayTestCase(DeviceTestCase): + EXTERNAL_KEY = "[1a0f5425/48h/1h/0h/2h]tpubDF23ETNjCC283QmYZtJp26GqHkSa6Yw6vPqp3UkMsPCvBzRC4dMQzE1U3WwKsFsx3apUkQA4JHQDSmcC3N1yhE2gF1aKJA1CiVtNyA9Rv4H" + + def _get_account_key(self, account_path): + xpub = self.do_command( + self.dev_args + ["getxpub", account_path] + )["xpub"] + return f"[{self.emulator.fingerprint}{account_path[1:]}]{xpub}" + + def _test_display_address(self, name, descriptor, expected_template): + address_index = 7 + multipath_index = 1 + expected_address = self.rpc.deriveaddresses( + AddChecksum(descriptor), [address_index, address_index] + )[multipath_index][0] + + registration = self.do_command(self.dev_args + [ + "registerdescriptor", + name, + descriptor, + ]) + self.assertNotIn("error", registration) + registered = RegisteredDescriptor.deserialize(registration["registration"]) + self.assertEqual( + registered.descriptor.get_bip388_template(), + expected_template, + ) + + result = self.do_command(self.dev_args + [ + "displayaddress", + "--index", str(address_index), + "--multipath-index", str(multipath_index), + "--registration", registration["registration"], + ]) + self.assertNotIn("error", result) + self.assertEqual( + bech32.decode("bcrt", expected_address), + bech32.decode("tb", result["address"]), + ) + self.assertEqual(result["index"], address_index) + self.assertEqual(result["multipath_index"], multipath_index) + +class TestSegwitMiniscriptDisplay(PolicyDisplayTestCase): + def setUp(self): + if not self.emulator.supports_segwit_miniscript: + self.skipTest("device does not support Segwit Miniscript policies") + super().setUp() + + def test_segwit_miniscript(self): + device_key = self._get_account_key("m/48h/1h/0h/2h") + descriptor = ( + f"wsh(and_v(v:pk({device_key}/<0;1>/*),older(12960)))" + ) + self._test_display_address( + f"Mini{self.emulator.fingerprint}", + descriptor, + "wsh(and_v(v:pk(@0/<0;1>/*),older(12960)))", + ) diff --git a/test/test_digitalbitbox.py b/test/test_digitalbitbox.py index 9fc41ed3f..d0f1ddfa9 100755 --- a/test/test_digitalbitbox.py +++ b/test/test_digitalbitbox.py @@ -39,6 +39,7 @@ def __init__(self, simulator): self.supports_xpub_ms_display = False self.supports_unsorted_ms = False self.supports_taproot = False + self.supports_segwit_miniscript = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_jade.py b/test/test_jade.py index 741892e80..aa658c689 100755 --- a/test/test_jade.py +++ b/test/test_jade.py @@ -19,6 +19,7 @@ TestGetKeypool, TestGetDescriptors, TestRegisterDescriptor, + TestSegwitMiniscriptDisplay, TestSignMessage, TestSignTx, ) @@ -50,6 +51,7 @@ def __init__(self, jade_qemu_emulator_path): self.supports_xpub_ms_display = False self.supports_unsorted_ms = False self.supports_taproot = False + self.supports_segwit_miniscript = True self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -251,6 +253,7 @@ def jade_test_suite(emulator, bitcoind, interface): suite.addTest(DeviceTestCase.parameterize(TestSignMessage, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestJadeSignTx, bitcoind, emulator=dev_emulator, interface=interface, signtx_cases=signtx_cases)) suite.addTest(DeviceTestCase.parameterize(TestRegisterDescriptor, bitcoind, emulator=dev_emulator, interface=interface, returns_registration=False)) + suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_keepkey.py b/test/test_keepkey.py index ff9cf84c0..7676a0029 100755 --- a/test/test_keepkey.py +++ b/test/test_keepkey.py @@ -61,6 +61,7 @@ def __init__(self, path): self.supports_xpub_ms_display = False self.supports_unsorted_ms = False self.supports_taproot = False + self.supports_segwit_miniscript = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_ledger.py b/test/test_ledger.py index 0d783cb44..1972d71ea 100755 --- a/test/test_ledger.py +++ b/test/test_ledger.py @@ -18,6 +18,7 @@ TestGetKeypool, TestGetDescriptors, TestRegisterDescriptor, + TestSegwitMiniscriptDisplay, TestSignMessage, TestSignTx, ) @@ -44,6 +45,7 @@ def __init__(self, path, legacy=False): self.supports_xpub_ms_display = False # Legacy does not multisig address display; tests not updated for new app self.supports_unsorted_ms = False # Legacy does not support unsorted multisig; tests not updated for new app self.supports_taproot = not legacy # Legacy does not support Taproot + self.supports_segwit_miniscript = not legacy self.strict_bip48 = True self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -193,6 +195,7 @@ def ledger_test_suite(emulator, bitcoind, interface, legacy=False): suite.addTest(DeviceTestCase.parameterize(TestSignTx, bitcoind, emulator=dev_emulator, interface=interface, signtx_cases=signtx_cases)) if not legacy: suite.addTest(DeviceTestCase.parameterize(TestRegisterDescriptor, bitcoind, emulator=dev_emulator, interface=interface, returns_registration=True)) + suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_trezor.py b/test/test_trezor.py index b61c1f00a..d735820a7 100755 --- a/test/test_trezor.py +++ b/test/test_trezor.py @@ -60,6 +60,7 @@ def __init__(self, path, model): self.supports_xpub_ms_display = True self.supports_unsorted_ms = True self.supports_taproot = True + self.supports_segwit_miniscript = False self.strict_bip48 = True self.include_xpubs = False self.supports_device_multiple_multisig = True From 6f9d5bcd701fcf6169a42b9a09ae46378de5e002 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:23:33 +0200 Subject: [PATCH 11/26] descriptor: parse tapscript Miniscript policies --- hwilib/descriptor.py | 32 +++++++++--- test/test_descriptor.py | 108 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 132 insertions(+), 8 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index 359210e42..f078b45dd 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -46,6 +46,7 @@ _MINISCRIPT_WRAPPERS = set("acdjlnstuv") _MINISCRIPT_KEY_FRAGMENTS = {"pk", "pk_k", "pk_h", "pkh"} +_MINISCRIPT_TAPSCRIPT_MULTI_FRAGMENTS = {"multi_a", "sortedmulti_a"} _MINISCRIPT_TIMELOCK_FRAGMENTS = {"older", "after"} _MINISCRIPT_HASH_FRAGMENTS = {"sha256": 64, "hash256": 64, "ripemd160": 40, "hash160": 40} _MINISCRIPT_BINARY_FRAGMENTS = {"and_v", "and_b", "and_n", "or_b", "or_c", "or_d", "or_i"} @@ -735,10 +736,6 @@ class _ParseDescriptorContext(Enum): P2WSH = 3 """Within a ``wsh()`` descriptor""" - P2TR = 4 - """Within a ``tr()`` descriptor""" - - class _MiniscriptContext(Enum): """ :meta private: @@ -749,6 +746,9 @@ class _MiniscriptContext(Enum): SEGWIT_V0 = 1 """A Segwit v0 witness script""" + TAPSCRIPT = 2 + """A Taproot leaf script""" + def _parse_miniscript_num(name: str, arg: str) -> int: if not arg.isdigit(): @@ -825,6 +825,20 @@ def _parse_miniscript( for arg_str in arg_strs[1:]: args.append(PubkeyProvider.parse(arg_str, key_expr_index)) key_expr_index += 1 + elif name in _MINISCRIPT_TAPSCRIPT_MULTI_FRAGMENTS: + if ctx != _MiniscriptContext.TAPSCRIPT: + raise ValueError(f"{name}() is only allowed in tapscript Miniscript") + if len(arg_strs) < 2: + raise ValueError(f"{name}() takes a threshold and at least one key expression") + if len(arg_strs) - 1 > 999: + raise ValueError(f"{name}() supports at most 999 keys") + thresh = _parse_miniscript_num(name, arg_strs[0]) + if not 1 <= thresh <= len(arg_strs) - 1: + raise ValueError(f"{name}() threshold must be between 1 and the number of keys") + args.append(arg_strs[0]) + for arg_str in arg_strs[1:]: + args.append(PubkeyProvider.parse(arg_str, key_expr_index)) + key_expr_index += 1 elif name in _MINISCRIPT_TIMELOCK_FRAGMENTS: if len(arg_strs) != 1: raise ValueError(f"{name}() takes exactly one number") @@ -949,7 +963,7 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: key_expr_index += 1 if internal_key.multipath_len > 1: multipath_len = internal_key.multipath_len - subscripts = [] + subscripts: List[Descriptor] = [] depths = [] if expr: expr = _get_const(expr, ",") @@ -969,8 +983,12 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: raise ValueError("tr() supports at most {MAX_TAPROOT_NODES} nesting levels") # Process script expression sarg, expr = _get_expr(expr) - subdesc, key_expr_index = _parse_descriptor(sarg, _ParseDescriptorContext.P2TR, key_expr_index) - for pub in subdesc.pubkeys: + subdesc, key_expr_index = _parse_miniscript( + sarg, + key_expr_index, + _MiniscriptContext.TAPSCRIPT, + ) + for pub in subdesc.get_derivation_providers(): if pub.multipath_len > 1: if multipath_len is None: multipath_len = pub.multipath_len diff --git a/test/test_descriptor.py b/test/test_descriptor.py index 69291b1f8..d8c23a98d 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -13,6 +13,7 @@ from hwilib.common import AddressType from hwilib.errors import InvalidPolicyError +import re import unittest class TestDescriptor(unittest.TestCase): @@ -56,7 +57,7 @@ def test_invalid_segwit_miniscript(self): parse_descriptor("wsh(sha256(abcd))") with self.assertRaisesRegex(ValueError, "threshold must be between"): parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),multi(2,{key}/{multipath})))") - with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: multi_a"): + with self.assertRaisesRegex(ValueError, "only allowed in tapscript"): parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),multi_a(1,{key}/{multipath})))") with self.assertRaisesRegex(ValueError, "Empty argument"): parse_descriptor("wsh(and_v(,older(1)))") @@ -71,6 +72,111 @@ def test_invalid_segwit_miniscript(self): with self.assertRaisesRegex(ValueError, "at most 20 keys"): parse_descriptor(f"wsh(and_v(v:pk({key}/{multipath}),multi(1,{keys})))") + def test_tapscript_miniscript_policy(self): + key_0 = "[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw" + key_1 = "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7" + recovery_key = "[6738736c/86'/0'/0']xpub6CryUDWPS28eR2cDyojB8G354izmx294BdjeSvH469Ty3o2E6Tq5VjBJCn8rWBgesvTJnyXNAJ3QpLFGuNwqFXNt3gn612raffLWfdHNkYL" + multipath = "<0;1>/*" + descriptor = ( + f"tr({recovery_key}/{multipath},{{" + f"multi_a(2,{key_0}/{multipath},{key_1}/{multipath})," + f"{{andor(pk({key_0}/{multipath}),older(1000),1)," + f"thresh(2,pk({key_1}/{multipath}),s:pk({recovery_key}/{multipath})," + f"snl:sha256(6c60f404f8167a38fc70eaf8aa17ac351023bef86bcb9d1086a19afe95bd5333))}}}})" + ) + parsed = parse_descriptor(descriptor) + self.assertIsInstance(parsed, TRDescriptor) + for subdescriptor in parsed.subdescriptors: + self.assertIsInstance(subdescriptor, MiniscriptDescriptor) + self.assertEqual(parsed.to_string_no_checksum(hardened_char="'"), descriptor) + self.assertEqual( + parsed.get_bip388_template(), + "tr(@0/<0;1>/*,{multi_a(2,@1/<0;1>/*,@2/<0;1>/*)," + "{andor(pk(@1/<0;1>/*),older(1000),1)," + "thresh(2,pk(@2/<0;1>/*),s:pk(@0/<0;1>/*)," + "snl:sha256(6c60f404f8167a38fc70eaf8aa17ac351023bef86bcb9d1086a19afe95bd5333))}})", + ) + self.assertEqual( + [provider.get_bip388_key_info() for provider in parsed.get_pubkey_providers()], + [recovery_key, key_0, key_1], + ) + + def test_invalid_tapscript_miniscript(self): + key = "[6738736c/86'/0'/0']xpub6CryUDWPS28eR2cDyojB8G354izmx294BdjeSvH469Ty3o2E6Tq5VjBJCn8rWBgesvTJnyXNAJ3QpLFGuNwqFXNt3gn612raffLWfdHNkYL" + multipath = "<0;1>/*" + with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: unknown"): + parse_descriptor(f"tr({key}/{multipath},unknown({key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: Pk"): + parse_descriptor(f"tr({key}/{multipath},Pk({key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "Invalid Miniscript expression"): + parse_descriptor(f"tr({key}/{multipath},12345)") + with self.assertRaisesRegex(ValueError, "Unknown Miniscript wrapper: x"): + parse_descriptor(f"tr({key}/{multipath},x:pk({key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "only allowed in Segwit v0"): + parse_descriptor(f"tr({key}/{multipath},multi(1,{key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "threshold must be between"): + parse_descriptor(f"tr({key}/{multipath},multi_a(3,{key}/{multipath},{key}/{multipath}))") + with self.assertRaisesRegex(ValueError, "Mismatched multipath"): + parse_descriptor(f"tr({key}/{multipath},pk({key}/<0;1;2>/*))") + with self.assertRaisesRegex(ValueError, "Invalid Miniscript expression"): + parse_descriptor(f"tr({key}/{multipath},)") + + non_ranged = parse_descriptor(f"tr({key}/{multipath},and_v(v:pk({key}),older(1)))") + with self.assertRaisesRegex(InvalidPolicyError, "ranged"): + non_ranged.get_bip388_template() + + xonly = "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9" + keys = ",".join([xonly] * 1000) + with self.assertRaisesRegex(ValueError, "at most 999 keys"): + parse_descriptor(f"tr({key}/{multipath},multi_a(1,{keys}))") + + def test_bip379_tapscript_corpus(self): + expressions = [ + "andor(and_b(multi_a(2,A,B,C),aj:multi_a(2,D,E,F)),multi_a(2,G,I,J),multi_a(2,K,L,M))", + "thresh(1,or_d(multi_a(2,A,B,C),pk(D)),s:pk(E),s:pk(F))", + "and_v(and_v(or_c(multi_a(2,A,B,C),v:multi_a(2,D,E,F)),v:after(1)),after(500000001))", + "andor(pk(A),older(4194305),pk(B))", + "and_n(pk(A),pk(B))", + "and_b(after(1),a:or_d(or_i(c:pk_h(A),0),multi_a(2,B,C,D)))", + "and_b(after(1),a:and_b(after(1),ac:pk_k(A)))", + "and_b(after(1),a:and_b(c:pk_h(A),an:after(500000001)))", + "and_v(or_c(sha256(926a54995ca48600920a19bf7bc502ca5f2f7d07e6f804c4f00ebf0325084dbc),v:after(1)),1)", + "u:pk(A)", + "l:pk(A)", + "pkh(A)", + "hash160(4355a46b19d348dc2f57c046f8ef63d4538ebb93)", + "ripemd160(4355a46b19d348dc2f57c046f8ef63d4538ebb93)", + "hash256(926a54995ca48600920a19bf7bc502ca5f2f7d07e6f804c4f00ebf0325084dbc)", + ] + internal_key = "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0" + for expression in expressions: + substituted = re.sub( + r"(?/*,{{sortedmulti_a(1,{key_0}/<2;3>/*,{key_1}/<0;1>/*)," + f"or_b(pk({key_2}/<0;1>/*),s:pk({key_3}/<0;1>/*))}})" + ) + self.assertEqual( + descriptor.get_bip388_template(), + "tr(@0/<0;1>/*,{sortedmulti_a(1,@0/<2;3>/*,@1/<0;1>/*)," + "or_b(pk(@2/<0;1>/*),s:pk(@3/<0;1>/*))})", + ) + self.assertEqual( + [provider.get_bip388_key_info() for provider in descriptor.get_pubkey_providers()], + [key_0, key_1, key_2, key_3], + ) + def test_derive(self): xpub = "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B" descriptor_str = "wsh(multi(1,{0}/<0;1;2>/*,{0}/<10;11;12>/*))".format(xpub) From fa04228b76b140f37341f03dc0d79cac8e8ea1ee Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:24:17 +0200 Subject: [PATCH 12/26] displayaddress: require registration for taproot script trees --- hwilib/commands.py | 2 ++ test/test_descriptor.py | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/hwilib/commands.py b/hwilib/commands.py index 7371a5356..eabba4f5d 100644 --- a/hwilib/commands.py +++ b/hwilib/commands.py @@ -511,6 +511,8 @@ def displayaddress( return {"address": client.display_multisig_address(addr_type, descriptor)} is_wpkh = isinstance(descriptor, WPKHDescriptor) if isinstance(descriptor, PKHDescriptor) or is_wpkh or isinstance(descriptor, TRDescriptor): + if descriptor.subdescriptors: + raise BadArgumentError("tr() descriptors with a script tree require a registered BIP 388 policy; use --registration") pubkey = descriptor.pubkeys[0] if pubkey.origin is None: raise BadArgumentError(f"Descriptor missing origin info: {desc}") diff --git a/test/test_descriptor.py b/test/test_descriptor.py index d8c23a98d..cce27602b 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -1,5 +1,6 @@ #! /usr/bin/env python3 +from hwilib.commands import displayaddress from hwilib.descriptor import ( MiniscriptDescriptor, parse_descriptor, @@ -11,7 +12,7 @@ WSHDescriptor, ) from hwilib.common import AddressType -from hwilib.errors import InvalidPolicyError +from hwilib.errors import BadArgumentError, InvalidPolicyError import re import unittest @@ -177,6 +178,12 @@ def test_bip388_taproot_miniscript_vector(self): [key_0, key_1, key_2, key_3], ) + def test_taproot_script_tree_requires_registration(self): + key = "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9" + descriptor = f"tr({key},pk({key}))" + with self.assertRaisesRegex(BadArgumentError, "registered BIP 388 policy"): + displayaddress(object(), desc=descriptor) + def test_derive(self): xpub = "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B" descriptor_str = "wsh(multi(1,{0}/<0;1;2>/*,{0}/<10;11;12>/*))".format(xpub) From 271ff364e5422b0132250f77381fb2c959c62903 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:24:55 +0200 Subject: [PATCH 13/26] test: display taproot Miniscript addresses --- test/test_bitbox02.py | 3 +++ test/test_coldcard.py | 3 +++ test/test_device.py | 20 ++++++++++++++++++++ test/test_digitalbitbox.py | 1 + test/test_jade.py | 1 + test/test_keepkey.py | 1 + test/test_ledger.py | 3 +++ test/test_trezor.py | 1 + 8 files changed, 33 insertions(+) diff --git a/test/test_bitbox02.py b/test/test_bitbox02.py index cb8939d3d..ead981714 100644 --- a/test/test_bitbox02.py +++ b/test/test_bitbox02.py @@ -20,6 +20,7 @@ TestGetDescriptors, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, + TestTaprootMiniscriptDisplay, TestSignTx, ) @@ -42,6 +43,7 @@ def __init__(self, simulator): self.supports_unsorted_ms = False self.supports_taproot = False self.supports_segwit_miniscript = True + self.supports_taproot_miniscript = True self.strict_bip48 = False self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -141,6 +143,7 @@ def bitbox02_test_suite(simulator, bitcoind, interface): supports_multiple_policies=False, )) suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_coldcard.py b/test/test_coldcard.py index 74948f2b8..0651972f6 100755 --- a/test/test_coldcard.py +++ b/test/test_coldcard.py @@ -23,6 +23,7 @@ TestGetDescriptors, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, + TestTaprootMiniscriptDisplay, TestSignMessage, TestSignTx, ) @@ -65,6 +66,7 @@ def __init__(self, simulator, is_edge=False): self.supports_unsorted_ms = False self.supports_taproot = is_edge self.supports_segwit_miniscript = is_edge + self.supports_taproot_miniscript = is_edge self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -213,6 +215,7 @@ def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False): suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) if is_edge: suite.addTest(DeviceTestCase.parameterize(TestColdcardEdgeDisplayAddress, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_device.py b/test/test_device.py index 641a363ae..8860dc6b1 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -34,6 +34,7 @@ def __init__(self): self.supports_unsorted_ms = None self.supports_taproot = None self.supports_segwit_miniscript = None + self.supports_taproot_miniscript = None self.strict_bip48 = None self.include_xpubs = None self.supports_device_multiple_multisig = None @@ -51,6 +52,7 @@ def start(self): assert self.supports_xpub_ms_display is not None assert self.supports_unsorted_ms is not None assert self.supports_segwit_miniscript is not None + assert self.supports_taproot_miniscript is not None assert self.strict_bip48 is not None assert self.include_xpubs is not None assert self.supports_device_multiple_multisig is not None @@ -1026,3 +1028,21 @@ def test_segwit_miniscript(self): descriptor, "wsh(and_v(v:pk(@0/<0;1>/*),older(12960)))", ) + +class TestTaprootMiniscriptDisplay(PolicyDisplayTestCase): + def setUp(self): + if not self.emulator.supports_taproot_miniscript: + self.skipTest("device does not support tapscript Miniscript policies") + super().setUp() + + def test_taproot_miniscript(self): + device_key = self._get_account_key("m/86h/1h/0h") + descriptor = ( + f"tr({device_key}/<0;1>/*," + f"and_v(v:pk({self.EXTERNAL_KEY}/<0;1>/*),older(12960)))" + ) + self._test_display_address( + f"TapMini{self.emulator.fingerprint}", + descriptor, + "tr(@0/<0;1>/*,and_v(v:pk(@1/<0;1>/*),older(12960)))", + ) diff --git a/test/test_digitalbitbox.py b/test/test_digitalbitbox.py index d0f1ddfa9..d9f495de5 100755 --- a/test/test_digitalbitbox.py +++ b/test/test_digitalbitbox.py @@ -40,6 +40,7 @@ def __init__(self, simulator): self.supports_unsorted_ms = False self.supports_taproot = False self.supports_segwit_miniscript = False + self.supports_taproot_miniscript = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_jade.py b/test/test_jade.py index aa658c689..5664b1ebb 100755 --- a/test/test_jade.py +++ b/test/test_jade.py @@ -52,6 +52,7 @@ def __init__(self, jade_qemu_emulator_path): self.supports_unsorted_ms = False self.supports_taproot = False self.supports_segwit_miniscript = True + self.supports_taproot_miniscript = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_keepkey.py b/test/test_keepkey.py index 7676a0029..37f373aca 100755 --- a/test/test_keepkey.py +++ b/test/test_keepkey.py @@ -62,6 +62,7 @@ def __init__(self, path): self.supports_unsorted_ms = False self.supports_taproot = False self.supports_segwit_miniscript = False + self.supports_taproot_miniscript = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_ledger.py b/test/test_ledger.py index 1972d71ea..4eeca64ba 100755 --- a/test/test_ledger.py +++ b/test/test_ledger.py @@ -19,6 +19,7 @@ TestGetDescriptors, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, + TestTaprootMiniscriptDisplay, TestSignMessage, TestSignTx, ) @@ -46,6 +47,7 @@ def __init__(self, path, legacy=False): self.supports_unsorted_ms = False # Legacy does not support unsorted multisig; tests not updated for new app self.supports_taproot = not legacy # Legacy does not support Taproot self.supports_segwit_miniscript = not legacy + self.supports_taproot_miniscript = not legacy self.strict_bip48 = True self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -196,6 +198,7 @@ def ledger_test_suite(emulator, bitcoind, interface, legacy=False): if not legacy: suite.addTest(DeviceTestCase.parameterize(TestRegisterDescriptor, bitcoind, emulator=dev_emulator, interface=interface, returns_registration=True)) suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_trezor.py b/test/test_trezor.py index d735820a7..a4abdbc9e 100755 --- a/test/test_trezor.py +++ b/test/test_trezor.py @@ -61,6 +61,7 @@ def __init__(self, path, model): self.supports_unsorted_ms = True self.supports_taproot = True self.supports_segwit_miniscript = False + self.supports_taproot_miniscript = False self.strict_bip48 = True self.include_xpubs = False self.supports_device_multiple_multisig = True From ca300b30d4322bb84001541df2cab4680b93306c Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 14:29:00 +0200 Subject: [PATCH 14/26] descriptor: support musig() aggregate keys Parse musig() key expressions as specified in BIP 390, checked against its test vectors. Participants may carry derivation paths only when the aggregate key has none; in that case derivation happens on the participant keys before aggregation. Aggregate key derivation must be unhardened and requires extended public key participants. The aggregate key carries the derivation path suffix, so derivation-related callers use the new get_derivation_providers(), while get_pubkey_providers() returns the participant keys, matching the BIP 388 Key information vector. BIP 388 does not allow derivation before aggregation, so get_bip388_placeholder() rejects it. --- hwilib/descriptor.py | 152 +++++++++++++++++++++++++++++++++++++--- test/test_descriptor.py | 71 +++++++++++++++++++ 2 files changed, 212 insertions(+), 11 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index f078b45dd..c787d7531 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -13,6 +13,7 @@ from .key import ( ExtendedKey, KeyOriginInfo, + is_hardened, parse_multipath, multipath_to_string, path_to_string, @@ -321,6 +322,100 @@ def __lt__(self, other: 'PubkeyProvider') -> bool: return self.pubkey < other.pubkey +class MusigPubkeyProvider(PubkeyProvider): + """ + A ``musig()`` aggregate key expression with a shared derivation path, as specified in BIP 390. + """ + + def __init__( + self, + participants: List['PubkeyProvider'], + deriv_path: Optional[List[List[int]]], + ranged: bool, + ) -> None: + r""" + :param participants: The :class:`PubkeyProvider`\ s aggregated by this ``musig()`` expression + :param deriv_path: Derivation path for the aggregate key + :param ranged: Whether the aggregate key is ranged + """ + super().__init__(None, "", deriv_path, participants[0].expr_index, ranged) + self.participants = participants + + @classmethod + def parse_musig(cls, s: str, key_expr_index: int) -> Tuple['MusigPubkeyProvider', int]: + """ + Deserialize a ``musig()`` key expression from the string into a ``MusigPubkeyProvider``. + + :param s: String containing the ``musig()`` key expression + :param key_expr_index: The position of the first participant key within the descriptor + :return: A new ``MusigPubkeyProvider`` and the position of the next key expression + :raises: ValueError: if the ``musig()`` key expression is malformed + """ + func, expr = _get_func_expr(s) + if func != "musig": + raise ValueError(f"Expected musig() key expression, got {func}()") + + suffix = s[s.rindex(")") + 1:] + deriv_path = None + ranged = False + if suffix: + if not suffix.startswith("/"): + raise ValueError("MuSig derivation path must begin with '/'") + deriv_path, ranged = _parse_ranged_deriv_path(suffix[1:]) + + for path in deriv_path or []: + for step in path: + if is_hardened(step): + raise ValueError("musig() cannot have hardened derivation steps") + + participants = [] + while expr: + if expr.startswith("musig("): + raise ValueError("musig() key expressions cannot be nested") + participant, expr, key_expr_index = parse_pubkey(expr, key_expr_index) + participants.append(participant) + if len(participants) < 2: + raise ValueError("musig() requires at least two participants") + if deriv_path is not None or ranged: + for participant in participants: + if participant.extkey is None: + raise ValueError("musig() derivation requires extended public key participants") + if participant.ranged or participant.multipath_len > 1: + raise ValueError("musig() participants cannot be ranged or multipath when musig() itself has a derivation path") + return cls(participants, deriv_path, ranged), key_expr_index + + def to_string(self, hardened_char: str = "h") -> str: + """ + Serialize the ``musig()`` expression to a string to be used in a descriptor + + :return: The ``musig()`` expression as a string + """ + participants = ",".join(p.to_string(hardened_char) for p in self.participants) + result = f"musig({participants})" + if self.deriv_path: + result += multipath_to_string(self.deriv_path, hardened_char) + if self.ranged: + result += "/*" + return result + + def get_bip388_placeholder(self) -> str: + """ + Get the key placeholder expression for this ``musig()`` expression to be used in BIP 388 Wallet Policies. + + :return: The key placeholder expression + :raises InvalidPolicyError: If the aggregate key does not meet the requirements for a wallet policy as specified in BIP 388 + """ + self._check_bip388_deriv_path() + for participant in self.participants: + if participant.deriv_path is not None or participant.ranged: + raise InvalidPolicyError("BIP 388 requires all derivation to follow musig() aggregation") + participants = ",".join(f"@{p.expr_index}" for p in self.participants) + return f"musig({participants}){self._get_bip388_deriv_suffix()}" + + def get_pubkey_bytes(self, pos: int, multipath_pos: int = 0) -> bytes: + raise NotImplementedError("HWI cannot expand musig() aggregate keys") + + class Descriptor(object): r""" An abstract class for Descriptors themselves. @@ -389,28 +484,40 @@ def get_bip388_template(self) -> str: def get_pubkey_providers(self) -> list['PubkeyProvider']: r""" Get the individual pubkey expressions contained in this descriptor, in the order in - which they first appear in the descriptor string. A key that appears more than once - is returned only once, matching the BIP 388 Key information vector, so these can be - used with :func:`get_bip388_template` to get a full BIP 388 Wallet Policy for this - descriptor. + which they first appear in the descriptor string. A ``musig()`` aggregate key is + replaced by its participant keys, and a key that appears more than once is returned + only once, matching the BIP 388 Key information vector, so these can be used with + :func:`get_bip388_template` to get a full BIP 388 Wallet Policy for this descriptor. :return: List of :class:`PubkeyProvider`\ s """ out: Dict[str, 'PubkeyProvider'] = {} for pubkey in self.get_derivation_providers(): - out.setdefault(pubkey.get_bip388_key_info(), pubkey) + participants = pubkey.participants if isinstance(pubkey, MusigPubkeyProvider) else [pubkey] + for participant in participants: + out.setdefault(participant.get_bip388_key_info(), participant) return list(out.values()) def get_derivation_providers(self) -> list['PubkeyProvider']: r""" Get the key expressions contained in this descriptor whose derivation path suffixes belong to the descriptor, in the same order that they appear in the descriptor - string. Unlike :func:`get_pubkey_providers`, a key that appears more than once is - returned once for each appearance. + string, including keys that appear more than once. Unlike + :func:`get_pubkey_providers`, a ``musig()`` aggregate key with its own derivation + path suffix is returned as a single :class:`MusigPubkeyProvider`, since the suffix + applies to the aggregate key. Participant keys are returned for a ``musig()`` + without a derivation path suffix, where any derivation happens on the participant + keys before aggregation. :return: List of :class:`PubkeyProvider`\ s """ - out = list(self.pubkeys) + out: list['PubkeyProvider'] = [] + for pubkey in self.pubkeys: + if isinstance(pubkey, MusigPubkeyProvider) and pubkey.deriv_path is None and not pubkey.ranged: + # Without an aggregate derivation path, derivation happens on the participant keys + out.extend(pubkey.participants) + else: + out.append(pubkey) for subdescriptor in self.subdescriptors: out.extend(subdescriptor.get_derivation_providers()) return out @@ -880,6 +987,22 @@ def _parse_miniscript( return MiniscriptDescriptor(wrappers, name, args), key_expr_index +def _parse_key_expr(expr: str, key_expr_index: int) -> Tuple['PubkeyProvider', int]: + """ + :meta private: + + Parse a single key expression, which may be a ``musig()`` aggregate key. + + :param expr: The key expression to parse + :param key_expr_index: The position of the key within the descriptor + :return: The parsed :class:`PubkeyProvider` and the position of the next key expression + :raises: ValueError: if the key expression is malformed + """ + if expr.startswith("musig("): + return MusigPubkeyProvider.parse_musig(expr, key_expr_index) + return PubkeyProvider.parse(expr, key_expr_index), key_expr_index + 1 + + def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: int) -> Tuple['Descriptor', int]: """ :meta private: @@ -900,6 +1023,8 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: return _parse_miniscript(desc, key_expr_index, _MiniscriptContext.SEGWIT_V0) raise if func == "pk": + if expr.startswith("musig("): + raise ValueError("musig() is only allowed in tr() descriptors") pubkey, expr, key_expr_index = parse_pubkey(expr, key_expr_index) if expr: raise ValueError("more than one pubkey in pk descriptor") @@ -907,6 +1032,8 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: if func == "pkh": if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH or ctx == _ParseDescriptorContext.P2WSH): raise ValueError("Can only have pkh at top level, in sh(), or in wsh()") + if expr.startswith("musig("): + raise ValueError("musig() is only allowed in tr() descriptors") pubkey, expr, key_expr_index = parse_pubkey(expr, key_expr_index) if expr: raise ValueError("More than one pubkey in pkh descriptor") @@ -940,6 +1067,8 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: if func == "wpkh": if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH): raise ValueError("Can only have wpkh() at top level or inside sh()") + if expr.startswith("musig("): + raise ValueError("musig() is only allowed in tr() descriptors") pubkey, expr, key_expr_index = parse_pubkey(expr, key_expr_index) if expr: raise ValueError("More than one pubkey in pkh descriptor") @@ -959,8 +1088,7 @@ def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext', key_expr_index: raise ValueError("Can only have tr at top level") multipath_len = None internal_expr, expr = _get_expr(expr) - internal_key = PubkeyProvider.parse(internal_expr, key_expr_index) - key_expr_index += 1 + internal_key, key_expr_index = _parse_key_expr(internal_expr, key_expr_index) if internal_key.multipath_len > 1: multipath_len = internal_key.multipath_len subscripts: List[Descriptor] = [] @@ -1037,7 +1165,9 @@ def parse_descriptor(desc: str) -> 'Descriptor': # BIP 388 Key information vector. indexes: Dict[str, int] = {} for pubkey in descriptor.get_derivation_providers(): - pubkey.expr_index = indexes.setdefault(pubkey.get_bip388_key_info(), len(indexes)) + participants = pubkey.participants if isinstance(pubkey, MusigPubkeyProvider) else [pubkey] + for participant in participants: + participant.expr_index = indexes.setdefault(participant.get_bip388_key_info(), len(indexes)) return descriptor class RegisteredDescriptor: diff --git a/test/test_descriptor.py b/test/test_descriptor.py index cce27602b..a79aafa54 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -356,6 +356,67 @@ def test_bip388_key_deduplication(self): [key, other], ) + def test_parse_invalid_musig(self): + key_0 = "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B" + key_1 = "tpubDFHiBJDeNvqPWNJbzzxqDVXmJZoNn2GEtoVcFhMjXipQiorGUmps3e5ieDGbRrBPTFTh9TXEKJCwbAGW9uZnfrVPbMxxbFohuFzfT6VThty" + with self.assertRaisesRegex(ValueError, "at least two participants"): + parse_descriptor(f"tr(musig({key_0}))") + with self.assertRaisesRegex(ValueError, "Empty key expression"): + parse_descriptor(f"tr(musig({key_0},,{key_1}))") + with self.assertRaisesRegex(ValueError, "Trailing comma"): + parse_descriptor(f"tr(musig({key_0},{key_1},))") + with self.assertRaisesRegex(ValueError, "cannot be nested"): + parse_descriptor(f"tr(musig(musig({key_0},{key_1}),{key_1}))") + with self.assertRaisesRegex(ValueError, "Invalid ranged derivation path"): + parse_descriptor(f"tr(musig({key_0},{key_1})/0*)") + + def test_parse_musig_bip390(self): + # Test vectors from BIP 390 + hex_1 = "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9" + hex_2 = "03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659" + hex_3 = "023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66" + xpub_a = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL" + xpub_b = "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y" + valid = [ + f"tr(musig({hex_1},{hex_2},{hex_3}))", + f"tr(musig({xpub_a}/1,{xpub_a}/1)/2)", + # Participants may be ranged when the aggregate key is not + f"tr(musig({xpub_a}/*,{xpub_b}/*))", + ] + for descriptor in valid: + self.assertEqual(parse_descriptor(descriptor).to_string_no_checksum(), descriptor) + + # Derivation happens on the participant keys when the aggregate key has no path + self.assertEqual( + parse_descriptor(f"tr(musig({xpub_a}/*,{xpub_b}/*))").derive(3).to_string_no_checksum(), + f"tr(musig({xpub_a}/3,{xpub_b}/3))", + ) + + with self.assertRaisesRegex(ValueError, "only allowed in tr"): + parse_descriptor(f"pk(musig({hex_1},{hex_2},{hex_3}))") + with self.assertRaisesRegex(ValueError, "only allowed in tr"): + parse_descriptor(f"pkh(musig({hex_1},{hex_2},{hex_3}))") + with self.assertRaisesRegex(ValueError, "only allowed in tr"): + parse_descriptor(f"wpkh(musig({hex_1},{hex_2},{hex_3}))") + with self.assertRaisesRegex(ValueError, "only allowed in tr"): + parse_descriptor(f"wsh(pk(musig({hex_1},{hex_2},{hex_3})))") + with self.assertRaisesRegex(ValueError, "Unknown Miniscript fragment: musig"): + parse_descriptor(f"wsh(musig({hex_1},{hex_2},{hex_3}))") + with self.assertRaisesRegex(ValueError, "extended public key participants"): + parse_descriptor(f"tr(musig({hex_1},{hex_2},{hex_3})/0/0)") + with self.assertRaisesRegex(ValueError, "cannot be ranged or multipath"): + parse_descriptor(f"tr(musig({xpub_a}/*,{xpub_b})/0/*)") + with self.assertRaisesRegex(ValueError, "cannot be ranged or multipath"): + parse_descriptor(f"tr(musig({xpub_a}/<0;1>,{xpub_b})/<2;3>)") + with self.assertRaisesRegex(ValueError, "hardened derivation steps"): + parse_descriptor(f"tr(musig({xpub_a},{xpub_b})/0h/*)") + with self.assertRaises(ValueError): + parse_descriptor(f"tr(musig({xpub_a},{xpub_b})/0/*h)") + + # BIP 388 does not allow derivation before aggregation + with self.assertRaisesRegex(InvalidPolicyError, "follow musig"): + parse_descriptor(f"tr(musig({xpub_a}/1,{xpub_b}/1)/<0;1>/*)").get_bip388_template() + def test_parse_descriptor_replace_h(self): d = "wpkh([00000001/84h/1h/0h]tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/0/0)" desc = parse_descriptor(d) @@ -512,6 +573,16 @@ def check(descriptor, keys, template): ["[6738736c/86'/0'/0']xpub6CryUDWPS28eR2cDyojB8G354izmx294BdjeSvH469Ty3o2E6Tq5VjBJCn8rWBgesvTJnyXNAJ3QpLFGuNwqFXNt3gn612raffLWfdHNkYL"], "tr(@0/<0;1>/*)" ) + musig_descriptor = "tr(musig([6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw,[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7)/<0;1>/*)" + check( + musig_descriptor, + ["[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw", "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7"], + "tr(musig(@0,@1)/<0;1>/*)" + ) + self.assertEqual( + parse_descriptor(musig_descriptor).derive(7, multipath_index=1).to_string_no_checksum(hardened_char="'"), + "tr(musig([6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw,[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7)/1/7)", + ) check( "wsh(sortedmulti(2,[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw/<0;1>/*,[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7/<0;1>/*))", ["[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw", "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7"], From 3ecbb061f14fccb25aeb6bcdc1f12f46e6bed234 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 13:56:27 +0200 Subject: [PATCH 15/26] displayaddress: require registration for musig() --- hwilib/commands.py | 3 +++ test/test_descriptor.py | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/hwilib/commands.py b/hwilib/commands.py index eabba4f5d..727c4cdb9 100644 --- a/hwilib/commands.py +++ b/hwilib/commands.py @@ -42,6 +42,7 @@ RegisteredDescriptor, parse_descriptor, MultisigDescriptor, + MusigPubkeyProvider, TRDescriptor, PKHDescriptor, PubkeyProvider, @@ -514,6 +515,8 @@ def displayaddress( if descriptor.subdescriptors: raise BadArgumentError("tr() descriptors with a script tree require a registered BIP 388 policy; use --registration") pubkey = descriptor.pubkeys[0] + if isinstance(pubkey, MusigPubkeyProvider): + raise BadArgumentError("musig() addresses require a registered BIP 388 policy; use --registration") if pubkey.origin is None: raise BadArgumentError(f"Descriptor missing origin info: {desc}") if pubkey.origin.fingerprint != client.get_master_fingerprint(): diff --git a/test/test_descriptor.py b/test/test_descriptor.py index a79aafa54..746d658ff 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -184,6 +184,12 @@ def test_taproot_script_tree_requires_registration(self): with self.assertRaisesRegex(BadArgumentError, "registered BIP 388 policy"): displayaddress(object(), desc=descriptor) + def test_musig_requires_registration(self): + key_0 = "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9" + key_1 = "03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659" + with self.assertRaisesRegex(BadArgumentError, "registered BIP 388 policy"): + displayaddress(object(), desc=f"tr(musig({key_0},{key_1}))") + def test_derive(self): xpub = "tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B" descriptor_str = "wsh(multi(1,{0}/<0;1;2>/*,{0}/<10;11;12>/*))".format(xpub) From 8ea09f3b8ca90ffb3fe23c3e649c891be0182e82 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:27:17 +0200 Subject: [PATCH 16/26] test: display MuSig2 addresses --- test/test_bitbox02.py | 1 + test/test_coldcard.py | 3 +++ test/test_device.py | 17 +++++++++++++++++ test/test_digitalbitbox.py | 1 + test/test_jade.py | 1 + test/test_keepkey.py | 1 + test/test_ledger.py | 3 +++ test/test_trezor.py | 1 + 8 files changed, 28 insertions(+) diff --git a/test/test_bitbox02.py b/test/test_bitbox02.py index ead981714..30addc3c1 100644 --- a/test/test_bitbox02.py +++ b/test/test_bitbox02.py @@ -44,6 +44,7 @@ def __init__(self, simulator): self.supports_taproot = False self.supports_segwit_miniscript = True self.supports_taproot_miniscript = True + self.supports_musig2 = False self.strict_bip48 = False self.include_xpubs = True self.supports_device_multiple_multisig = True diff --git a/test/test_coldcard.py b/test/test_coldcard.py index 0651972f6..06b4e4af0 100755 --- a/test/test_coldcard.py +++ b/test/test_coldcard.py @@ -21,6 +21,7 @@ TestDisplayAddress, TestGetKeypool, TestGetDescriptors, + TestMuSig2Display, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, TestTaprootMiniscriptDisplay, @@ -67,6 +68,7 @@ def __init__(self, simulator, is_edge=False): self.supports_taproot = is_edge self.supports_segwit_miniscript = is_edge self.supports_taproot_miniscript = is_edge + self.supports_musig2 = is_edge self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -216,6 +218,7 @@ def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False): if is_edge: suite.addTest(DeviceTestCase.parameterize(TestColdcardEdgeDisplayAddress, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestMuSig2Display, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_device.py b/test/test_device.py index 8860dc6b1..2f773f61c 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -35,6 +35,7 @@ def __init__(self): self.supports_taproot = None self.supports_segwit_miniscript = None self.supports_taproot_miniscript = None + self.supports_musig2 = None self.strict_bip48 = None self.include_xpubs = None self.supports_device_multiple_multisig = None @@ -53,6 +54,7 @@ def start(self): assert self.supports_unsorted_ms is not None assert self.supports_segwit_miniscript is not None assert self.supports_taproot_miniscript is not None + assert self.supports_musig2 is not None assert self.strict_bip48 is not None assert self.include_xpubs is not None assert self.supports_device_multiple_multisig is not None @@ -1046,3 +1048,18 @@ def test_taproot_miniscript(self): descriptor, "tr(@0/<0;1>/*,and_v(v:pk(@1/<0;1>/*),older(12960)))", ) + +class TestMuSig2Display(PolicyDisplayTestCase): + def setUp(self): + if not self.emulator.supports_musig2: + self.skipTest("device does not support MuSig2 policies") + super().setUp() + + def test_musig2(self): + device_key = self._get_account_key("m/87h/1h/0h") + descriptor = f"tr(musig({device_key},{self.EXTERNAL_KEY})/<0;1>/*)" + self._test_display_address( + f"MuSigDisplay{self.emulator.fingerprint}", + descriptor, + "tr(musig(@0,@1)/<0;1>/*)", + ) diff --git a/test/test_digitalbitbox.py b/test/test_digitalbitbox.py index d9f495de5..7ed09e5f6 100755 --- a/test/test_digitalbitbox.py +++ b/test/test_digitalbitbox.py @@ -41,6 +41,7 @@ def __init__(self, simulator): self.supports_taproot = False self.supports_segwit_miniscript = False self.supports_taproot_miniscript = False + self.supports_musig2 = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_jade.py b/test/test_jade.py index 5664b1ebb..78f14155d 100755 --- a/test/test_jade.py +++ b/test/test_jade.py @@ -53,6 +53,7 @@ def __init__(self, jade_qemu_emulator_path): self.supports_taproot = False self.supports_segwit_miniscript = True self.supports_taproot_miniscript = False + self.supports_musig2 = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_keepkey.py b/test/test_keepkey.py index 37f373aca..e2ed576bc 100755 --- a/test/test_keepkey.py +++ b/test/test_keepkey.py @@ -63,6 +63,7 @@ def __init__(self, path): self.supports_taproot = False self.supports_segwit_miniscript = False self.supports_taproot_miniscript = False + self.supports_musig2 = False self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True diff --git a/test/test_ledger.py b/test/test_ledger.py index 4eeca64ba..8a9acec69 100755 --- a/test/test_ledger.py +++ b/test/test_ledger.py @@ -17,6 +17,7 @@ TestDisplayAddress, TestGetKeypool, TestGetDescriptors, + TestMuSig2Display, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, TestTaprootMiniscriptDisplay, @@ -48,6 +49,7 @@ def __init__(self, path, legacy=False): self.supports_taproot = not legacy # Legacy does not support Taproot self.supports_segwit_miniscript = not legacy self.supports_taproot_miniscript = not legacy + self.supports_musig2 = not legacy self.strict_bip48 = True self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -199,6 +201,7 @@ def ledger_test_suite(emulator, bitcoind, interface, legacy=False): suite.addTest(DeviceTestCase.parameterize(TestRegisterDescriptor, bitcoind, emulator=dev_emulator, interface=interface, returns_registration=True)) suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestMuSig2Display, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_trezor.py b/test/test_trezor.py index a4abdbc9e..af66120d6 100755 --- a/test/test_trezor.py +++ b/test/test_trezor.py @@ -62,6 +62,7 @@ def __init__(self, path, model): self.supports_taproot = True self.supports_segwit_miniscript = False self.supports_taproot_miniscript = False + self.supports_musig2 = False self.strict_bip48 = True self.include_xpubs = False self.supports_device_multiple_multisig = True From e6dc37a4809df415df7e9a4ac200a9fa1ca8c0e0 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:28:50 +0200 Subject: [PATCH 17/26] descriptor: allow musig() keys in tapscript Miniscript --- hwilib/descriptor.py | 10 ++++++---- test/test_descriptor.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/hwilib/descriptor.py b/hwilib/descriptor.py index c787d7531..de13d108d 100644 --- a/hwilib/descriptor.py +++ b/hwilib/descriptor.py @@ -916,8 +916,10 @@ def _parse_miniscript( if name in _MINISCRIPT_KEY_FRAGMENTS: if len(arg_strs) != 1: raise ValueError(f"{name}() takes exactly one key expression") - args.append(PubkeyProvider.parse(arg_strs[0], key_expr_index)) - key_expr_index += 1 + if ctx != _MiniscriptContext.TAPSCRIPT and arg_strs[0].startswith("musig("): + raise ValueError("musig() is only allowed in tapscript Miniscript") + key, key_expr_index = _parse_key_expr(arg_strs[0], key_expr_index) + args.append(key) elif name == "multi": if ctx != _MiniscriptContext.SEGWIT_V0: raise ValueError("multi() is only allowed in Segwit v0 Miniscript") @@ -944,8 +946,8 @@ def _parse_miniscript( raise ValueError(f"{name}() threshold must be between 1 and the number of keys") args.append(arg_strs[0]) for arg_str in arg_strs[1:]: - args.append(PubkeyProvider.parse(arg_str, key_expr_index)) - key_expr_index += 1 + key, key_expr_index = _parse_key_expr(arg_str, key_expr_index) + args.append(key) elif name in _MINISCRIPT_TIMELOCK_FRAGMENTS: if len(arg_strs) != 1: raise ValueError(f"{name}() takes exactly one number") diff --git a/test/test_descriptor.py b/test/test_descriptor.py index 746d658ff..187297f98 100755 --- a/test/test_descriptor.py +++ b/test/test_descriptor.py @@ -423,6 +423,47 @@ def test_parse_musig_bip390(self): with self.assertRaisesRegex(InvalidPolicyError, "follow musig"): parse_descriptor(f"tr(musig({xpub_a}/1,{xpub_b}/1)/<0;1>/*)").get_bip388_template() + def test_musig_tapscript_key(self): + key_0 = "[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw" + key_1 = "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7" + internal_key = "[6738736c/86'/0'/0']xpub6CryUDWPS28eR2cDyojB8G354izmx294BdjeSvH469Ty3o2E6Tq5VjBJCn8rWBgesvTJnyXNAJ3QpLFGuNwqFXNt3gn612raffLWfdHNkYL" + descriptor = ( + f"tr({internal_key}/<0;1>/*," + f"and_v(v:pk(musig({key_0},{key_1})/<0;1>/*),older(12960)))" + ) + parsed = parse_descriptor(descriptor) + self.assertEqual(parsed.to_string_no_checksum(hardened_char="'"), descriptor) + self.assertEqual( + parsed.get_bip388_template(), + "tr(@0/<0;1>/*,and_v(v:pk(musig(@1,@2)/<0;1>/*),older(12960)))", + ) + self.assertEqual( + [provider.get_bip388_key_info() for provider in parsed.get_pubkey_providers()], + [internal_key, key_0, key_1], + ) + + def test_bip388_musig_tapscript_vector(self): + key_0 = "[6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa" + key_1 = "[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js" + key_2 = "[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2" + descriptor = parse_descriptor( + f"tr(musig({key_0},{key_1},{key_2})/<0;1>/*," + f"{{and_v(v:pk(musig({key_0},{key_1})/<0;1>/*),older(12960))," + f"{{and_v(v:pk(musig({key_0},{key_2})/<0;1>/*),older(12960))," + f"and_v(v:pk(musig({key_1},{key_2})/<0;1>/*),older(12960))}}}})" + ) + self.assertEqual( + descriptor.get_bip388_template(), + "tr(musig(@0,@1,@2)/<0;1>/*," + "{and_v(v:pk(musig(@0,@1)/<0;1>/*),older(12960))," + "{and_v(v:pk(musig(@0,@2)/<0;1>/*),older(12960))," + "and_v(v:pk(musig(@1,@2)/<0;1>/*),older(12960))}})", + ) + self.assertEqual( + [provider.get_bip388_key_info() for provider in descriptor.get_pubkey_providers()], + [key_0, key_1, key_2], + ) + def test_parse_descriptor_replace_h(self): d = "wpkh([00000001/84h/1h/0h]tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/0/0)" desc = parse_descriptor(d) From 35588fe75130833bb065c30f0dc07a1aad0dfa9a Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 16:29:36 +0200 Subject: [PATCH 18/26] test: display MuSig2 Miniscript addresses --- test/data/speculos-automation.json | 2 +- test/test_coldcard.py | 2 ++ test/test_device.py | 22 ++++++++++++++++++++++ test/test_ledger.py | 2 ++ 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/test/data/speculos-automation.json b/test/data/speculos-automation.json index c228efa54..1705427aa 100644 --- a/test/data/speculos-automation.json +++ b/test/data/speculos-automation.json @@ -33,7 +33,7 @@ ] }, { - "regexp": "^(Address|Review|Account name|Amount|External amounts|You spend|You receive|Confirm|The derivation|Derivation path|Reject if|The change path|Change path|Register wallet|Policy map|Key|Path|Public key|Our key|Their key|Unspendable key|Spend from|Spending policy|Primary spending path|Spending path|Transaction output|From account|Wallet name|Wallet policy|Descriptor template|Verify [Bb]itcoin|Output|Warning).*", + "regexp": "^(Address|Review|Account name|Amount|External amounts|You spend|You receive|Confirm|The derivation|Derivation path|Reject if|The change path|Change path|Register wallet|Policy map|Key|Path|Public key|Our key|Their key|Unspendable key|Spend from|Spending policy|Primary.*ing path|Spending path|Transaction output|From account|Wallet name|Wallet policy|Descriptor template|Verify [Bb]itcoin|Output|Warning).*", "actions": [ [ "button", 2, true ], [ "button", 2, false ] diff --git a/test/test_coldcard.py b/test/test_coldcard.py index 06b4e4af0..b298834bb 100755 --- a/test/test_coldcard.py +++ b/test/test_coldcard.py @@ -22,6 +22,7 @@ TestGetKeypool, TestGetDescriptors, TestMuSig2Display, + TestMuSig2MiniscriptDisplay, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, TestTaprootMiniscriptDisplay, @@ -219,6 +220,7 @@ def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False): suite.addTest(DeviceTestCase.parameterize(TestColdcardEdgeDisplayAddress, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestMuSig2Display, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestMuSig2MiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() diff --git a/test/test_device.py b/test/test_device.py index 2f773f61c..81f926fb7 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -1063,3 +1063,25 @@ def test_musig2(self): descriptor, "tr(musig(@0,@1)/<0;1>/*)", ) + +class TestMuSig2MiniscriptDisplay(PolicyDisplayTestCase): + def setUp(self): + if not self.emulator.supports_musig2: + self.skipTest("device does not support MuSig2 policies") + if not self.emulator.supports_taproot_miniscript: + self.skipTest("device does not support tapscript Miniscript policies") + super().setUp() + + def test_musig2_miniscript(self): + device_key = self._get_account_key("m/87h/1h/0h") + recovery_key = self._get_account_key("m/86h/1h/1h") + descriptor = ( + f"tr(musig({device_key},{self.EXTERNAL_KEY})/<0;1>/*," + f"and_v(v:pk({recovery_key}/<0;1>/*),older(12960)))" + ) + self._test_display_address( + f"MuSigMini{self.emulator.fingerprint}", + descriptor, + "tr(musig(@0,@1)/<0;1>/*," + "and_v(v:pk(@2/<0;1>/*),older(12960)))", + ) diff --git a/test/test_ledger.py b/test/test_ledger.py index 8a9acec69..055948f52 100755 --- a/test/test_ledger.py +++ b/test/test_ledger.py @@ -18,6 +18,7 @@ TestGetKeypool, TestGetDescriptors, TestMuSig2Display, + TestMuSig2MiniscriptDisplay, TestRegisterDescriptor, TestSegwitMiniscriptDisplay, TestTaprootMiniscriptDisplay, @@ -202,6 +203,7 @@ def ledger_test_suite(emulator, bitcoind, interface, legacy=False): suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestMuSig2Display, bitcoind, emulator=dev_emulator, interface=interface)) + suite.addTest(DeviceTestCase.parameterize(TestMuSig2MiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) return result.wasSuccessful() From dfdaed313e07e8485a4f4a62eaa5e898287718dc Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 24 Aug 2026 14:09:04 +0200 Subject: [PATCH 19/26] coldcard: recognize MuSig2 signing data --- hwilib/devices/coldcard.py | 2 +- hwilib/psbt.py | 20 ++++++++++++++++++++ test/test_psbt.py | 23 ++++++++++++++++++++++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/hwilib/devices/coldcard.py b/hwilib/devices/coldcard.py index e09857790..33af1c116 100644 --- a/hwilib/devices/coldcard.py +++ b/hwilib/devices/coldcard.py @@ -257,7 +257,7 @@ def _sign_with_policy_names( # request to infer a policy for any remaining unsigned device inputs. if any( psbt_in.has_fingerprint(master_fp) - and not psbt_in.has_signature(master_fp) + and not psbt_in.has_signing_data(master_fp) for psbt_in in psbt.inputs ): psbt = self._sign_tx_once(psbt) diff --git a/hwilib/psbt.py b/hwilib/psbt.py index 9baa8c845..ef2b50163 100644 --- a/hwilib/psbt.py +++ b/hwilib/psbt.py @@ -198,6 +198,26 @@ def has_signature(self, fingerprint: bytes) -> bool: return True return False + def has_signing_data(self, fingerprint: bytes) -> bool: + """ + Return whether a key with the specified fingerprint has contributed + signing data, including a MuSig2 public nonce. + """ + if self.has_signature(fingerprint): + return True + + musig2_providers = { + participant_pubkey[1:] + for participant_pubkey, _, _ in ( + self.musig2_pub_nonces.keys() + | self.musig2_partial_sigs.keys() + ) + } + return any( + origin.fingerprint == fingerprint and pubkey in musig2_providers + for pubkey, (_, origin) in self.tap_bip32_paths.items() + ) + def deserialize(self, f: Readable) -> None: """ Deserialize a serialized PSBT input. diff --git a/test/test_psbt.py b/test/test_psbt.py index 4d172b65a..9aa9c5ac2 100755 --- a/test/test_psbt.py +++ b/test/test_psbt.py @@ -1,6 +1,7 @@ #! /usr/bin/env python3 -from hwilib.psbt import PSBT +from hwilib.key import KeyOriginInfo +from hwilib.psbt import PSBT, PartiallySignedInput from hwilib.errors import PSBTSerializationError import json import os @@ -105,5 +106,25 @@ def test_has_signature(self): expected, ) + def test_has_signing_data(self): + fingerprint = bytes.fromhex("0f056943") + participant_pubkey = b"\x02" + b"\x11" * 32 + aggregate_pubkey = b"\x03" + b"\x22" * 32 + key = (participant_pubkey, aggregate_pubkey, None) + psbt_in = PartiallySignedInput(2) + psbt_in.tap_bip32_paths[participant_pubkey[1:]] = ( + set(), + KeyOriginInfo(fingerprint, [0]), + ) + + self.assertFalse(psbt_in.has_signing_data(fingerprint)) + psbt_in.musig2_pub_nonces[key] = b"\x33" * 66 + self.assertTrue(psbt_in.has_signing_data(fingerprint)) + self.assertFalse(psbt_in.has_signing_data(b"\x00" * 4)) + + psbt_in.musig2_pub_nonces.clear() + psbt_in.musig2_partial_sigs[key] = b"\x44" * 32 + self.assertTrue(psbt_in.has_signing_data(fingerprint)) + if __name__ == "__main__": unittest.main() From 828469b207eb1c2f4d9a6ef9a81b494327410f31 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Fri, 5 Sep 2025 15:37:36 +0200 Subject: [PATCH 20/26] ledger: sign MuSig2 This adds support handling public nonces and partial signatures. --- hwilib/devices/ledger.py | 93 ++++++++++++++++++++++++++++++-------- test/run_tests.py | 2 + test/test_ledger_musig2.py | 65 ++++++++++++++++++++++++++ 3 files changed, 142 insertions(+), 18 deletions(-) create mode 100644 test/test_ledger_musig2.py diff --git a/hwilib/devices/ledger.py b/hwilib/devices/ledger.py index 87f87505f..b4e5c912b 100644 --- a/hwilib/devices/ledger.py +++ b/hwilib/devices/ledger.py @@ -42,7 +42,13 @@ LegacyClient, TransportClient, ) -from .ledger_bitcoin.client_base import ApduException +from .ledger_bitcoin.client_base import ( + ApduException, + MusigPartialSignature, + MusigPubNonce, + PartialSignature, + UnknownSignPsbtYieldedObject, +) from .ledger_bitcoin.exception import NotSupportedError from .ledger_bitcoin.wallet import ( MultisigWallet, @@ -125,6 +131,27 @@ def check_keypath(key_path: str) -> bool: AddressType.LEGACY: 3, } +def _prepare_musig2_psbt_for_signing(psbt: PSBT, master_fp: bytes) -> None: + for psbt_in in psbt.inputs: + has_our_pubnonce = any( + participant_pubkey[1:] in psbt_in.tap_bip32_paths + and psbt_in.tap_bip32_paths[participant_pubkey[1:]][1].fingerprint == master_fp + for participant_pubkey, _, _ in psbt_in.musig2_pub_nonces + ) + + # The Ledger Bitcoin app refuses to yield its own MuSig2 pubnonce + # in round 1 if another participant's pubnonce is already present, + # and likewise refuses to yield its partial signature in round 2 + # if another partial signature is present. + # + # Seeing our own pubnonce means the device has already completed + # round 1, even if it was the last participant to do so and no + # partial signatures exist yet. + if psbt_in.musig2_partial_sigs or has_our_pubnonce: + psbt_in.musig2_partial_sigs.clear() + else: + psbt_in.musig2_pub_nonces.clear() + def handle_chip_exception(e: Union[BTChipException, ApduException], func_name: str) -> bool: if e.sw in bad_args: raise BadArgumentError('Bad argument') @@ -219,6 +246,7 @@ def legacy_sign_tx() -> PSBT: legacy_input_sigs = client.sign_psbt(psbt, wallet, None) for idx, partial_sig in legacy_input_sigs: + assert isinstance(partial_sig, PartialSignature) psbt_in = psbt.inputs[idx] psbt_in.partial_sigs[partial_sig.pubkey] = partial_sig.signature return psbt @@ -232,6 +260,12 @@ def legacy_sign_tx() -> PSBT: if psbt.version != 2: psbt2.convert_to_v2() + if registered_descriptors: + # Strip entries that prevent the Ledger Bitcoin app from + # contributing in the current round. The caller's PSBT keeps + # them and the device's fresh contributions are merged back. + _prepare_musig2_psbt_for_signing(psbt2, master_fp) + # Figure out which wallets are signing wallets: Dict[bytes, Tuple[int, AddressType, WalletPolicy, Optional[bytes]]] = {} for registered_descriptor in sorted( @@ -375,33 +409,56 @@ def process_origin(origin: KeyOriginInfo) -> None: if not is_wit: psbt_in.witness_utxo = None - input_sigs = self.client.sign_psbt(psbt2, wallet, wallet_hmac) + res = self.client.sign_psbt(psbt2, wallet, wallet_hmac) - for idx, yielded in input_sigs: + for idx, yielded in res: + if isinstance(yielded, UnknownSignPsbtYieldedObject): + continue psbt_in = psbt2.inputs[idx] - utxo = None - if psbt_in.witness_utxo: - utxo = psbt_in.witness_utxo - if psbt_in.non_witness_utxo: - assert psbt_in.prev_out is not None - utxo = psbt_in.non_witness_utxo.vout[psbt_in.prev_out] - assert utxo is not None - - is_wit, wit_ver, _ = utxo.is_witness() + if isinstance(yielded, MusigPubNonce): + psbt_key = ( + yielded.participant_pubkey, + yielded.aggregate_pubkey, + yielded.tapleaf_hash + ) - if is_wit and wit_ver >= 1: - if yielded.tapleaf_hash is None: - psbt_in.tap_key_sig = yielded.signature - else: - psbt_in.tap_script_sigs[(yielded.pubkey, yielded.tapleaf_hash)] = yielded.signature + assert len(yielded.aggregate_pubkey) == 33 + psbt_in.musig2_pub_nonces[psbt_key] = yielded.pubnonce + elif isinstance(yielded, MusigPartialSignature): + psbt_key = ( + yielded.participant_pubkey, + yielded.aggregate_pubkey, + yielded.tapleaf_hash + ) + psbt_in.musig2_partial_sigs[psbt_key] = yielded.partial_signature else: - psbt_in.partial_sigs[yielded.pubkey] = yielded.signature + assert isinstance(yielded, PartialSignature) + utxo = None + if psbt_in.witness_utxo: + utxo = psbt_in.witness_utxo + if psbt_in.non_witness_utxo: + assert psbt_in.prev_out is not None + utxo = psbt_in.non_witness_utxo.vout[psbt_in.prev_out] + assert utxo is not None + + is_wit, wit_ver, _ = utxo.is_witness() + + if is_wit and wit_ver >= 1: + if yielded.tapleaf_hash is None: + psbt_in.tap_key_sig = yielded.signature + else: + psbt_in.tap_script_sigs[(yielded.pubkey, yielded.tapleaf_hash)] = yielded.signature + + else: + psbt_in.partial_sigs[yielded.pubkey] = yielded.signature # Extract the sigs from psbt2 and put them into tx for sig_in, psbt_in in zip(psbt2.inputs, psbt.inputs): psbt_in.partial_sigs.update(sig_in.partial_sigs) + psbt_in.musig2_pub_nonces.update(sig_in.musig2_pub_nonces) + psbt_in.musig2_partial_sigs.update(sig_in.musig2_partial_sigs) psbt_in.tap_script_sigs.update(sig_in.tap_script_sigs) if len(sig_in.tap_key_sig) != 0 and len(psbt_in.tap_key_sig) == 0: psbt_in.tap_key_sig = sig_in.tap_key_sig diff --git a/test/run_tests.py b/test/run_tests.py index a90a42b57..d3d1530d4 100755 --- a/test/run_tests.py +++ b/test/run_tests.py @@ -10,6 +10,7 @@ from test_coldcard import coldcard_test_suite, TestColdcardFirmware from test_descriptor import TestDescriptor from test_device import Bitcoind +from test_ledger_musig2 import TestLedgerMuSig2 from test_psbt import TestPSBT from test_trezor import trezor_test_suite from test_ledger import ledger_test_suite @@ -92,6 +93,7 @@ suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestBIP32)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestColdcardFirmware)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestLedgerBitcoinClient)) + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestLedgerMuSig2)) if sys.platform.startswith("linux"): suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestUdevRulesInstaller)) success = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful() diff --git a/test/test_ledger_musig2.py b/test/test_ledger_musig2.py new file mode 100644 index 000000000..c61a71f79 --- /dev/null +++ b/test/test_ledger_musig2.py @@ -0,0 +1,65 @@ +#! /usr/bin/env python3 + +import unittest + +from hwilib.devices.ledger import _prepare_musig2_psbt_for_signing +from hwilib.key import KeyOriginInfo +from hwilib.psbt import PSBT, PartiallySignedInput + + +class TestLedgerMuSig2(unittest.TestCase): + MASTER_FP = bytes.fromhex("f5acc2fd") + OUR_PUBKEY = bytes.fromhex("02" + "11" * 32) + PEER_PUBKEY = bytes.fromhex("03" + "22" * 32) + AGGREGATE_PUBKEY = bytes.fromhex("02" + "33" * 32) + + def make_psbt(self): + psbt = PSBT() + psbt.version = 2 + psbt_in = PartiallySignedInput(psbt.version) + psbt_in.tap_bip32_paths[self.OUR_PUBKEY[1:]] = ( + set(), + KeyOriginInfo(self.MASTER_FP, []), + ) + psbt.inputs.append(psbt_in) + return psbt, psbt_in + + def test_peer_pubnonce_is_hidden_during_round_one(self): + psbt, psbt_in = self.make_psbt() + peer_key = (self.PEER_PUBKEY, self.AGGREGATE_PUBKEY, None) + psbt_in.musig2_pub_nonces[peer_key] = b"\x44" * 66 + + _prepare_musig2_psbt_for_signing(psbt, self.MASTER_FP) + + self.assertEqual(psbt_in.musig2_pub_nonces, {}) + + def test_our_pubnonce_selects_round_two(self): + psbt, psbt_in = self.make_psbt() + our_key = (self.OUR_PUBKEY, self.AGGREGATE_PUBKEY, None) + peer_key = (self.PEER_PUBKEY, self.AGGREGATE_PUBKEY, None) + psbt_in.musig2_pub_nonces[our_key] = b"\x44" * 66 + psbt_in.musig2_pub_nonces[peer_key] = b"\x55" * 66 + psbt_in.musig2_partial_sigs[peer_key] = b"\x66" * 32 + + _prepare_musig2_psbt_for_signing(psbt, self.MASTER_FP) + + self.assertEqual( + set(psbt_in.musig2_pub_nonces), + {our_key, peer_key}, + ) + self.assertEqual(psbt_in.musig2_partial_sigs, {}) + + def test_partial_signature_still_selects_round_two(self): + psbt, psbt_in = self.make_psbt() + peer_key = (self.PEER_PUBKEY, self.AGGREGATE_PUBKEY, None) + psbt_in.musig2_pub_nonces[peer_key] = b"\x44" * 66 + psbt_in.musig2_partial_sigs[peer_key] = b"\x55" * 32 + + _prepare_musig2_psbt_for_signing(psbt, self.MASTER_FP) + + self.assertIn(peer_key, psbt_in.musig2_pub_nonces) + self.assertEqual(psbt_in.musig2_partial_sigs, {}) + + +if __name__ == "__main__": + unittest.main() From 1b65916d0d753ffda912769680ca210b582f4f86 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Fri, 3 Jul 2026 19:22:59 +0200 Subject: [PATCH 21/26] ci: build Bitcoin Core from MuSig2 branch --- test/setup_environment.sh | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/test/setup_environment.sh b/test/setup_environment.sh index bec5755b3..a07d42b47 100755 --- a/test/setup_environment.sh +++ b/test/setup_environment.sh @@ -75,6 +75,8 @@ BITBOX02_VERSION="firmware/v9.24.0" KEEPKEY_VERSION="v7.10.0" SPECULOS_VERSION="ed952a54801f59a71399462b5422976d84c817bb" # Requires Python >=3.10 (v0.25.11+) JADE_VERSION="1.0.36" +BITCOIND_REPO_URL="${BITCOIND_REPO_URL:-https://github.com/Sjors/bitcoin.git}" +BITCOIND_BRANCH="${BITCOIND_BRANCH:-2025/06/musig2-power}" COLDCARD_VERSION="2026-07-31T0519-v5.6.0" COLDCARD_EDGE_VERSION="2026-07-31T1609-v6.6.0X" @@ -453,28 +455,15 @@ fi if [[ -n ${build_bitcoind} ]]; then # Clone bitcoind if it doesn't exist, or update it if it does - bitcoind_setup_needed=false if [ ! -d "bitcoin" ]; then - git clone https://github.com/bitcoin/bitcoin.git + git clone --branch "$BITCOIND_BRANCH" "$BITCOIND_REPO_URL" bitcoin cd bitcoin - bitcoind_setup_needed=true else cd bitcoin - git reset --hard origin/master - git fetch - - # Determine if we need to pull. From https://stackoverflow.com/a/3278427 - UPSTREAM=${1:-'@{u}'} - LOCAL=$(git rev-parse @) - REMOTE=$(git rev-parse "$UPSTREAM") - BASE=$(git merge-base @ "$UPSTREAM") - - if [ $LOCAL = $REMOTE ]; then - echo "Up-to-date" - elif [ $LOCAL = $BASE ]; then - git pull - bitcoind_setup_needed=true - fi + git remote set-url origin "$BITCOIND_REPO_URL" + git fetch origin "$BITCOIND_BRANCH" + git checkout -B "$BITCOIND_BRANCH" "origin/$BITCOIND_BRANCH" + git reset --hard "origin/$BITCOIND_BRANCH" fi # Build bitcoind. This is super slow, but it is cached so it runs fairly quickly. From db3778497572b79a3a3dcbe40c3ac9f2e315755d Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Tue, 18 Aug 2026 18:41:15 +0200 Subject: [PATCH 22/26] test: add Ledger MuSig2 device test Exercise the MuSig2 signing flow through the common device test harness so it runs with every supported interface. --- test/test_device.py | 92 +++++++++++++++++++++++++++++++++++++++++++++ test/test_ledger.py | 3 ++ 2 files changed, 95 insertions(+) diff --git a/test/test_device.py b/test/test_device.py index 81f926fb7..087aa00b2 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -1085,3 +1085,95 @@ def test_musig2_miniscript(self): "tr(musig(@0,@1)/<0;1>/*," "and_v(v:pk(@2/<0;1>/*),older(12960)))", ) + + +class TestMuSig2(DeviceTestCase): + def setUp(self): + super().setUp() + wallet_name = '{}_{}_test'.format(self.emulator.type, self.id()) + self.rpc.createwallet( + wallet_name=wallet_name, + disable_private_keys=False, + blank=True, + descriptors=True, + ) + self.wrpc = self.bitcoind.get_wallet_rpc(wallet_name) + self.wpk_rpc = self.bitcoind.get_wallet_rpc("supply") + self.wrpc.addhdkey() + + def _device_sign(self, registration, psbt): + result = self.do_command(self.dev_args + [ + "signtx", + "--registration", registration, + psbt, + ]) + self.assertNotIn("error", result) + self.assertTrue(result["signed"]) + return result["psbt"] + + def test_musig2(self): + account_path = "m/87h/1h/0h" + device_xpub = self.do_command(self.dev_args + ["getxpub", account_path])["xpub"] + device_key = f"[{self.emulator.fingerprint}{account_path[1:]}]{device_xpub}" + + local_info = self.wrpc.derivehdkey(path=account_path) + local_key = local_info["origin"] + local_info["xpub"] + recovery_info = self.wrpc.derivehdkey(path="m/87h/1h/1h") + recovery_key = recovery_info["origin"] + recovery_info["xpub"] + + descriptor = ( + f"tr(musig({device_key},{local_key})/<0;1>/*," + f"and_v(v:pk({recovery_key}/<0;1>/*),older(1)))" + ) + registration = self.do_command(self.dev_args + [ + "registerdescriptor", "MuSigTest", descriptor, + ]) + self.assertNotIn("error", registration) + registration = registration["registration"] + + imported = self.wrpc.importdescriptors([{ + "desc": AddChecksum(descriptor), + "timestamp": "now", + "active": True, + }]) + self.assertTrue(imported[0]["success"]) + + receive_address = self.wrpc.getnewaddress("", "bech32m") + display = self.do_command(self.dev_args + [ + "displayaddress", + "--index", "0", + "--registration", registration, + ]) + self.assertNotIn("error", display) + self.assertEqual( + bech32.decode("tb", display["address"]), + bech32.decode("bcrt", receive_address), + ) + + self.wpk_rpc.sendtoaddress(receive_address, 1) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + psbt = self.wrpc.walletcreatefundedpsbt( + [], + [{self.wpk_rpc.getnewaddress("", "bech32m"): 0.5}], + 0, + {"includeWatching": True}, + True, + )["psbt"] + self.assertEqual(self.rpc.decodepsbt(psbt)["psbt_version"], 2) + device_nonce = self._device_sign(registration, psbt) + local_nonce = self.wrpc.walletprocesspsbt(psbt=psbt, finalize=False)["psbt"] + nonce_psbt = self.rpc.combinepsbt([device_nonce, local_nonce]) + decoded = self.rpc.decodepsbt(nonce_psbt) + self.assertEqual(len(decoded["inputs"][0]["musig2_pubnonces"]), 2) + + device_partial_sig = self._device_sign(registration, nonce_psbt) + local_partial_sig = self.wrpc.walletprocesspsbt(psbt=nonce_psbt, finalize=False)["psbt"] + signed_psbt = self.rpc.combinepsbt([device_partial_sig, local_partial_sig]) + decoded = self.rpc.decodepsbt(signed_psbt) + self.assertEqual(len(decoded["inputs"][0]["musig2_partial_sigs"]), 2) + + finalized = self.rpc.finalizepsbt(signed_psbt) + self.assertTrue(finalized["complete"]) + txid = self.rpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreaterEqual(self.wrpc.gettransaction(txid)["confirmations"], 1) diff --git a/test/test_ledger.py b/test/test_ledger.py index 055948f52..3b3e6d6dc 100755 --- a/test/test_ledger.py +++ b/test/test_ledger.py @@ -17,6 +17,7 @@ TestDisplayAddress, TestGetKeypool, TestGetDescriptors, + TestMuSig2, TestMuSig2Display, TestMuSig2MiniscriptDisplay, TestRegisterDescriptor, @@ -202,6 +203,8 @@ def ledger_test_suite(emulator, bitcoind, interface, legacy=False): suite.addTest(DeviceTestCase.parameterize(TestRegisterDescriptor, bitcoind, emulator=dev_emulator, interface=interface, returns_registration=True)) suite.addTest(DeviceTestCase.parameterize(TestSegwitMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) + if dev_emulator.supports_musig2 and dev_emulator.supports_taproot_miniscript: + suite.addTest(DeviceTestCase.parameterize(TestMuSig2, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestMuSig2Display, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestMuSig2MiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) From df1977a7176f5a3a19d2afc4d58a7657d571d60e Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Tue, 18 Aug 2026 20:21:09 +0200 Subject: [PATCH 23/26] test: exercise MuSig2 device recovery path Use a separate account from the signing device for the delayed recovery leaf, then fund and spend it without the Core key-path participant. --- test/test_device.py | 47 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/test/test_device.py b/test/test_device.py index 087aa00b2..017791cf1 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -1118,8 +1118,11 @@ def test_musig2(self): local_info = self.wrpc.derivehdkey(path=account_path) local_key = local_info["origin"] + local_info["xpub"] - recovery_info = self.wrpc.derivehdkey(path="m/87h/1h/1h") - recovery_key = recovery_info["origin"] + recovery_info["xpub"] + recovery_path = "m/87h/1h/1h" + recovery_xpub = self.do_command( + self.dev_args + ["getxpub", recovery_path] + )["xpub"] + recovery_key = f"[{self.emulator.fingerprint}{recovery_path[1:]}]{recovery_xpub}" descriptor = ( f"tr(musig({device_key},{local_key})/<0;1>/*," @@ -1150,13 +1153,19 @@ def test_musig2(self): bech32.decode("bcrt", receive_address), ) + recovery_address = self.wrpc.getnewaddress("", "bech32m") self.wpk_rpc.sendtoaddress(receive_address, 1) + self.wpk_rpc.sendtoaddress(recovery_address, 1) self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + + key_path_utxo = self.wrpc.listunspent( + 1, 9999999, [receive_address] + )[0] psbt = self.wrpc.walletcreatefundedpsbt( - [], + [{"txid": key_path_utxo["txid"], "vout": key_path_utxo["vout"]}], [{self.wpk_rpc.getnewaddress("", "bech32m"): 0.5}], 0, - {"includeWatching": True}, + {"add_inputs": False, "includeWatching": True}, True, )["psbt"] self.assertEqual(self.rpc.decodepsbt(psbt)["psbt_version"], 2) @@ -1177,3 +1186,33 @@ def test_musig2(self): txid = self.rpc.sendrawtransaction(finalized["hex"]) self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) self.assertGreaterEqual(self.wrpc.gettransaction(txid)["confirmations"], 1) + + recovery_utxo = self.wrpc.listunspent( + 1, 9999999, [recovery_address] + )[0] + recovery_psbt = self.wrpc.walletcreatefundedpsbt( + [{ + "txid": recovery_utxo["txid"], + "vout": recovery_utxo["vout"], + "sequence": 1, + }], + [{self.wpk_rpc.getnewaddress("", "bech32m"): 0.5}], + 0, + {"add_inputs": False, "includeWatching": True}, + True, + )["psbt"] + self.assertEqual( + self.rpc.decodepsbt(recovery_psbt)["psbt_version"], + 2, + ) + recovery_psbt = self._device_sign(registration, recovery_psbt) + decoded = self.rpc.decodepsbt(recovery_psbt) + self.assertIn("taproot_script_path_sigs", decoded["inputs"][0]) + + finalized = self.rpc.finalizepsbt(recovery_psbt) + self.assertTrue(finalized["complete"]) + recovery_txid = self.rpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreaterEqual( + self.wrpc.gettransaction(recovery_txid)["confirmations"], 1 + ) From c23a442b52fdc1d940c03a875a27a448f6cb2edf Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Tue, 18 Aug 2026 18:41:32 +0200 Subject: [PATCH 24/26] test: add Coldcard Edge MuSig2 coverage --- test/test_coldcard.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_coldcard.py b/test/test_coldcard.py index b298834bb..fe4c09e37 100755 --- a/test/test_coldcard.py +++ b/test/test_coldcard.py @@ -21,6 +21,7 @@ TestDisplayAddress, TestGetKeypool, TestGetDescriptors, + TestMuSig2, TestMuSig2Display, TestMuSig2MiniscriptDisplay, TestRegisterDescriptor, @@ -219,6 +220,8 @@ def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False): if is_edge: suite.addTest(DeviceTestCase.parameterize(TestColdcardEdgeDisplayAddress, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestTaprootMiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) + if dev_emulator.supports_musig2 and dev_emulator.supports_taproot_miniscript: + suite.addTest(DeviceTestCase.parameterize(TestMuSig2, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestMuSig2Display, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestMuSig2MiniscriptDisplay, bitcoind, emulator=dev_emulator, interface=interface)) From 5f799a18fe4f7cbf6145760afef12ea5633ff2ff Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Tue, 18 Aug 2026 18:54:07 +0200 Subject: [PATCH 25/26] test: add MuSig2 device interoperability Exercise a no-fallback 3-of-3 MuSig2 policy between Coldcard Edge, Ledger, and Bitcoin Core in a dedicated CLI-only CI job. --- .github/workflows/ci.yml | 39 +++++++ test/test_interoperability.py | 209 ++++++++++++++++++++++++++++++++++ 2 files changed, 248 insertions(+) create mode 100644 test/test_interoperability.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb66eea51..3e102ba4b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -232,6 +232,45 @@ jobs: runs-on: ubuntu-latest python_versions: '["3.14"]' + test-interoperability: + name: Python 3.14 interoperability cli + runs-on: ubuntu-latest + timeout-minutes: 45 + needs: [sim-builder-coldcard-edge, sim-builder-ledger, ledger-app-builder, bitcoind-builder] + container: python:3.14 + steps: + - uses: actions/checkout@v7 + + - run: | + pip install poetry + poetry install + + - uses: actions/download-artifact@v8 + with: + name: bitcoind + + - run: | + tar -xvf bitcoind.tar.gz + + - name: Install Coldcard Edge simulator + uses: ./.github/actions/install-sim + with: + device: coldcard-edge + + - name: Install Ledger simulator + uses: ./.github/actions/install-sim + with: + device: ledger + + - name: Run interoperability test + run: | + cd test + poetry run python test_interoperability.py --interface=cli + + - if: failure() + run: | + tail -v -n +1 test/*-emulator.std* || true + test-bitbox01: uses: ./.github/workflows/device-test.yml needs: [sim-builder-bitbox, bitcoind-builder, dist-builder] diff --git a/test/test_interoperability.py b/test/test_interoperability.py new file mode 100644 index 000000000..aad60c9f7 --- /dev/null +++ b/test/test_interoperability.py @@ -0,0 +1,209 @@ +#! /usr/bin/env python3 + +import argparse +import sys +import unittest + +from hwilib import _bech32 as bech32 +from hwilib.descriptor import AddChecksum +from test_coldcard import ColdcardSimulator +from test_device import Bitcoind, DeviceTestCase +from test_ledger import LedgerEmulator + + +class TestMuSig2Interoperability(DeviceTestCase): + def __init__( + self, + bitcoind, + coldcard_edge, + ledger, + interface="library", + methodName="runTest", + ): + self.devices = [coldcard_edge, ledger] + super().__init__(bitcoind, coldcard_edge, interface, methodName) + + def setUp(self): + for device in self.devices: + device.start() + self.addCleanup(device.stop) + + wallet_name = "interoperability_{}_test".format(self.id()) + self.rpc.createwallet( + wallet_name=wallet_name, + disable_private_keys=False, + blank=True, + descriptors=True, + ) + self.wrpc = self.bitcoind.get_wallet_rpc(wallet_name) + self.wpk_rpc = self.bitcoind.get_wallet_rpc("supply") + self.wrpc.addhdkey() + + def tearDown(self): + # Each simulator is stopped by the cleanup registered immediately after + # it starts, including when a later simulator fails to start. + pass + + def _device_args(self, device): + args = ["-t", device.type, "-d", device.path, "--chain", "test"] + if device.password is not None: + args.extend(["-p", device.password]) + return args + + def _device_sign(self, device, registration, psbt): + result = self.do_command(self._device_args(device) + [ + "signtx", + "--registration", registration, + psbt, + ]) + self.assertNotIn("error", result) + self.assertTrue(result["signed"]) + return result["psbt"] + + def test_coldcard_ledger_core(self): + account_path = "m/87h/1h/0h" + device_keys = [] + for device in self.devices: + xpub = self.do_command( + self._device_args(device) + ["getxpub", account_path] + )["xpub"] + device_keys.append( + f"[{device.fingerprint}{account_path[1:]}]{xpub}" + ) + + core_info = self.wrpc.derivehdkey(path=account_path) + core_key = core_info["origin"] + core_info["xpub"] + descriptor = "tr(musig({})/<0;1>/*)".format( + ",".join(device_keys + [core_key]) + ) + + registrations = {} + for device in self.devices: + result = self.do_command(self._device_args(device) + [ + "registerdescriptor", "MuSigInterop", descriptor, + ]) + self.assertNotIn("error", result) + registrations[device] = result["registration"] + + imported = self.wrpc.importdescriptors([{ + "desc": AddChecksum(descriptor), + "timestamp": "now", + "active": True, + }]) + self.assertTrue(imported[0]["success"]) + + receive_address = self.wrpc.getnewaddress("", "bech32m") + for device in self.devices: + display = self.do_command(self._device_args(device) + [ + "displayaddress", + "--index", "0", + "--registration", registrations[device], + ]) + self.assertNotIn("error", display) + self.assertEqual( + bech32.decode("tb", display["address"]), + bech32.decode("bcrt", receive_address), + ) + + self.wpk_rpc.sendtoaddress(receive_address, 1) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + psbt = self.wrpc.walletcreatefundedpsbt( + [], + [{self.wpk_rpc.getnewaddress("", "bech32m"): 0.5}], + 0, + {"includeWatching": True}, + True, + )["psbt"] + self.assertEqual(self.rpc.decodepsbt(psbt)["psbt_version"], 2) + nonce_psbts = [ + self._device_sign(device, registrations[device], psbt) + for device in self.devices + ] + nonce_psbts.append( + self.wrpc.walletprocesspsbt(psbt=psbt, finalize=False)["psbt"] + ) + nonce_psbt = self.rpc.combinepsbt(nonce_psbts) + decoded = self.rpc.decodepsbt(nonce_psbt) + self.assertEqual(len(decoded["inputs"][0]["musig2_pubnonces"]), 3) + + partial_sig_psbts = [ + self._device_sign(device, registrations[device], nonce_psbt) + for device in self.devices + ] + partial_sig_psbts.append( + self.wrpc.walletprocesspsbt( + psbt=nonce_psbt, + finalize=False, + )["psbt"] + ) + signed_psbt = self.rpc.combinepsbt(partial_sig_psbts) + decoded = self.rpc.decodepsbt(signed_psbt) + self.assertEqual( + len(decoded["inputs"][0]["musig2_partial_sigs"]), + 3, + ) + + finalized = self.rpc.finalizepsbt(signed_psbt) + self.assertTrue(finalized["complete"]) + txid = self.rpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreaterEqual(self.wrpc.gettransaction(txid)["confirmations"], 1) + + +def interoperability_test_suite( + coldcard_edge_path, + ledger_path, + bitcoind, + interface, +): + coldcard_edge = ColdcardSimulator(coldcard_edge_path, is_edge=True) + ledger = LedgerEmulator(ledger_path) + suite = unittest.TestSuite() + suite.addTest(TestMuSig2Interoperability( + bitcoind, + coldcard_edge, + ledger, + interface, + "test_coldcard_ledger_core", + )) + return unittest.TextTestRunner( + stream=sys.stdout, + verbosity=2, + ).run(suite).wasSuccessful() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Test interoperability between hardware wallet devices" + ) + parser.add_argument( + "--coldcard-edge-path", + default="work/firmware/unix/simulator.py", + help="Path to the Coldcard Edge simulator", + ) + parser.add_argument( + "--ledger-path", + default="work/speculos/speculos.py", + help="Path to the Ledger emulator", + ) + parser.add_argument( + "--bitcoind", + default="work/bitcoin/build/bin/bitcoind", + help="Path to bitcoind", + ) + parser.add_argument( + "--interface", + choices=["library", "cli", "bindist", "stdin"], + default="library", + help="Which interface to send commands over", + ) + args = parser.parse_args() + + bitcoind = Bitcoind.create(args.bitcoind) + success = interoperability_test_suite( + args.coldcard_edge_path, + args.ledger_path, + bitcoind, + args.interface, + ) + sys.exit(not success) From 316ebf0525ed0f0c2aa0d2522b44d443db50e158 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Fri, 7 Aug 2026 09:45:26 +0200 Subject: [PATCH 26/26] docs: add MuSig2 walkthrough --- docs/examples/index.rst | 1 + docs/examples/musig2.rst | 109 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 docs/examples/musig2.rst diff --git a/docs/examples/index.rst b/docs/examples/index.rst index f95cedb8d..315a5ad6c 100644 --- a/docs/examples/index.rst +++ b/docs/examples/index.rst @@ -6,4 +6,5 @@ Example Usage bitcoin-core-usage examples + musig2 walkthrough/walkthrough diff --git a/docs/examples/musig2.rst b/docs/examples/musig2.rst new file mode 100644 index 000000000..f50d17273 --- /dev/null +++ b/docs/examples/musig2.rst @@ -0,0 +1,109 @@ +MuSig2 With Bitcoin Core And HWI +================================ + +This walkthrough describes the HWI side of a 2-of-2 MuSig2 wallet where +cosigner A is a hardware wallet and cosigner B is a hot key in the same +Bitcoin Core wallet. It assumes a Bitcoin Core build with ``tr(musig(...))`` +descriptors and external-signer descriptor registration support. + +The hardware wallet can be a Ledger or a Coldcard Edge. MuSig2 uses Taproot, +which is supported by the Edge firmware but not by the standard Coldcard +firmware. + +Get The Hardware Wallet Key +--------------------------- + +Use BIP87 account keys for MuSig2. For test networks the account path is +``m/87h/1h/0h``: + +.. code-block:: bash + + ./hwi.py --chain test --fingerprint "$FP_A" getxpub "m/87h/1h/0h" + +Build the key expression with origin information: + +.. code-block:: bash + + COSIGNER_A_KEY="[${FP_A}/87h/1h/0h]tpub..." + +Create the Core wallet with ``external_signer=true``, +``disable_private_keys=false``, and ``blank=true``. Add cosigner B's hot HD key +to that wallet, derive its BIP87 account xpub, and build a descriptor like: + +.. code-block:: bash + + DESC_NO_CKSUM="tr(musig(${COSIGNER_A_KEY},${COSIGNER_B_KEY})/<0;1>/*)" + +Register The Descriptor +----------------------- + +Bitcoin Core's ``registerdescriptor`` RPC derives the ordinary multipath +descriptor from the wallet's active receive and change descriptors and passes +it to HWI. The equivalent direct HWI command is: + +.. code-block:: bash + + ./hwi.py --chain test --fingerprint "$FP_A" registerdescriptor \ + MuSigTest "$DESC_NO_CKSUM" + +The result contains an opaque serialized registration. Bitcoin Core stores it +unchanged and supplies it to HWI when displaying addresses or signing: + +.. code-block:: json + + {"registration":"..."} + +On Ledger, this registration includes data that authenticates the policy to +the device. Coldcard Edge instead stores the named policy on the device during +registration. In either case, applications should treat the serialized value +as opaque and reuse it unchanged. Confirm the policy on the hardware wallet +before accepting the registration. + +Display A Registered Address +---------------------------- + +For registered descriptors, Bitcoin Core's ``walletdisplayaddress`` invokes +HWI with the stored registration instead of passing a single-address +descriptor: + +.. code-block:: bash + + ./hwi.py --chain test --fingerprint "$FP_A" displayaddress \ + --registration "$REGISTRATION" \ + --index 0 + +Use ``--change`` to display the change branch for the same index. HWI returns +the address reported by the device: + +.. code-block:: json + + { + "address": "tb1p...", + "index": 0, + "change": false + } + +Coldcard Edge looks up the policy stored under its registration name, then +derives the requested branch and index. Ledger reconstructs the registered +policy from the serialized registration. Both devices display the resulting +address for confirmation. + +Sign +---- + +Core invokes HWI's ``signtx`` with the same opaque registration: + +.. code-block:: bash + + ./hwi.py --chain test --fingerprint "$FP_A" signtx "$PSBT" \ + --registration "$REGISTRATION" + +MuSig2 signing has two rounds. When the coordinating wallet has another +cosigner locally, Bitcoin Core can run both rounds inside one ``send`` call: +first HWI yields the hardware wallet's public nonce, then Core adds the hot +cosigner's nonce and partial signature, and finally HWI yields the hardware +wallet's partial signature. The returned PSBT is then ready for finalization +by Core. + +Coldcard Edge and Ledger both accept PSBT version 2, so HWI can combine their +independent updates without first converting the PSBT.