[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / test / functional / assumevalid.py
blob65685c48b7eef7e314375a751964057b2e3f1bdf
1 #!/usr/bin/env python3
2 # Copyright (c) 2014-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 logic for skipping signature validation on old blocks.
7 Test logic for skipping signature validation on blocks which we've assumed
8 valid (https://github.com/bitcoin/bitcoin/pull/9484)
10 We build a chain that includes and invalid signature for one of the
11 transactions:
13 0: genesis block
14 1: block 1 with coinbase transaction output.
15 2-101: bury that block with 100 blocks so the coinbase transaction
16 output can be spent
17 102: a block containing a transaction spending the coinbase
18 transaction output. The transaction has an invalid signature.
19 103-2202: bury the bad block with just over two weeks' worth of blocks
20 (2100 blocks)
22 Start three nodes:
24 - node0 has no -assumevalid parameter. Try to sync to block 2202. It will
25 reject block 102 and only sync as far as block 101
26 - node1 has -assumevalid set to the hash of block 102. Try to sync to
27 block 2202. node1 will sync all the way to block 2202.
28 - node2 has -assumevalid set to the hash of block 102. Try to sync to
29 block 200. node2 will reject block 102 since it's assumed valid, but it
30 isn't buried by at least two weeks' work.
31 """
32 import time
34 from test_framework.blocktools import (create_block, create_coinbase)
35 from test_framework.key import CECKey
36 from test_framework.mininode import (CBlockHeader,
37 COutPoint,
38 CTransaction,
39 CTxIn,
40 CTxOut,
41 NetworkThread,
42 NodeConn,
43 NodeConnCB,
44 msg_block,
45 msg_headers)
46 from test_framework.script import (CScript, OP_TRUE)
47 from test_framework.test_framework import BitcoinTestFramework
48 from test_framework.util import (p2p_port, assert_equal)
50 class BaseNode(NodeConnCB):
51 def send_header_for_blocks(self, new_blocks):
52 headers_message = msg_headers()
53 headers_message.headers = [CBlockHeader(b) for b in new_blocks]
54 self.send_message(headers_message)
56 class AssumeValidTest(BitcoinTestFramework):
57 def set_test_params(self):
58 self.setup_clean_chain = True
59 self.num_nodes = 3
61 def setup_network(self):
62 self.add_nodes(3)
63 # Start node0. We don't start the other nodes yet since
64 # we need to pre-mine a block with an invalid transaction
65 # signature so we can pass in the block hash as assumevalid.
66 self.start_node(0)
68 def send_blocks_until_disconnected(self, node):
69 """Keep sending blocks to the node until we're disconnected."""
70 for i in range(len(self.blocks)):
71 if not node.connection:
72 break
73 try:
74 node.send_message(msg_block(self.blocks[i]))
75 except IOError as e:
76 assert str(e) == 'Not connected, no pushbuf'
77 break
79 def assert_blockchain_height(self, node, height):
80 """Wait until the blockchain is no longer advancing and verify it's reached the expected height."""
81 last_height = node.getblock(node.getbestblockhash())['height']
82 timeout = 10
83 while True:
84 time.sleep(0.25)
85 current_height = node.getblock(node.getbestblockhash())['height']
86 if current_height != last_height:
87 last_height = current_height
88 if timeout < 0:
89 assert False, "blockchain too short after timeout: %d" % current_height
90 timeout - 0.25
91 continue
92 elif current_height > height:
93 assert False, "blockchain too long: %d" % current_height
94 elif current_height == height:
95 break
97 def run_test(self):
99 # Connect to node0
100 node0 = BaseNode()
101 connections = []
102 connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], node0))
103 node0.add_connection(connections[0])
105 NetworkThread().start() # Start up network handling in another thread
106 node0.wait_for_verack()
108 # Build the blockchain
109 self.tip = int(self.nodes[0].getbestblockhash(), 16)
110 self.block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time'] + 1
112 self.blocks = []
114 # Get a pubkey for the coinbase TXO
115 coinbase_key = CECKey()
116 coinbase_key.set_secretbytes(b"horsebattery")
117 coinbase_pubkey = coinbase_key.get_pubkey()
119 # Create the first block with a coinbase output to our key
120 height = 1
121 block = create_block(self.tip, create_coinbase(height, coinbase_pubkey), self.block_time)
122 self.blocks.append(block)
123 self.block_time += 1
124 block.solve()
125 # Save the coinbase for later
126 self.block1 = block
127 self.tip = block.sha256
128 height += 1
130 # Bury the block 100 deep so the coinbase output is spendable
131 for i in range(100):
132 block = create_block(self.tip, create_coinbase(height), self.block_time)
133 block.solve()
134 self.blocks.append(block)
135 self.tip = block.sha256
136 self.block_time += 1
137 height += 1
139 # Create a transaction spending the coinbase output with an invalid (null) signature
140 tx = CTransaction()
141 tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b""))
142 tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE])))
143 tx.calc_sha256()
145 block102 = create_block(self.tip, create_coinbase(height), self.block_time)
146 self.block_time += 1
147 block102.vtx.extend([tx])
148 block102.hashMerkleRoot = block102.calc_merkle_root()
149 block102.rehash()
150 block102.solve()
151 self.blocks.append(block102)
152 self.tip = block102.sha256
153 self.block_time += 1
154 height += 1
156 # Bury the assumed valid block 2100 deep
157 for i in range(2100):
158 block = create_block(self.tip, create_coinbase(height), self.block_time)
159 block.nVersion = 4
160 block.solve()
161 self.blocks.append(block)
162 self.tip = block.sha256
163 self.block_time += 1
164 height += 1
166 # Start node1 and node2 with assumevalid so they accept a block with a bad signature.
167 self.start_node(1, extra_args=["-assumevalid=" + hex(block102.sha256)])
168 node1 = BaseNode() # connects to node1
169 connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], node1))
170 node1.add_connection(connections[1])
171 node1.wait_for_verack()
173 self.start_node(2, extra_args=["-assumevalid=" + hex(block102.sha256)])
174 node2 = BaseNode() # connects to node2
175 connections.append(NodeConn('127.0.0.1', p2p_port(2), self.nodes[2], node2))
176 node2.add_connection(connections[2])
177 node2.wait_for_verack()
179 # send header lists to all three nodes
180 node0.send_header_for_blocks(self.blocks[0:2000])
181 node0.send_header_for_blocks(self.blocks[2000:])
182 node1.send_header_for_blocks(self.blocks[0:2000])
183 node1.send_header_for_blocks(self.blocks[2000:])
184 node2.send_header_for_blocks(self.blocks[0:200])
186 # Send blocks to node0. Block 102 will be rejected.
187 self.send_blocks_until_disconnected(node0)
188 self.assert_blockchain_height(self.nodes[0], 101)
190 # Send all blocks to node1. All blocks will be accepted.
191 for i in range(2202):
192 node1.send_message(msg_block(self.blocks[i]))
193 # Syncing 2200 blocks can take a while on slow systems. Give it plenty of time to sync.
194 node1.sync_with_ping(120)
195 assert_equal(self.nodes[1].getblock(self.nodes[1].getbestblockhash())['height'], 2202)
197 # Send blocks to node2. Block 102 will be rejected.
198 self.send_blocks_until_disconnected(node2)
199 self.assert_blockchain_height(self.nodes[2], 101)
201 if __name__ == '__main__':
202 AssumeValidTest().main()