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