github.com/nisdas/go-ethereum@v1.9.7/accounts/usbwallet/ledger.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // This file contains the implementation for interacting with the Ledger hardware 18 // wallets. The wire protocol spec can be found in the Ledger Blue GitHub repo: 19 // https://raw.githubusercontent.com/LedgerHQ/blue-app-eth/master/doc/ethapp.asc 20 21 package usbwallet 22 23 import ( 24 "encoding/binary" 25 "encoding/hex" 26 "errors" 27 "fmt" 28 "io" 29 "math/big" 30 31 "github.com/ethereum/go-ethereum/accounts" 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/hexutil" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/crypto" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/rlp" 38 ) 39 40 // ledgerOpcode is an enumeration encoding the supported Ledger opcodes. 41 type ledgerOpcode byte 42 43 // ledgerParam1 is an enumeration encoding the supported Ledger parameters for 44 // specific opcodes. The same parameter values may be reused between opcodes. 45 type ledgerParam1 byte 46 47 // ledgerParam2 is an enumeration encoding the supported Ledger parameters for 48 // specific opcodes. The same parameter values may be reused between opcodes. 49 type ledgerParam2 byte 50 51 const ( 52 ledgerOpRetrieveAddress ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path 53 ledgerOpSignTransaction ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters 54 ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration 55 56 ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet 57 ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing 58 ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing 59 ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address 60 ) 61 62 // errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange 63 // if the device replies with a mismatching header. This usually means the device 64 // is in browser mode. 65 var errLedgerReplyInvalidHeader = errors.New("ledger: invalid reply header") 66 67 // errLedgerInvalidVersionReply is the error message returned by a Ledger version retrieval 68 // when a response does arrive, but it does not contain the expected data. 69 var errLedgerInvalidVersionReply = errors.New("ledger: invalid version reply") 70 71 // ledgerDriver implements the communication with a Ledger hardware wallet. 72 type ledgerDriver struct { 73 device io.ReadWriter // USB device connection to communicate through 74 version [3]byte // Current version of the Ledger firmware (zero if app is offline) 75 browser bool // Flag whether the Ledger is in browser mode (reply channel mismatch) 76 failure error // Any failure that would make the device unusable 77 log log.Logger // Contextual logger to tag the ledger with its id 78 } 79 80 // newLedgerDriver creates a new instance of a Ledger USB protocol driver. 81 func newLedgerDriver(logger log.Logger) driver { 82 return &ledgerDriver{ 83 log: logger, 84 } 85 } 86 87 // Status implements usbwallet.driver, returning various states the Ledger can 88 // currently be in. 89 func (w *ledgerDriver) Status() (string, error) { 90 if w.failure != nil { 91 return fmt.Sprintf("Failed: %v", w.failure), w.failure 92 } 93 if w.browser { 94 return "Ethereum app in browser mode", w.failure 95 } 96 if w.offline() { 97 return "Ethereum app offline", w.failure 98 } 99 return fmt.Sprintf("Ethereum app v%d.%d.%d online", w.version[0], w.version[1], w.version[2]), w.failure 100 } 101 102 // offline returns whether the wallet and the Ethereum app is offline or not. 103 // 104 // The method assumes that the state lock is held! 105 func (w *ledgerDriver) offline() bool { 106 return w.version == [3]byte{0, 0, 0} 107 } 108 109 // Open implements usbwallet.driver, attempting to initialize the connection to the 110 // Ledger hardware wallet. The Ledger does not require a user passphrase, so that 111 // parameter is silently discarded. 112 func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error { 113 w.device, w.failure = device, nil 114 115 _, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath) 116 if err != nil { 117 // Ethereum app is not running or in browser mode, nothing more to do, return 118 if err == errLedgerReplyInvalidHeader { 119 w.browser = true 120 } 121 return nil 122 } 123 // Try to resolve the Ethereum app's version, will fail prior to v1.0.2 124 if w.version, err = w.ledgerVersion(); err != nil { 125 w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1 126 } 127 return nil 128 } 129 130 // Close implements usbwallet.driver, cleaning up and metadata maintained within 131 // the Ledger driver. 132 func (w *ledgerDriver) Close() error { 133 w.browser, w.version = false, [3]byte{} 134 return nil 135 } 136 137 // Heartbeat implements usbwallet.driver, performing a sanity check against the 138 // Ledger to see if it's still online. 139 func (w *ledgerDriver) Heartbeat() error { 140 if _, err := w.ledgerVersion(); err != nil && err != errLedgerInvalidVersionReply { 141 w.failure = err 142 return err 143 } 144 return nil 145 } 146 147 // Derive implements usbwallet.driver, sending a derivation request to the Ledger 148 // and returning the Ethereum address located on that derivation path. 149 func (w *ledgerDriver) Derive(path accounts.DerivationPath) (common.Address, error) { 150 return w.ledgerDerive(path) 151 } 152 153 // SignTx implements usbwallet.driver, sending the transaction to the Ledger and 154 // waiting for the user to confirm or deny the transaction. 155 // 156 // Note, if the version of the Ethereum application running on the Ledger wallet is 157 // too old to sign EIP-155 transactions, but such is requested nonetheless, an error 158 // will be returned opposed to silently signing in Homestead mode. 159 func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) { 160 // If the Ethereum app doesn't run, abort 161 if w.offline() { 162 return common.Address{}, nil, accounts.ErrWalletClosed 163 } 164 // Ensure the wallet is capable of signing the given transaction 165 if chainID != nil && w.version[0] <= 1 && w.version[1] <= 0 && w.version[2] <= 2 { 166 return common.Address{}, nil, fmt.Errorf("Ledger v%d.%d.%d doesn't support signing this transaction, please update to v1.0.3 at least", w.version[0], w.version[1], w.version[2]) 167 } 168 // All infos gathered and metadata checks out, request signing 169 return w.ledgerSign(path, tx, chainID) 170 } 171 172 // ledgerVersion retrieves the current version of the Ethereum wallet app running 173 // on the Ledger wallet. 174 // 175 // The version retrieval protocol is defined as follows: 176 // 177 // CLA | INS | P1 | P2 | Lc | Le 178 // ----+-----+----+----+----+--- 179 // E0 | 06 | 00 | 00 | 00 | 04 180 // 181 // With no input data, and the output data being: 182 // 183 // Description | Length 184 // ---------------------------------------------------+-------- 185 // Flags 01: arbitrary data signature enabled by user | 1 byte 186 // Application major version | 1 byte 187 // Application minor version | 1 byte 188 // Application patch version | 1 byte 189 func (w *ledgerDriver) ledgerVersion() ([3]byte, error) { 190 // Send the request and wait for the response 191 reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil) 192 if err != nil { 193 return [3]byte{}, err 194 } 195 if len(reply) != 4 { 196 return [3]byte{}, errLedgerInvalidVersionReply 197 } 198 // Cache the version for future reference 199 var version [3]byte 200 copy(version[:], reply[1:]) 201 return version, nil 202 } 203 204 // ledgerDerive retrieves the currently active Ethereum address from a Ledger 205 // wallet at the specified derivation path. 206 // 207 // The address derivation protocol is defined as follows: 208 // 209 // CLA | INS | P1 | P2 | Lc | Le 210 // ----+-----+----+----+-----+--- 211 // E0 | 02 | 00 return address 212 // 01 display address and confirm before returning 213 // | 00: do not return the chain code 214 // | 01: return the chain code 215 // | var | 00 216 // 217 // Where the input data is: 218 // 219 // Description | Length 220 // -------------------------------------------------+-------- 221 // Number of BIP 32 derivations to perform (max 10) | 1 byte 222 // First derivation index (big endian) | 4 bytes 223 // ... | 4 bytes 224 // Last derivation index (big endian) | 4 bytes 225 // 226 // And the output data is: 227 // 228 // Description | Length 229 // ------------------------+------------------- 230 // Public Key length | 1 byte 231 // Uncompressed Public Key | arbitrary 232 // Ethereum address length | 1 byte 233 // Ethereum address | 40 bytes hex ascii 234 // Chain code if requested | 32 bytes 235 func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) { 236 // Flatten the derivation path into the Ledger request 237 path := make([]byte, 1+4*len(derivationPath)) 238 path[0] = byte(len(derivationPath)) 239 for i, component := range derivationPath { 240 binary.BigEndian.PutUint32(path[1+4*i:], component) 241 } 242 // Send the request and wait for the response 243 reply, err := w.ledgerExchange(ledgerOpRetrieveAddress, ledgerP1DirectlyFetchAddress, ledgerP2DiscardAddressChainCode, path) 244 if err != nil { 245 return common.Address{}, err 246 } 247 // Discard the public key, we don't need that for now 248 if len(reply) < 1 || len(reply) < 1+int(reply[0]) { 249 return common.Address{}, errors.New("reply lacks public key entry") 250 } 251 reply = reply[1+int(reply[0]):] 252 253 // Extract the Ethereum hex address string 254 if len(reply) < 1 || len(reply) < 1+int(reply[0]) { 255 return common.Address{}, errors.New("reply lacks address entry") 256 } 257 hexstr := reply[1 : 1+int(reply[0])] 258 259 // Decode the hex sting into an Ethereum address and return 260 var address common.Address 261 if _, err = hex.Decode(address[:], hexstr); err != nil { 262 return common.Address{}, err 263 } 264 return address, nil 265 } 266 267 // ledgerSign sends the transaction to the Ledger wallet, and waits for the user 268 // to confirm or deny the transaction. 269 // 270 // The transaction signing protocol is defined as follows: 271 // 272 // CLA | INS | P1 | P2 | Lc | Le 273 // ----+-----+----+----+-----+--- 274 // E0 | 04 | 00: first transaction data block 275 // 80: subsequent transaction data block 276 // | 00 | variable | variable 277 // 278 // Where the input for the first transaction block (first 255 bytes) is: 279 // 280 // Description | Length 281 // -------------------------------------------------+---------- 282 // Number of BIP 32 derivations to perform (max 10) | 1 byte 283 // First derivation index (big endian) | 4 bytes 284 // ... | 4 bytes 285 // Last derivation index (big endian) | 4 bytes 286 // RLP transaction chunk | arbitrary 287 // 288 // And the input for subsequent transaction blocks (first 255 bytes) are: 289 // 290 // Description | Length 291 // ----------------------+---------- 292 // RLP transaction chunk | arbitrary 293 // 294 // And the output data is: 295 // 296 // Description | Length 297 // ------------+--------- 298 // signature V | 1 byte 299 // signature R | 32 bytes 300 // signature S | 32 bytes 301 func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) { 302 // Flatten the derivation path into the Ledger request 303 path := make([]byte, 1+4*len(derivationPath)) 304 path[0] = byte(len(derivationPath)) 305 for i, component := range derivationPath { 306 binary.BigEndian.PutUint32(path[1+4*i:], component) 307 } 308 // Create the transaction RLP based on whether legacy or EIP155 signing was requested 309 var ( 310 txrlp []byte 311 err error 312 ) 313 if chainID == nil { 314 if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil { 315 return common.Address{}, nil, err 316 } 317 } else { 318 if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), chainID, big.NewInt(0), big.NewInt(0)}); err != nil { 319 return common.Address{}, nil, err 320 } 321 } 322 payload := append(path, txrlp...) 323 324 // Send the request and wait for the response 325 var ( 326 op = ledgerP1InitTransactionData 327 reply []byte 328 ) 329 for len(payload) > 0 { 330 // Calculate the size of the next data chunk 331 chunk := 255 332 if chunk > len(payload) { 333 chunk = len(payload) 334 } 335 // Send the chunk over, ensuring it's processed correctly 336 reply, err = w.ledgerExchange(ledgerOpSignTransaction, op, 0, payload[:chunk]) 337 if err != nil { 338 return common.Address{}, nil, err 339 } 340 // Shift the payload and ensure subsequent chunks are marked as such 341 payload = payload[chunk:] 342 op = ledgerP1ContTransactionData 343 } 344 // Extract the Ethereum signature and do a sanity validation 345 if len(reply) != crypto.SignatureLength { 346 return common.Address{}, nil, errors.New("reply lacks signature") 347 } 348 signature := append(reply[1:], reply[0]) 349 350 // Create the correct signer and signature transform based on the chain ID 351 var signer types.Signer 352 if chainID == nil { 353 signer = new(types.HomesteadSigner) 354 } else { 355 signer = types.NewEIP155Signer(chainID) 356 signature[64] -= byte(chainID.Uint64()*2 + 35) 357 } 358 signed, err := tx.WithSignature(signer, signature) 359 if err != nil { 360 return common.Address{}, nil, err 361 } 362 sender, err := types.Sender(signer, signed) 363 if err != nil { 364 return common.Address{}, nil, err 365 } 366 return sender, signed, nil 367 } 368 369 // ledgerExchange performs a data exchange with the Ledger wallet, sending it a 370 // message and retrieving the response. 371 // 372 // The common transport header is defined as follows: 373 // 374 // Description | Length 375 // --------------------------------------+---------- 376 // Communication channel ID (big endian) | 2 bytes 377 // Command tag | 1 byte 378 // Packet sequence index (big endian) | 2 bytes 379 // Payload | arbitrary 380 // 381 // The Communication channel ID allows commands multiplexing over the same 382 // physical link. It is not used for the time being, and should be set to 0101 383 // to avoid compatibility issues with implementations ignoring a leading 00 byte. 384 // 385 // The Command tag describes the message content. Use TAG_APDU (0x05) for standard 386 // APDU payloads, or TAG_PING (0x02) for a simple link test. 387 // 388 // The Packet sequence index describes the current sequence for fragmented payloads. 389 // The first fragment index is 0x00. 390 // 391 // APDU Command payloads are encoded as follows: 392 // 393 // Description | Length 394 // ----------------------------------- 395 // APDU length (big endian) | 2 bytes 396 // APDU CLA | 1 byte 397 // APDU INS | 1 byte 398 // APDU P1 | 1 byte 399 // APDU P2 | 1 byte 400 // APDU length | 1 byte 401 // Optional APDU data | arbitrary 402 func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) { 403 // Construct the message payload, possibly split into multiple chunks 404 apdu := make([]byte, 2, 7+len(data)) 405 406 binary.BigEndian.PutUint16(apdu, uint16(5+len(data))) 407 apdu = append(apdu, []byte{0xe0, byte(opcode), byte(p1), byte(p2), byte(len(data))}...) 408 apdu = append(apdu, data...) 409 410 // Stream all the chunks to the device 411 header := []byte{0x01, 0x01, 0x05, 0x00, 0x00} // Channel ID and command tag appended 412 chunk := make([]byte, 64) 413 space := len(chunk) - len(header) 414 415 for i := 0; len(apdu) > 0; i++ { 416 // Construct the new message to stream 417 chunk = append(chunk[:0], header...) 418 binary.BigEndian.PutUint16(chunk[3:], uint16(i)) 419 420 if len(apdu) > space { 421 chunk = append(chunk, apdu[:space]...) 422 apdu = apdu[space:] 423 } else { 424 chunk = append(chunk, apdu...) 425 apdu = nil 426 } 427 // Send over to the device 428 w.log.Trace("Data chunk sent to the Ledger", "chunk", hexutil.Bytes(chunk)) 429 if _, err := w.device.Write(chunk); err != nil { 430 return nil, err 431 } 432 } 433 // Stream the reply back from the wallet in 64 byte chunks 434 var reply []byte 435 chunk = chunk[:64] // Yeah, we surely have enough space 436 for { 437 // Read the next chunk from the Ledger wallet 438 if _, err := io.ReadFull(w.device, chunk); err != nil { 439 return nil, err 440 } 441 w.log.Trace("Data chunk received from the Ledger", "chunk", hexutil.Bytes(chunk)) 442 443 // Make sure the transport header matches 444 if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 { 445 return nil, errLedgerReplyInvalidHeader 446 } 447 // If it's the first chunk, retrieve the total message length 448 var payload []byte 449 450 if chunk[3] == 0x00 && chunk[4] == 0x00 { 451 reply = make([]byte, 0, int(binary.BigEndian.Uint16(chunk[5:7]))) 452 payload = chunk[7:] 453 } else { 454 payload = chunk[5:] 455 } 456 // Append to the reply and stop when filled up 457 if left := cap(reply) - len(reply); left > len(payload) { 458 reply = append(reply, payload...) 459 } else { 460 reply = append(reply, payload[:left]...) 461 break 462 } 463 } 464 return reply[:len(reply)-2], nil 465 }