hub.go 10.0 KB

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