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