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

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