Summary
if (!Unlock(strWalletPassphrase)) {
return false;
}
The above code src/wallet/wallet.cpp:890: runs after the wallet encryption process is already complete. Making the failed unlock operation to return false leads to a misleading RPC error message, just in case the encryption happens but the unlock operation fails. Probably it was added there because the function should always return a boolean.
Before change
This is the result of a failed unlock, i.e making the function to always return false to mimic the unlock failure
Mutated function
if (Unlock(plain_master_key)) {
// Now that we've unlocked, upgrade the descriptor cache
// UpgradeDescriptorCache();
return false;
}
Output
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$ ./bitcoin-cli createwallet testwallet
{
"name": "testwallet"
}
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$ ./bitcoin-cli encryptwallet "testpass"
error code: -16
error message:
Error: Failed to encrypt the wallet.
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$ ./bitcoin-cli encryptwallet "testpass"
error code: -15
error message:
Error: running with an encrypted wallet, but encryptwallet was called.
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$
Solution
The failed unlock is inconsequential to the encryption process. It can even just be written as
Lock();
Unlock(strWalletPassphrase)
SetupWalletGeneration();
Lock();
Instead of returning false, which leads to a misleading error message to the user, probably just logging a message might be necessary
if (!Unlock(strWalletPassphrase)) {
WalletLogPrintf("Unlocking the encrypted wallet failed\n");
}
After the change
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$ ./bitcoin-cli createwallet testwallet
{
"name": "testwallet"
}
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$ ./bitcoin-cli encryptwallet "testpass"
wallet encrypted; The keypool has been flushed and a new HD seed was generated. You need to make a new backup with the backupwallet RPC.
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$ ./bitcoin-cli encryptwallet "testpass"
error code: -15
error message:
Error: running with an encrypted wallet, but encryptwallet was called.
ratedg@0xratedg:~/Desktop/bitcoin/build/bin$
The nature of the log is the one to be probably determined or the essence of the conditional statement