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