github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/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/atheioschain/go-atheios/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  	// Subscribe to wallet notifications from all backends
    45  	updates := make(chan WalletEvent, 4*len(backends))
    46  
    47  	subs := make([]event.Subscription, len(backends))
    48  	for i, backend := range backends {
    49  		subs[i] = backend.Subscribe(updates)
    50  	}
    51  	// Retrieve the initial list of wallets from the backends and sort by URL
    52  	var wallets []Wallet
    53  	for _, backend := range backends {
    54  		wallets = merge(wallets, backend.Wallets()...)
    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  			if event.Arrive {
   100  				am.wallets = merge(am.wallets, event.Wallet)
   101  			} else {
   102  				am.wallets = drop(am.wallets, event.Wallet)
   103  			}
   104  			am.lock.Unlock()
   105  
   106  			// Notify any listeners of the event
   107  			am.feed.Send(event)
   108  
   109  		case errc := <-am.quit:
   110  			// Manager terminating, return
   111  			errc <- nil
   112  			return
   113  		}
   114  	}
   115  }
   116  
   117  // Backends retrieves the backend(s) with the given type from the account manager.
   118  func (am *Manager) Backends(kind reflect.Type) []Backend {
   119  	return am.backends[kind]
   120  }
   121  
   122  // Wallets returns all signer accounts registered under this account manager.
   123  func (am *Manager) Wallets() []Wallet {
   124  	am.lock.RLock()
   125  	defer am.lock.RUnlock()
   126  
   127  	cpy := make([]Wallet, len(am.wallets))
   128  	copy(cpy, am.wallets)
   129  	return cpy
   130  }
   131  
   132  // Wallet retrieves the wallet associated with a particular URL.
   133  func (am *Manager) Wallet(url string) (Wallet, error) {
   134  	am.lock.RLock()
   135  	defer am.lock.RUnlock()
   136  
   137  	parsed, err := parseURL(url)
   138  	if err != nil {
   139  		return nil, err
   140  	}
   141  	for _, wallet := range am.Wallets() {
   142  		if wallet.URL() == parsed {
   143  			return wallet, nil
   144  		}
   145  	}
   146  	return nil, ErrUnknownWallet
   147  }
   148  
   149  // Find attempts to locate the wallet corresponding to a specific account. Since
   150  // accounts can be dynamically added to and removed from wallets, this method has
   151  // a linear runtime in the number of wallets.
   152  func (am *Manager) Find(account Account) (Wallet, error) {
   153  	am.lock.RLock()
   154  	defer am.lock.RUnlock()
   155  
   156  	for _, wallet := range am.wallets {
   157  		if wallet.Contains(account) {
   158  			return wallet, nil
   159  		}
   160  	}
   161  	return nil, ErrUnknownAccount
   162  }
   163  
   164  // Subscribe creates an async subscription to receive notifications when the
   165  // manager detects the arrival or departure of a wallet from any of its backends.
   166  func (am *Manager) Subscribe(sink chan<- WalletEvent) event.Subscription {
   167  	return am.feed.Subscribe(sink)
   168  }
   169  
   170  // merge is a sorted analogue of append for wallets, where the ordering of the
   171  // origin list is preserved by inserting new wallets at the correct position.
   172  //
   173  // The original slice is assumed to be already sorted by URL.
   174  func merge(slice []Wallet, wallets ...Wallet) []Wallet {
   175  	for _, wallet := range wallets {
   176  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   177  		if n == len(slice) {
   178  			slice = append(slice, wallet)
   179  			continue
   180  		}
   181  		slice = append(slice[:n], append([]Wallet{wallet}, slice[n:]...)...)
   182  	}
   183  	return slice
   184  }
   185  
   186  // drop is the couterpart of merge, which looks up wallets from within the sorted
   187  // cache and removes the ones specified.
   188  func drop(slice []Wallet, wallets ...Wallet) []Wallet {
   189  	for _, wallet := range wallets {
   190  		n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 })
   191  		if n == len(slice) {
   192  			// Wallet not found, may happen during startup
   193  			continue
   194  		}
   195  		slice = append(slice[:n], slice[n+1:]...)
   196  	}
   197  	return slice
   198  }