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