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