github.com/bcskill/bcschain/v3@v3.4.9-beta2/accounts/keystore/account_cache.go (about) 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 17 package keystore 18 19 import ( 20 "bufio" 21 "encoding/json" 22 "fmt" 23 "os" 24 "path/filepath" 25 "sort" 26 "strings" 27 "sync" 28 "time" 29 30 "github.com/bcskill/bcschain/v3/accounts" 31 "github.com/bcskill/bcschain/v3/common" 32 "github.com/bcskill/bcschain/v3/log" 33 ) 34 35 // Minimum amount of time between cache reloads. This limit applies if the platform does 36 // not support change notifications. It also applies if the keystore directory does not 37 // exist yet, the code will attempt to create a watcher at most this often. 38 const minReloadInterval = 2 * time.Second 39 40 type accountsByURL []accounts.Account 41 42 func (s accountsByURL) Len() int { return len(s) } 43 func (s accountsByURL) Less(i, j int) bool { return s[i].URL.Cmp(s[j].URL) < 0 } 44 func (s accountsByURL) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 45 46 // AmbiguousAddrError is returned when attempting to unlock 47 // an address for which more than one file exists. 48 type AmbiguousAddrError struct { 49 Addr common.Address 50 Matches []accounts.Account 51 } 52 53 func (err *AmbiguousAddrError) Error() string { 54 files := "" 55 for i, a := range err.Matches { 56 files += a.URL.Path 57 if i < len(err.Matches)-1 { 58 files += ", " 59 } 60 } 61 return fmt.Sprintf("multiple keys match address (%s)", files) 62 } 63 64 // accountCache is a live index of all accounts in the keystore. 65 type accountCache struct { 66 keydir string 67 watcher *watcher 68 mu sync.Mutex 69 all accountsByURL 70 byAddr map[common.Address][]accounts.Account 71 throttle *time.Timer 72 notify chan struct{} 73 fileC fileCache 74 } 75 76 func newAccountCache(keydir string) (*accountCache, chan struct{}) { 77 ac := &accountCache{ 78 keydir: keydir, 79 byAddr: make(map[common.Address][]accounts.Account), 80 notify: make(chan struct{}, 1), 81 fileC: fileCache{all: make(map[string]struct{})}, 82 } 83 ac.watcher = newWatcher(ac) 84 return ac, ac.notify 85 } 86 87 func (ac *accountCache) accounts() []accounts.Account { 88 ac.maybeReload() 89 ac.mu.Lock() 90 defer ac.mu.Unlock() 91 cpy := make([]accounts.Account, len(ac.all)) 92 copy(cpy, ac.all) 93 return cpy 94 } 95 96 func (ac *accountCache) hasAddress(addr common.Address) bool { 97 ac.maybeReload() 98 ac.mu.Lock() 99 defer ac.mu.Unlock() 100 return len(ac.byAddr[addr]) > 0 101 } 102 103 func (ac *accountCache) add(newAccount accounts.Account) { 104 ac.mu.Lock() 105 defer ac.mu.Unlock() 106 107 i := sort.Search(len(ac.all), func(i int) bool { return ac.all[i].URL.Cmp(newAccount.URL) >= 0 }) 108 if i < len(ac.all) && ac.all[i] == newAccount { 109 return 110 } 111 // newAccount is not in the cache. 112 ac.all = append(ac.all, accounts.Account{}) 113 copy(ac.all[i+1:], ac.all[i:]) 114 ac.all[i] = newAccount 115 ac.byAddr[newAccount.Address] = append(ac.byAddr[newAccount.Address], newAccount) 116 } 117 118 // note: removed needs to be unique here (i.e. both File and Address must be set). 119 func (ac *accountCache) delete(removed accounts.Account) { 120 ac.mu.Lock() 121 defer ac.mu.Unlock() 122 123 ac.all = removeAccount(ac.all, removed) 124 if ba := removeAccount(ac.byAddr[removed.Address], removed); len(ba) == 0 { 125 delete(ac.byAddr, removed.Address) 126 } else { 127 ac.byAddr[removed.Address] = ba 128 } 129 } 130 131 // deleteByFile removes an account referenced by the given path. 132 func (ac *accountCache) deleteByFile(path string) { 133 ac.mu.Lock() 134 defer ac.mu.Unlock() 135 i := sort.Search(len(ac.all), func(i int) bool { return ac.all[i].URL.Path >= path }) 136 137 if i < len(ac.all) && ac.all[i].URL.Path == path { 138 removed := ac.all[i] 139 ac.all = append(ac.all[:i], ac.all[i+1:]...) 140 if ba := removeAccount(ac.byAddr[removed.Address], removed); len(ba) == 0 { 141 delete(ac.byAddr, removed.Address) 142 } else { 143 ac.byAddr[removed.Address] = ba 144 } 145 } 146 } 147 148 func removeAccount(slice []accounts.Account, elem accounts.Account) []accounts.Account { 149 for i := range slice { 150 if slice[i] == elem { 151 return append(slice[:i], slice[i+1:]...) 152 } 153 } 154 return slice 155 } 156 157 // find returns the cached account for address if there is a unique match. 158 // The exact matching rules are explained by the documentation of accounts.Account. 159 // Callers must hold ac.mu. 160 func (ac *accountCache) find(a accounts.Account) (accounts.Account, error) { 161 // Limit search to address candidates if possible. 162 matches := ac.all 163 if (a.Address != common.Address{}) { 164 matches = ac.byAddr[a.Address] 165 } 166 if a.URL.Path != "" { 167 // If only the basename is specified, complete the path. 168 if !strings.ContainsRune(a.URL.Path, filepath.Separator) { 169 a.URL.Path = filepath.Join(ac.keydir, a.URL.Path) 170 } 171 for i := range matches { 172 if matches[i].URL == a.URL { 173 return matches[i], nil 174 } 175 } 176 if (a.Address == common.Address{}) { 177 return accounts.Account{}, ErrNoMatch 178 } 179 } 180 switch len(matches) { 181 case 1: 182 return matches[0], nil 183 case 0: 184 return accounts.Account{}, ErrNoMatch 185 default: 186 err := &AmbiguousAddrError{Addr: a.Address, Matches: make([]accounts.Account, len(matches))} 187 copy(err.Matches, matches) 188 sort.Sort(accountsByURL(err.Matches)) 189 return accounts.Account{}, err 190 } 191 } 192 193 func (ac *accountCache) maybeReload() { 194 ac.mu.Lock() 195 196 if ac.watcher.running { 197 ac.mu.Unlock() 198 return // A watcher is running and will keep the cache up-to-date. 199 } 200 if ac.throttle == nil { 201 ac.throttle = time.NewTimer(0) 202 } else { 203 select { 204 case <-ac.throttle.C: 205 default: 206 ac.mu.Unlock() 207 return // The cache was reloaded recently. 208 } 209 } 210 // No watcher running, start it. 211 ac.watcher.start() 212 ac.throttle.Reset(minReloadInterval) 213 ac.mu.Unlock() 214 ac.scanAccounts() 215 } 216 217 func (ac *accountCache) close() { 218 ac.mu.Lock() 219 ac.watcher.close() 220 if ac.throttle != nil { 221 ac.throttle.Stop() 222 } 223 if ac.notify != nil { 224 close(ac.notify) 225 ac.notify = nil 226 } 227 ac.mu.Unlock() 228 } 229 230 // scanAccounts checks if any changes have occurred on the filesystem, and 231 // updates the account cache accordingly 232 func (ac *accountCache) scanAccounts() error { 233 // Scan the entire folder metadata for file changes 234 creates, deletes, updates, err := ac.fileC.scan(ac.keydir) 235 if err != nil { 236 log.Debug("Failed to reload keystore contents", "err", err) 237 return err 238 } 239 if len(creates) == 0 && len(deletes) == 0 && len(updates) == 0 { 240 return nil 241 } 242 // Create a helper method to scan the contents of the key files 243 var ( 244 buf = new(bufio.Reader) 245 key struct { 246 Address string `json:"address"` 247 } 248 ) 249 readAccount := func(path string) *accounts.Account { 250 fd, err := os.Open(path) 251 if err != nil { 252 log.Trace("Failed to open keystore file", "path", path, "err", err) 253 return nil 254 } 255 defer fd.Close() 256 buf.Reset(fd) 257 // Parse the address. 258 key.Address = "" 259 err = json.NewDecoder(buf).Decode(&key) 260 addr := common.HexToAddress(key.Address) 261 switch { 262 case err != nil: 263 log.Debug("Failed to decode keystore key", "path", path, "err", err) 264 case (addr == common.Address{}): 265 log.Debug("Failed to decode keystore key", "path", path, "err", "missing or zero address") 266 default: 267 return &accounts.Account{Address: addr, URL: accounts.URL{Scheme: KeyStoreScheme, Path: path}} 268 } 269 return nil 270 } 271 // Process all the file diffs 272 start := time.Now() 273 274 for p := range creates { 275 if a := readAccount(p); a != nil { 276 ac.add(*a) 277 } 278 } 279 for p := range deletes { 280 ac.deleteByFile(p) 281 } 282 for p := range updates { 283 ac.deleteByFile(p) 284 if a := readAccount(p); a != nil { 285 ac.add(*a) 286 } 287 } 288 end := time.Now() 289 290 select { 291 case ac.notify <- struct{}{}: 292 default: 293 } 294 log.Trace("Handled keystore changes", "time", end.Sub(start)) 295 return nil 296 }