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