manager.go 6.3 KB

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