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