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