github.com/core-coin/go-core/v2@v2.1.9/accounts/keystore/keystore.go (about) 1 // Copyright 2017 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package keystore implements encrypted storage of ed448 private keys. 18 // 19 // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification. 20 // See https://github.com/core/wiki/wiki/Web3-Secret-Storage-Definition for more information. 21 package keystore 22 23 import ( 24 crand "crypto/rand" 25 "errors" 26 "math/big" 27 "os" 28 "path/filepath" 29 "reflect" 30 "runtime" 31 "sync" 32 "time" 33 34 "github.com/core-coin/go-core/v2/accounts" 35 "github.com/core-coin/go-core/v2/common" 36 "github.com/core-coin/go-core/v2/core/types" 37 "github.com/core-coin/go-core/v2/crypto" 38 "github.com/core-coin/go-core/v2/event" 39 ) 40 41 var ( 42 ErrLocked = accounts.NewAuthNeededError("password or unlock") 43 ErrNoMatch = errors.New("no key for given address or file") 44 ErrDecrypt = errors.New("could not decrypt key with given password") 45 46 // ErrAccountAlreadyExists is returned if an account attempted to import is 47 // already present in the keystore. 48 ErrAccountAlreadyExists = errors.New("account already exists") 49 ) 50 51 // KeyStoreType is the reflect type of a keystore backend. 52 var KeyStoreType = reflect.TypeOf(&KeyStore{}) 53 54 // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs. 55 const KeyStoreScheme = "keystore" 56 57 // Maximum time between wallet refreshes (if filesystem notifications don't work). 58 const walletRefreshCycle = 3 * time.Second 59 60 // KeyStore manages a key storage directory on disk. 61 type KeyStore struct { 62 storage keyStore // Storage backend, might be cleartext or encrypted 63 cache *accountCache // In-memory account cache over the filesystem storage 64 changes chan struct{} // Channel receiving change notifications from the cache 65 unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys) 66 67 wallets []accounts.Wallet // Wallet wrappers around the individual key files 68 updateFeed event.Feed // Event feed to notify wallet additions/removals 69 updateScope event.SubscriptionScope // Subscription scope tracking current live listeners 70 updating bool // Whether the event notification loop is running 71 72 mu sync.RWMutex 73 importMu sync.Mutex // Import Mutex locks the import to prevent two insertions from racing 74 } 75 76 type unlocked struct { 77 *Key 78 abort chan struct{} 79 } 80 81 // NewKeyStore creates a keystore for the given directory. 82 func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore { 83 keydir, _ = filepath.Abs(keydir) 84 ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}} 85 ks.init(keydir) 86 return ks 87 } 88 89 func (ks *KeyStore) init(keydir string) { 90 // Lock the mutex since the account cache might call back with events 91 ks.mu.Lock() 92 defer ks.mu.Unlock() 93 94 // Initialize the set of unlocked keys and the account cache 95 ks.unlocked = make(map[common.Address]*unlocked) 96 ks.cache, ks.changes = newAccountCache(keydir) 97 98 // TODO: In order for this finalizer to work, there must be no references 99 // to ks. addressCache doesn't keep a reference but unlocked keys do, 100 // so the finalizer will not trigger until all timed unlocks have expired. 101 runtime.SetFinalizer(ks, func(m *KeyStore) { 102 m.cache.close() 103 }) 104 // Create the initial list of wallets from the cache 105 accs := ks.cache.accounts() 106 ks.wallets = make([]accounts.Wallet, len(accs)) 107 for i := 0; i < len(accs); i++ { 108 ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks} 109 } 110 } 111 112 // Wallets implements accounts.Backend, returning all single-key wallets from the 113 // keystore directory. 114 func (ks *KeyStore) Wallets() []accounts.Wallet { 115 // Make sure the list of wallets is in sync with the account cache 116 ks.refreshWallets() 117 118 ks.mu.RLock() 119 defer ks.mu.RUnlock() 120 121 cpy := make([]accounts.Wallet, len(ks.wallets)) 122 copy(cpy, ks.wallets) 123 return cpy 124 } 125 126 // refreshWallets retrieves the current account list and based on that does any 127 // necessary wallet refreshes. 128 func (ks *KeyStore) refreshWallets() { 129 // Retrieve the current list of accounts 130 ks.mu.Lock() 131 accs := ks.cache.accounts() 132 133 // Transform the current list of wallets into the new one 134 var ( 135 wallets = make([]accounts.Wallet, 0, len(accs)) 136 events []accounts.WalletEvent 137 ) 138 139 for _, account := range accs { 140 // Drop wallets while they were in front of the next account 141 for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 { 142 events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped}) 143 ks.wallets = ks.wallets[1:] 144 } 145 // If there are no more wallets or the account is before the next, wrap new wallet 146 if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 { 147 wallet := &keystoreWallet{account: account, keystore: ks} 148 149 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived}) 150 wallets = append(wallets, wallet) 151 continue 152 } 153 // If the account is the same as the first wallet, keep it 154 if ks.wallets[0].Accounts()[0] == account { 155 wallets = append(wallets, ks.wallets[0]) 156 ks.wallets = ks.wallets[1:] 157 continue 158 } 159 } 160 // Drop any leftover wallets and set the new batch 161 for _, wallet := range ks.wallets { 162 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped}) 163 } 164 ks.wallets = wallets 165 ks.mu.Unlock() 166 167 // Fire all wallet events and return 168 for _, event := range events { 169 ks.updateFeed.Send(event) 170 } 171 } 172 173 // Subscribe implements accounts.Backend, creating an async subscription to 174 // receive notifications on the addition or removal of keystore wallets. 175 func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription { 176 // We need the mutex to reliably start/stop the update loop 177 ks.mu.Lock() 178 defer ks.mu.Unlock() 179 180 // Subscribe the caller and track the subscriber count 181 sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink)) 182 183 // Subscribers require an active notification loop, start it 184 if !ks.updating { 185 ks.updating = true 186 go ks.updater() 187 } 188 return sub 189 } 190 191 // updater is responsible for maintaining an up-to-date list of wallets stored in 192 // the keystore, and for firing wallet addition/removal events. It listens for 193 // account change events from the underlying account cache, and also periodically 194 // forces a manual refresh (only triggers for systems where the filesystem notifier 195 // is not running). 196 func (ks *KeyStore) updater() { 197 for { 198 // Wait for an account update or a refresh timeout 199 select { 200 case <-ks.changes: 201 case <-time.After(walletRefreshCycle): 202 } 203 // Run the wallet refresher 204 ks.refreshWallets() 205 206 // If all our subscribers left, stop the updater 207 ks.mu.Lock() 208 if ks.updateScope.Count() == 0 { 209 ks.updating = false 210 ks.mu.Unlock() 211 return 212 } 213 ks.mu.Unlock() 214 } 215 } 216 217 // HasAddress reports whether a key with the given address is present. 218 func (ks *KeyStore) HasAddress(addr common.Address) bool { 219 return ks.cache.hasAddress(addr) 220 } 221 222 // Accounts returns all key files present in the directory. 223 func (ks *KeyStore) Accounts() []accounts.Account { 224 return ks.cache.accounts() 225 } 226 227 // Delete deletes the key matched by account if the passphrase is correct. 228 // If the account contains no filename, the address must match a unique key. 229 func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error { 230 // Decrypting the key isn't really necessary, but we do 231 // it anyway to check the password and zero out the key 232 // immediately afterwards. 233 a, key, err := ks.getDecryptedKey(a, passphrase) 234 if key != nil { 235 zeroKey(key.PrivateKey) 236 } 237 if err != nil { 238 return err 239 } 240 // The order is crucial here. The key is dropped from the 241 // cache after the file is gone so that a reload happening in 242 // between won't insert it into the cache again. 243 err = os.Remove(a.URL.Path) 244 if err == nil { 245 ks.cache.delete(a) 246 ks.refreshWallets() 247 } 248 return err 249 } 250 251 // SignHash calculates a EDDSA signature for the given hash. 252 func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) { 253 // Look up the key to sign with and abort if it cannot be found 254 ks.mu.RLock() 255 defer ks.mu.RUnlock() 256 257 unlockedKey, found := ks.unlocked[a.Address] 258 if !found { 259 return nil, ErrLocked 260 } 261 // Sign the hash using plain EDDSA operations 262 return crypto.Sign(hash, unlockedKey.PrivateKey) 263 } 264 265 // SignTx signs the given transaction with the requested account. 266 func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, networkID *big.Int) (*types.Transaction, error) { 267 // Look up the key to sign with and abort if it cannot be found 268 ks.mu.RLock() 269 defer ks.mu.RUnlock() 270 271 unlockedKey, found := ks.unlocked[a.Address] 272 if !found { 273 return nil, ErrLocked 274 } 275 return types.SignTx(tx, types.NewNucleusSigner(networkID), unlockedKey.PrivateKey) 276 } 277 278 // SignHashWithPassphrase signs hash if the private key matching the given address 279 // can be decrypted with the given passphrase. 280 func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) { 281 _, key, err := ks.getDecryptedKey(a, passphrase) 282 if err != nil { 283 return nil, err 284 } 285 defer zeroKey(key.PrivateKey) 286 return crypto.Sign(hash, key.PrivateKey) 287 } 288 289 // SignTxWithPassphrase signs the transaction if the private key matching the 290 // given address can be decrypted with the given passphrase. 291 func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, networkID *big.Int) (*types.Transaction, error) { 292 _, key, err := ks.getDecryptedKey(a, passphrase) 293 if err != nil { 294 return nil, err 295 } 296 defer zeroKey(key.PrivateKey) 297 298 return types.SignTx(tx, types.NewNucleusSigner(networkID), key.PrivateKey) 299 } 300 301 // Unlock unlocks the given account indefinitely. 302 func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error { 303 return ks.TimedUnlock(a, passphrase, 0) 304 } 305 306 // Lock removes the private key with the given address from memory. 307 func (ks *KeyStore) Lock(addr common.Address) error { 308 ks.mu.Lock() 309 if unl, found := ks.unlocked[addr]; found { 310 ks.mu.Unlock() 311 ks.expire(addr, unl, time.Duration(0)*time.Nanosecond) 312 } else { 313 ks.mu.Unlock() 314 } 315 return nil 316 } 317 318 // TimedUnlock unlocks the given account with the passphrase. The account 319 // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account 320 // until the program exits. The account must match a unique key file. 321 // 322 // If the account address is already unlocked for a duration, TimedUnlock extends or 323 // shortens the active unlock timeout. If the address was previously unlocked 324 // indefinitely the timeout is not altered. 325 func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error { 326 a, key, err := ks.getDecryptedKey(a, passphrase) 327 if err != nil { 328 return err 329 } 330 331 ks.mu.Lock() 332 defer ks.mu.Unlock() 333 u, found := ks.unlocked[a.Address] 334 if found { 335 if u.abort == nil { 336 // The address was unlocked indefinitely, so unlocking 337 // it with a timeout would be confusing. 338 zeroKey(key.PrivateKey) 339 return nil 340 } 341 // Terminate the expire goroutine and replace it below. 342 close(u.abort) 343 } 344 if timeout > 0 { 345 u = &unlocked{Key: key, abort: make(chan struct{})} 346 go ks.expire(a.Address, u, timeout) 347 } else { 348 u = &unlocked{Key: key} 349 } 350 ks.unlocked[a.Address] = u 351 return nil 352 } 353 354 // Find resolves the given account into a unique entry in the keystore. 355 func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) { 356 ks.cache.maybeReload() 357 ks.cache.mu.Lock() 358 a, err := ks.cache.find(a) 359 ks.cache.mu.Unlock() 360 return a, err 361 } 362 363 func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) { 364 a, err := ks.Find(a) 365 if err != nil { 366 return a, nil, err 367 } 368 key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth) 369 return a, key, err 370 } 371 372 func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) { 373 t := time.NewTimer(timeout) 374 defer t.Stop() 375 select { 376 case <-u.abort: 377 // just quit 378 case <-t.C: 379 ks.mu.Lock() 380 // only drop if it's still the same key instance that dropLater 381 // was launched with. we can check that using pointer equality 382 // because the map stores a new pointer every time the key is 383 // unlocked. 384 if ks.unlocked[addr] == u { 385 zeroKey(u.PrivateKey) 386 delete(ks.unlocked, addr) 387 } 388 ks.mu.Unlock() 389 } 390 } 391 392 // NewAccount generates a new key and stores it into the key directory, 393 // encrypting it with the passphrase. 394 func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) { 395 _, account, err := storeNewKey(ks.storage, crand.Reader, passphrase) 396 if err != nil { 397 return accounts.Account{}, err 398 } 399 // Add the account to the cache immediately rather 400 // than waiting for file system notifications to pick it up. 401 ks.cache.add(account) 402 ks.refreshWallets() 403 return account, nil 404 } 405 406 // Export exports as a JSON key, encrypted with newPassphrase. 407 func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) { 408 _, key, err := ks.getDecryptedKey(a, passphrase) 409 if err != nil { 410 return nil, err 411 } 412 var N, P int 413 if store, ok := ks.storage.(*keyStorePassphrase); ok { 414 N, P = store.scryptN, store.scryptP 415 } else { 416 N, P = StandardScryptN, StandardScryptP 417 } 418 return EncryptKey(key, newPassphrase, N, P) 419 } 420 421 // Import stores the given encrypted JSON key into the key directory. 422 func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) { 423 key, err := DecryptKey(keyJSON, passphrase) 424 if key != nil && key.PrivateKey != nil { 425 defer zeroKey(key.PrivateKey) 426 } 427 if err != nil { 428 return accounts.Account{}, err 429 } 430 ks.importMu.Lock() 431 defer ks.importMu.Unlock() 432 433 if ks.cache.hasAddress(key.Address) { 434 return accounts.Account{ 435 Address: key.Address, 436 }, ErrAccountAlreadyExists 437 } 438 return ks.importKey(key, newPassphrase) 439 } 440 441 // ImportEDDSA stores the given key into the key directory, encrypting it with the passphrase. 442 func (ks *KeyStore) ImportEDDSA(priv *crypto.PrivateKey, passphrase string) (accounts.Account, error) { 443 ks.importMu.Lock() 444 defer ks.importMu.Unlock() 445 446 key := newKeyFromEDDSA(priv) 447 if ks.cache.hasAddress(key.Address) { 448 return accounts.Account{ 449 Address: key.Address, 450 }, ErrAccountAlreadyExists 451 } 452 return ks.importKey(key, passphrase) 453 } 454 455 func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) { 456 a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}} 457 if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil { 458 return accounts.Account{}, err 459 } 460 ks.cache.add(a) 461 ks.refreshWallets() 462 return a, nil 463 } 464 465 // Update changes the passphrase of an existing account. 466 func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { 467 a, key, err := ks.getDecryptedKey(a, passphrase) 468 if err != nil { 469 return err 470 } 471 return ks.storage.StoreKey(a.URL.Path, key, newPassphrase) 472 } 473 474 // zeroKey zeroes a private key in memory. 475 func zeroKey(k *crypto.PrivateKey) { 476 k = new(crypto.PrivateKey) 477 }