[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / test / functional / p2p-compactblocks.py
blob94513d3f4387baa0db91fa124e9efd1acb85e3d8
1 #!/usr/bin/env python3
2 # Copyright (c) 2016 The Bitcoin Core 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 compact blocks (BIP 152).
7 Version 1 compact blocks are pre-segwit (txids)
8 Version 2 compact blocks are post-segwit (wtxids)
9 """
11 from test_framework.mininode import *
12 from test_framework.test_framework import BitcoinTestFramework
13 from test_framework.util import *
14 from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment
15 from test_framework.script import CScript, OP_TRUE
17 # TestNode: A peer we use to send messages to bitcoind, and store responses.
18 class TestNode(NodeConnCB):
19 def __init__(self):
20 super().__init__()
21 self.last_sendcmpct = []
22 self.block_announced = False
23 # Store the hashes of blocks we've seen announced.
24 # This is for synchronizing the p2p message traffic,
25 # so we can eg wait until a particular block is announced.
26 self.announced_blockhashes = set()
28 def on_sendcmpct(self, conn, message):
29 self.last_sendcmpct.append(message)
31 def on_cmpctblock(self, conn, message):
32 self.block_announced = True
33 self.last_message["cmpctblock"].header_and_shortids.header.calc_sha256()
34 self.announced_blockhashes.add(self.last_message["cmpctblock"].header_and_shortids.header.sha256)
36 def on_headers(self, conn, message):
37 self.block_announced = True
38 for x in self.last_message["headers"].headers:
39 x.calc_sha256()
40 self.announced_blockhashes.add(x.sha256)
42 def on_inv(self, conn, message):
43 for x in self.last_message["inv"].inv:
44 if x.type == 2:
45 self.block_announced = True
46 self.announced_blockhashes.add(x.hash)
48 # Requires caller to hold mininode_lock
49 def received_block_announcement(self):
50 return self.block_announced
52 def clear_block_announcement(self):
53 with mininode_lock:
54 self.block_announced = False
55 self.last_message.pop("inv", None)
56 self.last_message.pop("headers", None)
57 self.last_message.pop("cmpctblock", None)
59 def get_headers(self, locator, hashstop):
60 msg = msg_getheaders()
61 msg.locator.vHave = locator
62 msg.hashstop = hashstop
63 self.connection.send_message(msg)
65 def send_header_for_blocks(self, new_blocks):
66 headers_message = msg_headers()
67 headers_message.headers = [CBlockHeader(b) for b in new_blocks]
68 self.send_message(headers_message)
70 def request_headers_and_sync(self, locator, hashstop=0):
71 self.clear_block_announcement()
72 self.get_headers(locator, hashstop)
73 wait_until(self.received_block_announcement, timeout=30, lock=mininode_lock)
74 self.clear_block_announcement()
76 # Block until a block announcement for a particular block hash is
77 # received.
78 def wait_for_block_announcement(self, block_hash, timeout=30):
79 def received_hash():
80 return (block_hash in self.announced_blockhashes)
81 wait_until(received_hash, timeout=timeout, lock=mininode_lock)
83 def send_await_disconnect(self, message, timeout=30):
84 """Sends a message to the node and wait for disconnect.
86 This is used when we want to send a message into the node that we expect
87 will get us disconnected, eg an invalid block."""
88 self.send_message(message)
89 wait_until(lambda: not self.connected, timeout=timeout, lock=mininode_lock)
91 class CompactBlocksTest(BitcoinTestFramework):
92 def set_test_params(self):
93 self.setup_clean_chain = True
94 # Node0 = pre-segwit, node1 = segwit-aware
95 self.num_nodes = 2
96 self.extra_args = [["-vbparams=segwit:0:0"], ["-txindex"]]
97 self.utxos = []
99 def build_block_on_tip(self, node, segwit=False):
100 height = node.getblockcount()
101 tip = node.getbestblockhash()
102 mtp = node.getblockheader(tip)['mediantime']
103 block = create_block(int(tip, 16), create_coinbase(height + 1), mtp + 1)
104 block.nVersion = 4
105 if segwit:
106 add_witness_commitment(block)
107 block.solve()
108 return block
110 # Create 10 more anyone-can-spend utxo's for testing.
111 def make_utxos(self):
112 # Doesn't matter which node we use, just use node0.
113 block = self.build_block_on_tip(self.nodes[0])
114 self.test_node.send_and_ping(msg_block(block))
115 assert(int(self.nodes[0].getbestblockhash(), 16) == block.sha256)
116 self.nodes[0].generate(100)
118 total_value = block.vtx[0].vout[0].nValue
119 out_value = total_value // 10
120 tx = CTransaction()
121 tx.vin.append(CTxIn(COutPoint(block.vtx[0].sha256, 0), b''))
122 for i in range(10):
123 tx.vout.append(CTxOut(out_value, CScript([OP_TRUE])))
124 tx.rehash()
126 block2 = self.build_block_on_tip(self.nodes[0])
127 block2.vtx.append(tx)
128 block2.hashMerkleRoot = block2.calc_merkle_root()
129 block2.solve()
130 self.test_node.send_and_ping(msg_block(block2))
131 assert_equal(int(self.nodes[0].getbestblockhash(), 16), block2.sha256)
132 self.utxos.extend([[tx.sha256, i, out_value] for i in range(10)])
133 return
135 # Test "sendcmpct" (between peers preferring the same version):
136 # - No compact block announcements unless sendcmpct is sent.
137 # - If sendcmpct is sent with version > preferred_version, the message is ignored.
138 # - If sendcmpct is sent with boolean 0, then block announcements are not
139 # made with compact blocks.
140 # - If sendcmpct is then sent with boolean 1, then new block announcements
141 # are made with compact blocks.
142 # If old_node is passed in, request compact blocks with version=preferred-1
143 # and verify that it receives block announcements via compact block.
144 def test_sendcmpct(self, node, test_node, preferred_version, old_node=None):
145 # Make sure we get a SENDCMPCT message from our peer
146 def received_sendcmpct():
147 return (len(test_node.last_sendcmpct) > 0)
148 wait_until(received_sendcmpct, timeout=30, lock=mininode_lock)
149 with mininode_lock:
150 # Check that the first version received is the preferred one
151 assert_equal(test_node.last_sendcmpct[0].version, preferred_version)
152 # And that we receive versions down to 1.
153 assert_equal(test_node.last_sendcmpct[-1].version, 1)
154 test_node.last_sendcmpct = []
156 tip = int(node.getbestblockhash(), 16)
158 def check_announcement_of_new_block(node, peer, predicate):
159 peer.clear_block_announcement()
160 block_hash = int(node.generate(1)[0], 16)
161 peer.wait_for_block_announcement(block_hash, timeout=30)
162 assert(peer.block_announced)
164 with mininode_lock:
165 assert predicate(peer), (
166 "block_hash={!r}, cmpctblock={!r}, inv={!r}".format(
167 block_hash, peer.last_message.get("cmpctblock", None), peer.last_message.get("inv", None)))
169 # We shouldn't get any block announcements via cmpctblock yet.
170 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
172 # Try one more time, this time after requesting headers.
173 test_node.request_headers_and_sync(locator=[tip])
174 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message and "inv" in p.last_message)
176 # Test a few ways of using sendcmpct that should NOT
177 # result in compact block announcements.
178 # Before each test, sync the headers chain.
179 test_node.request_headers_and_sync(locator=[tip])
181 # Now try a SENDCMPCT message with too-high version
182 sendcmpct = msg_sendcmpct()
183 sendcmpct.version = preferred_version+1
184 sendcmpct.announce = True
185 test_node.send_and_ping(sendcmpct)
186 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
188 # Headers sync before next test.
189 test_node.request_headers_and_sync(locator=[tip])
191 # Now try a SENDCMPCT message with valid version, but announce=False
192 sendcmpct.version = preferred_version
193 sendcmpct.announce = False
194 test_node.send_and_ping(sendcmpct)
195 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message)
197 # Headers sync before next test.
198 test_node.request_headers_and_sync(locator=[tip])
200 # Finally, try a SENDCMPCT message with announce=True
201 sendcmpct.version = preferred_version
202 sendcmpct.announce = True
203 test_node.send_and_ping(sendcmpct)
204 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
206 # Try one more time (no headers sync should be needed!)
207 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
209 # Try one more time, after turning on sendheaders
210 test_node.send_and_ping(msg_sendheaders())
211 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
213 # Try one more time, after sending a version-1, announce=false message.
214 sendcmpct.version = preferred_version-1
215 sendcmpct.announce = False
216 test_node.send_and_ping(sendcmpct)
217 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" in p.last_message)
219 # Now turn off announcements
220 sendcmpct.version = preferred_version
221 sendcmpct.announce = False
222 test_node.send_and_ping(sendcmpct)
223 check_announcement_of_new_block(node, test_node, lambda p: "cmpctblock" not in p.last_message and "headers" in p.last_message)
225 if old_node is not None:
226 # Verify that a peer using an older protocol version can receive
227 # announcements from this node.
228 sendcmpct.version = preferred_version-1
229 sendcmpct.announce = True
230 old_node.send_and_ping(sendcmpct)
231 # Header sync
232 old_node.request_headers_and_sync(locator=[tip])
233 check_announcement_of_new_block(node, old_node, lambda p: "cmpctblock" in p.last_message)
235 # This test actually causes bitcoind to (reasonably!) disconnect us, so do this last.
236 def test_invalid_cmpctblock_message(self):
237 self.nodes[0].generate(101)
238 block = self.build_block_on_tip(self.nodes[0])
240 cmpct_block = P2PHeaderAndShortIDs()
241 cmpct_block.header = CBlockHeader(block)
242 cmpct_block.prefilled_txn_length = 1
243 # This index will be too high
244 prefilled_txn = PrefilledTransaction(1, block.vtx[0])
245 cmpct_block.prefilled_txn = [prefilled_txn]
246 self.test_node.send_await_disconnect(msg_cmpctblock(cmpct_block))
247 assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.hashPrevBlock)
249 # Compare the generated shortids to what we expect based on BIP 152, given
250 # bitcoind's choice of nonce.
251 def test_compactblock_construction(self, node, test_node, version, use_witness_address):
252 # Generate a bunch of transactions.
253 node.generate(101)
254 num_transactions = 25
255 address = node.getnewaddress()
256 if use_witness_address:
257 # Want at least one segwit spend, so move all funds to
258 # a witness address.
259 address = node.addwitnessaddress(address)
260 value_to_send = node.getbalance()
261 node.sendtoaddress(address, satoshi_round(value_to_send-Decimal(0.1)))
262 node.generate(1)
264 segwit_tx_generated = False
265 for i in range(num_transactions):
266 txid = node.sendtoaddress(address, 0.1)
267 hex_tx = node.gettransaction(txid)["hex"]
268 tx = FromHex(CTransaction(), hex_tx)
269 if not tx.wit.is_null():
270 segwit_tx_generated = True
272 if use_witness_address:
273 assert(segwit_tx_generated) # check that our test is not broken
275 # Wait until we've seen the block announcement for the resulting tip
276 tip = int(node.getbestblockhash(), 16)
277 test_node.wait_for_block_announcement(tip)
279 # Make sure we will receive a fast-announce compact block
280 self.request_cb_announcements(test_node, node, version)
282 # Now mine a block, and look at the resulting compact block.
283 test_node.clear_block_announcement()
284 block_hash = int(node.generate(1)[0], 16)
286 # Store the raw block in our internal format.
287 block = FromHex(CBlock(), node.getblock("%02x" % block_hash, False))
288 for tx in block.vtx:
289 tx.calc_sha256()
290 block.rehash()
292 # Wait until the block was announced (via compact blocks)
293 wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
295 # Now fetch and check the compact block
296 header_and_shortids = None
297 with mininode_lock:
298 assert("cmpctblock" in test_node.last_message)
299 # Convert the on-the-wire representation to absolute indexes
300 header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids)
301 self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block)
303 # Now fetch the compact block using a normal non-announce getdata
304 with mininode_lock:
305 test_node.clear_block_announcement()
306 inv = CInv(4, block_hash) # 4 == "CompactBlock"
307 test_node.send_message(msg_getdata([inv]))
309 wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
311 # Now fetch and check the compact block
312 header_and_shortids = None
313 with mininode_lock:
314 assert("cmpctblock" in test_node.last_message)
315 # Convert the on-the-wire representation to absolute indexes
316 header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids)
317 self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block)
319 def check_compactblock_construction_from_block(self, version, header_and_shortids, block_hash, block):
320 # Check that we got the right block!
321 header_and_shortids.header.calc_sha256()
322 assert_equal(header_and_shortids.header.sha256, block_hash)
324 # Make sure the prefilled_txn appears to have included the coinbase
325 assert(len(header_and_shortids.prefilled_txn) >= 1)
326 assert_equal(header_and_shortids.prefilled_txn[0].index, 0)
328 # Check that all prefilled_txn entries match what's in the block.
329 for entry in header_and_shortids.prefilled_txn:
330 entry.tx.calc_sha256()
331 # This checks the non-witness parts of the tx agree
332 assert_equal(entry.tx.sha256, block.vtx[entry.index].sha256)
334 # And this checks the witness
335 wtxid = entry.tx.calc_sha256(True)
336 if version == 2:
337 assert_equal(wtxid, block.vtx[entry.index].calc_sha256(True))
338 else:
339 # Shouldn't have received a witness
340 assert(entry.tx.wit.is_null())
342 # Check that the cmpctblock message announced all the transactions.
343 assert_equal(len(header_and_shortids.prefilled_txn) + len(header_and_shortids.shortids), len(block.vtx))
345 # And now check that all the shortids are as expected as well.
346 # Determine the siphash keys to use.
347 [k0, k1] = header_and_shortids.get_siphash_keys()
349 index = 0
350 while index < len(block.vtx):
351 if (len(header_and_shortids.prefilled_txn) > 0 and
352 header_and_shortids.prefilled_txn[0].index == index):
353 # Already checked prefilled transactions above
354 header_and_shortids.prefilled_txn.pop(0)
355 else:
356 tx_hash = block.vtx[index].sha256
357 if version == 2:
358 tx_hash = block.vtx[index].calc_sha256(True)
359 shortid = calculate_shortid(k0, k1, tx_hash)
360 assert_equal(shortid, header_and_shortids.shortids[0])
361 header_and_shortids.shortids.pop(0)
362 index += 1
364 # Test that bitcoind requests compact blocks when we announce new blocks
365 # via header or inv, and that responding to getblocktxn causes the block
366 # to be successfully reconstructed.
367 # Post-segwit: upgraded nodes would only make this request of cb-version-2,
368 # NODE_WITNESS peers. Unupgraded nodes would still make this request of
369 # any cb-version-1-supporting peer.
370 def test_compactblock_requests(self, node, test_node, version, segwit):
371 # Try announcing a block with an inv or header, expect a compactblock
372 # request
373 for announce in ["inv", "header"]:
374 block = self.build_block_on_tip(node, segwit=segwit)
375 with mininode_lock:
376 test_node.last_message.pop("getdata", None)
378 if announce == "inv":
379 test_node.send_message(msg_inv([CInv(2, block.sha256)]))
380 wait_until(lambda: "getheaders" in test_node.last_message, timeout=30, lock=mininode_lock)
381 test_node.send_header_for_blocks([block])
382 else:
383 test_node.send_header_for_blocks([block])
384 wait_until(lambda: "getdata" in test_node.last_message, timeout=30, lock=mininode_lock)
385 assert_equal(len(test_node.last_message["getdata"].inv), 1)
386 assert_equal(test_node.last_message["getdata"].inv[0].type, 4)
387 assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
389 # Send back a compactblock message that omits the coinbase
390 comp_block = HeaderAndShortIDs()
391 comp_block.header = CBlockHeader(block)
392 comp_block.nonce = 0
393 [k0, k1] = comp_block.get_siphash_keys()
394 coinbase_hash = block.vtx[0].sha256
395 if version == 2:
396 coinbase_hash = block.vtx[0].calc_sha256(True)
397 comp_block.shortids = [
398 calculate_shortid(k0, k1, coinbase_hash) ]
399 test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
400 assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
401 # Expect a getblocktxn message.
402 with mininode_lock:
403 assert("getblocktxn" in test_node.last_message)
404 absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute()
405 assert_equal(absolute_indexes, [0]) # should be a coinbase request
407 # Send the coinbase, and verify that the tip advances.
408 if version == 2:
409 msg = msg_witness_blocktxn()
410 else:
411 msg = msg_blocktxn()
412 msg.block_transactions.blockhash = block.sha256
413 msg.block_transactions.transactions = [block.vtx[0]]
414 test_node.send_and_ping(msg)
415 assert_equal(int(node.getbestblockhash(), 16), block.sha256)
417 # Create a chain of transactions from given utxo, and add to a new block.
418 def build_block_with_transactions(self, node, utxo, num_transactions):
419 block = self.build_block_on_tip(node)
421 for i in range(num_transactions):
422 tx = CTransaction()
423 tx.vin.append(CTxIn(COutPoint(utxo[0], utxo[1]), b''))
424 tx.vout.append(CTxOut(utxo[2] - 1000, CScript([OP_TRUE])))
425 tx.rehash()
426 utxo = [tx.sha256, 0, tx.vout[0].nValue]
427 block.vtx.append(tx)
429 block.hashMerkleRoot = block.calc_merkle_root()
430 block.solve()
431 return block
433 # Test that we only receive getblocktxn requests for transactions that the
434 # node needs, and that responding to them causes the block to be
435 # reconstructed.
436 def test_getblocktxn_requests(self, node, test_node, version):
437 with_witness = (version==2)
439 def test_getblocktxn_response(compact_block, peer, expected_result):
440 msg = msg_cmpctblock(compact_block.to_p2p())
441 peer.send_and_ping(msg)
442 with mininode_lock:
443 assert("getblocktxn" in peer.last_message)
444 absolute_indexes = peer.last_message["getblocktxn"].block_txn_request.to_absolute()
445 assert_equal(absolute_indexes, expected_result)
447 def test_tip_after_message(node, peer, msg, tip):
448 peer.send_and_ping(msg)
449 assert_equal(int(node.getbestblockhash(), 16), tip)
451 # First try announcing compactblocks that won't reconstruct, and verify
452 # that we receive getblocktxn messages back.
453 utxo = self.utxos.pop(0)
455 block = self.build_block_with_transactions(node, utxo, 5)
456 self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
457 comp_block = HeaderAndShortIDs()
458 comp_block.initialize_from_block(block, use_witness=with_witness)
460 test_getblocktxn_response(comp_block, test_node, [1, 2, 3, 4, 5])
462 msg_bt = msg_blocktxn()
463 if with_witness:
464 msg_bt = msg_witness_blocktxn() # serialize with witnesses
465 msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[1:])
466 test_tip_after_message(node, test_node, msg_bt, block.sha256)
468 utxo = self.utxos.pop(0)
469 block = self.build_block_with_transactions(node, utxo, 5)
470 self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
472 # Now try interspersing the prefilled transactions
473 comp_block.initialize_from_block(block, prefill_list=[0, 1, 5], use_witness=with_witness)
474 test_getblocktxn_response(comp_block, test_node, [2, 3, 4])
475 msg_bt.block_transactions = BlockTransactions(block.sha256, block.vtx[2:5])
476 test_tip_after_message(node, test_node, msg_bt, block.sha256)
478 # Now try giving one transaction ahead of time.
479 utxo = self.utxos.pop(0)
480 block = self.build_block_with_transactions(node, utxo, 5)
481 self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
482 test_node.send_and_ping(msg_tx(block.vtx[1]))
483 assert(block.vtx[1].hash in node.getrawmempool())
485 # Prefill 4 out of the 6 transactions, and verify that only the one
486 # that was not in the mempool is requested.
487 comp_block.initialize_from_block(block, prefill_list=[0, 2, 3, 4], use_witness=with_witness)
488 test_getblocktxn_response(comp_block, test_node, [5])
490 msg_bt.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]])
491 test_tip_after_message(node, test_node, msg_bt, block.sha256)
493 # Now provide all transactions to the node before the block is
494 # announced and verify reconstruction happens immediately.
495 utxo = self.utxos.pop(0)
496 block = self.build_block_with_transactions(node, utxo, 10)
497 self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
498 for tx in block.vtx[1:]:
499 test_node.send_message(msg_tx(tx))
500 test_node.sync_with_ping()
501 # Make sure all transactions were accepted.
502 mempool = node.getrawmempool()
503 for tx in block.vtx[1:]:
504 assert(tx.hash in mempool)
506 # Clear out last request.
507 with mininode_lock:
508 test_node.last_message.pop("getblocktxn", None)
510 # Send compact block
511 comp_block.initialize_from_block(block, prefill_list=[0], use_witness=with_witness)
512 test_tip_after_message(node, test_node, msg_cmpctblock(comp_block.to_p2p()), block.sha256)
513 with mininode_lock:
514 # Shouldn't have gotten a request for any transaction
515 assert("getblocktxn" not in test_node.last_message)
517 # Incorrectly responding to a getblocktxn shouldn't cause the block to be
518 # permanently failed.
519 def test_incorrect_blocktxn_response(self, node, test_node, version):
520 if (len(self.utxos) == 0):
521 self.make_utxos()
522 utxo = self.utxos.pop(0)
524 block = self.build_block_with_transactions(node, utxo, 10)
525 self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
526 # Relay the first 5 transactions from the block in advance
527 for tx in block.vtx[1:6]:
528 test_node.send_message(msg_tx(tx))
529 test_node.sync_with_ping()
530 # Make sure all transactions were accepted.
531 mempool = node.getrawmempool()
532 for tx in block.vtx[1:6]:
533 assert(tx.hash in mempool)
535 # Send compact block
536 comp_block = HeaderAndShortIDs()
537 comp_block.initialize_from_block(block, prefill_list=[0], use_witness=(version == 2))
538 test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
539 absolute_indexes = []
540 with mininode_lock:
541 assert("getblocktxn" in test_node.last_message)
542 absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute()
543 assert_equal(absolute_indexes, [6, 7, 8, 9, 10])
545 # Now give an incorrect response.
546 # Note that it's possible for bitcoind to be smart enough to know we're
547 # lying, since it could check to see if the shortid matches what we're
548 # sending, and eg disconnect us for misbehavior. If that behavior
549 # change were made, we could just modify this test by having a
550 # different peer provide the block further down, so that we're still
551 # verifying that the block isn't marked bad permanently. This is good
552 # enough for now.
553 msg = msg_blocktxn()
554 if version==2:
555 msg = msg_witness_blocktxn()
556 msg.block_transactions = BlockTransactions(block.sha256, [block.vtx[5]] + block.vtx[7:])
557 test_node.send_and_ping(msg)
559 # Tip should not have updated
560 assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
562 # We should receive a getdata request
563 wait_until(lambda: "getdata" in test_node.last_message, timeout=10, lock=mininode_lock)
564 assert_equal(len(test_node.last_message["getdata"].inv), 1)
565 assert(test_node.last_message["getdata"].inv[0].type == 2 or test_node.last_message["getdata"].inv[0].type == 2|MSG_WITNESS_FLAG)
566 assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
568 # Deliver the block
569 if version==2:
570 test_node.send_and_ping(msg_witness_block(block))
571 else:
572 test_node.send_and_ping(msg_block(block))
573 assert_equal(int(node.getbestblockhash(), 16), block.sha256)
575 def test_getblocktxn_handler(self, node, test_node, version):
576 # bitcoind will not send blocktxn responses for blocks whose height is
577 # more than 10 blocks deep.
578 MAX_GETBLOCKTXN_DEPTH = 10
579 chain_height = node.getblockcount()
580 current_height = chain_height
581 while (current_height >= chain_height - MAX_GETBLOCKTXN_DEPTH):
582 block_hash = node.getblockhash(current_height)
583 block = FromHex(CBlock(), node.getblock(block_hash, False))
585 msg = msg_getblocktxn()
586 msg.block_txn_request = BlockTransactionsRequest(int(block_hash, 16), [])
587 num_to_request = random.randint(1, len(block.vtx))
588 msg.block_txn_request.from_absolute(sorted(random.sample(range(len(block.vtx)), num_to_request)))
589 test_node.send_message(msg)
590 wait_until(lambda: "blocktxn" in test_node.last_message, timeout=10, lock=mininode_lock)
592 [tx.calc_sha256() for tx in block.vtx]
593 with mininode_lock:
594 assert_equal(test_node.last_message["blocktxn"].block_transactions.blockhash, int(block_hash, 16))
595 all_indices = msg.block_txn_request.to_absolute()
596 for index in all_indices:
597 tx = test_node.last_message["blocktxn"].block_transactions.transactions.pop(0)
598 tx.calc_sha256()
599 assert_equal(tx.sha256, block.vtx[index].sha256)
600 if version == 1:
601 # Witnesses should have been stripped
602 assert(tx.wit.is_null())
603 else:
604 # Check that the witness matches
605 assert_equal(tx.calc_sha256(True), block.vtx[index].calc_sha256(True))
606 test_node.last_message.pop("blocktxn", None)
607 current_height -= 1
609 # Next request should send a full block response, as we're past the
610 # allowed depth for a blocktxn response.
611 block_hash = node.getblockhash(current_height)
612 msg.block_txn_request = BlockTransactionsRequest(int(block_hash, 16), [0])
613 with mininode_lock:
614 test_node.last_message.pop("block", None)
615 test_node.last_message.pop("blocktxn", None)
616 test_node.send_and_ping(msg)
617 with mininode_lock:
618 test_node.last_message["block"].block.calc_sha256()
619 assert_equal(test_node.last_message["block"].block.sha256, int(block_hash, 16))
620 assert "blocktxn" not in test_node.last_message
622 def test_compactblocks_not_at_tip(self, node, test_node):
623 # Test that requesting old compactblocks doesn't work.
624 MAX_CMPCTBLOCK_DEPTH = 5
625 new_blocks = []
626 for i in range(MAX_CMPCTBLOCK_DEPTH + 1):
627 test_node.clear_block_announcement()
628 new_blocks.append(node.generate(1)[0])
629 wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
631 test_node.clear_block_announcement()
632 test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
633 wait_until(lambda: "cmpctblock" in test_node.last_message, timeout=30, lock=mininode_lock)
635 test_node.clear_block_announcement()
636 node.generate(1)
637 wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
638 test_node.clear_block_announcement()
639 with mininode_lock:
640 test_node.last_message.pop("block", None)
641 test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
642 wait_until(lambda: "block" in test_node.last_message, timeout=30, lock=mininode_lock)
643 with mininode_lock:
644 test_node.last_message["block"].block.calc_sha256()
645 assert_equal(test_node.last_message["block"].block.sha256, int(new_blocks[0], 16))
647 # Generate an old compactblock, and verify that it's not accepted.
648 cur_height = node.getblockcount()
649 hashPrevBlock = int(node.getblockhash(cur_height-5), 16)
650 block = self.build_block_on_tip(node)
651 block.hashPrevBlock = hashPrevBlock
652 block.solve()
654 comp_block = HeaderAndShortIDs()
655 comp_block.initialize_from_block(block)
656 test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
658 tips = node.getchaintips()
659 found = False
660 for x in tips:
661 if x["hash"] == block.hash:
662 assert_equal(x["status"], "headers-only")
663 found = True
664 break
665 assert(found)
667 # Requesting this block via getblocktxn should silently fail
668 # (to avoid fingerprinting attacks).
669 msg = msg_getblocktxn()
670 msg.block_txn_request = BlockTransactionsRequest(block.sha256, [0])
671 with mininode_lock:
672 test_node.last_message.pop("blocktxn", None)
673 test_node.send_and_ping(msg)
674 with mininode_lock:
675 assert "blocktxn" not in test_node.last_message
677 def activate_segwit(self, node):
678 node.generate(144*3)
679 assert_equal(get_bip9_status(node, "segwit")["status"], 'active')
681 def test_end_to_end_block_relay(self, node, listeners):
682 utxo = self.utxos.pop(0)
684 block = self.build_block_with_transactions(node, utxo, 10)
686 [l.clear_block_announcement() for l in listeners]
688 # ToHex() won't serialize with witness, but this block has no witnesses
689 # anyway. TODO: repeat this test with witness tx's to a segwit node.
690 node.submitblock(ToHex(block))
692 for l in listeners:
693 wait_until(lambda: l.received_block_announcement(), timeout=30, lock=mininode_lock)
694 with mininode_lock:
695 for l in listeners:
696 assert "cmpctblock" in l.last_message
697 l.last_message["cmpctblock"].header_and_shortids.header.calc_sha256()
698 assert_equal(l.last_message["cmpctblock"].header_and_shortids.header.sha256, block.sha256)
700 # Test that we don't get disconnected if we relay a compact block with valid header,
701 # but invalid transactions.
702 def test_invalid_tx_in_compactblock(self, node, test_node, use_segwit):
703 assert(len(self.utxos))
704 utxo = self.utxos[0]
706 block = self.build_block_with_transactions(node, utxo, 5)
707 del block.vtx[3]
708 block.hashMerkleRoot = block.calc_merkle_root()
709 if use_segwit:
710 # If we're testing with segwit, also drop the coinbase witness,
711 # but include the witness commitment.
712 add_witness_commitment(block)
713 block.vtx[0].wit.vtxinwit = []
714 block.solve()
716 # Now send the compact block with all transactions prefilled, and
717 # verify that we don't get disconnected.
718 comp_block = HeaderAndShortIDs()
719 comp_block.initialize_from_block(block, prefill_list=[0, 1, 2, 3, 4], use_witness=use_segwit)
720 msg = msg_cmpctblock(comp_block.to_p2p())
721 test_node.send_and_ping(msg)
723 # Check that the tip didn't advance
724 assert(int(node.getbestblockhash(), 16) is not block.sha256)
725 test_node.sync_with_ping()
727 # Helper for enabling cb announcements
728 # Send the sendcmpct request and sync headers
729 def request_cb_announcements(self, peer, node, version):
730 tip = node.getbestblockhash()
731 peer.get_headers(locator=[int(tip, 16)], hashstop=0)
733 msg = msg_sendcmpct()
734 msg.version = version
735 msg.announce = True
736 peer.send_and_ping(msg)
738 def test_compactblock_reconstruction_multiple_peers(self, node, stalling_peer, delivery_peer):
739 assert(len(self.utxos))
741 def announce_cmpct_block(node, peer):
742 utxo = self.utxos.pop(0)
743 block = self.build_block_with_transactions(node, utxo, 5)
745 cmpct_block = HeaderAndShortIDs()
746 cmpct_block.initialize_from_block(block)
747 msg = msg_cmpctblock(cmpct_block.to_p2p())
748 peer.send_and_ping(msg)
749 with mininode_lock:
750 assert "getblocktxn" in peer.last_message
751 return block, cmpct_block
753 block, cmpct_block = announce_cmpct_block(node, stalling_peer)
755 for tx in block.vtx[1:]:
756 delivery_peer.send_message(msg_tx(tx))
757 delivery_peer.sync_with_ping()
758 mempool = node.getrawmempool()
759 for tx in block.vtx[1:]:
760 assert(tx.hash in mempool)
762 delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
763 assert_equal(int(node.getbestblockhash(), 16), block.sha256)
765 self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
767 # Now test that delivering an invalid compact block won't break relay
769 block, cmpct_block = announce_cmpct_block(node, stalling_peer)
770 for tx in block.vtx[1:]:
771 delivery_peer.send_message(msg_tx(tx))
772 delivery_peer.sync_with_ping()
774 cmpct_block.prefilled_txn[0].tx.wit.vtxinwit = [ CTxInWitness() ]
775 cmpct_block.prefilled_txn[0].tx.wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(0)]
777 cmpct_block.use_witness = True
778 delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
779 assert(int(node.getbestblockhash(), 16) != block.sha256)
781 msg = msg_blocktxn()
782 msg.block_transactions.blockhash = block.sha256
783 msg.block_transactions.transactions = block.vtx[1:]
784 stalling_peer.send_and_ping(msg)
785 assert_equal(int(node.getbestblockhash(), 16), block.sha256)
787 def run_test(self):
788 # Setup the p2p connections and start up the network thread.
789 self.test_node = TestNode()
790 self.segwit_node = TestNode()
791 self.old_node = TestNode() # version 1 peer <--> segwit node
793 connections = []
794 connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node))
795 connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1],
796 self.segwit_node, services=NODE_NETWORK|NODE_WITNESS))
797 connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1],
798 self.old_node, services=NODE_NETWORK))
799 self.test_node.add_connection(connections[0])
800 self.segwit_node.add_connection(connections[1])
801 self.old_node.add_connection(connections[2])
803 NetworkThread().start() # Start up network handling in another thread
805 # Test logic begins here
806 self.test_node.wait_for_verack()
808 # We will need UTXOs to construct transactions in later tests.
809 self.make_utxos()
811 self.log.info("Running tests, pre-segwit activation:")
813 self.log.info("Testing SENDCMPCT p2p message... ")
814 self.test_sendcmpct(self.nodes[0], self.test_node, 1)
815 sync_blocks(self.nodes)
816 self.test_sendcmpct(self.nodes[1], self.segwit_node, 2, old_node=self.old_node)
817 sync_blocks(self.nodes)
819 self.log.info("Testing compactblock construction...")
820 self.test_compactblock_construction(self.nodes[0], self.test_node, 1, False)
821 sync_blocks(self.nodes)
822 self.test_compactblock_construction(self.nodes[1], self.segwit_node, 2, False)
823 sync_blocks(self.nodes)
825 self.log.info("Testing compactblock requests... ")
826 self.test_compactblock_requests(self.nodes[0], self.test_node, 1, False)
827 sync_blocks(self.nodes)
828 self.test_compactblock_requests(self.nodes[1], self.segwit_node, 2, False)
829 sync_blocks(self.nodes)
831 self.log.info("Testing getblocktxn requests...")
832 self.test_getblocktxn_requests(self.nodes[0], self.test_node, 1)
833 sync_blocks(self.nodes)
834 self.test_getblocktxn_requests(self.nodes[1], self.segwit_node, 2)
835 sync_blocks(self.nodes)
837 self.log.info("Testing getblocktxn handler...")
838 self.test_getblocktxn_handler(self.nodes[0], self.test_node, 1)
839 sync_blocks(self.nodes)
840 self.test_getblocktxn_handler(self.nodes[1], self.segwit_node, 2)
841 self.test_getblocktxn_handler(self.nodes[1], self.old_node, 1)
842 sync_blocks(self.nodes)
844 self.log.info("Testing compactblock requests/announcements not at chain tip...")
845 self.test_compactblocks_not_at_tip(self.nodes[0], self.test_node)
846 sync_blocks(self.nodes)
847 self.test_compactblocks_not_at_tip(self.nodes[1], self.segwit_node)
848 self.test_compactblocks_not_at_tip(self.nodes[1], self.old_node)
849 sync_blocks(self.nodes)
851 self.log.info("Testing handling of incorrect blocktxn responses...")
852 self.test_incorrect_blocktxn_response(self.nodes[0], self.test_node, 1)
853 sync_blocks(self.nodes)
854 self.test_incorrect_blocktxn_response(self.nodes[1], self.segwit_node, 2)
855 sync_blocks(self.nodes)
857 # End-to-end block relay tests
858 self.log.info("Testing end-to-end block relay...")
859 self.request_cb_announcements(self.test_node, self.nodes[0], 1)
860 self.request_cb_announcements(self.old_node, self.nodes[1], 1)
861 self.request_cb_announcements(self.segwit_node, self.nodes[1], 2)
862 self.test_end_to_end_block_relay(self.nodes[0], [self.segwit_node, self.test_node, self.old_node])
863 self.test_end_to_end_block_relay(self.nodes[1], [self.segwit_node, self.test_node, self.old_node])
865 self.log.info("Testing handling of invalid compact blocks...")
866 self.test_invalid_tx_in_compactblock(self.nodes[0], self.test_node, False)
867 self.test_invalid_tx_in_compactblock(self.nodes[1], self.segwit_node, False)
868 self.test_invalid_tx_in_compactblock(self.nodes[1], self.old_node, False)
870 self.log.info("Testing reconstructing compact blocks from all peers...")
871 self.test_compactblock_reconstruction_multiple_peers(self.nodes[1], self.segwit_node, self.old_node)
872 sync_blocks(self.nodes)
874 # Advance to segwit activation
875 self.log.info("Advancing to segwit activation")
876 self.activate_segwit(self.nodes[1])
877 self.log.info("Running tests, post-segwit activation...")
879 self.log.info("Testing compactblock construction...")
880 self.test_compactblock_construction(self.nodes[1], self.old_node, 1, True)
881 self.test_compactblock_construction(self.nodes[1], self.segwit_node, 2, True)
882 sync_blocks(self.nodes)
884 self.log.info("Testing compactblock requests (unupgraded node)... ")
885 self.test_compactblock_requests(self.nodes[0], self.test_node, 1, True)
887 self.log.info("Testing getblocktxn requests (unupgraded node)...")
888 self.test_getblocktxn_requests(self.nodes[0], self.test_node, 1)
890 # Need to manually sync node0 and node1, because post-segwit activation,
891 # node1 will not download blocks from node0.
892 self.log.info("Syncing nodes...")
893 assert(self.nodes[0].getbestblockhash() != self.nodes[1].getbestblockhash())
894 while (self.nodes[0].getblockcount() > self.nodes[1].getblockcount()):
895 block_hash = self.nodes[0].getblockhash(self.nodes[1].getblockcount()+1)
896 self.nodes[1].submitblock(self.nodes[0].getblock(block_hash, False))
897 assert_equal(self.nodes[0].getbestblockhash(), self.nodes[1].getbestblockhash())
899 self.log.info("Testing compactblock requests (segwit node)... ")
900 self.test_compactblock_requests(self.nodes[1], self.segwit_node, 2, True)
902 self.log.info("Testing getblocktxn requests (segwit node)...")
903 self.test_getblocktxn_requests(self.nodes[1], self.segwit_node, 2)
904 sync_blocks(self.nodes)
906 self.log.info("Testing getblocktxn handler (segwit node should return witnesses)...")
907 self.test_getblocktxn_handler(self.nodes[1], self.segwit_node, 2)
908 self.test_getblocktxn_handler(self.nodes[1], self.old_node, 1)
910 # Test that if we submitblock to node1, we'll get a compact block
911 # announcement to all peers.
912 # (Post-segwit activation, blocks won't propagate from node0 to node1
913 # automatically, so don't bother testing a block announced to node0.)
914 self.log.info("Testing end-to-end block relay...")
915 self.request_cb_announcements(self.test_node, self.nodes[0], 1)
916 self.request_cb_announcements(self.old_node, self.nodes[1], 1)
917 self.request_cb_announcements(self.segwit_node, self.nodes[1], 2)
918 self.test_end_to_end_block_relay(self.nodes[1], [self.segwit_node, self.test_node, self.old_node])
920 self.log.info("Testing handling of invalid compact blocks...")
921 self.test_invalid_tx_in_compactblock(self.nodes[0], self.test_node, False)
922 self.test_invalid_tx_in_compactblock(self.nodes[1], self.segwit_node, True)
923 self.test_invalid_tx_in_compactblock(self.nodes[1], self.old_node, True)
925 self.log.info("Testing invalid index in cmpctblock message...")
926 self.test_invalid_cmpctblock_message()
929 if __name__ == '__main__':
930 CompactBlocksTest().main()