/ test / functional / feature_minchainwork.py
feature_minchainwork.py
  1  #!/usr/bin/env python3
  2  # Copyright (c) 2017-2022 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 setting nMinimumChainWork on command line.
  6  
  7  Nodes don't consider themselves out of "initial block download" until
  8  their active chain has more work than nMinimumChainWork.
  9  
 10  Nodes don't download blocks from a peer unless the peer's best known block
 11  has more work than nMinimumChainWork.
 12  
 13  While in initial block download, nodes won't relay blocks to their peers, so
 14  test that this parameter functions as intended by verifying that block relay
 15  only succeeds past a given node once its nMinimumChainWork has been exceeded.
 16  """
 17  
 18  import time
 19  
 20  from test_framework.p2p import P2PInterface, msg_getheaders
 21  from test_framework.test_framework import BitcoinTestFramework
 22  from test_framework.util import assert_equal
 23  
 24  # 2 hashes required per regtest block (with no difficulty adjustment)
 25  REGTEST_WORK_PER_BLOCK = 2
 26  
 27  class MinimumChainWorkTest(BitcoinTestFramework):
 28      def set_test_params(self):
 29          self.setup_clean_chain = True
 30          self.num_nodes = 3
 31  
 32          self.extra_args = [[], ["-minimumchainwork=0x65"], ["-minimumchainwork=0x65"]]
 33          self.node_min_work = [0, 101, 101]
 34  
 35      def setup_network(self):
 36          # This test relies on the chain setup being:
 37          # node0 <- node1 <- node2
 38          # Before leaving IBD, nodes prefer to download blocks from outbound
 39          # peers, so ensure that we're mining on an outbound peer and testing
 40          # block relay to inbound peers.
 41          self.setup_nodes()
 42          for i in range(self.num_nodes-1):
 43              self.connect_nodes(i+1, i)
 44  
 45          # Set clock of node2 2 days ahead, to keep it in IBD during this test.
 46          self.nodes[2].setmocktime(int(time.time()) + 48*60*60)
 47  
 48      def run_test(self):
 49          # Start building a chain on node0.  node2 shouldn't be able to sync until node1's
 50          # minchainwork is exceeded
 51          starting_chain_work = REGTEST_WORK_PER_BLOCK # Genesis block's work
 52          self.log.info(f"Testing relay across node 1 (minChainWork = {self.node_min_work[1]})")
 53  
 54          starting_blockcount = self.nodes[2].getblockcount()
 55  
 56          num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK)
 57          self.log.info(f"Generating {num_blocks_to_generate} blocks on node0")
 58          hashes = self.generate(self.nodes[0], num_blocks_to_generate, sync_fun=self.no_op)
 59  
 60          self.log.info(f"Node0 current chain work: {self.nodes[0].getblockheader(hashes[-1])['chainwork']}")
 61  
 62          # Sleep a few seconds and verify that node2 didn't get any new blocks
 63          # or headers.  We sleep, rather than sync_blocks(node0, node1) because
 64          # it's reasonable either way for node1 to get the blocks, or not get
 65          # them (since they're below node1's minchainwork).
 66          time.sleep(3)
 67  
 68          self.log.info("Verifying node 2 has no more blocks than before")
 69          self.log.info(f"Blockcounts: {[n.getblockcount() for n in self.nodes]}")
 70          # Node2 shouldn't have any new headers yet, because node1 should not
 71          # have relayed anything.
 72          assert_equal(len(self.nodes[2].getchaintips()), 1)
 73          assert_equal(self.nodes[2].getchaintips()[0]['height'], 0)
 74  
 75          assert self.nodes[1].getbestblockhash() != self.nodes[0].getbestblockhash()
 76          assert_equal(self.nodes[2].getblockcount(), starting_blockcount)
 77  
 78          self.log.info("Check that getheaders requests to node2 are ignored")
 79          peer = self.nodes[2].add_p2p_connection(P2PInterface())
 80          msg = msg_getheaders()
 81          msg.locator.vHave = [int(self.nodes[2].getbestblockhash(), 16)]
 82          msg.hashstop = 0
 83          peer.send_and_ping(msg)
 84          time.sleep(5)
 85          assert "headers" not in peer.last_message or len(peer.last_message["headers"].headers) == 0
 86  
 87          self.log.info("Generating one more block")
 88          self.generate(self.nodes[0], 1)
 89  
 90          self.log.info("Verifying nodes are all synced")
 91  
 92          # Because nodes in regtest are all manual connections (eg using
 93          # addnode), node1 should not have disconnected node0. If not for that,
 94          # we'd expect node1 to have disconnected node0 for serving an
 95          # insufficient work chain, in which case we'd need to reconnect them to
 96          # continue the test.
 97  
 98          self.sync_all()
 99          self.log.info(f"Blockcounts: {[n.getblockcount() for n in self.nodes]}")
100  
101          self.log.info("Test that getheaders requests to node2 are not ignored")
102          peer.send_and_ping(msg)
103          assert "headers" in peer.last_message
104  
105          # Verify that node2 is in fact still in IBD (otherwise this test may
106          # not be exercising the logic we want!)
107          assert_equal(self.nodes[2].getblockchaininfo()['initialblockdownload'], True)
108  
109          self.log.info("Test -minimumchainwork with a non-hex value")
110          self.stop_node(0)
111          self.nodes[0].assert_start_raises_init_error(
112              ["-minimumchainwork=test"],
113              expected_msg='Error: Invalid non-hex (test) minimum chain work value specified',
114          )
115  
116  
117  if __name__ == '__main__':
118      MinimumChainWorkTest().main()