github.com/jimmyx0x/go-ethereum@v1.10.28/accounts/manager.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 accounts
    18  
    19  import (
    20  	"reflect"
    21  	"sort"
    22  	"sync"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/event"
    26  )
    27  
    28  // managerSubBufferSize determines how many incoming wallet events
    29  // the manager will buffer in its channel.
    30  const managerSubBufferSize = 50
    31  
    32  // Config contains the settings of the global account manager.
    33  //
    34  // TODO(rjl493456442, karalabe, holiman): Get rid of this when account management
    35  // is removed in favor of Clef.
    36  type Config struct {
    37  	InsecureUnlockAllowed bool // Whether account unlocking in insecure environment is allowed
    38  }
    39  
    40  // newBackendEvent lets the manager know it should
    41  // track the given backend for wallet updates.
    42  type newBackendEvent struct {
    43  	backend   Backend
    44  	processed chan struct{} // Informs event emitter that backend has been integrated
    45  }
    46  
    47  // Manager is an overarching account manager that can communicate with various
    48  // backends for signing transactions.
    49  type Manager struct {
    50  	config      *Config                    // Global account manager configurations
    51  	backends    map[reflect.Type][]Backend // Index of backends currently registered
    52  	updaters    []event.Subscription       // Wallet update subscriptions for all backends
    53  	updates     chan WalletEvent           // Subscription sink for backend wallet changes
    54  	newBackends chan newBackendEvent       // Incoming backends to be tracked by the manager
    55  	wallets     []Wallet                   // Cache of all wallets from all registered backends
    56  
    57  	feed event.Feed // Wallet feed notifying of arrivals/departures
    58  
    59  	quit chan chan error
    60  	term chan struct{} // Channel is closed upon termination of the update loop
    61  	lock sync.RWMutex
    62  }
    63  
    64  // NewManager creates a generic account manager to sign transaction via various
    65  // supported backends.
    66  func NewManager(config *Config, backends ...Backend) *Manager {
    67  	// Retrieve the initial list of wallets from the backends and sort by URL
    68  	var wallets []Wallet
    69  	for _, backend := range backends {
    70  		wallets = merge(wallets, backend.Wallets()...)
    71  	}
    72  	// Subscribe to wallet notifications from all backends
    73  	updates := make(chan WalletEvent, managerSubBufferSize)
    74  
    75  	subs := make([]event.Subscription, len(backends))
    76  	for i, backend := range backends {
    77  		subs[i] = backend.Subscribe(updates)
    78  	}
    79  	// Assemble the account manager and return
    80  	am := &Manager{
    81  		config:      config,
    82  		backends:    make(map[reflect.Type][]Backend),
    83  		updaters:    subs,
    84  		updates:     updates,
    85  		newBackends: make(chan newBackendEvent),
    86  		wallets:     wallets,
    87  		quit:        make(chan chan error),
    88  		term:        make(chan struct{}),
    89  	}
    90  	for _, backend := range backends {
    91  		kind := reflect.TypeOf(backend)
    92  		am.backends[kind] = append(am.backends[kind], backend)
    93  	}
    94  	go am.update()
    95  
    96  	return am
    97  }
    98  
    99  // Close terminates the account manager's internal notification processes.
   100  func (am *Manager) Close() error {
   101  	errc := make(chan error)
   102  	am.quit <- errc
   103  	return <-errc
   104  }
   105  
   106  // Config returns the configuration of account manager.
   107  func (am *Manager) Config() *Config {
   108  	return am.config
   109  }
   110  
   111  // AddBackend starts the tracking of an additional backend for wallet updates.
   112  // cmd/geth assumes once this func returns the backends have been already integrated.
   113  func (am *Manager) AddBackend(backend Backend) {
   114  	done := make(chan struct{})
   115  	am.newBackends <- newBackendEvent{backend, done}
   116  	<-done
   117  }
   118  
   119  // update is the wallet event loop listening for notifications from the backends
   120  // and updating the cache of wallets.
   121  func (am *Manager) update() {
   122  	// Close all subscriptions when the manager terminates
   123  	defer func() {
   124  		am.lock.Lock()
   125  		for _, sub := range am.updaters {
   126  			sub.Unsubscribe()
   127  		}
   128  		am.updaters = nil
   129  		am.lock.Unlock()
   130  	}()
   131  
   132  	// Loop until termination
   133  	for {
   134  		select {
   135  		case event := <-am.updates:
   136  			// Wallet event arrived, update local cache
   137  			am.lock.Lock()
   138  			switch event.Kind {
   139  			case WalletArrived:
   140  				am.wallets = merge(am.wallets, event.Wallet)
   141  			case WalletDropped:
   142  				am.wallets = drop(am.wallets, event.Wallet)
   143  			}
   144  			am.lock.Unlock()
   145  
   146  			// Notify any listeners of the event
   147  			am.feed.Send(event)
   148  		case event := <-am.newBackends:
   149  			am.lock.Lock()
   150  			// Update caches
   151  			backend := event.backend
   152  			am.wallets = merge(am.wallets, backend.Wallets()...)
   153  			am.updaters = append(am.updaters, backend.Subscribe(am.updates))
   154  			kind := reflect.TypeOf(backend)
   155  			am.backends[kind] = append(am.backends[kind], backend)
   156  			am.lock.Unlock()
   157  			close(event.processed)
   158  		case errc := <-am.quit:
   159  			// Manager terminating, return
   160  			errc <- nil
   161  			// Signals event emitters the loop is not receiving values
   162  			// to prevent them from getting stuck.
   163  			close(am.term)
   164  			return
   165  		}
   166  	}
   167  }
   168  
   169  // Backends retrieves the backend(s) with the given type from the account manager.
   170  func (am *Manager) Backends(kind reflect.Type) []Backend {
   171  	am.lock.RLock()
   172  	defer am.lock.RUnlock()
   173  
   174  	return am.backends[kind]
   175  }
   176  
   177  // Wallets returns all signer accounts registered under this account manager.
   178  func (am *Manager) Wallets() []Wallet {
   179  	am.lock.RLock()
   180  	defer am.lock.RUnlock()
   181  
   182  	return am.walletsNoLock()
   183  }
   184  
   185  // walletsNoLock returns all registered wallets. Callers must hold am.lock.
   186  func (am *Manager) walletsNoLock() []Wallet {
   187  	cpy := make([]Wallet, len(am.wallets))
   188  	copy(cpy, am.wallets)
   189  	return cpy
   190  }
   191  
   192  // Wallet retrieves the wallet associated with a particular URL.
   193  func (am *Manager) Wallet(url string) (Wallet, error) {
   194  	am.lock.RLock()
   195  	defer am.lock.RUnlock()
   196  
   197  	parsed, err := parseURL(url)
   198  	if err != nil {
   199  		return nil, err
   200  	}
   201  	for _, wallet := range am.walletsNoLock() {
   202  		if wallet.URL() == parsed {
   203  			return wallet, nil
   204  		}
   205  	}
   206  	return nil, ErrUnknownWallet
   207  }
   208  
   209  // Accounts returns all account addresses of all wallets within the account manager
   210  func (am *Manager) Accounts() []common.Address {
   211  	am.lock.RLock()
   212  	defer am.lock.RUnlock()
   213  
   214  	addresses := make([]common.Address, 0) // return [] instead of nil if empty
   215  	for _, wallet := range am.wallets {
   216  		for _, account := range wallet.Accounts() {
   217  			addresses = append(addresses, account.Address)
   218  		}
   219  	}
   220  	return addresses
   221  }
   222  
   223  // Find attempts to locate the wallet corresponding to a specific account. Since
   224  // accounts can be dynamically added to and removed from wallets, this method has
   225  // a linear runtime in the number of wallets.
   226  func (am *Manager) Find(account Account) (Wallet, error) {
   227  	am.lock.RLock()
   228  	defer am.lock.RUnlock()
   229  
   230  	for _, wallet := range am.wallets {
   231  		if wallet.Contains(account) {
   232  			return wallet, nil
   233  		}
   234  	}
   235  	return nil, ErrUnknownAccount
   236  }
   237  
   238  // Subscribe creates an async subscription to receive notifications when the
   239  // manager detects the arrival or departure of a wallet from any of its backends.
   240  func (am *Manager) Subscribe(sink chan<- WalletEvent) event.Subscription {
   241  	return am.feed.Subscribe(sink)
   242  }
   243  
   244  // merge is a sorted analogue of append for wallets, where the ordering of the
   245  // origin list is preserved by inserting new wallets at the correct position.
   246  //
   247  // The original slice is assumed to be already sorted by URL.
   248  func merge(slice []Wallet, wallets ...Wallet) []Wallet {
   249  	for _, wallet := range wallets {
   250  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   251  		if n == len(slice) {
   252  			slice = append(slice, wallet)
   253  			continue
   254  		}
   255  		slice = append(slice[:n], append([]Wallet{wallet}, slice[n:]...)...)
   256  	}
   257  	return slice
   258  }
   259  
   260  // drop is the counterpart of merge, which looks up wallets from within the sorted
   261  // cache and removes the ones specified.
   262  func drop(slice []Wallet, wallets ...Wallet) []Wallet {
   263  	for _, wallet := range wallets {
   264  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   265  		if n == len(slice) {
   266  			// Wallet not found, may happen during startup
   267  			continue
   268  		}
   269  		slice = append(slice[:n], slice[n+1:]...)
   270  	}
   271  	return slice
   272  }