Browse Source

Merge #10853: [tests] Fix RPC failure testing (again)

47ba8cf71 scripted-diff: rename assert_raises_jsonrpc to assert_raises_rpc error (John Newbery)
677d893ff [tests] do not allow assert_raises_message to be called with JSONRPCException (John Newbery)
5864e9c16 [tests] remove direct testing on JSONRPCException from individual test cases (John Newbery)

Pull request description:

  I did this a few months ago (here: #9707), but a few new examples have crept back in.

  When testing RPC failures, the test case should always assert the error value and message, to ensure that the failure was for the correct reason. Not doing that can hide bugs in the test code and mean that the test is not testing the correct behaviour.

  RPC failure testing should use the utility function `assert_raises_jsonrpc()` (renamed in the final commit of this PR to `assert_raises_rpc_error()`.

  This PR does the following:
  - changes all remaining instances of tests directly testing on `JSONRPCException` to calls to `assert_raises_jsonrpc()`
  - prevents `assert_raises_message()` from being called with `JSONRPCException`
  - scripted-diff changes `assert_raises_jsonrpc()` to `assert_raises_rpc_error()`

Tree-SHA512: 2cc5e320704ec623a6e5a27d3c2c81cea86b502e29896f03bb5bf92cc36725132c1144410aecdf49e90d4577d512ee467d50d8184e9d5c5d0870bfc931316a5a
0.16
MarcoFalke 7 years ago
parent
commit
c63364610f
No known key found for this signature in database
GPG Key ID: D2EA4850E7528B25
  1. 10
      test/functional/bip68-sequence.py
  2. 6
      test/functional/blockchain.py
  3. 14
      test/functional/bumpfee.py
  4. 4
      test/functional/deprecated_rpc.py
  5. 4
      test/functional/disablewallet.py
  6. 12
      test/functional/disconnect_ban.py
  7. 12
      test/functional/fundrawtransaction.py
  8. 30
      test/functional/import-rescan.py
  9. 4
      test/functional/importmulti.py
  10. 4
      test/functional/importprunedfunds.py
  11. 8
      test/functional/keypool.py
  12. 4
      test/functional/mempool_packages.py
  13. 2
      test/functional/mempool_persist.py
  14. 4
      test/functional/mempool_reorg.py
  15. 2
      test/functional/mempool_spendcoinbase.py
  16. 8
      test/functional/merkle_blocks.py
  17. 10
      test/functional/mining.py
  18. 6
      test/functional/multiwallet.py
  19. 4
      test/functional/net.py
  20. 6
      test/functional/nulldummy.py
  21. 2
      test/functional/p2p-acceptblock.py
  22. 2
      test/functional/prioritise_transaction.py
  23. 8
      test/functional/pruning.py
  24. 12
      test/functional/rawtransactions.py
  25. 30
      test/functional/replace-by-fee.py
  26. 4
      test/functional/resendwallettransactions.py
  27. 2
      test/functional/rpcbind_test.py
  28. 4
      test/functional/rpcnamedargs.py
  29. 14
      test/functional/segwit.py
  30. 2
      test/functional/signrawtransactions.py
  31. 14
      test/functional/test_framework/util.py
  32. 4
      test/functional/wallet-dump.py
  33. 12
      test/functional/wallet-encryption.py
  34. 8
      test/functional/wallet.py
  35. 4
      test/functional/zapwallettxes.py

10
test/functional/bip68-sequence.py

@ -83,7 +83,7 @@ class BIP68Test(BitcoinTestFramework):
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))] tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
tx2.rehash() tx2.rehash()
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx2)) assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx2))
# Setting the version back down to 1 should disable the sequence lock, # Setting the version back down to 1 should disable the sequence lock,
# so this should be accepted. # so this should be accepted.
@ -180,7 +180,7 @@ class BIP68Test(BitcoinTestFramework):
if (using_sequence_locks and not should_pass): if (using_sequence_locks and not should_pass):
# This transaction should be rejected # This transaction should be rejected
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, rawtx) assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, rawtx)
else: else:
# This raw transaction should be accepted # This raw transaction should be accepted
self.nodes[0].sendrawtransaction(rawtx) self.nodes[0].sendrawtransaction(rawtx)
@ -227,7 +227,7 @@ class BIP68Test(BitcoinTestFramework):
if (orig_tx.hash in node.getrawmempool()): if (orig_tx.hash in node.getrawmempool()):
# sendrawtransaction should fail if the tx is in the mempool # sendrawtransaction should fail if the tx is in the mempool
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx)) assert_raises_rpc_error(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx))
else: else:
# sendrawtransaction should succeed if the tx is not in the mempool # sendrawtransaction should succeed if the tx is not in the mempool
node.sendrawtransaction(ToHex(tx)) node.sendrawtransaction(ToHex(tx))
@ -280,7 +280,7 @@ class BIP68Test(BitcoinTestFramework):
tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN) tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN)
raw_tx5 = self.nodes[0].signrawtransaction(ToHex(tx5))["hex"] raw_tx5 = self.nodes[0].signrawtransaction(ToHex(tx5))["hex"]
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, raw_tx5) assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, raw_tx5)
# Test mempool-BIP68 consistency after reorg # Test mempool-BIP68 consistency after reorg
# #
@ -353,7 +353,7 @@ class BIP68Test(BitcoinTestFramework):
tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))] tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
tx3.rehash() tx3.rehash()
assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx3)) assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx3))
# make a block that violates bip68; ensure that the tip updates # make a block that violates bip68; ensure that the tip updates
tip = int(self.nodes[0].getbestblockhash(), 16) tip = int(self.nodes[0].getbestblockhash(), 16)

6
test/functional/blockchain.py

@ -27,7 +27,7 @@ from test_framework.util import (
assert_greater_than, assert_greater_than,
assert_greater_than_or_equal, assert_greater_than_or_equal,
assert_raises, assert_raises,
assert_raises_jsonrpc, assert_raises_rpc_error,
assert_is_hex_string, assert_is_hex_string,
assert_is_hash_string, assert_is_hash_string,
) )
@ -125,7 +125,7 @@ class BlockchainTest(BitcoinTestFramework):
assert('window_interval' not in chaintxstats) assert('window_interval' not in chaintxstats)
assert('txrate' not in chaintxstats) assert('txrate' not in chaintxstats)
assert_raises_jsonrpc(-8, "Invalid block count: should be between 0 and the block's height - 1", self.nodes[0].getchaintxstats, 201) assert_raises_rpc_error(-8, "Invalid block count: should be between 0 and the block's height - 1", self.nodes[0].getchaintxstats, 201)
def _test_gettxoutsetinfo(self): def _test_gettxoutsetinfo(self):
node = self.nodes[0] node = self.nodes[0]
@ -171,7 +171,7 @@ class BlockchainTest(BitcoinTestFramework):
def _test_getblockheader(self): def _test_getblockheader(self):
node = self.nodes[0] node = self.nodes[0]
assert_raises_jsonrpc(-5, "Block not found", assert_raises_rpc_error(-5, "Block not found",
node.getblockheader, "nonsense") node.getblockheader, "nonsense")
besthash = node.getbestblockhash() besthash = node.getbestblockhash()

14
test/functional/bumpfee.py

@ -133,7 +133,7 @@ def test_segwit_bumpfee_succeeds(rbf_node, dest_address):
def test_nonrbf_bumpfee_fails(peer_node, dest_address): def test_nonrbf_bumpfee_fails(peer_node, dest_address):
# cannot replace a non RBF transaction (from node which did not enable RBF) # cannot replace a non RBF transaction (from node which did not enable RBF)
not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.00090000")) not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.00090000"))
assert_raises_jsonrpc(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid) assert_raises_rpc_error(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address): def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
@ -153,7 +153,7 @@ def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
signedtx = rbf_node.signrawtransaction(rawtx) signedtx = rbf_node.signrawtransaction(rawtx)
signedtx = peer_node.signrawtransaction(signedtx["hex"]) signedtx = peer_node.signrawtransaction(signedtx["hex"])
rbfid = rbf_node.sendrawtransaction(signedtx["hex"]) rbfid = rbf_node.sendrawtransaction(signedtx["hex"])
assert_raises_jsonrpc(-4, "Transaction contains inputs that don't belong to this wallet", assert_raises_rpc_error(-4, "Transaction contains inputs that don't belong to this wallet",
rbf_node.bumpfee, rbfid) rbf_node.bumpfee, rbfid)
@ -164,7 +164,7 @@ def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address)
tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.00020000}) tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.00020000})
tx = rbf_node.signrawtransaction(tx) tx = rbf_node.signrawtransaction(tx)
rbf_node.sendrawtransaction(tx["hex"]) rbf_node.sendrawtransaction(tx["hex"])
assert_raises_jsonrpc(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id) assert_raises_rpc_error(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id)
def test_small_output_fails(rbf_node, dest_address): def test_small_output_fails(rbf_node, dest_address):
@ -173,7 +173,7 @@ def test_small_output_fails(rbf_node, dest_address):
rbf_node.bumpfee(rbfid, {"totalFee": 50000}) rbf_node.bumpfee(rbfid, {"totalFee": 50000})
rbfid = spend_one_input(rbf_node, dest_address) rbfid = spend_one_input(rbf_node, dest_address)
assert_raises_jsonrpc(-4, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 50001}) assert_raises_rpc_error(-4, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 50001})
def test_dust_to_fee(rbf_node, dest_address): def test_dust_to_fee(rbf_node, dest_address):
@ -205,7 +205,7 @@ def test_rebumping(rbf_node, dest_address):
# check that re-bumping the original tx fails, but bumping the bumper succeeds # check that re-bumping the original tx fails, but bumping the bumper succeeds
rbfid = spend_one_input(rbf_node, dest_address) rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 2000}) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 2000})
assert_raises_jsonrpc(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFee": 3000}) assert_raises_rpc_error(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFee": 3000})
rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000}) rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000})
@ -213,7 +213,7 @@ def test_rebumping_not_replaceable(rbf_node, dest_address):
# check that re-bumping a non-replaceable bump tx fails # check that re-bumping a non-replaceable bump tx fails
rbfid = spend_one_input(rbf_node, dest_address) rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False}) bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False})
assert_raises_jsonrpc(-4, "Transaction is not BIP 125 replaceable", rbf_node.bumpfee, bumped["txid"], assert_raises_rpc_error(-4, "Transaction is not BIP 125 replaceable", rbf_node.bumpfee, bumped["txid"],
{"totalFee": 20000}) {"totalFee": 20000})
@ -264,7 +264,7 @@ def test_bumpfee_metadata(rbf_node, dest_address):
def test_locked_wallet_fails(rbf_node, dest_address): def test_locked_wallet_fails(rbf_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address) rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.walletlock() rbf_node.walletlock()
assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first.", assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
rbf_node.bumpfee, rbfid) rbf_node.bumpfee, rbfid)

4
test/functional/deprecated_rpc.py

@ -4,7 +4,7 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls.""" """Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_raises_jsonrpc from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework): class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self): def set_test_params(self):
@ -14,7 +14,7 @@ class DeprecatedRpcTest(BitcoinTestFramework):
def run_test(self): def run_test(self):
self.log.info("estimatefee: Shows deprecated message") self.log.info("estimatefee: Shows deprecated message")
assert_raises_jsonrpc(-32, 'estimatefee is deprecated', self.nodes[0].estimatefee, 1) assert_raises_rpc_error(-32, 'estimatefee is deprecated', self.nodes[0].estimatefee, 1)
self.log.info("Using -deprecatedrpc=estimatefee bypasses the error") self.log.info("Using -deprecatedrpc=estimatefee bypasses the error")
self.nodes[1].estimatefee(1) self.nodes[1].estimatefee(1)

4
test/functional/disablewallet.py

@ -19,7 +19,7 @@ class DisableWalletTest (BitcoinTestFramework):
def run_test (self): def run_test (self):
# Make sure wallet is really disabled # Make sure wallet is really disabled
assert_raises_jsonrpc(-32601, 'Method not found', self.nodes[0].getwalletinfo) assert_raises_rpc_error(-32601, 'Method not found', self.nodes[0].getwalletinfo)
x = self.nodes[0].validateaddress('3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy') x = self.nodes[0].validateaddress('3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
assert(x['isvalid'] == False) assert(x['isvalid'] == False)
x = self.nodes[0].validateaddress('mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ') x = self.nodes[0].validateaddress('mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
@ -28,7 +28,7 @@ class DisableWalletTest (BitcoinTestFramework):
# Checking mining to an address without a wallet. Generating to a valid address should succeed # Checking mining to an address without a wallet. Generating to a valid address should succeed
# but generating to an invalid address will fail. # but generating to an invalid address will fail.
self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ') self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
assert_raises_jsonrpc(-5, "Invalid address", self.nodes[0].generatetoaddress, 1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy') assert_raises_rpc_error(-5, "Invalid address", self.nodes[0].generatetoaddress, 1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
if __name__ == '__main__': if __name__ == '__main__':
DisableWalletTest ().main () DisableWalletTest ().main ()

12
test/functional/disconnect_ban.py

@ -8,7 +8,7 @@ import time
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_jsonrpc, assert_raises_rpc_error,
connect_nodes_bi, connect_nodes_bi,
wait_until, wait_until,
) )
@ -34,14 +34,14 @@ class DisconnectBanTest(BitcoinTestFramework):
self.log.info("setban: fail to ban an already banned subnet") self.log.info("setban: fail to ban an already banned subnet")
assert_equal(len(self.nodes[1].listbanned()), 1) assert_equal(len(self.nodes[1].listbanned()), 1)
assert_raises_jsonrpc(-23, "IP/Subnet already banned", self.nodes[1].setban, "127.0.0.1", "add") assert_raises_rpc_error(-23, "IP/Subnet already banned", self.nodes[1].setban, "127.0.0.1", "add")
self.log.info("setban: fail to ban an invalid subnet") self.log.info("setban: fail to ban an invalid subnet")
assert_raises_jsonrpc(-30, "Error: Invalid IP/Subnet", self.nodes[1].setban, "127.0.0.1/42", "add") assert_raises_rpc_error(-30, "Error: Invalid IP/Subnet", self.nodes[1].setban, "127.0.0.1/42", "add")
assert_equal(len(self.nodes[1].listbanned()), 1) # still only one banned ip because 127.0.0.1 is within the range of 127.0.0.0/24 assert_equal(len(self.nodes[1].listbanned()), 1) # still only one banned ip because 127.0.0.1 is within the range of 127.0.0.0/24
self.log.info("setban remove: fail to unban a non-banned subnet") self.log.info("setban remove: fail to unban a non-banned subnet")
assert_raises_jsonrpc(-30, "Error: Unban failed", self.nodes[1].setban, "127.0.0.1", "remove") assert_raises_rpc_error(-30, "Error: Unban failed", self.nodes[1].setban, "127.0.0.1", "remove")
assert_equal(len(self.nodes[1].listbanned()), 1) assert_equal(len(self.nodes[1].listbanned()), 1)
self.log.info("setban remove: successfully unban subnet") self.log.info("setban remove: successfully unban subnet")
@ -81,10 +81,10 @@ class DisconnectBanTest(BitcoinTestFramework):
self.log.info("disconnectnode: fail to disconnect when calling with address and nodeid") self.log.info("disconnectnode: fail to disconnect when calling with address and nodeid")
address1 = self.nodes[0].getpeerinfo()[0]['addr'] address1 = self.nodes[0].getpeerinfo()[0]['addr']
node1 = self.nodes[0].getpeerinfo()[0]['addr'] node1 = self.nodes[0].getpeerinfo()[0]['addr']
assert_raises_jsonrpc(-32602, "Only one of address and nodeid should be provided.", self.nodes[0].disconnectnode, address=address1, nodeid=node1) assert_raises_rpc_error(-32602, "Only one of address and nodeid should be provided.", self.nodes[0].disconnectnode, address=address1, nodeid=node1)
self.log.info("disconnectnode: fail to disconnect when calling with junk address") self.log.info("disconnectnode: fail to disconnect when calling with junk address")
assert_raises_jsonrpc(-29, "Node not found in connected nodes", self.nodes[0].disconnectnode, address="221B Baker Street") assert_raises_rpc_error(-29, "Node not found in connected nodes", self.nodes[0].disconnectnode, address="221B Baker Street")
self.log.info("disconnectnode: successfully disconnect node by address") self.log.info("disconnectnode: successfully disconnect node by address")
address1 = self.nodes[0].getpeerinfo()[0]['addr'] address1 = self.nodes[0].getpeerinfo()[0]['addr']

12
test/functional/fundrawtransaction.py

@ -179,7 +179,7 @@ class RawTransactionsTest(BitcoinTestFramework):
dec_tx = self.nodes[2].decoderawtransaction(rawtx) dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_raises_jsonrpc(-3, "Unexpected key foo", self.nodes[2].fundrawtransaction, rawtx, {'foo':'bar'}) assert_raises_rpc_error(-3, "Unexpected key foo", self.nodes[2].fundrawtransaction, rawtx, {'foo':'bar'})
############################################################ ############################################################
# test a fundrawtransaction with an invalid change address # # test a fundrawtransaction with an invalid change address #
@ -192,7 +192,7 @@ class RawTransactionsTest(BitcoinTestFramework):
dec_tx = self.nodes[2].decoderawtransaction(rawtx) dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_raises_jsonrpc(-5, "changeAddress must be a valid bitcoin address", self.nodes[2].fundrawtransaction, rawtx, {'changeAddress':'foobar'}) assert_raises_rpc_error(-5, "changeAddress must be a valid bitcoin address", self.nodes[2].fundrawtransaction, rawtx, {'changeAddress':'foobar'})
############################################################ ############################################################
# test a fundrawtransaction with a provided change address # # test a fundrawtransaction with a provided change address #
@ -206,7 +206,7 @@ class RawTransactionsTest(BitcoinTestFramework):
assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
change = self.nodes[2].getnewaddress() change = self.nodes[2].getnewaddress()
assert_raises_jsonrpc(-8, "changePosition out of bounds", self.nodes[2].fundrawtransaction, rawtx, {'changeAddress':change, 'changePosition':2}) assert_raises_rpc_error(-8, "changePosition out of bounds", self.nodes[2].fundrawtransaction, rawtx, {'changeAddress':change, 'changePosition':2})
rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 0}) rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 0})
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
out = dec_tx['vout'][0] out = dec_tx['vout'][0]
@ -314,7 +314,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtx = self.nodes[2].createrawtransaction(inputs, outputs) rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx) dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_raises_jsonrpc(-4, "Insufficient funds", self.nodes[2].fundrawtransaction, rawtx) assert_raises_rpc_error(-4, "Insufficient funds", self.nodes[2].fundrawtransaction, rawtx)
############################################################ ############################################################
#compare fee of a standard pubkeyhash transaction #compare fee of a standard pubkeyhash transaction
@ -469,14 +469,14 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtx = self.nodes[1].createrawtransaction(inputs, outputs) rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
# fund a transaction that requires a new key for the change output # fund a transaction that requires a new key for the change output
# creating the key must be impossible because the wallet is locked # creating the key must be impossible because the wallet is locked
assert_raises_jsonrpc(-4, "Keypool ran out, please call keypoolrefill first", self.nodes[1].fundrawtransaction, rawtx) assert_raises_rpc_error(-4, "Keypool ran out, please call keypoolrefill first", self.nodes[1].fundrawtransaction, rawtx)
#refill the keypool #refill the keypool
self.nodes[1].walletpassphrase("test", 100) self.nodes[1].walletpassphrase("test", 100)
self.nodes[1].keypoolrefill(8) #need to refill the keypool to get an internal change address self.nodes[1].keypoolrefill(8) #need to refill the keypool to get an internal change address
self.nodes[1].walletlock() self.nodes[1].walletlock()
assert_raises_jsonrpc(-13, "walletpassphrase", self.nodes[1].sendtoaddress, self.nodes[0].getnewaddress(), 1.2) assert_raises_rpc_error(-13, "walletpassphrase", self.nodes[1].sendtoaddress, self.nodes[0].getnewaddress(), 1.2)
oldBalance = self.nodes[0].getbalance() oldBalance = self.nodes[0].getbalance()

30
test/functional/import-rescan.py

@ -19,9 +19,8 @@ importing nodes pick up the new transactions regardless of whether rescans
happened previously. happened previously.
""" """
from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (connect_nodes, sync_blocks, assert_equal, set_node_times) from test_framework.util import (assert_raises_rpc_error, connect_nodes, sync_blocks, assert_equal, set_node_times)
import collections import collections
import enum import enum
@ -35,21 +34,26 @@ Rescan = enum.Enum("Rescan", "no yes late_timestamp")
class Variant(collections.namedtuple("Variant", "call data rescan prune")): class Variant(collections.namedtuple("Variant", "call data rescan prune")):
"""Helper for importing one key and verifying scanned transactions.""" """Helper for importing one key and verifying scanned transactions."""
def try_rpc(self, func, *args, **kwargs):
if self.expect_disabled:
assert_raises_rpc_error(-4, "Rescan is disabled in pruned mode", func, *args, **kwargs)
else:
return func(*args, **kwargs)
def do_import(self, timestamp): def do_import(self, timestamp):
"""Call one key import RPC.""" """Call one key import RPC."""
if self.call == Call.single: if self.call == Call.single:
if self.data == Data.address: if self.data == Data.address:
response, error = try_rpc(self.node.importaddress, self.address["address"], self.label, response = self.try_rpc(self.node.importaddress, self.address["address"], self.label,
self.rescan == Rescan.yes) self.rescan == Rescan.yes)
elif self.data == Data.pub: elif self.data == Data.pub:
response, error = try_rpc(self.node.importpubkey, self.address["pubkey"], self.label, response = self.try_rpc(self.node.importpubkey, self.address["pubkey"], self.label,
self.rescan == Rescan.yes) self.rescan == Rescan.yes)
elif self.data == Data.priv: elif self.data == Data.priv:
response, error = try_rpc(self.node.importprivkey, self.key, self.label, self.rescan == Rescan.yes) response = self.try_rpc(self.node.importprivkey, self.key, self.label, self.rescan == Rescan.yes)
assert_equal(response, None) assert_equal(response, None)
assert_equal(error, {'message': 'Rescan is disabled in pruned mode',
'code': -4} if self.expect_disabled else None)
elif self.call == Call.multi: elif self.call == Call.multi:
response = self.node.importmulti([{ response = self.node.importmulti([{
"scriptPubKey": { "scriptPubKey": {
@ -179,13 +183,5 @@ class ImportRescanTest(BitcoinTestFramework):
else: else:
variant.check() variant.check()
def try_rpc(func, *args, **kwargs):
try:
return func(*args, **kwargs), None
except JSONRPCException as e:
return None, e.error
if __name__ == "__main__": if __name__ == "__main__":
ImportRescanTest().main() ImportRescanTest().main()

4
test/functional/importmulti.py

@ -423,11 +423,11 @@ class ImportMultiTest (BitcoinTestFramework):
# Bad or missing timestamps # Bad or missing timestamps
self.log.info("Should throw on invalid or missing timestamp values") self.log.info("Should throw on invalid or missing timestamp values")
assert_raises_message(JSONRPCException, 'Missing required timestamp field for key', assert_raises_rpc_error(-3, 'Missing required timestamp field for key',
self.nodes[1].importmulti, [{ self.nodes[1].importmulti, [{
"scriptPubKey": address['scriptPubKey'], "scriptPubKey": address['scriptPubKey'],
}]) }])
assert_raises_message(JSONRPCException, 'Expected number or "now" timestamp value for key. got type string', assert_raises_rpc_error(-3, 'Expected number or "now" timestamp value for key. got type string',
self.nodes[1].importmulti, [{ self.nodes[1].importmulti, [{
"scriptPubKey": address['scriptPubKey'], "scriptPubKey": address['scriptPubKey'],
"timestamp": "", "timestamp": "",

4
test/functional/importprunedfunds.py

@ -66,7 +66,7 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
self.sync_all() self.sync_all()
#Import with no affiliated address #Import with no affiliated address
assert_raises_jsonrpc(-5, "No addresses", self.nodes[1].importprunedfunds, rawtxn1, proof1) assert_raises_rpc_error(-5, "No addresses", self.nodes[1].importprunedfunds, rawtxn1, proof1)
balance1 = self.nodes[1].getbalance("", 0, True) balance1 = self.nodes[1].getbalance("", 0, True)
assert_equal(balance1, Decimal(0)) assert_equal(balance1, Decimal(0))
@ -97,7 +97,7 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
assert_equal(address_info['ismine'], True) assert_equal(address_info['ismine'], True)
#Remove transactions #Remove transactions
assert_raises_jsonrpc(-8, "Transaction does not exist in wallet.", self.nodes[1].removeprunedfunds, txnid1) assert_raises_rpc_error(-8, "Transaction does not exist in wallet.", self.nodes[1].removeprunedfunds, txnid1)
balance1 = self.nodes[1].getbalance("*", 0, True) balance1 = self.nodes[1].getbalance("*", 0, True)
assert_equal(balance1, Decimal('0.075')) assert_equal(balance1, Decimal('0.075'))

8
test/functional/keypool.py

@ -28,7 +28,7 @@ class KeyPoolTest(BitcoinTestFramework):
wallet_info = nodes[0].getwalletinfo() wallet_info = nodes[0].getwalletinfo()
assert(addr_before_encrypting_data['hdmasterkeyid'] != wallet_info['hdmasterkeyid']) assert(addr_before_encrypting_data['hdmasterkeyid'] != wallet_info['hdmasterkeyid'])
assert(addr_data['hdmasterkeyid'] == wallet_info['hdmasterkeyid']) assert(addr_data['hdmasterkeyid'] == wallet_info['hdmasterkeyid'])
assert_raises_jsonrpc(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress) assert_raises_rpc_error(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
# put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min) # put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min)
nodes[0].walletpassphrase('test', 12000) nodes[0].walletpassphrase('test', 12000)
@ -47,7 +47,7 @@ class KeyPoolTest(BitcoinTestFramework):
nodes[0].getrawchangeaddress() nodes[0].getrawchangeaddress()
addr = set() addr = set()
# the next one should fail # the next one should fail
assert_raises_jsonrpc(-12, "Keypool ran out", nodes[0].getrawchangeaddress) assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getrawchangeaddress)
# drain the external keys # drain the external keys
addr.add(nodes[0].getnewaddress()) addr.add(nodes[0].getnewaddress())
@ -58,7 +58,7 @@ class KeyPoolTest(BitcoinTestFramework):
addr.add(nodes[0].getnewaddress()) addr.add(nodes[0].getnewaddress())
assert(len(addr) == 6) assert(len(addr) == 6)
# the next one should fail # the next one should fail
assert_raises_jsonrpc(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress) assert_raises_rpc_error(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
# refill keypool with three new addresses # refill keypool with three new addresses
nodes[0].walletpassphrase('test', 1) nodes[0].walletpassphrase('test', 1)
@ -72,7 +72,7 @@ class KeyPoolTest(BitcoinTestFramework):
nodes[0].generate(1) nodes[0].generate(1)
nodes[0].generate(1) nodes[0].generate(1)
nodes[0].generate(1) nodes[0].generate(1)
assert_raises_jsonrpc(-12, "Keypool ran out", nodes[0].generate, 1) assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].generate, 1)
nodes[0].walletpassphrase('test', 100) nodes[0].walletpassphrase('test', 100)
nodes[0].keypoolrefill(100) nodes[0].keypoolrefill(100)

4
test/functional/mempool_packages.py

@ -115,7 +115,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN + 1000) assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN + 1000)
# Adding one more transaction on to the chain should fail. # Adding one more transaction on to the chain should fail.
assert_raises_jsonrpc(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], txid, vout, value, fee, 1) assert_raises_rpc_error(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], txid, vout, value, fee, 1)
# Check that prioritising a tx before it's added to the mempool works # Check that prioritising a tx before it's added to the mempool works
# First clear the mempool by mining a block. # First clear the mempool by mining a block.
@ -167,7 +167,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
# Sending one more chained transaction will fail # Sending one more chained transaction will fail
utxo = transaction_package.pop(0) utxo = transaction_package.pop(0)
assert_raises_jsonrpc(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10) assert_raises_rpc_error(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
# TODO: check that node1's mempool is as expected # TODO: check that node1's mempool is as expected

2
test/functional/mempool_persist.py

@ -103,7 +103,7 @@ class MempoolPersistTest(BitcoinTestFramework):
mempooldotnew1 = mempooldat1 + '.new' mempooldotnew1 = mempooldat1 + '.new'
with os.fdopen(os.open(mempooldotnew1, os.O_CREAT, 0o000), 'w'): with os.fdopen(os.open(mempooldotnew1, os.O_CREAT, 0o000), 'w'):
pass pass
assert_raises_jsonrpc(-1, "Unable to dump mempool to disk", self.nodes[1].savemempool) assert_raises_rpc_error(-1, "Unable to dump mempool to disk", self.nodes[1].savemempool)
os.remove(mempooldotnew1) os.remove(mempooldotnew1)
if __name__ == '__main__': if __name__ == '__main__':

4
test/functional/mempool_reorg.py

@ -50,14 +50,14 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
timelock_tx = timelock_tx[:-8] + hex(self.nodes[0].getblockcount() + 2)[2:] + "000000" timelock_tx = timelock_tx[:-8] + hex(self.nodes[0].getblockcount() + 2)[2:] + "000000"
timelock_tx = self.nodes[0].signrawtransaction(timelock_tx)["hex"] timelock_tx = self.nodes[0].signrawtransaction(timelock_tx)["hex"]
# This will raise an exception because the timelock transaction is too immature to spend # This will raise an exception because the timelock transaction is too immature to spend
assert_raises_jsonrpc(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx) assert_raises_rpc_error(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx)
# Broadcast and mine spend_102 and 103: # Broadcast and mine spend_102 and 103:
spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw) spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw)
spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw) spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw)
self.nodes[0].generate(1) self.nodes[0].generate(1)
# Time-locked transaction is still too immature to spend # Time-locked transaction is still too immature to spend
assert_raises_jsonrpc(-26,'non-final', self.nodes[0].sendrawtransaction, timelock_tx) assert_raises_rpc_error(-26,'non-final', self.nodes[0].sendrawtransaction, timelock_tx)
# Create 102_1 and 103_1: # Create 102_1 and 103_1:
spend_102_1_raw = create_tx(self.nodes[0], spend_102_id, node1_address, 49.98) spend_102_1_raw = create_tx(self.nodes[0], spend_102_id, node1_address, 49.98)

2
test/functional/mempool_spendcoinbase.py

@ -36,7 +36,7 @@ class MempoolSpendCoinbaseTest(BitcoinTestFramework):
spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0]) spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0])
# coinbase at height 102 should be too immature to spend # coinbase at height 102 should be too immature to spend
assert_raises_jsonrpc(-26,"bad-txns-premature-spend-of-coinbase", self.nodes[0].sendrawtransaction, spends_raw[1]) assert_raises_rpc_error(-26,"bad-txns-premature-spend-of-coinbase", self.nodes[0].sendrawtransaction, spends_raw[1])
# mempool should have just spend_101: # mempool should have just spend_101:
assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ]) assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ])

8
test/functional/merkle_blocks.py

@ -38,7 +38,7 @@ class MerkleBlockTest(BitcoinTestFramework):
tx2 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 49.99}) tx2 = self.nodes[0].createrawtransaction([node0utxos.pop()], {self.nodes[1].getnewaddress(): 49.99})
txid2 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransaction(tx2)["hex"]) txid2 = self.nodes[0].sendrawtransaction(self.nodes[0].signrawtransaction(tx2)["hex"])
# This will raise an exception because the transaction is not yet in a block # This will raise an exception because the transaction is not yet in a block
assert_raises_jsonrpc(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [txid1]) assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [txid1])
self.nodes[0].generate(1) self.nodes[0].generate(1)
blockhash = self.nodes[0].getblockhash(chain_height + 1) blockhash = self.nodes[0].getblockhash(chain_height + 1)
@ -63,11 +63,11 @@ class MerkleBlockTest(BitcoinTestFramework):
txid_unspent = txid1 if txin_spent["txid"] != txid1 else txid2 txid_unspent = txid1 if txin_spent["txid"] != txid1 else txid2
# We can't find the block from a fully-spent tx # We can't find the block from a fully-spent tx
assert_raises_jsonrpc(-5, "Transaction not yet in block", self.nodes[2].gettxoutproof, [txid_spent]) assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[2].gettxoutproof, [txid_spent])
# We can get the proof if we specify the block # We can get the proof if we specify the block
assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_spent], blockhash)), [txid_spent]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_spent], blockhash)), [txid_spent])
# We can't get the proof if we specify a non-existent block # We can't get the proof if we specify a non-existent block
assert_raises_jsonrpc(-5, "Block not found", self.nodes[2].gettxoutproof, [txid_spent], "00000000000000000000000000000000") assert_raises_rpc_error(-5, "Block not found", self.nodes[2].gettxoutproof, [txid_spent], "00000000000000000000000000000000")
# We can get the proof if the transaction is unspent # We can get the proof if the transaction is unspent
assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_unspent])), [txid_unspent]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[2].gettxoutproof([txid_unspent])), [txid_unspent])
# We can get the proof if we provide a list of transactions and one of them is unspent. The ordering of the list should not matter. # We can get the proof if we provide a list of transactions and one of them is unspent. The ordering of the list should not matter.
@ -76,7 +76,7 @@ class MerkleBlockTest(BitcoinTestFramework):
# We can always get a proof if we have a -txindex # We can always get a proof if we have a -txindex
assert_equal(self.nodes[2].verifytxoutproof(self.nodes[3].gettxoutproof([txid_spent])), [txid_spent]) assert_equal(self.nodes[2].verifytxoutproof(self.nodes[3].gettxoutproof([txid_spent])), [txid_spent])
# We can't get a proof if we specify transactions from different blocks # We can't get a proof if we specify transactions from different blocks
assert_raises_jsonrpc(-5, "Not all transactions found in specified or retrieved block", self.nodes[2].gettxoutproof, [txid1, txid3]) assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", self.nodes[2].gettxoutproof, [txid1, txid3])
if __name__ == '__main__': if __name__ == '__main__':

10
test/functional/mining.py

@ -15,7 +15,7 @@ from decimal import Decimal
from test_framework.blocktools import create_coinbase from test_framework.blocktools import create_coinbase
from test_framework.mininode import CBlock from test_framework.mininode import CBlock
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_jsonrpc from test_framework.util import assert_equal, assert_raises_rpc_error
def b2x(b): def b2x(b):
return b2a_hex(b).decode('ascii') return b2a_hex(b).decode('ascii')
@ -68,7 +68,7 @@ class MiningTest(BitcoinTestFramework):
assert_template(node, block, None) assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure") self.log.info("submitblock: Test block decode failure")
assert_raises_jsonrpc(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15])) assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15]))
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block) bad_block = copy.deepcopy(block)
@ -77,10 +77,10 @@ class MiningTest(BitcoinTestFramework):
assert_template(node, bad_block, 'bad-cb-missing') assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction") self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_jsonrpc(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize())) assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize()))
self.log.info("getblocktemplate: Test truncated final transaction") self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_jsonrpc(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'}) assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'})
self.log.info("getblocktemplate: Test duplicate transaction") self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block) bad_block = copy.deepcopy(block)
@ -107,7 +107,7 @@ class MiningTest(BitcoinTestFramework):
bad_block_sn = bytearray(block.serialize()) bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1)
bad_block_sn[TX_COUNT_OFFSET] += 1 bad_block_sn[TX_COUNT_OFFSET] += 1
assert_raises_jsonrpc(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'}) assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'})
self.log.info("getblocktemplate: Test bad bits") self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block) bad_block = copy.deepcopy(block)

6
test/functional/multiwallet.py

@ -9,7 +9,7 @@ Verify that a bitcoind node can load multiple wallet files
import os import os
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_jsonrpc from test_framework.util import assert_equal, assert_raises_rpc_error
class MultiWalletTest(BitcoinTestFramework): class MultiWalletTest(BitcoinTestFramework):
def set_test_params(self): def set_test_params(self):
@ -43,10 +43,10 @@ class MultiWalletTest(BitcoinTestFramework):
w1.generate(1) w1.generate(1)
# accessing invalid wallet fails # accessing invalid wallet fails
assert_raises_jsonrpc(-18, "Requested wallet does not exist or is not loaded", wallet_bad.getwalletinfo) assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", wallet_bad.getwalletinfo)
# accessing wallet RPC without using wallet endpoint fails # accessing wallet RPC without using wallet endpoint fails
assert_raises_jsonrpc(-19, "Wallet file not specified", self.nodes[0].getwalletinfo) assert_raises_rpc_error(-19, "Wallet file not specified", self.nodes[0].getwalletinfo)
# check w1 wallet balance # check w1 wallet balance
w1_info = w1.getwalletinfo() w1_info = w1.getwalletinfo()

4
test/functional/net.py

@ -12,7 +12,7 @@ import time
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_jsonrpc, assert_raises_rpc_error,
connect_nodes_bi, connect_nodes_bi,
p2p_port, p2p_port,
) )
@ -84,7 +84,7 @@ class NetTest(BitcoinTestFramework):
assert_equal(len(added_nodes), 1) assert_equal(len(added_nodes), 1)
assert_equal(added_nodes[0]['addednode'], ip_port) assert_equal(added_nodes[0]['addednode'], ip_port)
# check that a non-existent node returns an error # check that a non-existent node returns an error
assert_raises_jsonrpc(-24, "Node has not been added", assert_raises_rpc_error(-24, "Node has not been added",
self.nodes[0].getaddednodeinfo, '1.1.1.1') self.nodes[0].getaddednodeinfo, '1.1.1.1')
def _test_getpeerinfo(self): def _test_getpeerinfo(self):

6
test/functional/nulldummy.py

@ -71,7 +71,7 @@ class NULLDUMMYTest(BitcoinTestFramework):
self.log.info("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation") self.log.info("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation")
test2tx = self.create_transaction(self.nodes[0], txid2, self.ms_address, 47) test2tx = self.create_transaction(self.nodes[0], txid2, self.ms_address, 47)
trueDummy(test2tx) trueDummy(test2tx)
assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test2tx.serialize_with_witness()), True) assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test2tx.serialize_with_witness()), True)
self.log.info("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]") self.log.info("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]")
self.block_submit(self.nodes[0], [test2tx], False, True) self.block_submit(self.nodes[0], [test2tx], False, True)
@ -80,14 +80,14 @@ class NULLDUMMYTest(BitcoinTestFramework):
test4tx = self.create_transaction(self.nodes[0], test2tx.hash, self.address, 46) test4tx = self.create_transaction(self.nodes[0], test2tx.hash, self.address, 46)
test6txs=[CTransaction(test4tx)] test6txs=[CTransaction(test4tx)]
trueDummy(test4tx) trueDummy(test4tx)
assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test4tx.serialize_with_witness()), True) assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test4tx.serialize_with_witness()), True)
self.block_submit(self.nodes[0], [test4tx]) self.block_submit(self.nodes[0], [test4tx])
self.log.info("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation") self.log.info("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
test5tx = self.create_transaction(self.nodes[0], txid3, self.wit_address, 48) test5tx = self.create_transaction(self.nodes[0], txid3, self.wit_address, 48)
test6txs.append(CTransaction(test5tx)) test6txs.append(CTransaction(test5tx))
test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01' test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01'
assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test5tx.serialize_with_witness()), True) assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test5tx.serialize_with_witness()), True)
self.block_submit(self.nodes[0], [test5tx], True) self.block_submit(self.nodes[0], [test5tx], True)
self.log.info("Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [432]") self.log.info("Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [432]")

2
test/functional/p2p-acceptblock.py

@ -171,7 +171,7 @@ class AcceptBlockTest(BitcoinTestFramework):
# Blocks 1-287 should be accepted, block 288 should be ignored because it's too far ahead # Blocks 1-287 should be accepted, block 288 should be ignored because it's too far ahead
for x in all_blocks[:-1]: for x in all_blocks[:-1]:
self.nodes[0].getblock(x.hash) self.nodes[0].getblock(x.hash)
assert_raises_jsonrpc(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[-1].hash) assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[-1].hash)
headers_message.headers.pop() # Ensure the last block is unrequested headers_message.headers.pop() # Ensure the last block is unrequested
white_node.send_message(headers_message) # Send headers leading to tip white_node.send_message(headers_message) # Send headers leading to tip

2
test/functional/prioritise_transaction.py

@ -101,7 +101,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
tx_id = self.nodes[0].decoderawtransaction(tx_hex)["txid"] tx_id = self.nodes[0].decoderawtransaction(tx_hex)["txid"]
# This will raise an exception due to min relay fee not being met # This will raise an exception due to min relay fee not being met
assert_raises_jsonrpc(-26, "66: min relay fee not met", self.nodes[0].sendrawtransaction, tx_hex) assert_raises_rpc_error(-26, "66: min relay fee not met", self.nodes[0].sendrawtransaction, tx_hex)
assert(tx_id not in self.nodes[0].getrawmempool()) assert(tx_id not in self.nodes[0].getrawmempool())
# This is a less than 1000-byte transaction, so just set the fee # This is a less than 1000-byte transaction, so just set the fee

8
test/functional/pruning.py

@ -185,7 +185,7 @@ class PruneTest(BitcoinTestFramework):
def reorg_back(self): def reorg_back(self):
# Verify that a block on the old main chain fork has been pruned away # Verify that a block on the old main chain fork has been pruned away
assert_raises_jsonrpc(-1, "Block not available (pruned data)", self.nodes[2].getblock, self.forkhash) assert_raises_rpc_error(-1, "Block not available (pruned data)", self.nodes[2].getblock, self.forkhash)
self.log.info("Will need to redownload block %d" % self.forkheight) self.log.info("Will need to redownload block %d" % self.forkheight)
# Verify that we have enough history to reorg back to the fork point # Verify that we have enough history to reorg back to the fork point
@ -232,7 +232,7 @@ class PruneTest(BitcoinTestFramework):
self.start_node(node_number) self.start_node(node_number)
node = self.nodes[node_number] node = self.nodes[node_number]
assert_equal(node.getblockcount(), 995) assert_equal(node.getblockcount(), 995)
assert_raises_jsonrpc(-1, "not in prune mode", node.pruneblockchain, 500) assert_raises_rpc_error(-1, "not in prune mode", node.pruneblockchain, 500)
# now re-start in manual pruning mode # now re-start in manual pruning mode
self.stop_node(node_number) self.stop_node(node_number)
@ -265,14 +265,14 @@ class PruneTest(BitcoinTestFramework):
return os.path.isfile(self.options.tmpdir + "/node{}/regtest/blocks/blk{:05}.dat".format(node_number, index)) return os.path.isfile(self.options.tmpdir + "/node{}/regtest/blocks/blk{:05}.dat".format(node_number, index))
# should not prune because chain tip of node 3 (995) < PruneAfterHeight (1000) # should not prune because chain tip of node 3 (995) < PruneAfterHeight (1000)
assert_raises_jsonrpc(-1, "Blockchain is too short for pruning", node.pruneblockchain, height(500)) assert_raises_rpc_error(-1, "Blockchain is too short for pruning", node.pruneblockchain, height(500))
# mine 6 blocks so we are at height 1001 (i.e., above PruneAfterHeight) # mine 6 blocks so we are at height 1001 (i.e., above PruneAfterHeight)
node.generate(6) node.generate(6)
assert_equal(node.getblockchaininfo()["blocks"], 1001) assert_equal(node.getblockchaininfo()["blocks"], 1001)
# negative heights should raise an exception # negative heights should raise an exception
assert_raises_jsonrpc(-8, "Negative", node.pruneblockchain, -10) assert_raises_rpc_error(-8, "Negative", node.pruneblockchain, -10)
# height=100 too low to prune first block file so this is a no-op # height=100 too low to prune first block file so this is a no-op
prune(100) prune(100)

12
test/functional/rawtransactions.py

@ -48,7 +48,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtx = self.nodes[2].signrawtransaction(rawtx) rawtx = self.nodes[2].signrawtransaction(rawtx)
# This will raise an exception since there are missing inputs # This will raise an exception since there are missing inputs
assert_raises_jsonrpc(-25, "Missing inputs", self.nodes[2].sendrawtransaction, rawtx['hex']) assert_raises_rpc_error(-25, "Missing inputs", self.nodes[2].sendrawtransaction, rawtx['hex'])
######################### #########################
# RAW TX MULTISIG TESTS # # RAW TX MULTISIG TESTS #
@ -188,13 +188,13 @@ class RawTransactionsTest(BitcoinTestFramework):
assert_equal(self.nodes[0].getrawtransaction(txHash, True)["hex"], rawTxSigned['hex']) assert_equal(self.nodes[0].getrawtransaction(txHash, True)["hex"], rawTxSigned['hex'])
# 6. invalid parameters - supply txid and string "Flase" # 6. invalid parameters - supply txid and string "Flase"
assert_raises_jsonrpc(-3,"Invalid type", self.nodes[0].getrawtransaction, txHash, "Flase") assert_raises_rpc_error(-3,"Invalid type", self.nodes[0].getrawtransaction, txHash, "Flase")
# 7. invalid parameters - supply txid and empty array # 7. invalid parameters - supply txid and empty array
assert_raises_jsonrpc(-3,"Invalid type", self.nodes[0].getrawtransaction, txHash, []) assert_raises_rpc_error(-3,"Invalid type", self.nodes[0].getrawtransaction, txHash, [])
# 8. invalid parameters - supply txid and empty dict # 8. invalid parameters - supply txid and empty dict
assert_raises_jsonrpc(-3,"Invalid type", self.nodes[0].getrawtransaction, txHash, {}) assert_raises_rpc_error(-3,"Invalid type", self.nodes[0].getrawtransaction, txHash, {})
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 1000}] inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 1000}]
outputs = { self.nodes[0].getnewaddress() : 1 } outputs = { self.nodes[0].getnewaddress() : 1 }
@ -205,12 +205,12 @@ class RawTransactionsTest(BitcoinTestFramework):
# 9. invalid parameters - sequence number out of range # 9. invalid parameters - sequence number out of range
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : -1}] inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : -1}]
outputs = { self.nodes[0].getnewaddress() : 1 } outputs = { self.nodes[0].getnewaddress() : 1 }
assert_raises_jsonrpc(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs) assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs)
# 10. invalid parameters - sequence number out of range # 10. invalid parameters - sequence number out of range
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967296}] inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967296}]
outputs = { self.nodes[0].getnewaddress() : 1 } outputs = { self.nodes[0].getnewaddress() : 1 }
assert_raises_jsonrpc(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs) assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs)
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967294}] inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967294}]
outputs = { self.nodes[0].getnewaddress() : 1 } outputs = { self.nodes[0].getnewaddress() : 1 }

30
test/functional/replace-by-fee.py

@ -125,9 +125,9 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b_hex = txToHex(tx1b) tx1b_hex = txToHex(tx1b)
# This will raise an exception due to insufficient fee # This will raise an exception due to insufficient fee
assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True) assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True)
# This will raise an exception due to transaction replacement being disabled # This will raise an exception due to transaction replacement being disabled
assert_raises_jsonrpc(-26, "txn-mempool-conflict", self.nodes[1].sendrawtransaction, tx1b_hex, True) assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[1].sendrawtransaction, tx1b_hex, True)
# Extra 0.1 BTC fee # Extra 0.1 BTC fee
tx1b = CTransaction() tx1b = CTransaction()
@ -135,7 +135,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))] tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))]
tx1b_hex = txToHex(tx1b) tx1b_hex = txToHex(tx1b)
# Replacement still disabled even with "enough fee" # Replacement still disabled even with "enough fee"
assert_raises_jsonrpc(-26, "txn-mempool-conflict", self.nodes[1].sendrawtransaction, tx1b_hex, True) assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[1].sendrawtransaction, tx1b_hex, True)
# Works when enabled # Works when enabled
tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True) tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
@ -178,7 +178,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
dbl_tx_hex = txToHex(dbl_tx) dbl_tx_hex = txToHex(dbl_tx)
# This will raise an exception due to insufficient fee # This will raise an exception due to insufficient fee
assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True) assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True)
# Accepted with sufficient fee # Accepted with sufficient fee
dbl_tx = CTransaction() dbl_tx = CTransaction()
@ -239,7 +239,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
dbl_tx.vout = [CTxOut(initial_nValue - fee*n, CScript([1]))] dbl_tx.vout = [CTxOut(initial_nValue - fee*n, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx) dbl_tx_hex = txToHex(dbl_tx)
# This will raise an exception due to insufficient fee # This will raise an exception due to insufficient fee
assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True) assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True)
# 1 BTC fee is enough # 1 BTC fee is enough
dbl_tx = CTransaction() dbl_tx = CTransaction()
@ -267,7 +267,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
dbl_tx.vout = [CTxOut(initial_nValue - 2*fee*n, CScript([1]))] dbl_tx.vout = [CTxOut(initial_nValue - 2*fee*n, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx) dbl_tx_hex = txToHex(dbl_tx)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, dbl_tx_hex, True) assert_raises_rpc_error(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, dbl_tx_hex, True)
for tx in tree_txs: for tx in tree_txs:
tx.rehash() tx.rehash()
@ -291,7 +291,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b_hex = txToHex(tx1b) tx1b_hex = txToHex(tx1b)
# This will raise an exception due to insufficient fee # This will raise an exception due to insufficient fee
assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True) assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True)
def test_spends_of_conflicting_outputs(self): def test_spends_of_conflicting_outputs(self):
"""Replacements that spend conflicting tx outputs are rejected""" """Replacements that spend conflicting tx outputs are rejected"""
@ -314,7 +314,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2_hex = txToHex(tx2) tx2_hex = txToHex(tx2)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True) assert_raises_rpc_error(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True)
# Spend tx1a's output to test the indirect case. # Spend tx1a's output to test the indirect case.
tx1b = CTransaction() tx1b = CTransaction()
@ -331,7 +331,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2_hex = txToHex(tx2) tx2_hex = txToHex(tx2)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True) assert_raises_rpc_error(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True)
def test_new_unconfirmed_inputs(self): def test_new_unconfirmed_inputs(self):
"""Replacements that add new unconfirmed inputs are rejected""" """Replacements that add new unconfirmed inputs are rejected"""
@ -350,7 +350,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2_hex = txToHex(tx2) tx2_hex = txToHex(tx2)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "replacement-adds-unconfirmed", self.nodes[0].sendrawtransaction, tx2_hex, True) assert_raises_rpc_error(-26, "replacement-adds-unconfirmed", self.nodes[0].sendrawtransaction, tx2_hex, True)
def test_too_many_replacements(self): def test_too_many_replacements(self):
"""Replacements that evict too many transactions are rejected""" """Replacements that evict too many transactions are rejected"""
@ -396,7 +396,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
double_tx_hex = txToHex(double_tx) double_tx_hex = txToHex(double_tx)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, double_tx_hex, True) assert_raises_rpc_error(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, double_tx_hex, True)
# If we remove an input, it should pass # If we remove an input, it should pass
double_tx = CTransaction() double_tx = CTransaction()
@ -423,7 +423,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b_hex = txToHex(tx1b) tx1b_hex = txToHex(tx1b)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx1b_hex, True) assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx1b_hex, True)
tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN)) tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
@ -441,7 +441,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2b_hex = txToHex(tx2b) tx2b_hex = txToHex(tx2b)
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx2b_hex, True) assert_raises_rpc_error(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx2b_hex, True)
# Now create a new transaction that spends from tx1a and tx2a # Now create a new transaction that spends from tx1a and tx2a
# opt-in on one of the inputs # opt-in on one of the inputs
@ -493,7 +493,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b_hex = txToHex(tx1b) tx1b_hex = txToHex(tx1b)
# Verify tx1b cannot replace tx1a. # Verify tx1b cannot replace tx1a.
assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True) assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True)
# Use prioritisetransaction to set tx1a's fee to 0. # Use prioritisetransaction to set tx1a's fee to 0.
self.nodes[0].prioritisetransaction(txid=tx1a_txid, fee_delta=int(-0.1*COIN)) self.nodes[0].prioritisetransaction(txid=tx1a_txid, fee_delta=int(-0.1*COIN))
@ -520,7 +520,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2b_hex = txToHex(tx2b) tx2b_hex = txToHex(tx2b)
# Verify tx2b cannot replace tx2a. # Verify tx2b cannot replace tx2a.
assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx2b_hex, True) assert_raises_rpc_error(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx2b_hex, True)
# Now prioritise tx2b to have a higher modified fee # Now prioritise tx2b to have a higher modified fee
self.nodes[0].prioritisetransaction(txid=tx2b.hash, fee_delta=int(0.1*COIN)) self.nodes[0].prioritisetransaction(txid=tx2b.hash, fee_delta=int(0.1*COIN))

4
test/functional/resendwallettransactions.py

@ -5,7 +5,7 @@
"""Test resendwallettransactions RPC.""" """Test resendwallettransactions RPC."""
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_jsonrpc from test_framework.util import assert_equal, assert_raises_rpc_error
class ResendWalletTransactionsTest(BitcoinTestFramework): class ResendWalletTransactionsTest(BitcoinTestFramework):
def set_test_params(self): def set_test_params(self):
@ -14,7 +14,7 @@ class ResendWalletTransactionsTest(BitcoinTestFramework):
def run_test(self): def run_test(self):
# Should raise RPC_WALLET_ERROR (-4) if walletbroadcast is disabled. # Should raise RPC_WALLET_ERROR (-4) if walletbroadcast is disabled.
assert_raises_jsonrpc(-4, "Error: Wallet transaction broadcasting is disabled with -walletbroadcast", self.nodes[0].resendwallettransactions) assert_raises_rpc_error(-4, "Error: Wallet transaction broadcasting is disabled with -walletbroadcast", self.nodes[0].resendwallettransactions)
# Should return an empty array if there aren't unconfirmed wallet transactions. # Should return an empty array if there aren't unconfirmed wallet transactions.
self.stop_node(0) self.stop_node(0)

2
test/functional/rpcbind_test.py

@ -101,7 +101,7 @@ class RPCBindTest(BitcoinTestFramework):
# Check that with invalid rpcallowip, we are denied # Check that with invalid rpcallowip, we are denied
self.run_allowip_test([non_loopback_ip], non_loopback_ip, defaultport) self.run_allowip_test([non_loopback_ip], non_loopback_ip, defaultport)
assert_raises_jsonrpc(-342, "non-JSON HTTP response with '403 Forbidden' from server", self.run_allowip_test, ['1.1.1.1'], non_loopback_ip, defaultport) assert_raises_rpc_error(-342, "non-JSON HTTP response with '403 Forbidden' from server", self.run_allowip_test, ['1.1.1.1'], non_loopback_ip, defaultport)
if __name__ == '__main__': if __name__ == '__main__':
RPCBindTest().main() RPCBindTest().main()

4
test/functional/rpcnamedargs.py

@ -7,7 +7,7 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_jsonrpc, assert_raises_rpc_error,
) )
class NamedArgumentTest(BitcoinTestFramework): class NamedArgumentTest(BitcoinTestFramework):
@ -19,7 +19,7 @@ class NamedArgumentTest(BitcoinTestFramework):
h = node.help(command='getblockchaininfo') h = node.help(command='getblockchaininfo')
assert(h.startswith('getblockchaininfo\n')) assert(h.startswith('getblockchaininfo\n'))
assert_raises_jsonrpc(-8, 'Unknown named parameter', node.help, random='getblockchaininfo') assert_raises_rpc_error(-8, 'Unknown named parameter', node.help, random='getblockchaininfo')
h = node.getblockhash(height=0) h = node.getblockhash(height=0)
node.getblock(blockhash=h) node.getblock(blockhash=h)

14
test/functional/segwit.py

@ -99,11 +99,11 @@ class SegWitTest(BitcoinTestFramework):
sync_blocks(self.nodes) sync_blocks(self.nodes)
def fail_accept(self, node, error_msg, txid, sign, redeem_script=""): def fail_accept(self, node, error_msg, txid, sign, redeem_script=""):
assert_raises_jsonrpc(-26, error_msg, send_to_witness, 1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script) assert_raises_rpc_error(-26, error_msg, send_to_witness, 1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
def fail_mine(self, node, txid, sign, redeem_script=""): def fail_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script) send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
assert_raises_jsonrpc(-1, "CreateNewBlock: TestBlockValidity failed", node.generate, 1) assert_raises_rpc_error(-1, "CreateNewBlock: TestBlockValidity failed", node.generate, 1)
sync_blocks(self.nodes) sync_blocks(self.nodes)
def run_test(self): def run_test(self):
@ -452,11 +452,7 @@ class SegWitTest(BitcoinTestFramework):
for i in importlist: for i in importlist:
# import all generated addresses. The wallet already has the private keys for some of these, so catch JSON RPC # import all generated addresses. The wallet already has the private keys for some of these, so catch JSON RPC
# exceptions and continue. # exceptions and continue.
try: try_rpc(-4, "The wallet already contains the private key for this address or script", self.nodes[0].importaddress, i, "", False, True)
self.nodes[0].importaddress(i,"",False,True)
except JSONRPCException as exp:
assert_equal(exp.error["message"], "The wallet already contains the private key for this address or script")
assert_equal(exp.error["code"], -4)
self.nodes[0].importaddress(script_to_p2sh(op0)) # import OP_0 as address only self.nodes[0].importaddress(script_to_p2sh(op0)) # import OP_0 as address only
self.nodes[0].importaddress(multisig_without_privkey_address) # Test multisig_without_privkey self.nodes[0].importaddress(multisig_without_privkey_address) # Test multisig_without_privkey
@ -469,7 +465,7 @@ class SegWitTest(BitcoinTestFramework):
# addwitnessaddress should refuse to return a witness address if an uncompressed key is used # addwitnessaddress should refuse to return a witness address if an uncompressed key is used
# note that no witness address should be returned by unsolvable addresses # note that no witness address should be returned by unsolvable addresses
for i in uncompressed_spendable_address + uncompressed_solvable_address + unknown_address + unsolvable_address: for i in uncompressed_spendable_address + uncompressed_solvable_address + unknown_address + unsolvable_address:
assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i) assert_raises_rpc_error(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
# addwitnessaddress should return a witness addresses even if keys are not in the wallet # addwitnessaddress should return a witness addresses even if keys are not in the wallet
self.nodes[0].addwitnessaddress(multisig_without_privkey_address) self.nodes[0].addwitnessaddress(multisig_without_privkey_address)
@ -552,7 +548,7 @@ class SegWitTest(BitcoinTestFramework):
# premature_witaddress are not accepted until the script is added with addwitnessaddress first # premature_witaddress are not accepted until the script is added with addwitnessaddress first
for i in uncompressed_spendable_address + uncompressed_solvable_address + premature_witaddress: for i in uncompressed_spendable_address + uncompressed_solvable_address + premature_witaddress:
# This will raise an exception # This will raise an exception
assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i) assert_raises_rpc_error(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
# after importaddress it should pass addwitnessaddress # after importaddress it should pass addwitnessaddress
v = self.nodes[0].validateaddress(compressed_solvable_address[1]) v = self.nodes[0].validateaddress(compressed_solvable_address[1])

2
test/functional/signrawtransactions.py

@ -82,7 +82,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"]) assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"])
# Make sure decoderawtransaction throws if there is extra data # Make sure decoderawtransaction throws if there is extra data
assert_raises(JSONRPCException, self.nodes[0].decoderawtransaction, rawTx + "00") assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decoderawtransaction, rawTx + "00")
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys) rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)

14
test/functional/test_framework/util.py

@ -51,6 +51,8 @@ def assert_raises(exc, fun, *args, **kwds):
def assert_raises_message(exc, message, fun, *args, **kwds): def assert_raises_message(exc, message, fun, *args, **kwds):
try: try:
fun(*args, **kwds) fun(*args, **kwds)
except JSONRPCException:
raise AssertionError("Use assert_raises_rpc_error() to test RPC failures")
except exc as e: except exc as e:
if message is not None and message not in e.error['message']: if message is not None and message not in e.error['message']:
raise AssertionError("Expected substring not found:" + e.error['message']) raise AssertionError("Expected substring not found:" + e.error['message'])
@ -83,7 +85,7 @@ def assert_raises_process_error(returncode, output, fun, *args, **kwds):
else: else:
raise AssertionError("No exception raised") raise AssertionError("No exception raised")
def assert_raises_jsonrpc(code, message, fun, *args, **kwds): def assert_raises_rpc_error(code, message, fun, *args, **kwds):
"""Run an RPC and verify that a specific JSONRPC exception code and message is raised. """Run an RPC and verify that a specific JSONRPC exception code and message is raised.
Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException
@ -99,6 +101,13 @@ def assert_raises_jsonrpc(code, message, fun, *args, **kwds):
args*: positional arguments for the function. args*: positional arguments for the function.
kwds**: named arguments for the function. kwds**: named arguments for the function.
""" """
assert try_rpc(code, message, fun, *args, **kwds), "No exception raised"
def try_rpc(code, message, fun, *args, **kwds):
"""Tries to run an rpc command.
Test against error code and message if the rpc fails.
Returns whether a JSONRPCException was raised."""
try: try:
fun(*args, **kwds) fun(*args, **kwds)
except JSONRPCException as e: except JSONRPCException as e:
@ -107,10 +116,11 @@ def assert_raises_jsonrpc(code, message, fun, *args, **kwds):
raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"]) raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
if (message is not None) and (message not in e.error['message']): if (message is not None) and (message not in e.error['message']):
raise AssertionError("Expected substring not found:" + e.error['message']) raise AssertionError("Expected substring not found:" + e.error['message'])
return True
except Exception as e: except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__) raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else: else:
raise AssertionError("No exception raised") return False
def assert_is_hex_string(string): def assert_is_hex_string(string):
try: try:

4
test/functional/wallet-dump.py

@ -7,7 +7,7 @@
import os import os
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (assert_equal, assert_raises_jsonrpc) from test_framework.util import (assert_equal, assert_raises_rpc_error)
def read_dump(file_name, addrs, hd_master_addr_old): def read_dump(file_name, addrs, hd_master_addr_old):
@ -106,7 +106,7 @@ class WalletDumpTest(BitcoinTestFramework):
assert_equal(found_addr_rsv, 90*2) assert_equal(found_addr_rsv, 90*2)
# Overwriting should fail # Overwriting should fail
assert_raises_jsonrpc(-8, "already exists", self.nodes[0].dumpwallet, tmpdir + "/node0/wallet.unencrypted.dump") assert_raises_rpc_error(-8, "already exists", self.nodes[0].dumpwallet, tmpdir + "/node0/wallet.unencrypted.dump")
if __name__ == '__main__': if __name__ == '__main__':
WalletDumpTest().main () WalletDumpTest().main ()

12
test/functional/wallet-encryption.py

@ -9,7 +9,7 @@ import time
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_jsonrpc, assert_raises_rpc_error,
) )
class WalletEncryptionTest(BitcoinTestFramework): class WalletEncryptionTest(BitcoinTestFramework):
@ -32,7 +32,7 @@ class WalletEncryptionTest(BitcoinTestFramework):
self.start_node(0) self.start_node(0)
# Test that the wallet is encrypted # Test that the wallet is encrypted
assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address) assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Check that walletpassphrase works # Check that walletpassphrase works
self.nodes[0].walletpassphrase(passphrase, 2) self.nodes[0].walletpassphrase(passphrase, 2)
@ -40,20 +40,20 @@ class WalletEncryptionTest(BitcoinTestFramework):
# Check that the timeout is right # Check that the timeout is right
time.sleep(2) time.sleep(2)
assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address) assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Test wrong passphrase # Test wrong passphrase
assert_raises_jsonrpc(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10) assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10)
# Test walletlock # Test walletlock
self.nodes[0].walletpassphrase(passphrase, 84600) self.nodes[0].walletpassphrase(passphrase, 84600)
assert_equal(privkey, self.nodes[0].dumpprivkey(address)) assert_equal(privkey, self.nodes[0].dumpprivkey(address))
self.nodes[0].walletlock() self.nodes[0].walletlock()
assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address) assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Test passphrase changes # Test passphrase changes
self.nodes[0].walletpassphrasechange(passphrase, passphrase2) self.nodes[0].walletpassphrasechange(passphrase, passphrase2)
assert_raises_jsonrpc(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10) assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10)
self.nodes[0].walletpassphrase(passphrase2, 10) self.nodes[0].walletpassphrase(passphrase2, 10)
assert_equal(privkey, self.nodes[0].dumpprivkey(address)) assert_equal(privkey, self.nodes[0].dumpprivkey(address))

8
test/functional/wallet.py

@ -101,7 +101,7 @@ class WalletTest(BitcoinTestFramework):
unspent_0 = self.nodes[2].listunspent()[0] unspent_0 = self.nodes[2].listunspent()[0]
unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]} unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]}
self.nodes[2].lockunspent(False, [unspent_0]) self.nodes[2].lockunspent(False, [unspent_0])
assert_raises_jsonrpc(-4, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20) assert_raises_rpc_error(-4, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
assert_equal([unspent_0], self.nodes[2].listlockunspent()) assert_equal([unspent_0], self.nodes[2].listlockunspent())
self.nodes[2].lockunspent(True, [unspent_0]) self.nodes[2].lockunspent(True, [unspent_0])
assert_equal(len(self.nodes[2].listlockunspent()), 0) assert_equal(len(self.nodes[2].listlockunspent()), 0)
@ -286,10 +286,10 @@ class WalletTest(BitcoinTestFramework):
assert_equal(txObj['amount'], Decimal('-0.0001')) assert_equal(txObj['amount'], Decimal('-0.0001'))
# This will raise an exception because the amount type is wrong # This will raise an exception because the amount type is wrong
assert_raises_jsonrpc(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4") assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")
# This will raise an exception since generate does not accept a string # This will raise an exception since generate does not accept a string
assert_raises_jsonrpc(-1, "not an integer", self.nodes[0].generate, "2") assert_raises_rpc_error(-1, "not an integer", self.nodes[0].generate, "2")
# Import address and private key to check correct behavior of spendable unspents # Import address and private key to check correct behavior of spendable unspents
# 1. Send some coins to generate new UTXO # 1. Send some coins to generate new UTXO
@ -422,7 +422,7 @@ class WalletTest(BitcoinTestFramework):
node0_balance = self.nodes[0].getbalance() node0_balance = self.nodes[0].getbalance()
# With walletrejectlongchains we will not create the tx and store it in our wallet. # With walletrejectlongchains we will not create the tx and store it in our wallet.
assert_raises_jsonrpc(-4, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01')) assert_raises_rpc_error(-4, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
# Verify nothing new in wallet # Verify nothing new in wallet
assert_equal(total_txs, len(self.nodes[0].listtransactions("*",99999))) assert_equal(total_txs, len(self.nodes[0].listtransactions("*",99999)))

4
test/functional/zapwallettxes.py

@ -17,7 +17,7 @@
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_jsonrpc, assert_raises_rpc_error,
wait_until, wait_until,
) )
@ -72,7 +72,7 @@ class ZapWalletTXesTest (BitcoinTestFramework):
assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1) assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1)
# This will raise an exception because the unconfirmed transaction has been zapped # This will raise an exception because the unconfirmed transaction has been zapped
assert_raises_jsonrpc(-5, 'Invalid or non-wallet transaction id', self.nodes[0].gettransaction, txid2) assert_raises_rpc_error(-5, 'Invalid or non-wallet transaction id', self.nodes[0].gettransaction, txid2)
if __name__ == '__main__': if __name__ == '__main__':
ZapWalletTXesTest().main() ZapWalletTXesTest().main()

Loading…
Cancel
Save