Skip to content

wallet: Remove mapMasterKeys and enforce that only one encryption key can exist - #36031

Open
achow101 wants to merge 3 commits into
bitcoin:masterfrom
achow101:single-encryption-key
Open

achow101 wants to merge 3 commits into
bitcoin:masterfrom
achow101:single-encryption-key

Conversation

@achow101

Copy link
Copy Markdown
Member

mapMasterKeys was 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 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 encryption key, and the ID of that key should be 1.

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 the id is stored. Otherwise, new encryption keys always have an ID of 1.

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 mapMasterKeys and his response was

I have no idea I barely knew how to code when I wrote that shit.

@DrahtBot

DrahtBot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/36031.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK jeanpablojp, theStack, rkrux, w0xlt, polespinasa
Approach ACK vicjuma
Stale ACK davidgumberg

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #35998 (wallet: Handle or explicitly ignore WalletBatch write failures by achow101)

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. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • WriteIC(std::make_pair(DBKeys::MASTER_KEY, kMasterKey.m_id), kMasterKey, true) in src/wallet/walletdb.cpp

2026-09-22 20:23:21

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/32314344744/job/96263457089
LLM reason (✨ experimental): CI failed because IWYU reported an include-fixing issue (“Failure generated from IWYU”) in src/bench/wallet_encrypt.cpp, causing the CI test script to exit with code 1.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@jeanpablojp jeanpablojp left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK, keeping a single key makes sense. One thing inline.

Comment thread src/wallet/walletdb.cpp
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
kMasterKey.m_id = nID;

if (pwallet->m_encryption_key.has_value()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@theStack

Copy link
Copy Markdown
Contributor

Concept ACK

@vicjuma vicjuma left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach ACK

Comment thread src/wallet/crypter.h
//! 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};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clearly backward compatible as its value is independent of the encryption operations

Tweak

src/wallet/crypter.h:45  uint32_t m_id{10000};

Results

Image

Comment thread src/wallet/wallet.cpp Outdated
{
LOCK2(m_relock_mutex, cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = master_key;
m_encryption_key = master_key;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Image

@achow101
achow101 force-pushed the single-encryption-key branch from dc1d640 to 94af5c9 Compare August 24, 2026 22:56
@rkrux

rkrux commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Strong Concept ACK 94af5c9

I don't see a good reason to have multiple keys or passphrases to encrypt the wallet going forward.
And the corresponding code cleanup is necessary for long term wallet maintainability and usability.

@w0xlt

w0xlt commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

Comment thread src/wallet/walletdb.cpp
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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High-level out-of-scope remark:

It would be wise to just rename these records instead of deleting them.

@davidgumberg

davidgumberg commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

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.

@polespinasa polespinasa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/wallet/walletdb.h
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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in d60681a walletdb: Make WriteMasterKey take only a CMasterKey

Can't this function also take the kMasterKey so it is consistent with WriteMasterKey??

Comment thread src/wallet/wallet.cpp
if (!DecryptMasterKey(strWalletPassphrase, master_key, plain_master_key)) {
continue; // try another master key
}
if (DecryptMasterKey(strWalletPassphrase, *m_encryption_key, plain_master_key)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants