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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-2017 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. """Helpful routines for regression testing."""
  6. from base64 import b64encode
  7. from binascii import hexlify, unhexlify
  8. from decimal import Decimal, ROUND_DOWN
  9. import hashlib
  10. import json
  11. import logging
  12. import os
  13. import random
  14. import re
  15. from subprocess import CalledProcessError
  16. import time
  17. from . import coverage
  18. from .authproxy import AuthServiceProxy, JSONRPCException
  19. logger = logging.getLogger("TestFramework.utils")
  20. # Assert functions
  21. ##################
  22. def assert_fee_amount(fee, tx_size, fee_per_kB):
  23. """Assert the fee was in range"""
  24. target_fee = round(tx_size * fee_per_kB / 1000, 8)
  25. if fee < target_fee:
  26. raise AssertionError("Fee of %s BTC too low! (Should be %s BTC)" % (str(fee), str(target_fee)))
  27. # allow the wallet's estimation to be at most 2 bytes off
  28. if fee > (tx_size + 2) * fee_per_kB / 1000:
  29. raise AssertionError("Fee of %s BTC too high! (Should be %s BTC)" % (str(fee), str(target_fee)))
  30. def assert_equal(thing1, thing2, *args):
  31. if thing1 != thing2 or any(thing1 != arg for arg in args):
  32. raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
  33. def assert_greater_than(thing1, thing2):
  34. if thing1 <= thing2:
  35. raise AssertionError("%s <= %s" % (str(thing1), str(thing2)))
  36. def assert_greater_than_or_equal(thing1, thing2):
  37. if thing1 < thing2:
  38. raise AssertionError("%s < %s" % (str(thing1), str(thing2)))
  39. def assert_raises(exc, fun, *args, **kwds):
  40. assert_raises_message(exc, None, fun, *args, **kwds)
  41. def assert_raises_message(exc, message, fun, *args, **kwds):
  42. try:
  43. fun(*args, **kwds)
  44. except JSONRPCException:
  45. raise AssertionError("Use assert_raises_rpc_error() to test RPC failures")
  46. except exc as e:
  47. if message is not None and message not in e.error['message']:
  48. raise AssertionError("Expected substring not found:" + e.error['message'])
  49. except Exception as e:
  50. raise AssertionError("Unexpected exception raised: " + type(e).__name__)
  51. else:
  52. raise AssertionError("No exception raised")
  53. def assert_raises_process_error(returncode, output, fun, *args, **kwds):
  54. """Execute a process and asserts the process return code and output.
  55. Calls function `fun` with arguments `args` and `kwds`. Catches a CalledProcessError
  56. and verifies that the return code and output are as expected. Throws AssertionError if
  57. no CalledProcessError was raised or if the return code and output are not as expected.
  58. Args:
  59. returncode (int): the process return code.
  60. output (string): [a substring of] the process output.
  61. fun (function): the function to call. This should execute a process.
  62. args*: positional arguments for the function.
  63. kwds**: named arguments for the function.
  64. """
  65. try:
  66. fun(*args, **kwds)
  67. except CalledProcessError as e:
  68. if returncode != e.returncode:
  69. raise AssertionError("Unexpected returncode %i" % e.returncode)
  70. if output not in e.output:
  71. raise AssertionError("Expected substring not found:" + e.output)
  72. else:
  73. raise AssertionError("No exception raised")
  74. def assert_raises_rpc_error(code, message, fun, *args, **kwds):
  75. """Run an RPC and verify that a specific JSONRPC exception code and message is raised.
  76. Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException
  77. and verifies that the error code and message are as expected. Throws AssertionError if
  78. no JSONRPCException was raised or if the error code/message are not as expected.
  79. Args:
  80. code (int), optional: the error code returned by the RPC call (defined
  81. in src/rpc/protocol.h). Set to None if checking the error code is not required.
  82. message (string), optional: [a substring of] the error string returned by the
  83. RPC call. Set to None if checking the error string is not required.
  84. fun (function): the function to call. This should be the name of an RPC.
  85. args*: positional arguments for the function.
  86. kwds**: named arguments for the function.
  87. """
  88. assert try_rpc(code, message, fun, *args, **kwds), "No exception raised"
  89. def try_rpc(code, message, fun, *args, **kwds):
  90. """Tries to run an rpc command.
  91. Test against error code and message if the rpc fails.
  92. Returns whether a JSONRPCException was raised."""
  93. try:
  94. fun(*args, **kwds)
  95. except JSONRPCException as e:
  96. # JSONRPCException was thrown as expected. Check the code and message values are correct.
  97. if (code is not None) and (code != e.error["code"]):
  98. raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
  99. if (message is not None) and (message not in e.error['message']):
  100. raise AssertionError("Expected substring not found:" + e.error['message'])
  101. return True
  102. except Exception as e:
  103. raise AssertionError("Unexpected exception raised: " + type(e).__name__)
  104. else:
  105. return False
  106. def assert_is_hex_string(string):
  107. try:
  108. int(string, 16)
  109. except Exception as e:
  110. raise AssertionError(
  111. "Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
  112. def assert_is_hash_string(string, length=64):
  113. if not isinstance(string, str):
  114. raise AssertionError("Expected a string, got type %r" % type(string))
  115. elif length and len(string) != length:
  116. raise AssertionError(
  117. "String of length %d expected; got %d" % (length, len(string)))
  118. elif not re.match('[abcdef0-9]+$', string):
  119. raise AssertionError(
  120. "String %r contains invalid characters for a hash." % string)
  121. def assert_array_result(object_array, to_match, expected, should_not_find=False):
  122. """
  123. Pass in array of JSON objects, a dictionary with key/value pairs
  124. to match against, and another dictionary with expected key/value
  125. pairs.
  126. If the should_not_find flag is true, to_match should not be found
  127. in object_array
  128. """
  129. if should_not_find:
  130. assert_equal(expected, {})
  131. num_matched = 0
  132. for item in object_array:
  133. all_match = True
  134. for key, value in to_match.items():
  135. if item[key] != value:
  136. all_match = False
  137. if not all_match:
  138. continue
  139. elif should_not_find:
  140. num_matched = num_matched + 1
  141. for key, value in expected.items():
  142. if item[key] != value:
  143. raise AssertionError("%s : expected %s=%s" % (str(item), str(key), str(value)))
  144. num_matched = num_matched + 1
  145. if num_matched == 0 and not should_not_find:
  146. raise AssertionError("No objects matched %s" % (str(to_match)))
  147. if num_matched > 0 and should_not_find:
  148. raise AssertionError("Objects were found %s" % (str(to_match)))
  149. # Utility functions
  150. ###################
  151. def check_json_precision():
  152. """Make sure json library being used does not lose precision converting BTC values"""
  153. n = Decimal("20000000.00000003")
  154. satoshis = int(json.loads(json.dumps(float(n))) * 1.0e8)
  155. if satoshis != 2000000000000003:
  156. raise RuntimeError("JSON encode/decode loses precision")
  157. def count_bytes(hex_string):
  158. return len(bytearray.fromhex(hex_string))
  159. def bytes_to_hex_str(byte_str):
  160. return hexlify(byte_str).decode('ascii')
  161. def hash256(byte_str):
  162. sha256 = hashlib.sha256()
  163. sha256.update(byte_str)
  164. sha256d = hashlib.sha256()
  165. sha256d.update(sha256.digest())
  166. return sha256d.digest()[::-1]
  167. def hex_str_to_bytes(hex_str):
  168. return unhexlify(hex_str.encode('ascii'))
  169. def str_to_b64str(string):
  170. return b64encode(string.encode('utf-8')).decode('ascii')
  171. def satoshi_round(amount):
  172. return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
  173. def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf'), lock=None):
  174. if attempts == float('inf') and timeout == float('inf'):
  175. timeout = 60
  176. attempt = 0
  177. timeout += time.time()
  178. while attempt < attempts and time.time() < timeout:
  179. if lock:
  180. with lock:
  181. if predicate():
  182. return
  183. else:
  184. if predicate():
  185. return
  186. attempt += 1
  187. time.sleep(0.05)
  188. # Print the cause of the timeout
  189. assert_greater_than(attempts, attempt)
  190. assert_greater_than(timeout, time.time())
  191. raise RuntimeError('Unreachable')
  192. # RPC/P2P connection constants and functions
  193. ############################################
  194. # The maximum number of nodes a single test can spawn
  195. MAX_NODES = 8
  196. # Don't assign rpc or p2p ports lower than this
  197. PORT_MIN = 11000
  198. # The number of ports to "reserve" for p2p and rpc, each
  199. PORT_RANGE = 5000
  200. class PortSeed:
  201. # Must be initialized with a unique integer for each process
  202. n = None
  203. def get_rpc_proxy(url, node_number, timeout=None, coveragedir=None):
  204. """
  205. Args:
  206. url (str): URL of the RPC server to call
  207. node_number (int): the node number (or id) that this calls to
  208. Kwargs:
  209. timeout (int): HTTP timeout in seconds
  210. Returns:
  211. AuthServiceProxy. convenience object for making RPC calls.
  212. """
  213. proxy_kwargs = {}
  214. if timeout is not None:
  215. proxy_kwargs['timeout'] = timeout
  216. proxy = AuthServiceProxy(url, **proxy_kwargs)
  217. proxy.url = url # store URL on proxy for info
  218. coverage_logfile = coverage.get_filename(
  219. coveragedir, node_number) if coveragedir else None
  220. return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
  221. def p2p_port(n):
  222. assert(n <= MAX_NODES)
  223. return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
  224. def rpc_port(n):
  225. return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
  226. def rpc_url(datadir, i, rpchost=None):
  227. rpc_u, rpc_p = get_auth_cookie(datadir)
  228. host = '127.0.0.1'
  229. port = rpc_port(i)
  230. if rpchost:
  231. parts = rpchost.split(':')
  232. if len(parts) == 2:
  233. host, port = parts
  234. else:
  235. host = rpchost
  236. return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
  237. # Node functions
  238. ################
  239. def initialize_datadir(dirname, n):
  240. datadir = os.path.join(dirname, "node" + str(n))
  241. if not os.path.isdir(datadir):
  242. os.makedirs(datadir)
  243. with open(os.path.join(datadir, "bitcoin.conf"), 'w', encoding='utf8') as f:
  244. f.write("regtest=1\n")
  245. f.write("port=" + str(p2p_port(n)) + "\n")
  246. f.write("rpcport=" + str(rpc_port(n)) + "\n")
  247. f.write("listenonion=0\n")
  248. return datadir
  249. def get_datadir_path(dirname, n):
  250. return os.path.join(dirname, "node" + str(n))
  251. def get_auth_cookie(datadir):
  252. user = None
  253. password = None
  254. if os.path.isfile(os.path.join(datadir, "bitcoin.conf")):
  255. with open(os.path.join(datadir, "bitcoin.conf"), 'r', encoding='utf8') as f:
  256. for line in f:
  257. if line.startswith("rpcuser="):
  258. assert user is None # Ensure that there is only one rpcuser line
  259. user = line.split("=")[1].strip("\n")
  260. if line.startswith("rpcpassword="):
  261. assert password is None # Ensure that there is only one rpcpassword line
  262. password = line.split("=")[1].strip("\n")
  263. if os.path.isfile(os.path.join(datadir, "regtest", ".cookie")):
  264. with open(os.path.join(datadir, "regtest", ".cookie"), 'r') as f:
  265. userpass = f.read()
  266. split_userpass = userpass.split(':')
  267. user = split_userpass[0]
  268. password = split_userpass[1]
  269. if user is None or password is None:
  270. raise ValueError("No RPC credentials")
  271. return user, password
  272. def log_filename(dirname, n_node, logname):
  273. return os.path.join(dirname, "node" + str(n_node), "regtest", logname)
  274. def get_bip9_status(node, key):
  275. info = node.getblockchaininfo()
  276. return info['bip9_softforks'][key]
  277. def set_node_times(nodes, t):
  278. for node in nodes:
  279. node.setmocktime(t)
  280. def disconnect_nodes(from_connection, node_num):
  281. for peer_id in [peer['id'] for peer in from_connection.getpeerinfo() if "testnode%d" % node_num in peer['subver']]:
  282. from_connection.disconnectnode(nodeid=peer_id)
  283. # wait to disconnect
  284. wait_until(lambda: [peer['id'] for peer in from_connection.getpeerinfo() if "testnode%d" % node_num in peer['subver']] == [], timeout=5)
  285. def connect_nodes(from_connection, node_num):
  286. ip_port = "127.0.0.1:" + str(p2p_port(node_num))
  287. from_connection.addnode(ip_port, "onetry")
  288. # poll until version handshake complete to avoid race conditions
  289. # with transaction relaying
  290. wait_until(lambda: all(peer['version'] != 0 for peer in from_connection.getpeerinfo()))
  291. def connect_nodes_bi(nodes, a, b):
  292. connect_nodes(nodes[a], b)
  293. connect_nodes(nodes[b], a)
  294. def sync_blocks(rpc_connections, *, wait=1, timeout=60):
  295. """
  296. Wait until everybody has the same tip.
  297. sync_blocks needs to be called with an rpc_connections set that has least
  298. one node already synced to the latest, stable tip, otherwise there's a
  299. chance it might return before all nodes are stably synced.
  300. """
  301. # Use getblockcount() instead of waitforblockheight() to determine the
  302. # initial max height because the two RPCs look at different internal global
  303. # variables (chainActive vs latestBlock) and the former gets updated
  304. # earlier.
  305. maxheight = max(x.getblockcount() for x in rpc_connections)
  306. start_time = cur_time = time.time()
  307. while cur_time <= start_time + timeout:
  308. tips = [r.waitforblockheight(maxheight, int(wait * 1000)) for r in rpc_connections]
  309. if all(t["height"] == maxheight for t in tips):
  310. if all(t["hash"] == tips[0]["hash"] for t in tips):
  311. return
  312. raise AssertionError("Block sync failed, mismatched block hashes:{}".format(
  313. "".join("\n {!r}".format(tip) for tip in tips)))
  314. cur_time = time.time()
  315. raise AssertionError("Block sync to height {} timed out:{}".format(
  316. maxheight, "".join("\n {!r}".format(tip) for tip in tips)))
  317. def sync_chain(rpc_connections, *, wait=1, timeout=60):
  318. """
  319. Wait until everybody has the same best block
  320. """
  321. while timeout > 0:
  322. best_hash = [x.getbestblockhash() for x in rpc_connections]
  323. if best_hash == [best_hash[0]] * len(best_hash):
  324. return
  325. time.sleep(wait)
  326. timeout -= wait
  327. raise AssertionError("Chain sync failed: Best block hashes don't match")
  328. def sync_mempools(rpc_connections, *, wait=1, timeout=60, flush_scheduler=True):
  329. """
  330. Wait until everybody has the same transactions in their memory
  331. pools
  332. """
  333. while timeout > 0:
  334. pool = set(rpc_connections[0].getrawmempool())
  335. num_match = 1
  336. for i in range(1, len(rpc_connections)):
  337. if set(rpc_connections[i].getrawmempool()) == pool:
  338. num_match = num_match + 1
  339. if num_match == len(rpc_connections):
  340. if flush_scheduler:
  341. for r in rpc_connections:
  342. r.syncwithvalidationinterfacequeue()
  343. return
  344. time.sleep(wait)
  345. timeout -= wait
  346. raise AssertionError("Mempool sync failed")
  347. # Transaction/Block functions
  348. #############################
  349. def find_output(node, txid, amount):
  350. """
  351. Return index to output of txid with value amount
  352. Raises exception if there is none.
  353. """
  354. txdata = node.getrawtransaction(txid, 1)
  355. for i in range(len(txdata["vout"])):
  356. if txdata["vout"][i]["value"] == amount:
  357. return i
  358. raise RuntimeError("find_output txid %s : %s not found" % (txid, str(amount)))
  359. def gather_inputs(from_node, amount_needed, confirmations_required=1):
  360. """
  361. Return a random set of unspent txouts that are enough to pay amount_needed
  362. """
  363. assert(confirmations_required >= 0)
  364. utxo = from_node.listunspent(confirmations_required)
  365. random.shuffle(utxo)
  366. inputs = []
  367. total_in = Decimal("0.00000000")
  368. while total_in < amount_needed and len(utxo) > 0:
  369. t = utxo.pop()
  370. total_in += t["amount"]
  371. inputs.append({"txid": t["txid"], "vout": t["vout"], "address": t["address"]})
  372. if total_in < amount_needed:
  373. raise RuntimeError("Insufficient funds: need %d, have %d" % (amount_needed, total_in))
  374. return (total_in, inputs)
  375. def make_change(from_node, amount_in, amount_out, fee):
  376. """
  377. Create change output(s), return them
  378. """
  379. outputs = {}
  380. amount = amount_out + fee
  381. change = amount_in - amount
  382. if change > amount * 2:
  383. # Create an extra change output to break up big inputs
  384. change_address = from_node.getnewaddress()
  385. # Split change in two, being careful of rounding:
  386. outputs[change_address] = Decimal(change / 2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
  387. change = amount_in - amount - outputs[change_address]
  388. if change > 0:
  389. outputs[from_node.getnewaddress()] = change
  390. return outputs
  391. def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
  392. """
  393. Create a random transaction.
  394. Returns (txid, hex-encoded-transaction-data, fee)
  395. """
  396. from_node = random.choice(nodes)
  397. to_node = random.choice(nodes)
  398. fee = min_fee + fee_increment * random.randint(0, fee_variants)
  399. (total_in, inputs) = gather_inputs(from_node, amount + fee)
  400. outputs = make_change(from_node, total_in, amount, fee)
  401. outputs[to_node.getnewaddress()] = float(amount)
  402. rawtx = from_node.createrawtransaction(inputs, outputs)
  403. signresult = from_node.signrawtransaction(rawtx)
  404. txid = from_node.sendrawtransaction(signresult["hex"], True)
  405. return (txid, signresult["hex"], fee)
  406. # Helper to create at least "count" utxos
  407. # Pass in a fee that is sufficient for relay and mining new transactions.
  408. def create_confirmed_utxos(fee, node, count):
  409. to_generate = int(0.5 * count) + 101
  410. while to_generate > 0:
  411. node.generate(min(25, to_generate))
  412. to_generate -= 25
  413. utxos = node.listunspent()
  414. iterations = count - len(utxos)
  415. addr1 = node.getnewaddress()
  416. addr2 = node.getnewaddress()
  417. if iterations <= 0:
  418. return utxos
  419. for i in range(iterations):
  420. t = utxos.pop()
  421. inputs = []
  422. inputs.append({"txid": t["txid"], "vout": t["vout"]})
  423. outputs = {}
  424. send_value = t['amount'] - fee
  425. outputs[addr1] = satoshi_round(send_value / 2)
  426. outputs[addr2] = satoshi_round(send_value / 2)
  427. raw_tx = node.createrawtransaction(inputs, outputs)
  428. signed_tx = node.signrawtransaction(raw_tx)["hex"]
  429. node.sendrawtransaction(signed_tx)
  430. while (node.getmempoolinfo()['size'] > 0):
  431. node.generate(1)
  432. utxos = node.listunspent()
  433. assert(len(utxos) >= count)
  434. return utxos
  435. # Create large OP_RETURN txouts that can be appended to a transaction
  436. # to make it large (helper for constructing large transactions).
  437. def gen_return_txouts():
  438. # Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
  439. # So we have big transactions (and therefore can't fit very many into each block)
  440. # create one script_pubkey
  441. script_pubkey = "6a4d0200" # OP_RETURN OP_PUSH2 512 bytes
  442. for i in range(512):
  443. script_pubkey = script_pubkey + "01"
  444. # concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
  445. txouts = "81"
  446. for k in range(128):
  447. # add txout value
  448. txouts = txouts + "0000000000000000"
  449. # add length of script_pubkey
  450. txouts = txouts + "fd0402"
  451. # add script_pubkey
  452. txouts = txouts + script_pubkey
  453. return txouts
  454. def create_tx(node, coinbase, to_address, amount):
  455. inputs = [{"txid": coinbase, "vout": 0}]
  456. outputs = {to_address: amount}
  457. rawtx = node.createrawtransaction(inputs, outputs)
  458. signresult = node.signrawtransaction(rawtx)
  459. assert_equal(signresult["complete"], True)
  460. return signresult["hex"]
  461. # Create a spend of each passed-in utxo, splicing in "txouts" to each raw
  462. # transaction to make it large. See gen_return_txouts() above.
  463. def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
  464. addr = node.getnewaddress()
  465. txids = []
  466. for _ in range(num):
  467. t = utxos.pop()
  468. inputs = [{"txid": t["txid"], "vout": t["vout"]}]
  469. outputs = {}
  470. change = t['amount'] - fee
  471. outputs[addr] = satoshi_round(change)
  472. rawtx = node.createrawtransaction(inputs, outputs)
  473. newtx = rawtx[0:92]
  474. newtx = newtx + txouts
  475. newtx = newtx + rawtx[94:]
  476. signresult = node.signrawtransaction(newtx, None, None, "NONE")
  477. txid = node.sendrawtransaction(signresult["hex"], True)
  478. txids.append(txid)
  479. return txids
  480. def mine_large_block(node, utxos=None):
  481. # generate a 66k transaction,
  482. # and 14 of them is close to the 1MB block limit
  483. num = 14
  484. txouts = gen_return_txouts()
  485. utxos = utxos if utxos is not None else []
  486. if len(utxos) < num:
  487. utxos.clear()
  488. utxos.extend(node.listunspent())
  489. fee = 100 * node.getnetworkinfo()["relayfee"]
  490. create_lots_of_big_transactions(node, txouts, utxos, num, fee=fee)
  491. node.generate(1)