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

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