github.com/aaa256/atlantis@v0.0.0-20210707112435-42ee889287a2/accounts/manager.go (about)

     1  // Copyright 2017 The go-athereum Authors
     2  // This file is part of the go-athereum library.
     3  //
     4  // The go-athereum 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-athereum 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-athereum 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/athereum/go-athereum/event"
    25  )
    26  
    27  // Manager is an overarching account manager that can communicate with various
    28  // backends for signing transactions.
    29  type Manager struct {
    30  	backends map[reflect.Type][]Backend // Index of backends currently registered
    31  	updaters []event.Subscription       // Wallet update subscriptions for all backends
    32  	updates  chan WalletEvent           // Subscription sink for backend wallet changes
    33  	wallets  []Wallet                   // Cache of all wallets from all registered backends
    34  
    35  	feed event.Feed // Wallet feed notifying of arrivals/departures
    36  
    37  	quit chan chan error
    38  	lock sync.RWMutex
    39  }
    40  
    41  // NewManager creates a generic account manager to sign transaction via various
    42  // supported backends.
    43  func NewManager(backends ...Backend) *Manager {
    44  	// Retrieve the initial list of wallets from the backends and sort by URL
    45  	var wallets []Wallet
    46  	for _, backend := range backends {
    47  		wallets = merge(wallets, backend.Wallets()...)
    48  	}
    49  	// Subscribe to wallet notifications from all backends
    50  	updates := make(chan WalletEvent, 4*len(backends))
    51  
    52  	subs := make([]event.Subscription, len(backends))
    53  	for i, backend := range backends {
    54  		subs[i] = backend.Subscribe(updates)
    55  	}
    56  	// Assemble the account manager and return
    57  	am := &Manager{
    58  		backends: make(map[reflect.Type][]Backend),
    59  		updaters: subs,
    60  		updates:  updates,
    61  		wallets:  wallets,
    62  		quit:     make(chan chan error),
    63  	}
    64  	for _, backend := range backends {
    65  		kind := reflect.TypeOf(backend)
    66  		am.backends[kind] = append(am.backends[kind], backend)
    67  	}
    68  	go am.update()
    69  
    70  	return am
    71  }
    72  
    73  // Close terminates the account manager's internal notification processes.
    74  func (am *Manager) Close() error {
    75  	errc := make(chan error)
    76  	am.quit <- errc
    77  	return <-errc
    78  }
    79  
    80  // update is the wallet event loop listening for notifications from the backends
    81  // and updating the cache of wallets.
    82  func (am *Manager) update() {
    83  	// Close all subscriptions when the manager terminates
    84  	defer func() {
    85  		am.lock.Lock()
    86  		for _, sub := range am.updaters {
    87  			sub.Unsubscribe()
    88  		}
    89  		am.updaters = nil
    90  		am.lock.Unlock()
    91  	}()
    92  
    93  	// Loop until termination
    94  	for {
    95  		select {
    96  		case event := <-am.updates:
    97  			// Wallet event arrived, update local cache
    98  			am.lock.Lock()
    99  			switch event.Kind {
   100  			case WalletArrived:
   101  				am.wallets = merge(am.wallets, event.Wallet)
   102  			case WalletDropped:
   103  				am.wallets = drop(am.wallets, event.Wallet)
   104  			}
   105  			am.lock.Unlock()
   106  
   107  			// Notify any listeners of the event
   108  			am.feed.Send(event)
   109  
   110  		case errc := <-am.quit:
   111  			// Manager terminating, return
   112  			errc <- nil
   113  			return
   114  		}
   115  	}
   116  }
   117  
   118  // Backends retrieves the backend(s) with the given type from the account manager.
   119  func (am *Manager) Backends(kind reflect.Type) []Backend {
   120  	return am.backends[kind]
   121  }
   122  
   123  // Wallets returns all signer accounts registered under this account manager.
   124  func (am *Manager) Wallets() []Wallet {
   125  	am.lock.RLock()
   126  	defer am.lock.RUnlock()
   127  
   128  	cpy := make([]Wallet, len(am.wallets))
   129  	copy(cpy, am.wallets)
   130  	return cpy
   131  }
   132  
   133  // Wallet retrieves the wallet associated with a particular URL.
   134  func (am *Manager) Wallet(url string) (Wallet, error) {
   135  	am.lock.RLock()
   136  	defer am.lock.RUnlock()
   137  
   138  	parsed, err := parseURL(url)
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  	for _, wallet := range am.Wallets() {
   143  		if wallet.URL() == parsed {
   144  			return wallet, nil
   145  		}
   146  	}
   147  	return nil, ErrUnknownWallet
   148  }
   149  
   150  // Find attempts to locate the wallet corresponding to a specific account. Since
   151  // accounts can be dynamically added to and removed from wallets, this method has
   152  // a linear runtime in the number of wallets.
   153  func (am *Manager) Find(account Account) (Wallet, error) {
   154  	am.lock.RLock()
   155  	defer am.lock.RUnlock()
   156  
   157  	for _, wallet := range am.wallets {
   158  		if wallet.Contains(account) {
   159  			return wallet, nil
   160  		}
   161  	}
   162  	return nil, ErrUnknownAccount
   163  }
   164  
   165  // Subscribe creates an async subscription to receive notifications when the
   166  // manager detects the arrival or departure of a wallet from any of its backends.
   167  func (am *Manager) Subscribe(sink chan<- WalletEvent) event.Subscription {
   168  	return am.feed.Subscribe(sink)
   169  }
   170  
   171  // merge is a sorted analogue of append for wallets, where the ordering of the
   172  // origin list is preserved by inserting new wallets at the correct position.
   173  //
   174  // The original slice is assumed to be already sorted by URL.
   175  func merge(slice []Wallet, wallets ...Wallet) []Wallet {
   176  	for _, wallet := range wallets {
   177  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   178  		if n == len(slice) {
   179  			slice = append(slice, wallet)
   180  			continue
   181  		}
   182  		slice = append(slice[:n], append([]Wallet{wallet}, slice[n:]...)...)
   183  	}
   184  	return slice
   185  }
   186  
   187  // drop is the couterpart of merge, which looks up wallets from within the sorted
   188  // cache and removes the ones specified.
   189  func drop(slice []Wallet, wallets ...Wallet) []Wallet {
   190  	for _, wallet := range wallets {
   191  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   192  		if n == len(slice) {
   193  			// Wallet not found, may happen during startup
   194  			continue
   195  		}
   196  		slice = append(slice[:n], slice[n+1:]...)
   197  	}
   198  	return slice
   199  }