ledger_wallet.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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. "sync"
  28. "time"
  29. ethereum "github.com/ethereum/go-ethereum"
  30. "github.com/ethereum/go-ethereum/accounts"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/logger"
  34. "github.com/ethereum/go-ethereum/logger/glog"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. "github.com/karalabe/hid"
  37. "golang.org/x/net/context"
  38. )
  39. // Maximum time between wallet health checks to detect USB unplugs.
  40. const ledgerHeartbeatCycle = time.Second
  41. // Minimum time to wait between self derivation attempts, even it the user is
  42. // requesting accounts like crazy.
  43. const ledgerSelfDeriveThrottling = time.Second
  44. // ledgerOpcode is an enumeration encoding the supported Ledger opcodes.
  45. type ledgerOpcode byte
  46. // ledgerParam1 is an enumeration encoding the supported Ledger parameters for
  47. // specific opcodes. The same parameter values may be reused between opcodes.
  48. type ledgerParam1 byte
  49. // ledgerParam2 is an enumeration encoding the supported Ledger parameters for
  50. // specific opcodes. The same parameter values may be reused between opcodes.
  51. type ledgerParam2 byte
  52. const (
  53. ledgerOpRetrieveAddress ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path
  54. ledgerOpSignTransaction ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters
  55. ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
  56. ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet
  57. ledgerP1ConfirmFetchAddress ledgerParam1 = 0x01 // Require a user confirmation before returning the address
  58. ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing
  59. ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing
  60. ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
  61. ledgerP2ReturnAddressChainCode ledgerParam2 = 0x01 // Require a user confirmation before returning the address
  62. )
  63. // errReplyInvalidHeader is the error message returned by a Ledger data exchange
  64. // if the device replies with a mismatching header. This usually means the device
  65. // is in browser mode.
  66. var errReplyInvalidHeader = errors.New("invalid reply header")
  67. // errInvalidVersionReply 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 errInvalidVersionReply = errors.New("invalid version reply")
  70. // ledgerWallet represents a live USB Ledger hardware wallet.
  71. type ledgerWallet struct {
  72. url *accounts.URL // Textual URL uniquely identifying this wallet
  73. info hid.DeviceInfo // Known USB device infos about the wallet
  74. device *hid.Device // USB device advertising itself as a Ledger wallet
  75. failure error // Any failure that would make the device unusable
  76. version [3]byte // Current version of the Ledger Ethereum app (zero if app is offline)
  77. browser bool // Flag whether the Ledger is in browser mode (reply channel mismatch)
  78. accounts []accounts.Account // List of derive accounts pinned on the Ledger
  79. paths map[common.Address]accounts.DerivationPath // Known derivation paths for signing operations
  80. deriveNextPath accounts.DerivationPath // Next derivation path for account auto-discovery
  81. deriveNextAddr common.Address // Next derived account address for auto-discovery
  82. deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
  83. deriveReq chan chan struct{} // Channel to request a self-derivation on
  84. deriveQuit chan chan error // Channel to terminate the self-deriver with
  85. healthQuit chan chan error
  86. // Locking a hardware wallet is a bit special. Since hardware devices are lower
  87. // performing, any communication with them might take a non negligible amount of
  88. // time. Worse still, waiting for user confirmation can take arbitrarily long,
  89. // but exclusive communication must be upheld during. Locking the entire wallet
  90. // in the mean time however would stall any parts of the system that don't want
  91. // to communicate, just read some state (e.g. list the accounts).
  92. //
  93. // As such, a hardware wallet needs two locks to function correctly. A state
  94. // lock can be used to protect the wallet's software-side internal state, which
  95. // must not be held exlusively during hardware communication. A communication
  96. // lock can be used to achieve exclusive access to the device itself, this one
  97. // however should allow "skipping" waiting for operations that might want to
  98. // use the device, but can live without too (e.g. account self-derivation).
  99. //
  100. // Since we have two locks, it's important to know how to properly use them:
  101. // - Communication requires the `device` to not change, so obtaining the
  102. // commsLock should be done after having a stateLock.
  103. // - Communication must not disable read access to the wallet state, so it
  104. // must only ever hold a *read* lock to stateLock.
  105. commsLock chan struct{} // Mutex (buf=1) for the USB comms without keeping the state locked
  106. stateLock sync.RWMutex // Protects read and write access to the wallet struct fields
  107. }
  108. // URL implements accounts.Wallet, returning the URL of the Ledger device.
  109. func (w *ledgerWallet) URL() accounts.URL {
  110. return *w.url // Immutable, no need for a lock
  111. }
  112. // Status implements accounts.Wallet, always whether the Ledger is opened, closed
  113. // or whether the Ethereum app was not started on it.
  114. func (w *ledgerWallet) Status() string {
  115. w.stateLock.RLock() // No device communication, state lock is enough
  116. defer w.stateLock.RUnlock()
  117. if w.failure != nil {
  118. return fmt.Sprintf("Failed: %v", w.failure)
  119. }
  120. if w.device == nil {
  121. return "Closed"
  122. }
  123. if w.browser {
  124. return "Ethereum app in browser mode"
  125. }
  126. if w.offline() {
  127. return "Ethereum app offline"
  128. }
  129. return fmt.Sprintf("Ethereum app v%d.%d.%d online", w.version[0], w.version[1], w.version[2])
  130. }
  131. // offline returns whether the wallet and the Ethereum app is offline or not.
  132. //
  133. // The method assumes that the state lock is held!
  134. func (w *ledgerWallet) offline() bool {
  135. return w.version == [3]byte{0, 0, 0}
  136. }
  137. // failed returns if the USB device wrapped by the wallet failed for some reason.
  138. // This is used by the device scanner to report failed wallets as departed.
  139. //
  140. // The method assumes that the state lock is *not* held!
  141. func (w *ledgerWallet) failed() bool {
  142. w.stateLock.RLock() // No device communication, state lock is enough
  143. defer w.stateLock.RUnlock()
  144. return w.failure != nil
  145. }
  146. // Open implements accounts.Wallet, attempting to open a USB connection to the
  147. // Ledger hardware wallet. The Ledger does not require a user passphrase, so that
  148. // parameter is silently discarded.
  149. func (w *ledgerWallet) Open(passphrase string) error {
  150. w.stateLock.Lock() // State lock is enough since there's no connection yet at this point
  151. defer w.stateLock.Unlock()
  152. // If the wallet was already opened, don't try to open again
  153. if w.device != nil {
  154. return accounts.ErrWalletAlreadyOpen
  155. }
  156. // Otherwise iterate over all USB devices and find this again (no way to directly do this)
  157. device, err := w.info.Open()
  158. if err != nil {
  159. return err
  160. }
  161. // Wallet seems to be successfully opened, guess if the Ethereum app is running
  162. w.device = device
  163. w.commsLock = make(chan struct{}, 1)
  164. w.commsLock <- struct{}{} // Enable lock
  165. w.paths = make(map[common.Address]accounts.DerivationPath)
  166. w.deriveReq = make(chan chan struct{})
  167. w.deriveQuit = make(chan chan error)
  168. w.healthQuit = make(chan chan error)
  169. defer func() {
  170. go w.heartbeat()
  171. go w.selfDerive()
  172. }()
  173. if _, err = w.ledgerDerive(accounts.DefaultBaseDerivationPath); err != nil {
  174. // Ethereum app is not running or in browser mode, nothing more to do, return
  175. if err == errReplyInvalidHeader {
  176. w.browser = true
  177. }
  178. return nil
  179. }
  180. // Try to resolve the Ethereum app's version, will fail prior to v1.0.2
  181. if w.version, err = w.ledgerVersion(); err != nil {
  182. w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1
  183. }
  184. return nil
  185. }
  186. // heartbeat is a health check loop for the Ledger wallets to periodically verify
  187. // whether they are still present or if they malfunctioned. It is needed because:
  188. // - libusb on Windows doesn't support hotplug, so we can't detect USB unplugs
  189. // - communication timeout on the Ledger requires a device power cycle to fix
  190. func (w *ledgerWallet) heartbeat() {
  191. glog.V(logger.Debug).Infof("%s health-check started", w.url.String())
  192. defer glog.V(logger.Debug).Infof("%s health-check stopped", w.url.String())
  193. // Execute heartbeat checks until termination or error
  194. var (
  195. errc chan error
  196. err error
  197. )
  198. for errc == nil && err == nil {
  199. // Wait until termination is requested or the heartbeat cycle arrives
  200. select {
  201. case errc = <-w.healthQuit:
  202. // Termination requested
  203. continue
  204. case <-time.After(ledgerHeartbeatCycle):
  205. // Heartbeat time
  206. }
  207. // Execute a tiny data exchange to see responsiveness
  208. w.stateLock.RLock()
  209. if w.device == nil {
  210. // Terminated while waiting for the lock
  211. w.stateLock.RUnlock()
  212. continue
  213. }
  214. <-w.commsLock // Don't lock state while resolving version
  215. _, err = w.ledgerVersion()
  216. w.commsLock <- struct{}{}
  217. w.stateLock.RUnlock()
  218. if err != nil && err != errInvalidVersionReply {
  219. w.stateLock.Lock() // Lock state to tear the wallet down
  220. w.failure = err
  221. w.close()
  222. w.stateLock.Unlock()
  223. }
  224. // Ignore non hardware related errors
  225. err = nil
  226. }
  227. // In case of error, wait for termination
  228. if err != nil {
  229. glog.V(logger.Debug).Infof("%s health-check failed: %v", w.url.String(), err)
  230. errc = <-w.healthQuit
  231. }
  232. errc <- err
  233. }
  234. // Close implements accounts.Wallet, closing the USB connection to the Ledger.
  235. func (w *ledgerWallet) Close() error {
  236. // Ensure the wallet was opened
  237. w.stateLock.RLock()
  238. hQuit, dQuit := w.healthQuit, w.deriveQuit
  239. w.stateLock.RUnlock()
  240. // Terminate the health checks
  241. var herr error
  242. if hQuit != nil {
  243. errc := make(chan error)
  244. hQuit <- errc
  245. herr = <-errc // Save for later, we *must* close the USB
  246. }
  247. // Terminate the self-derivations
  248. var derr error
  249. if dQuit != nil {
  250. errc := make(chan error)
  251. dQuit <- errc
  252. derr = <-errc // Save for later, we *must* close the USB
  253. }
  254. // Terminate the device connection
  255. w.stateLock.Lock()
  256. defer w.stateLock.Unlock()
  257. w.healthQuit = nil
  258. w.deriveQuit = nil
  259. w.deriveReq = nil
  260. if err := w.close(); err != nil {
  261. return err
  262. }
  263. if herr != nil {
  264. return herr
  265. }
  266. return derr
  267. }
  268. // close is the internal wallet closer that terminates the USB connection and
  269. // resets all the fields to their defaults.
  270. //
  271. // Note, close assumes the state lock is held!
  272. func (w *ledgerWallet) close() error {
  273. // Allow duplicate closes, especially for health-check failures
  274. if w.device == nil {
  275. return nil
  276. }
  277. // Close the device, clear everything, then return
  278. w.device.Close()
  279. w.device = nil
  280. w.browser, w.version = false, [3]byte{}
  281. w.accounts, w.paths = nil, nil
  282. return nil
  283. }
  284. // Accounts implements accounts.Wallet, returning the list of accounts pinned to
  285. // the Ledger hardware wallet. If self-derivation was enabled, the account list
  286. // is periodically expanded based on current chain state.
  287. func (w *ledgerWallet) Accounts() []accounts.Account {
  288. // Attempt self-derivation if it's running
  289. reqc := make(chan struct{}, 1)
  290. select {
  291. case w.deriveReq <- reqc:
  292. // Self-derivation request accepted, wait for it
  293. <-reqc
  294. default:
  295. // Self-derivation offline, throttled or busy, skip
  296. }
  297. // Return whatever account list we ended up with
  298. w.stateLock.RLock()
  299. defer w.stateLock.RUnlock()
  300. cpy := make([]accounts.Account, len(w.accounts))
  301. copy(cpy, w.accounts)
  302. return cpy
  303. }
  304. // selfDerive is an account derivation loop that upon request attempts to find
  305. // new non-zero accounts.
  306. func (w *ledgerWallet) selfDerive() {
  307. glog.V(logger.Debug).Infof("%s self-derivation started", w.url.String())
  308. defer glog.V(logger.Debug).Infof("%s self-derivation stopped", w.url.String())
  309. // Execute self-derivations until termination or error
  310. var (
  311. reqc chan struct{}
  312. errc chan error
  313. err error
  314. )
  315. for errc == nil && err == nil {
  316. // Wait until either derivation or termination is requested
  317. select {
  318. case errc = <-w.deriveQuit:
  319. // Termination requested
  320. continue
  321. case reqc = <-w.deriveReq:
  322. // Account discovery requested
  323. }
  324. // Derivation needs a chain and device access, skip if either unavailable
  325. w.stateLock.RLock()
  326. if w.device == nil || w.deriveChain == nil || w.offline() {
  327. w.stateLock.RUnlock()
  328. reqc <- struct{}{}
  329. continue
  330. }
  331. select {
  332. case <-w.commsLock:
  333. default:
  334. w.stateLock.RUnlock()
  335. reqc <- struct{}{}
  336. continue
  337. }
  338. // Device lock obtained, derive the next batch of accounts
  339. var (
  340. accs []accounts.Account
  341. paths []accounts.DerivationPath
  342. nextAddr = w.deriveNextAddr
  343. nextPath = w.deriveNextPath
  344. context = context.Background()
  345. )
  346. for empty := false; !empty; {
  347. // Retrieve the next derived Ethereum account
  348. if nextAddr == (common.Address{}) {
  349. if nextAddr, err = w.ledgerDerive(nextPath); err != nil {
  350. glog.V(logger.Warn).Infof("%s self-derivation failed: %v", w.url.String(), err)
  351. break
  352. }
  353. }
  354. // Check the account's status against the current chain state
  355. var (
  356. balance *big.Int
  357. nonce uint64
  358. )
  359. balance, err = w.deriveChain.BalanceAt(context, nextAddr, nil)
  360. if err != nil {
  361. glog.V(logger.Warn).Infof("%s self-derivation balance retrieval failed: %v", w.url.String(), err)
  362. break
  363. }
  364. nonce, err = w.deriveChain.NonceAt(context, nextAddr, nil)
  365. if err != nil {
  366. glog.V(logger.Warn).Infof("%s self-derivation nonce retrieval failed: %v", w.url.String(), err)
  367. break
  368. }
  369. // If the next account is empty, stop self-derivation, but add it nonetheless
  370. if balance.BitLen() == 0 && nonce == 0 {
  371. empty = true
  372. }
  373. // We've just self-derived a new account, start tracking it locally
  374. path := make(accounts.DerivationPath, len(nextPath))
  375. copy(path[:], nextPath[:])
  376. paths = append(paths, path)
  377. account := accounts.Account{
  378. Address: nextAddr,
  379. URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)},
  380. }
  381. accs = append(accs, account)
  382. // Display a log message to the user for new (or previously empty accounts)
  383. if _, known := w.paths[nextAddr]; !known || (!empty && nextAddr == w.deriveNextAddr) {
  384. glog.V(logger.Info).Infof("%s discovered %s (balance %22v, nonce %4d) at %s", w.url.String(), nextAddr.Hex(), balance, nonce, path)
  385. }
  386. // Fetch the next potential account
  387. if !empty {
  388. nextAddr = common.Address{}
  389. nextPath[len(nextPath)-1]++
  390. }
  391. }
  392. // Self derivation complete, release device lock
  393. w.commsLock <- struct{}{}
  394. w.stateLock.RUnlock()
  395. // Insert any accounts successfully derived
  396. w.stateLock.Lock()
  397. for i := 0; i < len(accs); i++ {
  398. if _, ok := w.paths[accs[i].Address]; !ok {
  399. w.accounts = append(w.accounts, accs[i])
  400. w.paths[accs[i].Address] = paths[i]
  401. }
  402. }
  403. // Shift the self-derivation forward
  404. // TODO(karalabe): don't overwrite changes from wallet.SelfDerive
  405. w.deriveNextAddr = nextAddr
  406. w.deriveNextPath = nextPath
  407. w.stateLock.Unlock()
  408. // Notify the user of termination and loop after a bit of time (to avoid trashing)
  409. reqc <- struct{}{}
  410. if err == nil {
  411. select {
  412. case errc = <-w.deriveQuit:
  413. // Termination requested, abort
  414. case <-time.After(ledgerSelfDeriveThrottling):
  415. // Waited enough, willing to self-derive again
  416. }
  417. }
  418. }
  419. // In case of error, wait for termination
  420. if err != nil {
  421. glog.V(logger.Debug).Infof("%s self-derivation failed: %s", w.url.String(), err)
  422. errc = <-w.deriveQuit
  423. }
  424. errc <- err
  425. }
  426. // Contains implements accounts.Wallet, returning whether a particular account is
  427. // or is not pinned into this Ledger instance. Although we could attempt to resolve
  428. // unpinned accounts, that would be an non-negligible hardware operation.
  429. func (w *ledgerWallet) Contains(account accounts.Account) bool {
  430. w.stateLock.RLock()
  431. defer w.stateLock.RUnlock()
  432. _, exists := w.paths[account.Address]
  433. return exists
  434. }
  435. // Derive implements accounts.Wallet, deriving a new account at the specific
  436. // derivation path. If pin is set to true, the account will be added to the list
  437. // of tracked accounts.
  438. func (w *ledgerWallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
  439. // Try to derive the actual account and update its URL if successful
  440. w.stateLock.RLock() // Avoid device disappearing during derivation
  441. if w.device == nil || w.offline() {
  442. w.stateLock.RUnlock()
  443. return accounts.Account{}, accounts.ErrWalletClosed
  444. }
  445. <-w.commsLock // Avoid concurrent hardware access
  446. address, err := w.ledgerDerive(path)
  447. w.commsLock <- struct{}{}
  448. w.stateLock.RUnlock()
  449. // If an error occurred or no pinning was requested, return
  450. if err != nil {
  451. return accounts.Account{}, err
  452. }
  453. account := accounts.Account{
  454. Address: address,
  455. URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)},
  456. }
  457. if !pin {
  458. return account, nil
  459. }
  460. // Pinning needs to modify the state
  461. w.stateLock.Lock()
  462. defer w.stateLock.Unlock()
  463. if _, ok := w.paths[address]; !ok {
  464. w.accounts = append(w.accounts, account)
  465. w.paths[address] = path
  466. }
  467. return account, nil
  468. }
  469. // SelfDerive implements accounts.Wallet, trying to discover accounts that the
  470. // user used previously (based on the chain state), but ones that he/she did not
  471. // explicitly pin to the wallet manually. To avoid chain head monitoring, self
  472. // derivation only runs during account listing (and even then throttled).
  473. func (w *ledgerWallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
  474. w.stateLock.Lock()
  475. defer w.stateLock.Unlock()
  476. w.deriveNextPath = make(accounts.DerivationPath, len(base))
  477. copy(w.deriveNextPath[:], base[:])
  478. w.deriveNextAddr = common.Address{}
  479. w.deriveChain = chain
  480. }
  481. // SignHash implements accounts.Wallet, however signing arbitrary data is not
  482. // supported for Ledger wallets, so this method will always return an error.
  483. func (w *ledgerWallet) SignHash(acc accounts.Account, hash []byte) ([]byte, error) {
  484. return nil, accounts.ErrNotSupported
  485. }
  486. // SignTx implements accounts.Wallet. It sends the transaction over to the Ledger
  487. // wallet to request a confirmation from the user. It returns either the signed
  488. // transaction or a failure if the user denied the transaction.
  489. //
  490. // Note, if the version of the Ethereum application running on the Ledger wallet is
  491. // too old to sign EIP-155 transactions, but such is requested nonetheless, an error
  492. // will be returned opposed to silently signing in Homestead mode.
  493. func (w *ledgerWallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  494. w.stateLock.RLock() // Comms have own mutex, this is for the state fields
  495. defer w.stateLock.RUnlock()
  496. // If the wallet is closed, or the Ethereum app doesn't run, abort
  497. if w.device == nil || w.offline() {
  498. return nil, accounts.ErrWalletClosed
  499. }
  500. // Make sure the requested account is contained within
  501. path, ok := w.paths[account.Address]
  502. if !ok {
  503. return nil, accounts.ErrUnknownAccount
  504. }
  505. // Ensure the wallet is capable of signing the given transaction
  506. if chainID != nil && w.version[0] <= 1 && w.version[1] <= 0 && w.version[2] <= 2 {
  507. return 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])
  508. }
  509. // All infos gathered and metadata checks out, request signing
  510. <-w.commsLock
  511. defer func() { w.commsLock <- struct{}{} }()
  512. return w.ledgerSign(path, account.Address, tx, chainID)
  513. }
  514. // SignHashWithPassphrase implements accounts.Wallet, however signing arbitrary
  515. // data is not supported for Ledger wallets, so this method will always return
  516. // an error.
  517. func (w *ledgerWallet) SignHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
  518. return nil, accounts.ErrNotSupported
  519. }
  520. // SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given
  521. // transaction with the given account using passphrase as extra authentication.
  522. // Since the Ledger does not support extra passphrases, it is silently ignored.
  523. func (w *ledgerWallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  524. return w.SignTx(account, tx, chainID)
  525. }
  526. // ledgerVersion retrieves the current version of the Ethereum wallet app running
  527. // on the Ledger wallet.
  528. //
  529. // The version retrieval protocol is defined as follows:
  530. //
  531. // CLA | INS | P1 | P2 | Lc | Le
  532. // ----+-----+----+----+----+---
  533. // E0 | 06 | 00 | 00 | 00 | 04
  534. //
  535. // With no input data, and the output data being:
  536. //
  537. // Description | Length
  538. // ---------------------------------------------------+--------
  539. // Flags 01: arbitrary data signature enabled by user | 1 byte
  540. // Application major version | 1 byte
  541. // Application minor version | 1 byte
  542. // Application patch version | 1 byte
  543. func (w *ledgerWallet) ledgerVersion() ([3]byte, error) {
  544. // Send the request and wait for the response
  545. reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil)
  546. if err != nil {
  547. return [3]byte{}, err
  548. }
  549. if len(reply) != 4 {
  550. return [3]byte{}, errInvalidVersionReply
  551. }
  552. // Cache the version for future reference
  553. var version [3]byte
  554. copy(version[:], reply[1:])
  555. return version, nil
  556. }
  557. // ledgerDerive retrieves the currently active Ethereum address from a Ledger
  558. // wallet at the specified derivation path.
  559. //
  560. // The address derivation protocol is defined as follows:
  561. //
  562. // CLA | INS | P1 | P2 | Lc | Le
  563. // ----+-----+----+----+-----+---
  564. // E0 | 02 | 00 return address
  565. // 01 display address and confirm before returning
  566. // | 00: do not return the chain code
  567. // | 01: return the chain code
  568. // | var | 00
  569. //
  570. // Where the input data is:
  571. //
  572. // Description | Length
  573. // -------------------------------------------------+--------
  574. // Number of BIP 32 derivations to perform (max 10) | 1 byte
  575. // First derivation index (big endian) | 4 bytes
  576. // ... | 4 bytes
  577. // Last derivation index (big endian) | 4 bytes
  578. //
  579. // And the output data is:
  580. //
  581. // Description | Length
  582. // ------------------------+-------------------
  583. // Public Key length | 1 byte
  584. // Uncompressed Public Key | arbitrary
  585. // Ethereum address length | 1 byte
  586. // Ethereum address | 40 bytes hex ascii
  587. // Chain code if requested | 32 bytes
  588. func (w *ledgerWallet) ledgerDerive(derivationPath []uint32) (common.Address, error) {
  589. // Flatten the derivation path into the Ledger request
  590. path := make([]byte, 1+4*len(derivationPath))
  591. path[0] = byte(len(derivationPath))
  592. for i, component := range derivationPath {
  593. binary.BigEndian.PutUint32(path[1+4*i:], component)
  594. }
  595. // Send the request and wait for the response
  596. reply, err := w.ledgerExchange(ledgerOpRetrieveAddress, ledgerP1DirectlyFetchAddress, ledgerP2DiscardAddressChainCode, path)
  597. if err != nil {
  598. return common.Address{}, err
  599. }
  600. // Discard the public key, we don't need that for now
  601. if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
  602. return common.Address{}, errors.New("reply lacks public key entry")
  603. }
  604. reply = reply[1+int(reply[0]):]
  605. // Extract the Ethereum hex address string
  606. if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
  607. return common.Address{}, errors.New("reply lacks address entry")
  608. }
  609. hexstr := reply[1 : 1+int(reply[0])]
  610. // Decode the hex sting into an Ethereum address and return
  611. var address common.Address
  612. hex.Decode(address[:], hexstr)
  613. return address, nil
  614. }
  615. // ledgerSign sends the transaction to the Ledger wallet, and waits for the user
  616. // to confirm or deny the transaction.
  617. //
  618. // The transaction signing protocol is defined as follows:
  619. //
  620. // CLA | INS | P1 | P2 | Lc | Le
  621. // ----+-----+----+----+-----+---
  622. // E0 | 04 | 00: first transaction data block
  623. // 80: subsequent transaction data block
  624. // | 00 | variable | variable
  625. //
  626. // Where the input for the first transaction block (first 255 bytes) is:
  627. //
  628. // Description | Length
  629. // -------------------------------------------------+----------
  630. // Number of BIP 32 derivations to perform (max 10) | 1 byte
  631. // First derivation index (big endian) | 4 bytes
  632. // ... | 4 bytes
  633. // Last derivation index (big endian) | 4 bytes
  634. // RLP transaction chunk | arbitrary
  635. //
  636. // And the input for subsequent transaction blocks (first 255 bytes) are:
  637. //
  638. // Description | Length
  639. // ----------------------+----------
  640. // RLP transaction chunk | arbitrary
  641. //
  642. // And the output data is:
  643. //
  644. // Description | Length
  645. // ------------+---------
  646. // signature V | 1 byte
  647. // signature R | 32 bytes
  648. // signature S | 32 bytes
  649. func (w *ledgerWallet) ledgerSign(derivationPath []uint32, address common.Address, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  650. // Flatten the derivation path into the Ledger request
  651. path := make([]byte, 1+4*len(derivationPath))
  652. path[0] = byte(len(derivationPath))
  653. for i, component := range derivationPath {
  654. binary.BigEndian.PutUint32(path[1+4*i:], component)
  655. }
  656. // Create the transaction RLP based on whether legacy or EIP155 signing was requeste
  657. var (
  658. txrlp []byte
  659. err error
  660. )
  661. if chainID == nil {
  662. if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil {
  663. return nil, err
  664. }
  665. } else {
  666. 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 {
  667. return nil, err
  668. }
  669. }
  670. payload := append(path, txrlp...)
  671. // Send the request and wait for the response
  672. var (
  673. op = ledgerP1InitTransactionData
  674. reply []byte
  675. )
  676. for len(payload) > 0 {
  677. // Calculate the size of the next data chunk
  678. chunk := 255
  679. if chunk > len(payload) {
  680. chunk = len(payload)
  681. }
  682. // Send the chunk over, ensuring it's processed correctly
  683. reply, err = w.ledgerExchange(ledgerOpSignTransaction, op, 0, payload[:chunk])
  684. if err != nil {
  685. return nil, err
  686. }
  687. // Shift the payload and ensure subsequent chunks are marked as such
  688. payload = payload[chunk:]
  689. op = ledgerP1ContTransactionData
  690. }
  691. // Extract the Ethereum signature and do a sanity validation
  692. if len(reply) != 65 {
  693. return nil, errors.New("reply lacks signature")
  694. }
  695. signature := append(reply[1:], reply[0])
  696. // Create the correct signer and signature transform based on the chain ID
  697. var signer types.Signer
  698. if chainID == nil {
  699. signer = new(types.HomesteadSigner)
  700. } else {
  701. signer = types.NewEIP155Signer(chainID)
  702. signature[64] = signature[64] - byte(chainID.Uint64()*2+35)
  703. }
  704. // Inject the final signature into the transaction and sanity check the sender
  705. signed, err := tx.WithSignature(signer, signature)
  706. if err != nil {
  707. return nil, err
  708. }
  709. sender, err := types.Sender(signer, signed)
  710. if err != nil {
  711. return nil, err
  712. }
  713. if sender != address {
  714. return nil, fmt.Errorf("signer mismatch: expected %s, got %s", address.Hex(), sender.Hex())
  715. }
  716. return signed, nil
  717. }
  718. // ledgerExchange performs a data exchange with the Ledger wallet, sending it a
  719. // message and retrieving the response.
  720. //
  721. // The common transport header is defined as follows:
  722. //
  723. // Description | Length
  724. // --------------------------------------+----------
  725. // Communication channel ID (big endian) | 2 bytes
  726. // Command tag | 1 byte
  727. // Packet sequence index (big endian) | 2 bytes
  728. // Payload | arbitrary
  729. //
  730. // The Communication channel ID allows commands multiplexing over the same
  731. // physical link. It is not used for the time being, and should be set to 0101
  732. // to avoid compatibility issues with implementations ignoring a leading 00 byte.
  733. //
  734. // The Command tag describes the message content. Use TAG_APDU (0x05) for standard
  735. // APDU payloads, or TAG_PING (0x02) for a simple link test.
  736. //
  737. // The Packet sequence index describes the current sequence for fragmented payloads.
  738. // The first fragment index is 0x00.
  739. //
  740. // APDU Command payloads are encoded as follows:
  741. //
  742. // Description | Length
  743. // -----------------------------------
  744. // APDU length (big endian) | 2 bytes
  745. // APDU CLA | 1 byte
  746. // APDU INS | 1 byte
  747. // APDU P1 | 1 byte
  748. // APDU P2 | 1 byte
  749. // APDU length | 1 byte
  750. // Optional APDU data | arbitrary
  751. func (w *ledgerWallet) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) {
  752. // Construct the message payload, possibly split into multiple chunks
  753. apdu := make([]byte, 2, 7+len(data))
  754. binary.BigEndian.PutUint16(apdu, uint16(5+len(data)))
  755. apdu = append(apdu, []byte{0xe0, byte(opcode), byte(p1), byte(p2), byte(len(data))}...)
  756. apdu = append(apdu, data...)
  757. // Stream all the chunks to the device
  758. header := []byte{0x01, 0x01, 0x05, 0x00, 0x00} // Channel ID and command tag appended
  759. chunk := make([]byte, 64)
  760. space := len(chunk) - len(header)
  761. for i := 0; len(apdu) > 0; i++ {
  762. // Construct the new message to stream
  763. chunk = append(chunk[:0], header...)
  764. binary.BigEndian.PutUint16(chunk[3:], uint16(i))
  765. if len(apdu) > space {
  766. chunk = append(chunk, apdu[:space]...)
  767. apdu = apdu[space:]
  768. } else {
  769. chunk = append(chunk, apdu...)
  770. apdu = nil
  771. }
  772. // Send over to the device
  773. if glog.V(logger.Detail) {
  774. glog.Infof("-> %s: %x", w.device.Path, chunk)
  775. }
  776. if _, err := w.device.Write(chunk); err != nil {
  777. return nil, err
  778. }
  779. }
  780. // Stream the reply back from the wallet in 64 byte chunks
  781. var reply []byte
  782. chunk = chunk[:64] // Yeah, we surely have enough space
  783. for {
  784. // Read the next chunk from the Ledger wallet
  785. if _, err := io.ReadFull(w.device, chunk); err != nil {
  786. return nil, err
  787. }
  788. if glog.V(logger.Detail) {
  789. glog.Infof("<- %s: %x", w.device.Path, chunk)
  790. }
  791. // Make sure the transport header matches
  792. if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 {
  793. return nil, errReplyInvalidHeader
  794. }
  795. // If it's the first chunk, retrieve the total message length
  796. var payload []byte
  797. if chunk[3] == 0x00 && chunk[4] == 0x00 {
  798. reply = make([]byte, 0, int(binary.BigEndian.Uint16(chunk[5:7])))
  799. payload = chunk[7:]
  800. } else {
  801. payload = chunk[5:]
  802. }
  803. // Append to the reply and stop when filled up
  804. if left := cap(reply) - len(reply); left > len(payload) {
  805. reply = append(reply, payload...)
  806. } else {
  807. reply = append(reply, payload[:left]...)
  808. break
  809. }
  810. }
  811. return reply[:len(reply)-2], nil
  812. }