| 639 | } |
| 640 | |
| 641 | bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) |
| 642 | { |
| 643 | if (IsCrypted()) |
| 644 | return false; |
| 645 | |
| 646 | CKeyingMaterial _vMasterKey; |
| 647 | |
| 648 | _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); |
| 649 | GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); |
| 650 | |
| 651 | CMasterKey kMasterKey; |
| 652 | |
| 653 | kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); |
| 654 | GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); |
| 655 | |
| 656 | CCrypter crypter; |
| 657 | int64_t nStartTime = GetTimeMillis(); |
| 658 | crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); |
| 659 | kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime))); |
| 660 | |
| 661 | nStartTime = GetTimeMillis(); |
| 662 | crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); |
| 663 | kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2; |
| 664 | |
| 665 | if (kMasterKey.nDeriveIterations < 25000) |
| 666 | kMasterKey.nDeriveIterations = 25000; |
| 667 | |
| 668 | WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); |
| 669 | |
| 670 | if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) |
| 671 | return false; |
| 672 | if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey)) |
| 673 | return false; |
| 674 | |
| 675 | { |
| 676 | LOCK(cs_wallet); |
| 677 | mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; |
| 678 | assert(!encrypted_batch); |
| 679 | encrypted_batch = new WalletBatch(*database); |
| 680 | if (!encrypted_batch->TxnBegin()) { |
| 681 | delete encrypted_batch; |
| 682 | encrypted_batch = nullptr; |
| 683 | return false; |
| 684 | } |
| 685 | encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey); |
| 686 | |
| 687 | if (!EncryptKeys(_vMasterKey)) |
| 688 | { |
| 689 | encrypted_batch->TxnAbort(); |
| 690 | delete encrypted_batch; |
| 691 | // We now probably have half of our keys encrypted in memory, and half not... |
| 692 | // die and let the user reload the unencrypted wallet. |
| 693 | assert(false); |
| 694 | } |
| 695 | |
| 696 | // Encryption was introduced in version 0.4.0 |
| 697 | SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true); |
| 698 |
no test coverage detected