aboutsummaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rwxr-xr-xtest/functional/feature_config_args.py2
-rwxr-xr-xtest/functional/feature_dbcrash.py55
-rwxr-xr-xtest/functional/feature_index_prune.py7
-rwxr-xr-xtest/functional/feature_minchainwork.py29
-rwxr-xr-xtest/functional/feature_proxy.py6
-rwxr-xr-xtest/functional/mempool_accept.py4
-rwxr-xr-xtest/functional/mempool_packages.py6
-rwxr-xr-xtest/functional/p2p_blockfilters.py5
-rwxr-xr-xtest/functional/p2p_compactblocks.py159
-rwxr-xr-xtest/functional/p2p_compactblocks_blocksonly.py6
-rwxr-xr-xtest/functional/p2p_unrequested_blocks.py15
-rwxr-xr-xtest/functional/rpc_getblockfrompeer.py13
-rwxr-xr-xtest/functional/rpc_mempool_entry_fee_fields_deprecation.py67
-rwxr-xr-xtest/functional/rpc_mempool_info.py102
-rwxr-xr-xtest/functional/rpc_net.py4
-rwxr-xr-xtest/functional/rpc_rawtransaction.py165
-rwxr-xr-xtest/functional/rpc_signrawtransaction.py51
-rwxr-xr-xtest/functional/test_framework/messages.py6
-rwxr-xr-xtest/functional/test_framework/p2p.py6
-rw-r--r--test/functional/test_framework/util.py1
-rw-r--r--test/functional/test_framework/wallet.py11
-rwxr-xr-xtest/functional/test_runner.py3
-rwxr-xr-xtest/functional/wallet_listreceivedby.py34
-rwxr-xr-xtest/functional/wallet_taproot.py4
-rwxr-xr-xtest/lint/lint-circular-dependencies.py3
-rwxr-xr-xtest/lint/lint-files.py77
-rwxr-xr-xtest/lint/lint-logs.py4
-rw-r--r--test/lint/spelling.ignore-words.txt1
28 files changed, 432 insertions, 414 deletions
diff --git a/test/functional/feature_config_args.py b/test/functional/feature_config_args.py
index fe3196d5ee..6c51a5ac31 100755
--- a/test/functional/feature_config_args.py
+++ b/test/functional/feature_config_args.py
@@ -85,7 +85,7 @@ class ConfArgsTest(BitcoinTestFramework):
def test_invalid_command_line_options(self):
self.nodes[0].assert_start_raises_init_error(
- expected_msg='Error: No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>.',
+ expected_msg='Error: Error parsing command line arguments: Can not set -proxy with no value. Please specify value with -proxy=value.',
extra_args=['-proxy'],
)
diff --git a/test/functional/feature_dbcrash.py b/test/functional/feature_dbcrash.py
index 3e60efbb3c..a3a5e9e27d 100755
--- a/test/functional/feature_dbcrash.py
+++ b/test/functional/feature_dbcrash.py
@@ -30,17 +30,17 @@ import http.client
import random
import time
+from test_framework.blocktools import COINBASE_MATURITY
from test_framework.messages import (
COIN,
- COutPoint,
- CTransaction,
- CTxIn,
- CTxOut,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
- create_confirmed_utxos,
+)
+from test_framework.wallet import (
+ MiniWallet,
+ getnewdestination,
)
@@ -66,13 +66,9 @@ class ChainstateWriteCrashTest(BitcoinTestFramework):
self.node3_args = ["-blockmaxweight=4000000", "-acceptnonstdtxn"]
self.extra_args = [self.node0_args, self.node1_args, self.node2_args, self.node3_args]
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
-
def setup_network(self):
self.add_nodes(self.num_nodes, extra_args=self.extra_args)
self.start_nodes()
- self.import_deterministic_coinbase_privkeys()
# Leave them unconnected, we'll use submitblock directly in this test
def restart_node(self, node_index, expected_tip):
@@ -190,34 +186,36 @@ class ChainstateWriteCrashTest(BitcoinTestFramework):
num_transactions = 0
random.shuffle(utxo_list)
while len(utxo_list) >= 2 and num_transactions < count:
- tx = CTransaction()
- input_amount = 0
- for _ in range(2):
- utxo = utxo_list.pop()
- tx.vin.append(CTxIn(COutPoint(int(utxo['txid'], 16), utxo['vout'])))
- input_amount += int(utxo['amount'] * COIN)
- output_amount = (input_amount - FEE) // 3
-
- if output_amount <= 0:
+ utxos_to_spend = [utxo_list.pop() for _ in range(2)]
+ input_amount = int(sum([utxo['value'] for utxo in utxos_to_spend]) * COIN)
+ if input_amount < FEE:
# Sanity check -- if we chose inputs that are too small, skip
continue
- for _ in range(3):
- tx.vout.append(CTxOut(output_amount, bytes.fromhex(utxo['scriptPubKey'])))
+ tx = self.wallet.create_self_transfer_multi(
+ from_node=node,
+ utxos_to_spend=utxos_to_spend,
+ num_outputs=3,
+ fee_per_output=FEE // 3)
- # Sign and send the transaction to get into the mempool
- tx_signed_hex = node.signrawtransactionwithwallet(tx.serialize().hex())['hex']
- node.sendrawtransaction(tx_signed_hex)
+ # Send the transaction to get into the mempool (skip fee-checks to run faster)
+ node.sendrawtransaction(hexstring=tx.serialize().hex(), maxfeerate=0)
num_transactions += 1
def run_test(self):
+ self.wallet = MiniWallet(self.nodes[3])
+ self.wallet.rescan_utxos()
+ initial_height = self.nodes[3].getblockcount()
+ self.generate(self.nodes[3], COINBASE_MATURITY, sync_fun=self.no_op)
+
# Track test coverage statistics
self.restart_counts = [0, 0, 0] # Track the restarts for nodes 0-2
self.crashed_on_restart = 0 # Track count of crashes during recovery
# Start by creating a lot of utxos on node3
- initial_height = self.nodes[3].getblockcount()
- utxo_list = create_confirmed_utxos(self, self.nodes[3].getnetworkinfo()['relayfee'], self.nodes[3], 5000, sync_fun=self.no_op)
+ utxo_list = self.wallet.send_self_transfer_multi(from_node=self.nodes[3], num_outputs=5000)['new_utxos']
+ self.generate(self.nodes[3], 1, sync_fun=self.no_op)
+ assert_equal(len(self.nodes[3].getrawmempool()), 0)
self.log.info(f"Prepped {len(utxo_list)} utxo entries")
# Sync these blocks with the other nodes
@@ -257,13 +255,14 @@ class ChainstateWriteCrashTest(BitcoinTestFramework):
self.nodes[3],
nblocks=min(10, current_height + 1 - self.nodes[3].getblockcount()),
# new address to avoid mining a block that has just been invalidated
- address=self.nodes[3].getnewaddress(),
+ address=getnewdestination()[2],
sync_fun=self.no_op,
))
self.log.debug(f"Syncing {len(block_hashes)} new blocks...")
self.sync_node3blocks(block_hashes)
- utxo_list = self.nodes[3].listunspent()
- self.log.debug(f"Node3 utxo count: {len(utxo_list)}")
+ self.wallet.rescan_utxos()
+ utxo_list = self.wallet.get_utxos()
+ self.log.debug(f"MiniWallet utxo count: {len(utxo_list)}")
# Check that the utxo hashes agree with node3
# Useful side effect: each utxo cache gets flushed here, so that we
diff --git a/test/functional/feature_index_prune.py b/test/functional/feature_index_prune.py
index 2bf57db923..3ee6a8036c 100755
--- a/test/functional/feature_index_prune.py
+++ b/test/functional/feature_index_prune.py
@@ -8,7 +8,6 @@ from test_framework.util import (
assert_equal,
assert_greater_than,
assert_raises_rpc_error,
- p2p_port,
)
@@ -132,11 +131,11 @@ class FeatureIndexPruneTest(BitcoinTestFramework):
self.nodes[i].assert_start_raises_init_error(extra_args=self.extra_args[i], expected_msg=msg)
self.log.info("make sure the nodes start again with the indices and an additional -reindex arg")
- ip_port = "127.0.0.1:" + str(p2p_port(3))
for i in range(3):
- # The nodes need to be reconnected to the non-pruning node upon restart, otherwise they will be stuck
- restart_args = self.extra_args[i]+["-reindex", f"-connect={ip_port}"]
+ restart_args = self.extra_args[i]+["-reindex"]
self.restart_node(i, extra_args=restart_args)
+ # The nodes need to be reconnected to the non-pruning node upon restart, otherwise they will be stuck
+ self.connect_nodes(i, 3)
self.sync_blocks(timeout=300)
diff --git a/test/functional/feature_minchainwork.py b/test/functional/feature_minchainwork.py
index 489a729cfc..fa10855a98 100755
--- a/test/functional/feature_minchainwork.py
+++ b/test/functional/feature_minchainwork.py
@@ -17,6 +17,7 @@ only succeeds past a given node once its nMinimumChainWork has been exceeded.
import time
+from test_framework.p2p import P2PInterface, msg_getheaders
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
@@ -41,6 +42,9 @@ class MinimumChainWorkTest(BitcoinTestFramework):
for i in range(self.num_nodes-1):
self.connect_nodes(i+1, i)
+ # Set clock of node2 2 days ahead, to keep it in IBD during this test.
+ self.nodes[2].setmocktime(int(time.time()) + 48*60*60)
+
def run_test(self):
# Start building a chain on node0. node2 shouldn't be able to sync until node1's
# minchainwork is exceeded
@@ -71,6 +75,15 @@ class MinimumChainWorkTest(BitcoinTestFramework):
assert self.nodes[1].getbestblockhash() != self.nodes[0].getbestblockhash()
assert_equal(self.nodes[2].getblockcount(), starting_blockcount)
+ self.log.info("Check that getheaders requests to node2 are ignored")
+ peer = self.nodes[2].add_p2p_connection(P2PInterface())
+ msg = msg_getheaders()
+ msg.locator.vHave = [int(self.nodes[2].getbestblockhash(), 16)]
+ msg.hashstop = 0
+ peer.send_and_ping(msg)
+ time.sleep(5)
+ assert "headers" not in peer.last_message
+
self.log.info("Generating one more block")
self.generate(self.nodes[0], 1)
@@ -85,5 +98,21 @@ class MinimumChainWorkTest(BitcoinTestFramework):
self.sync_all()
self.log.info(f"Blockcounts: {[n.getblockcount() for n in self.nodes]}")
+ self.log.info("Test that getheaders requests to node2 are not ignored")
+ peer.send_and_ping(msg)
+ assert "headers" in peer.last_message
+
+ # Verify that node2 is in fact still in IBD (otherwise this test may
+ # not be exercising the logic we want!)
+ assert_equal(self.nodes[2].getblockchaininfo()['initialblockdownload'], True)
+
+ self.log.info("Test -minimumchainwork with a non-hex value")
+ self.stop_node(0)
+ self.nodes[0].assert_start_raises_init_error(
+ ["-minimumchainwork=test"],
+ expected_msg='Error: Invalid non-hex (test) minimum chain work value specified',
+ )
+
+
if __name__ == '__main__':
MinimumChainWorkTest().main()
diff --git a/test/functional/feature_proxy.py b/test/functional/feature_proxy.py
index 8541c3ed88..50e0e2c4cc 100755
--- a/test/functional/feature_proxy.py
+++ b/test/functional/feature_proxy.py
@@ -36,6 +36,7 @@ addnode connect to a CJDNS address
- Test passing invalid -i2psam
- Test passing -onlynet=onion without -proxy or -onion
- Test passing -onlynet=onion with -onion=0 and with -noonion
+- Test passing unknown -onlynet
"""
import socket
@@ -349,6 +350,11 @@ class ProxyTest(BitcoinTestFramework):
self.nodes[1].extra_args = ["-onlynet=onion", arg]
self.nodes[1].assert_start_raises_init_error(expected_msg=msg)
+ self.log.info("Test passing unknown network to -onlynet raises expected init error")
+ self.nodes[1].extra_args = ["-onlynet=abc"]
+ msg = "Error: Unknown network specified in -onlynet: 'abc'"
+ self.nodes[1].assert_start_raises_init_error(expected_msg=msg)
+
if __name__ == '__main__':
ProxyTest().main()
diff --git a/test/functional/mempool_accept.py b/test/functional/mempool_accept.py
index d3961e753d..85464b8d0d 100755
--- a/test/functional/mempool_accept.py
+++ b/test/functional/mempool_accept.py
@@ -76,7 +76,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.vout[0].nValue = int(0.3 * COIN)
tx.vout[1].nValue = int(49 * COIN)
raw_tx_in_block = tx.serialize().hex()
- txid_in_block = self.wallet.sendrawtransaction(from_node=node, tx_hex=raw_tx_in_block, maxfeerate=0)
+ txid_in_block = self.wallet.sendrawtransaction(from_node=node, tx_hex=raw_tx_in_block)
self.generate(node, 1)
self.mempool_size = 0
self.check_mempool_result(
@@ -166,7 +166,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.vin[1].prevout = COutPoint(hash=int(txid_1, 16), n=0)
tx.vout[0].nValue = int(0.1 * COIN)
raw_tx_spend_both = tx.serialize().hex()
- txid_spend_both = self.wallet.sendrawtransaction(from_node=node, tx_hex=raw_tx_spend_both, maxfeerate=0)
+ txid_spend_both = self.wallet.sendrawtransaction(from_node=node, tx_hex=raw_tx_spend_both)
self.generate(node, 1)
self.mempool_size = 0
# Now see if we can add the coins back to the utxo set by sending the exact txs again
diff --git a/test/functional/mempool_packages.py b/test/functional/mempool_packages.py
index 068fdc0b65..a2a2caf324 100755
--- a/test/functional/mempool_packages.py
+++ b/test/functional/mempool_packages.py
@@ -100,6 +100,12 @@ class MempoolPackagesTest(BitcoinTestFramework):
entry = self.nodes[0].getmempoolentry(x)
assert_equal(entry, mempool[x])
+ # Check that gettxspendingprevout is consistent with getrawmempool
+ witnesstx = self.nodes[0].gettransaction(txid=x, verbose=True)['decoded']
+ for tx_in in witnesstx["vin"]:
+ spending_result = self.nodes[0].gettxspendingprevout([ {'txid' : tx_in["txid"], 'vout' : tx_in["vout"]} ])
+ assert_equal(spending_result, [ {'txid' : tx_in["txid"], 'vout' : tx_in["vout"], 'spendingtxid' : x} ])
+
# Check that the descendant calculations are correct
assert_equal(entry['descendantcount'], descendant_count)
descendant_fees += entry['fees']['base']
diff --git a/test/functional/p2p_blockfilters.py b/test/functional/p2p_blockfilters.py
index 2ffc825acd..ef12b5f6b7 100755
--- a/test/functional/p2p_blockfilters.py
+++ b/test/functional/p2p_blockfilters.py
@@ -250,6 +250,11 @@ class CompactFiltersTest(BitcoinTestFramework):
msg = "Error: Cannot set -peerblockfilters without -blockfilterindex."
self.nodes[0].assert_start_raises_init_error(expected_msg=msg)
+ self.log.info("Test unknown value to -blockfilterindex raises an error")
+ self.nodes[0].extra_args = ["-blockfilterindex=abc"]
+ msg = "Error: Unknown -blockfilterindex value abc."
+ self.nodes[0].assert_start_raises_init_error(expected_msg=msg)
+
self.log.info("Test -blockfilterindex with -reindex-chainstate raises an error")
self.nodes[0].assert_start_raises_init_error(
expected_msg='Error: -reindex-chainstate option is not compatible with -blockfilterindex. '
diff --git a/test/functional/p2p_compactblocks.py b/test/functional/p2p_compactblocks.py
index 364e806e18..b9ac3c32c5 100755
--- a/test/functional/p2p_compactblocks.py
+++ b/test/functional/p2p_compactblocks.py
@@ -2,11 +2,7 @@
# Copyright (c) 2016-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
-"""Test compact blocks (BIP 152).
-
-Version 1 compact blocks are pre-segwit (txids)
-Version 2 compact blocks are post-segwit (wtxids)
-"""
+"""Test compact blocks (BIP 152)."""
import random
from test_framework.blocktools import (
@@ -31,7 +27,6 @@ from test_framework.messages import (
MSG_BLOCK,
MSG_CMPCT_BLOCK,
MSG_WITNESS_FLAG,
- NODE_NETWORK,
P2PHeaderAndShortIDs,
PrefilledTransaction,
calculate_shortid,
@@ -70,7 +65,7 @@ from test_framework.wallet import MiniWallet
# TestP2PConn: A peer we use to send messages to bitcoind, and store responses.
class TestP2PConn(P2PInterface):
- def __init__(self, cmpct_version):
+ def __init__(self):
super().__init__()
self.last_sendcmpct = []
self.block_announced = False
@@ -78,7 +73,6 @@ class TestP2PConn(P2PInterface):
# This is for synchronizing the p2p message traffic,
# so we can eg wait until a particular block is announced.
self.announced_blockhashes = set()
- self.cmpct_version = cmpct_version
def on_sendcmpct(self, message):
self.last_sendcmpct.append(message)
@@ -152,10 +146,8 @@ class CompactBlocksTest(BitcoinTestFramework):
]]
self.utxos = []
- def build_block_on_tip(self, node, segwit=False):
+ def build_block_on_tip(self, node):
block = create_block(tmpl=node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS))
- if segwit:
- add_witness_commitment(block)
block.solve()
return block
@@ -185,15 +177,13 @@ class CompactBlocksTest(BitcoinTestFramework):
# Test "sendcmpct" (between peers preferring the same version):
# - No compact block announcements unless sendcmpct is sent.
- # - If sendcmpct is sent with version > preferred_version, the message is ignored.
+ # - If sendcmpct is sent with version = 1, the message is ignored.
+ # - If sendcmpct is sent with version > 2, the message is ignored.
# - If sendcmpct is sent with boolean 0, then block announcements are not
# made with compact blocks.
# - If sendcmpct is then sent with boolean 1, then new block announcements
# are made with compact blocks.
- # If old_node is passed in, request compact blocks with version=preferred-1
- # and verify that it receives block announcements via compact block.
- def test_sendcmpct(self, test_node, old_node=None):
- preferred_version = test_node.cmpct_version
+ def test_sendcmpct(self, test_node):
node = self.nodes[0]
# Make sure we get a SENDCMPCT message from our peer
@@ -201,10 +191,8 @@ class CompactBlocksTest(BitcoinTestFramework):
return (len(test_node.last_sendcmpct) > 0)
test_node.wait_until(received_sendcmpct, timeout=30)
with p2p_lock:
- # Check that the first version received is the preferred one
- assert_equal(test_node.last_sendcmpct[0].version, preferred_version)
- # And that we receive versions down to 1.
- assert_equal(test_node.last_sendcmpct[-1].version, 1)
+ # Check that version 2 is received.
+ assert_equal(test_node.last_sendcmpct[0].version, 2)
test_node.last_sendcmpct = []
tip = int(node.getbestblockhash(), 16)
@@ -232,22 +220,29 @@ class CompactBlocksTest(BitcoinTestFramework):
# Before each test, sync the headers chain.
test_node.request_headers_and_sync(locator=[tip])
+ # Now try a SENDCMPCT message with too-low version
+ test_node.send_and_ping(msg_sendcmpct(announce=True, version=1))
+ check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
+
+ # Headers sync before next test.
+ test_node.request_headers_and_sync(locator=[tip])
+
# Now try a SENDCMPCT message with too-high version
- test_node.send_and_ping(msg_sendcmpct(announce=True, version=preferred_version+1))
+ test_node.send_and_ping(msg_sendcmpct(announce=True, version=3))
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
# Headers sync before next test.
test_node.request_headers_and_sync(locator=[tip])
# Now try a SENDCMPCT message with valid version, but announce=False
- test_node.send_and_ping(msg_sendcmpct(announce=False, version=preferred_version))
+ test_node.send_and_ping(msg_sendcmpct(announce=False, version=2))
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
# Headers sync before next test.
test_node.request_headers_and_sync(locator=[tip])
# Finally, try a SENDCMPCT message with announce=True
- test_node.send_and_ping(msg_sendcmpct(announce=True, version=preferred_version))
+ test_node.send_and_ping(msg_sendcmpct(announce=True, version=2))
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
# Try one more time (no headers sync should be needed!)
@@ -257,22 +252,14 @@ class CompactBlocksTest(BitcoinTestFramework):
test_node.send_and_ping(msg_sendheaders())
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
- # Try one more time, after sending a version-1, announce=false message.
- test_node.send_and_ping(msg_sendcmpct(announce=False, version=preferred_version-1))
+ # Try one more time, after sending a version=1, announce=false message.
+ test_node.send_and_ping(msg_sendcmpct(announce=False, version=1))
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
# Now turn off announcements
- test_node.send_and_ping(msg_sendcmpct(announce=False, version=preferred_version))
+ test_node.send_and_ping(msg_sendcmpct(announce=False, version=2))
check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message and "headers" in p.last_message)
- if old_node is not None:
- # Verify that a peer using an older protocol version can receive
- # announcements from this node.
- old_node.send_and_ping(msg_sendcmpct(announce=True, version=preferred_version-1))
- # Header sync
- old_node.request_headers_and_sync(locator=[tip])
- check_announcement_of_new_block(node, old_node, lambda p: "cmpctblock" in p.last_message)
-
# This test actually causes bitcoind to (reasonably!) disconnect us, so do this last.
def test_invalid_cmpctblock_message(self):
self.generate(self.nodes[0], COINBASE_MATURITY + 1)
@@ -289,8 +276,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Compare the generated shortids to what we expect based on BIP 152, given
# bitcoind's choice of nonce.
- def test_compactblock_construction(self, test_node, use_witness_address=True):
- version = test_node.cmpct_version
+ def test_compactblock_construction(self, test_node):
node = self.nodes[0]
# Generate a bunch of transactions.
self.generate(node, COINBASE_MATURITY + 1)
@@ -303,8 +289,7 @@ class CompactBlocksTest(BitcoinTestFramework):
if not tx.wit.is_null():
segwit_tx_generated = True
- if use_witness_address:
- assert segwit_tx_generated # check that our test is not broken
+ assert segwit_tx_generated # check that our test is not broken
# Wait until we've seen the block announcement for the resulting tip
tip = int(node.getbestblockhash(), 16)
@@ -331,7 +316,7 @@ class CompactBlocksTest(BitcoinTestFramework):
with p2p_lock:
# Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids)
- self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block)
+ self.check_compactblock_construction_from_block(header_and_shortids, block_hash, block)
# Now fetch the compact block using a normal non-announce getdata
test_node.clear_block_announcement()
@@ -345,9 +330,9 @@ class CompactBlocksTest(BitcoinTestFramework):
with p2p_lock:
# Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids)
- self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block)
+ self.check_compactblock_construction_from_block(header_and_shortids, block_hash, block)
- def check_compactblock_construction_from_block(self, version, header_and_shortids, block_hash, block):
+ def check_compactblock_construction_from_block(self, header_and_shortids, block_hash, block):
# Check that we got the right block!
header_and_shortids.header.calc_sha256()
assert_equal(header_and_shortids.header.sha256, block_hash)
@@ -364,11 +349,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# And this checks the witness
wtxid = entry.tx.calc_sha256(True)
- if version == 2:
- assert_equal(wtxid, block.vtx[entry.index].calc_sha256(True))
- else:
- # Shouldn't have received a witness
- assert entry.tx.wit.is_null()
+ assert_equal(wtxid, block.vtx[entry.index].calc_sha256(True))
# Check that the cmpctblock message announced all the transactions.
assert_equal(len(header_and_shortids.prefilled_txn) + len(header_and_shortids.shortids), len(block.vtx))
@@ -384,9 +365,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Already checked prefilled transactions above
header_and_shortids.prefilled_txn.pop(0)
else:
- tx_hash = block.vtx[index].sha256
- if version == 2:
- tx_hash = block.vtx[index].calc_sha256(True)
+ tx_hash = block.vtx[index].calc_sha256(True)
shortid = calculate_shortid(k0, k1, tx_hash)
assert_equal(shortid, header_and_shortids.shortids[0])
header_and_shortids.shortids.pop(0)
@@ -395,16 +374,12 @@ class CompactBlocksTest(BitcoinTestFramework):
# Test that bitcoind requests compact blocks when we announce new blocks
# via header or inv, and that responding to getblocktxn causes the block
# to be successfully reconstructed.
- # Post-segwit: upgraded nodes would only make this request of cb-version-2,
- # NODE_WITNESS peers. Unupgraded nodes would still make this request of
- # any cb-version-1-supporting peer.
- def test_compactblock_requests(self, test_node, segwit=True):
- version = test_node.cmpct_version
+ def test_compactblock_requests(self, test_node):
node = self.nodes[0]
# Try announcing a block with an inv or header, expect a compactblock
# request
for announce in ["inv", "header"]:
- block = self.build_block_on_tip(node, segwit=segwit)
+ block = self.build_block_on_tip(node)
if announce == "inv":
test_node.send_message(msg_inv([CInv(MSG_BLOCK, block.sha256)]))
@@ -420,9 +395,7 @@ class CompactBlocksTest(BitcoinTestFramework):
comp_block.header = CBlockHeader(block)
comp_block.nonce = 0
[k0, k1] = comp_block.get_siphash_keys()
- coinbase_hash = block.vtx[0].sha256
- if version == 2:
- coinbase_hash = block.vtx[0].calc_sha256(True)
+ coinbase_hash = block.vtx[0].calc_sha256(True)
comp_block.shortids = [calculate_shortid(k0, k1, coinbase_hash)]
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
@@ -433,10 +406,7 @@ class CompactBlocksTest(BitcoinTestFramework):
assert_equal(absolute_indexes, [0]) # should be a coinbase request
# Send the coinbase, and verify that the tip advances.
- if version == 2:
- msg = msg_blocktxn()
- else:
- msg = msg_no_witness_blocktxn()
+ msg = msg_blocktxn()
msg.block_transactions.blockhash = block.sha256
msg.block_transactions.transactions = [block.vtx[0]]
test_node.send_and_ping(msg)
@@ -462,9 +432,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# node needs, and that responding to them causes the block to be
# reconstructed.
def test_getblocktxn_requests(self, test_node):
- version = test_node.cmpct_version
node = self.nodes[0]
- with_witness = (version == 2)
def test_getblocktxn_response(compact_block, peer, expected_result):
msg = msg_cmpctblock(compact_block.to_p2p())
@@ -485,13 +453,12 @@ class CompactBlocksTest(BitcoinTestFramework):
block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
comp_block = HeaderAndShortIDs()
- comp_block.initialize_from_block(block, use_witness=with_witness)
+ comp_block.initialize_from_block(block, use_witness=True)
test_getblocktxn_response(comp_block, test_node, [1, 2, 3, 4, 5])
msg_bt = msg_no_witness_blocktxn()
- if with_witness:
- msg_bt = msg_blocktxn() # serialize with witnesses
+ msg_bt = msg_blocktxn() # serialize with witnesses
msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[1:])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
@@ -500,7 +467,7 @@ class CompactBlocksTest(BitcoinTestFramework):
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
# Now try interspersing the prefilled transactions
- comp_block.initialize_from_block(block, prefill_list=[0, 1, 5], use_witness=with_witness)
+ comp_block.initialize_from_block(block, prefill_list=[0, 1, 5], use_witness=True)
test_getblocktxn_response(comp_block, test_node, [2, 3, 4])
msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[2:5])
test_tip_after_message(node, test_node, msg_bt, block.sha256)
@@ -514,7 +481,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Prefill 4 out of the 6 transactions, and verify that only the one
# that was not in the mempool is requested.
- comp_block.initialize_from_block(block, prefill_list=[0, 2, 3, 4], use_witness=with_witness)
+ comp_block.initialize_from_block(block, prefill_list=[0, 2, 3, 4], use_witness=True)
test_getblocktxn_response(comp_block, test_node, [5])
msg_bt.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]])
@@ -538,7 +505,7 @@ class CompactBlocksTest(BitcoinTestFramework):
test_node.last_message.pop("getblocktxn", None)
# Send compact block
- comp_block.initialize_from_block(block, prefill_list=[0], use_witness=with_witness)
+ comp_block.initialize_from_block(block, prefill_list=[0], use_witness=True)
test_tip_after_message(node, test_node, msg_cmpctblock(comp_block.to_p2p()), block.sha256)
with p2p_lock:
# Shouldn't have gotten a request for any transaction
@@ -547,7 +514,6 @@ class CompactBlocksTest(BitcoinTestFramework):
# Incorrectly responding to a getblocktxn shouldn't cause the block to be
# permanently failed.
def test_incorrect_blocktxn_response(self, test_node):
- version = test_node.cmpct_version
node = self.nodes[0]
utxo = self.utxos.pop(0)
@@ -564,7 +530,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Send compact block
comp_block = HeaderAndShortIDs()
- comp_block.initialize_from_block(block, prefill_list=[0], use_witness=(version == 2))
+ comp_block.initialize_from_block(block, prefill_list=[0], use_witness=True)
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
absolute_indexes = []
with p2p_lock:
@@ -580,9 +546,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# different peer provide the block further down, so that we're still
# verifying that the block isn't marked bad permanently. This is good
# enough for now.
- msg = msg_no_witness_blocktxn()
- if version == 2:
- msg = msg_blocktxn()
+ msg = msg_blocktxn()
msg.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]] + block.vtx[7:])
test_node.send_and_ping(msg)
@@ -595,14 +559,10 @@ class CompactBlocksTest(BitcoinTestFramework):
test_node.last_message["getdata"].inv[0].type == MSG_BLOCK | MSG_WITNESS_FLAG
# Deliver the block
- if version == 2:
- test_node.send_and_ping(msg_block(block))
- else:
- test_node.send_and_ping(msg_no_witness_block(block))
+ test_node.send_and_ping(msg_block(block))
assert_equal(int(node.getbestblockhash(), 16), block.sha256)
def test_getblocktxn_handler(self, test_node):
- version = test_node.cmpct_version
node = self.nodes[0]
# bitcoind will not send blocktxn responses for blocks whose height is
# more than 10 blocks deep.
@@ -628,12 +588,8 @@ class CompactBlocksTest(BitcoinTestFramework):
tx = test_node.last_message["blocktxn"].block_transactions.transactions.pop(0)
tx.calc_sha256()
assert_equal(tx.sha256, block.vtx[index].sha256)
- if version == 1:
- # Witnesses should have been stripped
- assert tx.wit.is_null()
- else:
- # Check that the witness matches
- assert_equal(tx.calc_sha256(True), block.vtx[index].calc_sha256(True))
+ # Check that the witness matches
+ assert_equal(tx.calc_sha256(True), block.vtx[index].calc_sha256(True))
test_node.last_message.pop("blocktxn", None)
current_height -= 1
@@ -727,7 +683,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Test that we don't get disconnected if we relay a compact block with valid header,
# but invalid transactions.
- def test_invalid_tx_in_compactblock(self, test_node, use_segwit=True):
+ def test_invalid_tx_in_compactblock(self, test_node):
node = self.nodes[0]
assert len(self.utxos)
utxo = self.utxos[0]
@@ -735,17 +691,15 @@ class CompactBlocksTest(BitcoinTestFramework):
block = self.build_block_with_transactions(node, utxo, 5)
del block.vtx[3]
block.hashMerkleRoot = block.calc_merkle_root()
- if use_segwit:
- # If we're testing with segwit, also drop the coinbase witness,
- # but include the witness commitment.
- add_witness_commitment(block)
- block.vtx[0].wit.vtxinwit = []
+ # Drop the coinbase witness but include the witness commitment.
+ add_witness_commitment(block)
+ block.vtx[0].wit.vtxinwit = []
block.solve()
# Now send the compact block with all transactions prefilled, and
# verify that we don't get disconnected.
comp_block = HeaderAndShortIDs()
- comp_block.initialize_from_block(block, prefill_list=[0, 1, 2, 3, 4], use_witness=use_segwit)
+ comp_block.initialize_from_block(block, prefill_list=[0, 1, 2, 3, 4], use_witness=True)
msg = msg_cmpctblock(comp_block.to_p2p())
test_node.send_and_ping(msg)
@@ -759,7 +713,7 @@ class CompactBlocksTest(BitcoinTestFramework):
node = self.nodes[0]
tip = node.getbestblockhash()
peer.get_headers(locator=[int(tip, 16)], hashstop=0)
- peer.send_and_ping(msg_sendcmpct(announce=True, version=peer.cmpct_version))
+ peer.send_and_ping(msg_sendcmpct(announce=True, version=2))
def test_compactblock_reconstruction_multiple_peers(self, stalling_peer, delivery_peer):
node = self.nodes[0]
@@ -813,7 +767,7 @@ class CompactBlocksTest(BitcoinTestFramework):
def test_highbandwidth_mode_states_via_getpeerinfo(self):
# create new p2p connection for a fresh state w/o any prior sendcmpct messages sent
- hb_test_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=2))
+ hb_test_node = self.nodes[0].add_p2p_connection(TestP2PConn())
# assert the RPC getpeerinfo boolean fields `bip152_hb_{to, from}`
# match the given parameters for the last peer of a given node
@@ -843,9 +797,8 @@ class CompactBlocksTest(BitcoinTestFramework):
self.wallet = MiniWallet(self.nodes[0])
# Setup the p2p connections
- self.segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=2))
- self.old_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=1), services=NODE_NETWORK)
- self.additional_segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn(cmpct_version=2))
+ self.segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn())
+ self.additional_segwit_node = self.nodes[0].add_p2p_connection(TestP2PConn())
# We will need UTXOs to construct transactions in later tests.
self.make_utxos()
@@ -853,11 +806,10 @@ class CompactBlocksTest(BitcoinTestFramework):
assert softfork_active(self.nodes[0], "segwit")
self.log.info("Testing SENDCMPCT p2p message... ")
- self.test_sendcmpct(self.segwit_node, old_node=self.old_node)
+ self.test_sendcmpct(self.segwit_node)
self.test_sendcmpct(self.additional_segwit_node)
self.log.info("Testing compactblock construction...")
- self.test_compactblock_construction(self.old_node)
self.test_compactblock_construction(self.segwit_node)
self.log.info("Testing compactblock requests (segwit node)... ")
@@ -868,11 +820,9 @@ class CompactBlocksTest(BitcoinTestFramework):
self.log.info("Testing getblocktxn handler (segwit node should return witnesses)...")
self.test_getblocktxn_handler(self.segwit_node)
- self.test_getblocktxn_handler(self.old_node)
self.log.info("Testing compactblock requests/announcements not at chain tip...")
self.test_compactblocks_not_at_tip(self.segwit_node)
- self.test_compactblocks_not_at_tip(self.old_node)
self.log.info("Testing handling of incorrect blocktxn responses...")
self.test_incorrect_blocktxn_response(self.segwit_node)
@@ -885,13 +835,12 @@ class CompactBlocksTest(BitcoinTestFramework):
# (Post-segwit activation, blocks won't propagate from node0 to node1
# automatically, so don't bother testing a block announced to node0.)
self.log.info("Testing end-to-end block relay...")
- self.request_cb_announcements(self.old_node)
self.request_cb_announcements(self.segwit_node)
- self.test_end_to_end_block_relay([self.segwit_node, self.old_node])
+ self.request_cb_announcements(self.additional_segwit_node)
+ self.test_end_to_end_block_relay([self.segwit_node, self.additional_segwit_node])
self.log.info("Testing handling of invalid compact blocks...")
self.test_invalid_tx_in_compactblock(self.segwit_node)
- self.test_invalid_tx_in_compactblock(self.old_node)
self.log.info("Testing invalid index in cmpctblock message...")
self.test_invalid_cmpctblock_message()
diff --git a/test/functional/p2p_compactblocks_blocksonly.py b/test/functional/p2p_compactblocks_blocksonly.py
index 6367eb26a3..3d0c421a93 100755
--- a/test/functional/p2p_compactblocks_blocksonly.py
+++ b/test/functional/p2p_compactblocks_blocksonly.py
@@ -48,7 +48,7 @@ class P2PCompactBlocksBlocksOnly(BitcoinTestFramework):
p2p_conn_high_bw = self.nodes[1].add_p2p_connection(P2PInterface())
p2p_conn_low_bw = self.nodes[3].add_p2p_connection(P2PInterface())
for conn in [p2p_conn_blocksonly, p2p_conn_high_bw, p2p_conn_low_bw]:
- assert_equal(conn.message_count['sendcmpct'], 2)
+ assert_equal(conn.message_count['sendcmpct'], 1)
conn.send_and_ping(msg_sendcmpct(announce=False, version=2))
# Nodes:
@@ -74,14 +74,14 @@ class P2PCompactBlocksBlocksOnly(BitcoinTestFramework):
# receiving a new valid block at the tip.
p2p_conn_blocksonly.send_and_ping(msg_block(block0))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), block0.sha256)
- assert_equal(p2p_conn_blocksonly.message_count['sendcmpct'], 2)
+ assert_equal(p2p_conn_blocksonly.message_count['sendcmpct'], 1)
assert_equal(p2p_conn_blocksonly.last_message['sendcmpct'].announce, False)
# A normal node participating in transaction relay should request BIP152
# high bandwidth mode upon receiving a new valid block at the tip.
p2p_conn_high_bw.send_and_ping(msg_block(block0))
assert_equal(int(self.nodes[1].getbestblockhash(), 16), block0.sha256)
- p2p_conn_high_bw.wait_until(lambda: p2p_conn_high_bw.message_count['sendcmpct'] == 3)
+ p2p_conn_high_bw.wait_until(lambda: p2p_conn_high_bw.message_count['sendcmpct'] == 2)
assert_equal(p2p_conn_high_bw.last_message['sendcmpct'].announce, True)
# Don't send a block from the p2p_conn_low_bw so the low bandwidth node
diff --git a/test/functional/p2p_unrequested_blocks.py b/test/functional/p2p_unrequested_blocks.py
index 9c4e1dd1b1..76d9b045ce 100755
--- a/test/functional/p2p_unrequested_blocks.py
+++ b/test/functional/p2p_unrequested_blocks.py
@@ -257,16 +257,11 @@ class AcceptBlockTest(BitcoinTestFramework):
test_node.send_message(msg_block(block_291))
# At this point we've sent an obviously-bogus block, wait for full processing
- # without assuming whether we will be disconnected or not
- try:
- # Only wait a short while so the test doesn't take forever if we do get
- # disconnected
- test_node.sync_with_ping(timeout=1)
- except AssertionError:
- test_node.wait_for_disconnect()
-
- self.nodes[0].disconnect_p2ps()
- test_node = self.nodes[0].add_p2p_connection(P2PInterface())
+ # and assume disconnection
+ test_node.wait_for_disconnect()
+
+ self.nodes[0].disconnect_p2ps()
+ test_node = self.nodes[0].add_p2p_connection(P2PInterface())
# We should have failed reorg and switched back to 290 (but have block 291)
assert_equal(self.nodes[0].getblockcount(), 290)
diff --git a/test/functional/rpc_getblockfrompeer.py b/test/functional/rpc_getblockfrompeer.py
index b65322d920..a7628b5591 100755
--- a/test/functional/rpc_getblockfrompeer.py
+++ b/test/functional/rpc_getblockfrompeer.py
@@ -5,6 +5,11 @@
"""Test the getblockfrompeer RPC."""
from test_framework.authproxy import JSONRPCException
+from test_framework.messages import NODE_WITNESS
+from test_framework.p2p import (
+ P2P_SERVICES,
+ P2PInterface,
+)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
@@ -58,6 +63,13 @@ class GetBlockFromPeerTest(BitcoinTestFramework):
self.log.info("Non-existent peer generates error")
assert_raises_rpc_error(-1, "Peer does not exist", self.nodes[0].getblockfrompeer, short_tip, peer_0_peer_1_id + 1)
+ self.log.info("Fetching from pre-segwit peer generates error")
+ self.nodes[0].add_p2p_connection(P2PInterface(), services=P2P_SERVICES & ~NODE_WITNESS)
+ peers = self.nodes[0].getpeerinfo()
+ assert_equal(len(peers), 2)
+ presegwit_peer_id = peers[1]["id"]
+ assert_raises_rpc_error(-1, "Pre-SegWit peer", self.nodes[0].getblockfrompeer, short_tip, presegwit_peer_id)
+
self.log.info("Successful fetch")
result = self.nodes[0].getblockfrompeer(short_tip, peer_0_peer_1_id)
self.wait_until(lambda: self.check_for_block(short_tip), timeout=1)
@@ -66,5 +78,6 @@ class GetBlockFromPeerTest(BitcoinTestFramework):
self.log.info("Don't fetch blocks we already have")
assert_raises_rpc_error(-1, "Block already downloaded", self.nodes[0].getblockfrompeer, short_tip, peer_0_peer_1_id)
+
if __name__ == '__main__':
GetBlockFromPeerTest().main()
diff --git a/test/functional/rpc_mempool_entry_fee_fields_deprecation.py b/test/functional/rpc_mempool_entry_fee_fields_deprecation.py
deleted file mode 100755
index 82761ff7c8..0000000000
--- a/test/functional/rpc_mempool_entry_fee_fields_deprecation.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) 2021 The Bitcoin Core developers
-# Distributed under the MIT software license, see the accompanying
-# file COPYING or http://www.opensource.org/licenses/mit-license.php.
-"""Test deprecation of fee fields from top level mempool entry object"""
-
-from test_framework.blocktools import COIN
-from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import assert_equal
-from test_framework.wallet import MiniWallet
-
-
-def assertions_helper(new_object, deprecated_object, deprecated_fields):
- for field in deprecated_fields:
- assert field in deprecated_object
- assert field not in new_object
-
-
-class MempoolFeeFieldsDeprecationTest(BitcoinTestFramework):
- def set_test_params(self):
- self.num_nodes = 2
- self.extra_args = [[], ["-deprecatedrpc=fees"]]
-
- def run_test(self):
- # we get spendable outputs from the premined chain starting
- # at block 76. see BitcoinTestFramework._initialize_chain() for details
- self.wallet = MiniWallet(self.nodes[0])
- self.wallet.rescan_utxos()
-
- # we create the tx on the first node and wait until it syncs to node_deprecated
- # thus, any differences must be coming from getmempoolentry or getrawmempool
- tx = self.wallet.send_self_transfer(from_node=self.nodes[0])
- self.nodes[1].sendrawtransaction(tx["hex"])
-
- deprecated_fields = ["ancestorfees", "descendantfees", "modifiedfee", "fee"]
- self.test_getmempoolentry(tx["txid"], deprecated_fields)
- self.test_getrawmempool(tx["txid"], deprecated_fields)
- self.test_deprecated_fields_match(tx["txid"])
-
- def test_getmempoolentry(self, txid, deprecated_fields):
-
- self.log.info("Test getmempoolentry rpc")
- entry = self.nodes[0].getmempoolentry(txid)
- deprecated_entry = self.nodes[1].getmempoolentry(txid)
- assertions_helper(entry, deprecated_entry, deprecated_fields)
-
- def test_getrawmempool(self, txid, deprecated_fields):
-
- self.log.info("Test getrawmempool rpc")
- entry = self.nodes[0].getrawmempool(verbose=True)[txid]
- deprecated_entry = self.nodes[1].getrawmempool(verbose=True)[txid]
- assertions_helper(entry, deprecated_entry, deprecated_fields)
-
- def test_deprecated_fields_match(self, txid):
-
- self.log.info("Test deprecated fee fields match new fees object")
- entry = self.nodes[0].getmempoolentry(txid)
- deprecated_entry = self.nodes[1].getmempoolentry(txid)
-
- assert_equal(deprecated_entry["fee"], entry["fees"]["base"])
- assert_equal(deprecated_entry["modifiedfee"], entry["fees"]["modified"])
- assert_equal(deprecated_entry["descendantfees"], entry["fees"]["descendant"] * COIN)
- assert_equal(deprecated_entry["ancestorfees"], entry["fees"]["ancestor"] * COIN)
-
-
-if __name__ == "__main__":
- MempoolFeeFieldsDeprecationTest().main()
diff --git a/test/functional/rpc_mempool_info.py b/test/functional/rpc_mempool_info.py
new file mode 100755
index 0000000000..cd7a48d387
--- /dev/null
+++ b/test/functional/rpc_mempool_info.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+# Copyright (c) 2014-2022 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test RPCs that retrieve information from the mempool."""
+
+from test_framework.blocktools import COINBASE_MATURITY
+from test_framework.test_framework import BitcoinTestFramework
+from test_framework.util import (
+ assert_equal,
+ assert_raises_rpc_error,
+)
+from test_framework.wallet import MiniWallet
+
+
+class RPCMempoolInfoTest(BitcoinTestFramework):
+ def set_test_params(self):
+ self.num_nodes = 1
+
+ def run_test(self):
+ self.wallet = MiniWallet(self.nodes[0])
+ self.generate(self.wallet, COINBASE_MATURITY + 1)
+ self.wallet.rescan_utxos()
+ confirmed_utxo = self.wallet.get_utxo()
+
+ # Create a tree of unconfirmed transactions in the mempool:
+ # txA
+ # / \
+ # / \
+ # / \
+ # / \
+ # / \
+ # txB txC
+ # / \ / \
+ # / \ / \
+ # txD txE txF txG
+ # \ /
+ # \ /
+ # txH
+
+ def create_tx(**kwargs):
+ return self.wallet.send_self_transfer_multi(
+ from_node=self.nodes[0],
+ **kwargs,
+ )
+
+ txA = create_tx(utxos_to_spend=[confirmed_utxo], num_outputs=2)
+ txB = create_tx(utxos_to_spend=[txA["new_utxos"][0]], num_outputs=2)
+ txC = create_tx(utxos_to_spend=[txA["new_utxos"][1]], num_outputs=2)
+ txD = create_tx(utxos_to_spend=[txB["new_utxos"][0]], num_outputs=1)
+ txE = create_tx(utxos_to_spend=[txB["new_utxos"][1]], num_outputs=1)
+ txF = create_tx(utxos_to_spend=[txC["new_utxos"][0]], num_outputs=2)
+ txG = create_tx(utxos_to_spend=[txC["new_utxos"][1]], num_outputs=1)
+ txH = create_tx(utxos_to_spend=[txE["new_utxos"][0],txF["new_utxos"][0]], num_outputs=1)
+ txidA, txidB, txidC, txidD, txidE, txidF, txidG, txidH = [
+ tx["txid"] for tx in [txA, txB, txC, txD, txE, txF, txG, txH]
+ ]
+
+ mempool = self.nodes[0].getrawmempool()
+ assert_equal(len(mempool), 8)
+ for txid in [txidA, txidB, txidC, txidD, txidE, txidF, txidG, txidH]:
+ assert_equal(txid in mempool, True)
+
+ self.log.info("Find transactions spending outputs")
+ result = self.nodes[0].gettxspendingprevout([ {'txid' : confirmed_utxo['txid'], 'vout' : 0}, {'txid' : txidA, 'vout' : 1} ])
+ assert_equal(result, [ {'txid' : confirmed_utxo['txid'], 'vout' : 0, 'spendingtxid' : txidA}, {'txid' : txidA, 'vout' : 1, 'spendingtxid' : txidC} ])
+
+ self.log.info("Find transaction spending multiple outputs")
+ result = self.nodes[0].gettxspendingprevout([ {'txid' : txidE, 'vout' : 0}, {'txid' : txidF, 'vout' : 0} ])
+ assert_equal(result, [ {'txid' : txidE, 'vout' : 0, 'spendingtxid' : txidH}, {'txid' : txidF, 'vout' : 0, 'spendingtxid' : txidH} ])
+
+ self.log.info("Find no transaction when output is unspent")
+ result = self.nodes[0].gettxspendingprevout([ {'txid' : txidH, 'vout' : 0} ])
+ assert_equal(result, [ {'txid' : txidH, 'vout' : 0} ])
+ result = self.nodes[0].gettxspendingprevout([ {'txid' : txidA, 'vout' : 5} ])
+ assert_equal(result, [ {'txid' : txidA, 'vout' : 5} ])
+
+ self.log.info("Mixed spent and unspent outputs")
+ result = self.nodes[0].gettxspendingprevout([ {'txid' : txidB, 'vout' : 0}, {'txid' : txidG, 'vout' : 3} ])
+ assert_equal(result, [ {'txid' : txidB, 'vout' : 0, 'spendingtxid' : txidD}, {'txid' : txidG, 'vout' : 3} ])
+
+ self.log.info("Unknown input fields")
+ assert_raises_rpc_error(-3, "Unexpected key unknown", self.nodes[0].gettxspendingprevout, [{'txid' : txidC, 'vout' : 1, 'unknown' : 42}])
+
+ self.log.info("Invalid vout provided")
+ assert_raises_rpc_error(-8, "Invalid parameter, vout cannot be negative", self.nodes[0].gettxspendingprevout, [{'txid' : txidA, 'vout' : -1}])
+
+ self.log.info("Invalid txid provided")
+ assert_raises_rpc_error(-3, "Expected type string for txid, got number", self.nodes[0].gettxspendingprevout, [{'txid' : 42, 'vout' : 0}])
+
+ self.log.info("Missing outputs")
+ assert_raises_rpc_error(-8, "Invalid parameter, outputs are missing", self.nodes[0].gettxspendingprevout, [])
+
+ self.log.info("Missing vout")
+ assert_raises_rpc_error(-3, "Missing vout", self.nodes[0].gettxspendingprevout, [{'txid' : txidA}])
+
+ self.log.info("Missing txid")
+ assert_raises_rpc_error(-3, "Missing txid", self.nodes[0].gettxspendingprevout, [{'vout' : 3}])
+
+
+if __name__ == '__main__':
+ RPCMempoolInfoTest().main()
diff --git a/test/functional/rpc_net.py b/test/functional/rpc_net.py
index 81a3cfee97..ad8ba06824 100755
--- a/test/functional/rpc_net.py
+++ b/test/functional/rpc_net.py
@@ -257,6 +257,10 @@ class NetTest(BitcoinTestFramework):
assert_equal(node.addpeeraddress(address="", port=8333), {"success": False})
assert_equal(node.getnodeaddresses(count=0), [])
+ self.log.debug("Test that adding an address with invalid port fails")
+ assert_raises_rpc_error(-1, "JSON integer out of range", self.nodes[0].addpeeraddress, address="1.2.3.4", port=-1)
+ assert_raises_rpc_error(-1, "JSON integer out of range", self.nodes[0].addpeeraddress,address="1.2.3.4", port=65536)
+
self.log.debug("Test that adding a valid address to the tried table succeeds")
assert_equal(node.addpeeraddress(address="1.2.3.4", tried=True, port=8333), {"success": True})
with node.assert_debug_log(expected_msgs=["CheckAddrman: new 0, tried 1, total 1 started"]):
diff --git a/test/functional/rpc_rawtransaction.py b/test/functional/rpc_rawtransaction.py
index a839af0288..1f95814e18 100755
--- a/test/functional/rpc_rawtransaction.py
+++ b/test/functional/rpc_rawtransaction.py
@@ -17,6 +17,7 @@ from decimal import Decimal
from test_framework.blocktools import COINBASE_MATURITY
from test_framework.messages import (
+ BIP125_SEQUENCE_NUMBER,
CTransaction,
tx_from_hex,
)
@@ -24,7 +25,10 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
- find_vout_for_address,
+)
+from test_framework.wallet import (
+ getnewdestination,
+ MiniWallet,
)
@@ -52,79 +56,67 @@ class multidict(dict):
class RawTransactionsTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
- self.num_nodes = 4
+ self.num_nodes = 3
self.extra_args = [
["-txindex"],
["-txindex"],
- ["-txindex"],
[],
]
# whitelist all peers to speed up tx relay / mempool sync
for args in self.extra_args:
args.append("-whitelist=noban@127.0.0.1")
+ self.requires_wallet = self.is_specified_wallet_compiled()
self.supports_cli = False
- def skip_test_if_missing_module(self):
- self.skip_if_no_wallet()
-
def setup_network(self):
super().setup_network()
self.connect_nodes(0, 2)
def run_test(self):
+ self.wallet = MiniWallet(self.nodes[0])
self.log.info("Prepare some coins for multiple *rawtransaction commands")
- self.generate(self.nodes[2], 1)
+ self.generate(self.wallet, 10)
self.generate(self.nodes[0], COINBASE_MATURITY + 1)
- for amount in [1.5, 1.0, 5.0]:
- self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), amount)
- self.sync_all()
- self.generate(self.nodes[0], 5)
self.getrawtransaction_tests()
self.createrawtransaction_tests()
- self.signrawtransactionwithwallet_tests()
self.sendrawtransaction_tests()
self.sendrawtransaction_testmempoolaccept_tests()
self.decoderawtransaction_tests()
self.transaction_version_number_tests()
- if not self.options.descriptors:
+ if self.requires_wallet and not self.options.descriptors:
self.raw_multisig_transaction_legacy_tests()
def getrawtransaction_tests(self):
- addr = self.nodes[1].getnewaddress()
- txid = self.nodes[0].sendtoaddress(addr, 10)
+ tx = self.wallet.send_self_transfer(from_node=self.nodes[0])
self.generate(self.nodes[0], 1)
- vout = find_vout_for_address(self.nodes[1], txid, addr)
- rawTx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {self.nodes[1].getnewaddress(): 9.999})
- rawTxSigned = self.nodes[1].signrawtransactionwithwallet(rawTx)
- txId = self.nodes[1].sendrawtransaction(rawTxSigned['hex'])
- self.generateblock(self.nodes[0], output=self.nodes[0].getnewaddress(), transactions=[rawTxSigned['hex']])
+ txId = tx['txid']
err_msg = (
"No such mempool transaction. Use -txindex or provide a block hash to enable"
" blockchain transaction queries. Use gettransaction for wallet transactions."
)
- for n in [0, 3]:
+ for n in [0, 2]:
self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex")
if n == 0:
# With -txindex.
# 1. valid parameters - only supply txid
- assert_equal(self.nodes[n].getrawtransaction(txId), rawTxSigned['hex'])
+ assert_equal(self.nodes[n].getrawtransaction(txId), tx['hex'])
# 2. valid parameters - supply txid and 0 for non-verbose
- assert_equal(self.nodes[n].getrawtransaction(txId, 0), rawTxSigned['hex'])
+ assert_equal(self.nodes[n].getrawtransaction(txId, 0), tx['hex'])
# 3. valid parameters - supply txid and False for non-verbose
- assert_equal(self.nodes[n].getrawtransaction(txId, False), rawTxSigned['hex'])
+ assert_equal(self.nodes[n].getrawtransaction(txId, False), tx['hex'])
# 4. valid parameters - supply txid and 1 for verbose.
# We only check the "hex" field of the output so we don't need to update this test every time the output format changes.
- assert_equal(self.nodes[n].getrawtransaction(txId, 1)["hex"], rawTxSigned['hex'])
+ assert_equal(self.nodes[n].getrawtransaction(txId, 1)["hex"], tx['hex'])
# 5. valid parameters - supply txid and True for non-verbose
- assert_equal(self.nodes[n].getrawtransaction(txId, True)["hex"], rawTxSigned['hex'])
+ assert_equal(self.nodes[n].getrawtransaction(txId, True)["hex"], tx['hex'])
else:
# Without -txindex, expect to raise.
for verbose in [None, 0, False, 1, True]:
@@ -141,9 +133,9 @@ class RawTransactionsTest(BitcoinTestFramework):
assert_raises_rpc_error(-1, "not a boolean", self.nodes[n].getrawtransaction, txId, {})
# Make a tx by sending, then generate 2 blocks; block1 has the tx in it
- tx = self.nodes[2].sendtoaddress(self.nodes[1].getnewaddress(), 1)
+ tx = self.wallet.send_self_transfer(from_node=self.nodes[2])['txid']
block1, block2 = self.generate(self.nodes[2], 2)
- for n in [0, 3]:
+ for n in [0, 2]:
self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex, with blockhash")
# We should be able to get the raw transaction by providing the correct block
gottx = self.nodes[n].getrawtransaction(txid=tx, verbose=True, blockhash=block1)
@@ -200,20 +192,21 @@ class RawTransactionsTest(BitcoinTestFramework):
# sequence number out of range
for invalid_seq in [-1, 4294967296]:
inputs = [{'txid': TXID, 'vout': 1, 'sequence': invalid_seq}]
- outputs = {self.nodes[0].getnewaddress(): 1}
+ address = getnewdestination()[2]
+ outputs = {address: 1}
assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range',
self.nodes[0].createrawtransaction, inputs, outputs)
# with valid sequence number
for valid_seq in [1000, 4294967294]:
inputs = [{'txid': TXID, 'vout': 1, 'sequence': valid_seq}]
- outputs = {self.nodes[0].getnewaddress(): 1}
+ address = getnewdestination()[2]
+ outputs = {address: 1}
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
decrawtx = self.nodes[0].decoderawtransaction(rawtx)
assert_equal(decrawtx['vin'][0]['sequence'], valid_seq)
# Test `createrawtransaction` invalid `outputs`
- address = self.nodes[0].getnewaddress()
- address2 = self.nodes[0].getnewaddress()
+ address = getnewdestination()[2]
assert_raises_rpc_error(-1, "JSON value is not an array as expected", self.nodes[0].createrawtransaction, [], 'foo')
self.nodes[0].createrawtransaction(inputs=[], outputs={}) # Should not throw for backwards compatibility
self.nodes[0].createrawtransaction(inputs=[], outputs=[])
@@ -228,6 +221,10 @@ class RawTransactionsTest(BitcoinTestFramework):
assert_raises_rpc_error(-8, "Invalid parameter, key-value pair must contain exactly one key", self.nodes[0].createrawtransaction, [], [{'a': 1, 'b': 2}])
assert_raises_rpc_error(-8, "Invalid parameter, key-value pair not an object as expected", self.nodes[0].createrawtransaction, [], [['key-value pair1'], ['2']])
+ # Test `createrawtransaction` mismatch between sequence number(s) and `replaceable` option
+ assert_raises_rpc_error(-8, "Invalid parameter combination: Sequence number(s) contradict replaceable option",
+ self.nodes[0].createrawtransaction, [{'txid': TXID, 'vout': 0, 'sequence': BIP125_SEQUENCE_NUMBER+1}], {}, 0, True)
+
# Test `createrawtransaction` invalid `locktime`
assert_raises_rpc_error(-3, "Expected type number", self.nodes[0].createrawtransaction, [], {}, 'foo')
assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, -1)
@@ -245,6 +242,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=[{address: 99}]),
)
# Two outputs
+ address2 = getnewdestination()[2]
tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=OrderedDict([(address, 99), (address2, 99)])))
assert_equal(len(tx.vout), 2)
assert_equal(
@@ -259,122 +257,53 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=[{address: 99}, {address2: 99}, {'data': '99'}]),
)
- def signrawtransactionwithwallet_tests(self):
- for type in ["bech32", "p2sh-segwit", "legacy"]:
- self.log.info(f"Test signrawtransactionwithwallet with missing prevtx info ({type})")
- addr = self.nodes[0].getnewaddress("", type)
- addrinfo = self.nodes[0].getaddressinfo(addr)
- pubkey = addrinfo["scriptPubKey"]
- inputs = [{'txid': TXID, 'vout': 3, 'sequence': 1000}]
- outputs = {self.nodes[0].getnewaddress(): 1}
- rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
-
- prevtx = dict(txid=TXID, scriptPubKey=pubkey, vout=3, amount=1)
- succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
- assert succ["complete"]
-
- if type == "legacy":
- del prevtx["amount"]
- succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
- assert succ["complete"]
- else:
- assert_raises_rpc_error(-3, "Missing amount", self.nodes[0].signrawtransactionwithwallet, rawtx, [
- {
- "txid": TXID,
- "scriptPubKey": pubkey,
- "vout": 3,
- }
- ])
-
- assert_raises_rpc_error(-3, "Missing vout", self.nodes[0].signrawtransactionwithwallet, rawtx, [
- {
- "txid": TXID,
- "scriptPubKey": pubkey,
- "amount": 1,
- }
- ])
- assert_raises_rpc_error(-3, "Missing txid", self.nodes[0].signrawtransactionwithwallet, rawtx, [
- {
- "scriptPubKey": pubkey,
- "vout": 3,
- "amount": 1,
- }
- ])
- assert_raises_rpc_error(-3, "Missing scriptPubKey", self.nodes[0].signrawtransactionwithwallet, rawtx, [
- {
- "txid": TXID,
- "vout": 3,
- "amount": 1
- }
- ])
-
def sendrawtransaction_tests(self):
self.log.info("Test sendrawtransaction with missing input")
inputs = [{'txid': TXID, 'vout': 1}] # won't exist
- outputs = {self.nodes[0].getnewaddress(): 4.998}
+ address = getnewdestination()[2]
+ outputs = {address: 4.998}
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
- rawtx = self.nodes[2].signrawtransactionwithwallet(rawtx)
- assert_raises_rpc_error(-25, "bad-txns-inputs-missingorspent", self.nodes[2].sendrawtransaction, rawtx['hex'])
+ assert_raises_rpc_error(-25, "bad-txns-inputs-missingorspent", self.nodes[2].sendrawtransaction, rawtx)
def sendrawtransaction_testmempoolaccept_tests(self):
self.log.info("Test sendrawtransaction/testmempoolaccept with maxfeerate")
fee_exceeds_max = "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)"
# Test a transaction with a small fee.
- txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
- rawTx = self.nodes[0].getrawtransaction(txId, True)
- vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('1.00000000'))
-
- self.sync_all()
- inputs = [{"txid": txId, "vout": vout['n']}]
- # Fee 10,000 satoshis, (1 - (10000 sat * 0.00000001 BTC/sat)) = 0.9999
- outputs = {self.nodes[0].getnewaddress(): Decimal("0.99990000")}
- rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
- rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
- assert_equal(rawTxSigned['complete'], True)
- # Fee 10,000 satoshis, ~100 b transaction, fee rate should land around 100 sat/byte = 0.00100000 BTC/kB
+ # Fee rate is 0.00100000 BTC/kvB
+ tx = self.wallet.create_self_transfer(fee_rate=Decimal('0.00100000'))
# Thus, testmempoolaccept should reject
- testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']], 0.00001000)[0]
+ testres = self.nodes[2].testmempoolaccept([tx['hex']], 0.00001000)[0]
assert_equal(testres['allowed'], False)
assert_equal(testres['reject-reason'], 'max-fee-exceeded')
# and sendrawtransaction should throw
- assert_raises_rpc_error(-25, fee_exceeds_max, self.nodes[2].sendrawtransaction, rawTxSigned['hex'], 0.00001000)
+ assert_raises_rpc_error(-25, fee_exceeds_max, self.nodes[2].sendrawtransaction, tx['hex'], 0.00001000)
# and the following calls should both succeed
- testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']])[0]
+ testres = self.nodes[2].testmempoolaccept(rawtxs=[tx['hex']])[0]
assert_equal(testres['allowed'], True)
- self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'])
+ self.nodes[2].sendrawtransaction(hexstring=tx['hex'])
# Test a transaction with a large fee.
- txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
- rawTx = self.nodes[0].getrawtransaction(txId, True)
- vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('1.00000000'))
-
- self.sync_all()
- inputs = [{"txid": txId, "vout": vout['n']}]
- # Fee 2,000,000 satoshis, (1 - (2000000 sat * 0.00000001 BTC/sat)) = 0.98
- outputs = {self.nodes[0].getnewaddress() : Decimal("0.98000000")}
- rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
- rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
- assert_equal(rawTxSigned['complete'], True)
- # Fee 2,000,000 satoshis, ~100 b transaction, fee rate should land around 20,000 sat/byte = 0.20000000 BTC/kB
+ # Fee rate is 0.20000000 BTC/kvB
+ tx = self.wallet.create_self_transfer(mempool_valid=False, from_node=self.nodes[0], fee_rate=Decimal('0.20000000'))
# Thus, testmempoolaccept should reject
- testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']])[0]
+ testres = self.nodes[2].testmempoolaccept([tx['hex']])[0]
assert_equal(testres['allowed'], False)
assert_equal(testres['reject-reason'], 'max-fee-exceeded')
# and sendrawtransaction should throw
- assert_raises_rpc_error(-25, fee_exceeds_max, self.nodes[2].sendrawtransaction, rawTxSigned['hex'])
+ assert_raises_rpc_error(-25, fee_exceeds_max, self.nodes[2].sendrawtransaction, tx['hex'])
# and the following calls should both succeed
- testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']], maxfeerate='0.20000000')[0]
+ testres = self.nodes[2].testmempoolaccept(rawtxs=[tx['hex']], maxfeerate='0.20000000')[0]
assert_equal(testres['allowed'], True)
- self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'], maxfeerate='0.20000000')
+ self.nodes[2].sendrawtransaction(hexstring=tx['hex'], maxfeerate='0.20000000')
self.log.info("Test sendrawtransaction/testmempoolaccept with tx already in the chain")
self.generate(self.nodes[2], 1)
for node in self.nodes:
- testres = node.testmempoolaccept([rawTxSigned['hex']])[0]
+ testres = node.testmempoolaccept([tx['hex']])[0]
assert_equal(testres['allowed'], False)
assert_equal(testres['reject-reason'], 'txn-already-known')
- assert_raises_rpc_error(-27, 'Transaction already in block chain', node.sendrawtransaction, rawTxSigned['hex'])
+ assert_raises_rpc_error(-27, 'Transaction already in block chain', node.sendrawtransaction, tx['hex'])
def decoderawtransaction_tests(self):
self.log.info("Test decoderawtransaction")
diff --git a/test/functional/rpc_signrawtransaction.py b/test/functional/rpc_signrawtransaction.py
index a2091b4ece..8da2cfa72b 100755
--- a/test/functional/rpc_signrawtransaction.py
+++ b/test/functional/rpc_signrawtransaction.py
@@ -334,6 +334,56 @@ class SignRawTransactionsTest(BitcoinTestFramework):
assert_equal(signed["complete"], True)
self.nodes[0].sendrawtransaction(signed["hex"])
+ def test_signing_with_missing_prevtx_info(self):
+ txid = "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000"
+ for type in ["bech32", "p2sh-segwit", "legacy"]:
+ self.log.info(f"Test signing with missing prevtx info ({type})")
+ addr = self.nodes[0].getnewaddress("", type)
+ addrinfo = self.nodes[0].getaddressinfo(addr)
+ pubkey = addrinfo["scriptPubKey"]
+ inputs = [{'txid': txid, 'vout': 3, 'sequence': 1000}]
+ outputs = {self.nodes[0].getnewaddress(): 1}
+ rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
+
+ prevtx = dict(txid=txid, scriptPubKey=pubkey, vout=3, amount=1)
+ succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
+ assert succ["complete"]
+
+ if type == "legacy":
+ del prevtx["amount"]
+ succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
+ assert succ["complete"]
+ else:
+ assert_raises_rpc_error(-3, "Missing amount", self.nodes[0].signrawtransactionwithwallet, rawtx, [
+ {
+ "txid": txid,
+ "scriptPubKey": pubkey,
+ "vout": 3,
+ }
+ ])
+
+ assert_raises_rpc_error(-3, "Missing vout", self.nodes[0].signrawtransactionwithwallet, rawtx, [
+ {
+ "txid": txid,
+ "scriptPubKey": pubkey,
+ "amount": 1,
+ }
+ ])
+ assert_raises_rpc_error(-3, "Missing txid", self.nodes[0].signrawtransactionwithwallet, rawtx, [
+ {
+ "scriptPubKey": pubkey,
+ "vout": 3,
+ "amount": 1,
+ }
+ ])
+ assert_raises_rpc_error(-3, "Missing scriptPubKey", self.nodes[0].signrawtransactionwithwallet, rawtx, [
+ {
+ "txid": txid,
+ "vout": 3,
+ "amount": 1
+ }
+ ])
+
def run_test(self):
self.successful_signing_test()
self.script_verification_error_test()
@@ -343,6 +393,7 @@ class SignRawTransactionsTest(BitcoinTestFramework):
self.test_fully_signed_tx()
self.test_signing_with_csv()
self.test_signing_with_cltv()
+ self.test_signing_with_missing_prevtx_info()
if __name__ == '__main__':
diff --git a/test/functional/test_framework/messages.py b/test/functional/test_framework/messages.py
index f57b6e7494..aae44c0ac0 100755
--- a/test/functional/test_framework/messages.py
+++ b/test/functional/test_framework/messages.py
@@ -1672,7 +1672,7 @@ class msg_getcfilters:
__slots__ = ("filter_type", "start_height", "stop_hash")
msgtype = b"getcfilters"
- def __init__(self, filter_type, start_height, stop_hash):
+ def __init__(self, filter_type=None, start_height=None, stop_hash=None):
self.filter_type = filter_type
self.start_height = start_height
self.stop_hash = stop_hash
@@ -1722,7 +1722,7 @@ class msg_getcfheaders:
__slots__ = ("filter_type", "start_height", "stop_hash")
msgtype = b"getcfheaders"
- def __init__(self, filter_type, start_height, stop_hash):
+ def __init__(self, filter_type=None, start_height=None, stop_hash=None):
self.filter_type = filter_type
self.start_height = start_height
self.stop_hash = stop_hash
@@ -1775,7 +1775,7 @@ class msg_getcfcheckpt:
__slots__ = ("filter_type", "stop_hash")
msgtype = b"getcfcheckpt"
- def __init__(self, filter_type, stop_hash):
+ def __init__(self, filter_type=None, stop_hash=None):
self.filter_type = filter_type
self.stop_hash = stop_hash
diff --git a/test/functional/test_framework/p2p.py b/test/functional/test_framework/p2p.py
index 251d3d5eae..fc72a9ab73 100755
--- a/test/functional/test_framework/p2p.py
+++ b/test/functional/test_framework/p2p.py
@@ -47,6 +47,9 @@ from test_framework.messages import (
msg_getaddr,
msg_getblocks,
msg_getblocktxn,
+ msg_getcfcheckpt,
+ msg_getcfheaders,
+ msg_getcfilters,
msg_getdata,
msg_getheaders,
msg_headers,
@@ -108,6 +111,9 @@ MESSAGEMAP = {
b"getaddr": msg_getaddr,
b"getblocks": msg_getblocks,
b"getblocktxn": msg_getblocktxn,
+ b"getcfcheckpt": msg_getcfcheckpt,
+ b"getcfheaders": msg_getcfheaders,
+ b"getcfilters": msg_getcfilters,
b"getdata": msg_getdata,
b"getheaders": msg_getheaders,
b"headers": msg_headers,
diff --git a/test/functional/test_framework/util.py b/test/functional/test_framework/util.py
index 8651bcf636..b043d1a70d 100644
--- a/test/functional/test_framework/util.py
+++ b/test/functional/test_framework/util.py
@@ -378,6 +378,7 @@ def write_config(config_path, *, n, chain, extra_config="", disable_autoconnect=
f.write("[{}]\n".format(chain_name_conf_section))
f.write("port=" + str(p2p_port(n)) + "\n")
f.write("rpcport=" + str(rpc_port(n)) + "\n")
+ f.write("rpcdoccheck=1\n")
f.write("fallbackfee=0.0002\n")
f.write("server=1\n")
f.write("keypool=1\n")
diff --git a/test/functional/test_framework/wallet.py b/test/functional/test_framework/wallet.py
index 6901bcfe66..336b2afe26 100644
--- a/test/functional/test_framework/wallet.py
+++ b/test/functional/test_framework/wallet.py
@@ -167,6 +167,13 @@ class MiniWallet:
else:
return self._utxos[index]
+ def get_utxos(self, *, mark_as_spent=True):
+ """Returns the list of all utxos and optionally mark them as spent"""
+ utxos = deepcopy(self._utxos)
+ if mark_as_spent:
+ self._utxos = []
+ return utxos
+
def send_self_transfer(self, **kwargs):
"""Create and send a tx with the specified fee_rate. Fee may be exact or at most one satoshi higher than needed."""
tx = self.create_self_transfer(**kwargs)
@@ -270,8 +277,8 @@ class MiniWallet:
return {'txid': tx.rehash(), 'wtxid': tx.getwtxid(), 'hex': tx_hex, 'tx': tx}
- def sendrawtransaction(self, *, from_node, tx_hex, **kwargs):
- txid = from_node.sendrawtransaction(hexstring=tx_hex, **kwargs)
+ def sendrawtransaction(self, *, from_node, tx_hex, maxfeerate=0, **kwargs):
+ txid = from_node.sendrawtransaction(hexstring=tx_hex, maxfeerate=maxfeerate, **kwargs)
self.scan_tx(from_node.decoderawtransaction(tx_hex))
return txid
diff --git a/test/functional/test_runner.py b/test/functional/test_runner.py
index 7b67027d6f..6a44f9d21d 100755
--- a/test/functional/test_runner.py
+++ b/test/functional/test_runner.py
@@ -184,7 +184,6 @@ BASE_SCRIPTS = [
'rpc_signrawtransaction.py --legacy-wallet',
'rpc_signrawtransaction.py --descriptors',
'rpc_rawtransaction.py --legacy-wallet',
- 'rpc_rawtransaction.py --descriptors',
'wallet_groups.py --legacy-wallet',
'wallet_transactiontime_rescan.py --descriptors',
'wallet_transactiontime_rescan.py --legacy-wallet',
@@ -329,7 +328,7 @@ BASE_SCRIPTS = [
'feature_presegwit_node_upgrade.py',
'feature_settings.py',
'rpc_getdescriptorinfo.py',
- 'rpc_mempool_entry_fee_fields_deprecation.py',
+ 'rpc_mempool_info.py',
'rpc_help.py',
'feature_dirsymlinks.py',
'feature_help.py',
diff --git a/test/functional/wallet_listreceivedby.py b/test/functional/wallet_listreceivedby.py
index a7f4f9ffaf..db1d8eb54a 100755
--- a/test/functional/wallet_listreceivedby.py
+++ b/test/functional/wallet_listreceivedby.py
@@ -18,8 +18,6 @@ from test_framework.wallet_util import test_address
class ReceivedByTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
- # Test deprecated exclude coinbase on second node
- self.extra_args = [[], ["-deprecatedrpc=exclude_coinbase"]]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
@@ -131,6 +129,9 @@ class ReceivedByTest(BitcoinTestFramework):
txid = self.nodes[0].sendtoaddress(addr, 0.1)
self.sync_all()
+ # getreceivedbylabel returns an error if the wallet doesn't own the label
+ assert_raises_rpc_error(-4, "Label not found in wallet", self.nodes[0].getreceivedbylabel, "dummy")
+
# listreceivedbylabel should return received_by_label_json because of 0 confirmations
assert_array_result(self.nodes[1].listreceivedbylabel(),
{"label": label},
@@ -250,35 +251,6 @@ class ReceivedByTest(BitcoinTestFramework):
{"label": label},
{}, True)
- # Test exclude_coinbase
- address2 = self.nodes[1].getnewaddress(label)
- self.generatetoaddress(self.nodes[1], COINBASE_MATURITY + 1, address2, sync_fun=self.no_op)
-
- self.log.info("getreceivedbyaddress returns nothing when excluding coinbase")
- balance = self.nodes[1].getreceivedbyaddress(address2)
- assert_equal(balance, 0)
-
- self.log.info("getreceivedbylabel returns nothing when excluding coinbase")
- balance = self.nodes[1].getreceivedbylabel("label")
- assert_equal(balance, 0)
-
- self.log.info("listreceivedbyaddress does not include address when excluding coinbase")
- assert_array_result(self.nodes[1].listreceivedbyaddress(),
- {"address": address2},
- {}, True)
-
- self.log.info("listreceivedbylabel does not include label when excluding coinbase")
- assert_array_result(self.nodes[1].listreceivedbylabel(),
- {"label": label},
- {}, True)
-
- self.log.info("getreceivedbyaddress throws when setting include_immature_coinbase with deprecated exclude_coinbase")
- assert_raises_rpc_error(-8, 'include_immature_coinbase is incompatible with deprecated exclude_coinbase', self.nodes[1].getreceivedbyaddress, address2, 1, True)
-
-
- self.log.info("listreceivedbyaddress throws when setting include_immature_coinbase with deprecated exclude_coinbase")
- assert_raises_rpc_error(-8, 'include_immature_coinbase is incompatible with deprecated exclude_coinbase', self.nodes[1].listreceivedbyaddress, 1, False, False, "", True)
-
if __name__ == '__main__':
ReceivedByTest().main()
diff --git a/test/functional/wallet_taproot.py b/test/functional/wallet_taproot.py
index 41bb86f962..a4d836c8fe 100755
--- a/test/functional/wallet_taproot.py
+++ b/test/functional/wallet_taproot.py
@@ -441,11 +441,11 @@ class WalletTaprootTest(BitcoinTestFramework):
self.log.info("Sending everything back...")
- txid = self.rpc_online.sendtoaddress(address=self.boring.getnewaddress(), amount=self.rpc_online.getbalance(), subtractfeefromamount=True)
+ txid = self.rpc_online.sendall(recipients=[self.boring.getnewaddress()])["txid"]
self.generatetoaddress(self.nodes[0], 1, self.boring.getnewaddress(), sync_fun=self.no_op)
assert(self.rpc_online.gettransaction(txid)["confirmations"] > 0)
- psbt = self.psbt_online.walletcreatefundedpsbt([], [{self.boring.getnewaddress(): self.psbt_online.getbalance()}], None, {"subtractFeeFromOutputs": [0]})['psbt']
+ psbt = self.psbt_online.sendall(recipients=[self.boring.getnewaddress()], options={"psbt": True})["psbt"]
res = self.psbt_offline.walletprocesspsbt(psbt)
assert(res['complete'])
rawtx = self.nodes[0].finalizepsbt(res['psbt'])['hex']
diff --git a/test/lint/lint-circular-dependencies.py b/test/lint/lint-circular-dependencies.py
index 7ca2ec994b..5d157eb4b1 100755
--- a/test/lint/lint-circular-dependencies.py
+++ b/test/lint/lint-circular-dependencies.py
@@ -14,7 +14,6 @@ import sys
EXPECTED_CIRCULAR_DEPENDENCIES = (
"chainparamsbase -> util/system -> chainparamsbase",
"node/blockstorage -> validation -> node/blockstorage",
- "index/coinstatsindex -> node/coinstats -> index/coinstatsindex",
"policy/fees -> txmempool -> policy/fees",
"qt/addresstablemodel -> qt/walletmodel -> qt/addresstablemodel",
"qt/recentrequeststablemodel -> qt/walletmodel -> qt/recentrequeststablemodel",
@@ -22,7 +21,7 @@ EXPECTED_CIRCULAR_DEPENDENCIES = (
"qt/transactiontablemodel -> qt/walletmodel -> qt/transactiontablemodel",
"wallet/fees -> wallet/wallet -> wallet/fees",
"wallet/wallet -> wallet/walletdb -> wallet/wallet",
- "node/coinstats -> validation -> node/coinstats",
+ "kernel/coinstats -> validation -> kernel/coinstats",
)
CODE_DIR = "src"
diff --git a/test/lint/lint-files.py b/test/lint/lint-files.py
index 3723e0ee6a..dbb51ce54e 100755
--- a/test/lint/lint-files.py
+++ b/test/lint/lint-files.py
@@ -11,19 +11,20 @@ import os
import re
import sys
from subprocess import check_output
-from typing import Optional, NoReturn
+from typing import Dict, Optional, NoReturn
CMD_TOP_LEVEL = ["git", "rev-parse", "--show-toplevel"]
-CMD_ALL_FILES = "git ls-files -z --full-name"
-CMD_SOURCE_FILES = 'git ls-files -z --full-name -- "*.[cC][pP][pP]" "*.[hH]" "*.[pP][yY]" "*.[sS][hH]"'
-CMD_SHEBANG_FILES = "git grep --full-name --line-number -I '^#!'"
+CMD_ALL_FILES = ["git", "ls-files", "-z", "--full-name", "--stage"]
+CMD_SHEBANG_FILES = ["git", "grep", "--full-name", "--line-number", "-I", "^#!"]
+
+ALL_SOURCE_FILENAMES_REGEXP = r"^.*\.(cpp|h|py|sh)$"
ALLOWED_FILENAME_REGEXP = "^[a-zA-Z0-9/_.@][a-zA-Z0-9/_.@-]*$"
ALLOWED_SOURCE_FILENAME_REGEXP = "^[a-z0-9_./-]+$"
ALLOWED_SOURCE_FILENAME_EXCEPTION_REGEXP = (
"^src/(secp256k1/|minisketch/|univalue/|test/fuzz/FuzzedDataProvider.h)"
)
-ALLOWED_PERMISSION_NON_EXECUTABLES = 644
-ALLOWED_PERMISSION_EXECUTABLES = 755
+ALLOWED_PERMISSION_NON_EXECUTABLES = 0o644
+ALLOWED_PERMISSION_EXECUTABLES = 0o755
ALLOWED_EXECUTABLE_SHEBANG = {
"py": [b"#!/usr/bin/env python3"],
"sh": [b"#!/usr/bin/env bash", b"#!/bin/sh"],
@@ -31,8 +32,15 @@ ALLOWED_EXECUTABLE_SHEBANG = {
class FileMeta(object):
- def __init__(self, file_path: str):
- self.file_path = file_path
+ def __init__(self, file_spec: str):
+ '''Parse a `git ls files --stage` output line.'''
+ # 100755 5a150d5f8031fcd75e80a4dd9843afa33655f579 0 ci/test/00_setup_env.sh
+ meta, self.file_path = file_spec.split('\t', 2)
+ meta = meta.split()
+ # The octal file permission of the file. Internally, git only
+ # keeps an 'executable' bit, so this will always be 0o644 or 0o755.
+ self.permissions = int(meta[0], 8) & 0o7777
+ # We don't currently care about the other fields
@property
def extension(self) -> Optional[str]:
@@ -60,20 +68,24 @@ class FileMeta(object):
except IndexError:
return None
- @property
- def permissions(self) -> int:
- """
- Returns the octal file permission of the file
- """
- return int(oct(os.stat(self.file_path).st_mode)[-3:])
+def get_git_file_metadata() -> Dict[str, FileMeta]:
+ '''
+ Return a dictionary mapping the name of all files in the repository to git tree metadata.
+ '''
+ files_raw = check_output(CMD_ALL_FILES).decode("utf8").rstrip("\0").split("\0")
+ files = {}
+ for file_spec in files_raw:
+ meta = FileMeta(file_spec)
+ files[meta.file_path] = meta
+ return files
-def check_all_filenames() -> int:
+def check_all_filenames(files) -> int:
"""
Checks every file in the repository against an allowed regexp to make sure only lowercase or uppercase
alphanumerics (a-zA-Z0-9), underscores (_), hyphens (-), at (@) and dots (.) are used in repository filenames.
"""
- filenames = check_output(CMD_ALL_FILES, shell=True).decode("utf8").rstrip("\0").split("\0")
+ filenames = files.keys()
filename_regex = re.compile(ALLOWED_FILENAME_REGEXP)
failed_tests = 0
for filename in filenames:
@@ -85,14 +97,14 @@ def check_all_filenames() -> int:
return failed_tests
-def check_source_filenames() -> int:
+def check_source_filenames(files) -> int:
"""
Checks only source files (*.cpp, *.h, *.py, *.sh) against a stricter allowed regexp to make sure only lowercase
alphanumerics (a-z0-9), underscores (_), hyphens (-) and dots (.) are used in source code filenames.
Additionally there is an exception regexp for directories or files which are excepted from matching this regexp.
"""
- filenames = check_output(CMD_SOURCE_FILES, shell=True).decode("utf8").rstrip("\0").split("\0")
+ filenames = [filename for filename in files.keys() if re.match(ALL_SOURCE_FILENAMES_REGEXP, filename, re.IGNORECASE)]
filename_regex = re.compile(ALLOWED_SOURCE_FILENAME_REGEXP)
filename_exception_regex = re.compile(ALLOWED_SOURCE_FILENAME_EXCEPTION_REGEXP)
failed_tests = 0
@@ -105,16 +117,14 @@ def check_source_filenames() -> int:
return failed_tests
-def check_all_file_permissions() -> int:
+def check_all_file_permissions(files) -> int:
"""
Checks all files in the repository match an allowed executable or non-executable file permission octal.
Additionally checks that for executable files, the file contains a shebang line
"""
- filenames = check_output(CMD_ALL_FILES, shell=True).decode("utf8").rstrip("\0").split("\0")
failed_tests = 0
- for filename in filenames:
- file_meta = FileMeta(filename)
+ for filename, file_meta in files.items():
if file_meta.permissions == ALLOWED_PERMISSION_EXECUTABLES:
with open(filename, "rb") as f:
shebang = f.readline().rstrip(b"\n")
@@ -122,7 +132,7 @@ def check_all_file_permissions() -> int:
# For any file with executable permissions the first line must contain a shebang
if not shebang.startswith(b"#!"):
print(
- f"""File "{filename}" has permission {ALLOWED_PERMISSION_EXECUTABLES} (executable) and is thus expected to contain a shebang '#!'. Add shebang or do "chmod {ALLOWED_PERMISSION_NON_EXECUTABLES} {filename}" to make it non-executable."""
+ f"""File "{filename}" has permission {ALLOWED_PERMISSION_EXECUTABLES:03o} (executable) and is thus expected to contain a shebang '#!'. Add shebang or do "chmod {ALLOWED_PERMISSION_NON_EXECUTABLES:03o} {filename}" to make it non-executable."""
)
failed_tests += 1
@@ -145,18 +155,18 @@ def check_all_file_permissions() -> int:
continue
else:
print(
- f"""File "{filename}" has unexpected permission {file_meta.permissions}. Do "chmod {ALLOWED_PERMISSION_NON_EXECUTABLES} {filename}" (if non-executable) or "chmod {ALLOWED_PERMISSION_EXECUTABLES} {filename}" (if executable)."""
+ f"""File "{filename}" has unexpected permission {file_meta.permissions:03o}. Do "chmod {ALLOWED_PERMISSION_NON_EXECUTABLES:03o} {filename}" (if non-executable) or "chmod {ALLOWED_PERMISSION_EXECUTABLES:03o} {filename}" (if executable)."""
)
failed_tests += 1
return failed_tests
-def check_shebang_file_permissions() -> int:
+def check_shebang_file_permissions(files_meta) -> int:
"""
Checks every file that contains a shebang line to ensure it has an executable permission
"""
- filenames = check_output(CMD_SHEBANG_FILES, shell=True).decode("utf8").strip().split("\n")
+ filenames = check_output(CMD_SHEBANG_FILES).decode("utf8").strip().split("\n")
# The git grep command we use returns files which contain a shebang on any line within the file
# so we need to filter the list to only files with the shebang on the first line
@@ -164,7 +174,7 @@ def check_shebang_file_permissions() -> int:
failed_tests = 0
for filename in filenames:
- file_meta = FileMeta(filename)
+ file_meta = files_meta[filename]
if file_meta.permissions != ALLOWED_PERMISSION_EXECUTABLES:
# These file types are typically expected to be sourced and not executed directly
if file_meta.full_extension in ["bash", "init", "openrc", "sh.in"]:
@@ -178,7 +188,7 @@ def check_shebang_file_permissions() -> int:
continue
print(
- f"""File "{filename}" contains a shebang line, but has the file permission {file_meta.permissions} instead of the expected executable permission {ALLOWED_PERMISSION_EXECUTABLES}. Do "chmod {ALLOWED_PERMISSION_EXECUTABLES} {filename}" (or remove the shebang line)."""
+ f"""File "{filename}" contains a shebang line, but has the file permission {file_meta.permissions:03o} instead of the expected executable permission {ALLOWED_PERMISSION_EXECUTABLES:03o}. Do "chmod {ALLOWED_PERMISSION_EXECUTABLES:03o} {filename}" (or remove the shebang line)."""
)
failed_tests += 1
return failed_tests
@@ -187,11 +197,14 @@ def check_shebang_file_permissions() -> int:
def main() -> NoReturn:
root_dir = check_output(CMD_TOP_LEVEL).decode("utf8").strip()
os.chdir(root_dir)
+
+ files = get_git_file_metadata()
+
failed_tests = 0
- failed_tests += check_all_filenames()
- failed_tests += check_source_filenames()
- failed_tests += check_all_file_permissions()
- failed_tests += check_shebang_file_permissions()
+ failed_tests += check_all_filenames(files)
+ failed_tests += check_source_filenames(files)
+ failed_tests += check_all_file_permissions(files)
+ failed_tests += check_shebang_file_permissions(files)
if failed_tests:
print(
diff --git a/test/lint/lint-logs.py b/test/lint/lint-logs.py
index e6c4c068fb..de53729b4e 100755
--- a/test/lint/lint-logs.py
+++ b/test/lint/lint-logs.py
@@ -16,12 +16,12 @@ from subprocess import check_output
def main():
- logs_list = check_output(["git", "grep", "--extended-regexp", r"LogPrintf?\(", "--", "*.cpp"], universal_newlines=True, encoding="utf8").splitlines()
+ logs_list = check_output(["git", "grep", "--extended-regexp", r"(LogPrintLevel|LogPrintf?)\(", "--", "*.cpp"], universal_newlines=True, encoding="utf8").splitlines()
unterminated_logs = [line for line in logs_list if not re.search(r'(\\n"|/\* Continued \*/)', line)]
if unterminated_logs != []:
- print("All calls to LogPrintf() and LogPrint() should be terminated with \\n")
+ print("All calls to LogPrintf(), LogPrint(), LogPrintLevel(), and WalletLogPrintf() should be terminated with \"\\n\".")
print("")
for line in unterminated_logs:
diff --git a/test/lint/spelling.ignore-words.txt b/test/lint/spelling.ignore-words.txt
index afdb0692d8..c931a0aae1 100644
--- a/test/lint/spelling.ignore-words.txt
+++ b/test/lint/spelling.ignore-words.txt
@@ -11,6 +11,7 @@ inout
invokable
keypair
mor
+nd
nin
ser
unparseable