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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #!/usr/bin/env python2
  2. # Copyright (c) 2014-2015 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. #
  6. # Test pruning code
  7. # ********
  8. # WARNING:
  9. # This test uses 4GB of disk space.
  10. # This test takes 30 mins or more (up to 2 hours)
  11. # ********
  12. from test_framework.test_framework import BitcoinTestFramework
  13. from test_framework.util import *
  14. def calc_usage(blockdir):
  15. return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f)) / (1024. * 1024.)
  16. class PruneTest(BitcoinTestFramework):
  17. def __init__(self):
  18. self.utxo = []
  19. self.address = ["",""]
  20. self.txouts = gen_return_txouts()
  21. def setup_chain(self):
  22. print("Initializing test directory "+self.options.tmpdir)
  23. initialize_chain_clean(self.options.tmpdir, 3)
  24. def setup_network(self):
  25. self.nodes = []
  26. self.is_network_split = False
  27. # Create nodes 0 and 1 to mine
  28. self.nodes.append(start_node(0, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5"], timewait=900))
  29. self.nodes.append(start_node(1, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5"], timewait=900))
  30. # Create node 2 to test pruning
  31. self.nodes.append(start_node(2, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-prune=550"], timewait=900))
  32. self.prunedir = self.options.tmpdir+"/node2/regtest/blocks/"
  33. self.address[0] = self.nodes[0].getnewaddress()
  34. self.address[1] = self.nodes[1].getnewaddress()
  35. # Determine default relay fee
  36. self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"]
  37. connect_nodes(self.nodes[0], 1)
  38. connect_nodes(self.nodes[1], 2)
  39. connect_nodes(self.nodes[2], 0)
  40. sync_blocks(self.nodes[0:3])
  41. def create_big_chain(self):
  42. # Start by creating some coinbases we can spend later
  43. self.nodes[1].generate(200)
  44. sync_blocks(self.nodes[0:2])
  45. self.nodes[0].generate(150)
  46. # Then mine enough full blocks to create more than 550MiB of data
  47. for i in xrange(645):
  48. self.mine_full_block(self.nodes[0], self.address[0])
  49. sync_blocks(self.nodes[0:3])
  50. def test_height_min(self):
  51. if not os.path.isfile(self.prunedir+"blk00000.dat"):
  52. raise AssertionError("blk00000.dat is missing, pruning too early")
  53. print "Success"
  54. print "Though we're already using more than 550MiB, current usage:", calc_usage(self.prunedir)
  55. print "Mining 25 more blocks should cause the first block file to be pruned"
  56. # Pruning doesn't run until we're allocating another chunk, 20 full blocks past the height cutoff will ensure this
  57. for i in xrange(25):
  58. self.mine_full_block(self.nodes[0],self.address[0])
  59. waitstart = time.time()
  60. while os.path.isfile(self.prunedir+"blk00000.dat"):
  61. time.sleep(0.1)
  62. if time.time() - waitstart > 10:
  63. raise AssertionError("blk00000.dat not pruned when it should be")
  64. print "Success"
  65. usage = calc_usage(self.prunedir)
  66. print "Usage should be below target:", usage
  67. if (usage > 550):
  68. raise AssertionError("Pruning target not being met")
  69. def create_chain_with_staleblocks(self):
  70. # Create stale blocks in manageable sized chunks
  71. print "Mine 24 (stale) blocks on Node 1, followed by 25 (main chain) block reorg from Node 0, for 12 rounds"
  72. for j in xrange(12):
  73. # Disconnect node 0 so it can mine a longer reorg chain without knowing about node 1's soon-to-be-stale chain
  74. # Node 2 stays connected, so it hears about the stale blocks and then reorg's when node0 reconnects
  75. # Stopping node 0 also clears its mempool, so it doesn't have node1's transactions to accidentally mine
  76. stop_node(self.nodes[0],0)
  77. self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5"], timewait=900)
  78. # Mine 24 blocks in node 1
  79. self.utxo = self.nodes[1].listunspent()
  80. for i in xrange(24):
  81. if j == 0:
  82. self.mine_full_block(self.nodes[1],self.address[1])
  83. else:
  84. self.nodes[1].generate(1) #tx's already in mempool from previous disconnects
  85. # Reorg back with 25 block chain from node 0
  86. self.utxo = self.nodes[0].listunspent()
  87. for i in xrange(25):
  88. self.mine_full_block(self.nodes[0],self.address[0])
  89. # Create connections in the order so both nodes can see the reorg at the same time
  90. connect_nodes(self.nodes[1], 0)
  91. connect_nodes(self.nodes[2], 0)
  92. sync_blocks(self.nodes[0:3])
  93. print "Usage can be over target because of high stale rate:", calc_usage(self.prunedir)
  94. def reorg_test(self):
  95. # Node 1 will mine a 300 block chain starting 287 blocks back from Node 0 and Node 2's tip
  96. # This will cause Node 2 to do a reorg requiring 288 blocks of undo data to the reorg_test chain
  97. # Reboot node 1 to clear its mempool (hopefully make the invalidate faster)
  98. # Lower the block max size so we don't keep mining all our big mempool transactions (from disconnected blocks)
  99. stop_node(self.nodes[1],1)
  100. self.nodes[1]=start_node(1, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"], timewait=900)
  101. height = self.nodes[1].getblockcount()
  102. print "Current block height:", height
  103. invalidheight = height-287
  104. badhash = self.nodes[1].getblockhash(invalidheight)
  105. print "Invalidating block at height:",invalidheight,badhash
  106. self.nodes[1].invalidateblock(badhash)
  107. # We've now switched to our previously mined-24 block fork on node 1, but thats not what we want
  108. # So invalidate that fork as well, until we're on the same chain as node 0/2 (but at an ancestor 288 blocks ago)
  109. mainchainhash = self.nodes[0].getblockhash(invalidheight - 1)
  110. curhash = self.nodes[1].getblockhash(invalidheight - 1)
  111. while curhash != mainchainhash:
  112. self.nodes[1].invalidateblock(curhash)
  113. curhash = self.nodes[1].getblockhash(invalidheight - 1)
  114. assert(self.nodes[1].getblockcount() == invalidheight - 1)
  115. print "New best height", self.nodes[1].getblockcount()
  116. # Reboot node1 to clear those giant tx's from mempool
  117. stop_node(self.nodes[1],1)
  118. self.nodes[1]=start_node(1, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"], timewait=900)
  119. print "Generating new longer chain of 300 more blocks"
  120. self.nodes[1].generate(300)
  121. print "Reconnect nodes"
  122. connect_nodes(self.nodes[0], 1)
  123. connect_nodes(self.nodes[2], 1)
  124. sync_blocks(self.nodes[0:3])
  125. print "Verify height on node 2:",self.nodes[2].getblockcount()
  126. print "Usage possibly still high bc of stale blocks in block files:", calc_usage(self.prunedir)
  127. print "Mine 220 more blocks so we have requisite history (some blocks will be big and cause pruning of previous chain)"
  128. self.nodes[0].generate(220) #node 0 has many large tx's in its mempool from the disconnects
  129. sync_blocks(self.nodes[0:3])
  130. usage = calc_usage(self.prunedir)
  131. print "Usage should be below target:", usage
  132. if (usage > 550):
  133. raise AssertionError("Pruning target not being met")
  134. return invalidheight,badhash
  135. def reorg_back(self):
  136. # Verify that a block on the old main chain fork has been pruned away
  137. try:
  138. self.nodes[2].getblock(self.forkhash)
  139. raise AssertionError("Old block wasn't pruned so can't test redownload")
  140. except JSONRPCException as e:
  141. print "Will need to redownload block",self.forkheight
  142. # Verify that we have enough history to reorg back to the fork point
  143. # Although this is more than 288 blocks, because this chain was written more recently
  144. # and only its other 299 small and 220 large block are in the block files after it,
  145. # its expected to still be retained
  146. self.nodes[2].getblock(self.nodes[2].getblockhash(self.forkheight))
  147. first_reorg_height = self.nodes[2].getblockcount()
  148. curchainhash = self.nodes[2].getblockhash(self.mainchainheight)
  149. self.nodes[2].invalidateblock(curchainhash)
  150. goalbestheight = self.mainchainheight
  151. goalbesthash = self.mainchainhash2
  152. # As of 0.10 the current block download logic is not able to reorg to the original chain created in
  153. # create_chain_with_stale_blocks because it doesn't know of any peer thats on that chain from which to
  154. # redownload its missing blocks.
  155. # Invalidate the reorg_test chain in node 0 as well, it can successfully switch to the original chain
  156. # because it has all the block data.
  157. # However it must mine enough blocks to have a more work chain than the reorg_test chain in order
  158. # to trigger node 2's block download logic.
  159. # At this point node 2 is within 288 blocks of the fork point so it will preserve its ability to reorg
  160. if self.nodes[2].getblockcount() < self.mainchainheight:
  161. blocks_to_mine = first_reorg_height + 1 - self.mainchainheight
  162. print "Rewind node 0 to prev main chain to mine longer chain to trigger redownload. Blocks needed:", blocks_to_mine
  163. self.nodes[0].invalidateblock(curchainhash)
  164. assert(self.nodes[0].getblockcount() == self.mainchainheight)
  165. assert(self.nodes[0].getbestblockhash() == self.mainchainhash2)
  166. goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1]
  167. goalbestheight = first_reorg_height + 1
  168. print "Verify node 2 reorged back to the main chain, some blocks of which it had to redownload"
  169. waitstart = time.time()
  170. while self.nodes[2].getblockcount() < goalbestheight:
  171. time.sleep(0.1)
  172. if time.time() - waitstart > 900:
  173. raise AssertionError("Node 2 didn't reorg to proper height")
  174. assert(self.nodes[2].getbestblockhash() == goalbesthash)
  175. # Verify we can now have the data for a block previously pruned
  176. assert(self.nodes[2].getblock(self.forkhash)["height"] == self.forkheight)
  177. def mine_full_block(self, node, address):
  178. # Want to create a full block
  179. # We'll generate a 66k transaction below, and 14 of them is close to the 1MB block limit
  180. for j in xrange(14):
  181. if len(self.utxo) < 14:
  182. self.utxo = node.listunspent()
  183. inputs=[]
  184. outputs = {}
  185. t = self.utxo.pop()
  186. inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
  187. remchange = t["amount"] - 100*self.relayfee # Fee must be above min relay rate for 66kb tx
  188. outputs[address]=remchange
  189. # Create a basic transaction that will send change back to ourself after account for a fee
  190. # And then insert the 128 generated transaction outs in the middle rawtx[92] is where the #
  191. # of txouts is stored and is the only thing we overwrite from the original transaction
  192. rawtx = node.createrawtransaction(inputs, outputs)
  193. newtx = rawtx[0:92]
  194. newtx = newtx + self.txouts
  195. newtx = newtx + rawtx[94:]
  196. # Appears to be ever so slightly faster to sign with SIGHASH_NONE
  197. signresult = node.signrawtransaction(newtx,None,None,"NONE")
  198. txid = node.sendrawtransaction(signresult["hex"], True)
  199. # Mine a full sized block which will be these transactions we just created
  200. node.generate(1)
  201. def run_test(self):
  202. print "Warning! This test requires 4GB of disk space and takes over 30 mins (up to 2 hours)"
  203. print "Mining a big blockchain of 995 blocks"
  204. self.create_big_chain()
  205. # Chain diagram key:
  206. # * blocks on main chain
  207. # +,&,$,@ blocks on other forks
  208. # X invalidated block
  209. # N1 Node 1
  210. #
  211. # Start by mining a simple chain that all nodes have
  212. # N0=N1=N2 **...*(995)
  213. print "Check that we haven't started pruning yet because we're below PruneAfterHeight"
  214. self.test_height_min()
  215. # Extend this chain past the PruneAfterHeight
  216. # N0=N1=N2 **...*(1020)
  217. print "Check that we'll exceed disk space target if we have a very high stale block rate"
  218. self.create_chain_with_staleblocks()
  219. # Disconnect N0
  220. # And mine a 24 block chain on N1 and a separate 25 block chain on N0
  221. # N1=N2 **...*+...+(1044)
  222. # N0 **...**...**(1045)
  223. #
  224. # reconnect nodes causing reorg on N1 and N2
  225. # N1=N2 **...*(1020) *...**(1045)
  226. # \
  227. # +...+(1044)
  228. #
  229. # repeat this process until you have 12 stale forks hanging off the
  230. # main chain on N1 and N2
  231. # N0 *************************...***************************(1320)
  232. #
  233. # N1=N2 **...*(1020) *...**(1045) *.. ..**(1295) *...**(1320)
  234. # \ \ \
  235. # +...+(1044) &.. $...$(1319)
  236. # Save some current chain state for later use
  237. self.mainchainheight = self.nodes[2].getblockcount() #1320
  238. self.mainchainhash2 = self.nodes[2].getblockhash(self.mainchainheight)
  239. print "Check that we can survive a 288 block reorg still"
  240. (self.forkheight,self.forkhash) = self.reorg_test() #(1033, )
  241. # Now create a 288 block reorg by mining a longer chain on N1
  242. # First disconnect N1
  243. # Then invalidate 1033 on main chain and 1032 on fork so height is 1032 on main chain
  244. # N1 **...*(1020) **...**(1032)X..
  245. # \
  246. # ++...+(1031)X..
  247. #
  248. # Now mine 300 more blocks on N1
  249. # N1 **...*(1020) **...**(1032) @@...@(1332)
  250. # \ \
  251. # \ X...
  252. # \ \
  253. # ++...+(1031)X.. ..
  254. #
  255. # Reconnect nodes and mine 220 more blocks on N1
  256. # N1 **...*(1020) **...**(1032) @@...@@@(1552)
  257. # \ \
  258. # \ X...
  259. # \ \
  260. # ++...+(1031)X.. ..
  261. #
  262. # N2 **...*(1020) **...**(1032) @@...@@@(1552)
  263. # \ \
  264. # \ *...**(1320)
  265. # \ \
  266. # ++...++(1044) ..
  267. #
  268. # N0 ********************(1032) @@...@@@(1552)
  269. # \
  270. # *...**(1320)
  271. print "Test that we can rerequest a block we previously pruned if needed for a reorg"
  272. self.reorg_back()
  273. # Verify that N2 still has block 1033 on current chain (@), but not on main chain (*)
  274. # Invalidate 1033 on current chain (@) on N2 and we should be able to reorg to
  275. # original main chain (*), but will require redownload of some blocks
  276. # In order to have a peer we think we can download from, must also perform this invalidation
  277. # on N0 and mine a new longest chain to trigger.
  278. # Final result:
  279. # N0 ********************(1032) **...****(1553)
  280. # \
  281. # X@...@@@(1552)
  282. #
  283. # N2 **...*(1020) **...**(1032) **...****(1553)
  284. # \ \
  285. # \ X@...@@@(1552)
  286. # \
  287. # +..
  288. #
  289. # N1 doesn't change because 1033 on main chain (*) is invalid
  290. print "Done"
  291. if __name__ == '__main__':
  292. PruneTest().main()