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