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