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) 2017-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 multiwallet.7Verify that a bitcoind node can load multiple wallet files8"""9from threading import Thread10import os11import platform12import shutil13import stat15from test_framework.blocktools import COINBASE_MATURITY16from test_framework.test_framework import BitcoinTestFramework17from test_framework.test_node import ErrorMatch18from test_framework.util import (19assert_equal,20assert_raises_rpc_error,21ensure_for,22JSONRPCException,23)25got_loading_error = False28def test_load_unload(node, name):29global got_loading_error30while True:31if got_loading_error:32return33try:34node.loadwallet(name)35node.unloadwallet(name)36except JSONRPCException as e:37if e.error['code'] == -4 and 'Wallet already loading' in e.error['message']:38got_loading_error = True39return41def data_dir(node, *p):42return os.path.join(node.chain_path, *p)44def wallet_dir(node, *p):45return data_dir(node, 'wallets', *p)47def get_wallet(node, name):48return node.get_wallet_rpc(name)51class MultiWalletTest(BitcoinTestFramework):52def set_test_params(self):53self.setup_clean_chain = True54self.num_nodes = 255self.rpc_timeout = 12056self.extra_args = [["-nowallet"], []]58def skip_test_if_missing_module(self):59self.skip_if_no_wallet()61def wallet_file(self, node, name):62if name == self.default_wallet_name:63return wallet_dir(node, self.default_wallet_name, self.wallet_data_filename)64if os.path.isdir(wallet_dir(node, name)):65return wallet_dir(node, name, "wallet.dat")66return wallet_dir(node, name)68def run_test(self):69self.check_chmod = True70self.check_symlinks = True71if platform.system() == 'Windows':72# Additional context:73# - chmod: Posix has one user per file while Windows has an ACL approach74# - symlinks: GCC 13 has FIXME notes for symlinks under Windows:75# https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/src/filesystem/ops-common.h;h=ba377905a2e90f7baf30c900b090f1f732397e08;hb=refs/heads/releases/gcc-13#l12476self.log.warning('Skipping chmod+symlink checks on Windows: '77'chmod works differently due to how access rights work and '78'symlink behavior with regard to the standard library is non-standard on cross-built binaries.')79self.check_chmod = False80self.check_symlinks = False81elif os.geteuid() == 0:82self.log.warning('Skipping checks involving chmod as they require non-root permissions.')83self.check_chmod = False85node = self.nodes[0]87assert_equal(node.listwalletdir(), {'wallets': [{'name': self.default_wallet_name, "warnings": []}]})89self.test_invalid_wallet_names()91# check wallet.dat is created92self.stop_nodes()93assert_equal(os.path.isfile(wallet_dir(node, self.default_wallet_name, self.wallet_data_filename)), True)95self.test_scanning_main_dir_access(node)96empty_wallet, empty_created_wallet, wallet_names, in_wallet_dir = self.test_mixed_wallets(node)97self.test_scanning_sub_dir(node, in_wallet_dir)98self.test_scanning_symlink_levels(node, in_wallet_dir)99self.test_init(node, wallet_names)100self.test_balances_and_fees(node, wallet_names, in_wallet_dir)101w1, w2 = self.test_loading(node, wallet_names)102self.test_creation(node, in_wallet_dir)103self.test_unloading(node, in_wallet_dir, w1, w2)104self.test_backup_and_restore(node, wallet_names, empty_wallet, empty_created_wallet)105self.test_lock_file_closed(node)107def test_scanning_main_dir_access(self, node):108if not self.check_chmod:109return111self.log.info("Verify warning is emitted when failing to scan the wallets directory")112self.start_node(0)113with node.assert_debug_log(unexpected_msgs=['Error scanning directory entries under'], expected_msgs=[]):114result = node.listwalletdir()115assert_equal(result, {'wallets': [{'name': 'default_wallet', 'warnings': []}]})116os.chmod(data_dir(node, 'wallets'), 0)117with node.assert_debug_log(expected_msgs=['Error scanning directory entries under']):118result = node.listwalletdir()119assert_equal(result, {'wallets': []})120self.stop_node(0)121# Restore permissions122os.chmod(data_dir(node, 'wallets'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)124def test_mixed_wallets(self, node):125self.log.info("Test mixed wallets")126# create symlink to verify wallet directory path can be referenced127# through symlink128os.mkdir(wallet_dir(node, 'w7'))129os.symlink('w7', wallet_dir(node, 'w7_symlink'))131if self.check_symlinks:132os.symlink('..', wallet_dir(node, 'recursive_dir_symlink'))134# rename wallet.dat to make sure plain wallet file paths (as opposed to135# directory paths) can be loaded136# create another dummy wallet for use in testing backups later137self.start_node(0)138node.createwallet("empty")139node.createwallet("plain")140node.createwallet("created")141self.stop_nodes()142empty_wallet = os.path.join(self.options.tmpdir, 'empty.dat')143os.rename(self.wallet_file(node, "empty"), empty_wallet)144os.rmdir(wallet_dir(node, "empty"))145empty_created_wallet = os.path.join(self.options.tmpdir, 'empty.created.dat')146os.rename(wallet_dir(node, "created", self.wallet_data_filename), empty_created_wallet)147os.rmdir(wallet_dir(node, "created"))148os.rename(self.wallet_file(node, "plain"), wallet_dir(node, "w8"))149os.rmdir(wallet_dir(node, "plain"))151# restart node with a mix of wallet names:152# w1, w2, w3 - to verify new wallets created when non-existing paths specified153# w - to verify wallet name matching works when one wallet path is prefix of another154# sub/w5 - to verify relative wallet path is created correctly155# extern/w6 - to verify absolute wallet path is created correctly156# w7_symlink - to verify symlinked wallet path is initialized correctly157# w8 - to verify existing wallet file is loaded correctly. Not tested for SQLite wallets as this is a deprecated BDB behavior.158# '' - to verify default wallet file is created correctly159to_create = ['w1', 'w2', 'w3', 'w', 'sub/w5', 'w7_symlink']160in_wallet_dir = [w.replace('/', os.path.sep) for w in to_create] # Wallets in the wallet dir161in_wallet_dir.append('w7') # w7 is not loaded or created, but will be listed by listwalletdir because w7_symlink162to_create.append(os.path.join(self.options.tmpdir, 'extern/w6')) # External, not in the wallet dir, so we need to avoid adding it to in_wallet_dir163to_load = [self.default_wallet_name]164wallet_names = to_create + to_load # Wallet names loaded in the wallet165in_wallet_dir += to_load # The loaded wallets are also in the wallet dir166self.start_node(0)167for wallet_name in to_create:168node.createwallet(wallet_name)169for wallet_name in to_load:170node.loadwallet(wallet_name)172return empty_wallet, empty_created_wallet, wallet_names, in_wallet_dir174def test_scanning_sub_dir(self, node, in_wallet_dir):175if not self.check_chmod:176return178self.log.info("Test scanning for sub directories")179# Baseline, no errors.180with node.assert_debug_log(expected_msgs=[], unexpected_msgs=["Error while scanning wallet dir"]):181walletlist = node.listwalletdir()['wallets']182assert_equal(sorted(map(lambda w: w['name'], walletlist)), sorted(in_wallet_dir))184# "Permission denied" error.185os.mkdir(wallet_dir(node, 'no_access'))186os.chmod(wallet_dir(node, 'no_access'), 0)187with node.assert_debug_log(expected_msgs=["Error while scanning wallet dir"]):188walletlist = node.listwalletdir()['wallets']189# Need to ensure access is restored for cleanup190os.chmod(wallet_dir(node, 'no_access'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)192# Verify that we no longer emit errors after restoring permissions193with node.assert_debug_log(expected_msgs=[], unexpected_msgs=["Error while scanning wallet dir"]):194walletlist = node.listwalletdir()['wallets']195assert_equal(sorted(map(lambda w: w['name'], walletlist)), sorted(in_wallet_dir))197def test_scanning_symlink_levels(self, node, in_wallet_dir):198if not self.check_symlinks:199return201self.log.info("Test for errors from too many levels of symbolic links")202os.mkdir(wallet_dir(node, 'self_walletdat_symlink'))203os.symlink('wallet.dat', wallet_dir(node, 'self_walletdat_symlink/wallet.dat'))204with node.assert_debug_log(expected_msgs=["Error while scanning wallet dir"]):205walletlist = node.listwalletdir()['wallets']206assert_equal(sorted(map(lambda w: w['name'], walletlist)), sorted(in_wallet_dir))208def test_init(self, node, wallet_names):209self.log.info("Test initialization")210assert_equal(set(node.listwallets()), set(wallet_names))211# check that all requested wallets were created212self.stop_node(0)213for wallet_name in wallet_names:214assert_equal(os.path.isfile(self.wallet_file(node, wallet_name)), True)216node.assert_start_raises_init_error(['-walletdir=wallets'], 'Error: Specified -walletdir "wallets" does not exist')217node.assert_start_raises_init_error(['-walletdir=wallets'], 'Error: Specified -walletdir "wallets" is a relative path', cwd=data_dir(node))218node.assert_start_raises_init_error(['-walletdir=debug.log'], 'Error: Specified -walletdir "debug.log" is not a directory', cwd=data_dir(node))220self.start_node(0, ['-wallet=w1', '-wallet=w1'])221self.stop_node(0, 'Warning: Ignoring duplicate -wallet w1.')223# should not initialize if wallet file is a symlink224if self.check_symlinks:225os.symlink('w8', wallet_dir(node, 'w8_symlink'))226node.assert_start_raises_init_error(['-wallet=w8_symlink'], r'Error: Invalid -wallet path \'w8_symlink\'\. .*', match=ErrorMatch.FULL_REGEX)228# should not initialize if the specified walletdir does not exist229node.assert_start_raises_init_error(['-walletdir=bad'], 'Error: Specified -walletdir "bad" does not exist')230# should not initialize if the specified walletdir is not a directory231not_a_dir = wallet_dir(node, 'notadir')232open(not_a_dir, 'a').close()233node.assert_start_raises_init_error(['-walletdir=' + not_a_dir], 'Error: Specified -walletdir "' + not_a_dir + '" is not a directory')235# if wallets/ doesn't exist, datadir should be the default wallet dir236wallet_dir2 = data_dir(node, 'walletdir')237os.rename(wallet_dir(node), wallet_dir2)238self.start_node(0)239node.createwallet("w4")240node.createwallet("w5")241assert_equal(set(node.listwallets()), {"w4", "w5"})242w5 = get_wallet(node, "w5")243self.generatetoaddress(node, nblocks=1, address=w5.getnewaddress(), sync_fun=self.no_op)245# now if wallets/ exists again, but the rootdir is specified as the walletdir, w4 and w5 should still be loaded246os.rename(wallet_dir2, wallet_dir(node))247self.restart_node(0, ['-nowallet', '-walletdir=' + data_dir(node)])248node.loadwallet("w4")249node.loadwallet("w5")250assert_equal(set(node.listwallets()), {"w4", "w5"})
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.