manager.go 5.8 KB

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