hub.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. package usbwallet
  17. import (
  18. "errors"
  19. "runtime"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/accounts"
  23. "github.com/ethereum/go-ethereum/event"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/karalabe/hid"
  26. )
  27. // LedgerScheme is the protocol scheme prefixing account and wallet URLs.
  28. const LedgerScheme = "ledger"
  29. // TrezorScheme is the protocol scheme prefixing account and wallet URLs.
  30. const TrezorScheme = "trezor"
  31. // refreshCycle is the maximum time between wallet refreshes (if USB hotplug
  32. // notifications don't work).
  33. const refreshCycle = time.Second
  34. // refreshThrottling is the minimum time between wallet refreshes to avoid USB
  35. // trashing.
  36. const refreshThrottling = 500 * time.Millisecond
  37. // Hub is a accounts.Backend that can find and handle generic USB hardware wallets.
  38. type Hub struct {
  39. scheme string // Protocol scheme prefixing account and wallet URLs.
  40. vendorID uint16 // USB vendor identifier used for device discovery
  41. productIDs []uint16 // USB product identifiers used for device discovery
  42. usageID uint16 // USB usage page identifier used for macOS device discovery
  43. endpointID int // USB endpoint identifier used for non-macOS device discovery
  44. makeDriver func(log.Logger) driver // Factory method to construct a vendor specific driver
  45. refreshed time.Time // Time instance when the list of wallets was last refreshed
  46. wallets []accounts.Wallet // List of USB wallet devices currently tracking
  47. updateFeed event.Feed // Event feed to notify wallet additions/removals
  48. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  49. updating bool // Whether the event notification loop is running
  50. quit chan chan error
  51. stateLock sync.RWMutex // Protects the internals of the hub from racey access
  52. // TODO(karalabe): remove if hotplug lands on Windows
  53. commsPend int // Number of operations blocking enumeration
  54. commsLock sync.Mutex // Lock protecting the pending counter and enumeration
  55. }
  56. // NewLedgerHub creates a new hardware wallet manager for Ledger devices.
  57. func NewLedgerHub() (*Hub, error) {
  58. return newHub(LedgerScheme, 0x2c97, []uint16{0x0000 /* Ledger Blue */, 0x0001 /* Ledger Nano S */}, 0xffa0, 0, newLedgerDriver)
  59. }
  60. // NewTrezorHub creates a new hardware wallet manager for Trezor devices.
  61. func NewTrezorHub() (*Hub, error) {
  62. return newHub(TrezorScheme, 0x534c, []uint16{0x0001 /* Trezor 1 */}, 0xff00, 0, newTrezorDriver)
  63. }
  64. // newHub creates a new hardware wallet manager for generic USB devices.
  65. func newHub(scheme string, vendorID uint16, productIDs []uint16, usageID uint16, endpointID int, makeDriver func(log.Logger) driver) (*Hub, error) {
  66. if !hid.Supported() {
  67. return nil, errors.New("unsupported platform")
  68. }
  69. hub := &Hub{
  70. scheme: scheme,
  71. vendorID: vendorID,
  72. productIDs: productIDs,
  73. usageID: usageID,
  74. endpointID: endpointID,
  75. makeDriver: makeDriver,
  76. quit: make(chan chan error),
  77. }
  78. hub.refreshWallets()
  79. return hub, nil
  80. }
  81. // Wallets implements accounts.Backend, returning all the currently tracked USB
  82. // devices that appear to be hardware wallets.
  83. func (hub *Hub) Wallets() []accounts.Wallet {
  84. // Make sure the list of wallets is up to date
  85. hub.refreshWallets()
  86. hub.stateLock.RLock()
  87. defer hub.stateLock.RUnlock()
  88. cpy := make([]accounts.Wallet, len(hub.wallets))
  89. copy(cpy, hub.wallets)
  90. return cpy
  91. }
  92. // refreshWallets scans the USB devices attached to the machine and updates the
  93. // list of wallets based on the found devices.
  94. func (hub *Hub) refreshWallets() {
  95. // Don't scan the USB like crazy it the user fetches wallets in a loop
  96. hub.stateLock.RLock()
  97. elapsed := time.Since(hub.refreshed)
  98. hub.stateLock.RUnlock()
  99. if elapsed < refreshThrottling {
  100. return
  101. }
  102. // Retrieve the current list of USB wallet devices
  103. var devices []hid.DeviceInfo
  104. if runtime.GOOS == "linux" {
  105. // hidapi on Linux opens the device during enumeration to retrieve some infos,
  106. // breaking the Ledger protocol if that is waiting for user confirmation. This
  107. // is a bug acknowledged at Ledger, but it won't be fixed on old devices so we
  108. // need to prevent concurrent comms ourselves. The more elegant solution would
  109. // be to ditch enumeration in favor of hotplug events, but that don't work yet
  110. // on Windows so if we need to hack it anyway, this is more elegant for now.
  111. hub.commsLock.Lock()
  112. if hub.commsPend > 0 { // A confirmation is pending, don't refresh
  113. hub.commsLock.Unlock()
  114. return
  115. }
  116. }
  117. for _, info := range hid.Enumerate(hub.vendorID, 0) {
  118. for _, id := range hub.productIDs {
  119. if info.ProductID == id && (info.UsagePage == hub.usageID || info.Interface == hub.endpointID) {
  120. devices = append(devices, info)
  121. break
  122. }
  123. }
  124. }
  125. if runtime.GOOS == "linux" {
  126. // See rationale before the enumeration why this is needed and only on Linux.
  127. hub.commsLock.Unlock()
  128. }
  129. // Transform the current list of wallets into the new one
  130. hub.stateLock.Lock()
  131. wallets := make([]accounts.Wallet, 0, len(devices))
  132. events := []accounts.WalletEvent{}
  133. for _, device := range devices {
  134. url := accounts.URL{Scheme: hub.scheme, Path: device.Path}
  135. // Drop wallets in front of the next device or those that failed for some reason
  136. for len(hub.wallets) > 0 {
  137. // Abort if we're past the current device and found an operational one
  138. _, failure := hub.wallets[0].Status()
  139. if hub.wallets[0].URL().Cmp(url) >= 0 || failure == nil {
  140. break
  141. }
  142. // Drop the stale and failed devices
  143. events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Kind: accounts.WalletDropped})
  144. hub.wallets = hub.wallets[1:]
  145. }
  146. // If there are no more wallets or the device is before the next, wrap new wallet
  147. if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
  148. logger := log.New("url", url)
  149. wallet := &wallet{hub: hub, driver: hub.makeDriver(logger), url: &url, info: device, log: logger}
  150. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  151. wallets = append(wallets, wallet)
  152. continue
  153. }
  154. // If the device is the same as the first wallet, keep it
  155. if hub.wallets[0].URL().Cmp(url) == 0 {
  156. wallets = append(wallets, hub.wallets[0])
  157. hub.wallets = hub.wallets[1:]
  158. continue
  159. }
  160. }
  161. // Drop any leftover wallets and set the new batch
  162. for _, wallet := range hub.wallets {
  163. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  164. }
  165. hub.refreshed = time.Now()
  166. hub.wallets = wallets
  167. hub.stateLock.Unlock()
  168. // Fire all wallet events and return
  169. for _, event := range events {
  170. hub.updateFeed.Send(event)
  171. }
  172. }
  173. // Subscribe implements accounts.Backend, creating an async subscription to
  174. // receive notifications on the addition or removal of USB wallets.
  175. func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  176. // We need the mutex to reliably start/stop the update loop
  177. hub.stateLock.Lock()
  178. defer hub.stateLock.Unlock()
  179. // Subscribe the caller and track the subscriber count
  180. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  181. // Subscribers require an active notification loop, start it
  182. if !hub.updating {
  183. hub.updating = true
  184. go hub.updater()
  185. }
  186. return sub
  187. }
  188. // updater is responsible for maintaining an up-to-date list of wallets managed
  189. // by the USB hub, and for firing wallet addition/removal events.
  190. func (hub *Hub) updater() {
  191. for {
  192. // TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout
  193. // <-hub.changes
  194. time.Sleep(refreshCycle)
  195. // Run the wallet refresher
  196. hub.refreshWallets()
  197. // If all our subscribers left, stop the updater
  198. hub.stateLock.Lock()
  199. if hub.updateScope.Count() == 0 {
  200. hub.updating = false
  201. hub.stateLock.Unlock()
  202. return
  203. }
  204. hub.stateLock.Unlock()
  205. }
  206. }