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.

feature_pruning.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-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. """Test the pruning code.
  6. WARNING:
  7. This test uses 4GB of disk space.
  8. This test takes 30 mins or more (up to 2 hours)
  9. """
  10. from test_framework.test_framework import BitcoinTestFramework
  11. from test_framework.util import *
  12. import os
  13. MIN_BLOCKS_TO_KEEP = 288
  14. # Rescans start at the earliest block up to 2 hours before a key timestamp, so
  15. # the manual prune RPC avoids pruning blocks in the same window to be
  16. # compatible with pruning based on key creation time.
  17. TIMESTAMP_WINDOW = 2 * 60 * 60
  18. def calc_usage(blockdir):
  19. return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f)) / (1024. * 1024.)
  20. class PruneTest(BitcoinTestFramework):
  21. def set_test_params(self):
  22. self.setup_clean_chain = True
  23. self.num_nodes = 6
  24. # Create nodes 0 and 1 to mine.
  25. # Create node 2 to test pruning.
  26. self.full_node_default_args = ["-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5", "-limitdescendantcount=100", "-limitdescendantsize=5000", "-limitancestorcount=100", "-limitancestorsize=5000" ]
  27. # Create nodes 3 and 4 to test manual pruning (they will be re-started with manual pruning later)
  28. # Create nodes 5 to test wallet in prune mode, but do not connect
  29. self.extra_args = [self.full_node_default_args,
  30. self.full_node_default_args,
  31. ["-maxreceivebuffer=20000", "-prune=550"],
  32. ["-maxreceivebuffer=20000", "-blockmaxsize=999000"],
  33. ["-maxreceivebuffer=20000", "-blockmaxsize=999000"],
  34. ["-prune=550"]]
  35. def setup_network(self):
  36. self.setup_nodes()
  37. self.prunedir = self.options.tmpdir + "/node2/regtest/blocks/"
  38. connect_nodes(self.nodes[0], 1)
  39. connect_nodes(self.nodes[1], 2)
  40. connect_nodes(self.nodes[2], 0)
  41. connect_nodes(self.nodes[0], 3)
  42. connect_nodes(self.nodes[0], 4)
  43. sync_blocks(self.nodes[0:5])
  44. def setup_nodes(self):
  45. self.add_nodes(self.num_nodes, self.extra_args, timewait=900)
  46. self.start_nodes()
  47. def create_big_chain(self):
  48. # Start by creating some coinbases we can spend later
  49. self.nodes[1].generate(200)
  50. sync_blocks(self.nodes[0:2])
  51. self.nodes[0].generate(150)
  52. # Then mine enough full blocks to create more than 550MiB of data
  53. for i in range(645):
  54. mine_large_block(self.nodes[0], self.utxo_cache_0)
  55. sync_blocks(self.nodes[0:5])
  56. def test_height_min(self):
  57. if not os.path.isfile(self.prunedir+"blk00000.dat"):
  58. raise AssertionError("blk00000.dat is missing, pruning too early")
  59. self.log.info("Success")
  60. self.log.info("Though we're already using more than 550MiB, current usage: %d" % calc_usage(self.prunedir))
  61. self.log.info("Mining 25 more blocks should cause the first block file to be pruned")
  62. # Pruning doesn't run until we're allocating another chunk, 20 full blocks past the height cutoff will ensure this
  63. for i in range(25):
  64. mine_large_block(self.nodes[0], self.utxo_cache_0)
  65. # Wait for blk00000.dat to be pruned
  66. wait_until(lambda: not os.path.isfile(self.prunedir+"blk00000.dat"), timeout=30)
  67. self.log.info("Success")
  68. usage = calc_usage(self.prunedir)
  69. self.log.info("Usage should be below target: %d" % usage)
  70. if (usage > 550):
  71. raise AssertionError("Pruning target not being met")
  72. def create_chain_with_staleblocks(self):
  73. # Create stale blocks in manageable sized chunks
  74. self.log.info("Mine 24 (stale) blocks on Node 1, followed by 25 (main chain) block reorg from Node 0, for 12 rounds")
  75. for j in range(12):
  76. # Disconnect node 0 so it can mine a longer reorg chain without knowing about node 1's soon-to-be-stale chain
  77. # Node 2 stays connected, so it hears about the stale blocks and then reorg's when node0 reconnects
  78. # Stopping node 0 also clears its mempool, so it doesn't have node1's transactions to accidentally mine
  79. self.stop_node(0)
  80. self.start_node(0, extra_args=self.full_node_default_args)
  81. # Mine 24 blocks in node 1
  82. for i in range(24):
  83. if j == 0:
  84. mine_large_block(self.nodes[1], self.utxo_cache_1)
  85. else:
  86. # Add node1's wallet transactions back to the mempool, to
  87. # avoid the mined blocks from being too small.
  88. self.nodes[1].resendwallettransactions()
  89. self.nodes[1].generate(1) #tx's already in mempool from previous disconnects
  90. # Reorg back with 25 block chain from node 0
  91. for i in range(25):
  92. mine_large_block(self.nodes[0], self.utxo_cache_0)
  93. # Create connections in the order so both nodes can see the reorg at the same time
  94. connect_nodes(self.nodes[1], 0)
  95. connect_nodes(self.nodes[2], 0)
  96. sync_blocks(self.nodes[0:3])
  97. self.log.info("Usage can be over target because of high stale rate: %d" % calc_usage(self.prunedir))
  98. def reorg_test(self):
  99. # Node 1 will mine a 300 block chain starting 287 blocks back from Node 0 and Node 2's tip
  100. # This will cause Node 2 to do a reorg requiring 288 blocks of undo data to the reorg_test chain
  101. # Reboot node 1 to clear its mempool (hopefully make the invalidate faster)
  102. # Lower the block max size so we don't keep mining all our big mempool transactions (from disconnected blocks)
  103. self.stop_node(1)
  104. self.start_node(1, extra_args=["-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"])
  105. height = self.nodes[1].getblockcount()
  106. self.log.info("Current block height: %d" % height)
  107. invalidheight = height-287
  108. badhash = self.nodes[1].getblockhash(invalidheight)
  109. self.log.info("Invalidating block %s at height %d" % (badhash,invalidheight))
  110. self.nodes[1].invalidateblock(badhash)
  111. # We've now switched to our previously mined-24 block fork on node 1, but that's not what we want
  112. # So invalidate that fork as well, until we're on the same chain as node 0/2 (but at an ancestor 288 blocks ago)
  113. mainchainhash = self.nodes[0].getblockhash(invalidheight - 1)
  114. curhash = self.nodes[1].getblockhash(invalidheight - 1)
  115. while curhash != mainchainhash:
  116. self.nodes[1].invalidateblock(curhash)
  117. curhash = self.nodes[1].getblockhash(invalidheight - 1)
  118. assert(self.nodes[1].getblockcount() == invalidheight - 1)
  119. self.log.info("New best height: %d" % self.nodes[1].getblockcount())
  120. # Reboot node1 to clear those giant tx's from mempool
  121. self.stop_node(1)
  122. self.start_node(1, extra_args=["-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"])
  123. self.log.info("Generating new longer chain of 300 more blocks")
  124. self.nodes[1].generate(300)
  125. self.log.info("Reconnect nodes")
  126. connect_nodes(self.nodes[0], 1)
  127. connect_nodes(self.nodes[2], 1)
  128. sync_blocks(self.nodes[0:3], timeout=120)
  129. self.log.info("Verify height on node 2: %d" % self.nodes[2].getblockcount())
  130. self.log.info("Usage possibly still high bc of stale blocks in block files: %d" % calc_usage(self.prunedir))
  131. self.log.info("Mine 220 more blocks so we have requisite history (some blocks will be big and cause pruning of previous chain)")
  132. # Get node0's wallet transactions back in its mempool, to avoid the
  133. # mined blocks from being too small.
  134. self.nodes[0].resendwallettransactions()
  135. for i in range(22):
  136. # This can be slow, so do this in multiple RPC calls to avoid
  137. # RPC timeouts.
  138. self.nodes[0].generate(10) #node 0 has many large tx's in its mempool from the disconnects
  139. sync_blocks(self.nodes[0:3], timeout=300)
  140. usage = calc_usage(self.prunedir)
  141. self.log.info("Usage should be below target: %d" % usage)
  142. if (usage > 550):
  143. raise AssertionError("Pruning target not being met")
  144. return invalidheight,badhash
  145. def reorg_back(self):
  146. # Verify that a block on the old main chain fork has been pruned away
  147. assert_raises_rpc_error(-1, "Block not available (pruned data)", self.nodes[2].getblock, self.forkhash)
  148. self.log.info("Will need to redownload block %d" % self.forkheight)
  149. # Verify that we have enough history to reorg back to the fork point
  150. # Although this is more than 288 blocks, because this chain was written more recently
  151. # and only its other 299 small and 220 large block are in the block files after it,
  152. # its expected to still be retained
  153. self.nodes[2].getblock(self.nodes[2].getblockhash(self.forkheight))
  154. first_reorg_height = self.nodes[2].getblockcount()
  155. curchainhash = self.nodes[2].getblockhash(self.mainchainheight)
  156. self.nodes[2].invalidateblock(curchainhash)
  157. goalbestheight = self.mainchainheight
  158. goalbesthash = self.mainchainhash2
  159. # As of 0.10 the current block download logic is not able to reorg to the original chain created in
  160. # create_chain_with_stale_blocks because it doesn't know of any peer that's on that chain from which to
  161. # redownload its missing blocks.
  162. # Invalidate the reorg_test chain in node 0 as well, it can successfully switch to the original chain
  163. # because it has all the block data.
  164. # However it must mine enough blocks to have a more work chain than the reorg_test chain in order
  165. # to trigger node 2's block download logic.
  166. # At this point node 2 is within 288 blocks of the fork point so it will preserve its ability to reorg
  167. if self.nodes[2].getblockcount() < self.mainchainheight:
  168. blocks_to_mine = first_reorg_height + 1 - self.mainchainheight
  169. self.log.info("Rewind node 0 to prev main chain to mine longer chain to trigger redownload. Blocks needed: %d" % blocks_to_mine)
  170. self.nodes[0].invalidateblock(curchainhash)
  171. assert(self.nodes[0].getblockcount() == self.mainchainheight)
  172. assert(self.nodes[0].getbestblockhash() == self.mainchainhash2)
  173. goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1]
  174. goalbestheight = first_reorg_height + 1
  175. self.log.info("Verify node 2 reorged back to the main chain, some blocks of which it had to redownload")
  176. # Wait for Node 2 to reorg to proper height
  177. wait_until(lambda: self.nodes[2].getblockcount() >= goalbestheight, timeout=900)
  178. assert(self.nodes[2].getbestblockhash() == goalbesthash)
  179. # Verify we can now have the data for a block previously pruned
  180. assert(self.nodes[2].getblock(self.forkhash)["height"] == self.forkheight)
  181. def manual_test(self, node_number, use_timestamp):
  182. # at this point, node has 995 blocks and has not yet run in prune mode
  183. self.start_node(node_number)
  184. node = self.nodes[node_number]
  185. assert_equal(node.getblockcount(), 995)
  186. assert_raises_rpc_error(-1, "not in prune mode", node.pruneblockchain, 500)
  187. # now re-start in manual pruning mode
  188. self.stop_node(node_number)
  189. self.start_node(node_number, extra_args=["-prune=1"])
  190. node = self.nodes[node_number]
  191. assert_equal(node.getblockcount(), 995)
  192. def height(index):
  193. if use_timestamp:
  194. return node.getblockheader(node.getblockhash(index))["time"] + TIMESTAMP_WINDOW
  195. else:
  196. return index
  197. def prune(index, expected_ret=None):
  198. ret = node.pruneblockchain(height(index))
  199. # Check the return value. When use_timestamp is True, just check
  200. # that the return value is less than or equal to the expected
  201. # value, because when more than one block is generated per second,
  202. # a timestamp will not be granular enough to uniquely identify an
  203. # individual block.
  204. if expected_ret is None:
  205. expected_ret = index
  206. if use_timestamp:
  207. assert_greater_than(ret, 0)
  208. assert_greater_than(expected_ret + 1, ret)
  209. else:
  210. assert_equal(ret, expected_ret)
  211. def has_block(index):
  212. return os.path.isfile(self.options.tmpdir + "/node{}/regtest/blocks/blk{:05}.dat".format(node_number, index))
  213. # should not prune because chain tip of node 3 (995) < PruneAfterHeight (1000)
  214. assert_raises_rpc_error(-1, "Blockchain is too short for pruning", node.pruneblockchain, height(500))
  215. # mine 6 blocks so we are at height 1001 (i.e., above PruneAfterHeight)
  216. node.generate(6)
  217. assert_equal(node.getblockchaininfo()["blocks"], 1001)
  218. # negative heights should raise an exception
  219. assert_raises_rpc_error(-8, "Negative", node.pruneblockchain, -10)
  220. # height=100 too low to prune first block file so this is a no-op
  221. prune(100)
  222. if not has_block(0):
  223. raise AssertionError("blk00000.dat is missing when should still be there")
  224. # Does nothing
  225. node.pruneblockchain(height(0))
  226. if not has_block(0):
  227. raise AssertionError("blk00000.dat is missing when should still be there")
  228. # height=500 should prune first file
  229. prune(500)
  230. if has_block(0):
  231. raise AssertionError("blk00000.dat is still there, should be pruned by now")
  232. if not has_block(1):
  233. raise AssertionError("blk00001.dat is missing when should still be there")
  234. # height=650 should prune second file
  235. prune(650)
  236. if has_block(1):
  237. raise AssertionError("blk00001.dat is still there, should be pruned by now")
  238. # height=1000 should not prune anything more, because tip-288 is in blk00002.dat.
  239. prune(1000, 1001 - MIN_BLOCKS_TO_KEEP)
  240. if not has_block(2):
  241. raise AssertionError("blk00002.dat is still there, should be pruned by now")
  242. # advance the tip so blk00002.dat and blk00003.dat can be pruned (the last 288 blocks should now be in blk00004.dat)
  243. node.generate(288)
  244. prune(1000)
  245. if has_block(2):
  246. raise AssertionError("blk00002.dat is still there, should be pruned by now")
  247. if has_block(3):
  248. raise AssertionError("blk00003.dat is still there, should be pruned by now")
  249. # stop node, start back up with auto-prune at 550MB, make sure still runs
  250. self.stop_node(node_number)
  251. self.start_node(node_number, extra_args=["-prune=550"])
  252. self.log.info("Success")
  253. def wallet_test(self):
  254. # check that the pruning node's wallet is still in good shape
  255. self.log.info("Stop and start pruning node to trigger wallet rescan")
  256. self.stop_node(2)
  257. self.start_node(2, extra_args=["-prune=550"])
  258. self.log.info("Success")
  259. # check that wallet loads successfully when restarting a pruned node after IBD.
  260. # this was reported to fail in #7494.
  261. self.log.info("Syncing node 5 to test wallet")
  262. connect_nodes(self.nodes[0], 5)
  263. nds = [self.nodes[0], self.nodes[5]]
  264. sync_blocks(nds, wait=5, timeout=300)
  265. self.stop_node(5) #stop and start to trigger rescan
  266. self.start_node(5, extra_args=["-prune=550"])
  267. self.log.info("Success")
  268. def run_test(self):
  269. self.log.info("Warning! This test requires 4GB of disk space and takes over 30 mins (up to 2 hours)")
  270. self.log.info("Mining a big blockchain of 995 blocks")
  271. # Determine default relay fee
  272. self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"]
  273. # Cache for utxos, as the listunspent may take a long time later in the test
  274. self.utxo_cache_0 = []
  275. self.utxo_cache_1 = []
  276. self.create_big_chain()
  277. # Chain diagram key:
  278. # * blocks on main chain
  279. # +,&,$,@ blocks on other forks
  280. # X invalidated block
  281. # N1 Node 1
  282. #
  283. # Start by mining a simple chain that all nodes have
  284. # N0=N1=N2 **...*(995)
  285. # stop manual-pruning node with 995 blocks
  286. self.stop_node(3)
  287. self.stop_node(4)
  288. self.log.info("Check that we haven't started pruning yet because we're below PruneAfterHeight")
  289. self.test_height_min()
  290. # Extend this chain past the PruneAfterHeight
  291. # N0=N1=N2 **...*(1020)
  292. self.log.info("Check that we'll exceed disk space target if we have a very high stale block rate")
  293. self.create_chain_with_staleblocks()
  294. # Disconnect N0
  295. # And mine a 24 block chain on N1 and a separate 25 block chain on N0
  296. # N1=N2 **...*+...+(1044)
  297. # N0 **...**...**(1045)
  298. #
  299. # reconnect nodes causing reorg on N1 and N2
  300. # N1=N2 **...*(1020) *...**(1045)
  301. # \
  302. # +...+(1044)
  303. #
  304. # repeat this process until you have 12 stale forks hanging off the
  305. # main chain on N1 and N2
  306. # N0 *************************...***************************(1320)
  307. #
  308. # N1=N2 **...*(1020) *...**(1045) *.. ..**(1295) *...**(1320)
  309. # \ \ \
  310. # +...+(1044) &.. $...$(1319)
  311. # Save some current chain state for later use
  312. self.mainchainheight = self.nodes[2].getblockcount() #1320
  313. self.mainchainhash2 = self.nodes[2].getblockhash(self.mainchainheight)
  314. self.log.info("Check that we can survive a 288 block reorg still")
  315. (self.forkheight,self.forkhash) = self.reorg_test() #(1033, )
  316. # Now create a 288 block reorg by mining a longer chain on N1
  317. # First disconnect N1
  318. # Then invalidate 1033 on main chain and 1032 on fork so height is 1032 on main chain
  319. # N1 **...*(1020) **...**(1032)X..
  320. # \
  321. # ++...+(1031)X..
  322. #
  323. # Now mine 300 more blocks on N1
  324. # N1 **...*(1020) **...**(1032) @@...@(1332)
  325. # \ \
  326. # \ X...
  327. # \ \
  328. # ++...+(1031)X.. ..
  329. #
  330. # Reconnect nodes and mine 220 more blocks on N1
  331. # N1 **...*(1020) **...**(1032) @@...@@@(1552)
  332. # \ \
  333. # \ X...
  334. # \ \
  335. # ++...+(1031)X.. ..
  336. #
  337. # N2 **...*(1020) **...**(1032) @@...@@@(1552)
  338. # \ \
  339. # \ *...**(1320)
  340. # \ \
  341. # ++...++(1044) ..
  342. #
  343. # N0 ********************(1032) @@...@@@(1552)
  344. # \
  345. # *...**(1320)
  346. self.log.info("Test that we can rerequest a block we previously pruned if needed for a reorg")
  347. self.reorg_back()
  348. # Verify that N2 still has block 1033 on current chain (@), but not on main chain (*)
  349. # Invalidate 1033 on current chain (@) on N2 and we should be able to reorg to
  350. # original main chain (*), but will require redownload of some blocks
  351. # In order to have a peer we think we can download from, must also perform this invalidation
  352. # on N0 and mine a new longest chain to trigger.
  353. # Final result:
  354. # N0 ********************(1032) **...****(1553)
  355. # \
  356. # X@...@@@(1552)
  357. #
  358. # N2 **...*(1020) **...**(1032) **...****(1553)
  359. # \ \
  360. # \ X@...@@@(1552)
  361. # \
  362. # +..
  363. #
  364. # N1 doesn't change because 1033 on main chain (*) is invalid
  365. self.log.info("Test manual pruning with block indices")
  366. self.manual_test(3, use_timestamp=False)
  367. self.log.info("Test manual pruning with timestamps")
  368. self.manual_test(4, use_timestamp=True)
  369. self.log.info("Test wallet re-scan")
  370. self.wallet_test()
  371. self.log.info("Done")
  372. if __name__ == '__main__':
  373. PruneTest().main()