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