ledger_hub.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. // +build !ios
  20. package usbwallet
  21. import (
  22. "fmt"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/accounts"
  26. "github.com/ethereum/go-ethereum/event"
  27. "github.com/karalabe/gousb/usb"
  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. ctx *usb.Context // Context interfacing with a libusb instance
  43. refreshed time.Time // Time instance when the list of wallets was last refreshed
  44. wallets []accounts.Wallet // List of Ledger devices currently tracking
  45. updateFeed event.Feed // Event feed to notify wallet additions/removals
  46. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  47. updating bool // Whether the event notification loop is running
  48. quit chan chan error
  49. lock sync.RWMutex
  50. }
  51. // NewLedgerHub creates a new hardware wallet manager for Ledger devices.
  52. func NewLedgerHub() (*LedgerHub, error) {
  53. // Initialize the USB library to access Ledgers through
  54. ctx, err := usb.NewContext()
  55. if err != nil {
  56. return nil, err
  57. }
  58. // Create the USB hub, start and return it
  59. hub := &LedgerHub{
  60. ctx: ctx,
  61. quit: make(chan chan error),
  62. }
  63. hub.refreshWallets()
  64. return hub, nil
  65. }
  66. // Wallets implements accounts.Backend, returning all the currently tracked USB
  67. // devices that appear to be Ledger hardware wallets.
  68. func (hub *LedgerHub) Wallets() []accounts.Wallet {
  69. // Make sure the list of wallets is up to date
  70. hub.refreshWallets()
  71. hub.lock.RLock()
  72. defer hub.lock.RUnlock()
  73. cpy := make([]accounts.Wallet, len(hub.wallets))
  74. copy(cpy, hub.wallets)
  75. return cpy
  76. }
  77. // refreshWallets scans the USB devices attached to the machine and updates the
  78. // list of wallets based on the found devices.
  79. func (hub *LedgerHub) refreshWallets() {
  80. // Don't scan the USB like crazy it the user fetches wallets in a loop
  81. hub.lock.RLock()
  82. elapsed := time.Since(hub.refreshed)
  83. hub.lock.RUnlock()
  84. if elapsed < ledgerRefreshThrottling {
  85. return
  86. }
  87. // Retrieve the current list of Ledger devices
  88. var devIDs []deviceID
  89. var busIDs []uint16
  90. hub.ctx.ListDevices(func(desc *usb.Descriptor) bool {
  91. // Gather Ledger devices, don't connect any just yet
  92. for _, id := range ledgerDeviceIDs {
  93. if desc.Vendor == id.Vendor && desc.Product == id.Product {
  94. devIDs = append(devIDs, deviceID{Vendor: desc.Vendor, Product: desc.Product})
  95. busIDs = append(busIDs, uint16(desc.Bus)<<8+uint16(desc.Address))
  96. return false
  97. }
  98. }
  99. // Not ledger, ignore and don't connect either
  100. return false
  101. })
  102. // Transform the current list of wallets into the new one
  103. hub.lock.Lock()
  104. wallets := make([]accounts.Wallet, 0, len(devIDs))
  105. events := []accounts.WalletEvent{}
  106. for i := 0; i < len(devIDs); i++ {
  107. devID, busID := devIDs[i], busIDs[i]
  108. url := accounts.URL{Scheme: LedgerScheme, Path: fmt.Sprintf("%03d:%03d", busID>>8, busID&0xff)}
  109. // Drop wallets while they were in front of the next account
  110. for len(hub.wallets) > 0 && hub.wallets[0].URL().Cmp(url) < 0 {
  111. events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Arrive: false})
  112. hub.wallets = hub.wallets[1:]
  113. }
  114. // If there are no more wallets or the account is before the next, wrap new wallet
  115. if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
  116. wallet := &ledgerWallet{context: hub.ctx, hardwareID: devID, locationID: busID, url: &url}
  117. events = append(events, accounts.WalletEvent{Wallet: wallet, Arrive: true})
  118. wallets = append(wallets, wallet)
  119. continue
  120. }
  121. // If the account is the same as the first wallet, keep it
  122. if hub.wallets[0].URL().Cmp(url) == 0 {
  123. wallets = append(wallets, hub.wallets[0])
  124. hub.wallets = hub.wallets[1:]
  125. continue
  126. }
  127. }
  128. // Drop any leftover wallets and set the new batch
  129. for _, wallet := range hub.wallets {
  130. events = append(events, accounts.WalletEvent{Wallet: wallet, Arrive: false})
  131. }
  132. hub.refreshed = time.Now()
  133. hub.wallets = wallets
  134. hub.lock.Unlock()
  135. // Fire all wallet events and return
  136. for _, event := range events {
  137. hub.updateFeed.Send(event)
  138. }
  139. }
  140. // Subscribe implements accounts.Backend, creating an async subscription to
  141. // receive notifications on the addition or removal of Ledger wallets.
  142. func (hub *LedgerHub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  143. // We need the mutex to reliably start/stop the update loop
  144. hub.lock.Lock()
  145. defer hub.lock.Unlock()
  146. // Subscribe the caller and track the subscriber count
  147. sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
  148. // Subscribers require an active notification loop, start it
  149. if !hub.updating {
  150. hub.updating = true
  151. go hub.updater()
  152. }
  153. return sub
  154. }
  155. // updater is responsible for maintaining an up-to-date list of wallets stored in
  156. // the keystore, and for firing wallet addition/removal events. It listens for
  157. // account change events from the underlying account cache, and also periodically
  158. // forces a manual refresh (only triggers for systems where the filesystem notifier
  159. // is not running).
  160. func (hub *LedgerHub) updater() {
  161. for {
  162. // Wait for a USB hotplug event (not supported yet) or a refresh timeout
  163. select {
  164. //case <-hub.changes: // reenable on hutplug implementation
  165. case <-time.After(ledgerRefreshCycle):
  166. }
  167. // Run the wallet refresher
  168. hub.refreshWallets()
  169. // If all our subscribers left, stop the updater
  170. hub.lock.Lock()
  171. if hub.updateScope.Count() == 0 {
  172. hub.updating = false
  173. hub.lock.Unlock()
  174. return
  175. }
  176. hub.lock.Unlock()
  177. }
  178. }