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