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.

pruning.py 21KB

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