ledger.go 17 KB

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