github.com/FusionFoundation/efsn/v4@v4.2.0/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/FusionFoundation/efsn/v4/accounts" 37 "github.com/FusionFoundation/efsn/v4/common" 38 "github.com/FusionFoundation/efsn/v4/core/types" 39 "github.com/FusionFoundation/efsn/v4/crypto" 40 "github.com/FusionFoundation/efsn/v4/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 ) 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 wallets := make([]accounts.Wallet, 0, len(accs)) 141 events := []accounts.WalletEvent{} 142 143 for _, account := range accs { 144 // Drop wallets while they were in front of the next account 145 for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 { 146 events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped}) 147 ks.wallets = ks.wallets[1:] 148 } 149 // If there are no more wallets or the account is before the next, wrap new wallet 150 if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 { 151 wallet := &keystoreWallet{account: account, keystore: ks} 152 153 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived}) 154 wallets = append(wallets, wallet) 155 continue 156 } 157 // If the account is the same as the first wallet, keep it 158 if ks.wallets[0].Accounts()[0] == account { 159 wallets = append(wallets, ks.wallets[0]) 160 ks.wallets = ks.wallets[1:] 161 continue 162 } 163 } 164 // Drop any leftover wallets and set the new batch 165 for _, wallet := range ks.wallets { 166 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped}) 167 } 168 ks.wallets = wallets 169 ks.mu.Unlock() 170 171 // Fire all wallet events and return 172 for _, event := range events { 173 ks.updateFeed.Send(event) 174 } 175 } 176 177 // Subscribe implements accounts.Backend, creating an async subscription to 178 // receive notifications on the addition or removal of keystore wallets. 179 func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription { 180 // We need the mutex to reliably start/stop the update loop 181 ks.mu.Lock() 182 defer ks.mu.Unlock() 183 184 // Subscribe the caller and track the subscriber count 185 sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink)) 186 187 // Subscribers require an active notification loop, start it 188 if !ks.updating { 189 ks.updating = true 190 go ks.updater() 191 } 192 return sub 193 } 194 195 // updater is responsible for maintaining an up-to-date list of wallets stored in 196 // the keystore, and for firing wallet addition/removal events. It listens for 197 // account change events from the underlying account cache, and also periodically 198 // forces a manual refresh (only triggers for systems where the filesystem notifier 199 // is not running). 200 func (ks *KeyStore) updater() { 201 for { 202 // Wait for an account update or a refresh timeout 203 select { 204 case <-ks.changes: 205 case <-time.After(walletRefreshCycle): 206 } 207 // Run the wallet refresher 208 ks.refreshWallets() 209 210 // If all our subscribers left, stop the updater 211 ks.mu.Lock() 212 if ks.updateScope.Count() == 0 { 213 ks.updating = false 214 ks.mu.Unlock() 215 return 216 } 217 ks.mu.Unlock() 218 } 219 } 220 221 // HasAddress reports whether a key with the given address is present. 222 func (ks *KeyStore) HasAddress(addr common.Address) bool { 223 return ks.cache.hasAddress(addr) 224 } 225 226 // Accounts returns all key files present in the directory. 227 func (ks *KeyStore) Accounts() []accounts.Account { 228 return ks.cache.accounts() 229 } 230 231 // Delete deletes the key matched by account if the passphrase is correct. 232 // If the account contains no filename, the address must match a unique key. 233 func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error { 234 // Decrypting the key isn't really necessary, but we do 235 // it anyway to check the password and zero out the key 236 // immediately afterwards. 237 a, key, err := ks.getDecryptedKey(a, passphrase) 238 if key != nil { 239 zeroKey(key.PrivateKey) 240 } 241 if err != nil { 242 return err 243 } 244 // The order is crucial here. The key is dropped from the 245 // cache after the file is gone so that a reload happening in 246 // between won't insert it into the cache again. 247 err = os.Remove(a.URL.Path) 248 if err == nil { 249 ks.cache.delete(a) 250 ks.refreshWallets() 251 } 252 return err 253 } 254 255 // SignHash calculates a ECDSA signature for the given hash. The produced 256 // signature is in the [R || S || V] format where V is 0 or 1. 257 func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) { 258 // Look up the key to sign with and abort if it cannot be found 259 ks.mu.RLock() 260 defer ks.mu.RUnlock() 261 262 unlockedKey, found := ks.unlocked[a.Address] 263 if !found { 264 return nil, ErrLocked 265 } 266 // Sign the hash using plain ECDSA operations 267 return crypto.Sign(hash, unlockedKey.PrivateKey) 268 } 269 270 // SignTx signs the given transaction with the requested account. 271 func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 272 // Look up the key to sign with and abort if it cannot be found 273 ks.mu.RLock() 274 defer ks.mu.RUnlock() 275 276 unlockedKey, found := ks.unlocked[a.Address] 277 if !found { 278 return nil, ErrLocked 279 } 280 // Depending on the presence of the chain ID, sign with 2718 or homestead 281 signer := types.LatestSignerForChainID(chainID) 282 return types.SignTx(tx, signer, unlockedKey.PrivateKey) 283 } 284 285 // SignHashWithPassphrase signs hash if the private key matching the given address 286 // can be decrypted with the given passphrase. The produced signature is in the 287 // [R || S || V] format where V is 0 or 1. 288 func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) { 289 _, key, err := ks.getDecryptedKey(a, passphrase) 290 if err != nil { 291 return nil, err 292 } 293 defer zeroKey(key.PrivateKey) 294 return crypto.Sign(hash, key.PrivateKey) 295 } 296 297 // SignTxWithPassphrase signs the transaction if the private key matching the 298 // given address can be decrypted with the given passphrase. 299 func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 300 _, key, err := ks.getDecryptedKey(a, passphrase) 301 if err != nil { 302 return nil, err 303 } 304 defer zeroKey(key.PrivateKey) 305 // Depending on the presence of the chain ID, sign with or without replay protection. 306 signer := types.LatestSignerForChainID(chainID) 307 return types.SignTx(tx, signer, key.PrivateKey) 308 } 309 310 // Unlock unlocks the given account indefinitely. 311 func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error { 312 return ks.TimedUnlock(a, passphrase, 0) 313 } 314 315 // Lock removes the private key with the given address from memory. 316 func (ks *KeyStore) Lock(addr common.Address) error { 317 ks.mu.Lock() 318 if unl, found := ks.unlocked[addr]; found { 319 ks.mu.Unlock() 320 ks.expire(addr, unl, time.Duration(0)*time.Nanosecond) 321 } else { 322 ks.mu.Unlock() 323 } 324 return nil 325 } 326 327 // TimedUnlock unlocks the given account with the passphrase. The account 328 // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account 329 // until the program exits. The account must match a unique key file. 330 // 331 // If the account address is already unlocked for a duration, TimedUnlock extends or 332 // shortens the active unlock timeout. If the address was previously unlocked 333 // indefinitely the timeout is not altered. 334 func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error { 335 a, key, err := ks.getDecryptedKey(a, passphrase) 336 if err != nil { 337 return err 338 } 339 340 ks.mu.Lock() 341 defer ks.mu.Unlock() 342 u, found := ks.unlocked[a.Address] 343 if found { 344 if u.abort == nil { 345 // The address was unlocked indefinitely, so unlocking 346 // it with a timeout would be confusing. 347 zeroKey(key.PrivateKey) 348 return nil 349 } 350 // Terminate the expire goroutine and replace it below. 351 close(u.abort) 352 } 353 if timeout > 0 { 354 u = &unlocked{Key: key, abort: make(chan struct{})} 355 go ks.expire(a.Address, u, timeout) 356 } else { 357 u = &unlocked{Key: key} 358 } 359 ks.unlocked[a.Address] = u 360 return nil 361 } 362 363 // Find resolves the given account into a unique entry in the keystore. 364 func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) { 365 ks.cache.maybeReload() 366 ks.cache.mu.Lock() 367 a, err := ks.cache.find(a) 368 ks.cache.mu.Unlock() 369 return a, err 370 } 371 372 func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) { 373 a, err := ks.Find(a) 374 if err != nil { 375 return a, nil, err 376 } 377 key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth) 378 return a, key, err 379 } 380 381 func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) { 382 t := time.NewTimer(timeout) 383 defer t.Stop() 384 select { 385 case <-u.abort: 386 // just quit 387 case <-t.C: 388 ks.mu.Lock() 389 // only drop if it's still the same key instance that dropLater 390 // was launched with. we can check that using pointer equality 391 // because the map stores a new pointer every time the key is 392 // unlocked. 393 if ks.unlocked[addr] == u { 394 zeroKey(u.PrivateKey) 395 delete(ks.unlocked, addr) 396 } 397 ks.mu.Unlock() 398 } 399 } 400 401 // NewAccount generates a new key and stores it into the key directory, 402 // encrypting it with the passphrase. 403 func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) { 404 _, account, err := storeNewKey(ks.storage, crand.Reader, passphrase) 405 if err != nil { 406 return accounts.Account{}, err 407 } 408 // Add the account to the cache immediately rather 409 // than waiting for file system notifications to pick it up. 410 ks.cache.add(account) 411 ks.refreshWallets() 412 return account, nil 413 } 414 415 // Export exports as a JSON key, encrypted with newPassphrase. 416 func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) { 417 _, key, err := ks.getDecryptedKey(a, passphrase) 418 if err != nil { 419 return nil, err 420 } 421 var N, P int 422 if store, ok := ks.storage.(*keyStorePassphrase); ok { 423 N, P = store.scryptN, store.scryptP 424 } else { 425 N, P = StandardScryptN, StandardScryptP 426 } 427 return EncryptKey(key, newPassphrase, N, P) 428 } 429 430 // Import stores the given encrypted JSON key into the key directory. 431 func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) { 432 key, err := DecryptKey(keyJSON, passphrase) 433 if key != nil && key.PrivateKey != nil { 434 defer zeroKey(key.PrivateKey) 435 } 436 if err != nil { 437 return accounts.Account{}, err 438 } 439 return ks.importKey(key, newPassphrase) 440 } 441 442 // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase. 443 func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) { 444 key := newKeyFromECDSA(priv) 445 if ks.cache.hasAddress(key.Address) { 446 return accounts.Account{}, fmt.Errorf("account already exists") 447 } 448 return ks.importKey(key, passphrase) 449 } 450 451 func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) { 452 a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}} 453 if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil { 454 return accounts.Account{}, err 455 } 456 ks.cache.add(a) 457 ks.refreshWallets() 458 return a, nil 459 } 460 461 // Update changes the passphrase of an existing account. 462 func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { 463 a, key, err := ks.getDecryptedKey(a, passphrase) 464 if err != nil { 465 return err 466 } 467 return ks.storage.StoreKey(a.URL.Path, key, newPassphrase) 468 } 469 470 // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores 471 // a key file in the key directory. The key file is encrypted with the same passphrase. 472 func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) { 473 a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase) 474 if err != nil { 475 return a, err 476 } 477 ks.cache.add(a) 478 ks.refreshWallets() 479 return a, nil 480 } 481 482 // zeroKey zeroes a private key in memory. 483 func zeroKey(k *ecdsa.PrivateKey) { 484 b := k.D.Bits() 485 for i := range b { 486 b[i] = 0 487 } 488 }