Skip to content

Commit c9bd0f6

Browse files
committed
Fix RPC failure testing (2 of 2)
Commit 9db8eec improved the assert_raises_jsonrpc() function for better testing of RPC failure modes. This commit completes the job by removing remaining broken try-except RPC testing from the individual test cases and replacing it with calls to assert_raises_jsonrpc().
1 parent ce01e62 commit c9bd0f6

16 files changed

+119
-265
lines changed

qa/rpc-tests/bip65-cltv.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,8 @@ def run_test(self):
6969
if (self.nodes[0].getblockcount() != cnt + 1051):
7070
raise AssertionError("Failed to mine a version=4 block")
7171

72-
# Mine 1 old-version blocks
73-
try:
74-
self.nodes[1].generate(1)
75-
raise AssertionError("Succeeded to mine a version=3 block after 950 version=4 blocks")
76-
except JSONRPCException:
77-
pass
72+
# Mine 1 old-version blocks. This should fail
73+
assert_raises_jsonrpc(-1,"CreateNewBlock: TestBlockValidity failed: bad-version(0x00000003)", self.nodes[1].generate, 1)
7874
self.sync_all()
7975
if (self.nodes[0].getblockcount() != cnt + 1051):
8076
raise AssertionError("Accepted a version=3 block after 950 version=4 blocks")

qa/rpc-tests/bip68-sequence.py

Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,7 @@ def test_disable_flag(self):
9090
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
9191
tx2.rehash()
9292

93-
try:
94-
self.nodes[0].sendrawtransaction(ToHex(tx2))
95-
except JSONRPCException as exp:
96-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
97-
else:
98-
assert(False)
93+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx2))
9994

10095
# Setting the version back down to 1 should disable the sequence lock,
10196
# so this should be accepted.
@@ -190,14 +185,12 @@ def test_sequence_lock_confirmed_inputs(self):
190185
tx.vout.append(CTxOut(int(value-self.relayfee*tx_size*COIN/1000), CScript([b'a'])))
191186
rawtx = self.nodes[0].signrawtransaction(ToHex(tx))["hex"]
192187

193-
try:
194-
self.nodes[0].sendrawtransaction(rawtx)
195-
except JSONRPCException as exp:
196-
assert(not should_pass and using_sequence_locks)
197-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
188+
if (using_sequence_locks and not should_pass):
189+
# This transaction should be rejected
190+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, rawtx)
198191
else:
199-
assert(should_pass or not using_sequence_locks)
200-
# Recalculate utxos if we successfully sent the transaction
192+
# This raw transaction should be accepted
193+
self.nodes[0].sendrawtransaction(rawtx)
201194
utxos = self.nodes[0].listunspent()
202195

203196
# Test that sequence locks on unconfirmed inputs must have nSequence
@@ -239,14 +232,13 @@ def test_nonzero_locks(orig_tx, node, relayfee, use_height_lock):
239232
tx.vout = [CTxOut(int(orig_tx.vout[0].nValue - relayfee*COIN), CScript([b'a']))]
240233
tx.rehash()
241234

242-
try:
243-
node.sendrawtransaction(ToHex(tx))
244-
except JSONRPCException as exp:
245-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
246-
assert(orig_tx.hash in node.getrawmempool())
235+
if (orig_tx.hash in node.getrawmempool()):
236+
# sendrawtransaction should fail if the tx is in the mempool
237+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx))
247238
else:
248-
# orig_tx must not be in mempool
249-
assert(orig_tx.hash not in node.getrawmempool())
239+
# sendrawtransaction should succeed if the tx is not in the mempool
240+
node.sendrawtransaction(ToHex(tx))
241+
250242
return tx
251243

252244
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True)
@@ -295,12 +287,7 @@ def test_nonzero_locks(orig_tx, node, relayfee, use_height_lock):
295287
tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN)
296288
raw_tx5 = self.nodes[0].signrawtransaction(ToHex(tx5))["hex"]
297289

298-
try:
299-
self.nodes[0].sendrawtransaction(raw_tx5)
300-
except JSONRPCException as exp:
301-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
302-
else:
303-
assert(False)
290+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, raw_tx5)
304291

305292
# Test mempool-BIP68 consistency after reorg
306293
#
@@ -373,12 +360,7 @@ def test_bip68_not_consensus(self):
373360
tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
374361
tx3.rehash()
375362

376-
try:
377-
self.nodes[0].sendrawtransaction(ToHex(tx3))
378-
except JSONRPCException as exp:
379-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
380-
else:
381-
assert(False)
363+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx3))
382364

383365
# make a block that violates bip68; ensure that the tip updates
384366
tip = int(self.nodes[0].getbestblockhash(), 16)

qa/rpc-tests/bipdersig.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,8 @@ def run_test(self):
6868
if (self.nodes[0].getblockcount() != cnt + 1051):
6969
raise AssertionError("Failed to mine a version=3 block")
7070

71-
# Mine 1 old-version blocks
72-
try:
73-
self.nodes[1].generate(1)
74-
raise AssertionError("Succeeded to mine a version=2 block after 950 version=3 blocks")
75-
except JSONRPCException:
76-
pass
71+
# Mine 1 old-version blocks. This should fail
72+
assert_raises_jsonrpc(-1, "CreateNewBlock: TestBlockValidity failed: bad-version(0x00000002)", self.nodes[1].generate, 1)
7773
self.sync_all()
7874
if (self.nodes[0].getblockcount() != cnt + 1051):
7975
raise AssertionError("Accepted a version=2 block after 950 version=3 blocks")

qa/rpc-tests/blockchain.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,9 @@
1414
from decimal import Decimal
1515

1616
from test_framework.test_framework import BitcoinTestFramework
17-
from test_framework.authproxy import JSONRPCException
1817
from test_framework.util import (
1918
assert_equal,
20-
assert_raises,
19+
assert_raises_jsonrpc,
2120
assert_is_hex_string,
2221
assert_is_hash_string,
2322
start_nodes,
@@ -58,8 +57,7 @@ def _test_gettxoutsetinfo(self):
5857
def _test_getblockheader(self):
5958
node = self.nodes[0]
6059

61-
assert_raises(
62-
JSONRPCException, lambda: node.getblockheader('nonsense'))
60+
assert_raises_jsonrpc(-5, "Block not found", node.getblockheader, "nonsense")
6361

6462
besthash = node.getbestblockhash()
6563
secondbesthash = node.getblockhash(199)

qa/rpc-tests/disablewallet.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,10 @@ def run_test (self):
3030
x = self.nodes[0].validateaddress('mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
3131
assert(x['isvalid'] == True)
3232

33-
# Checking mining to an address without a wallet
34-
try:
35-
self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
36-
except JSONRPCException as e:
37-
assert("Invalid address" not in e.error['message'])
38-
assert("ProcessNewBlock, block not accepted" not in e.error['message'])
39-
assert("Couldn't create new block" not in e.error['message'])
40-
41-
try:
42-
self.nodes[0].generatetoaddress(1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
43-
raise AssertionError("Must not mine to invalid address!")
44-
except JSONRPCException as e:
45-
assert("Invalid address" in e.error['message'])
33+
# Checking mining to an address without a wallet. Generating to a valid address should succeed
34+
# but generating to an invalid address will fail.
35+
self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
36+
assert_raises_jsonrpc(-5, "Invalid address", self.nodes[0].generatetoaddress, 1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
4637

4738
if __name__ == '__main__':
4839
DisableWalletTest ().main ()

qa/rpc-tests/getblocktemplate_proposals.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def run_test(self):
105105

106106
# Test 3: Truncated final tx
107107
lastbyte = txlist[-1].pop()
108-
assert_raises(JSONRPCException, assert_template, node, tmpl, txlist, 'n/a')
108+
assert_raises_jsonrpc(-22, "Block decode failed", assert_template, node, tmpl, txlist, 'n/a')
109109
txlist[-1].append(lastbyte)
110110

111111
# Test 4: Add an invalid tx to the end (duplicate of gen tx)
@@ -126,7 +126,7 @@ def run_test(self):
126126

127127
# Test 7: Bad tx count
128128
txlist.append(b'')
129-
assert_raises(JSONRPCException, assert_template, node, tmpl, txlist, 'n/a')
129+
assert_raises_jsonrpc(-22, 'Block decode failed', assert_template, node, tmpl, txlist, 'n/a')
130130
txlist.pop()
131131

132132
# Test 8: Bad bits

qa/rpc-tests/keypool.py

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,7 @@ def run_test(self):
2828
assert(addr_before_encrypting_data['hdmasterkeyid'] != wallet_info['hdmasterkeyid'])
2929
assert(addr_data['hdmasterkeyid'] == wallet_info['hdmasterkeyid'])
3030

31-
try:
32-
addr = nodes[0].getnewaddress()
33-
raise AssertionError('Keypool should be exhausted after one address')
34-
except JSONRPCException as e:
35-
assert(e.error['code']==-12)
31+
assert_raises_jsonrpc(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
3632

3733
# put three new keys in the keypool
3834
nodes[0].walletpassphrase('test', 12000)
@@ -48,11 +44,7 @@ def run_test(self):
4844
# assert that four unique addresses were returned
4945
assert(len(addr) == 4)
5046
# the next one should fail
51-
try:
52-
addr = nodes[0].getrawchangeaddress()
53-
raise AssertionError('Keypool should be exhausted after three addresses')
54-
except JSONRPCException as e:
55-
assert(e.error['code']==-12)
47+
assert_raises_jsonrpc(-12, "Keypool ran out", nodes[0].getrawchangeaddress)
5648

5749
# refill keypool with three new addresses
5850
nodes[0].walletpassphrase('test', 1)
@@ -66,11 +58,7 @@ def run_test(self):
6658
nodes[0].generate(1)
6759
nodes[0].generate(1)
6860
nodes[0].generate(1)
69-
try:
70-
nodes[0].generate(1)
71-
raise AssertionError('Keypool should be exhausted after three addesses')
72-
except JSONRPCException as e:
73-
assert(e.error['code']==-12)
61+
assert_raises_jsonrpc(-12, "Keypool ran out", nodes[0].generate, 1)
7462

7563
def __init__(self):
7664
super().__init__()

qa/rpc-tests/mempool_packages.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,7 @@ def run_test(self):
112112
assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN + 1000)
113113

114114
# Adding one more transaction on to the chain should fail.
115-
try:
116-
self.chain_transaction(self.nodes[0], txid, vout, value, fee, 1)
117-
except JSONRPCException as e:
118-
self.log.info("too-long-ancestor-chain successfully rejected")
115+
assert_raises_jsonrpc(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], txid, vout, value, fee, 1)
119116

120117
# Check that prioritising a tx before it's added to the mempool works
121118
# First clear the mempool by mining a block.
@@ -155,19 +152,19 @@ def run_test(self):
155152
for i in range(10):
156153
transaction_package.append({'txid': txid, 'vout': i, 'amount': sent_value})
157154

158-
for i in range(MAX_DESCENDANTS):
155+
# Sign and send up to MAX_DESCENDANT transactions chained off the parent tx
156+
for i in range(MAX_DESCENDANTS - 1):
159157
utxo = transaction_package.pop(0)
160-
try:
161-
(txid, sent_value) = self.chain_transaction(self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
162-
for j in range(10):
163-
transaction_package.append({'txid': txid, 'vout': j, 'amount': sent_value})
164-
if i == MAX_DESCENDANTS - 2:
165-
mempool = self.nodes[0].getrawmempool(True)
166-
assert_equal(mempool[parent_transaction]['descendantcount'], MAX_DESCENDANTS)
167-
except JSONRPCException as e:
168-
self.log.info(e.error['message'])
169-
assert_equal(i, MAX_DESCENDANTS - 1)
170-
self.log.info("tx that would create too large descendant package successfully rejected")
158+
(txid, sent_value) = self.chain_transaction(self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
159+
for j in range(10):
160+
transaction_package.append({'txid': txid, 'vout': j, 'amount': sent_value})
161+
162+
mempool = self.nodes[0].getrawmempool(True)
163+
assert_equal(mempool[parent_transaction]['descendantcount'], MAX_DESCENDANTS)
164+
165+
# Sending one more chained transaction will fail
166+
utxo = transaction_package.pop(0)
167+
assert_raises_jsonrpc(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
171168

172169
# TODO: check that node1's mempool is as expected
173170

qa/rpc-tests/mempool_reorg.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,10 @@ def setup_network(self):
3030
self.sync_all()
3131

3232
def run_test(self):
33-
start_count = self.nodes[0].getblockcount()
33+
# Start with a 200 block chain
34+
assert_equal(self.nodes[0].getblockcount(), 200)
3435

35-
# Mine three blocks. After this, nodes[0] blocks
36+
# Mine four blocks. After this, nodes[0] blocks
3637
# 101, 102, and 103 are spend-able.
3738
new_blocks = self.nodes[1].generate(4)
3839
self.sync_all()
@@ -52,19 +53,21 @@ def run_test(self):
5253
spend_102_raw = create_tx(self.nodes[0], coinbase_txids[2], node0_address, 49.99)
5354
spend_103_raw = create_tx(self.nodes[0], coinbase_txids[3], node0_address, 49.99)
5455

55-
# Create a block-height-locked transaction which will be invalid after reorg
56+
# Create a transaction which is time-locked to two blocks in the future
5657
timelock_tx = self.nodes[0].createrawtransaction([{"txid": coinbase_txids[0], "vout": 0}], {node0_address: 49.99})
5758
# Set the time lock
5859
timelock_tx = timelock_tx.replace("ffffffff", "11111191", 1)
5960
timelock_tx = timelock_tx[:-8] + hex(self.nodes[0].getblockcount() + 2)[2:] + "000000"
6061
timelock_tx = self.nodes[0].signrawtransaction(timelock_tx)["hex"]
61-
assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, timelock_tx)
62+
# This will raise an exception because the timelock transaction is too immature to spend
63+
assert_raises_jsonrpc(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx)
6264

6365
# Broadcast and mine spend_102 and 103:
6466
spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw)
6567
spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw)
6668
self.nodes[0].generate(1)
67-
assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, timelock_tx)
69+
# Time-locked transaction is still too immature to spend
70+
assert_raises_jsonrpc(-26,'non-final', self.nodes[0].sendrawtransaction, timelock_tx)
6871

6972
# Create 102_1 and 103_1:
7073
spend_102_1_raw = create_tx(self.nodes[0], spend_102_id, node1_address, 49.98)
@@ -73,6 +76,7 @@ def run_test(self):
7376
# Broadcast and mine 103_1:
7477
spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw)
7578
last_block = self.nodes[0].generate(1)
79+
# Time-locked transaction can now be spent
7680
timelock_tx_id = self.nodes[0].sendrawtransaction(timelock_tx)
7781

7882
# ... now put spend_101 and spend_102_1 in memory pools:
@@ -85,6 +89,8 @@ def run_test(self):
8589

8690
for node in self.nodes:
8791
node.invalidateblock(last_block[0])
92+
# Time-locked transaction is now too immature and has been removed from the mempool
93+
# spend_103_1 has been re-orged out of the chain and is back in the mempool
8894
assert_equal(set(self.nodes[0].getrawmempool()), {spend_101_id, spend_102_1_id, spend_103_1_id})
8995

9096
# Use invalidateblock to re-org back and make all those coinbase spends

qa/rpc-tests/mempool_spendcoinbase.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def run_test(self):
4545
spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0])
4646

4747
# coinbase at height 102 should be too immature to spend
48-
assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, spends_raw[1])
48+
assert_raises_jsonrpc(-26,"bad-txns-premature-spend-of-coinbase", self.nodes[0].sendrawtransaction, spends_raw[1])
4949

5050
# mempool should have just spend_101:
5151
assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ])

0 commit comments

Comments
 (0)