Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. Code Coverage & BenchmarksFor details see: https://corecheck.dev/bitcoin/bitcoin/pulls/36031. ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. LLM Linter (✨ experimental)Possible places where named args for integral literals may be used (e.g.
2026-09-22 20:23:21 |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
jeanpablojp
left a comment
There was a problem hiding this comment.
Concept ACK, keeping a single key makes sense. One thing inline.
| strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); | ||
| kMasterKey.m_id = nID; | ||
|
|
||
| if (pwallet->m_encryption_key.has_value()) { |
There was a problem hiding this comment.
Tried this out. With v0.19.1, I created a wallet with blank=true and ran encryptwallet, unloadwallet, loadwallet, and encryptwallet again, ending up with two mkey records. The second encryptwallet succeeded because IsCrypted() back then read an in-memory flag that loading an mkey never set. v28.2 opens that wallet and leaves both mkey records in place. On master, migratewallet converts it to a descriptor wallet but carries both records over. On this branch, migratewallet rejects the legacy wallet and loadwallet rejects the already migrated descriptor wallet with Wallet corrupted. Neither failure writes to the file. I don't know how common these wallets are.
There was a problem hiding this comment.
That's interesting.
I think this scenario is pretty unlikely. It requires you to create a blank wallet, encrypt it, and then unload it, then reload, then encrypt again. The expected usage of blank wallets was that you would immediately put stuff into that wallet and it would no longer become blank. There's really no reason to have a blank wallet that you would reload. This was a also a fairly niche feature when introduced (and kinda still is) and it looks like this behavior was present for 0.18 and 0.19, so I expect that the number of affected users is approximately 0.
I should also note that once the wallet becomes not blank, even with the multiple encryption keys, only one of those keys would actually be used and be the correct one for that wallet. If we had some way to figure out which key that was, this change would still mostly hold.
But I don't think that this is worth addressing as I expect no one to actually be affected by it. If it is problem, I have a half-baked solution that should work, but I feel like it's a bit complicated and premature to be adding that in when we don't know if anyone is affected by this.
|
Concept ACK |
| //! Use this for more parameters to key derivation (currently unused) | ||
| std::vector<unsigned char> vchOtherDerivationParameters; | ||
| //! Id of this CMasterKey. Only used for writing the key of the database record. Retained for backwards compatibility, otherwise unused. | ||
| uint32_t m_id{1}; |
| { | ||
| LOCK2(m_relock_mutex, cs_wallet); | ||
| mapMasterKeys[++nMasterKeyMaxID] = master_key; | ||
| m_encryption_key = master_key; |
There was a problem hiding this comment.
Confirmed the assertion via a functional test
def test_nonstandard_master_key_id(self, passphrase, do_wallet_tool):
self.log.info("Test that a master key with a non-standard ID remains unchanged")
current_node = self.nodes[0]
wallet_name = "pr36031_non_standard_id"
current_node.createwallet(wallet_name=wallet_name)
pr36031_non_standard_id = current_node.get_wallet_rpc(wallet_name)
pr36031_non_standard_id.encryptwallet(passphrase)
pr36031_non_standard_id.unloadwallet()
dumpfile_path = current_node.datadir_path / f"{pr36031_non_standard_id}.dump"
do_wallet_tool(f"-wallet={wallet_name}", f"-dumpfile={dumpfile_path}", "dump")
mkey_prefix = "046d6b6579"
''' Patch the mkey record's ID from 1 (01000000, 4-byte LE) to 42 (2a000000)'''
with open(dumpfile_path, "r") as f:
dump_content = f.readlines()
dump_content = dump_content[:-1]
mkey_idx = next(i for i, l in enumerate(dump_content) if l.startswith(F"{mkey_prefix}"))
key_hex, value_hex = dump_content[mkey_idx].strip().split(",")
''''asserts that the value is not 1 as changed in `src/wallet/crypter.h:45 uint32_t m_id{10000};` '''
assert_not_equal(key_hex[-8:], "01000000")
dump_content[mkey_idx] = f"{key_hex[:-8]}2a000000,{value_hex}\n"
with open(dumpfile_path, "w") as f:
contents = "".join(dump_content)
f.write(contents)
checksum = hash256(contents.encode())
f.write(f"checksum,{checksum.hex()}\n")
wallet_name_new = "pr36031_non_standard_id_new"
do_wallet_tool(f"-wallet={wallet_name_new}", f"-dumpfile={dumpfile_path}", "createfromdump")
current_node.loadwallet(wallet_name_new)
pr36031_non_standard_id_new = current_node.get_wallet_rpc(wallet_name_new)
receive = pr36031_non_standard_id_new.getnewaddress()
current_node.generatetoaddress(101, receive, called_by_framework=True)
with WalletUnlock(pr36031_non_standard_id_new, passphrase):
destination = pr36031_non_standard_id_new.getnewaddress()
utxo = pr36031_non_standard_id_new.listunspent()[0]
raw = pr36031_non_standard_id_new.createrawtransaction(
[{"txid": utxo["txid"], "vout": utxo["vout"]}],
{destination: 1.0},
)
signed = pr36031_non_standard_id_new.signrawtransactionwithwallet(raw)
assert_equal(signed["complete"], True)
pr36031_non_standard_id_new.unloadwallet()
redump_path = current_node.datadir_path / "pr36031_non_standard_id_new.dump"
do_wallet_tool(f"-wallet={wallet_name_new}", f"-dumpfile={redump_path}", "dump")
with open(redump_path, "r") as f:
mkey_line = next(l for l in f if l.startswith(f"{mkey_prefix}"))
''''asserts that the above operations were actually done using the tweaked mkey '''
assert mkey_line.split(",")[0].endswith("2a000000")The test passes with the above change
output
dc1d640 to
94af5c9
Compare
|
Strong Concept ACK 94af5c9 I don't see a good reason to have multiple keys or passphrases to encrypt the wallet going forward. |
|
Concept ACK |
| pwallet->WalletLogPrintf("Error: Unable to remove extraneous encryption key '%u'. Wallet corrupt.\n", id); | ||
| return DBErrors::CORRUPT; | ||
| } | ||
| if (!EraseMasterKey(pwallet->m_encryption_key->m_id)) { |
There was a problem hiding this comment.
High-level out-of-scope remark:
It would be wise to just rename these records instead of deleting them.
|
crACK 94af5c9 From a high-level this change is safe: the first two commits are basically ~refactors, but there is a slight behavior change in eea1022 which is that multiple encryption keys in a wallet file will result in failing to load after only this commit. In the main commit (94af5c9) it seems to me that the worst that can happen is that some wallet edge case has not been taken into account and will fail to load on startup, which is fine. |
94af5c9 to
8e3e423
Compare
polespinasa
left a comment
There was a problem hiding this comment.
concept ACK
from 8e3e423 wallet: Hold only one encryption key in memory:
No one should have a wallet that has more than one
encrypion key.
What if someone does? IIUC think this PR makes the wallet unloadable.
| bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta); | ||
| bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey); | ||
| bool WriteMasterKey(const CMasterKey& kMasterKey); | ||
| bool EraseMasterKey(unsigned int id); |
There was a problem hiding this comment.
in d60681a walletdb: Make WriteMasterKey take only a CMasterKey
Can't this function also take the kMasterKey so it is consistent with WriteMasterKey??
| if (!DecryptMasterKey(strWalletPassphrase, master_key, plain_master_key)) { | ||
| continue; // try another master key | ||
| } | ||
| if (DecryptMasterKey(strWalletPassphrase, *m_encryption_key, plain_master_key)) { |
There was a problem hiding this comment.
in 8e3e423 wallet: Hold only one encryption key in memory
Isn't this undefined behavior if m_encryption_key is empty? I've checked and I think all callers have some kind of guard. I think an assert(m_encryption_key.hasvalue()) would make the function safer. Or as the function is Expected maybe return an error if it does not have value.
| @@ -78,9 +79,7 @@ static void WalletEncrypt(benchmark::Bench& bench, unsigned int key_count) | |||
| .run([&] { | |||
| wallet->EncryptWallet(secure_pass); | |||
There was a problem hiding this comment.
8e3e423 wallet: Hold only one encryption key in memory
Not introduced by this PR but, this return is silently ignored. Maybe worth ensure it returns true?
mapMasterKeys was introduced in bitcoin#352 without a clear rationale. Likely it was to allow the user to have multiple passphrases by encrypting the wallet's encryption key with different passphrases. However, this functionality was never implemented, and current code enforces in a few places that there is only one encryption key. By removing mapMasterKeys and replacing it with a single m_encryption_key, we can remove this confusion and simplify encryption key handling. No one should have a wallet that has more than one encrypion key.
8e3e423 to
0ca8bea
Compare

mapMasterKeyswas introduced in #352 without a clear rationale. Likely it was to allow the user to have multiple passphrases by encrypting the wallet's encryption key with different passphrases. However, this functionality was never implemented, and current code enforces in a few places (inconsistently) that there is only one encryption key.By removing
mapMasterKeysand replacing it with a singlem_encryption_key, we can remove this confusion and simplify encryption key handling. No one should have a wallet that has more than one encryption key, and the ID of that key should be1.The format of the database record remains unchanged. If a wallet somehow has an encryption key with an ID other than
1, the record will stay the same and theidis stored. Otherwise, new encryption keys always have an ID of1.If a wallet has more than one encryption key, this becomes a corruption error because it should never happen outside of someone doing something weird with their wallet.
I asked Matt for his rationale for adding
mapMasterKeysand his response was