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