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