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 the invalidateblock RPC."""
7 from test_framework
.test_framework
import BitcoinTestFramework
8 from test_framework
.util
import *
10 class InvalidateTest(BitcoinTestFramework
):
11 def set_test_params(self
):
12 self
.setup_clean_chain
= True
15 def setup_network(self
):
19 self
.log
.info("Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:")
20 self
.log
.info("Mine 4 blocks on Node 0")
21 self
.nodes
[0].generate(4)
22 assert(self
.nodes
[0].getblockcount() == 4)
23 besthash
= self
.nodes
[0].getbestblockhash()
25 self
.log
.info("Mine competing 6 blocks on Node 1")
26 self
.nodes
[1].generate(6)
27 assert(self
.nodes
[1].getblockcount() == 6)
29 self
.log
.info("Connect nodes to force a reorg")
30 connect_nodes_bi(self
.nodes
,0,1)
31 sync_blocks(self
.nodes
[0:2])
32 assert(self
.nodes
[0].getblockcount() == 6)
33 badhash
= self
.nodes
[1].getblockhash(2)
35 self
.log
.info("Invalidate block 2 on node 0 and verify we reorg to node 0's original chain")
36 self
.nodes
[0].invalidateblock(badhash
)
37 newheight
= self
.nodes
[0].getblockcount()
38 newhash
= self
.nodes
[0].getbestblockhash()
39 if (newheight
!= 4 or newhash
!= besthash
):
40 raise AssertionError("Wrong tip for node0, hash %s, height %d"%(newhash
,newheight
))
42 self
.log
.info("Make sure we won't reorg to a lower work chain:")
43 connect_nodes_bi(self
.nodes
,1,2)
44 self
.log
.info("Sync node 2 to node 1 so both have 6 blocks")
45 sync_blocks(self
.nodes
[1:3])
46 assert(self
.nodes
[2].getblockcount() == 6)
47 self
.log
.info("Invalidate block 5 on node 1 so its tip is now at 4")
48 self
.nodes
[1].invalidateblock(self
.nodes
[1].getblockhash(5))
49 assert(self
.nodes
[1].getblockcount() == 4)
50 self
.log
.info("Invalidate block 3 on node 2, so its tip is now 2")
51 self
.nodes
[2].invalidateblock(self
.nodes
[2].getblockhash(3))
52 assert(self
.nodes
[2].getblockcount() == 2)
53 self
.log
.info("..and then mine a block")
54 self
.nodes
[2].generate(1)
55 self
.log
.info("Verify all nodes are at the right height")
57 assert_equal(self
.nodes
[2].getblockcount(), 3)
58 assert_equal(self
.nodes
[0].getblockcount(), 4)
59 node1height
= self
.nodes
[1].getblockcount()
61 raise AssertionError("Node 1 reorged to a lower height: %d"%node1height
)
63 if __name__
== '__main__':
64 InvalidateTest().main()