Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2016-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test Wallet encryption"""7import time8import subprocess10from test_framework.messages import hash25611from test_framework.test_framework import BitcoinTestFramework12from test_framework.util import (13assert_raises_rpc_error,14assert_equal,15)16from test_framework.wallet_util import WalletUnlock19class WalletEncryptionTest(BitcoinTestFramework):20def set_test_params(self):21self.setup_clean_chain = True22self.num_nodes = 124def skip_test_if_missing_module(self):25self.skip_if_no_wallet()27def run_test(self):28passphrase = "WalletPassphrase"29passphrase2 = "SecondWalletPassphrase"31# Make sure the wallet isn't encrypted first32msg = "test message"33address = self.nodes[0].getnewaddress(address_type='legacy')34sig = self.nodes[0].signmessage(address, msg)35assert self.nodes[0].verifymessage(address, sig, msg)36assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called", self.nodes[0].walletpassphrase, 'ff', 1)37assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.", self.nodes[0].walletpassphrasechange, 'ff', 'ff')39# Encrypt the wallet40assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].encryptwallet, '')41self.nodes[0].encryptwallet(passphrase)43# Test that the wallet is encrypted44assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)45assert_raises_rpc_error(-15, "Error: running with an encrypted wallet, but encryptwallet was called.", self.nodes[0].encryptwallet, 'ff')46assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].walletpassphrase, '', 1)47assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].walletpassphrasechange, '', 'ff')49# Check that walletpassphrase works50self.nodes[0].walletpassphrase(passphrase, 2)51sig = self.nodes[0].signmessage(address, msg)52assert self.nodes[0].verifymessage(address, sig, msg)54# Check that the timeout is right55time.sleep(3)56assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)58# Test wrong passphrase59assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10)61# Test walletlock62with WalletUnlock(self.nodes[0], passphrase):63sig = self.nodes[0].signmessage(address, msg)64assert self.nodes[0].verifymessage(address, sig, msg)65assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)67# Test passphrase changes68self.nodes[0].walletpassphrasechange(passphrase, passphrase2)69assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10)70with WalletUnlock(self.nodes[0], passphrase2):71sig = self.nodes[0].signmessage(address, msg)72assert self.nodes[0].verifymessage(address, sig, msg)74# Test timeout bounds75assert_raises_rpc_error(-8, "Timeout cannot be negative.", self.nodes[0].walletpassphrase, passphrase2, -10)77self.log.info('Check a timeout less than the limit')78MAX_VALUE = 10000000079now = int(time.time())80self.nodes[0].setmocktime(now)81expected_time = now + MAX_VALUE - 60082self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE - 600)83actual_time = self.nodes[0].getwalletinfo()['unlocked_until']84assert_equal(actual_time, expected_time)86self.log.info('Check a timeout greater than the limit')87expected_time = now + MAX_VALUE88self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE + 1000)89actual_time = self.nodes[0].getwalletinfo()['unlocked_until']90assert_equal(actual_time, expected_time)91self.nodes[0].walletlock()93if not self.options.usecli: # can't be done with the test framework for cli since subprocess.Popen doesn't allow null characters94# Test passphrase with null characters95passphrase_with_nulls = "Phrase\0With\0Nulls"96self.nodes[0].walletpassphrasechange(passphrase2, passphrase_with_nulls)97# walletpassphrasechange should not stop at null characters98assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase_with_nulls.partition("\0")[0], 10)99assert_raises_rpc_error(-14, "The wallet passphrase entered was incorrect", self.nodes[0].walletpassphrasechange, passphrase_with_nulls.partition("\0")[0], "abc")100assert_raises_rpc_error(-14, "wallet passphrase entered is incorrect. It contains a null character (ie - a zero byte)", self.nodes[0].walletpassphrase, passphrase_with_nulls + "\0", 10)101assert_raises_rpc_error(-14, "The old wallet passphrase entered is incorrect. It contains a null character (ie - a zero byte)", self.nodes[0].walletpassphrasechange, passphrase_with_nulls + "\0", "abc")102with WalletUnlock(self.nodes[0], passphrase_with_nulls):103sig = self.nodes[0].signmessage(address, msg)104assert self.nodes[0].verifymessage(address, sig, msg)106self.log.info("Test that wallets without private keys cannot be encrypted")107self.nodes[0].createwallet(wallet_name="noprivs", disable_private_keys=True)108noprivs_wallet = self.nodes[0].get_wallet_rpc("noprivs")109assert_raises_rpc_error(-16, "Error: wallet does not contain private keys, nothing to encrypt.", noprivs_wallet.encryptwallet, "pass")111if self.is_wallet_tool_compiled():112self.log.info("Test that encryption keys in wallets without privkeys are removed")114def do_wallet_tool(*args):115proc = subprocess.Popen(116self.get_binaries().wallet_argv() + [f"-datadir={self.nodes[0].datadir_path}", f"-chain={self.chain}"] + list(args),117stdin=subprocess.PIPE,118stdout=subprocess.PIPE,119stderr=subprocess.PIPE,120text=True121)122stdout, stderr = proc.communicate()123assert_equal(proc.poll(), 0)124assert_equal(stderr, "")126# Since it is no longer possible to encrypt a wallet without privkeys, we need to force one into the wallet127# 1. Make a dump of the wallet128# 2. Add mkey record to the dump129# 3. Create a new wallet from the dump131# Make the dump132noprivs_wallet.unloadwallet()133dumpfile_path = self.nodes[0].datadir_path / "noprivs.dump"134do_wallet_tool("-wallet=noprivs", f"-dumpfile={dumpfile_path}", "dump")136# Modify the dump137with open(dumpfile_path, "r") as f:138dump_content = f.readlines()139# Drop the checksum line140dump_content = dump_content[:-1]141# Insert a valid mkey line. This corresponds to a passphrase of "pass".142dump_content.append("046d6b657901000000,300dc926f3b3887aad3d5d5f5a0fc1b1a4a1722f9284bd5c6ff93b64a83902765953939c58fe144013c8b819f42cf698b208e9911e5f0c544fa300000000cc52050000\n")143with open(dumpfile_path, "w") as f:144contents = "".join(dump_content)145f.write(contents)146checksum = hash256(contents.encode())147f.write(f"checksum,{checksum.hex()}\n")149# Load the dump into a new wallet150do_wallet_tool("-wallet=noprivs_enc", f"-dumpfile={dumpfile_path}", "createfromdump")151# Load the wallet and make sure it is no longer encrypted152with self.nodes[0].assert_debug_log(["Detected extraneous encryption keys in this wallet without private keys. Removing extraneous encryption keys."]):153self.nodes[0].loadwallet("noprivs_enc")154noprivs_wallet = self.nodes[0].get_wallet_rpc("noprivs_enc")155assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.", noprivs_wallet.walletpassphrase, "pass", 1)156noprivs_wallet.unloadwallet()158# Make a new dump and check that there are no mkeys159dumpfile_path = self.nodes[0].datadir_path / "noprivs_enc.dump"160do_wallet_tool("-wallet=noprivs_enc", f"-dumpfile={dumpfile_path}", "dump")161with open(dumpfile_path, "r") as f:162# Check there's nothing with an 'mkey' prefix163assert_equal(all([not line.startswith("046d6b6579") for line in f]), True)166if __name__ == '__main__':167WalletEncryptionTest(__file__).main()
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.