Skip to content
Open
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
8 changes: 8 additions & 0 deletions hwilib/devices/trezor.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ def parse_multisig(script: bytes, tx_xpubs: Dict[bytes, KeyOriginInfo], psbt_sco
if op_cms != 174:
return (False, None)

script_keys = [pub.node.public_key for pub in pubkeys]

# check if we know corresponding xpubs from global scope
for pub in pubkeys:
if pub.node.public_key in psbt_scope.hd_keypaths:
Expand All @@ -165,6 +167,12 @@ def parse_multisig(script: bytes, tx_xpubs: Dict[bytes, KeyOriginInfo], psbt_sco
break
# Build MultisigRedeemScriptType and return it
multisig = messages.MultisigRedeemScriptType(m=m, signatures=[b''] * n, pubkeys=pubkeys)
# Keys in lexicographic order most likely come from sortedmulti(), where the order of
# the xpubs changes from one address to the next. Tell the device: otherwise it
# fingerprints the xpubs in the order given, the change's fingerprint differs from
# the inputs', and the change is shown as a payment.
if script_keys == sorted(script_keys):
multisig.pubkeys_order = messages.MultisigPubkeysOrder.LEXICOGRAPHIC
return (True, multisig)


Expand Down
8 changes: 8 additions & 0 deletions hwilib/devices/trezorlib/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ class AmountUnit(IntEnum):
SATOSHI = 3


class MultisigPubkeysOrder(IntEnum):
PRESERVED = 0
LEXICOGRAPHIC = 1


class RequestType(IntEnum):
TXINPUT = 0
TXOUTPUT = 1
Expand Down Expand Up @@ -396,6 +401,7 @@ class MultisigRedeemScriptType(protobuf.MessageType):
3: protobuf.Field("m", "uint32", repeated=False, required=True),
4: protobuf.Field("nodes", "HDNodeType", repeated=True, required=False),
5: protobuf.Field("address_n", "uint32", repeated=True, required=False),
6: protobuf.Field("pubkeys_order", "MultisigPubkeysOrder", repeated=False, required=False),
}

def __init__(
Expand All @@ -406,12 +412,14 @@ def __init__(
signatures: Optional[List["bytes"]] = None,
nodes: Optional[List["HDNodeType"]] = None,
address_n: Optional[List["int"]] = None,
pubkeys_order: Optional["MultisigPubkeysOrder"] = None,
) -> None:
self.pubkeys = pubkeys if pubkeys is not None else []
self.signatures = signatures if signatures is not None else []
self.nodes = nodes if nodes is not None else []
self.address_n = address_n if address_n is not None else []
self.m = m
self.pubkeys_order = pubkeys_order


class GetPublicKey(protobuf.MessageType):
Expand Down
3 changes: 2 additions & 1 deletion test/run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from test_descriptor import TestDescriptor
from test_device import Bitcoind
from test_psbt import TestPSBT
from test_trezor import trezor_test_suite
from test_trezor import trezor_test_suite, TestTrezorMultisig
from test_ledger import ledger_test_suite
from test_digitalbitbox import digitalbitbox_test_suite
from test_keepkey import keepkey_test_suite
Expand Down Expand Up @@ -90,6 +90,7 @@
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestBase58))
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestBIP32))
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestColdcardFirmware))
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestTrezorMultisig))
if sys.platform.startswith("linux"):
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestUdevRulesInstaller))
success = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful()
Expand Down
57 changes: 56 additions & 1 deletion test/test_trezor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import argparse
import atexit
import hashlib
import json
import os
import shlex
import signal
import socket
import struct
import subprocess
import sys
import time
Expand All @@ -28,7 +30,9 @@
)

from hwilib._cli import process_commands
from hwilib.devices.trezor import TrezorClient
from hwilib.devices.trezor import TrezorClient, parse_multisig
from hwilib.key import HARDENED_FLAG, ExtendedKey, KeyOriginInfo
from hwilib.psbt import PartiallySignedOutput

from types import MethodType

Expand Down Expand Up @@ -421,6 +425,57 @@ def test_passphrase(self):
else:
self.fail("Did not enumerate device")

def trezor_multisig_fingerprint(multisig):
# What the device compares to tell change from payments
# (multisig_fingerprint in core/src/apps/bitcoin/multisig.py)
order = multisig.pubkeys_order or messages.MultisigPubkeysOrder.PRESERVED
nodes = [p.node for p in multisig.pubkeys]
if order == messages.MultisigPubkeysOrder.LEXICOGRAPHIC:
nodes.sort(key=lambda n: n.public_key + n.chain_code)
h = hashlib.sha256(struct.pack("<III", multisig.m, len(nodes), order))
for n in nodes:
h.update(struct.pack("<III", n.depth, n.fingerprint, n.child_num) + n.chain_code + n.public_key)
return h.digest()

class TestTrezorMultisig(unittest.TestCase):
ORIGIN = [48 | HARDENED_FLAG, 1 | HARDENED_FLAG, HARDENED_FLAG, 2 | HARDENED_FLAG]

def setUp(self):
account = ExtendedKey.deserialize("tpubDCknDegFqAdP4V2AhHhs635DPe8N1aTjfKE9m2UFbdej8zmeNbtqDzK59SxnsYSRSx5uS3AujbwgANUiAk4oHmDNUKoGGkWWUY6c48WgjEx")
# Three cosigners, and the global xpubs a PSBT carries for them
self.cosigners = [(bytes([0, 0, 0, i]), account.derive_pub(i)) for i in range(1, 4)]
self.tx_xpubs = {xpub.serialize(): KeyOriginInfo(fp, self.ORIGIN) for fp, xpub in self.cosigners}

def multisig(self, branch, index, sort=True):
# parse_multisig() on the 2-of-3 script at <branch>/<index>, keys sorted or not
scope = PartiallySignedOutput(0)
keys = []
for fp, xpub in self.cosigners:
key = xpub.derive_pub_path([branch, index]).pubkey
scope.hd_keypaths[key] = KeyOriginInfo(fp, self.ORIGIN + [branch, index])
keys.append(key)
keys.sort(reverse=not sort)
script = b"\x52" + b"".join(b"\x21" + k for k in keys) + b"\x53\xae"
is_ms, multisig = parse_multisig(script, self.tx_xpubs, scope)
self.assertTrue(is_ms)
return multisig

def test_sortedmulti_change(self):
def xpub_order(multisig):
return [p.node.public_key for p in multisig.pubkeys]

receive = self.multisig(0, 0)
# A change address whose script lists the cosigners in another order
change = next(ms for ms in (self.multisig(1, i) for i in range(10)) if xpub_order(ms) != xpub_order(receive))
self.assertEqual(receive.pubkeys_order, messages.MultisigPubkeysOrder.LEXICOGRAPHIC)
self.assertEqual(change.pubkeys_order, messages.MultisigPubkeysOrder.LEXICOGRAPHIC)
self.assertEqual(trezor_multisig_fingerprint(receive), trezor_multisig_fingerprint(change))

def test_unsorted_multi(self):
# multi() keeps the order of its keys, so the device has to as well
multisig = self.multisig(0, 0, sort=False)
self.assertNotEqual(multisig.pubkeys_order, messages.MultisigPubkeysOrder.LEXICOGRAPHIC)

def trezor_test_suite(emulator, bitcoind, interface, model):
assert model in TREZOR_MODELS
# Redirect stderr to /dev/null as it's super spammy
Expand Down