dash/test/functional/p2p_invalid_tx.py

189 lines
8.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
Backports 0.15 pr2 (#2597) * Merge #9815: Trivial: use EXIT_ codes instead of magic numbers a87d02a use EXIT_ codes instead of magic numbers (Marko Bencun) * Merge #9801: Removed redundant parameter from mempool.PrioritiseTransaction eaea2bb Removed redundant parameter from mempool.PrioritiseTransaction (gubatron) * remove extra parameter (see 3a3745bb) in dash specific code * Merge #9819: Remove harmless read of unusued priority estimates bc8fd12 Remove harmless read of unusued priority estimates (Alex Morcos) * Merge #9766: Add --exclude option to rpc-tests.py c578408 Add exclude option to rpc-tests.py (John Newbery) * Merge #9577: Fix docstrings in qa tests 3f95a80 Fix docstrings in qa tests (John Newbery) * Merge #9823: qa: Set correct path for binaries in rpc tests 3333ad0 qa: Set correct path for binaries in rpc tests (MarcoFalke) * Merge #9833: Trivial: fix comments referencing AppInit2 ef9f495 Trivial: fix comments referencing AppInit2 (Marko Bencun) * Merge #9612: [trivial] Rephrase the definition of difficulty. dc222f8 Trivial: Rephrase the definition of difficulty in the code. (Karl-Johan Alm) * Merge #9847: Extra test vector for BIP32 30aedcb BIP32 extra test vector (Pieter Wuille) * Merge #9839: [qa] Make import-rescan.py watchonly check reliable 864890a [qa] Make import-rescan.py watchonly check reliable (Russell Yanofsky) Tree-SHA512: ea0e2b1d4fc8f35174c3d575fb751b428daf6ad3aa944fad4e3ddcc9195e4f17051473acabc54203b1d27cca64cf911b737ab92e986c40ef384410652e2dbea1 * Change back file params
2019-01-07 10:55:35 +01:00
"""Test node responses to invalid transactions.
In this test we connect to one node over p2p, and test tx requests."""
from test_framework.blocktools import create_block, create_coinbase, create_transaction
from test_framework.mininode import (
COIN,
COutPoint,
CTransaction,
CTxIn,
CTxOut,
)
from test_framework.mininode import network_thread_start, P2PDataStore, network_thread_join
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
wait_until,
)
Merge bitcoin#13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications (#3414) * Merge #13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications 87fe292d897e09e176ac7e254144466c319cc9ac doc: Mention disabling BIP61 in bips.md (Wladimir J. van der Laan) fe16dd8226d924f44432c5b5014aa49ff45c82ff net: Add option `-enablebip61` to configure sending of BIP61 notifications (Wladimir J. van der Laan) Pull request description: This commit adds a boolean option `-peersendreject`, defaulting to `1`, that can be used to disable the sending of [BIP61](https://github.com/bitcoin/bips/blob/master/bip-0061.mediawiki) `reject` messages. This functionality has been requested for various reasons: - security (DoS): reject messages can reveal internal state that can be used to target certain resources such as the mempool more easily. - bandwidth: a typical node sends lots of reject messages; this counts against upstream bandwidth. Also the reject messages tend to be larger than the message that was rejected. On the other hand, reject messages can be useful while developing client software (I found them indispensable while creating bitcoin-submittx), as well as for our own test cases, so whatever the default becomes on the long run, IMO the functionality should be retained as option. But that's a discussion for later, for now it's simply a node operator decision. Also adds a RPC test that checks the functionality. Tree-SHA512: 9488cc53e13cd8e5c6f8eb472a44309572673405c1d1438c3488f627fae622c95e2198bde5ed7d29e56b948e2918bf1920239e9f865889f4c37c097c37a4d7a9 * 0.17 -> 0.16 Signed-off-by: Pasta <pasta@dashboost.org> * tx1 -> base_ tx fixing 13134 Signed-off-by: Pasta <pasta@dashboost.org> * move added bip61 message checking up Signed-off-by: Pasta <pasta@dashboost.org> * Dash specific code, only send reject messages if bip61 is enabled Signed-off-by: Pasta <pasta@dashboost.org> * Fix invalidtxrequest.py Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-04-19 13:04:31 +02:00
class InvalidTxRequestTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def bootstrap_p2p(self, *, num_connections=1):
"""Add a P2P connection to the node.
Helper to connect and wait for version handshake."""
for _ in range(num_connections):
self.nodes[0].add_p2p_connection(P2PDataStore())
network_thread_start()
self.nodes[0].p2p.wait_for_verack()
def reconnect_p2p(self, **kwargs):
"""Tear down and bootstrap the P2P connection to the node.
The node gets disconnected several times in this test. This helper
method reconnects the p2p and restarts the network thread."""
self.nodes[0].disconnect_p2ps()
network_thread_join()
self.bootstrap_p2p(**kwargs)
def run_test(self):
node = self.nodes[0] # convenience reference to the node
self.bootstrap_p2p() # Add one p2p connection to the node
best_block = self.nodes[0].getbestblockhash()
tip = int(best_block, 16)
best_block_time = self.nodes[0].getblock(best_block)['time']
block_time = best_block_time + 1
self.log.info("Create a new block with an anyone-can-spend coinbase.")
height = 1
block = create_block(tip, create_coinbase(height), block_time)
block.solve()
# Save the coinbase for later
block1 = block
tip = block.sha256
# Create a second one to test orphan resolution via block receival
height += 1
block_time += 1
block = create_block(tip, create_coinbase(height), block_time)
block.solve()
# Save the coinbase for later
block2 = block
tip = block.sha256
node.p2p.send_blocks_and_test([block1, block2], node, success=True)
self.log.info("Mature the block.")
self.nodes[0].generate(100)
# b'\x64' is OP_NOTIF
# Transaction will be rejected with code 16 (REJECT_INVALID)
# and we get disconnected immediately
self.log.info('Test a transaction that is rejected')
tx1 = create_transaction(block1.vtx[0], 0, b'\x64', 50 * COIN)
node.p2p.send_txs_and_test([tx1], node, success=False, expect_disconnect=True)
# Make two p2p connections to provide the node with orphans
# * p2ps[0] will send valid orphan txs (one with low fee)
# * p2ps[1] will send an invalid orphan tx (and is later disconnected for that)
self.reconnect_p2p(num_connections=2)
self.log.info('Test orphan transaction handling ... ')
self.test_orphan_tx_handling(block1.vtx[0].sha256, False)
Merge bitcoin#13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications (#3414) * Merge #13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications 87fe292d897e09e176ac7e254144466c319cc9ac doc: Mention disabling BIP61 in bips.md (Wladimir J. van der Laan) fe16dd8226d924f44432c5b5014aa49ff45c82ff net: Add option `-enablebip61` to configure sending of BIP61 notifications (Wladimir J. van der Laan) Pull request description: This commit adds a boolean option `-peersendreject`, defaulting to `1`, that can be used to disable the sending of [BIP61](https://github.com/bitcoin/bips/blob/master/bip-0061.mediawiki) `reject` messages. This functionality has been requested for various reasons: - security (DoS): reject messages can reveal internal state that can be used to target certain resources such as the mempool more easily. - bandwidth: a typical node sends lots of reject messages; this counts against upstream bandwidth. Also the reject messages tend to be larger than the message that was rejected. On the other hand, reject messages can be useful while developing client software (I found them indispensable while creating bitcoin-submittx), as well as for our own test cases, so whatever the default becomes on the long run, IMO the functionality should be retained as option. But that's a discussion for later, for now it's simply a node operator decision. Also adds a RPC test that checks the functionality. Tree-SHA512: 9488cc53e13cd8e5c6f8eb472a44309572673405c1d1438c3488f627fae622c95e2198bde5ed7d29e56b948e2918bf1920239e9f865889f4c37c097c37a4d7a9 * 0.17 -> 0.16 Signed-off-by: Pasta <pasta@dashboost.org> * tx1 -> base_ tx fixing 13134 Signed-off-by: Pasta <pasta@dashboost.org> * move added bip61 message checking up Signed-off-by: Pasta <pasta@dashboost.org> * Dash specific code, only send reject messages if bip61 is enabled Signed-off-by: Pasta <pasta@dashboost.org> * Fix invalidtxrequest.py Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-04-19 13:04:31 +02:00
# restart node with sending BIP61 messages disabled, check that it disconnects without sending the reject message
self.log.info('Test a transaction that is rejected, with BIP61 disabled')
self.restart_node(0, ['-enablebip61=0', '-persistmempool=0'])
Merge bitcoin#13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications (#3414) * Merge #13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications 87fe292d897e09e176ac7e254144466c319cc9ac doc: Mention disabling BIP61 in bips.md (Wladimir J. van der Laan) fe16dd8226d924f44432c5b5014aa49ff45c82ff net: Add option `-enablebip61` to configure sending of BIP61 notifications (Wladimir J. van der Laan) Pull request description: This commit adds a boolean option `-peersendreject`, defaulting to `1`, that can be used to disable the sending of [BIP61](https://github.com/bitcoin/bips/blob/master/bip-0061.mediawiki) `reject` messages. This functionality has been requested for various reasons: - security (DoS): reject messages can reveal internal state that can be used to target certain resources such as the mempool more easily. - bandwidth: a typical node sends lots of reject messages; this counts against upstream bandwidth. Also the reject messages tend to be larger than the message that was rejected. On the other hand, reject messages can be useful while developing client software (I found them indispensable while creating bitcoin-submittx), as well as for our own test cases, so whatever the default becomes on the long run, IMO the functionality should be retained as option. But that's a discussion for later, for now it's simply a node operator decision. Also adds a RPC test that checks the functionality. Tree-SHA512: 9488cc53e13cd8e5c6f8eb472a44309572673405c1d1438c3488f627fae622c95e2198bde5ed7d29e56b948e2918bf1920239e9f865889f4c37c097c37a4d7a9 * 0.17 -> 0.16 Signed-off-by: Pasta <pasta@dashboost.org> * tx1 -> base_ tx fixing 13134 Signed-off-by: Pasta <pasta@dashboost.org> * move added bip61 message checking up Signed-off-by: Pasta <pasta@dashboost.org> * Dash specific code, only send reject messages if bip61 is enabled Signed-off-by: Pasta <pasta@dashboost.org> * Fix invalidtxrequest.py Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-04-19 13:04:31 +02:00
self.reconnect_p2p(num_connections=1)
with node.assert_debug_log(expected_msgs=[
"{} from peer=0 was not accepted: mandatory-script-verify-flag-failed (Invalid OP_IF construction) (code 16)".format(tx1.hash),
"disconnecting peer=0",
]):
node.p2p.send_txs_and_test([tx1], node, success=False, expect_disconnect=True)
Merge bitcoin#13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications (#3414) * Merge #13134: net: Add option `-enablebip61` to configure sending of BIP61 notifications 87fe292d897e09e176ac7e254144466c319cc9ac doc: Mention disabling BIP61 in bips.md (Wladimir J. van der Laan) fe16dd8226d924f44432c5b5014aa49ff45c82ff net: Add option `-enablebip61` to configure sending of BIP61 notifications (Wladimir J. van der Laan) Pull request description: This commit adds a boolean option `-peersendreject`, defaulting to `1`, that can be used to disable the sending of [BIP61](https://github.com/bitcoin/bips/blob/master/bip-0061.mediawiki) `reject` messages. This functionality has been requested for various reasons: - security (DoS): reject messages can reveal internal state that can be used to target certain resources such as the mempool more easily. - bandwidth: a typical node sends lots of reject messages; this counts against upstream bandwidth. Also the reject messages tend to be larger than the message that was rejected. On the other hand, reject messages can be useful while developing client software (I found them indispensable while creating bitcoin-submittx), as well as for our own test cases, so whatever the default becomes on the long run, IMO the functionality should be retained as option. But that's a discussion for later, for now it's simply a node operator decision. Also adds a RPC test that checks the functionality. Tree-SHA512: 9488cc53e13cd8e5c6f8eb472a44309572673405c1d1438c3488f627fae622c95e2198bde5ed7d29e56b948e2918bf1920239e9f865889f4c37c097c37a4d7a9 * 0.17 -> 0.16 Signed-off-by: Pasta <pasta@dashboost.org> * tx1 -> base_ tx fixing 13134 Signed-off-by: Pasta <pasta@dashboost.org> * move added bip61 message checking up Signed-off-by: Pasta <pasta@dashboost.org> * Dash specific code, only send reject messages if bip61 is enabled Signed-off-by: Pasta <pasta@dashboost.org> * Fix invalidtxrequest.py Co-authored-by: Wladimir J. van der Laan <laanwj@gmail.com> Co-authored-by: UdjinM6 <UdjinM6@users.noreply.github.com>
2020-04-19 13:04:31 +02:00
# send_txs_and_test will have waited for disconnect, so we can safely check that no reject has been received
assert_equal(node.p2p.reject_code_received, None)
self.log.info('Test orphan transaction handling, resolve via block')
self.restart_node(0, ['-persistmempool=0'])
self.reconnect_p2p(num_connections=2)
self.test_orphan_tx_handling(block2.vtx[0].sha256, True)
def test_orphan_tx_handling(self, base_tx, resolve_via_block):
node = self.nodes[0] # convenience reference to the node
# Create a root transaction that we withold until all dependend transactions
# are sent out and in the orphan cache
tx_withhold = CTransaction()
tx_withhold.vin.append(CTxIn(outpoint=COutPoint(base_tx, 0)))
tx_withhold.vout.append(CTxOut(nValue=50 * COIN - 12000, scriptPubKey=b'\x51'))
tx_withhold.calc_sha256()
# Our first orphan tx with some outputs to create further orphan txs
tx_orphan_1 = CTransaction()
tx_orphan_1.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.sha256, 0)))
tx_orphan_1.vout = [CTxOut(nValue=10 * COIN, scriptPubKey=b'\x51')] * 3
tx_orphan_1.calc_sha256()
# A valid transaction with low fee
tx_orphan_2_no_fee = CTransaction()
tx_orphan_2_no_fee.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 0)))
tx_orphan_2_no_fee.vout.append(CTxOut(nValue=10 * COIN, scriptPubKey=b'\x51'))
# A valid transaction with sufficient fee
tx_orphan_2_valid = CTransaction()
tx_orphan_2_valid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 1)))
tx_orphan_2_valid.vout.append(CTxOut(nValue=10 * COIN - 12000, scriptPubKey=b'\x51'))
tx_orphan_2_valid.calc_sha256()
# An invalid transaction with negative fee
tx_orphan_2_invalid = CTransaction()
tx_orphan_2_invalid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 2)))
tx_orphan_2_invalid.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=b'\x51'))
self.log.info('Send the orphans ... ')
# Send valid orphan txs from p2ps[0]
node.p2p.send_txs_and_test([tx_orphan_1, tx_orphan_2_no_fee, tx_orphan_2_valid], node, success=False)
# Send invalid tx from p2ps[1]
node.p2ps[1].send_txs_and_test([tx_orphan_2_invalid], node, success=False)
assert_equal(0, node.getmempoolinfo()['size']) # Mempool should be empty
assert_equal(2, len(node.getpeerinfo())) # p2ps[1] is still connected
self.log.info('Send the withhold tx ... ')
if resolve_via_block:
# Test orphan handling/resolution by publishing the withhold TX via a mined block
prev_block = node.getblockheader(node.getbestblockhash())
block = create_block(int(prev_block['hash'], 16), create_coinbase(prev_block['height'] + 1), prev_block["time"] + 1)
block.vtx.append(tx_withhold)
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
node.p2p.send_blocks_and_test([block], node, success=True)
else:
# Test orphan handling/resolution by publishing the withhold TX via the mempool
node.p2p.send_txs_and_test([tx_withhold], node, success=True)
# Transactions that should end up in the mempool
expected_mempool = {
t.hash
for t in [
tx_withhold, # The transaction that is the root for all orphans
tx_orphan_1, # The orphan transaction that splits the coins
tx_orphan_2_valid, # The valid transaction (with sufficient fee)
]
}
# Transactions that do not end up in the mempool
# tx_orphan_no_fee, because it has too low fee (p2ps[0] is not disconnected for relaying that tx)
# tx_orphan_invaid, because it has negative fee (p2ps[1] is disconnected for relaying that tx)
if resolve_via_block:
# This TX has appeared in a block instead of being broadcasted via the mempool
expected_mempool.remove(tx_withhold.hash)
wait_until(lambda: 1 == len(node.getpeerinfo()), timeout=12) # p2ps[1] is no longer connected
assert_equal(expected_mempool, set(node.getrawmempool()))
if __name__ == '__main__':
InvalidTxRequestTest().main()