github.com/theQRL/go-zond@v0.1.1/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/theQRL/go-zond/accounts" 32 "github.com/theQRL/go-zond/common" 33 "github.com/theQRL/go-zond/common/hexutil" 34 "github.com/theQRL/go-zond/core/types" 35 "github.com/theQRL/go-zond/crypto" 36 "github.com/theQRL/go-zond/log" 37 "github.com/theQRL/go-zond/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 ledgerOpSignTypedMessage ledgerOpcode = 0x0c // Signs an Ethereum message following the EIP 712 specification 56 57 ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet 58 ledgerP1InitTypedMessageData ledgerParam1 = 0x00 // First chunk of Typed Message data 59 ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing 60 ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing 61 ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address 62 63 ledgerEip155Size int = 3 // Size of the EIP-155 chain_id,r,s in unsigned transactions 64 ) 65 66 // errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange 67 // if the device replies with a mismatching header. This usually means the device 68 // is in browser mode. 69 var errLedgerReplyInvalidHeader = errors.New("ledger: invalid reply header") 70 71 // errLedgerInvalidVersionReply is the error message returned by a Ledger version retrieval 72 // when a response does arrive, but it does not contain the expected data. 73 var errLedgerInvalidVersionReply = errors.New("ledger: invalid version reply") 74 75 // ledgerDriver implements the communication with a Ledger hardware wallet. 76 type ledgerDriver struct { 77 device io.ReadWriter // USB device connection to communicate through 78 version [3]byte // Current version of the Ledger firmware (zero if app is offline) 79 browser bool // Flag whether the Ledger is in browser mode (reply channel mismatch) 80 failure error // Any failure that would make the device unusable 81 log log.Logger // Contextual logger to tag the ledger with its id 82 } 83 84 // newLedgerDriver creates a new instance of a Ledger USB protocol driver. 85 func newLedgerDriver(logger log.Logger) driver { 86 return &ledgerDriver{ 87 log: logger, 88 } 89 } 90 91 // Status implements usbwallet.driver, returning various states the Ledger can 92 // currently be in. 93 func (w *ledgerDriver) Status() (string, error) { 94 if w.failure != nil { 95 return fmt.Sprintf("Failed: %v", w.failure), w.failure 96 } 97 if w.browser { 98 return "Ethereum app in browser mode", w.failure 99 } 100 if w.offline() { 101 return "Ethereum app offline", w.failure 102 } 103 return fmt.Sprintf("Ethereum app v%d.%d.%d online", w.version[0], w.version[1], w.version[2]), w.failure 104 } 105 106 // offline returns whether the wallet and the Ethereum app is offline or not. 107 // 108 // The method assumes that the state lock is held! 109 func (w *ledgerDriver) offline() bool { 110 return w.version == [3]byte{0, 0, 0} 111 } 112 113 // Open implements usbwallet.driver, attempting to initialize the connection to the 114 // Ledger hardware wallet. The Ledger does not require a user passphrase, so that 115 // parameter is silently discarded. 116 func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error { 117 w.device, w.failure = device, nil 118 119 _, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath) 120 if err != nil { 121 // Ethereum app is not running or in browser mode, nothing more to do, return 122 if err == errLedgerReplyInvalidHeader { 123 w.browser = true 124 } 125 return nil 126 } 127 // Try to resolve the Ethereum app's version, will fail prior to v1.0.2 128 if w.version, err = w.ledgerVersion(); err != nil { 129 w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1 130 } 131 return nil 132 } 133 134 // Close implements usbwallet.driver, cleaning up and metadata maintained within 135 // the Ledger driver. 136 func (w *ledgerDriver) Close() error { 137 w.browser, w.version = false, [3]byte{} 138 return nil 139 } 140 141 // Heartbeat implements usbwallet.driver, performing a sanity check against the 142 // Ledger to see if it's still online. 143 func (w *ledgerDriver) Heartbeat() error { 144 if _, err := w.ledgerVersion(); err != nil && err != errLedgerInvalidVersionReply { 145 w.failure = err 146 return err 147 } 148 return nil 149 } 150 151 // Derive implements usbwallet.driver, sending a derivation request to the Ledger 152 // and returning the Ethereum address located on that derivation path. 153 func (w *ledgerDriver) Derive(path accounts.DerivationPath) (common.Address, error) { 154 return w.ledgerDerive(path) 155 } 156 157 // SignTx implements usbwallet.driver, sending the transaction to the Ledger and 158 // waiting for the user to confirm or deny the transaction. 159 // 160 // Note, if the version of the Ethereum application running on the Ledger wallet is 161 // too old to sign EIP-155 transactions, but such is requested nonetheless, an error 162 // will be returned opposed to silently signing in Homestead mode. 163 func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) { 164 // If the Ethereum app doesn't run, abort 165 if w.offline() { 166 return common.Address{}, nil, accounts.ErrWalletClosed 167 } 168 // Ensure the wallet is capable of signing the given transaction 169 if chainID != nil && w.version[0] <= 1 && w.version[1] <= 0 && w.version[2] <= 2 { 170 //lint:ignore ST1005 brand name displayed on the console 171 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]) 172 } 173 // All infos gathered and metadata checks out, request signing 174 return w.ledgerSign(path, tx, chainID) 175 } 176 177 // SignTypedMessage implements usbwallet.driver, sending the message to the Ledger and 178 // waiting for the user to sign or deny the transaction. 179 // 180 // Note: this was introduced in the ledger 1.5.0 firmware 181 func (w *ledgerDriver) SignTypedMessage(path accounts.DerivationPath, domainHash []byte, messageHash []byte) ([]byte, error) { 182 // If the Ethereum app doesn't run, abort 183 if w.offline() { 184 return nil, accounts.ErrWalletClosed 185 } 186 // Ensure the wallet is capable of signing the given transaction 187 if w.version[0] < 1 && w.version[1] < 5 { 188 //lint:ignore ST1005 brand name displayed on the console 189 return nil, fmt.Errorf("Ledger version >= 1.5.0 required for EIP-712 signing (found version v%d.%d.%d)", w.version[0], w.version[1], w.version[2]) 190 } 191 // All infos gathered and metadata checks out, request signing 192 return w.ledgerSignTypedMessage(path, domainHash, messageHash) 193 } 194 195 // ledgerVersion retrieves the current version of the Ethereum wallet app running 196 // on the Ledger wallet. 197 // 198 // The version retrieval protocol is defined as follows: 199 // 200 // CLA | INS | P1 | P2 | Lc | Le 201 // ----+-----+----+----+----+--- 202 // E0 | 06 | 00 | 00 | 00 | 04 203 // 204 // With no input data, and the output data being: 205 // 206 // Description | Length 207 // ---------------------------------------------------+-------- 208 // Flags 01: arbitrary data signature enabled by user | 1 byte 209 // Application major version | 1 byte 210 // Application minor version | 1 byte 211 // Application patch version | 1 byte 212 func (w *ledgerDriver) ledgerVersion() ([3]byte, error) { 213 // Send the request and wait for the response 214 reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil) 215 if err != nil { 216 return [3]byte{}, err 217 } 218 if len(reply) != 4 { 219 return [3]byte{}, errLedgerInvalidVersionReply 220 } 221 // Cache the version for future reference 222 var version [3]byte 223 copy(version[:], reply[1:]) 224 return version, nil 225 } 226 227 // ledgerDerive retrieves the currently active Ethereum address from a Ledger 228 // wallet at the specified derivation path. 229 // 230 // The address derivation protocol is defined as follows: 231 // 232 // CLA | INS | P1 | P2 | Lc | Le 233 // ----+-----+----+----+-----+--- 234 // E0 | 02 | 00 return address 235 // 01 display address and confirm before returning 236 // | 00: do not return the chain code 237 // | 01: return the chain code 238 // | var | 00 239 // 240 // Where the input data is: 241 // 242 // Description | Length 243 // -------------------------------------------------+-------- 244 // Number of BIP 32 derivations to perform (max 10) | 1 byte 245 // First derivation index (big endian) | 4 bytes 246 // ... | 4 bytes 247 // Last derivation index (big endian) | 4 bytes 248 // 249 // And the output data is: 250 // 251 // Description | Length 252 // ------------------------+------------------- 253 // Public Key length | 1 byte 254 // Uncompressed Public Key | arbitrary 255 // Ethereum address length | 1 byte 256 // Ethereum address | 40 bytes hex ascii 257 // Chain code if requested | 32 bytes 258 func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) { 259 // Flatten the derivation path into the Ledger request 260 path := make([]byte, 1+4*len(derivationPath)) 261 path[0] = byte(len(derivationPath)) 262 for i, component := range derivationPath { 263 binary.BigEndian.PutUint32(path[1+4*i:], component) 264 } 265 // Send the request and wait for the response 266 reply, err := w.ledgerExchange(ledgerOpRetrieveAddress, ledgerP1DirectlyFetchAddress, ledgerP2DiscardAddressChainCode, path) 267 if err != nil { 268 return common.Address{}, err 269 } 270 // Discard the public key, we don't need that for now 271 if len(reply) < 1 || len(reply) < 1+int(reply[0]) { 272 return common.Address{}, errors.New("reply lacks public key entry") 273 } 274 reply = reply[1+int(reply[0]):] 275 276 // Extract the Ethereum hex address string 277 if len(reply) < 1 || len(reply) < 1+int(reply[0]) { 278 return common.Address{}, errors.New("reply lacks address entry") 279 } 280 hexstr := reply[1 : 1+int(reply[0])] 281 282 // Decode the hex sting into an Ethereum address and return 283 var address common.Address 284 if _, err = hex.Decode(address[:], hexstr); err != nil { 285 return common.Address{}, err 286 } 287 return address, nil 288 } 289 290 // ledgerSign sends the transaction to the Ledger wallet, and waits for the user 291 // to confirm or deny the transaction. 292 // 293 // The transaction signing protocol is defined as follows: 294 // 295 // CLA | INS | P1 | P2 | Lc | Le 296 // ----+-----+----+----+-----+--- 297 // E0 | 04 | 00: first transaction data block 298 // 80: subsequent transaction data block 299 // | 00 | variable | variable 300 // 301 // Where the input for the first transaction block (first 255 bytes) is: 302 // 303 // Description | Length 304 // -------------------------------------------------+---------- 305 // Number of BIP 32 derivations to perform (max 10) | 1 byte 306 // First derivation index (big endian) | 4 bytes 307 // ... | 4 bytes 308 // Last derivation index (big endian) | 4 bytes 309 // RLP transaction chunk | arbitrary 310 // 311 // And the input for subsequent transaction blocks (first 255 bytes) are: 312 // 313 // Description | Length 314 // ----------------------+---------- 315 // RLP transaction chunk | arbitrary 316 // 317 // And the output data is: 318 // 319 // Description | Length 320 // ------------+--------- 321 // signature V | 1 byte 322 // signature R | 32 bytes 323 // signature S | 32 bytes 324 func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) { 325 // Flatten the derivation path into the Ledger request 326 path := make([]byte, 1+4*len(derivationPath)) 327 path[0] = byte(len(derivationPath)) 328 for i, component := range derivationPath { 329 binary.BigEndian.PutUint32(path[1+4*i:], component) 330 } 331 // Create the transaction RLP based on whether legacy or EIP155 signing was requested 332 var ( 333 txrlp []byte 334 err error 335 ) 336 if chainID == nil { 337 if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil { 338 return common.Address{}, nil, err 339 } 340 } else { 341 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 { 342 return common.Address{}, nil, err 343 } 344 } 345 payload := append(path, txrlp...) 346 347 // Send the request and wait for the response 348 var ( 349 op = ledgerP1InitTransactionData 350 reply []byte 351 ) 352 353 // Chunk size selection to mitigate an underlying RLP deserialization issue on the ledger app. 354 // https://github.com/LedgerHQ/app-ethereum/issues/409 355 chunk := 255 356 for ; len(payload)%chunk <= ledgerEip155Size; chunk-- { 357 } 358 359 for len(payload) > 0 { 360 // Calculate the size of the next data chunk 361 if chunk > len(payload) { 362 chunk = len(payload) 363 } 364 // Send the chunk over, ensuring it's processed correctly 365 reply, err = w.ledgerExchange(ledgerOpSignTransaction, op, 0, payload[:chunk]) 366 if err != nil { 367 return common.Address{}, nil, err 368 } 369 // Shift the payload and ensure subsequent chunks are marked as such 370 payload = payload[chunk:] 371 op = ledgerP1ContTransactionData 372 } 373 // Extract the Ethereum signature and do a sanity validation 374 if len(reply) != crypto.SignatureLength { 375 return common.Address{}, nil, errors.New("reply lacks signature") 376 } 377 signature := append(reply[1:], reply[0]) 378 379 // Create the correct signer and signature transform based on the chain ID 380 var signer types.Signer 381 if chainID == nil { 382 signer = new(types.HomesteadSigner) 383 } else { 384 signer = types.NewEIP155Signer(chainID) 385 signature[64] -= byte(chainID.Uint64()*2 + 35) 386 } 387 // TODO (cyyber): intentionally added pk as nil, fix this issue later 388 signed, err := tx.WithSignatureAndPublicKey(signer, signature, nil) 389 if err != nil { 390 return common.Address{}, nil, err 391 } 392 sender, err := types.Sender(signer, signed) 393 if err != nil { 394 return common.Address{}, nil, err 395 } 396 return sender, signed, nil 397 } 398 399 // ledgerSignTypedMessage sends the transaction to the Ledger wallet, and waits for the user 400 // to confirm or deny the transaction. 401 // 402 // The signing protocol is defined as follows: 403 // 404 // CLA | INS | P1 | P2 | Lc | Le 405 // ----+-----+----+-----------------------------+-----+--- 406 // E0 | 0C | 00 | implementation version : 00 | variable | variable 407 // 408 // Where the input is: 409 // 410 // Description | Length 411 // -------------------------------------------------+---------- 412 // Number of BIP 32 derivations to perform (max 10) | 1 byte 413 // First derivation index (big endian) | 4 bytes 414 // ... | 4 bytes 415 // Last derivation index (big endian) | 4 bytes 416 // domain hash | 32 bytes 417 // message hash | 32 bytes 418 // 419 // And the output data is: 420 // 421 // Description | Length 422 // ------------+--------- 423 // signature V | 1 byte 424 // signature R | 32 bytes 425 // signature S | 32 bytes 426 func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHash []byte, messageHash []byte) ([]byte, error) { 427 // Flatten the derivation path into the Ledger request 428 path := make([]byte, 1+4*len(derivationPath)) 429 path[0] = byte(len(derivationPath)) 430 for i, component := range derivationPath { 431 binary.BigEndian.PutUint32(path[1+4*i:], component) 432 } 433 // Create the 712 message 434 payload := append(path, domainHash...) 435 payload = append(payload, messageHash...) 436 437 // Send the request and wait for the response 438 var ( 439 op = ledgerP1InitTypedMessageData 440 reply []byte 441 err error 442 ) 443 444 // Send the message over, ensuring it's processed correctly 445 reply, err = w.ledgerExchange(ledgerOpSignTypedMessage, op, 0, payload) 446 447 if err != nil { 448 return nil, err 449 } 450 451 // Extract the Ethereum signature and do a sanity validation 452 if len(reply) != crypto.SignatureLength { 453 return nil, errors.New("reply lacks signature") 454 } 455 signature := append(reply[1:], reply[0]) 456 return signature, nil 457 } 458 459 // ledgerExchange performs a data exchange with the Ledger wallet, sending it a 460 // message and retrieving the response. 461 // 462 // The common transport header is defined as follows: 463 // 464 // Description | Length 465 // --------------------------------------+---------- 466 // Communication channel ID (big endian) | 2 bytes 467 // Command tag | 1 byte 468 // Packet sequence index (big endian) | 2 bytes 469 // Payload | arbitrary 470 // 471 // The Communication channel ID allows commands multiplexing over the same 472 // physical link. It is not used for the time being, and should be set to 0101 473 // to avoid compatibility issues with implementations ignoring a leading 00 byte. 474 // 475 // The Command tag describes the message content. Use TAG_APDU (0x05) for standard 476 // APDU payloads, or TAG_PING (0x02) for a simple link test. 477 // 478 // The Packet sequence index describes the current sequence for fragmented payloads. 479 // The first fragment index is 0x00. 480 // 481 // APDU Command payloads are encoded as follows: 482 // 483 // Description | Length 484 // ----------------------------------- 485 // APDU length (big endian) | 2 bytes 486 // APDU CLA | 1 byte 487 // APDU INS | 1 byte 488 // APDU P1 | 1 byte 489 // APDU P2 | 1 byte 490 // APDU length | 1 byte 491 // Optional APDU data | arbitrary 492 func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) { 493 // Construct the message payload, possibly split into multiple chunks 494 apdu := make([]byte, 2, 7+len(data)) 495 496 binary.BigEndian.PutUint16(apdu, uint16(5+len(data))) 497 apdu = append(apdu, []byte{0xe0, byte(opcode), byte(p1), byte(p2), byte(len(data))}...) 498 apdu = append(apdu, data...) 499 500 // Stream all the chunks to the device 501 header := []byte{0x01, 0x01, 0x05, 0x00, 0x00} // Channel ID and command tag appended 502 chunk := make([]byte, 64) 503 space := len(chunk) - len(header) 504 505 for i := 0; len(apdu) > 0; i++ { 506 // Construct the new message to stream 507 chunk = append(chunk[:0], header...) 508 binary.BigEndian.PutUint16(chunk[3:], uint16(i)) 509 510 if len(apdu) > space { 511 chunk = append(chunk, apdu[:space]...) 512 apdu = apdu[space:] 513 } else { 514 chunk = append(chunk, apdu...) 515 apdu = nil 516 } 517 // Send over to the device 518 w.log.Trace("Data chunk sent to the Ledger", "chunk", hexutil.Bytes(chunk)) 519 if _, err := w.device.Write(chunk); err != nil { 520 return nil, err 521 } 522 } 523 // Stream the reply back from the wallet in 64 byte chunks 524 var reply []byte 525 chunk = chunk[:64] // Yeah, we surely have enough space 526 for { 527 // Read the next chunk from the Ledger wallet 528 if _, err := io.ReadFull(w.device, chunk); err != nil { 529 return nil, err 530 } 531 w.log.Trace("Data chunk received from the Ledger", "chunk", hexutil.Bytes(chunk)) 532 533 // Make sure the transport header matches 534 if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 { 535 return nil, errLedgerReplyInvalidHeader 536 } 537 // If it's the first chunk, retrieve the total message length 538 var payload []byte 539 540 if chunk[3] == 0x00 && chunk[4] == 0x00 { 541 reply = make([]byte, 0, int(binary.BigEndian.Uint16(chunk[5:7]))) 542 payload = chunk[7:] 543 } else { 544 payload = chunk[5:] 545 } 546 // Append to the reply and stop when filled up 547 if left := cap(reply) - len(reply); left > len(payload) { 548 reply = append(reply, payload...) 549 } else { 550 reply = append(reply, payload[:left]...) 551 break 552 } 553 } 554 return reply[:len(reply)-2], nil 555 }