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

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