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