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