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.

util.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. # Copyright (c) 2014 The Bitcoin Core developers
  2. # Distributed under the MIT software license, see the accompanying
  3. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #
  5. # Helpful routines for regression testing
  6. #
  7. # Add python-bitcoinrpc to module search path:
  8. import os
  9. import sys
  10. sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc"))
  11. from decimal import Decimal, ROUND_DOWN
  12. import json
  13. import random
  14. import shutil
  15. import subprocess
  16. import time
  17. import re
  18. from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
  19. from util import *
  20. def p2p_port(n):
  21. return 11000 + n + os.getpid()%999
  22. def rpc_port(n):
  23. return 12000 + n + os.getpid()%999
  24. def check_json_precision():
  25. """Make sure json library being used does not lose precision converting BTC values"""
  26. n = Decimal("20000000.00000003")
  27. satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
  28. if satoshis != 2000000000000003:
  29. raise RuntimeError("JSON encode/decode loses precision")
  30. def sync_blocks(rpc_connections):
  31. """
  32. Wait until everybody has the same block count
  33. """
  34. while True:
  35. counts = [ x.getblockcount() for x in rpc_connections ]
  36. if counts == [ counts[0] ]*len(counts):
  37. break
  38. time.sleep(1)
  39. def sync_mempools(rpc_connections):
  40. """
  41. Wait until everybody has the same transactions in their memory
  42. pools
  43. """
  44. while True:
  45. pool = set(rpc_connections[0].getrawmempool())
  46. num_match = 1
  47. for i in range(1, len(rpc_connections)):
  48. if set(rpc_connections[i].getrawmempool()) == pool:
  49. num_match = num_match+1
  50. if num_match == len(rpc_connections):
  51. break
  52. time.sleep(1)
  53. bitcoind_processes = {}
  54. def initialize_datadir(dirname, n):
  55. datadir = os.path.join(dirname, "node"+str(n))
  56. if not os.path.isdir(datadir):
  57. os.makedirs(datadir)
  58. with open(os.path.join(datadir, "bitcoin.conf"), 'w') as f:
  59. f.write("regtest=1\n");
  60. f.write("rpcuser=rt\n");
  61. f.write("rpcpassword=rt\n");
  62. f.write("port="+str(p2p_port(n))+"\n");
  63. f.write("rpcport="+str(rpc_port(n))+"\n");
  64. return datadir
  65. def initialize_chain(test_dir):
  66. """
  67. Create (or copy from cache) a 200-block-long chain and
  68. 4 wallets.
  69. bitcoind and bitcoin-cli must be in search path.
  70. """
  71. if not os.path.isdir(os.path.join("cache", "node0")):
  72. devnull = open("/dev/null", "w+")
  73. # Create cache directories, run bitcoinds:
  74. for i in range(4):
  75. datadir=initialize_datadir("cache", i)
  76. args = [ os.getenv("BITCOIND", "bitcoind"), "-keypool=1", "-datadir="+datadir, "-discover=0" ]
  77. if i > 0:
  78. args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
  79. bitcoind_processes[i] = subprocess.Popen(args)
  80. subprocess.check_call([ os.getenv("BITCOINCLI", "bitcoin-cli"), "-datadir="+datadir,
  81. "-rpcwait", "getblockcount"], stdout=devnull)
  82. devnull.close()
  83. rpcs = []
  84. for i in range(4):
  85. try:
  86. url = "http://rt:rt@127.0.0.1:%d"%(rpc_port(i),)
  87. rpcs.append(AuthServiceProxy(url))
  88. except:
  89. sys.stderr.write("Error connecting to "+url+"\n")
  90. sys.exit(1)
  91. # Create a 200-block-long chain; each of the 4 nodes
  92. # gets 25 mature blocks and 25 immature.
  93. # blocks are created with timestamps 10 minutes apart, starting
  94. # at 1 Jan 2014
  95. block_time = 1388534400
  96. for i in range(2):
  97. for peer in range(4):
  98. for j in range(25):
  99. set_node_times(rpcs, block_time)
  100. rpcs[peer].generate(1)
  101. block_time += 10*60
  102. # Must sync before next peer starts generating blocks
  103. sync_blocks(rpcs)
  104. # Shut them down, and clean up cache directories:
  105. stop_nodes(rpcs)
  106. wait_bitcoinds()
  107. for i in range(4):
  108. os.remove(log_filename("cache", i, "debug.log"))
  109. os.remove(log_filename("cache", i, "db.log"))
  110. os.remove(log_filename("cache", i, "peers.dat"))
  111. os.remove(log_filename("cache", i, "fee_estimates.dat"))
  112. for i in range(4):
  113. from_dir = os.path.join("cache", "node"+str(i))
  114. to_dir = os.path.join(test_dir, "node"+str(i))
  115. shutil.copytree(from_dir, to_dir)
  116. initialize_datadir(test_dir, i) # Overwrite port/rpcport in bitcoin.conf
  117. def initialize_chain_clean(test_dir, num_nodes):
  118. """
  119. Create an empty blockchain and num_nodes wallets.
  120. Useful if a test case wants complete control over initialization.
  121. """
  122. for i in range(num_nodes):
  123. datadir=initialize_datadir(test_dir, i)
  124. def _rpchost_to_args(rpchost):
  125. '''Convert optional IP:port spec to rpcconnect/rpcport args'''
  126. if rpchost is None:
  127. return []
  128. match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
  129. if not match:
  130. raise ValueError('Invalid RPC host spec ' + rpchost)
  131. rpcconnect = match.group(1)
  132. rpcport = match.group(2)
  133. if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
  134. rpcconnect = rpcconnect[1:-1]
  135. rv = ['-rpcconnect=' + rpcconnect]
  136. if rpcport:
  137. rv += ['-rpcport=' + rpcport]
  138. return rv
  139. def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None):
  140. """
  141. Start a bitcoind and return RPC connection to it
  142. """
  143. datadir = os.path.join(dirname, "node"+str(i))
  144. args = [ os.getenv("BITCOIND", "bitcoind"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ]
  145. if extra_args is not None: args.extend(extra_args)
  146. bitcoind_processes[i] = subprocess.Popen(args)
  147. devnull = open("/dev/null", "w+")
  148. subprocess.check_call([ os.getenv("BITCOINCLI", "bitcoin-cli"), "-datadir="+datadir] +
  149. _rpchost_to_args(rpchost) +
  150. ["-rpcwait", "getblockcount"], stdout=devnull)
  151. devnull.close()
  152. url = "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))
  153. if timewait is not None:
  154. proxy = AuthServiceProxy(url, timeout=timewait)
  155. else:
  156. proxy = AuthServiceProxy(url)
  157. proxy.url = url # store URL on proxy for info
  158. return proxy
  159. def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None):
  160. """
  161. Start multiple bitcoinds, return RPC connections to them
  162. """
  163. if extra_args is None: extra_args = [ None for i in range(num_nodes) ]
  164. return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ]
  165. def log_filename(dirname, n_node, logname):
  166. return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
  167. def stop_node(node, i):
  168. node.stop()
  169. bitcoind_processes[i].wait()
  170. del bitcoind_processes[i]
  171. def stop_nodes(nodes):
  172. for node in nodes:
  173. node.stop()
  174. del nodes[:] # Emptying array closes connections as a side effect
  175. def set_node_times(nodes, t):
  176. for node in nodes:
  177. node.setmocktime(t)
  178. def wait_bitcoinds():
  179. # Wait for all bitcoinds to cleanly exit
  180. for bitcoind in bitcoind_processes.values():
  181. bitcoind.wait()
  182. bitcoind_processes.clear()
  183. def connect_nodes(from_connection, node_num):
  184. ip_port = "127.0.0.1:"+str(p2p_port(node_num))
  185. from_connection.addnode(ip_port, "onetry")
  186. # poll until version handshake complete to avoid race conditions
  187. # with transaction relaying
  188. while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
  189. time.sleep(0.1)
  190. def connect_nodes_bi(nodes, a, b):
  191. connect_nodes(nodes[a], b)
  192. connect_nodes(nodes[b], a)
  193. def find_output(node, txid, amount):
  194. """
  195. Return index to output of txid with value amount
  196. Raises exception if there is none.
  197. """
  198. txdata = node.getrawtransaction(txid, 1)
  199. for i in range(len(txdata["vout"])):
  200. if txdata["vout"][i]["value"] == amount:
  201. return i
  202. raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
  203. def gather_inputs(from_node, amount_needed, confirmations_required=1):
  204. """
  205. Return a random set of unspent txouts that are enough to pay amount_needed
  206. """
  207. assert(confirmations_required >=0)
  208. utxo = from_node.listunspent(confirmations_required)
  209. random.shuffle(utxo)
  210. inputs = []
  211. total_in = Decimal("0.00000000")
  212. while total_in < amount_needed and len(utxo) > 0:
  213. t = utxo.pop()
  214. total_in += t["amount"]
  215. inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } )
  216. if total_in < amount_needed:
  217. raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in))
  218. return (total_in, inputs)
  219. def make_change(from_node, amount_in, amount_out, fee):
  220. """
  221. Create change output(s), return them
  222. """
  223. outputs = {}
  224. amount = amount_out+fee
  225. change = amount_in - amount
  226. if change > amount*2:
  227. # Create an extra change output to break up big inputs
  228. change_address = from_node.getnewaddress()
  229. # Split change in two, being careful of rounding:
  230. outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
  231. change = amount_in - amount - outputs[change_address]
  232. if change > 0:
  233. outputs[from_node.getnewaddress()] = change
  234. return outputs
  235. def send_zeropri_transaction(from_node, to_node, amount, fee):
  236. """
  237. Create&broadcast a zero-priority transaction.
  238. Returns (txid, hex-encoded-txdata)
  239. Ensures transaction is zero-priority by first creating a send-to-self,
  240. then using it's output
  241. """
  242. # Create a send-to-self with confirmed inputs:
  243. self_address = from_node.getnewaddress()
  244. (total_in, inputs) = gather_inputs(from_node, amount+fee*2)
  245. outputs = make_change(from_node, total_in, amount+fee, fee)
  246. outputs[self_address] = float(amount+fee)
  247. self_rawtx = from_node.createrawtransaction(inputs, outputs)
  248. self_signresult = from_node.signrawtransaction(self_rawtx)
  249. self_txid = from_node.sendrawtransaction(self_signresult["hex"], True)
  250. vout = find_output(from_node, self_txid, amount+fee)
  251. # Now immediately spend the output to create a 1-input, 1-output
  252. # zero-priority transaction:
  253. inputs = [ { "txid" : self_txid, "vout" : vout } ]
  254. outputs = { to_node.getnewaddress() : float(amount) }
  255. rawtx = from_node.createrawtransaction(inputs, outputs)
  256. signresult = from_node.signrawtransaction(rawtx)
  257. txid = from_node.sendrawtransaction(signresult["hex"], True)
  258. return (txid, signresult["hex"])
  259. def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
  260. """
  261. Create a random zero-priority transaction.
  262. Returns (txid, hex-encoded-transaction-data, fee)
  263. """
  264. from_node = random.choice(nodes)
  265. to_node = random.choice(nodes)
  266. fee = min_fee + fee_increment*random.randint(0,fee_variants)
  267. (txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
  268. return (txid, txhex, fee)
  269. def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
  270. """
  271. Create a random transaction.
  272. Returns (txid, hex-encoded-transaction-data, fee)
  273. """
  274. from_node = random.choice(nodes)
  275. to_node = random.choice(nodes)
  276. fee = min_fee + fee_increment*random.randint(0,fee_variants)
  277. (total_in, inputs) = gather_inputs(from_node, amount+fee)
  278. outputs = make_change(from_node, total_in, amount, fee)
  279. outputs[to_node.getnewaddress()] = float(amount)
  280. rawtx = from_node.createrawtransaction(inputs, outputs)
  281. signresult = from_node.signrawtransaction(rawtx)
  282. txid = from_node.sendrawtransaction(signresult["hex"], True)
  283. return (txid, signresult["hex"], fee)
  284. def assert_equal(thing1, thing2):
  285. if thing1 != thing2:
  286. raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
  287. def assert_greater_than(thing1, thing2):
  288. if thing1 <= thing2:
  289. raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
  290. def assert_raises(exc, fun, *args, **kwds):
  291. try:
  292. fun(*args, **kwds)
  293. except exc:
  294. pass
  295. except Exception as e:
  296. raise AssertionError("Unexpected exception raised: "+type(e).__name__)
  297. else:
  298. raise AssertionError("No exception raised")