github.com/aquanetwork/aquachain@v1.7.8/aqua/accounts/usbwallet/hub.go (about) 1 // Copyright 2017 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 // +build usb 18 19 package usbwallet 20 21 import ( 22 "errors" 23 "runtime" 24 "sync" 25 "time" 26 27 "github.com/karalabe/hid" 28 "gitlab.com/aquachain/aquachain/aqua/accounts" 29 "gitlab.com/aquachain/aquachain/aqua/event" 30 "gitlab.com/aquachain/aquachain/common/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 } 70 71 // NewLedgerHub creates a new hardware wallet manager for Ledger devices. 72 func NewLedgerHub() (*Hub, error) { 73 return newHub(LedgerScheme, 0x2c97, []uint16{0x0000 /* Ledger Blue */, 0x0001 /* Ledger Nano S */}, 0xffa0, 0, newLedgerDriver) 74 } 75 76 // NewTrezorHub creates a new hardware wallet manager for Trezor devices. 77 func NewTrezorHub() (*Hub, error) { 78 return newHub(TrezorScheme, 0x534c, []uint16{0x0001 /* Trezor 1 */}, 0xff00, 0, newTrezorDriver) 79 } 80 81 // newHub creates a new hardware wallet manager for generic USB devices. 82 func newHub(scheme string, vendorID uint16, productIDs []uint16, usageID uint16, endpointID int, makeDriver func(log.Logger) driver) (*Hub, error) { 83 if !hid.Supported() { 84 return nil, errors.New("unsupported platform") 85 } 86 hub := &Hub{ 87 scheme: scheme, 88 vendorID: vendorID, 89 productIDs: productIDs, 90 usageID: usageID, 91 endpointID: endpointID, 92 makeDriver: makeDriver, 93 quit: make(chan chan error), 94 } 95 hub.refreshWallets() 96 return hub, nil 97 } 98 99 // Wallets implements accounts.Backend, returning all the currently tracked USB 100 // devices that appear to be hardware wallets. 101 func (hub *Hub) Wallets() []accounts.Wallet { 102 // Make sure the list of wallets is up to date 103 hub.refreshWallets() 104 105 hub.stateLock.RLock() 106 defer hub.stateLock.RUnlock() 107 108 cpy := make([]accounts.Wallet, len(hub.wallets)) 109 copy(cpy, hub.wallets) 110 return cpy 111 } 112 113 // refreshWallets scans the USB devices attached to the machine and updates the 114 // list of wallets based on the found devices. 115 func (hub *Hub) refreshWallets() { 116 // Don't scan the USB like crazy it the user fetches wallets in a loop 117 hub.stateLock.RLock() 118 elapsed := time.Since(hub.refreshed) 119 hub.stateLock.RUnlock() 120 121 if elapsed < refreshThrottling { 122 return 123 } 124 // Retrieve the current list of USB wallet devices 125 var devices []hid.DeviceInfo 126 127 if runtime.GOOS == "linux" { 128 // hidapi on Linux opens the device during enumeration to retrieve some infos, 129 // breaking the Ledger protocol if that is waiting for user confirmation. This 130 // is a bug acknowledged at Ledger, but it won't be fixed on old devices so we 131 // need to prevent concurrent comms ourselves. The more elegant solution would 132 // be to ditch enumeration in favor of hutplug events, but that don't work yet 133 // on Windows so if we need to hack it anyway, this is more elegant for now. 134 hub.commsLock.Lock() 135 if hub.commsPend > 0 { // A confirmation is pending, don't refresh 136 hub.commsLock.Unlock() 137 return 138 } 139 } 140 for _, info := range hid.Enumerate(hub.vendorID, 0) { 141 for _, id := range hub.productIDs { 142 if info.ProductID == id && (info.UsagePage == hub.usageID || info.Interface == hub.endpointID) { 143 devices = append(devices, info) 144 break 145 } 146 } 147 } 148 if runtime.GOOS == "linux" { 149 // See rationale before the enumeration why this is needed and only on Linux. 150 hub.commsLock.Unlock() 151 } 152 // Transform the current list of wallets into the new one 153 hub.stateLock.Lock() 154 155 wallets := make([]accounts.Wallet, 0, len(devices)) 156 events := []accounts.WalletEvent{} 157 158 for _, device := range devices { 159 url := accounts.URL{Scheme: hub.scheme, Path: device.Path} 160 161 // Drop wallets in front of the next device or those that failed for some reason 162 for len(hub.wallets) > 0 { 163 // Abort if we're past the current device and found an operational one 164 _, failure := hub.wallets[0].Status() 165 if hub.wallets[0].URL().Cmp(url) >= 0 || failure == nil { 166 break 167 } 168 // Drop the stale and failed devices 169 events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Kind: accounts.WalletDropped}) 170 hub.wallets = hub.wallets[1:] 171 } 172 // If there are no more wallets or the device is before the next, wrap new wallet 173 if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 { 174 logger := log.New("url", url) 175 wallet := &wallet{hub: hub, driver: hub.makeDriver(logger), url: &url, info: device, log: logger} 176 177 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived}) 178 wallets = append(wallets, wallet) 179 continue 180 } 181 // If the device is the same as the first wallet, keep it 182 if hub.wallets[0].URL().Cmp(url) == 0 { 183 wallets = append(wallets, hub.wallets[0]) 184 hub.wallets = hub.wallets[1:] 185 continue 186 } 187 } 188 // Drop any leftover wallets and set the new batch 189 for _, wallet := range hub.wallets { 190 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped}) 191 } 192 hub.refreshed = time.Now() 193 hub.wallets = wallets 194 hub.stateLock.Unlock() 195 196 // Fire all wallet events and return 197 for _, event := range events { 198 hub.updateFeed.Send(event) 199 } 200 } 201 202 // Subscribe implements accounts.Backend, creating an async subscription to 203 // receive notifications on the addition or removal of USB wallets. 204 func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription { 205 // We need the mutex to reliably start/stop the update loop 206 hub.stateLock.Lock() 207 defer hub.stateLock.Unlock() 208 209 // Subscribe the caller and track the subscriber count 210 sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink)) 211 212 // Subscribers require an active notification loop, start it 213 if !hub.updating { 214 hub.updating = true 215 go hub.updater() 216 } 217 return sub 218 } 219 220 // updater is responsible for maintaining an up-to-date list of wallets managed 221 // by the USB hub, and for firing wallet addition/removal events. 222 func (hub *Hub) updater() { 223 for { 224 // TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout 225 // <-hub.changes 226 time.Sleep(refreshCycle) 227 228 // Run the wallet refresher 229 hub.refreshWallets() 230 231 // If all our subscribers left, stop the updater 232 hub.stateLock.Lock() 233 if hub.updateScope.Count() == 0 { 234 hub.updating = false 235 hub.stateLock.Unlock() 236 return 237 } 238 hub.stateLock.Unlock() 239 } 240 }