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.

smartfees.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 fee estimation code."""
  6. from collections import OrderedDict
  7. from test_framework.test_framework import BitcoinTestFramework
  8. from test_framework.util import *
  9. # Construct 2 trivial P2SH's and the ScriptSigs that spend them
  10. # So we can create many many transactions without needing to spend
  11. # time signing.
  12. P2SH_1 = "2MySexEGVzZpRgNQ1JdjdP5bRETznm3roQ2" # P2SH of "OP_1 OP_DROP"
  13. P2SH_2 = "2NBdpwq8Aoo1EEKEXPNrKvr5xQr3M9UfcZA" # P2SH of "OP_2 OP_DROP"
  14. # Associated ScriptSig's to spend satisfy P2SH_1 and P2SH_2
  15. # 4 bytes of OP_TRUE and push 2-byte redeem script of "OP_1 OP_DROP" or "OP_2 OP_DROP"
  16. SCRIPT_SIG = ["0451025175", "0451025275"]
  17. def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increment):
  18. """
  19. Create and send a transaction with a random fee.
  20. The transaction pays to a trivial P2SH script, and assumes that its inputs
  21. are of the same form.
  22. The function takes a list of confirmed outputs and unconfirmed outputs
  23. and attempts to use the confirmed list first for its inputs.
  24. It adds the newly created outputs to the unconfirmed list.
  25. Returns (raw transaction, fee)
  26. """
  27. # It's best to exponentially distribute our random fees
  28. # because the buckets are exponentially spaced.
  29. # Exponentially distributed from 1-128 * fee_increment
  30. rand_fee = float(fee_increment)*(1.1892**random.randint(0,28))
  31. # Total fee ranges from min_fee to min_fee + 127*fee_increment
  32. fee = min_fee - fee_increment + satoshi_round(rand_fee)
  33. inputs = []
  34. total_in = Decimal("0.00000000")
  35. while total_in <= (amount + fee) and len(conflist) > 0:
  36. t = conflist.pop(0)
  37. total_in += t["amount"]
  38. inputs.append({ "txid" : t["txid"], "vout" : t["vout"]} )
  39. if total_in <= amount + fee:
  40. while total_in <= (amount + fee) and len(unconflist) > 0:
  41. t = unconflist.pop(0)
  42. total_in += t["amount"]
  43. inputs.append({ "txid" : t["txid"], "vout" : t["vout"]} )
  44. if total_in <= amount + fee:
  45. raise RuntimeError("Insufficient funds: need %d, have %d"%(amount+fee, total_in))
  46. outputs = {}
  47. outputs = OrderedDict([(P2SH_1, total_in - amount - fee),
  48. (P2SH_2, amount)])
  49. rawtx = from_node.createrawtransaction(inputs, outputs)
  50. # createrawtransaction constructs a transaction that is ready to be signed.
  51. # These transactions don't need to be signed, but we still have to insert the ScriptSig
  52. # that will satisfy the ScriptPubKey.
  53. completetx = rawtx[0:10]
  54. inputnum = 0
  55. for inp in inputs:
  56. completetx += rawtx[10+82*inputnum:82+82*inputnum]
  57. completetx += SCRIPT_SIG[inp["vout"]]
  58. completetx += rawtx[84+82*inputnum:92+82*inputnum]
  59. inputnum += 1
  60. completetx += rawtx[10+82*inputnum:]
  61. txid = from_node.sendrawtransaction(completetx, True)
  62. unconflist.append({ "txid" : txid, "vout" : 0 , "amount" : total_in - amount - fee})
  63. unconflist.append({ "txid" : txid, "vout" : 1 , "amount" : amount})
  64. return (completetx, fee)
  65. def split_inputs(from_node, txins, txouts, initial_split = False):
  66. """
  67. We need to generate a lot of very small inputs so we can generate a ton of transactions
  68. and they will have low priority.
  69. This function takes an input from txins, and creates and sends a transaction
  70. which splits the value into 2 outputs which are appended to txouts.
  71. """
  72. prevtxout = txins.pop()
  73. inputs = []
  74. inputs.append({ "txid" : prevtxout["txid"], "vout" : prevtxout["vout"] })
  75. half_change = satoshi_round(prevtxout["amount"]/2)
  76. rem_change = prevtxout["amount"] - half_change - Decimal("0.00001000")
  77. outputs = OrderedDict([(P2SH_1, half_change), (P2SH_2, rem_change)])
  78. rawtx = from_node.createrawtransaction(inputs, outputs)
  79. # If this is the initial split we actually need to sign the transaction
  80. # Otherwise we just need to insert the property ScriptSig
  81. if (initial_split) :
  82. completetx = from_node.signrawtransaction(rawtx)["hex"]
  83. else :
  84. completetx = rawtx[0:82] + SCRIPT_SIG[prevtxout["vout"]] + rawtx[84:]
  85. txid = from_node.sendrawtransaction(completetx, True)
  86. txouts.append({ "txid" : txid, "vout" : 0 , "amount" : half_change})
  87. txouts.append({ "txid" : txid, "vout" : 1 , "amount" : rem_change})
  88. def check_estimates(node, fees_seen, max_invalid, print_estimates = True):
  89. """
  90. This function calls estimatefee and verifies that the estimates
  91. meet certain invariants.
  92. """
  93. all_estimates = [ node.estimatefee(i) for i in range(1,26) ]
  94. if print_estimates:
  95. print([str(all_estimates[e-1]) for e in [1,2,3,6,15,25]])
  96. delta = 1.0e-6 # account for rounding error
  97. last_e = max(fees_seen)
  98. for e in [x for x in all_estimates if x >= 0]:
  99. # Estimates should be within the bounds of what transactions fees actually were:
  100. if float(e)+delta < min(fees_seen) or float(e)-delta > max(fees_seen):
  101. raise AssertionError("Estimated fee (%f) out of range (%f,%f)"
  102. %(float(e), min(fees_seen), max(fees_seen)))
  103. # Estimates should be monotonically decreasing
  104. if float(e)-delta > last_e:
  105. raise AssertionError("Estimated fee (%f) larger than last fee (%f) for lower number of confirms"
  106. %(float(e),float(last_e)))
  107. last_e = e
  108. valid_estimate = False
  109. invalid_estimates = 0
  110. for i,e in enumerate(all_estimates): # estimate is for i+1
  111. if e >= 0:
  112. valid_estimate = True
  113. # estimatesmartfee should return the same result
  114. assert_equal(node.estimatesmartfee(i+1)["feerate"], e)
  115. else:
  116. invalid_estimates += 1
  117. # estimatesmartfee should still be valid
  118. approx_estimate = node.estimatesmartfee(i+1)["feerate"]
  119. answer_found = node.estimatesmartfee(i+1)["blocks"]
  120. assert(approx_estimate > 0)
  121. assert(answer_found > i+1)
  122. # Once we're at a high enough confirmation count that we can give an estimate
  123. # We should have estimates for all higher confirmation counts
  124. if valid_estimate:
  125. raise AssertionError("Invalid estimate appears at higher confirm count than valid estimate")
  126. # Check on the expected number of different confirmation counts
  127. # that we might not have valid estimates for
  128. if invalid_estimates > max_invalid:
  129. raise AssertionError("More than (%d) invalid estimates"%(max_invalid))
  130. return all_estimates
  131. class EstimateFeeTest(BitcoinTestFramework):
  132. def __init__(self):
  133. super().__init__()
  134. self.num_nodes = 3
  135. self.setup_clean_chain = False
  136. def setup_network(self):
  137. """
  138. We'll setup the network to have 3 nodes that all mine with different parameters.
  139. But first we need to use one node to create a lot of small low priority outputs
  140. which we will use to generate our transactions.
  141. """
  142. self.nodes = []
  143. # Use node0 to mine blocks for input splitting
  144. self.nodes.append(start_node(0, self.options.tmpdir, ["-maxorphantx=1000",
  145. "-whitelist=127.0.0.1"]))
  146. print("This test is time consuming, please be patient")
  147. print("Splitting inputs to small size so we can generate low priority tx's")
  148. self.txouts = []
  149. self.txouts2 = []
  150. # Split a coinbase into two transaction puzzle outputs
  151. split_inputs(self.nodes[0], self.nodes[0].listunspent(0), self.txouts, True)
  152. # Mine
  153. while (len(self.nodes[0].getrawmempool()) > 0):
  154. self.nodes[0].generate(1)
  155. # Repeatedly split those 2 outputs, doubling twice for each rep
  156. # Use txouts to monitor the available utxo, since these won't be tracked in wallet
  157. reps = 0
  158. while (reps < 5):
  159. #Double txouts to txouts2
  160. while (len(self.txouts)>0):
  161. split_inputs(self.nodes[0], self.txouts, self.txouts2)
  162. while (len(self.nodes[0].getrawmempool()) > 0):
  163. self.nodes[0].generate(1)
  164. #Double txouts2 to txouts
  165. while (len(self.txouts2)>0):
  166. split_inputs(self.nodes[0], self.txouts2, self.txouts)
  167. while (len(self.nodes[0].getrawmempool()) > 0):
  168. self.nodes[0].generate(1)
  169. reps += 1
  170. print("Finished splitting")
  171. # Now we can connect the other nodes, didn't want to connect them earlier
  172. # so the estimates would not be affected by the splitting transactions
  173. # Node1 mines small blocks but that are bigger than the expected transaction rate,
  174. # and allows free transactions.
  175. # NOTE: the CreateNewBlock code starts counting block size at 1,000 bytes,
  176. # (17k is room enough for 110 or so transactions)
  177. self.nodes.append(start_node(1, self.options.tmpdir,
  178. ["-blockmaxsize=17000",
  179. "-maxorphantx=1000", "-debug=estimatefee"]))
  180. connect_nodes(self.nodes[1], 0)
  181. # Node2 is a stingy miner, that
  182. # produces too small blocks (room for only 55 or so transactions)
  183. node2args = ["-blockmaxsize=8000", "-maxorphantx=1000"]
  184. self.nodes.append(start_node(2, self.options.tmpdir, node2args))
  185. connect_nodes(self.nodes[0], 2)
  186. connect_nodes(self.nodes[2], 1)
  187. self.is_network_split = False
  188. self.sync_all()
  189. def transact_and_mine(self, numblocks, mining_node):
  190. min_fee = Decimal("0.00001")
  191. # We will now mine numblocks blocks generating on average 100 transactions between each block
  192. # We shuffle our confirmed txout set before each set of transactions
  193. # small_txpuzzle_randfee will use the transactions that have inputs already in the chain when possible
  194. # resorting to tx's that depend on the mempool when those run out
  195. for i in range(numblocks):
  196. random.shuffle(self.confutxo)
  197. for j in range(random.randrange(100-50,100+50)):
  198. from_index = random.randint(1,2)
  199. (txhex, fee) = small_txpuzzle_randfee(self.nodes[from_index], self.confutxo,
  200. self.memutxo, Decimal("0.005"), min_fee, min_fee)
  201. tx_kbytes = (len(txhex) // 2) / 1000.0
  202. self.fees_per_kb.append(float(fee)/tx_kbytes)
  203. sync_mempools(self.nodes[0:3], wait=.1)
  204. mined = mining_node.getblock(mining_node.generate(1)[0],True)["tx"]
  205. sync_blocks(self.nodes[0:3], wait=.1)
  206. # update which txouts are confirmed
  207. newmem = []
  208. for utx in self.memutxo:
  209. if utx["txid"] in mined:
  210. self.confutxo.append(utx)
  211. else:
  212. newmem.append(utx)
  213. self.memutxo = newmem
  214. def run_test(self):
  215. self.fees_per_kb = []
  216. self.memutxo = []
  217. self.confutxo = self.txouts # Start with the set of confirmed txouts after splitting
  218. print("Will output estimates for 1/2/3/6/15/25 blocks")
  219. for i in range(2):
  220. print("Creating transactions and mining them with a block size that can't keep up")
  221. # Create transactions and mine 10 small blocks with node 2, but create txs faster than we can mine
  222. self.transact_and_mine(10, self.nodes[2])
  223. check_estimates(self.nodes[1], self.fees_per_kb, 14)
  224. print("Creating transactions and mining them at a block size that is just big enough")
  225. # Generate transactions while mining 10 more blocks, this time with node1
  226. # which mines blocks with capacity just above the rate that transactions are being created
  227. self.transact_and_mine(10, self.nodes[1])
  228. check_estimates(self.nodes[1], self.fees_per_kb, 2)
  229. # Finish by mining a normal-sized block:
  230. while len(self.nodes[1].getrawmempool()) > 0:
  231. self.nodes[1].generate(1)
  232. sync_blocks(self.nodes[0:3], wait=.1)
  233. print("Final estimates after emptying mempools")
  234. check_estimates(self.nodes[1], self.fees_per_kb, 2)
  235. if __name__ == '__main__':
  236. EstimateFeeTest().main()