hub.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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/usb"
  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{
  59. // Original product IDs
  60. 0x0000, /* Ledger Blue */
  61. 0x0001, /* Ledger Nano S */
  62. 0x0004, /* Ledger Nano X */
  63. // Upcoming product IDs: https://www.ledger.com/2019/05/17/windows-10-update-sunsetting-u2f-tunnel-transport-for-ledger-devices/
  64. 0x0015, /* HID + U2F + WebUSB Ledger Blue */
  65. 0x1015, /* HID + U2F + WebUSB Ledger Nano S */
  66. 0x4015, /* HID + U2F + WebUSB Ledger Nano X */
  67. 0x0011, /* HID + WebUSB Ledger Blue */
  68. 0x1011, /* HID + WebUSB Ledger Nano S */
  69. 0x4011, /* HID + WebUSB Ledger Nano X */
  70. }, 0xffa0, 0, newLedgerDriver)
  71. }
  72. // NewTrezorHubWithHID creates a new hardware wallet manager for Trezor devices.
  73. func NewTrezorHubWithHID() (*Hub, error) {
  74. return newHub(TrezorScheme, 0x534c, []uint16{0x0001 /* Trezor HID */}, 0xff00, 0, newTrezorDriver)
  75. }
  76. // NewTrezorHubWithWebUSB creates a new hardware wallet manager for Trezor devices with
  77. // firmware version > 1.8.0
  78. func NewTrezorHubWithWebUSB() (*Hub, error) {
  79. return newHub(TrezorScheme, 0x1209, []uint16{0x53c1 /* Trezor WebUSB */}, 0xffff /* No usage id on webusb, don't match unset (0) */, 0, newTrezorDriver)
  80. }
  81. // newHub creates a new hardware wallet manager for generic USB devices.
  82. func newHub(scheme string, vendorID uint16, productIDs []uint16, usageID uint16, endpointID int, makeDriver func(log.Logger) driver) (*Hub, error) {
  83. if !usb.Supported() {
  84. return nil, errors.New("unsupported platform")
  85. }
  86. hub := &Hub{
  87. scheme: scheme,
  88. vendorID: vendorID,
  89. productIDs: productIDs,
  90. usageID: usageID,
  91. endpointID: endpointID,
  92. makeDriver: makeDriver,
  93. quit: make(chan chan error),
  94. }
  95. hub.refreshWallets()
  96. return hub, nil
  97. }
  98. // Wallets implements accounts.Backend, returning all the currently tracked USB
  99. // devices that appear to be hardware wallets.
  100. func (hub *Hub) Wallets() []accounts.Wallet {
  101. // Make sure the list of wallets is up to date
  102. hub.refreshWallets()
  103. hub.stateLock.RLock()
  104. defer hub.stateLock.RUnlock()
  105. cpy := make([]accounts.Wallet, len(hub.wallets))
  106. copy(cpy, hub.wallets)
  107. return cpy
  108. }
  109. // refreshWallets scans the USB devices attached to the machine and updates the
  110. // list of wallets based on the found devices.
  111. func (hub *Hub) refreshWallets() {
  112. // Don't scan the USB like crazy it the user fetches wallets in a loop
  113. hub.stateLock.RLock()
  114. elapsed := time.Since(hub.refreshed)
  115. hub.stateLock.RUnlock()
  116. if elapsed < refreshThrottling {
  117. return
  118. }
  119. // Retrieve the current list of USB wallet devices
  120. var devices []usb.DeviceInfo
  121. if runtime.GOOS == "linux" {
  122. // hidapi on Linux opens the device during enumeration to retrieve some infos,
  123. // breaking the Ledger protocol if that is waiting for user confirmation. This
  124. // is a bug acknowledged at Ledger, but it won't be fixed on old devices so we
  125. // need to prevent concurrent comms ourselves. The more elegant solution would
  126. // be to ditch enumeration in favor of hotplug events, but that don't work yet
  127. // on Windows so if we need to hack it anyway, this is more elegant for now.
  128. hub.commsLock.Lock()
  129. if hub.commsPend > 0 { // A confirmation is pending, don't refresh
  130. hub.commsLock.Unlock()
  131. return
  132. }
  133. }
  134. infos, err := usb.Enumerate(hub.vendorID, 0)
  135. if err != nil {
  136. if runtime.GOOS == "linux" {
  137. // See rationale before the enumeration why this is needed and only on Linux.
  138. hub.commsLock.Unlock()
  139. }
  140. log.Error("error enumerating USB enumeration: ", "code", err)
  141. return
  142. }
  143. for _, info := range infos {
  144. for _, id := range hub.productIDs {
  145. // Windows and Macos use UsageID matching, Linux uses Interface matching
  146. if info.ProductID == id && (info.UsagePage == hub.usageID || info.Interface == hub.endpointID) {
  147. devices = append(devices, info)
  148. break
  149. }
  150. }
  151. }
  152. if runtime.GOOS == "linux" {
  153. // See rationale before the enumeration why this is needed and only on Linux.
  154. hub.commsLock.Unlock()
  155. }
  156. // Transform the current list of wallets into the new one
  157. hub.stateLock.Lock()
  158. var (
  159. wallets = make([]accounts.Wallet, 0, len(devices))
  160. events []accounts.WalletEvent
  161. )
  162. for _, device := range devices {
  163. url := accounts.URL{Scheme: hub.scheme, Path: device.Path}
  164. // Drop wallets in front of the next device or those that failed for some reason
  165. for len(hub.wallets) > 0 {
  166. // Abort if we're past the current device and found an operational one
  167. _, failure := hub.wallets[0].Status()
  168. if hub.wallets[0].URL().Cmp(url) >= 0 || failure == nil {
  169. break
  170. }
  171. // Drop the stale and failed devices
  172. events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Kind: accounts.WalletDropped})
  173. hub.wallets = hub.wallets[1:]
  174. }
  175. // If there are no more wallets or the device is before the next, wrap new wallet
  176. if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
  177. logger := log.New("url", url)
  178. wallet := &wallet{hub: hub, driver: hub.makeDriver(logger), url: &url, info: device, log: logger}
  179. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  180. wallets = append(wallets, wallet)
  181. continue
  182. }
  183. // If the device is the same as the first wallet, keep it
  184. if hub.wallets[0].URL().Cmp(url) == 0 {
  185. wallets = append(wallets, hub.wallets[0])
  186. hub.wallets = hub.wallets[1:]
  187. continue
  188. }
  189. }
  190. // Drop any leftover wallets and set the new batch
  191. for _, wallet := range hub.wallets {
  192. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  193. }
  194. hub.refreshed = time.Now()
  195. hub.wallets = wallets
  196. hub.stateLock.Unlock()
  197. // Fire all wallet events and return
  198. for _, event := range events {
  199. hub.updateFeed.Send(event)
  200. }
  201. }
  202. // Subscribe implements accounts.Backend, creating an async subscription to
  203. // receive notifications on the addition or removal of USB wallets.
  204. func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  205. // We need the mutex to reliably start/stop the update loop
  206. hub.stateLock.Lock()
  207. defer hub.stateLock.Unlock()
  208. // Subscribe the caller and track the subscriber count
  209. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  210. // Subscribers require an active notification loop, start it
  211. if !hub.updating {
  212. hub.updating = true
  213. go hub.updater()
  214. }
  215. return sub
  216. }
  217. // updater is responsible for maintaining an up-to-date list of wallets managed
  218. // by the USB hub, and for firing wallet addition/removal events.
  219. func (hub *Hub) updater() {
  220. for {
  221. // TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout
  222. // <-hub.changes
  223. time.Sleep(refreshCycle)
  224. // Run the wallet refresher
  225. hub.refreshWallets()
  226. // If all our subscribers left, stop the updater
  227. hub.stateLock.Lock()
  228. if hub.updateScope.Count() == 0 {
  229. hub.updating = false
  230. hub.stateLock.Unlock()
  231. return
  232. }
  233. hub.stateLock.Unlock()
  234. }
  235. }