github.com/amazechain/amc@v0.1.3/accounts/manager.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain 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/amazechain/amc/common/types" 25 event "github.com/amazechain/amc/modules/event/v2" 26 ) 27 28 // managerSubBufferSize determines how many incoming wallet events 29 // the manager will buffer in its channel. 30 const managerSubBufferSize = 50 31 32 // Config contains the settings of the global account manager. 33 // 34 // TODO(rjl493456442, karalabe, holiman): Get rid of this when account management 35 // is removed in favor of Clef. 36 type Config struct { 37 InsecureUnlockAllowed bool // Whether account unlocking in insecure environment is allowed 38 } 39 40 // newBackendEvent lets the manager know it should 41 // track the given backend for wallet updates. 42 type newBackendEvent struct { 43 backend Backend 44 processed chan struct{} // Informs event emitter that backend has been integrated 45 } 46 47 // Manager is an overarching account manager that can communicate with various 48 // backends for signing transactions. 49 type Manager struct { 50 config *Config // Global account manager configurations 51 backends map[reflect.Type][]Backend // Index of backends currently registered 52 updaters []event.Subscription // Wallet update subscriptions for all backends 53 updates chan WalletEvent // Subscription sink for backend wallet changes 54 newBackends chan newBackendEvent // Incoming backends to be tracked by the manager 55 wallets []Wallet // Cache of all wallets from all registered backends 56 57 quit chan chan error 58 term chan struct{} // Channel is closed upon termination of the update loop 59 lock sync.RWMutex 60 } 61 62 // NewManager creates a generic account manager to sign transaction via various 63 // supported backends. 64 func NewManager(config *Config, backends ...Backend) *Manager { 65 // Retrieve the initial list of wallets from the backends and sort by URL 66 var wallets []Wallet 67 for _, backend := range backends { 68 wallets = merge(wallets, backend.Wallets()...) 69 } 70 // Subscribe to wallet notifications from all backends 71 updates := make(chan WalletEvent, managerSubBufferSize) 72 73 subs := make([]event.Subscription, len(backends)) 74 for i, backend := range backends { 75 subs[i] = backend.Subscribe(updates) 76 } 77 // Assemble the account manager and return 78 am := &Manager{ 79 config: config, 80 backends: make(map[reflect.Type][]Backend), 81 updaters: subs, 82 updates: updates, 83 newBackends: make(chan newBackendEvent), 84 wallets: wallets, 85 quit: make(chan chan error), 86 term: make(chan struct{}), 87 } 88 for _, backend := range backends { 89 kind := reflect.TypeOf(backend) 90 am.backends[kind] = append(am.backends[kind], backend) 91 } 92 go am.update() 93 94 return am 95 } 96 97 // Close terminates the account manager's internal notification processes. 98 func (am *Manager) Close() error { 99 errc := make(chan error) 100 am.quit <- errc 101 return <-errc 102 } 103 104 // Config returns the configuration of account manager. 105 func (am *Manager) Config() *Config { 106 return am.config 107 } 108 109 // AddBackend starts the tracking of an additional backend for wallet updates. 110 // cmd/geth assumes once this func returns the backends have been already integrated. 111 func (am *Manager) AddBackend(backend Backend) { 112 done := make(chan struct{}) 113 am.newBackends <- newBackendEvent{backend, done} 114 <-done 115 } 116 117 // update is the wallet event loop listening for notifications from the backends 118 // and updating the cache of wallets. 119 func (am *Manager) update() { 120 // Close all subscriptions when the manager terminates 121 defer func() { 122 am.lock.Lock() 123 for _, sub := range am.updaters { 124 sub.Unsubscribe() 125 } 126 am.updaters = nil 127 am.lock.Unlock() 128 }() 129 130 // Loop until termination 131 for { 132 select { 133 case walletEvent := <-am.updates: 134 // Wallet event arrived, update local cache 135 am.lock.Lock() 136 switch walletEvent.Kind { 137 case WalletArrived: 138 am.wallets = merge(am.wallets, walletEvent.Wallet) 139 case WalletDropped: 140 am.wallets = drop(am.wallets, walletEvent.Wallet) 141 } 142 am.lock.Unlock() 143 144 // Notify any listeners of the event 145 146 //am.feed.Send(&walletEvent) 147 event.GlobalEvent.Send(walletEvent) 148 case backendEvent := <-am.newBackends: 149 am.lock.Lock() 150 // Update caches 151 backend := backendEvent.backend 152 am.wallets = merge(am.wallets, backend.Wallets()...) 153 am.updaters = append(am.updaters, backend.Subscribe(am.updates)) 154 kind := reflect.TypeOf(backend) 155 am.backends[kind] = append(am.backends[kind], backend) 156 am.lock.Unlock() 157 close(backendEvent.processed) 158 case errc := <-am.quit: 159 // Manager terminating, return 160 errc <- nil 161 // Signals event emitters the loop is not receiving values 162 // to prevent them from getting stuck. 163 close(am.term) 164 return 165 } 166 } 167 } 168 169 // Backends retrieves the backend(s) with the given type from the account manager. 170 func (am *Manager) Backends(kind reflect.Type) []Backend { 171 am.lock.RLock() 172 defer am.lock.RUnlock() 173 174 return am.backends[kind] 175 } 176 177 // Wallets returns all signer accounts registered under this account manager. 178 func (am *Manager) Wallets() []Wallet { 179 am.lock.RLock() 180 defer am.lock.RUnlock() 181 182 return am.walletsNoLock() 183 } 184 185 // walletsNoLock returns all registered wallets. Callers must hold am.lock. 186 func (am *Manager) walletsNoLock() []Wallet { 187 cpy := make([]Wallet, len(am.wallets)) 188 copy(cpy, am.wallets) 189 return cpy 190 } 191 192 // Wallet retrieves the wallet associated with a particular URL. 193 func (am *Manager) Wallet(url string) (Wallet, error) { 194 am.lock.RLock() 195 defer am.lock.RUnlock() 196 197 parsed, err := parseURL(url) 198 if err != nil { 199 return nil, err 200 } 201 for _, wallet := range am.walletsNoLock() { 202 if wallet.URL() == parsed { 203 return wallet, nil 204 } 205 } 206 return nil, ErrUnknownWallet 207 } 208 209 // Accounts returns all account addresses of all wallets within the account manager 210 func (am *Manager) Accounts() []types.Address { 211 am.lock.RLock() 212 defer am.lock.RUnlock() 213 214 addresses := make([]types.Address, 0) // return [] instead of nil if empty 215 for _, wallet := range am.wallets { 216 for _, account := range wallet.Accounts() { 217 addresses = append(addresses, account.Address) 218 } 219 } 220 return addresses 221 } 222 223 // Find attempts to locate the wallet corresponding to a specific account. Since 224 // accounts can be dynamically added to and removed from wallets, this method has 225 // a linear runtime in the number of wallets. 226 func (am *Manager) Find(account Account) (Wallet, error) { 227 am.lock.RLock() 228 defer am.lock.RUnlock() 229 230 for _, wallet := range am.wallets { 231 if wallet.Contains(account) { 232 return wallet, nil 233 } 234 } 235 return nil, ErrUnknownAccount 236 } 237 238 // Subscribe creates an async subscription to receive notifications when the 239 // manager detects the arrival or departure of a wallet from any of its backends. 240 func (am *Manager) Subscribe(sink chan<- WalletEvent) event.Subscription { 241 return event.GlobalEvent.Subscribe(sink) 242 } 243 244 // merge is a sorted analogue of append for wallets, where the ordering of the 245 // origin list is preserved by inserting new wallets at the correct position. 246 // 247 // The original slice is assumed to be already sorted by URL. 248 func merge(slice []Wallet, wallets ...Wallet) []Wallet { 249 for _, wallet := range wallets { 250 n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 }) 251 if n == len(slice) { 252 slice = append(slice, wallet) 253 continue 254 } 255 slice = append(slice[:n], append([]Wallet{wallet}, slice[n:]...)...) 256 } 257 return slice 258 } 259 260 // drop is the couterpart of merge, which looks up wallets from within the sorted 261 // cache and removes the ones specified. 262 func drop(slice []Wallet, wallets ...Wallet) []Wallet { 263 for _, wallet := range wallets { 264 n := sort.Search(len(slice), func(i int) bool { return slice[i].URL().Cmp(wallet.URL()) >= 0 }) 265 if n == len(slice) { 266 // Wallet not found, may happen during startup 267 continue 268 } 269 slice = append(slice[:n], slice[n+1:]...) 270 } 271 return slice 272 }