ledger_hub.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. "errors"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/accounts"
  25. "github.com/ethereum/go-ethereum/event"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/karalabe/hid"
  28. )
  29. // LedgerScheme is the protocol scheme prefixing account and wallet URLs.
  30. var LedgerScheme = "ledger"
  31. // ledgerDeviceIDs are the known device IDs that Ledger wallets use.
  32. var ledgerDeviceIDs = []deviceID{
  33. {Vendor: 0x2c97, Product: 0x0000}, // Ledger Blue
  34. {Vendor: 0x2c97, Product: 0x0001}, // Ledger Nano S
  35. }
  36. // Maximum time between wallet refreshes (if USB hotplug notifications don't work).
  37. const ledgerRefreshCycle = time.Second
  38. // Minimum time between wallet refreshes to avoid USB trashing.
  39. const ledgerRefreshThrottling = 500 * time.Millisecond
  40. // LedgerHub is a accounts.Backend that can find and handle Ledger hardware wallets.
  41. type LedgerHub struct {
  42. refreshed time.Time // Time instance when the list of wallets was last refreshed
  43. wallets []accounts.Wallet // List of Ledger devices currently tracking
  44. updateFeed event.Feed // Event feed to notify wallet additions/removals
  45. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  46. updating bool // Whether the event notification loop is running
  47. quit chan chan error
  48. lock sync.RWMutex
  49. }
  50. // NewLedgerHub creates a new hardware wallet manager for Ledger devices.
  51. func NewLedgerHub() (*LedgerHub, error) {
  52. if !hid.Supported() {
  53. return nil, errors.New("unsupported platform")
  54. }
  55. hub := &LedgerHub{
  56. quit: make(chan chan error),
  57. }
  58. hub.refreshWallets()
  59. return hub, nil
  60. }
  61. // Wallets implements accounts.Backend, returning all the currently tracked USB
  62. // devices that appear to be Ledger hardware wallets.
  63. func (hub *LedgerHub) Wallets() []accounts.Wallet {
  64. // Make sure the list of wallets is up to date
  65. hub.refreshWallets()
  66. hub.lock.RLock()
  67. defer hub.lock.RUnlock()
  68. cpy := make([]accounts.Wallet, len(hub.wallets))
  69. copy(cpy, hub.wallets)
  70. return cpy
  71. }
  72. // refreshWallets scans the USB devices attached to the machine and updates the
  73. // list of wallets based on the found devices.
  74. func (hub *LedgerHub) refreshWallets() {
  75. // Don't scan the USB like crazy it the user fetches wallets in a loop
  76. hub.lock.RLock()
  77. elapsed := time.Since(hub.refreshed)
  78. hub.lock.RUnlock()
  79. if elapsed < ledgerRefreshThrottling {
  80. return
  81. }
  82. // Retrieve the current list of Ledger devices
  83. var ledgers []hid.DeviceInfo
  84. for _, info := range hid.Enumerate(0, 0) { // Can't enumerate directly, one valid ID is the 0 wildcard
  85. for _, id := range ledgerDeviceIDs {
  86. if info.VendorID == id.Vendor && info.ProductID == id.Product {
  87. ledgers = append(ledgers, info)
  88. break
  89. }
  90. }
  91. }
  92. // Transform the current list of wallets into the new one
  93. hub.lock.Lock()
  94. wallets := make([]accounts.Wallet, 0, len(ledgers))
  95. events := []accounts.WalletEvent{}
  96. for _, ledger := range ledgers {
  97. url := accounts.URL{Scheme: LedgerScheme, Path: ledger.Path}
  98. // Drop wallets in front of the next device or those that failed for some reason
  99. for len(hub.wallets) > 0 && (hub.wallets[0].URL().Cmp(url) < 0 || hub.wallets[0].(*ledgerWallet).failed()) {
  100. events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Arrive: false})
  101. hub.wallets = hub.wallets[1:]
  102. }
  103. // If there are no more wallets or the device is before the next, wrap new wallet
  104. if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
  105. wallet := &ledgerWallet{url: &url, info: ledger, logger: log.New("url", url)}
  106. events = append(events, accounts.WalletEvent{Wallet: wallet, Arrive: true})
  107. wallets = append(wallets, wallet)
  108. continue
  109. }
  110. // If the device is the same as the first wallet, keep it
  111. if hub.wallets[0].URL().Cmp(url) == 0 {
  112. wallets = append(wallets, hub.wallets[0])
  113. hub.wallets = hub.wallets[1:]
  114. continue
  115. }
  116. }
  117. // Drop any leftover wallets and set the new batch
  118. for _, wallet := range hub.wallets {
  119. events = append(events, accounts.WalletEvent{Wallet: wallet, Arrive: false})
  120. }
  121. hub.refreshed = time.Now()
  122. hub.wallets = wallets
  123. hub.lock.Unlock()
  124. // Fire all wallet events and return
  125. for _, event := range events {
  126. hub.updateFeed.Send(event)
  127. }
  128. }
  129. // Subscribe implements accounts.Backend, creating an async subscription to
  130. // receive notifications on the addition or removal of Ledger wallets.
  131. func (hub *LedgerHub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  132. // We need the mutex to reliably start/stop the update loop
  133. hub.lock.Lock()
  134. defer hub.lock.Unlock()
  135. // Subscribe the caller and track the subscriber count
  136. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  137. // Subscribers require an active notification loop, start it
  138. if !hub.updating {
  139. hub.updating = true
  140. go hub.updater()
  141. }
  142. return sub
  143. }
  144. // updater is responsible for maintaining an up-to-date list of wallets stored in
  145. // the keystore, and for firing wallet addition/removal events. It listens for
  146. // account change events from the underlying account cache, and also periodically
  147. // forces a manual refresh (only triggers for systems where the filesystem notifier
  148. // is not running).
  149. func (hub *LedgerHub) updater() {
  150. for {
  151. // Wait for a USB hotplug event (not supported yet) or a refresh timeout
  152. select {
  153. //case <-hub.changes: // reenable on hutplug implementation
  154. case <-time.After(ledgerRefreshCycle):
  155. }
  156. // Run the wallet refresher
  157. hub.refreshWallets()
  158. // If all our subscribers left, stop the updater
  159. hub.lock.Lock()
  160. if hub.updateScope.Count() == 0 {
  161. hub.updating = false
  162. hub.lock.Unlock()
  163. return
  164. }
  165. hub.lock.Unlock()
  166. }
  167. }