wallet_encryption.py raw

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