Skip to content

Commit f59cacd

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 9db8eec commit f59cacd

17 files changed

+118
-265
lines changed

qa/rpc-tests/bip65-cltv.py

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

75-
# Mine 1 old-version blocks
76-
try:
77-
self.nodes[1].generate(1)
78-
raise AssertionError("Succeeded to mine a version=3 block after 950 version=4 blocks")
79-
except JSONRPCException:
80-
pass
75+
# Mine 1 old-version blocks. This should fail
76+
assert_raises_jsonrpc(-1,"CreateNewBlock: TestBlockValidity failed: bad-version(0x00000003)", self.nodes[1].generate, 1)
8177
self.sync_all()
8278
if (self.nodes[0].getblockcount() != cnt + 1051):
8379
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
@@ -97,12 +97,7 @@ def test_disable_flag(self):
9797
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
9898
tx2.rehash()
9999

100-
try:
101-
self.nodes[0].sendrawtransaction(ToHex(tx2))
102-
except JSONRPCException as exp:
103-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
104-
else:
105-
assert(False)
100+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx2))
106101

107102
# Setting the version back down to 1 should disable the sequence lock,
108103
# so this should be accepted.
@@ -197,14 +192,12 @@ def test_sequence_lock_confirmed_inputs(self):
197192
tx.vout.append(CTxOut(int(value-self.relayfee*tx_size*COIN/1000), CScript([b'a'])))
198193
rawtx = self.nodes[0].signrawtransaction(ToHex(tx))["hex"]
199194

200-
try:
201-
self.nodes[0].sendrawtransaction(rawtx)
202-
except JSONRPCException as exp:
203-
assert(not should_pass and using_sequence_locks)
204-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
195+
if (using_sequence_locks and not should_pass):
196+
# This transaction should be rejected
197+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, rawtx)
205198
else:
206-
assert(should_pass or not using_sequence_locks)
207-
# Recalculate utxos if we successfully sent the transaction
199+
# This raw transaction should be accepted
200+
self.nodes[0].sendrawtransaction(rawtx)
208201
utxos = self.nodes[0].listunspent()
209202

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

249-
try:
250-
node.sendrawtransaction(ToHex(tx))
251-
except JSONRPCException as exp:
252-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
253-
assert(orig_tx.hash in node.getrawmempool())
242+
if (orig_tx.hash in node.getrawmempool()):
243+
# sendrawtransaction should fail if the tx is in the mempool
244+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx))
254245
else:
255-
# orig_tx must not be in mempool
256-
assert(orig_tx.hash not in node.getrawmempool())
246+
# sendrawtransaction should succeed if the tx is not in the mempool
247+
node.sendrawtransaction(ToHex(tx))
248+
257249
return tx
258250

259251
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True)
@@ -302,12 +294,7 @@ def test_nonzero_locks(orig_tx, node, relayfee, use_height_lock):
302294
tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN)
303295
raw_tx5 = self.nodes[0].signrawtransaction(ToHex(tx5))["hex"]
304296

305-
try:
306-
self.nodes[0].sendrawtransaction(raw_tx5)
307-
except JSONRPCException as exp:
308-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
309-
else:
310-
assert(False)
297+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, raw_tx5)
311298

312299
# Test mempool-BIP68 consistency after reorg
313300
#
@@ -380,12 +367,7 @@ def test_bip68_not_consensus(self):
380367
tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
381368
tx3.rehash()
382369

383-
try:
384-
self.nodes[0].sendrawtransaction(ToHex(tx3))
385-
except JSONRPCException as exp:
386-
assert_equal(exp.error["message"], NOT_FINAL_ERROR)
387-
else:
388-
assert(False)
370+
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx3))
389371

390372
# make a block that violates bip68; ensure that the tip updates
391373
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
@@ -71,12 +71,8 @@ def run_test(self):
7171
if (self.nodes[0].getblockcount() != cnt + 1051):
7272
raise AssertionError("Failed to mine a version=3 block")
7373

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

qa/rpc-tests/blockchain.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,13 @@
1111
from decimal import Decimal
1212

1313
from test_framework.test_framework import BitcoinTestFramework
14-
from test_framework.authproxy import JSONRPCException
1514
from test_framework.util import (
1615
assert_equal,
17-
assert_raises,
16+
assert_raises_jsonrpc,
1817
assert_is_hex_string,
1918
assert_is_hash_string,
2019
start_nodes,
21-
connect_nodes_bi,
20+
connect_nodes_bi
2221
)
2322

2423

@@ -62,8 +61,7 @@ def _test_gettxoutsetinfo(self):
6261
def _test_getblockheader(self):
6362
node = self.nodes[0]
6463

65-
assert_raises(
66-
JSONRPCException, lambda: node.getblockheader('nonsense'))
64+
assert_raises_jsonrpc(-5, "Block not found", node.getblockheader, "nonsense")
6765

6866
besthash = node.getbestblockhash()
6967
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
@@ -107,7 +107,7 @@ def run_test(self):
107107

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

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

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

134134
# Test 8: Bad bits

qa/rpc-tests/keypool.py

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

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

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

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

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

qa/rpc-tests/mempool_packages.py

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

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

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

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

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

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
@@ -46,7 +46,7 @@ def run_test(self):
4646
spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0])
4747

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

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

0 commit comments

Comments
 (0)