github.com/ethereum/go-ethereum@v1.14.3/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  	for _, w := range am.wallets {
   102  		w.Close()
   103  	}
   104  	errc := make(chan error)
   105  	am.quit <- errc
   106  	return <-errc
   107  }
   108  
   109  // Config returns the configuration of account manager.
   110  func (am *Manager) Config() *Config {
   111  	return am.config
   112  }
   113  
   114  // AddBackend starts the tracking of an additional backend for wallet updates.
   115  // cmd/geth assumes once this func returns the backends have been already integrated.
   116  func (am *Manager) AddBackend(backend Backend) {
   117  	done := make(chan struct{})
   118  	am.newBackends <- newBackendEvent{backend, done}
   119  	<-done
   120  }
   121  
   122  // update is the wallet event loop listening for notifications from the backends
   123  // and updating the cache of wallets.
   124  func (am *Manager) update() {
   125  	// Close all subscriptions when the manager terminates
   126  	defer func() {
   127  		am.lock.Lock()
   128  		for _, sub := range am.updaters {
   129  			sub.Unsubscribe()
   130  		}
   131  		am.updaters = nil
   132  		am.lock.Unlock()
   133  	}()
   134  
   135  	// Loop until termination
   136  	for {
   137  		select {
   138  		case event := <-am.updates:
   139  			// Wallet event arrived, update local cache
   140  			am.lock.Lock()
   141  			switch event.Kind {
   142  			case WalletArrived:
   143  				am.wallets = merge(am.wallets, event.Wallet)
   144  			case WalletDropped:
   145  				am.wallets = drop(am.wallets, event.Wallet)
   146  			}
   147  			am.lock.Unlock()
   148  
   149  			// Notify any listeners of the event
   150  			am.feed.Send(event)
   151  		case event := <-am.newBackends:
   152  			am.lock.Lock()
   153  			// Update caches
   154  			backend := event.backend
   155  			am.wallets = merge(am.wallets, backend.Wallets()...)
   156  			am.updaters = append(am.updaters, backend.Subscribe(am.updates))
   157  			kind := reflect.TypeOf(backend)
   158  			am.backends[kind] = append(am.backends[kind], backend)
   159  			am.lock.Unlock()
   160  			close(event.processed)
   161  		case errc := <-am.quit:
   162  			// Manager terminating, return
   163  			errc <- nil
   164  			// Signals event emitters the loop is not receiving values
   165  			// to prevent them from getting stuck.
   166  			close(am.term)
   167  			return
   168  		}
   169  	}
   170  }
   171  
   172  // Backends retrieves the backend(s) with the given type from the account manager.
   173  func (am *Manager) Backends(kind reflect.Type) []Backend {
   174  	am.lock.RLock()
   175  	defer am.lock.RUnlock()
   176  
   177  	return am.backends[kind]
   178  }
   179  
   180  // Wallets returns all signer accounts registered under this account manager.
   181  func (am *Manager) Wallets() []Wallet {
   182  	am.lock.RLock()
   183  	defer am.lock.RUnlock()
   184  
   185  	return am.walletsNoLock()
   186  }
   187  
   188  // walletsNoLock returns all registered wallets. Callers must hold am.lock.
   189  func (am *Manager) walletsNoLock() []Wallet {
   190  	cpy := make([]Wallet, len(am.wallets))
   191  	copy(cpy, am.wallets)
   192  	return cpy
   193  }
   194  
   195  // Wallet retrieves the wallet associated with a particular URL.
   196  func (am *Manager) Wallet(url string) (Wallet, error) {
   197  	am.lock.RLock()
   198  	defer am.lock.RUnlock()
   199  
   200  	parsed, err := parseURL(url)
   201  	if err != nil {
   202  		return nil, err
   203  	}
   204  	for _, wallet := range am.walletsNoLock() {
   205  		if wallet.URL() == parsed {
   206  			return wallet, nil
   207  		}
   208  	}
   209  	return nil, ErrUnknownWallet
   210  }
   211  
   212  // Accounts returns all account addresses of all wallets within the account manager
   213  func (am *Manager) Accounts() []common.Address {
   214  	am.lock.RLock()
   215  	defer am.lock.RUnlock()
   216  
   217  	addresses := make([]common.Address, 0) // return [] instead of nil if empty
   218  	for _, wallet := range am.wallets {
   219  		for _, account := range wallet.Accounts() {
   220  			addresses = append(addresses, account.Address)
   221  		}
   222  	}
   223  	return addresses
   224  }
   225  
   226  // Find attempts to locate the wallet corresponding to a specific account. Since
   227  // accounts can be dynamically added to and removed from wallets, this method has
   228  // a linear runtime in the number of wallets.
   229  func (am *Manager) Find(account Account) (Wallet, error) {
   230  	am.lock.RLock()
   231  	defer am.lock.RUnlock()
   232  
   233  	for _, wallet := range am.wallets {
   234  		if wallet.Contains(account) {
   235  			return wallet, nil
   236  		}
   237  	}
   238  	return nil, ErrUnknownAccount
   239  }
   240  
   241  // Subscribe creates an async subscription to receive notifications when the
   242  // manager detects the arrival or departure of a wallet from any of its backends.
   243  func (am *Manager) Subscribe(sink chan<- WalletEvent) event.Subscription {
   244  	return am.feed.Subscribe(sink)
   245  }
   246  
   247  // merge is a sorted analogue of append for wallets, where the ordering of the
   248  // origin list is preserved by inserting new wallets at the correct position.
   249  //
   250  // The original slice is assumed to be already sorted by URL.
   251  func merge(slice []Wallet, wallets ...Wallet) []Wallet {
   252  	for _, wallet := range wallets {
   253  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   254  		if n == len(slice) {
   255  			slice = append(slice, wallet)
   256  			continue
   257  		}
   258  		slice = append(slice[:n], append([]Wallet{wallet}, slice[n:]...)...)
   259  	}
   260  	return slice
   261  }
   262  
   263  // drop is the counterpart of merge, which looks up wallets from within the sorted
   264  // cache and removes the ones specified.
   265  func drop(slice []Wallet, wallets ...Wallet) []Wallet {
   266  	for _, wallet := range wallets {
   267  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   268  		if n == len(slice) {
   269  			// Wallet not found, may happen during startup
   270  			continue
   271  		}
   272  		slice = append(slice[:n], slice[n+1:]...)
   273  	}
   274  	return slice
   275  }