|
| 1 | +import atexit |
1 | 2 | import json |
2 | 3 | import os |
| 4 | +import sys |
3 | 5 | from typing import Protocol, cast |
4 | 6 |
|
| 7 | +import trezorlib.ethereum as trezor_eth |
5 | 8 | from eth_account.account import Account |
6 | 9 | from eth_account.datastructures import SignedTransaction |
7 | 10 | from eth_account.messages import encode_defunct |
8 | 11 | from eth_account.signers.local import LocalAccount |
9 | 12 | from eth_account.types import TransactionDictType |
| 13 | +from eth_account._utils.legacy_transactions import ( |
| 14 | + encode_transaction, |
| 15 | + serializable_unsigned_transaction_from_dict, |
| 16 | +) |
10 | 17 | from eth_typing.evm import ChecksumAddress |
| 18 | +from eth_utils.conversions import to_int |
| 19 | +from eth_utils.crypto import keccak |
11 | 20 | from hexbytes import HexBytes |
| 21 | +from trezorlib.client import TrezorClient |
| 22 | +from trezorlib.client import get_default_client # type: ignore |
| 23 | +from trezorlib.ui import TrezorClientUI |
| 24 | +from trezorlib.tools import parse_path |
| 25 | +from trezorlib.transport import DeviceIsBusy |
| 26 | +from web3 import Web3 |
12 | 27 | from web3.constants import CHECKSUM_ADDRESSS_ZERO |
13 | 28 | from web3.types import TxParams |
14 | 29 |
|
| 30 | +from .constants import TREZOR_DEFAULT_PREFIX |
| 31 | +from .exceptions import DeviceError |
| 32 | + |
15 | 33 |
|
16 | 34 | class Authenticator(Protocol): |
17 | 35 | address: ChecksumAddress |
@@ -69,12 +87,154 @@ class KeyfileAuthenticator(PrivateKeyAuthenticator): |
69 | 87 | key_file : str |
70 | 88 | The path to the keyfile. |
71 | 89 | password : str |
72 | | - The password for decrypting the keyfile. |
| 90 | + The password for decrypting the keyfile. Defaults to no password. |
73 | 91 | """ |
74 | 92 |
|
75 | | - def __init__(self, key_file: str, password: str) -> None: |
| 93 | + def __init__(self, key_file: str, password: str = "") -> None: |
76 | 94 | with open(os.path.expanduser(key_file), encoding="utf8") as f: |
77 | 95 | key_data = json.load(f) |
78 | 96 |
|
79 | 97 | private_key = Account.decrypt(key_data, password=password) |
80 | 98 | super().__init__(private_key.to_0x_hex()) |
| 99 | + |
| 100 | + |
| 101 | +class TrezorAuthenticator(Authenticator): |
| 102 | + """Authenticates with a Trezor device. |
| 103 | +
|
| 104 | + Parameters |
| 105 | + ---------- |
| 106 | + path_or_index: str or int |
| 107 | + The full derivation path of the account, e.g. `m/44'/60'/0'/0/123`; or the |
| 108 | + index of the account at the default Trezor derivation prefix for Ethereum |
| 109 | + accounts `m/44'/60'/0'/0`, e.g. `123`. |
| 110 | + passphrase: str |
| 111 | + The passphrase for the Trezor device. Defaults to no passphrase. |
| 112 | + """ |
| 113 | + |
| 114 | + client: TrezorClient[TrezorClientUI] |
| 115 | + |
| 116 | + def __init__(self, path_or_index: str | int, passphrase: str = ""): |
| 117 | + if isinstance(path_or_index, int) or path_or_index.isdigit(): |
| 118 | + path_str = f"{TREZOR_DEFAULT_PREFIX}/{int(path_or_index)}" |
| 119 | + else: |
| 120 | + path_str = path_or_index.replace("'", "h") |
| 121 | + try: |
| 122 | + self.path = parse_path(path_str) |
| 123 | + except ValueError as exc: |
| 124 | + raise DeviceError( |
| 125 | + f"Invalid Trezor BIP32 derivation path '{path_str}'" |
| 126 | + ) from exc |
| 127 | + self.client = self._get_client(passphrase) |
| 128 | + atexit.register(self.client.end_session) |
| 129 | + |
| 130 | + address_str = trezor_eth.get_address( # type: ignore |
| 131 | + self.client, self.path |
| 132 | + ) |
| 133 | + self.address = Web3.to_checksum_address(address_str) |
| 134 | + |
| 135 | + def sign_transaction(self, params: TxParams) -> SignedTransaction: |
| 136 | + assert "chainId" in params |
| 137 | + assert "gas" in params |
| 138 | + assert "nonce" in params |
| 139 | + assert "to" in params |
| 140 | + assert "value" in params |
| 141 | + data_bytes = HexBytes(params["data"] if "data" in params else b"") |
| 142 | + |
| 143 | + print("[Confirm on Trezor device]", file=sys.stderr) |
| 144 | + |
| 145 | + if "gasPrice" in params and params["gasPrice"]: |
| 146 | + v_int, r_bytes, s_bytes = trezor_eth.sign_tx( # type: ignore |
| 147 | + self.client, |
| 148 | + self.path, |
| 149 | + nonce=cast(int, params["nonce"]), |
| 150 | + gas_price=cast(int, params["gasPrice"]), |
| 151 | + gas_limit=params["gas"], |
| 152 | + to=cast(str, params["to"]), |
| 153 | + value=cast(int, params["value"]), |
| 154 | + data=data_bytes, |
| 155 | + chain_id=params["chainId"], |
| 156 | + ) |
| 157 | + else: |
| 158 | + assert "maxFeePerGas" in params |
| 159 | + assert "maxPriorityFeePerGas" in params |
| 160 | + v_int, r_bytes, s_bytes = trezor_eth.sign_tx_eip1559( # type: ignore |
| 161 | + self.client, |
| 162 | + self.path, |
| 163 | + nonce=cast(int, params["nonce"]), |
| 164 | + gas_limit=params["gas"], |
| 165 | + to=cast(str, params["to"]), |
| 166 | + value=cast(int, params["value"]), |
| 167 | + data=data_bytes, |
| 168 | + chain_id=params["chainId"], |
| 169 | + max_gas_fee=int(params["maxFeePerGas"]), |
| 170 | + max_priority_fee=int(params["maxPriorityFeePerGas"]), |
| 171 | + ) |
| 172 | + |
| 173 | + r_int = to_int(r_bytes) |
| 174 | + s_int = to_int(s_bytes) |
| 175 | + filtered_tx = dict((k, v) for (k, v) in params.items() if k not in ("from")) |
| 176 | + # In a LegacyTransaction, "type" is not a valid field. See EIP-2718. |
| 177 | + if "type" in filtered_tx and filtered_tx["type"] == "0x0": |
| 178 | + filtered_tx.pop("type") |
| 179 | + tx_unsigned = serializable_unsigned_transaction_from_dict( |
| 180 | + cast(TransactionDictType, filtered_tx) |
| 181 | + ) |
| 182 | + tx_encoded = encode_transaction(tx_unsigned, vrs=(v_int, r_int, s_int)) |
| 183 | + txhash = keccak(tx_encoded) |
| 184 | + return SignedTransaction( |
| 185 | + raw_transaction=HexBytes(tx_encoded), |
| 186 | + hash=HexBytes(txhash), |
| 187 | + r=r_int, |
| 188 | + s=s_int, |
| 189 | + v=v_int, |
| 190 | + ) |
| 191 | + |
| 192 | + def sign_message(self, message: bytes) -> HexBytes: |
| 193 | + print("[Confirm on Trezor device]", file=sys.stderr) |
| 194 | + |
| 195 | + sigdata = trezor_eth.sign_message( # type: ignore |
| 196 | + self.client, |
| 197 | + self.path, |
| 198 | + message.decode("utf-8"), |
| 199 | + ) |
| 200 | + return HexBytes(sigdata.signature) |
| 201 | + |
| 202 | + @staticmethod |
| 203 | + def _get_client( |
| 204 | + passphrase: str, |
| 205 | + ) -> TrezorClient[TrezorClientUI]: |
| 206 | + ui = _NonInteractiveTrezorUI(passphrase) |
| 207 | + try: |
| 208 | + return cast( |
| 209 | + TrezorClient[TrezorClientUI], |
| 210 | + get_default_client(ui=ui), |
| 211 | + ) |
| 212 | + except DeviceIsBusy as exc: |
| 213 | + raise DeviceError("Device in use by another process") from exc |
| 214 | + except Exception as exc: |
| 215 | + raise DeviceError( |
| 216 | + "No Trezor device found; " |
| 217 | + "check device is connected, unlocked, and detected by OS" |
| 218 | + ) from exc |
| 219 | + |
| 220 | + |
| 221 | +class _NonInteractiveTrezorUI(TrezorClientUI): |
| 222 | + """Replacement for the default TrezorClientUI of the Trezor library. |
| 223 | +
|
| 224 | + Bringing up an interactive passphrase prompt is unwanted in the SDK; |
| 225 | + this implementation receives the passphrase as constructor argument. |
| 226 | + """ |
| 227 | + |
| 228 | + _passphrase: str |
| 229 | + |
| 230 | + def __init__(self, passphrase: str) -> None: |
| 231 | + self._passphrase = passphrase |
| 232 | + |
| 233 | + def button_request(self, br: object) -> None: |
| 234 | + pass |
| 235 | + |
| 236 | + def get_pin(self, code: object) -> str: |
| 237 | + raise DeviceError("PIN entry on host is not supported") |
| 238 | + |
| 239 | + def get_passphrase(self, available_on_device: bool) -> str: |
| 240 | + return self._passphrase |
0 commit comments