manager.go 5.8 KB

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