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