feature_maxuploadtarget.py
1 #!/usr/bin/env python3 2 # Copyright (c) 2015-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 behavior of -maxuploadtarget. 6 7 * Verify that getdata requests for old blocks (>1week) are dropped 8 if uploadtarget has been reached. 9 * Verify that getdata requests for recent blocks are respected even 10 if uploadtarget has been reached. 11 * Verify that mempool requests lead to a disconnect if uploadtarget has been reached. 12 * Verify that the upload counters are reset after 24 hours. 13 """ 14 from collections import defaultdict 15 import time 16 17 from test_framework.messages import ( 18 CInv, 19 MSG_BLOCK, 20 msg_getdata, 21 msg_mempool, 22 ) 23 from test_framework.p2p import P2PInterface 24 from test_framework.test_framework import BitcoinTestFramework 25 from test_framework.util import ( 26 assert_equal, 27 mine_large_block, 28 ) 29 from test_framework.wallet import MiniWallet 30 31 32 UPLOAD_TARGET_MB = 800 33 34 35 class TestP2PConn(P2PInterface): 36 def __init__(self): 37 super().__init__() 38 self.block_receive_map = defaultdict(int) 39 40 def on_inv(self, message): 41 pass 42 43 def on_block(self, message): 44 message.block.calc_sha256() 45 self.block_receive_map[message.block.sha256] += 1 46 47 class MaxUploadTest(BitcoinTestFramework): 48 49 def set_test_params(self): 50 self.setup_clean_chain = True 51 self.num_nodes = 1 52 self.extra_args = [[ 53 f"-maxuploadtarget={UPLOAD_TARGET_MB}M", 54 "-datacarriersize=100000", 55 ]] 56 self.supports_cli = False 57 58 def assert_uploadtarget_state(self, *, target_reached, serve_historical_blocks): 59 """Verify the node's current upload target state via the `getnettotals` RPC call.""" 60 uploadtarget = self.nodes[0].getnettotals()["uploadtarget"] 61 assert_equal(uploadtarget["target_reached"], target_reached) 62 assert_equal(uploadtarget["serve_historical_blocks"], serve_historical_blocks) 63 64 def run_test(self): 65 # Initially, neither historical blocks serving limit nor total limit are reached 66 self.assert_uploadtarget_state(target_reached=False, serve_historical_blocks=True) 67 68 # Before we connect anything, we first set the time on the node 69 # to be in the past, otherwise things break because the CNode 70 # time counters can't be reset backward after initialization 71 old_time = int(time.time() - 2*60*60*24*7) 72 self.nodes[0].setmocktime(old_time) 73 74 # Generate some old blocks 75 self.wallet = MiniWallet(self.nodes[0]) 76 self.generate(self.wallet, 130) 77 78 # p2p_conns[0] will only request old blocks 79 # p2p_conns[1] will only request new blocks 80 # p2p_conns[2] will test resetting the counters 81 p2p_conns = [] 82 83 for _ in range(3): 84 # Don't use v2transport in this test (too slow with the unoptimized python ChaCha20 implementation) 85 p2p_conns.append(self.nodes[0].add_p2p_connection(TestP2PConn(), supports_v2_p2p=False)) 86 87 # Now mine a big block 88 mine_large_block(self, self.wallet, self.nodes[0]) 89 90 # Store the hash; we'll request this later 91 big_old_block = self.nodes[0].getbestblockhash() 92 old_block_size = self.nodes[0].getblock(big_old_block, True)['size'] 93 big_old_block = int(big_old_block, 16) 94 95 # Advance to two days ago 96 self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24) 97 98 # Mine one more block, so that the prior block looks old 99 mine_large_block(self, self.wallet, self.nodes[0]) 100 101 # We'll be requesting this new block too 102 big_new_block = self.nodes[0].getbestblockhash() 103 big_new_block = int(big_new_block, 16) 104 105 # p2p_conns[0] will test what happens if we just keep requesting the 106 # the same big old block too many times (expect: disconnect) 107 108 getdata_request = msg_getdata() 109 getdata_request.inv.append(CInv(MSG_BLOCK, big_old_block)) 110 111 max_bytes_per_day = UPLOAD_TARGET_MB * 1024 *1024 112 daily_buffer = 144 * 4000000 113 max_bytes_available = max_bytes_per_day - daily_buffer 114 success_count = max_bytes_available // old_block_size 115 116 # 576MB will be reserved for relaying new blocks, so expect this to 117 # succeed for ~235 tries. 118 for i in range(success_count): 119 p2p_conns[0].send_and_ping(getdata_request) 120 assert_equal(p2p_conns[0].block_receive_map[big_old_block], i+1) 121 122 assert_equal(len(self.nodes[0].getpeerinfo()), 3) 123 # At most a couple more tries should succeed (depending on how long 124 # the test has been running so far). 125 with self.nodes[0].assert_debug_log(expected_msgs=["historical block serving limit reached, disconnect peer"]): 126 for _ in range(3): 127 p2p_conns[0].send_message(getdata_request) 128 p2p_conns[0].wait_for_disconnect() 129 assert_equal(len(self.nodes[0].getpeerinfo()), 2) 130 self.log.info("Peer 0 disconnected after downloading old block too many times") 131 132 # Historical blocks serving limit is reached by now, but total limit still isn't 133 self.assert_uploadtarget_state(target_reached=False, serve_historical_blocks=False) 134 135 # Requesting the current block on p2p_conns[1] should succeed indefinitely, 136 # even when over the max upload target. 137 # We'll try 800 times 138 getdata_request.inv = [CInv(MSG_BLOCK, big_new_block)] 139 for i in range(800): 140 p2p_conns[1].send_and_ping(getdata_request) 141 assert_equal(p2p_conns[1].block_receive_map[big_new_block], i+1) 142 143 # Both historical blocks serving limit and total limit are reached 144 self.assert_uploadtarget_state(target_reached=True, serve_historical_blocks=False) 145 146 self.log.info("Peer 1 able to repeatedly download new block") 147 148 # But if p2p_conns[1] tries for an old block, it gets disconnected too. 149 getdata_request.inv = [CInv(MSG_BLOCK, big_old_block)] 150 with self.nodes[0].assert_debug_log(expected_msgs=["historical block serving limit reached, disconnect peer"]): 151 p2p_conns[1].send_message(getdata_request) 152 p2p_conns[1].wait_for_disconnect() 153 assert_equal(len(self.nodes[0].getpeerinfo()), 1) 154 155 self.log.info("Peer 1 disconnected after trying to download old block") 156 157 self.log.info("Advancing system time on node to clear counters...") 158 159 # If we advance the time by 24 hours, then the counters should reset, 160 # and p2p_conns[2] should be able to retrieve the old block. 161 self.nodes[0].setmocktime(int(time.time())) 162 p2p_conns[2].sync_with_ping() 163 p2p_conns[2].send_and_ping(getdata_request) 164 assert_equal(p2p_conns[2].block_receive_map[big_old_block], 1) 165 self.assert_uploadtarget_state(target_reached=False, serve_historical_blocks=True) 166 167 self.log.info("Peer 2 able to download old block") 168 169 self.nodes[0].disconnect_p2ps() 170 171 self.log.info("Restarting node 0 with download permission, bloom filter support and 1MB maxuploadtarget") 172 self.restart_node(0, ["-whitelist=download@127.0.0.1", "-peerbloomfilters", "-maxuploadtarget=1"]) 173 # Total limit isn't reached after restart, but 1 MB is too small to serve historical blocks 174 self.assert_uploadtarget_state(target_reached=False, serve_historical_blocks=False) 175 176 # Reconnect to self.nodes[0] 177 peer = self.nodes[0].add_p2p_connection(TestP2PConn(), supports_v2_p2p=False) 178 179 # Sending mempool message shouldn't disconnect peer, as total limit isn't reached yet 180 peer.send_and_ping(msg_mempool()) 181 182 #retrieve 20 blocks which should be enough to break the 1MB limit 183 getdata_request.inv = [CInv(MSG_BLOCK, big_new_block)] 184 for i in range(20): 185 peer.send_and_ping(getdata_request) 186 assert_equal(peer.block_receive_map[big_new_block], i+1) 187 188 # Total limit is exceeded 189 self.assert_uploadtarget_state(target_reached=True, serve_historical_blocks=False) 190 191 getdata_request.inv = [CInv(MSG_BLOCK, big_old_block)] 192 peer.send_and_ping(getdata_request) 193 194 self.log.info("Peer still connected after trying to download old block (download permission)") 195 peer_info = self.nodes[0].getpeerinfo() 196 assert_equal(len(peer_info), 1) # node is still connected 197 assert_equal(peer_info[0]['permissions'], ['download']) 198 199 self.log.info("Peer gets disconnected for a mempool request after limit is reached") 200 with self.nodes[0].assert_debug_log(expected_msgs=["mempool request with bandwidth limit reached, disconnect peer"]): 201 peer.send_message(msg_mempool()) 202 peer.wait_for_disconnect() 203 204 self.log.info("Test passing an unparsable value to -maxuploadtarget throws an error") 205 self.stop_node(0) 206 self.nodes[0].assert_start_raises_init_error(extra_args=["-maxuploadtarget=abc"], expected_msg="Error: Unable to parse -maxuploadtarget: 'abc'") 207 208 if __name__ == '__main__': 209 MaxUploadTest().main()