wallet_encryption.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2016-present The Bitcoin Core developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Test Wallet encryption"""
   6  
   7  import time
   8  import subprocess
   9  
  10  from test_framework.messages import hash256
  11  from test_framework.test_framework import BitcoinTestFramework
  12  from test_framework.util import (
  13      assert_raises_rpc_error,
  14      assert_equal,
  15  )
  16  from test_framework.wallet_util import WalletUnlock
  17  
  18  
  19  class WalletEncryptionTest(BitcoinTestFramework):
  20      def set_test_params(self):
  21          self.setup_clean_chain = True
  22          self.num_nodes = 1
  23  
  24      def skip_test_if_missing_module(self):
  25          self.skip_if_no_wallet()
  26  
  27      def run_test(self):
  28          passphrase = "WalletPassphrase"
  29          passphrase2 = "SecondWalletPassphrase"
  30  
  31          # Make sure the wallet isn't encrypted first
  32          msg = "test message"
  33          address = self.nodes[0].getnewaddress(address_type='legacy')
  34          sig = self.nodes[0].signmessage(address, msg)
  35          assert self.nodes[0].verifymessage(address, sig, msg)
  36          assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called", self.nodes[0].walletpassphrase, 'ff', 1)
  37          assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.", self.nodes[0].walletpassphrasechange, 'ff', 'ff')
  38  
  39          # Encrypt the wallet
  40          assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].encryptwallet, '')
  41          self.nodes[0].encryptwallet(passphrase)
  42  
  43          # Test that the wallet is encrypted
  44          assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
  45          assert_raises_rpc_error(-15, "Error: running with an encrypted wallet, but encryptwallet was called.", self.nodes[0].encryptwallet, 'ff')
  46          assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].walletpassphrase, '', 1)
  47          assert_raises_rpc_error(-8, "passphrase cannot be empty", self.nodes[0].walletpassphrasechange, '', 'ff')
  48  
  49          # Check that walletpassphrase works
  50          self.nodes[0].walletpassphrase(passphrase, 2)
  51          sig = self.nodes[0].signmessage(address, msg)
  52          assert self.nodes[0].verifymessage(address, sig, msg)
  53  
  54          # Check that the timeout is right
  55          time.sleep(3)
  56          assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
  57  
  58          # Test wrong passphrase
  59          assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10)
  60  
  61          # Test walletlock
  62          with WalletUnlock(self.nodes[0], passphrase):
  63              sig = self.nodes[0].signmessage(address, msg)
  64              assert self.nodes[0].verifymessage(address, sig, msg)
  65          assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
  66  
  67          # Test passphrase changes
  68          self.nodes[0].walletpassphrasechange(passphrase, passphrase2)
  69          assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10)
  70          with WalletUnlock(self.nodes[0], passphrase2):
  71              sig = self.nodes[0].signmessage(address, msg)
  72              assert self.nodes[0].verifymessage(address, sig, msg)
  73  
  74          # Test timeout bounds
  75          assert_raises_rpc_error(-8, "Timeout cannot be negative.", self.nodes[0].walletpassphrase, passphrase2, -10)
  76  
  77          self.log.info('Check a timeout less than the limit')
  78          MAX_VALUE = 100000000
  79          now = int(time.time())
  80          self.nodes[0].setmocktime(now)
  81          expected_time = now + MAX_VALUE - 600
  82          self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE - 600)
  83          actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
  84          assert_equal(actual_time, expected_time)
  85  
  86          self.log.info('Check a timeout greater than the limit')
  87          expected_time = now + MAX_VALUE
  88          self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE + 1000)
  89          actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
  90          assert_equal(actual_time, expected_time)
  91          self.nodes[0].walletlock()
  92  
  93          if not self.options.usecli: # can't be done with the test framework for cli since subprocess.Popen doesn't allow null characters
  94              # Test passphrase with null characters
  95              passphrase_with_nulls = "Phrase\0With\0Nulls"
  96              self.nodes[0].walletpassphrasechange(passphrase2, passphrase_with_nulls)
  97              # walletpassphrasechange should not stop at null characters
  98              assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase_with_nulls.partition("\0")[0], 10)
  99              assert_raises_rpc_error(-14, "The wallet passphrase entered was incorrect", self.nodes[0].walletpassphrasechange, passphrase_with_nulls.partition("\0")[0], "abc")
 100              assert_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)
 101              assert_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")
 102              with WalletUnlock(self.nodes[0], passphrase_with_nulls):
 103                  sig = self.nodes[0].signmessage(address, msg)
 104                  assert self.nodes[0].verifymessage(address, sig, msg)
 105  
 106          self.log.info("Test that wallets without private keys cannot be encrypted")
 107          self.nodes[0].createwallet(wallet_name="noprivs", disable_private_keys=True)
 108          noprivs_wallet = self.nodes[0].get_wallet_rpc("noprivs")
 109          assert_raises_rpc_error(-16, "Error: wallet does not contain private keys, nothing to encrypt.", noprivs_wallet.encryptwallet, "pass")
 110  
 111          if self.is_wallet_tool_compiled():
 112              self.log.info("Test that encryption keys in wallets without privkeys are removed")
 113  
 114              def do_wallet_tool(*args):
 115                  proc = subprocess.Popen(
 116                      self.get_binaries().wallet_argv() + [f"-datadir={self.nodes[0].datadir_path}", f"-chain={self.chain}"] + list(args),
 117                      stdin=subprocess.PIPE,
 118                      stdout=subprocess.PIPE,
 119                      stderr=subprocess.PIPE,
 120                      text=True
 121                  )
 122                  stdout, stderr = proc.communicate()
 123                  assert_equal(proc.poll(), 0)
 124                  assert_equal(stderr, "")
 125  
 126              # Since it is no longer possible to encrypt a wallet without privkeys, we need to force one into the wallet
 127              # 1. Make a dump of the wallet
 128              # 2. Add mkey record to the dump
 129              # 3. Create a new wallet from the dump
 130  
 131              # Make the dump
 132              noprivs_wallet.unloadwallet()
 133              dumpfile_path = self.nodes[0].datadir_path / "noprivs.dump"
 134              do_wallet_tool("-wallet=noprivs", f"-dumpfile={dumpfile_path}", "dump")
 135  
 136              # Modify the dump
 137              with open(dumpfile_path, "r") as f:
 138                  dump_content = f.readlines()
 139              # Drop the checksum line
 140              dump_content = dump_content[:-1]
 141              # Insert a valid mkey line. This corresponds to a passphrase of "pass".
 142              dump_content.append("046d6b657901000000,300dc926f3b3887aad3d5d5f5a0fc1b1a4a1722f9284bd5c6ff93b64a83902765953939c58fe144013c8b819f42cf698b208e9911e5f0c544fa300000000cc52050000\n")
 143              with open(dumpfile_path, "w") as f:
 144                  contents = "".join(dump_content)
 145                  f.write(contents)
 146                  checksum = hash256(contents.encode())
 147                  f.write(f"checksum,{checksum.hex()}\n")
 148  
 149              # Load the dump into a new wallet
 150              do_wallet_tool("-wallet=noprivs_enc", f"-dumpfile={dumpfile_path}", "createfromdump")
 151              # Load the wallet and make sure it is no longer encrypted
 152              with self.nodes[0].assert_debug_log(["Detected extraneous encryption keys in this wallet without private keys. Removing extraneous encryption keys."]):
 153                  self.nodes[0].loadwallet("noprivs_enc")
 154              noprivs_wallet = self.nodes[0].get_wallet_rpc("noprivs_enc")
 155              assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.", noprivs_wallet.walletpassphrase, "pass", 1)
 156              noprivs_wallet.unloadwallet()
 157  
 158              # Make a new dump and check that there are no mkeys
 159              dumpfile_path = self.nodes[0].datadir_path / "noprivs_enc.dump"
 160              do_wallet_tool("-wallet=noprivs_enc", f"-dumpfile={dumpfile_path}", "dump")
 161              with open(dumpfile_path, "r") as f:
 162                  # Check there's nothing with an 'mkey' prefix
 163                  assert_equal(all([not line.startswith("046d6b6579") for line in f]), True)
 164  
 165  
 166  if __name__ == '__main__':
 167      WalletEncryptionTest(__file__).main()
 168