You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

example_test.py 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2017 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. """An example functional test
  6. The module-level docstring should include a high-level description of
  7. what the test is doing. It's the first thing people see when they open
  8. the file and should give the reader information about *what* the test
  9. is testing and *how* it's being tested
  10. """
  11. # Imports should be in PEP8 ordering (std library first, then third party
  12. # libraries then local imports).
  13. from collections import defaultdict
  14. # Avoid wildcard * imports if possible
  15. from test_framework.blocktools import (create_block, create_coinbase)
  16. from test_framework.mininode import (
  17. CInv,
  18. NetworkThread,
  19. NodeConn,
  20. NodeConnCB,
  21. mininode_lock,
  22. msg_block,
  23. msg_getdata,
  24. )
  25. from test_framework.test_framework import BitcoinTestFramework
  26. from test_framework.util import (
  27. assert_equal,
  28. connect_nodes,
  29. p2p_port,
  30. wait_until,
  31. )
  32. # NodeConnCB is a class containing callbacks to be executed when a P2P
  33. # message is received from the node-under-test. Subclass NodeConnCB and
  34. # override the on_*() methods if you need custom behaviour.
  35. class BaseNode(NodeConnCB):
  36. def __init__(self):
  37. """Initialize the NodeConnCB
  38. Used to inialize custom properties for the Node that aren't
  39. included by default in the base class. Be aware that the NodeConnCB
  40. base class already stores a counter for each P2P message type and the
  41. last received message of each type, which should be sufficient for the
  42. needs of most tests.
  43. Call super().__init__() first for standard initialization and then
  44. initialize custom properties."""
  45. super().__init__()
  46. # Stores a dictionary of all blocks received
  47. self.block_receive_map = defaultdict(int)
  48. def on_block(self, conn, message):
  49. """Override the standard on_block callback
  50. Store the hash of a received block in the dictionary."""
  51. message.block.calc_sha256()
  52. self.block_receive_map[message.block.sha256] += 1
  53. def on_inv(self, conn, message):
  54. """Override the standard on_inv callback"""
  55. pass
  56. def custom_function():
  57. """Do some custom behaviour
  58. If this function is more generally useful for other tests, consider
  59. moving it to a module in test_framework."""
  60. # self.log.info("running custom_function") # Oops! Can't run self.log outside the BitcoinTestFramework
  61. pass
  62. class ExampleTest(BitcoinTestFramework):
  63. # Each functional test is a subclass of the BitcoinTestFramework class.
  64. # Override the set_test_params(), add_options(), setup_chain(), setup_network()
  65. # and setup_nodes() methods to customize the test setup as required.
  66. def set_test_params(self):
  67. """Override test parameters for your individual test.
  68. This method must be overridden and num_nodes must be exlicitly set."""
  69. self.setup_clean_chain = True
  70. self.num_nodes = 3
  71. # Use self.extra_args to change command-line arguments for the nodes
  72. self.extra_args = [[], ["-logips"], []]
  73. # self.log.info("I've finished set_test_params") # Oops! Can't run self.log before run_test()
  74. # Use add_options() to add specific command-line options for your test.
  75. # In practice this is not used very much, since the tests are mostly written
  76. # to be run in automated environments without command-line options.
  77. # def add_options()
  78. # pass
  79. # Use setup_chain() to customize the node data directories. In practice
  80. # this is not used very much since the default behaviour is almost always
  81. # fine
  82. # def setup_chain():
  83. # pass
  84. def setup_network(self):
  85. """Setup the test network topology
  86. Often you won't need to override this, since the standard network topology
  87. (linear: node0 <-> node1 <-> node2 <-> ...) is fine for most tests.
  88. If you do override this method, remember to start the nodes, assign
  89. them to self.nodes, connect them and then sync."""
  90. self.setup_nodes()
  91. # In this test, we're not connecting node2 to node0 or node1. Calls to
  92. # sync_all() should not include node2, since we're not expecting it to
  93. # sync.
  94. connect_nodes(self.nodes[0], 1)
  95. self.sync_all([self.nodes[0:1]])
  96. # Use setup_nodes() to customize the node start behaviour (for example if
  97. # you don't want to start all nodes at the start of the test).
  98. # def setup_nodes():
  99. # pass
  100. def custom_method(self):
  101. """Do some custom behaviour for this test
  102. Define it in a method here because you're going to use it repeatedly.
  103. If you think it's useful in general, consider moving it to the base
  104. BitcoinTestFramework class so other tests can use it."""
  105. self.log.info("Running custom_method")
  106. def run_test(self):
  107. """Main test logic"""
  108. # Create a P2P connection to one of the nodes
  109. node0 = BaseNode()
  110. connections = []
  111. connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], node0))
  112. node0.add_connection(connections[0])
  113. # Start up network handling in another thread. This needs to be called
  114. # after the P2P connections have been created.
  115. NetworkThread().start()
  116. # wait_for_verack ensures that the P2P connection is fully up.
  117. node0.wait_for_verack()
  118. # Generating a block on one of the nodes will get us out of IBD
  119. blocks = [int(self.nodes[0].generate(nblocks=1)[0], 16)]
  120. self.sync_all([self.nodes[0:1]])
  121. # Notice above how we called an RPC by calling a method with the same
  122. # name on the node object. Notice also how we used a keyword argument
  123. # to specify a named RPC argument. Neither of those are defined on the
  124. # node object. Instead there's some __getattr__() magic going on under
  125. # the covers to dispatch unrecognised attribute calls to the RPC
  126. # interface.
  127. # Logs are nice. Do plenty of them. They can be used in place of comments for
  128. # breaking the test into sub-sections.
  129. self.log.info("Starting test!")
  130. self.log.info("Calling a custom function")
  131. custom_function()
  132. self.log.info("Calling a custom method")
  133. self.custom_method()
  134. self.log.info("Create some blocks")
  135. self.tip = int(self.nodes[0].getbestblockhash(), 16)
  136. self.block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time'] + 1
  137. height = 1
  138. for i in range(10):
  139. # Use the mininode and blocktools functionality to manually build a block
  140. # Calling the generate() rpc is easier, but this allows us to exactly
  141. # control the blocks and transactions.
  142. block = create_block(self.tip, create_coinbase(height), self.block_time)
  143. block.solve()
  144. block_message = msg_block(block)
  145. # Send message is used to send a P2P message to the node over our NodeConn connection
  146. node0.send_message(block_message)
  147. self.tip = block.sha256
  148. blocks.append(self.tip)
  149. self.block_time += 1
  150. height += 1
  151. self.log.info("Wait for node1 to reach current tip (height 11) using RPC")
  152. self.nodes[1].waitforblockheight(11)
  153. self.log.info("Connect node2 and node1")
  154. connect_nodes(self.nodes[1], 2)
  155. self.log.info("Add P2P connection to node2")
  156. node2 = BaseNode()
  157. connections.append(NodeConn('127.0.0.1', p2p_port(2), self.nodes[2], node2))
  158. node2.add_connection(connections[1])
  159. node2.wait_for_verack()
  160. self.log.info("Wait for node2 reach current tip. Test that it has propogated all the blocks to us")
  161. getdata_request = msg_getdata()
  162. for block in blocks:
  163. getdata_request.inv.append(CInv(2, block))
  164. node2.send_message(getdata_request)
  165. # wait_until() will loop until a predicate condition is met. Use it to test properties of the
  166. # NodeConnCB objects.
  167. wait_until(lambda: sorted(blocks) == sorted(list(node2.block_receive_map.keys())), timeout=5, lock=mininode_lock)
  168. self.log.info("Check that each block was received only once")
  169. # The network thread uses a global lock on data access to the NodeConn objects when sending and receiving
  170. # messages. The test thread should acquire the global lock before accessing any NodeConn data to avoid locking
  171. # and synchronization issues. Note wait_until() acquires this global lock when testing the predicate.
  172. with mininode_lock:
  173. for block in node2.block_receive_map.values():
  174. assert_equal(block, 1)
  175. if __name__ == '__main__':
  176. ExampleTest().main()