/ 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 (
 23      assert_equal,
 24      ensure_for,
 25      assert_not_equal,
 26  )
 27  
 28  # 2 hashes required per regtest block (with no difficulty adjustment)
 29  REGTEST_WORK_PER_BLOCK = 2
 30  
 31  class MinimumChainWorkTest(BitcoinTestFramework):
 32      def set_test_params(self):
 33          self.setup_clean_chain = True
 34          self.num_nodes = 3
 35  
 36          self.extra_args = [[], ["-minimumchainwork=0x65"], ["-minimumchainwork=0x65"]]
 37          self.node_min_work = [0, 101, 101]
 38  
 39      def setup_network(self):
 40          # This test relies on the chain setup being:
 41          # node0 <- node1 <- node2
 42          # Before leaving IBD, nodes prefer to download blocks from outbound
 43          # peers, so ensure that we're mining on an outbound peer and testing
 44          # block relay to inbound peers.
 45          self.setup_nodes()
 46          for i in range(self.num_nodes-1):
 47              self.connect_nodes(i+1, i)
 48  
 49          # Set clock of node2 2 days ahead, to keep it in IBD during this test.
 50          self.nodes[2].setmocktime(int(time.time()) + 48*60*60)
 51  
 52      def run_test(self):
 53          # Start building a chain on node0.  node2 shouldn't be able to sync until node1's
 54          # minchainwork is exceeded
 55          starting_chain_work = REGTEST_WORK_PER_BLOCK # Genesis block's work
 56          self.log.info(f"Testing relay across node 1 (minChainWork = {self.node_min_work[1]})")
 57  
 58          starting_blockcount = self.nodes[2].getblockcount()
 59  
 60          num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK)
 61          self.log.info(f"Generating {num_blocks_to_generate} blocks on node0")
 62          hashes = self.generate(self.nodes[0], num_blocks_to_generate, sync_fun=self.no_op)
 63  
 64          self.log.info(f"Node0 current chain work: {self.nodes[0].getblockheader(hashes[-1])['chainwork']}")
 65          self.log.info("Verifying node 2 has no more blocks than before")
 66          self.log.info(f"Blockcounts: {[n.getblockcount() for n in self.nodes]}")
 67          # Node2 shouldn't have any new headers yet, because node1 should not
 68          # have relayed anything.
 69          # We wait 3 seconds, rather than sync_blocks(node0, node1) because
 70          # it's reasonable either way for node1 to get the blocks, or not get
 71          # them (since they're below node1's minchainwork).
 72          ensure_for(duration=3, f=lambda: len(self.nodes[2].getchaintips()) == 1)
 73          assert_equal(self.nodes[2].getchaintips()[0]['height'], 0)
 74  
 75          assert_not_equal(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          ensure_for(duration=5, f=lambda: "headers" not in peer.last_message or len(peer.last_message["headers"].headers) == 0)
 85  
 86          self.log.info("Generating one more block")
 87          self.generate(self.nodes[0], 1)
 88  
 89          self.log.info("Verifying nodes are all synced")
 90  
 91          # Because nodes in regtest are all manual connections (eg using
 92          # addnode), node1 should not have disconnected node0. If not for that,
 93          # we'd expect node1 to have disconnected node0 for serving an
 94          # insufficient work chain, in which case we'd need to reconnect them to
 95          # continue the test.
 96  
 97          self.sync_all()
 98          self.log.info(f"Blockcounts: {[n.getblockcount() for n in self.nodes]}")
 99  
100          self.log.info("Test that getheaders requests to node2 are not ignored")
101          peer.send_and_ping(msg)
102          assert "headers" in peer.last_message
103  
104          # Verify that node2 is in fact still in IBD (otherwise this test may
105          # not be exercising the logic we want!)
106          assert_equal(self.nodes[2].getblockchaininfo()['initialblockdownload'], True)
107  
108          self.log.info("Test -minimumchainwork with a non-hex value")
109          self.stop_node(0)
110          self.nodes[0].assert_start_raises_init_error(
111              ["-minimumchainwork=test"],
112              expected_msg='Error: Invalid minimum work specified (test), must be up to 64 hex digits',
113          )
114  
115  
116  if __name__ == '__main__':
117      MinimumChainWorkTest(__file__).main()