/ test / functional / interface_bitcoin_cli.py
interface_bitcoin_cli.py
  1  #!/usr/bin/env python3
  2  # Copyright (c) 2017-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 bitcoin-cli"""
  6  
  7  from decimal import Decimal
  8  import re
  9  
 10  from test_framework.blocktools import COINBASE_MATURITY
 11  from test_framework.netutil import test_ipv6_local
 12  from test_framework.test_framework import BitcoinTestFramework
 13  from test_framework.util import (
 14      assert_equal,
 15      assert_greater_than_or_equal,
 16      assert_raises_process_error,
 17      assert_raises_rpc_error,
 18      get_auth_cookie,
 19      rpc_port,
 20  )
 21  import time
 22  
 23  # The block reward of coinbaseoutput.nValue (50) BTC/block matures after
 24  # COINBASE_MATURITY (100) blocks. Therefore, after mining 101 blocks we expect
 25  # node 0 to have a balance of (BLOCKS - COINBASE_MATURITY) * 50 BTC/block.
 26  BLOCKS = COINBASE_MATURITY + 1
 27  BALANCE = (BLOCKS - 100) * 50
 28  
 29  JSON_PARSING_ERROR = 'error: Error parsing JSON: foo'
 30  BLOCKS_VALUE_OF_ZERO = 'error: the first argument (number of blocks to generate, default: 1) must be an integer value greater than zero'
 31  TOO_MANY_ARGS = 'error: too many arguments (maximum 2 for nblocks and maxtries)'
 32  WALLET_NOT_LOADED = 'Requested wallet does not exist or is not loaded'
 33  WALLET_NOT_SPECIFIED = (
 34      "Multiple wallets are loaded. Please select which wallet to use by requesting the RPC "
 35      "through the /wallet/<walletname> URI path. Or for the CLI, specify the \"-rpcwallet=<walletname>\" "
 36      "option before the command (run \"bitcoin-cli -h\" for help or \"bitcoin-cli listwallets\" to see "
 37      "which wallets are currently loaded)."
 38  )
 39  
 40  
 41  def cli_get_info_string_to_dict(cli_get_info_string):
 42      """Helper method to convert human-readable -getinfo into a dictionary"""
 43      cli_get_info = {}
 44      lines = cli_get_info_string.splitlines()
 45      line_idx = 0
 46      ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
 47      while line_idx < len(lines):
 48          # Remove ansi colour code
 49          line = ansi_escape.sub('', lines[line_idx])
 50          if "Balances" in line:
 51              # When "Balances" appears in a line, all of the following lines contain "balance: wallet" until an empty line
 52              cli_get_info["Balances"] = {}
 53              while line_idx < len(lines) and not (lines[line_idx + 1] == ''):
 54                  line_idx += 1
 55                  balance, wallet = lines[line_idx].strip().split(" ")
 56                  # Remove right justification padding
 57                  wallet = wallet.strip()
 58                  if wallet == '""':
 59                      # Set default wallet("") to empty string
 60                      wallet = ''
 61                  cli_get_info["Balances"][wallet] = balance.strip()
 62          elif ": " in line:
 63              key, value = line.split(": ")
 64              if key == 'Wallet' and value == '""':
 65                  # Set default wallet("") to empty string
 66                  value = ''
 67              if key == "Proxies" and value == "n/a":
 68                  # Set N/A to empty string to represent no proxy
 69                  value = ''
 70              cli_get_info[key.strip()] = value.strip()
 71          line_idx += 1
 72      return cli_get_info
 73  
 74  
 75  class TestBitcoinCli(BitcoinTestFramework):
 76      def set_test_params(self):
 77          self.setup_clean_chain = True
 78          self.num_nodes = 1
 79          self.uses_wallet = None
 80  
 81      def skip_test_if_missing_module(self):
 82          self.skip_if_no_cli()
 83  
 84      def test_netinfo(self):
 85          """Test -netinfo output format."""
 86          self.log.info("Test -netinfo header and separate local services line")
 87          out = self.nodes[0].cli('-netinfo').send_cli().splitlines()
 88          assert out[0].startswith(f"{self.config['environment']['CLIENT_NAME']} client ")
 89          assert any(re.match(r"^Local services:.+network", line) for line in out)
 90  
 91          self.log.info("Test -netinfo local services are moved to header if details are requested")
 92          det = self.nodes[0].cli('-netinfo', '1').send_cli().splitlines()
 93          self.log.debug(f"Test -netinfo 1 header output: {det[0]}")
 94          assert re.match(rf"^{re.escape(self.config['environment']['CLIENT_NAME'])} client.+services nwl2?$", det[0])
 95          assert not any(line.startswith("Local services:") for line in det)
 96  
 97      def test_echojson_positional_equals(self):
 98          """Test JSON parameter parsing containing '=' with -named echojson"""
 99          self.log.info("Test JSON parameter parsing containing '=' is handled correctly with -named")
100  
101          # This should be treated as a positional JSON argument, not as a named
102          result = self.nodes[0].cli("-named", "echojson", '["key=value"]').send_cli()
103          assert_equal(result, [["key=value"]])
104  
105          result = self.nodes[0].cli("-named", "echojson", '["key=value", "another=test"]').send_cli()
106          assert_equal(result, [["key=value", "another=test"]])
107  
108          result = self.nodes[0].cli("-named", "echojson", '["data=test"]', "42").send_cli()
109          expected = [["data=test"], 42]
110          assert_equal(result, expected)
111  
112          # This should be treated as a named parameter, as arg0 and arg1 are valid parameter names
113          result = self.nodes[0].cli("-named", "echojson", 'arg0=["data=test"]', 'arg1=42').send_cli()
114          expected = [["data=test"], 42]
115          assert_equal(result, expected)
116  
117      def run_test(self):
118          """Main test logic"""
119          self.test_echojson_positional_equals()
120  
121          self.generate(self.nodes[0], BLOCKS)
122  
123          self.log.info("Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`")
124          cli_response = self.nodes[0].cli.getblockchaininfo()
125          rpc_response = self.nodes[0].getblockchaininfo()
126          assert_equal(cli_response, rpc_response)
127  
128          self.log.info("Test named arguments")
129          assert_equal(self.nodes[0].cli.echo(0, 1, arg3=3, arg5=5), ['0', '1', None, '3', None, '5'])
130          assert_raises_rpc_error(-8, "Parameter arg1 specified twice both as positional and named argument", self.nodes[0].cli.echo, 0, 1, arg1=1)
131          assert_raises_rpc_error(-8, "Parameter arg1 specified twice both as positional and named argument", self.nodes[0].cli.echo, 0, None, 2, arg1=1)
132  
133          self.log.info("Test that later cli named arguments values silently overwrite earlier ones")
134          assert_equal(self.nodes[0].cli("-named", "echo", "arg0=0", "arg1=1", "arg2=2", "arg1=3").send_cli(), ['0', '3', '2'])
135          assert_raises_rpc_error(-8, "Parameter args specified multiple times", self.nodes[0].cli("-named", "echo", "args=[0,1,2,3]", "4", "5", "6", ).send_cli)
136  
137          user, password = get_auth_cookie(self.nodes[0].datadir_path, self.chain)
138  
139          self.log.info("Test -stdinrpcpass option")
140          assert_equal(BLOCKS, self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input=password).getblockcount())
141          assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input='foo').echo)
142  
143          self.log.info("Test -stdin and -stdinrpcpass")
144          assert_equal(['foo', 'bar'], self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input=f'{password}\nfoo\nbar').echo())
145          assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input='foo').echo)
146  
147          self.log.info("Test connecting to a non-existing server")
148          assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo)
149  
150          self.log.info("Test handling of invalid ports in rpcconnect")
151          assert_raises_process_error(1, "Invalid port provided in -rpcconnect: 127.0.0.1:notaport", self.nodes[0].cli("-rpcconnect=127.0.0.1:notaport").echo)
152          assert_raises_process_error(1, "Invalid port provided in -rpcconnect: 127.0.0.1:-1", self.nodes[0].cli("-rpcconnect=127.0.0.1:-1").echo)
153          assert_raises_process_error(1, "Invalid port provided in -rpcconnect: 127.0.0.1:0", self.nodes[0].cli("-rpcconnect=127.0.0.1:0").echo)
154          assert_raises_process_error(1, "Invalid port provided in -rpcconnect: 127.0.0.1:65536", self.nodes[0].cli("-rpcconnect=127.0.0.1:65536").echo)
155  
156          self.log.info("Checking for IPv6")
157          have_ipv6 = test_ipv6_local()
158          if not have_ipv6:
159              self.log.info("Skipping IPv6 tests")
160  
161          if have_ipv6:
162              assert_raises_process_error(1, "Invalid port provided in -rpcconnect: [::1]:notaport", self.nodes[0].cli("-rpcconnect=[::1]:notaport").echo)
163              assert_raises_process_error(1, "Invalid port provided in -rpcconnect: [::1]:-1", self.nodes[0].cli("-rpcconnect=[::1]:-1").echo)
164              assert_raises_process_error(1, "Invalid port provided in -rpcconnect: [::1]:0", self.nodes[0].cli("-rpcconnect=[::1]:0").echo)
165              assert_raises_process_error(1, "Invalid port provided in -rpcconnect: [::1]:65536", self.nodes[0].cli("-rpcconnect=[::1]:65536").echo)
166  
167          self.log.info("Test handling of invalid ports in rpcport")
168          assert_raises_process_error(1, "Invalid port provided in -rpcport: notaport", self.nodes[0].cli("-rpcport=notaport").echo)
169          assert_raises_process_error(1, "Invalid port provided in -rpcport: -1", self.nodes[0].cli("-rpcport=-1").echo)
170          assert_raises_process_error(1, "Invalid port provided in -rpcport: 0", self.nodes[0].cli("-rpcport=0").echo)
171          assert_raises_process_error(1, "Invalid port provided in -rpcport: 65536", self.nodes[0].cli("-rpcport=65536").echo)
172  
173          self.log.info("Test port usage preferences")
174          node_rpc_port = rpc_port(self.nodes[0].index)
175          # Prevent bitcoin-cli from using existing rpcport in conf
176          conf_rpcport = "rpcport=" + str(node_rpc_port)
177          self.nodes[0].replace_in_config([(conf_rpcport, "#" + conf_rpcport)])
178          # prefer rpcport over rpcconnect
179          assert_raises_process_error(1, "Could not connect to the server 127.0.0.1:1", self.nodes[0].cli(f"-rpcconnect=127.0.0.1:{node_rpc_port}", "-rpcport=1").echo)
180          if have_ipv6:
181              assert_raises_process_error(1, "Could not connect to the server ::1:1", self.nodes[0].cli(f"-rpcconnect=[::1]:{node_rpc_port}", "-rpcport=1").echo)
182  
183          assert_equal(BLOCKS, self.nodes[0].cli("-rpcconnect=127.0.0.1:18999", f'-rpcport={node_rpc_port}').getblockcount())
184          if have_ipv6:
185              assert_equal(BLOCKS, self.nodes[0].cli("-rpcconnect=[::1]:18999", f'-rpcport={node_rpc_port}').getblockcount())
186  
187          # prefer rpcconnect port over default
188          assert_equal(BLOCKS, self.nodes[0].cli(f"-rpcconnect=127.0.0.1:{node_rpc_port}").getblockcount())
189          if have_ipv6:
190              assert_equal(BLOCKS, self.nodes[0].cli(f"-rpcconnect=[::1]:{node_rpc_port}").getblockcount())
191  
192          # prefer rpcport over default
193          assert_equal(BLOCKS, self.nodes[0].cli(f'-rpcport={node_rpc_port}').getblockcount())
194          # Re-enable rpcport in conf if present
195          self.nodes[0].replace_in_config([("#" + conf_rpcport, conf_rpcport)])
196  
197          self.log.info("Test connecting with non-existing RPC cookie file")
198          assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli('-rpccookiefile=does-not-exist', '-rpcpassword=').echo)
199  
200          self.log.info("Test connecting without RPC cookie file and with password arg")
201          assert_equal(BLOCKS, self.nodes[0].cli('-norpccookiefile', f'-rpcuser={user}', f'-rpcpassword={password}').getblockcount())
202  
203          self.log.info("Test -getinfo with arguments fails")
204          assert_raises_process_error(1, "-getinfo takes no arguments", self.nodes[0].cli('-getinfo').help)
205  
206          self.log.info("Test -getinfo with -color=never does not return ANSI escape codes")
207          assert "\u001b[0m" not in self.nodes[0].cli('-getinfo', '-color=never').send_cli()
208  
209          self.log.info("Test -getinfo with -color=always returns ANSI escape codes")
210          assert "\u001b[0m" in self.nodes[0].cli('-getinfo', '-color=always').send_cli()
211  
212          self.log.info("Test -getinfo with invalid value for -color option")
213          assert_raises_process_error(1, "Invalid value for -color option. Valid values: always, auto, never.", self.nodes[0].cli('-getinfo', '-color=foo').send_cli)
214  
215          self.log.info("Test -getinfo returns expected network and blockchain info")
216          if self.is_wallet_compiled():
217              self.import_deterministic_coinbase_privkeys()
218              self.nodes[0].encryptwallet(password)
219          cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
220          cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
221  
222          network_info = self.nodes[0].getnetworkinfo()
223          blockchain_info = self.nodes[0].getblockchaininfo()
224          assert_equal(int(cli_get_info['Version']), network_info['version'])
225          assert_equal(cli_get_info['Verification progress'], "%.4f%%" % (blockchain_info['verificationprogress'] * 100))
226          assert_equal(int(cli_get_info['Blocks']), blockchain_info['blocks'])
227          assert_equal(int(cli_get_info['Headers']), blockchain_info['headers'])
228          assert_equal(int(cli_get_info['Time offset (s)']), network_info['timeoffset'])
229          expected_network_info = f"in {network_info['connections_in']}, out {network_info['connections_out']}, total {network_info['connections']}"
230          assert_equal(cli_get_info["Network"], expected_network_info)
231          assert_equal(cli_get_info['Proxies'], network_info['networks'][0]['proxy'])
232          assert_equal(Decimal(cli_get_info['Difficulty']), blockchain_info['difficulty'])
233          assert_equal(cli_get_info['Chain'], blockchain_info['chain'])
234  
235          self.log.info("Test -getinfo and bitcoin-cli return all proxies")
236          self.restart_node(0, extra_args=["-proxy=127.0.0.1:9050", "-i2psam=127.0.0.1:7656"])
237          network_info = self.nodes[0].getnetworkinfo()
238          cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
239          cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
240          assert_equal(cli_get_info["Proxies"], "127.0.0.1:9050 (ipv4, ipv6, onion, cjdns), 127.0.0.1:7656 (i2p)")
241  
242          if self.is_wallet_compiled():
243              self.log.info("Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info")
244              # Explicitly set the output type in order to have consistent tx vsize / fees
245              # for both legacy and descriptor wallets (disables the change address type detection algorithm)
246              self.restart_node(0, extra_args=["-addresstype=bech32", "-changetype=bech32"])
247              assert_equal(Decimal(cli_get_info['Balance']), BALANCE)
248              assert 'Balances' not in cli_get_info_string
249              wallet_info = self.nodes[0].getwalletinfo()
250              assert_equal(int(cli_get_info['Keypool size']), wallet_info['keypoolsize'])
251              assert_equal(int(cli_get_info['Unlocked until']), wallet_info['unlocked_until'])
252              assert_equal(Decimal(cli_get_info['Min tx relay fee rate (BTC/kvB)']), network_info['relayfee'])
253              assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info)
254  
255              # Setup to test -getinfo, -generate, and -rpcwallet= with multiple wallets.
256              wallets = [self.default_wallet_name, 'Encrypted', 'secret']
257              amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)]
258              self.nodes[0].createwallet(wallet_name=wallets[1])
259              self.nodes[0].createwallet(wallet_name=wallets[2])
260              w1 = self.nodes[0].get_wallet_rpc(wallets[0])
261              w2 = self.nodes[0].get_wallet_rpc(wallets[1])
262              w3 = self.nodes[0].get_wallet_rpc(wallets[2])
263              rpcwallet2 = f'-rpcwallet={wallets[1]}'
264              rpcwallet3 = f'-rpcwallet={wallets[2]}'
265              w1.walletpassphrase(password, self.rpc_timeout)
266              w2.encryptwallet(password)
267              w1.sendtoaddress(w2.getnewaddress(), amounts[1])
268              w1.sendtoaddress(w3.getnewaddress(), amounts[2])
269  
270              # Mine a block to confirm; adds a block reward (50 BTC) to the default wallet.
271              self.generate(self.nodes[0], 1)
272  
273              self.log.info("Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance")
274              for i in range(len(wallets)):
275                  cli_get_info_string = self.nodes[0].cli('-getinfo', f'-rpcwallet={wallets[i]}').send_cli()
276                  cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
277                  assert 'Balances' not in cli_get_info_string
278                  assert_equal(cli_get_info["Wallet"], wallets[i])
279                  assert_equal(Decimal(cli_get_info['Balance']), amounts[i])
280  
281              self.log.info("Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balances")
282              cli_get_info_string = self.nodes[0].cli('-getinfo', '-rpcwallet=does-not-exist').send_cli()
283              assert 'Balance' not in cli_get_info_string
284              assert 'Balances' not in cli_get_info_string
285  
286              self.log.info("Test -getinfo with multiple wallets returns all loaded wallet names and balances")
287              assert_equal(set(self.nodes[0].listwallets()), set(wallets))
288              cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
289              cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
290              assert 'Balance' not in cli_get_info
291              for k, v in zip(wallets, amounts):
292                  assert_equal(Decimal(cli_get_info['Balances'][k]), v)
293  
294              # Unload the default wallet and re-verify.
295              self.nodes[0].unloadwallet(wallets[0])
296              assert wallets[0] not in self.nodes[0].listwallets()
297              cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
298              cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
299              assert 'Balance' not in cli_get_info
300              assert 'Balances' in cli_get_info_string
301              for k, v in zip(wallets[1:], amounts[1:]):
302                  assert_equal(Decimal(cli_get_info['Balances'][k]), v)
303              assert wallets[0] not in cli_get_info
304  
305              self.log.info("Test -getinfo after unloading all wallets except a non-default one returns its balance")
306              self.nodes[0].unloadwallet(wallets[2])
307              assert_equal(self.nodes[0].listwallets(), [wallets[1]])
308              cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
309              cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
310              assert 'Balances' not in cli_get_info_string
311              assert_equal(cli_get_info['Wallet'], wallets[1])
312              assert_equal(Decimal(cli_get_info['Balance']), amounts[1])
313  
314              self.log.info("Test -getinfo -norpcwallet returns the same as -getinfo")
315              # Previously there was a bug where -norpcwallet was treated like -rpcwallet=0
316              assert_equal(self.nodes[0].cli('-getinfo', "-norpcwallet").send_cli(), cli_get_info_string)
317  
318              self.log.info("Test -getinfo with -rpcwallet=remaining-non-default-wallet returns only its balance")
319              cli_get_info_string = self.nodes[0].cli('-getinfo', rpcwallet2).send_cli()
320              cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
321              assert 'Balances' not in cli_get_info_string
322              assert_equal(cli_get_info['Wallet'], wallets[1])
323              assert_equal(Decimal(cli_get_info['Balance']), amounts[1])
324  
325              self.log.info("Test -getinfo with -rpcwallet=unloaded wallet returns no balances")
326              cli_get_info_string = self.nodes[0].cli('-getinfo', rpcwallet3).send_cli()
327              cli_get_info_keys = cli_get_info_string_to_dict(cli_get_info_string)
328              assert 'Balance' not in cli_get_info_keys
329              assert 'Balances' not in cli_get_info_string
330  
331              # Test bitcoin-cli -generate.
332              n1 = 3
333              n2 = 4
334              w2.walletpassphrase(password, self.rpc_timeout)
335              blocks = self.nodes[0].getblockcount()
336  
337              self.log.info('Test -generate with no args')
338              generate = self.nodes[0].cli('-generate').send_cli()
339              assert_equal(set(generate.keys()), {'address', 'blocks'})
340              assert_equal(len(generate["blocks"]), 1)
341              assert_equal(self.nodes[0].getblockcount(), blocks + 1)
342  
343              self.log.info('Test -generate with bad args')
344              assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli('-generate', 'foo').echo)
345              assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli('-generate', 0).echo)
346              assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli('-generate', 1, 2, 3).echo)
347  
348              self.log.info('Test -generate with nblocks')
349              generate = self.nodes[0].cli('-generate', n1).send_cli()
350              assert_equal(set(generate.keys()), {'address', 'blocks'})
351              assert_equal(len(generate["blocks"]), n1)
352              assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1)
353  
354              self.log.info('Test -generate with nblocks and maxtries')
355              generate = self.nodes[0].cli('-generate', n2, 1000000).send_cli()
356              assert_equal(set(generate.keys()), {'address', 'blocks'})
357              assert_equal(len(generate["blocks"]), n2)
358              assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1 + n2)
359  
360              self.log.info('Test -generate -rpcwallet in single-wallet mode')
361              generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli()
362              assert_equal(set(generate.keys()), {'address', 'blocks'})
363              assert_equal(len(generate["blocks"]), 1)
364              assert_equal(self.nodes[0].getblockcount(), blocks + 2 + n1 + n2)
365  
366              self.log.info('Test -generate -rpcwallet=unloaded wallet raises RPC error')
367              assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate').echo)
368              assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 'foo').echo)
369              assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 0).echo)
370              assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 1, 2, 3).echo)
371  
372              # Test bitcoin-cli -generate with -rpcwallet in multiwallet mode.
373              self.nodes[0].loadwallet(wallets[2])
374              n3 = 4
375              n4 = 10
376              blocks = self.nodes[0].getblockcount()
377  
378              self.log.info('Test -generate -rpcwallet=<filename> raise RPC error')
379              wallet2_path = f'-rpcwallet={self.nodes[0].wallets_path / wallets[2] / self.wallet_data_filename}'
380              assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(wallet2_path, '-generate').echo)
381  
382              self.log.info('Test -generate -rpcwallet with no args')
383              generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli()
384              assert_equal(set(generate.keys()), {'address', 'blocks'})
385              assert_equal(len(generate["blocks"]), 1)
386              assert_equal(self.nodes[0].getblockcount(), blocks + 1)
387  
388              self.log.info('Test -generate -rpcwallet with bad args')
389              assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli(rpcwallet2, '-generate', 'foo').echo)
390              assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli(rpcwallet2, '-generate', 0).echo)
391              assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli(rpcwallet2, '-generate', 1, 2, 3).echo)
392  
393              self.log.info('Test -generate -rpcwallet with nblocks')
394              generate = self.nodes[0].cli(rpcwallet2, '-generate', n3).send_cli()
395              assert_equal(set(generate.keys()), {'address', 'blocks'})
396              assert_equal(len(generate["blocks"]), n3)
397              assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3)
398  
399              self.log.info('Test -generate -rpcwallet with nblocks and maxtries')
400              generate = self.nodes[0].cli(rpcwallet2, '-generate', n4, 1000000).send_cli()
401              assert_equal(set(generate.keys()), {'address', 'blocks'})
402              assert_equal(len(generate["blocks"]), n4)
403              assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3 + n4)
404  
405              self.log.info('Test -generate without -rpcwallet in multiwallet mode raises RPC error')
406              assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate').echo)
407              assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 'foo').echo)
408              assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 0).echo)
409              assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 1, 2, 3).echo)
410          else:
411              self.log.info("*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped")
412              self.generate(self.nodes[0], 25)  # maintain block parity with the wallet_compiled conditional branch
413  
414          self.test_netinfo()
415  
416          self.log.info("Test -version with node stopped")
417          self.stop_node(0)
418          cli_response = self.nodes[0].cli('-version').send_cli()
419          assert f"{self.config['environment']['CLIENT_NAME']} RPC client version" in cli_response
420  
421          self.log.info("Test -rpcwait option successfully waits for RPC connection")
422          self.nodes[0].start()  # start node without RPC connection
423          self.nodes[0].wait_for_cookie_credentials()  # ensure cookie file is available to avoid race condition
424          blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount')
425          self.nodes[0].wait_for_rpc_connection()
426          assert_equal(blocks, BLOCKS + 25)
427  
428          self.log.info("Test -rpcwait option waits at most -rpcwaittimeout seconds for startup")
429          self.stop_node(0)  # stop the node so we time out
430          start_time = time.time()
431          assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcwait', '-rpcwaittimeout=5').echo)
432          assert_greater_than_or_equal(time.time(), start_time + 5)
433  
434          self.log.info("Test that only one of -addrinfo, -generate, -getinfo, -netinfo may be specified at a time")
435          assert_raises_process_error(1, "Only one of -getinfo, -netinfo may be specified", self.nodes[0].cli('-getinfo', '-netinfo').send_cli)
436  
437  
438  if __name__ == '__main__':
439      TestBitcoinCli(__file__).main()