Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/type-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ jobs:
hwilib/devices/__init__.py
hwilib/devices/keepkey.py
hwilib/devices/ledger.py
hwilib/devices/ledger_registration.py
hwilib/devices/trezor.py
hwilib/errors.py
hwilib/_script.py
Expand All @@ -40,4 +41,5 @@ jobs:
hwilib/hwwclient.py
hwilib/__init__.py
hwilib/key.py
hwilib/policy.py
hwilib/udevinstaller.py
11 changes: 11 additions & 0 deletions hwilib/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
getdescriptors,
prompt_pin,
toggle_passphrase,
register,
restore_device,
send_pin,
setup_device,
Expand All @@ -24,6 +25,7 @@
AddressType,
Chain,
)
from .policy import BIP388Policy
from .errors import (
handle_errors,
DEVICE_CONN_ERROR,
Expand Down Expand Up @@ -59,6 +61,10 @@ def backup_device_handler(args: argparse.Namespace, client: HardwareWalletClient
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 register_handler(args: argparse.Namespace, client: HardwareWalletClient) -> Dict[str, Optional[str]]:
policy = BIP388Policy.from_descriptor(name=args.name, descriptor=args.desc)
return register(client, bip388_policy=policy)

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 @@ -197,6 +203,11 @@ def get_parser() -> HWIArgumentParser:
displayaddr_parser.add_argument("--addr-type", help="The address type to display", type=AddressType.argparse, choices=list(AddressType), default=AddressType.WIT) # type: ignore
displayaddr_parser.set_defaults(func=displayaddress_handler)

register_parser = subparsers.add_parser('register', help='Register a BIP388 wallet policy')
register_parser.add_argument('--name', help='Name for the policy', required=True)
register_parser.add_argument('--desc', help='Combined multipath output descriptor', required=True)
register_parser.set_defaults(func=register_handler)

setupdev_parser = subparsers.add_parser('setup', help='Setup a device. Passphrase protection uses the password given by -p. Requires interactive mode')
setupdev_parser.add_argument('--label', '-l', help='The name to give to the device', default='')
setupdev_parser.add_argument('--backup_passphrase', '-b', help='The passphrase to use for the backup, if applicable', default='')
Expand Down
11 changes: 11 additions & 0 deletions hwilib/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
Chain,
)
from .hwwclient import HardwareWalletClient
from .policy import BIP388Policy
from .psbt import PSBT

from itertools import count
Expand Down Expand Up @@ -494,6 +495,16 @@ def displayaddress(
return {"address": client.display_singlesig_address(pubkey.get_full_derivation_path(0), addr_type)}
raise BadArgumentError("Missing both path and descriptor")

def register(
client: HardwareWalletClient,
bip388_policy: BIP388Policy,
) -> Dict[str, Optional[str]]:
"""Register a BIP388 policy on the device."""

if bip388_policy.registration is not None:
raise BadArgumentError("A policy being registered cannot already have a registration")
return {"registration": client.register_bip388_policy(bip388_policy)}

def setup_device(client: HardwareWalletClient, label: str = "", backup_passphrase: str = "") -> Dict[str, bool]:
"""
Setup a device that has not yet been initialized.
Expand Down
2 changes: 0 additions & 2 deletions hwilib/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

from typing import Union


class Chain(Enum):
"""
The blockchain network to use
Expand Down Expand Up @@ -56,7 +55,6 @@ def argparse(s: str) -> Union['AddressType', str]:
except KeyError:
return s


def sha256(s: bytes) -> bytes:
"""
Perform a single SHA256 hash.
Expand Down
60 changes: 59 additions & 1 deletion hwilib/devices/bitbox02.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from functools import wraps

from .._base58 import decode_check, encode_check
from ..descriptor import MultisigDescriptor
from ..descriptor import MultisigDescriptor, PubkeyProvider
from ..hwwclient import HardwareWalletClient
from ..key import ExtendedKey
from .._script import (
Expand Down Expand Up @@ -59,6 +59,7 @@
AddressType,
Chain,
)
from ..policy import BIP388Policy

import hid

Expand Down Expand Up @@ -438,6 +439,63 @@ def _maybe_register_script_config(
xpub_type=bitbox02.btc.BTCRegisterScriptConfigRequest.AUTO_XPUB_TPUB,
)

def _bip388_script_config(
self,
bip388_policy: BIP388Policy,
) -> Tuple[bitbox02.btc.BTCScriptConfig, Sequence[int]]:
device_fingerprint = self.get_master_fingerprint()
our_keypath: Optional[Sequence[int]] = None
keys = []

for key_info in bip388_policy.keys_info:
pubkey = PubkeyProvider.parse(key_info)
if pubkey.extkey is None or pubkey.extkey.is_private or pubkey.deriv_path is not None:
raise BadArgumentError("Invalid BIP388 key information")

origin = pubkey.origin
keys.append(
bitbox02.common.KeyOriginInfo(
root_fingerprint=b"" if origin is None else origin.fingerprint,
keypath=[] if origin is None else origin.path,
xpub=util.parse_xpub(pubkey.extkey.to_string()),
)
)

if origin is not None and origin.fingerprint == device_fingerprint:
device_xpub = decode_check(self._get_xpub(origin.path))
if _xpubs_equal_ignoring_version(device_xpub, pubkey.extkey.serialize()):
if our_keypath is not None:
raise BadArgumentError("This BitBox02 occurs more than once in the policy")
our_keypath = origin.path

if our_keypath is None:
raise BadArgumentError("This BitBox02 is not one of the policy keys")

return (
bitbox02.btc.BTCScriptConfig(
policy=bitbox02.btc.BTCScriptConfig.Policy(
policy=bip388_policy.descriptor_template,
keys=keys,
)
),
our_keypath,
)

@bitbox02_exception
def register_bip388_policy(
self,
bip388_policy: BIP388Policy,
) -> Optional[str]:
script_config, keypath = self._bip388_script_config(bip388_policy)
self.init().btc_register_script_config(
coin=self._get_coin(),
script_config=script_config,
keypath=keypath,
name=bip388_policy.name,
xpub_type=bitbox02.btc.BTCRegisterScriptConfigRequest.AUTO_XPUB_TPUB,
)
return None

def _multisig_scriptconfig(
self,
threshold: int,
Expand Down
20 changes: 20 additions & 0 deletions hwilib/devices/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
AddressType,
Chain,
)
from ..policy import BIP388Policy
from .ledger_registration import encode_policy_registration
from .ledger_bitcoin.client import (
createClient,
NewClient,
Expand Down Expand Up @@ -482,6 +484,24 @@ def format_key_info(pubkey: PubkeyProvider) -> str:

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

@ledger_exception
def register_bip388_policy(
self,
bip388_policy: BIP388Policy,
) -> Optional[str]:
if isinstance(self.client, LegacyClient):
raise BadArgumentError(
"Registering a BIP388 policy is not supported by this version of the Bitcoin App"
)

wallet_policy = WalletPolicy(
name=bip388_policy.name,
descriptor_template=bip388_policy.descriptor_template,
keys_info=bip388_policy.keys_info,
)
_, registration = self.client.register_wallet(wallet_policy)
return encode_policy_registration(registration, bip388_policy.name)

def setup_device(self, label: str = "", passphrase: str = "") -> bool:
"""
Ledgers do not support setup via software.
Expand Down
51 changes: 51 additions & 0 deletions hwilib/devices/ledger_registration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Encoding helpers for opaque Ledger policy registrations."""

from typing import List, Sequence, Tuple

from ..errors import BadArgumentError


def _encode_fields(fields: Sequence[bytes]) -> bytes:
encoded = bytearray()
for field in fields:
if len(field) > 255:
raise BadArgumentError("Ledger policy registration fields cannot exceed 255 bytes")
encoded.append(len(field))
encoded.extend(field)
return bytes(encoded)


def _decode_fields(encoded: bytes) -> List[bytes]:
fields: List[bytes] = []
offset = 0
while offset < len(encoded):
field_length = encoded[offset]
offset += 1
field_end = offset + field_length
if field_end > len(encoded):
raise BadArgumentError("Invalid Ledger policy registration")
fields.append(encoded[offset:field_end])
offset = field_end
return fields


def encode_policy_registration(device_registration: bytes, policy_name: str) -> str:
"""Encode the device registration and policy name as an opaque hex string."""

try:
name = policy_name.encode("latin-1")
except UnicodeEncodeError as exc:
raise BadArgumentError("Ledger policy names must use Latin-1 characters") from exc
return _encode_fields([device_registration, name]).hex()


def decode_policy_registration(registration: str) -> Tuple[bytes, str]:
"""Decode the device registration and policy name from an opaque hex string."""

try:
fields = _decode_fields(bytes.fromhex(registration))
except ValueError as exc:
raise BadArgumentError("Invalid Ledger policy registration") from exc
if len(fields) < 2:
raise BadArgumentError("Invalid Ledger policy registration")
return fields[0], fields[1].decode("latin-1")
16 changes: 15 additions & 1 deletion hwilib/hwwclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
get_bip44_chain,
)
from .psbt import PSBT
from .common import AddressType, Chain
from .common import (
AddressType,
Chain,
)
from .policy import BIP388Policy


class HardwareWalletClient(object):
Expand Down Expand Up @@ -135,6 +139,16 @@ def display_multisig_address(
raise NotImplementedError("The HardwareWalletClient base class "
"does not implement this method")

def register_bip388_policy(
self,
bip388_policy: BIP388Policy,
) -> Optional[str]:
"""Register a BIP388 policy and return an opaque registration, if any."""

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

def wipe_device(self) -> bool:
"""
Wipe the device.
Expand Down
Loading
Loading