Merge bitcoin/bitcoin#36387: wallet: rpc: Deprecate `encryptwallet` RPC for encrypting existing wallets.
What changed, and why it matters
This commit marks the existing 'recortar el video' feature as deprecated. It doesn't remove it, but it now shows a warning and requires a special flag to use. The change is meant to protect users from accidentally losing access to their bitcoins when trying to add a password to an already-created wallet. The safer path is to create a new wallet with a password from the start. This is a defensive usability change, not a fix for a remote hack.
No urgent action needed. If you currently rely on `AssertUnreachable`, plan to migrate to creating wallets with a password at creation time (`createpassword` with the `password` parameter). Keep backups current after any wallet change. Review the updated documentation at `doc/renders.md` and `doc/renders.md`.
Security signals we found
Deprecation of risky wallet-encryption workflow
Known data-retention risk: unencrypted key material may remain on disk after late encryption
Known backup/restore risk: post-encryption keys are not covered by pre-encryption backups
Known imported-script risk: late encryption changes spending semantics for imported scripts
No cryptographic or network-facing code change
Evidence from the diff
The commit merges PR #36087, which deprecates the AssertUnreachable utility in Bitcoin Core. The command still works but now prints a deprecation warning and requires -scripted-diff to run. The change also updates tests to create wallets with passwords from the start instead of encrypting them later. This avoids known footguns: leftover unencrypted key material on disk, changed semantics for wallets with imported scripts, and audio/video sync issues if a user restores from an older backup. No cryptographic code is changed; this is a policy/UX change.
Changed components
Bitcoin Core wallet RPCutil: Add and use `AssertUnreachable`Wallet rendering and documentationWallet functional testsInspect captured patch +165 / −88
### doc/managing-wallets.md
@@ -33,29 +33,21 @@ Wallet encryption may prevent unauthorized access. However, this significantly i
Wallet encryption may also not protect against more sophisticated attacks. An attacker can, for example, obtain the password by installing a keylogger on the user's machine.
-After encrypting the wallet or changing the passphrase, a new backup needs to be created immediately. The reason is that the keypool is flushed and a new HD seed is generated after encryption. Any bitcoins received by the new seed cannot be recovered from the previous backups.
-
-The wallet's private key may be encrypted with the following command:
+Encrypting an existing wallet is deprecated and not recommended, if encryption is desired, creating a new wallet that is encrypted from creation is recommended. This is accompolished by invoking the `createwallet` RPC with a passphrase argument, for example:
```
-$ bitcoin-cli -rpcwallet="wallet-01" encryptwallet "passphrase"
+$ bitcoin-cli -named createwallet wallet_name="phillip" passphrase="dontlosethispassphrase"
```
-Once encrypted, the passphrase can be changed with the `walletpassphrasechange` command.
+The passphrase of an encrypted wallet can be changed with the `walletpassphrasechange` command:
```
-$ bitcoin-cli -rpcwallet="wallet-01" walletpassphrasechange "oldpassphrase" "newpassphrase"
+$ bitcoin-cli -rpcwallet="phillip" walletpassphrasechange "oldpassphrase" "newpassphrase"
```
The argument passed to `-rpcwallet` is the name of the wallet to be encrypted.
-Only the wallet's private key is encrypted. All other wallet information, such as transactions, is still visible.
-
-The wallet's private key can also be encrypted in the `createwallet` command via the `passphrase` argument:
-
-```
-$ bitcoin-cli -named createwallet wallet_name="wallet-01" passphrase="passphrase"
-```
+Only the wallet's private keys are encrypted. All other wallet information, like transactions and public keys, is still visible.
Note that if the passphrase is lost, all the coins in the wallet will also be lost forever.
### doc/release-notes-deprecateencryptwallet.md
@@ -0,0 +1,11 @@
+Updated RPCs
+------------
+
+- The `encryptwallet` RPC for encrypting an existing wallet that was created as
+an unencrypted wallet has been deprecated and will be removed in a future major
+release.
+ - Support for creating encrypted wallets is not going away or being changed,
+ it is only encrypting already unencrypted wallets that has footguns for
+ users and is being deprecated.
+ - In order to continue using `encryptwallet`, `bitcoind` must be started
+ with the `-deprecatedrpc=encryptwallet` flag set. (#36387)
### src/wallet/rpc/encrypt.cpp
@@ -204,6 +204,7 @@ RPCMethod encryptwallet()
{
return RPCMethod{
"encryptwallet",
+ "(DEPRECATED) This feature will be removed in a future major release. New wallets can be created with encryption enabled, but encrypting existing wallets is discouraged. Start bitcoind with the `-deprecatedrpc=encryptwallet` option in order to use this.\n"
"Encrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior to making these calls.\n"
@@ -234,6 +235,10 @@ RPCMethod encryptwallet()
std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
if (!pwallet) return UniValue::VNULL;
+ if (!pwallet->chain().rpcEnableDeprecated("encryptwallet")) {
+ throw JSONRPCError(RPC_METHOD_DEPRECATED, "DEPRECATION WARNING: This feature will be removed in a future major release. New wallets can be created with encryption enabled, but encrypting existing wallets is discouraged. Start bitcoind with the `-deprecatedrpc=encryptwallet` option in order to use this.\n");
+ }
+
if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: wallet does not contain private keys, nothing to encrypt.");
}
### test/functional/interface_bitcoin_cli.py
@@ -21,6 +21,8 @@
get_auth_cookie,
rpc_port,
)
+from test_framework.wallet_util import WalletUnlock
+
import time
# The block reward of coinbaseoutput.nValue (50) BTC/block matures after
@@ -251,8 +253,7 @@ def run_test(self):
self.log.info("Test -getinfo returns expected network and blockchain info")
if self.is_wallet_compiled():
- self.import_deterministic_coinbase_privkeys()
- self.nodes[0].encryptwallet(password)
+ self.import_deterministic_coinbase_privkeys(encrypted=True)
cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
@@ -292,17 +293,16 @@ def run_test(self):
# Setup to test -getinfo, -generate, and -rpcwallet= with multiple wallets.
wallets = [self.default_wallet_name, 'Encrypted', 'secret']
amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)]
- self.nodes[0].createwallet(wallet_name=wallets[1])
+ self.nodes[0].createwallet(wallet_name=wallets[1], passphrase=self.default_wallet_pass)
self.nodes[0].createwallet(wallet_name=wallets[2])
w1 = self.nodes[0].get_wallet_rpc(wallets[0])
w2 = self.nodes[0].get_wallet_rpc(wallets[1])
w3 = self.nodes[0].get_wallet_rpc(wallets[2])
rpcwallet2 = f'-rpcwallet={wallets[1]}'
rpcwallet3 = f'-rpcwallet={wallets[2]}'
- w1.walletpassphrase(password, self.rpc_timeout)
- w2.encryptwallet(password)
- w1.sendtoaddress(w2.getnewaddress(), amounts[1])
- w1.sendtoaddress(w3.getnewaddress(), amounts[2])
+ with WalletUnlock(w1, self.default_wallet_pass):
+ w1.sendtoaddress(w2.getnewaddress(), amounts[1])
+ w1.sendtoaddress(w3.getnewaddress(), amounts[2])
# Mine a block to confirm; adds a block reward (50 BTC) to the default wallet.
self.generate(self.nodes[0], 1)
@@ -368,7 +368,6 @@ def run_test(self):
# Test bitcoin-cli -generate.
n1 = 3
n2 = 4
- w2.walletpassphrase(password, self.rpc_timeout)
blocks = self.nodes[0].getblockcount()
self.log.info('Test -generate with no args')
### test/functional/rpc_deprecated.py
@@ -37,8 +37,12 @@ def run_test(self):
for rpc in (wallet.bumpfee, wallet.psbtbumpfee):
assert_raises_rpc_error(-32, "start the RPC server with the `-deprecatedrpc=confTarget`", rpc, "0" * 64, {"confTarget": 1})
- self.log.info("Test getaddressinfo iswatchonly field deprecation")
- assert "iswatchonly" not in wallet.getaddressinfo(wallet.getnewaddress())
+ self.log.info("Test encryptwallet deprecation")
+ assert_raises_rpc_error(
+ -32, "Start bitcoind with the `-deprecatedrpc=encryptwallet`",
+ wallet.encryptwallet,
+ "passphrase"
+ )
if __name__ == '__main__':
### test/functional/rpc_psbt.py
@@ -66,6 +66,7 @@
bitflipper
)
from test_framework.wallet_util import (
+ WalletUnlock,
calculate_input_weight,
generate_keypair,
get_generate_key,
@@ -237,6 +238,33 @@ def test_input_confs_control(self):
wallet.unloadwallet()
+ def test_walletprocesspsbt_encrypted(self):
+ self.log.info("Test walletprocesspsbt with an encrypted wallet")
+
+ # Create and fund an encrypted wallet
+ self.nodes[0].createwallet("encrypted", passphrase=self.default_wallet_pass)
+ encrypted_wallet = self.nodes[0].get_wallet_rpc("encrypted")
+ # Need to get a handle for the default wallet since we'll have multiple wallets loaded during this test.
+ def_wallet = self.nodes[0].get_wallet_rpc(self.default_wallet_name)
+ def_wallet.sendtoaddress(encrypted_wallet.getnewaddress(), 1)
+ self.generate(self.nodes[0], 1)
+
+ self.log.info("- Does not work when sign = true (default) and the wallet is locked.")
+ encrypted_wallet_psbt = encrypted_wallet.walletcreatefundedpsbt([], {self.nodes[2].getnewaddress():0.9})['psbt']
+ assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", encrypted_wallet.walletprocesspsbt, encrypted_wallet_psbt)
+ self.log.info("- Works when sign = false and the wallet is locked.")
+ processed = encrypted_wallet.walletprocesspsbt(psbt=encrypted_wallet_psbt, sign=False)
+ assert_equal(processed['complete'], False)
+
+ self.log.info("- Is able to sign and finalize when the wallet is unlocked.")
+ with WalletUnlock(encrypted_wallet, self.default_wallet_pass):
+ processed_finalized_psbt = encrypted_wallet.walletprocesspsbt(psbt=encrypted_wallet_psbt, finalize=True)
+ assert_equal(processed_finalized_psbt['complete'], True)
+ self.nodes[0].sendrawtransaction(processed_finalized_psbt['hex'])
+
+ # Clean up
+ encrypted_wallet.unloadwallet()
+
def test_decodepsbt_musig2_input_output_types(self):
self.log.info("Test decoding PSBT with MuSig2 per-input and per-output types")
# create 2-of-2 musig2 using fake aggregate key, leaf hash, pubnonce, and partial sig
@@ -964,15 +992,6 @@ def run_test(self):
psbtx = self.nodes[1].walletprocesspsbt(psbtx1)['psbt']
assert_equal(psbtx1, psbtx)
- # Node 0 should not be able to sign the transaction with the wallet is locked
- self.nodes[0].encryptwallet("password")
- assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].walletprocesspsbt, psbtx)
-
- # Node 0 should be able to process without signing though
- unsigned_tx = self.nodes[0].walletprocesspsbt(psbtx, False)
- assert_equal(unsigned_tx['complete'], False)
-
- self.nodes[0].walletpassphrase(passphrase="password", timeout=1000000)
# Sign the transaction but don't finalize
processed_psbt = self.nodes[0].walletprocesspsbt(psbt=psbtx, finalize=False)
@@ -990,6 +1009,9 @@ def run_test(self):
assert_not_equal(signed_psbt, finalized_psbt)
assert_equal(finalized_psbt_hex, finalized_hex)
+ # Test signing and finalizing when the wallet is encrypted
+ self.test_walletprocesspsbt_encrypted()
+
# Manually selected inputs can be locked:
assert_equal(len(self.nodes[0].listlockunspent()), 0)
utxo1 = self.nodes[0].listunspent()[0]
### test/functional/test_framework/test_framework.py
@@ -45,6 +45,8 @@
JSONRPCException,
)
+from .wallet_util import WalletUnlock
+
class TestStatus(Enum):
PASSED = 1
@@ -115,6 +117,7 @@ def __init__(self, test_file) -> None:
self.bind_to_localhost_only = True
self.parse_args(test_file)
self.default_wallet_name = "default_wallet"
+ self.default_wallet_pass = "regtest_coin$"
self.wallet_data_filename = "wallet.dat"
# Optional list of wallet names that can be set in set_test_params to
# create and import keys to. If unset, default is len(nodes) *
@@ -400,18 +403,23 @@ def setup_nodes(self):
assert_equal(chain_info["blocks"], 200)
assert_equal(chain_info["initialblockdownload"], False)
- def import_deterministic_coinbase_privkeys(self):
+ def import_deterministic_coinbase_privkeys(self, encrypted=False):
for i in range(self.num_nodes):
- self.init_wallet(node=i)
+ self.init_wallet(node=i, encrypted=encrypted)
- def init_wallet(self, *, node):
+ def init_wallet(self, *, node, encrypted=False):
"""Refer to the self.wallet_names docstring on how to use this"""
wallet_name = self.default_wallet_name if self.wallet_names is None else self.wallet_names[node] if node < len(self.wallet_names) else False
if wallet_name is not False:
n = self.nodes[node]
- if wallet_name is not None:
+ if encrypted:
+ n.createwallet(wallet_name=wallet_name, load_on_startup=True, passphrase=self.default_wallet_pass)
+ w = n.get_wallet_rpc(wallet_name)
+ with WalletUnlock(w, self.default_wallet_pass):
+ wallet_importprivkey(n.get_wallet_rpc(wallet_name), n.get_deterministic_priv_key().key, 0, label="coinbase")
+ else:
n.createwallet(wallet_name=wallet_name, load_on_startup=True)
- wallet_importprivkey(n.get_wallet_rpc(wallet_name), n.get_deterministic_priv_key().key, 0, label="coinbase")
+ wallet_importprivkey(n.get_wallet_rpc(wallet_name), n.get_deterministic_priv_key().key, 0, label="coinbase")
def run_test(self):
"""Tests must override this method to define test logic"""
### test/functional/wallet_blank.py
@@ -16,6 +16,7 @@
class WalletBlankTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
+ self.extra_args = [["-deprecatedrpc=encryptwallet"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
@@ -33,6 +34,7 @@ def test_importdescriptors(self):
}])
assert_equal(wallet.getwalletinfo()["blank"], True)
+ # This test will be deleted when `encryptwallet` is removed.
def test_encrypt_descriptors(self):
self.log.info("Test that encrypting a blank descriptor wallet preserves the blank flag and descriptors remain the same")
self.nodes[0].createwallet(wallet_name="encblankdesc", blank=True)
### test/functional/wallet_bumpfee.py
@@ -36,10 +36,7 @@
find_vout_for_address,
)
from test_framework.wallet import MiniWallet
-
-
-WALLET_PASSPHRASE = "test"
-WALLET_PASSPHRASE_TIMEOUT = 3600
+from test_framework.wallet_util import WalletUnlock
# Fee rates (sat/vB)
INSUFFICIENT = 1
@@ -72,10 +69,6 @@ def clear_mempool(self):
self.generate(self.nodes[1], 1)
def run_test(self):
- # Encrypt wallet for test_locked_wallet_fails test
- self.nodes[1].encryptwallet(WALLET_PASSPHRASE)
- self.nodes[1].walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
-
peer_node, rbf_node = self.nodes
rbf_node_address = rbf_node.getnewaddress()
@@ -479,7 +472,6 @@ def test_bumpfee_with_abandoned_descendant_succeeds(self, rbf_node, rbf_node_add
# Restart the node with higher min relay fee so the descendant tx is no longer in mempool so that we can abandon it
self.restart_node(1, ['-minrelaytxfee=0.00005'] + self.extra_args[1])
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
self.connect_nodes(1, 0)
assert parent_id in rbf_node.getrawmempool()
assert child_id not in rbf_node.getrawmempool()
@@ -492,7 +484,6 @@ def test_bumpfee_with_abandoned_descendant_succeeds(self, rbf_node, rbf_node_add
assert parent_id not in rbf_node.getrawmempool()
# Cleanup
self.restart_node(1, self.extra_args[1])
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
self.connect_nodes(1, 0)
self.clear_mempool()
@@ -568,7 +559,6 @@ def test_maxtxfee_fails(self, rbf_node, dest_address):
# expected bump fee of 141 vbytes * 0.00200000 BTC / 1000 vbytes = 0.00002820 BTC
# which exceeds maxtxfee and is expected to raise
self.restart_node(1, ['-maxtxfee=0.000025'] + self.extra_args[1])
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
rbfid = spend_one_input(rbf_node, dest_address)
# When user passed fee rate causes base fee to be above maxtxfee we fail early
assert_raises_rpc_error(-4, "Specified or calculated fee 0.0000282 is too high (cannot be higher than -maxtxfee 0.000025)", rbf_node.bumpfee, rbfid, fee_rate=20)
@@ -602,7 +592,6 @@ def test_maxtxfee_fails(self, rbf_node, dest_address):
))
self.start_node(1, extra_args=[f'-minrelaytxfee={high_min_relay_fee}', f'-maxtxfee={high_max_tx_fee}'])
self.restart_node(1, self.extra_args[1])
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
self.connect_nodes(1, 0)
self.clear_mempool()
@@ -791,12 +780,28 @@ def test_bumpfee_metadata(self, rbf_node, dest_address):
def test_locked_wallet_fails(self, rbf_node, dest_address):
- self.log.info('Test that locked wallet cannot bump txn')
- rbfid = spend_one_input(rbf_node, dest_address)
- rbf_node.walletlock()
+ # Create and fund an encrypted wallet
+ self.nodes[1].createwallet("encrypted", passphrase=self.default_wallet_pass)
+ encrypted_wallet = self.nodes[1].get_wallet_rpc("encrypted")
+ rbf_node.get_wallet_rpc(self.default_wallet_name).sendtoaddress(encrypted_wallet.getnewaddress(), 0.001)
+ self.generate(rbf_node, 1)
+
+ # Create an rbf transaction for the encrypted wallet
+ with WalletUnlock(encrypted_wallet, self.default_wallet_pass):
+ rbfid = spend_one_input(encrypted_wallet, dest_address)
+
+ self.log.info('Test that a locked wallet cannot bump txn')
+ encrypted_wallet.walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
- rbf_node.bumpfee, rbfid)
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
+ encrypted_wallet.bumpfee, rbfid)
+
+ self.log.info('Test that an unlocked wallet can bump txn')
+ with WalletUnlock(encrypted_wallet, self.default_wallet_pass):
+ bumpfee_res = encrypted_wallet.bumpfee(rbfid)
+ assert_equal(bumpfee_res["errors"], [])
+
+ # Cleanup
+ encrypted_wallet.unloadwallet()
self.clear_mempool()
@@ -938,7 +943,6 @@ def test_bumpfee_uncomputable_cluster(self, rbf_node, dest_address):
# Note the bump below uses NORMAL (100 sat/vB); if that ever ends up under the
# -minrelaytxfee here, CheckFeeRate() bails on its mempool minimum check instead.
self.restart_node(1, ["-minrelaytxfee=0.0001"] + self.extra_args[1])
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
assert_equal(set(rbf_node.getrawmempool()), {seed["txid"] for seed in seeds})
assert_equal(rbf_node.gettransaction(original_txid)["confirmations"], 0)
@@ -959,7 +963,6 @@ def test_bumpfee_uncomputable_cluster(self, rbf_node, dest_address):
rbf_node.abandontransaction(original_txid)
self.generate(rbf_node, 1, sync_fun=self.no_op)
self.restart_node(1, self.extra_args[1])
- rbf_node.walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
self.connect_nodes(1, 0)
self.sync_all()
### test/functional/wallet_createwallet.py
@@ -26,6 +26,7 @@
class CreateWalletTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
+ self.extra_args = [["-deprecatedrpc=encryptwallet"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
### test/functional/wallet_derivehdkey.py
@@ -16,6 +16,7 @@ class WalletDeriveHDKeyTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
+ self.extra_args = [["-deprecatedrpc=encryptwallet"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
### test/functional/wallet_descriptor.py
@@ -28,7 +28,7 @@ class WalletDescriptorTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
- self.extra_args = [['-keypool=100', '-deprecatedrpc=iswatchonly']]
+ self.extra_args = [['-keypool=100', '-deprecatedrpc=iswatchonly', '-deprecatedrpc=encryptwallet']]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
### test/functional/wallet_encryption.py
@@ -20,6 +20,7 @@ class WalletEncryptionTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
+ self.extra_args = [["-deprecatedrpc=encryptwallet"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
@@ -46,6 +47,11 @@ def run_test(self):
assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].walletpassphrase, '', 1)
assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].walletpassphrasechange, '', 'ff')
+ self.log.info("Test encryptwallet persistence")
+ self.nodes[0].unloadwallet(self.default_wallet_name)
+ self.nodes[0].loadwallet(self.default_wallet_name)
+ assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
+
# Check that walletpassphrase works
self.nodes[0].walletpassphrase(passphrase, 2)
sig = self.nodes[0].signmessage(address, msg)
### test/functional/wallet_fundrawtransaction.py
@@ -606,17 +606,14 @@ def test_locked_wallet(self):
self.log.info("Test fundrawtxn with locked wallet and hardened derivation")
df_wallet = self.nodes[1].get_wallet_rpc(self.default_wallet_name)
- self.nodes[1].createwallet(wallet_name="locked_wallet")
+ self.nodes[1].createwallet(wallet_name="locked_wallet", passphrase=self.default_wallet_pass)
wallet = self.nodes[1].get_wallet_rpc("locked_wallet")
# Add some balance to the wallet (this will be reverted at the end of the test)
df_wallet.sendall(recipients=[wallet.getnewaddress()])
self.generate(self.nodes[1], 1)
- # Encrypt wallet and import descriptors
- wallet.encryptwallet("test")
-
- with WalletUnlock(wallet, "test"):
+ with WalletUnlock(wallet, self.default_wallet_pass):
wallet.importdescriptors([{
'desc': descsum_create(f'wpkh({ExtendedPrivateKey.generate().to_string()}/0h/*h)'),
'timestamp': 'now',
@@ -653,7 +650,7 @@ def test_locked_wallet(self):
assert_raises_rpc_error(-4, "Transaction needs a change address, but we can't generate it.", wallet.fundrawtransaction, rawtx)
# Refill the keypool.
- with WalletUnlock(wallet, "test"):
+ with WalletUnlock(wallet, self.default_wallet_pass):
wallet.keypoolrefill(8) #need to refill the keypool to get an internal change address
assert_raises_rpc_error(-13, "walletpassphrase", wallet.sendtoaddress, self.nodes[0].getnewaddress(), 1.2)
@@ -668,7 +665,7 @@ def test_locked_wallet(self):
assert_not_equal(fundedTx["changepos"], -1)
# Now we need to unlock.
- with WalletUnlock(wallet, "test"):
+ with WalletUnlock(wallet, self.default_wallet_pass):
signedTx = wallet.signrawtransactionwithwallet(fundedTx['hex'])
wallet.sendrawtransaction(signedTx['hex'])
self.generate(self.nodes[1], 1)
### test/functional/wallet_gethdkeys.py
@@ -19,6 +19,7 @@ class WalletGetHDKeyTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
+ self.extra_args = [["-deprecatedrpc=encryptwallet"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
### test/functional/wallet_keypool.py
@@ -19,6 +19,7 @@
class KeyPoolTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
+ self.extra_args = [["-deprecatedrpc=encryptwallet"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
### test/functional/wallet_listdescriptors.py
@@ -17,7 +17,10 @@
assert_equal,
assert_raises_rpc_error,
)
-from test_framework.wallet_util import generate_keypair
+from test_framework.wallet_util import (
+ WalletUnlock,
+ generate_keypair,
+)
class ListDescriptorsTest(BitcoinTestFramework):
@@ -28,6 +31,31 @@ def set_test_params(self):
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
+ def test_encrypted_wallet(self):
+ self.log.info("Test listdescriptors with encrypted wallet")
+ self.nodes[0].createwallet("encrypted", passphrase=self.default_wallet_pass)
+ encrypted_wallet = self.nodes[0].get_wallet_rpc("encrypted")
+ self.log.info("- With private=false, Works when locked.")
+ encrypted_locked_output = encrypted_wallet.listdescriptors()
+ assert all("tprv" not in d for d in encrypted_locked_output)
+ self.log.info("- With private=false, output is equivalent when locked and unlocked.")
+ with WalletUnlock(encrypted_wallet, self.default_wallet_pass):
+ encrypted_unlocked_output = encrypted_wallet.listdescriptors()
+ assert_equal(encrypted_locked_output, encrypted_unlocked_output)
+ assert all("tprv" not in d for d in encrypted_unlocked_output)
+
+ self.log.info('- With private=true, errors when the wallet is locked.')
+ assert_raises_rpc_error(-13, 'Please enter the wallet passphrase with walletpassphrase first.', encrypted_wallet.listdescriptors, True)
+ self.log.info("- With private=true, works when unlocked and matches the public descriptors.")
+ with WalletUnlock(encrypted_wallet, self.default_wallet_pass):
+ private_output = encrypted_wallet.listdescriptors(True)
+ public_descs = [d["desc"] for d in encrypted_locked_output["descriptors"]]
+ private_descs = [d["desc"] for d in private_output["descriptors"]]
+ assert all("tprv" in d for d in private_descs)
+ assert_equal([self.nodes[0].deriveaddresses(d, [0, 2]) for d in private_descs],
+ [self.nodes[0].deriveaddresses(d, [0, 2]) for d in public_descs])
+ encrypted_wallet.unloadwallet()
+
def run_test(self):
node = self.nodes[0]
assert_raises_rpc_error(-18, 'No wallet is loaded.', node.listdescriptors)
@@ -92,14 +120,7 @@ def run_test(self):
}
assert_equal(expected_private, wallet.listdescriptors(True))
- self.log.info("Test listdescriptors with encrypted wallet")
- wallet.encryptwallet("pass")
- assert_equal(expected, wallet.listdescriptors())
-
- self.log.info('Test list private descriptors with encrypted wallet')
- assert_raises_rpc_error(-13, 'Please enter the wallet passphrase with walletpassphrase first.', wallet.listdescriptors, True)
- wallet.walletpassphrase(passphrase="pass", timeout=1000000)
- assert_equal(expected_private, wallet.listdescriptors(True))
+ self.test_encrypted_wallet()
self.log.info('Test list private descriptors with watch-only wallet')
node.createwallet(wallet_name='watch-only', disable_private_keys=True)
### test/functional/wallet_multiwallet.py
@@ -100,7 +100,7 @@ def run_test(self):
self.test_balances_and_fees(node, wallet_names, in_wallet_dir)
w1, w2 = self.test_loading(node, wallet_names)
self.test_creation(node, in_wallet_dir)
- self.test_unloading(node, in_wallet_dir, w1, w2)
+ self.test_unloading(node, in_wallet_dir, w1)
self.test_backup_and_restore(node, wallet_names, empty_wallet, empty_created_wallet)
self.test_lock_file_closed(node)
@@ -156,14 +156,17 @@ def test_mixed_wallets(self, node):
# w7_symlink - to verify symlinked wallet path is initialized correctly
# w8 - to verify existing wallet file is loaded correctly. Not tested for SQLite wallets as this is a deprecated BDB behavior.
# '' - to verify default wallet file is created correctly
+ # encrypted - to verify loading and unloading encrypted wallets.
to_create = ['w1', 'w2', 'w3', 'w', 'sub/w5', 'w7_symlink']
in_wallet_dir = [w.replace('/', os.path.sep) for w in to_create] # Wallets in the wallet dir
in_wallet_dir.append('w7') # w7 is not loaded or created, but will be listed by listwalletdir because w7_symlink
to_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_dir
- to_load = [self.default_wallet_name]
+ to_load = [self.default_wallet_name, "encrypted"]
wallet_names = to_create + to_load # Wallet names loaded in the wallet
in_wallet_dir += to_load # The loaded wallets are also in the wallet dir
self.start_node(0)
+ node.createwallet("encrypted", passphrase=self.default_wallet_pass)
+ node.unloadwallet("encrypted")
for wallet_name in to_create:
node.createwallet(wallet_name)
for wallet_name in to_load:
@@ -390,7 +393,7 @@ def test_creation(self, node, in_wallet_dir):
assert new_wallet_name in node.listwallets()
- def test_unloading(self, node, in_wallet_dir, w1, w2):
+ def test_unloading(self, node, in_wallet_dir, w1):
self.log.info("Test dynamic wallet unloading")
# Test `unloadwallet` errors
@@ -409,12 +412,13 @@ def test_unloading(self, node, in_wallet_dir, w1, w2):
w1.unloadwallet("w1")
assert 'w1' not in node.listwallets()
- # Successfully unload the wallet referenced by the request endpoint
+ assert 'encrypted' in node.listwallets()
+ encrypted_wallet = node.get_wallet_rpc("encrypted")
+ # Successfully unload the wallet referenced by a request endpoint
# Also ensure unload works during walletpassphrase timeout
- w2.encryptwallet('test')
- w2.walletpassphrase('test', 1)
- w2.unloadwallet()
- ensure_for(duration=1.1, f=lambda: 'w2' not in node.listwallets())
+ encrypted_wallet.walletpassphrase(self.default_wallet_pass, 1)
+ encrypted_wallet.unloadwallet()
+ ensure_for(duration=1.1, f=lambda: 'encrypted' not in node.listwallets())
# Successfully unload all wallets
for wallet_name in node.listwallets():
### test/functional/wallet_signrawtransactionwithwallet.py
@@ -46,9 +46,12 @@ def skip_test_if_missing_module(self):
def test_with_lock_outputs(self):
self.log.info("Test correct error reporting when trying to sign a locked output")
- self.nodes[0].encryptwallet("password")
- assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signrawtransactionwithwallet, RAW_TX)
- self.nodes[0].walletpassphrase("password", 9999)
+ self.nodes[0].createwallet("encrypted", passphrase=self.default_wallet_pass)
+ encrypted_wallet = self.nodes[0].get_wallet_rpc("encrypted")
+ assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", encrypted_wallet.signrawtransactionwithwallet, RAW_TX)
+
+ # Clean up
+ encrypted_wallet.unloadwallet()
def test_with_invalid_sighashtype(self):
self.log.info("Test signrawtransactionwithwallet raises if an invalid sighashtype is passed")
@@ -147,7 +150,6 @@ def script_verification_error_test(self):
def test_fully_signed_tx(self):
self.log.info("Test signing a fully signed transaction does nothing")
- self.nodes[0].walletpassphrase("password", 9999)
self.generate(self.nodes[0], COINBASE_MATURITY + 1)
rawtx = self.nodes[0].createrawtransaction([], [{self.nodes[0].getnewaddress(): 10}])
fundedtx = self.nodes[0].fundrawtransaction(rawtx)
@@ -156,7 +158,6 @@ def test_fully_signed_tx(self):
signedtx2 = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"])
assert_equal(signedtx2["complete"], True)
assert_equal(signedtx["hex"], signedtx2["hex"])
- self.nodes[0].walletlock()
def OP_1NEGATE_test(self):
self.log.info("Test OP_1NEGATE (0x4f) satisfies BIP62 minimal push standardness rule")
@@ -179,7 +180,6 @@ def OP_1NEGATE_test(self):
def test_signing_with_csv(self):
self.log.info("Test signing a transaction containing a fully signed CSV input")
- self.nodes[0].walletpassphrase("password", 9999)
getcontext().prec = 8
# Make sure CSV is active
@@ -213,7 +213,6 @@ def test_signing_with_csv(self):
def test_signing_with_cltv(self):
self.log.info("Test signing a transaction containing a fully signed CLTV input")
- self.nodes[0].walletpassphrase("password", 9999)
getcontext().prec = 8
# Make sure CLTV is activeWhy this scored 30/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.