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