Skip to content
Merged
18 changes: 16 additions & 2 deletions hwilib/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,16 @@
def backup_device_handler(args: argparse.Namespace, client: HardwareWalletClient) -> Dict[str, bool]:
return backup_device(client, label=args.label, backup_passphrase=args.backup_passphrase)

def displayaddress_handler(args: argparse.Namespace, client: HardwareWalletClient) -> Dict[str, str]:
return displayaddress(client, desc=args.desc, path=args.path, addr_type=args.addr_type)
def displayaddress_handler(args: argparse.Namespace, client: HardwareWalletClient) -> Dict[str, Union[int, str]]:
return displayaddress(
client,
desc=args.desc,
path=args.path,
addr_type=args.addr_type,
registration=args.registration,
index=args.index,
multipath_index=args.multipath_index,
)

def enumerate_handler(args: argparse.Namespace) -> List[Dict[str, Any]]:
return enumerate(password=args.password, expert=args.expert, chain=args.chain, allow_emulators=args.allow_emulators)
Expand Down Expand Up @@ -198,7 +206,13 @@ def get_parser() -> HWIArgumentParser:
group = displayaddr_parser.add_mutually_exclusive_group(required=True)
group.add_argument('--desc', help='Output Descriptor. E.g. wpkh([00000000/84h/0h/0h]xpub.../0/0), where 00000000 must match --fingerprint and xpub can be obtained with getxpub. See doc/descriptors.md in Bitcoin Core')
group.add_argument('--path', help='The BIP 32 derivation path of the key embedded in the address, default follows BIP43 convention, e.g. ``m/84h/0h/0h/1/*``')
group.add_argument('--registration', help='Registration returned by the registerdescriptor command')
displayaddr_parser.add_argument("--addr-type", help="The address type to display", type=AddressType.argparse, choices=list(AddressType), default=AddressType.WIT) # type: ignore
displayaddr_policy_group = displayaddr_parser.add_argument_group("BIP388 policy")
displayaddr_policy_group.add_argument('--index', help='Address index to display from the policy', type=int)
displayaddr_multipath_group = displayaddr_policy_group.add_mutually_exclusive_group()
displayaddr_multipath_group.add_argument('--multipath-index', help='Multipath index to select from the policy', type=int)
displayaddr_multipath_group.add_argument('--change', help='Select the change branch (equivalent to --multipath-index 1)', action='store_const', const=1, dest='multipath_index')
displayaddr_parser.set_defaults(func=displayaddress_handler)

setupdev_parser = subparsers.add_parser('setup', help='Setup a device. Passphrase protection uses the password given by -p. Requires interactive mode')
Expand Down
35 changes: 33 additions & 2 deletions hwilib/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
)
from .descriptor import (
Descriptor,
RegisteredDescriptor,
parse_descriptor,
MultisigDescriptor,
TRDescriptor,
Expand Down Expand Up @@ -435,8 +436,11 @@ def displayaddress(
client: HardwareWalletClient,
path: Optional[str] = None,
desc: Optional[str] = None,
addr_type: AddressType = AddressType.WIT
) -> Dict[str, str]:
addr_type: AddressType = AddressType.WIT,
registration: Optional[str] = None,
index: Optional[int] = None,
multipath_index: Optional[int] = None,
) -> Dict[str, Union[int, str]]:
"""
Display an address on the device for client.
The address can be specified by the path with additional parameters, or by a descriptor.
Expand All @@ -445,10 +449,37 @@ def displayaddress(
:param path: The path of the address to display. Mutually exclusive with ``desc``
:param desc: The descriptor to display the address for. Mutually exclusive with ``path``
:param addr_type: The address type to return. Only works with ``path``
:param registration: Serialized registered descriptor for BIP388 policy display
:param index: Address index to display for BIP388 policy mode
:param multipath_index: Multipath index to select for BIP388 policy mode
:return: A dictionary containing the address displayed.
Returned as ``{"address": <base58 or bech32 address string>}``.
:raises: BadArgumentError: if an argument is malformed, missing, or conflicts.
"""
policy_mode = index is not None or registration is not None or multipath_index is not None
if policy_mode:
if registration is None:
raise BadArgumentError("Missing --registration")
if index is None:
raise BadArgumentError("Missing --index")
if index < 0:
raise BadArgumentError("Address index must be non-negative")
if multipath_index is None:
multipath_index = 0
elif multipath_index < 0:
raise BadArgumentError("Multipath index must be non-negative")

registered_descriptor = RegisteredDescriptor.deserialize(registration)
address = client.display_bip388_policy_address(
registered_descriptor,
index,
multipath_index,
)
return {
"address": address,
"index": index,
"multipath_index": multipath_index,
}
if path is not None:
return {"address": client.display_singlesig_address(path, addr_type)}
elif desc is not None:
Expand Down
12 changes: 12 additions & 0 deletions hwilib/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from base64 import b64decode, b64encode
from binascii import unhexlify
from collections import namedtuple
from copy import deepcopy
from enum import Enum
from io import BufferedReader, BytesIO
from typing import (
Expand Down Expand Up @@ -354,6 +355,17 @@ def get_pubkey_providers(self) -> list['PubkeyProvider']:
out.extend(s.get_pubkey_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():
path = pubkey.get_deriv_path(pos, multipath_index)
pubkey.deriv_path = [[step] for step in path] or None
pubkey.ranged = False
pubkey.multipath_len = 1
return descriptor


class PKDescriptor(Descriptor):
"""
Expand Down
27 changes: 27 additions & 0 deletions hwilib/devices/bitbox02.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,33 @@ def display_singlesig_address(
)
return address

@bitbox02_exception
def display_bip388_policy_address(
self,
registered_descriptor: RegisteredDescriptor,
index: int,
multipath_index: int = 0,
) -> str:
descriptor = registered_descriptor.descriptor
account_keypath = None
device_fingerprint = self.get_master_fingerprint()
for pubkey in descriptor.get_pubkey_providers():
if (
pubkey.origin is not None
and pubkey.origin.fingerprint == device_fingerprint
):
account_keypath = pubkey.origin.path
break
if account_keypath is None:
raise BadArgumentError("This BitBox02 is not one of the policy keys")

return self.init().btc_address(
[*account_keypath, multipath_index, index],
coin=self._get_coin(),
script_config=self._bip388_script_config(descriptor),
display=True,
)

@bitbox02_exception
def display_multisig_address(
self,
Expand Down
42 changes: 41 additions & 1 deletion hwilib/devices/coldcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
Descriptor,
MultisigDescriptor,
RegisteredDescriptor,
WSHDescriptor,
)
from ..hwwclient import HardwareWalletClient
from ..errors import (
Expand Down Expand Up @@ -346,6 +347,40 @@ def display_multisig_address(
self.device.send_recv(CCProtocolPacker.sim_keypress(b'y'))
return address

def display_bip388_policy_address(
self,
registered_descriptor: RegisteredDescriptor,
index: int,
multipath_index: int = 0,
) -> str:
if self.is_edge:
if multipath_index not in (0, 1):
raise BadArgumentError("Coldcard Edge only supports receive and change branches")
address = self.device.send_recv(
CCProtocolPacker.miniscript_address(
registered_descriptor.name,
change=bool(multipath_index),
idx=index,
),
timeout=None,
)
assert isinstance(address, str)
if self.device.is_simulator:
self.device.send_recv(CCProtocolPacker.sim_keypress(b'y'))
return address

descriptor = registered_descriptor.descriptor.derive(index, multipath_index)
if (
not isinstance(descriptor, WSHDescriptor)
or len(descriptor.subdescriptors) != 1
or not isinstance(descriptor.subdescriptors[0], MultisigDescriptor)
):
raise BadArgumentError("Coldcard only supports wsh(sortedmulti()) policies")
return self.display_multisig_address(
AddressType.WIT,
descriptor.subdescriptors[0],
)

def setup_device(self, label: str = "", passphrase: str = "") -> bool:
"""
The Coldcard does not support setup via software.
Expand Down Expand Up @@ -471,7 +506,12 @@ def register_descriptor(self, name: str, descriptor: 'Descriptor') -> Registered
raise DeviceFailureError(f"Wrong checksum, expected {expect.hex()}, got {result.hex()}")

# Register the descriptor
self.device.send_recv(CCProtocolPacker.multisig_enroll(size, expect), timeout=None)
enroll = (
CCProtocolPacker.miniscript_enroll
if self.is_edge
else CCProtocolPacker.multisig_enroll
)
self.device.send_recv(enroll(size, expect), timeout=None)
if self.device.is_simulator:
self.device.send_recv(CCProtocolPacker.sim_keypress(b'y'))
return RegisteredDescriptor(name=name, descriptor=descriptor, device_type="coldcard", registration=b"")
Expand Down
15 changes: 15 additions & 0 deletions hwilib/devices/jade.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,21 @@ def display_multisig_address(self, addr_type: AddressType, multisig: MultisigDes

return str(address)

@jade_exception
def display_bip388_policy_address(
self,
registered_descriptor: RegisteredDescriptor,
index: int,
multipath_index: int = 0,
) -> str:
address = self.jade.get_receive_address(
self._network(),
multipath_index,
index,
descriptor_name=registered_descriptor.name,
)
return str(address)

# Setup a new device
def setup_device(self, label: str = "", passphrase: str = "") -> bool:
"""
Expand Down
28 changes: 28 additions & 0 deletions hwilib/devices/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,34 @@ def format_key_info(pubkey: PubkeyProvider) -> str:

return self.client.get_wallet_address(multisig_wallet, registered_hmac, change, address_index, True)

@ledger_exception
def display_bip388_policy_address(
self,
registered_descriptor: RegisteredDescriptor,
index: int,
multipath_index: int = 0,
) -> str:
if isinstance(self.client, LegacyClient):
raise BadArgumentError(
"Displaying a BIP388 policy address is not supported by this version of the Bitcoin App"
)

wallet_policy = WalletPolicy(
name=registered_descriptor.name,
descriptor_template=registered_descriptor.descriptor.get_bip388_template(),
keys_info=[
key.get_bip388_key_info()
for key in registered_descriptor.descriptor.get_pubkey_providers()
],
)
return self.client.get_wallet_address(
wallet_policy,
registered_descriptor.registration,
multipath_index,
index,
True,
)

def setup_device(self, label: str = "", passphrase: str = "") -> bool:
"""
Ledgers do not support setup via software.
Expand Down
12 changes: 12 additions & 0 deletions hwilib/hwwclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,18 @@ def display_multisig_address(
raise NotImplementedError("The HardwareWalletClient base class "
"does not implement this method")

def display_bip388_policy_address(
self,
registered_descriptor: RegisteredDescriptor,
index: int,
multipath_index: int = 0,
) -> str:
"""Display and return an address from a BIP388 descriptor policy."""

raise NotImplementedError(
"This device does not support BIP388 policy address display or it is not yet implemented"
)

def wipe_device(self) -> bool:
"""
Wipe the device.
Expand Down
3 changes: 1 addition & 2 deletions test/data/coldcard-multisig.patch
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ index 1e692d41..6294e9a3 100644
# return list of lists [xfp, *deriv]
- return list(self.xfp_paths.values())
+ ret = []
+ for paths_list in self.xfp_paths:
+ for paths_list in self.xfp_paths.values():
+ for xfp_path in paths_list:
+ ret.append(xfp_path)
+ return ret
Expand Down Expand Up @@ -111,4 +111,3 @@ index 1e692d41..6294e9a3 100644
return True
--
2.51.0

42 changes: 24 additions & 18 deletions test/data/speculos-automation.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,43 @@
"text": "Confirm",
"x": 43, "y": 37,
"actions": [
[ "button", 1, true ],
[ "button", 2, true ],
[ "button", 1, false ],
[ "button", 2, false ]
[ "button", 3, true ],
[ "button", 3, false ]
]
},
{
"text": "Confirm",
"x": 41, "y": 34,
"actions": [
[ "button", 1, true ],
[ "button", 3, true ],
[ "button", 3, false ]
]
},
{
"text": "Confirm account ",
"actions": [
[ "button", 3, true ],
[ "button", 3, false ]
]
},
{
"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).*",
"actions": [
[ "button", 2, true ],
[ "button", 1, false ],
[ "button", 2, false ]
]
},
{
"text": "Confirm account ",
"regexp": "^Fee.*",
"y": 3,
"actions": [
[ "button", 1, true ],
[ "button", 2, true ],
[ "button", 1, false ],
[ "button", 2, false ]
]
},
{
"regexp": "^(Address|Review|Account name|Amount|External amounts|You spend|You receive|Fee|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": "^Fees$",
"y": 7,
"actions": [
[ "button", 2, true ],
[ "button", 2, false ]
Expand All @@ -63,10 +73,8 @@
{
"regexp": "^(Accept|Approve|Continue|Sign message|Sign transaction|Register account).*",
"actions": [
[ "button", 1, true ],
[ "button", 2, true ],
[ "button", 1, false ],
[ "button", 2, false ]
[ "button", 3, true ],
[ "button", 3, false ]
]
},
{
Expand Down Expand Up @@ -102,10 +110,8 @@
[ "seen_msg_hash", true ]
],
"actions": [
[ "button", 1, true ],
[ "button", 2, true ],
[ "button", 1, false ],
[ "button", 2, false ],
[ "button", 3, true ],
[ "button", 3, false ],
[ "setbool", "seen_msg_hash", false ]
]
}
Expand Down
Loading