1 #!/usr/bin/env python3
2 # Copyright (c) 2015-2022 The Limenka developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 """Test node responses to invalid transactions.
6 7 In this test we connect to one node over p2p, and test tx requests."""
8 from test_framework.blocktools import create_block, create_coinbase
9 from test_framework.messages import (
10 COIN,
11 COutPoint,
12 CTransaction,
13 CTxIn,
14 CTxOut,
15 )
16 from test_framework.p2p import P2PDataStore
17 from test_framework.test_framework import LimenkaTestFramework
18 from test_framework.util import (
19 assert_equal,
20 )
21 from data import invalid_txs
22 23 24 class InvalidTxRequestTest(LimenkaTestFramework):
25 def set_test_params(self):
26 self.num_nodes = 1
27 self.extra_args = [[
28 "-acceptnonstdtxn=1",
29 ]]
30 self.setup_clean_chain = True
31 32 def bootstrap_p2p(self, *, num_connections=1):
33 """Add a P2P connection to the node.
34 35 Helper to connect and wait for version handshake."""
36 for i in range(num_connections):
37 self.nodes[0].add_outbound_p2p_connection(P2PDataStore(), p2p_idx=i)
38 39 def reconnect_p2p(self, **kwargs):
40 """Tear down and bootstrap the P2P connection to the node.
41 42 The node gets disconnected several times in this test. This helper
43 method reconnects the p2p and restarts the network thread."""
44 self.nodes[0].disconnect_p2ps()
45 self.bootstrap_p2p(**kwargs)
46 47 def run_test(self):
48 node = self.nodes[0] # convenience reference to the node
49 50 self.bootstrap_p2p() # Add one p2p connection to the node
51 52 best_block = self.nodes[0].getbestblockhash()
53 tip = int(best_block, 16)
54 best_block_time = self.nodes[0].getblock(best_block)['time']
55 block_time = best_block_time + 1
56 57 self.log.info("Create a new block with an anyone-can-spend coinbase.")
58 height = 1
59 block = create_block(tip, create_coinbase(height), block_time)
60 block.solve()
61 # Save the coinbase for later
62 block1 = block
63 node.p2ps[0].send_blocks_and_test([block], node, success=True)
64 65 self.log.info("Mature the block.")
66 self.generatetoaddress(self.nodes[0], 100, self.nodes[0].get_deterministic_priv_key().address)
67 68 # Iterate through a list of known invalid transaction types, ensuring each is
69 # rejected. Some are consensus invalid and some just violate policy.
70 for BadTxTemplate in invalid_txs.iter_all_templates():
71 self.log.info("Testing invalid transaction: %s", BadTxTemplate.__name__)
72 template = BadTxTemplate(spend_block=block1)
73 tx = template.get_tx()
74 node.p2ps[0].send_txs_and_test(
75 [tx], node, success=False,
76 reject_reason=template.reject_reason,
77 )
78 79 # Make two p2p connections to provide the node with orphans
80 # * p2ps[0] will send valid orphan txs (one with low fee)
81 # * p2ps[1] will send an invalid orphan tx (and is later disconnected for that)
82 self.reconnect_p2p(num_connections=2)
83 84 self.log.info('Test orphan transaction handling ... ')
85 # Create a root transaction that we withhold until all dependent transactions
86 # are sent out and in the orphan cache
87 SCRIPT_PUB_KEY_OP_TRUE = b'\x51\x75' * 15 + b'\x51'
88 tx_withhold = CTransaction()
89 tx_withhold.vin.append(CTxIn(outpoint=COutPoint(block1.vtx[0].sha256, 0)))
90 tx_withhold.vout = [CTxOut(nValue=25 * COIN - 12000, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)] * 2
91 tx_withhold.calc_sha256()
92 93 # Our first orphan tx with some outputs to create further orphan txs
94 tx_orphan_1 = CTransaction()
95 tx_orphan_1.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.sha256, 0)))
96 tx_orphan_1.vout = [CTxOut(nValue=8 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)] * 3
97 tx_orphan_1.calc_sha256()
98 99 # A valid transaction with low fee
100 tx_orphan_2_no_fee = CTransaction()
101 tx_orphan_2_no_fee.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 0)))
102 tx_orphan_2_no_fee.vout.append(CTxOut(nValue=8 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
103 104 # A valid transaction with sufficient fee
105 tx_orphan_2_valid = CTransaction()
106 tx_orphan_2_valid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 1)))
107 tx_orphan_2_valid.vout.append(CTxOut(nValue=8 * COIN - 12000, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
108 tx_orphan_2_valid.calc_sha256()
109 110 # An invalid transaction with negative fee
111 tx_orphan_2_invalid = CTransaction()
112 tx_orphan_2_invalid.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_1.sha256, 2)))
113 tx_orphan_2_invalid.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
114 tx_orphan_2_invalid.calc_sha256()
115 116 self.log.info('Send the orphans ... ')
117 # Send valid orphan txs from p2ps[0]
118 node.p2ps[0].send_txs_and_test([tx_orphan_1, tx_orphan_2_no_fee, tx_orphan_2_valid], node, success=False)
119 # Send invalid tx from p2ps[1]
120 node.p2ps[1].send_txs_and_test([tx_orphan_2_invalid], node, success=False)
121 122 assert_equal(0, node.getmempoolinfo()['size']) # Mempool should be empty
123 assert_equal(2, len(node.getpeerinfo())) # p2ps[1] is still connected
124 125 self.log.info('Send the withhold tx ... ')
126 with node.assert_debug_log(expected_msgs=["bad-txns-in-belowout"]):
127 node.p2ps[0].send_txs_and_test([tx_withhold], node, success=True)
128 129 # Transactions that should end up in the mempool
130 expected_mempool = {
131 t.hash
132 for t in [
133 tx_withhold, # The transaction that is the root for all orphans
134 tx_orphan_1, # The orphan transaction that splits the coins
135 tx_orphan_2_valid, # The valid transaction (with sufficient fee)
136 ]
137 }
138 # Transactions that do not end up in the mempool:
139 # tx_orphan_2_no_fee, because it has too low fee (p2ps[0] is not disconnected for relaying that tx)
140 # tx_orphan_2_invalid, because it has negative fee (p2ps[1] is disconnected for relaying that tx)
141 142 assert_equal(expected_mempool, set(node.getrawmempool()))
143 144 self.log.info('Test orphan pool overflow')
145 orphan_tx_pool = [CTransaction() for _ in range(101)]
146 for i in range(len(orphan_tx_pool)):
147 orphan_tx_pool[i].vin.append(CTxIn(outpoint=COutPoint(i, 333)))
148 orphan_tx_pool[i].vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
149 150 with node.assert_debug_log(['orphanage overflow, removed 1 tx']):
151 node.p2ps[0].send_txs_and_test(orphan_tx_pool, node, success=False)
152 153 self.log.info('Test orphan with rejected parents')
154 rejected_parent = CTransaction()
155 rejected_parent.vin.append(CTxIn(outpoint=COutPoint(tx_orphan_2_invalid.sha256, 0)))
156 rejected_parent.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
157 rejected_parent.rehash()
158 with node.assert_debug_log(['not keeping orphan with rejected parents {}'.format(rejected_parent.hash)]):
159 node.p2ps[0].send_txs_and_test([rejected_parent], node, success=False)
160 161 self.log.info('Test that a peer disconnection causes erase its transactions from the orphan pool')
162 with node.assert_debug_log(['Erased 100 orphan transaction(s) from peer=']):
163 self.reconnect_p2p(num_connections=1)
164 165 self.log.info('Test that a transaction in the orphan pool is included in a new tip block causes erase this transaction from the orphan pool')
166 tx_withhold_until_block_A = CTransaction()
167 tx_withhold_until_block_A.vin.append(CTxIn(outpoint=COutPoint(tx_withhold.sha256, 1)))
168 tx_withhold_until_block_A.vout = [CTxOut(nValue=12 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE)] * 2
169 tx_withhold_until_block_A.calc_sha256()
170 171 tx_orphan_include_by_block_A = CTransaction()
172 tx_orphan_include_by_block_A.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_A.sha256, 0)))
173 tx_orphan_include_by_block_A.vout.append(CTxOut(nValue=12 * COIN - 12000, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
174 tx_orphan_include_by_block_A.calc_sha256()
175 176 self.log.info('Send the orphan ... ')
177 node.p2ps[0].send_txs_and_test([tx_orphan_include_by_block_A], node, success=False)
178 179 tip = int(node.getbestblockhash(), 16)
180 height = node.getblockcount() + 1
181 block_A = create_block(tip, create_coinbase(height))
182 block_A.vtx.extend([tx_withhold, tx_withhold_until_block_A, tx_orphan_include_by_block_A])
183 block_A.hashMerkleRoot = block_A.calc_merkle_root()
184 block_A.solve()
185 186 self.log.info('Send the block that includes the previous orphan ... ')
187 with node.assert_debug_log(["Erased 1 orphan transaction(s) included or conflicted by block"]):
188 node.p2ps[0].send_blocks_and_test([block_A], node, success=True)
189 node.syncwithvalidationinterfacequeue()
190 191 self.log.info('Test that a transaction in the orphan pool conflicts with a new tip block causes erase this transaction from the orphan pool')
192 tx_withhold_until_block_B = CTransaction()
193 tx_withhold_until_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_A.sha256, 1)))
194 tx_withhold_until_block_B.vout.append(CTxOut(nValue=11 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
195 tx_withhold_until_block_B.calc_sha256()
196 197 tx_orphan_include_by_block_B = CTransaction()
198 tx_orphan_include_by_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_B.sha256, 0)))
199 tx_orphan_include_by_block_B.vout.append(CTxOut(nValue=10 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
200 tx_orphan_include_by_block_B.calc_sha256()
201 202 tx_orphan_conflict_by_block_B = CTransaction()
203 tx_orphan_conflict_by_block_B.vin.append(CTxIn(outpoint=COutPoint(tx_withhold_until_block_B.sha256, 0)))
204 tx_orphan_conflict_by_block_B.vout.append(CTxOut(nValue=9 * COIN, scriptPubKey=SCRIPT_PUB_KEY_OP_TRUE))
205 tx_orphan_conflict_by_block_B.calc_sha256()
206 self.log.info('Send the orphan ... ')
207 node.p2ps[0].send_txs_and_test([tx_orphan_conflict_by_block_B], node, success=False)
208 209 tip = int(node.getbestblockhash(), 16)
210 height = node.getblockcount() + 1
211 block_B = create_block(tip, create_coinbase(height))
212 block_B.vtx.extend([tx_withhold_until_block_B, tx_orphan_include_by_block_B])
213 block_B.hashMerkleRoot = block_B.calc_merkle_root()
214 block_B.solve()
215 216 self.log.info('Send the block that includes a transaction which conflicts with the previous orphan ... ')
217 with node.assert_debug_log(["Erased 1 orphan transaction(s) included or conflicted by block"]):
218 node.p2ps[0].send_blocks_and_test([block_B], node, success=True)
219 node.syncwithvalidationinterfacequeue()
220 221 222 if __name__ == '__main__':
223 InvalidTxRequestTest(__file__).main()
224