2016-05-06 11:23:48 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# Copyright (c) 2014-2016 The Bitcoin Core developers
|
2021-04-20 21:33:02 +02:00
|
|
|
# Copyright (c) 2014-2021 The Dash Core developers
|
2016-05-06 11:23:48 +02:00
|
|
|
# Distributed under the MIT software license, see the accompanying
|
2014-03-18 10:11:00 +01:00
|
|
|
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
2019-01-07 10:55:35 +01:00
|
|
|
"""Helpful routines for regression testing."""
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2016-04-10 16:54:28 +02:00
|
|
|
from base64 import b64encode
|
2017-06-29 17:37:19 +02:00
|
|
|
from binascii import hexlify, unhexlify
|
2014-09-03 21:07:43 +02:00
|
|
|
from decimal import Decimal, ROUND_DOWN
|
2017-09-29 19:44:10 +02:00
|
|
|
import hashlib
|
2020-01-11 02:31:25 +01:00
|
|
|
import inspect
|
2014-02-26 22:31:18 +01:00
|
|
|
import json
|
2017-06-29 17:37:19 +02:00
|
|
|
import logging
|
|
|
|
import os
|
2014-03-17 13:19:54 +01:00
|
|
|
import random
|
2019-08-13 21:48:24 +02:00
|
|
|
import shutil
|
2014-04-07 17:29:36 +02:00
|
|
|
import re
|
2017-09-06 17:35:57 +02:00
|
|
|
from subprocess import CalledProcessError
|
2017-06-29 17:37:19 +02:00
|
|
|
import time
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2015-10-11 07:41:19 +02:00
|
|
|
from . import coverage
|
|
|
|
from .authproxy import AuthServiceProxy, JSONRPCException
|
2019-07-15 14:02:00 +02:00
|
|
|
from io import BytesIO
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2017-03-09 21:16:20 +01:00
|
|
|
logger = logging.getLogger("TestFramework.utils")
|
|
|
|
|
2020-07-12 21:32:38 +02:00
|
|
|
# Util options
|
|
|
|
##############
|
|
|
|
|
|
|
|
class Options:
|
|
|
|
timeout_scale = 1
|
|
|
|
|
|
|
|
def set_timeout_scale(_timeout_scale):
|
|
|
|
Options.timeout_scale = _timeout_scale
|
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Assert functions
|
|
|
|
##################
|
2016-05-09 17:01:55 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def assert_fee_amount(fee, tx_size, fee_per_kB):
|
|
|
|
"""Assert the fee was in range"""
|
2018-02-23 17:01:33 +01:00
|
|
|
target_fee = round(tx_size * fee_per_kB / 1000, 8)
|
2017-06-29 17:37:19 +02:00
|
|
|
if fee < target_fee:
|
2019-08-13 18:27:56 +02:00
|
|
|
raise AssertionError("Fee of %s DASH too low! (Should be %s DASH)" % (str(fee), str(target_fee)))
|
2017-06-29 17:37:19 +02:00
|
|
|
# allow the wallet's estimation to be at most 2 bytes off
|
|
|
|
if fee > (tx_size + 2) * fee_per_kB / 1000:
|
2019-08-13 18:27:56 +02:00
|
|
|
raise AssertionError("Fee of %s DASH too high! (Should be %s DASH)" % (str(fee), str(target_fee)))
|
2016-05-20 17:33:46 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def assert_equal(thing1, thing2, *args):
|
|
|
|
if thing1 != thing2 or any(thing1 != arg for arg in args):
|
|
|
|
raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
|
2016-05-10 18:27:31 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def assert_greater_than(thing1, thing2):
|
|
|
|
if thing1 <= thing2:
|
|
|
|
raise AssertionError("%s <= %s" % (str(thing1), str(thing2)))
|
|
|
|
|
|
|
|
def assert_greater_than_or_equal(thing1, thing2):
|
|
|
|
if thing1 < thing2:
|
|
|
|
raise AssertionError("%s < %s" % (str(thing1), str(thing2)))
|
|
|
|
|
|
|
|
def assert_raises(exc, fun, *args, **kwds):
|
|
|
|
assert_raises_message(exc, None, fun, *args, **kwds)
|
|
|
|
|
|
|
|
def assert_raises_message(exc, message, fun, *args, **kwds):
|
|
|
|
try:
|
|
|
|
fun(*args, **kwds)
|
2017-07-12 16:29:21 +02:00
|
|
|
except JSONRPCException:
|
2019-09-25 11:34:51 +02:00
|
|
|
raise AssertionError("Use assert_raises_rpc_error() to test RPC failures")
|
2017-06-29 17:37:19 +02:00
|
|
|
except exc as e:
|
|
|
|
if message is not None and message not in e.error['message']:
|
|
|
|
raise AssertionError("Expected substring not found:" + e.error['message'])
|
|
|
|
except Exception as e:
|
|
|
|
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
|
|
|
|
else:
|
|
|
|
raise AssertionError("No exception raised")
|
|
|
|
|
2017-09-06 17:35:57 +02:00
|
|
|
def assert_raises_process_error(returncode, output, fun, *args, **kwds):
|
|
|
|
"""Execute a process and asserts the process return code and output.
|
|
|
|
|
|
|
|
Calls function `fun` with arguments `args` and `kwds`. Catches a CalledProcessError
|
|
|
|
and verifies that the return code and output are as expected. Throws AssertionError if
|
|
|
|
no CalledProcessError was raised or if the return code and output are not as expected.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
returncode (int): the process return code.
|
|
|
|
output (string): [a substring of] the process output.
|
|
|
|
fun (function): the function to call. This should execute a process.
|
|
|
|
args*: positional arguments for the function.
|
|
|
|
kwds**: named arguments for the function.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
fun(*args, **kwds)
|
|
|
|
except CalledProcessError as e:
|
|
|
|
if returncode != e.returncode:
|
|
|
|
raise AssertionError("Unexpected returncode %i" % e.returncode)
|
|
|
|
if output not in e.output:
|
|
|
|
raise AssertionError("Expected substring not found:" + e.output)
|
|
|
|
else:
|
|
|
|
raise AssertionError("No exception raised")
|
|
|
|
|
2019-09-25 11:34:51 +02:00
|
|
|
def assert_raises_rpc_error(code, message, fun, *args, **kwds):
|
2017-06-29 17:37:19 +02:00
|
|
|
"""Run an RPC and verify that a specific JSONRPC exception code and message is raised.
|
|
|
|
|
|
|
|
Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException
|
|
|
|
and verifies that the error code and message are as expected. Throws AssertionError if
|
2017-09-06 17:52:25 +02:00
|
|
|
no JSONRPCException was raised or if the error code/message are not as expected.
|
2017-06-29 17:37:19 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
code (int), optional: the error code returned by the RPC call (defined
|
|
|
|
in src/rpc/protocol.h). Set to None if checking the error code is not required.
|
|
|
|
message (string), optional: [a substring of] the error string returned by the
|
2017-09-06 17:52:25 +02:00
|
|
|
RPC call. Set to None if checking the error string is not required.
|
2017-06-29 17:37:19 +02:00
|
|
|
fun (function): the function to call. This should be the name of an RPC.
|
|
|
|
args*: positional arguments for the function.
|
|
|
|
kwds**: named arguments for the function.
|
|
|
|
"""
|
2017-07-12 16:29:02 +02:00
|
|
|
assert try_rpc(code, message, fun, *args, **kwds), "No exception raised"
|
|
|
|
|
|
|
|
def try_rpc(code, message, fun, *args, **kwds):
|
|
|
|
"""Tries to run an rpc command.
|
|
|
|
|
|
|
|
Test against error code and message if the rpc fails.
|
|
|
|
Returns whether a JSONRPCException was raised."""
|
2017-06-29 17:37:19 +02:00
|
|
|
try:
|
|
|
|
fun(*args, **kwds)
|
|
|
|
except JSONRPCException as e:
|
|
|
|
# JSONRPCException was thrown as expected. Check the code and message values are correct.
|
|
|
|
if (code is not None) and (code != e.error["code"]):
|
|
|
|
raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
|
|
|
|
if (message is not None) and (message not in e.error['message']):
|
|
|
|
raise AssertionError("Expected substring not found:" + e.error['message'])
|
2017-07-12 16:29:02 +02:00
|
|
|
return True
|
2017-06-29 17:37:19 +02:00
|
|
|
except Exception as e:
|
|
|
|
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
|
|
|
|
else:
|
2017-07-12 16:29:02 +02:00
|
|
|
return False
|
2017-06-29 17:37:19 +02:00
|
|
|
|
|
|
|
def assert_is_hex_string(string):
|
|
|
|
try:
|
|
|
|
int(string, 16)
|
|
|
|
except Exception as e:
|
|
|
|
raise AssertionError(
|
|
|
|
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
|
|
|
|
|
|
|
|
def assert_is_hash_string(string, length=64):
|
|
|
|
if not isinstance(string, str):
|
|
|
|
raise AssertionError("Expected a string, got type %r" % type(string))
|
|
|
|
elif length and len(string) != length:
|
|
|
|
raise AssertionError(
|
|
|
|
"String of length %d expected; got %d" % (length, len(string)))
|
|
|
|
elif not re.match('[abcdef0-9]+$', string):
|
|
|
|
raise AssertionError(
|
|
|
|
"String %r contains invalid characters for a hash." % string)
|
|
|
|
|
|
|
|
def assert_array_result(object_array, to_match, expected, should_not_find=False):
|
|
|
|
"""
|
|
|
|
Pass in array of JSON objects, a dictionary with key/value pairs
|
|
|
|
to match against, and another dictionary with expected key/value
|
|
|
|
pairs.
|
|
|
|
If the should_not_find flag is true, to_match should not be found
|
|
|
|
in object_array
|
|
|
|
"""
|
|
|
|
if should_not_find:
|
|
|
|
assert_equal(expected, {})
|
|
|
|
num_matched = 0
|
|
|
|
for item in object_array:
|
|
|
|
all_match = True
|
|
|
|
for key, value in to_match.items():
|
|
|
|
if item[key] != value:
|
|
|
|
all_match = False
|
|
|
|
if not all_match:
|
|
|
|
continue
|
|
|
|
elif should_not_find:
|
|
|
|
num_matched = num_matched + 1
|
|
|
|
for key, value in expected.items():
|
|
|
|
if item[key] != value:
|
|
|
|
raise AssertionError("%s : expected %s=%s" % (str(item), str(key), str(value)))
|
|
|
|
num_matched = num_matched + 1
|
|
|
|
if num_matched == 0 and not should_not_find:
|
|
|
|
raise AssertionError("No objects matched %s" % (str(to_match)))
|
|
|
|
if num_matched > 0 and should_not_find:
|
|
|
|
raise AssertionError("Objects were found %s" % (str(to_match)))
|
2016-05-10 18:27:31 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Utility functions
|
|
|
|
###################
|
2015-12-05 18:02:02 +01:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def check_json_precision():
|
|
|
|
"""Make sure json library being used does not lose precision converting BTC values"""
|
|
|
|
n = Decimal("20000000.00000003")
|
|
|
|
satoshis = int(json.loads(json.dumps(float(n))) * 1.0e8)
|
|
|
|
if satoshis != 2000000000000003:
|
|
|
|
raise RuntimeError("JSON encode/decode loses precision")
|
2015-12-05 18:02:02 +01:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def count_bytes(hex_string):
|
|
|
|
return len(bytearray.fromhex(hex_string))
|
2015-12-05 18:02:02 +01:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def bytes_to_hex_str(byte_str):
|
|
|
|
return hexlify(byte_str).decode('ascii')
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2017-09-29 19:44:10 +02:00
|
|
|
def hash256(byte_str):
|
|
|
|
sha256 = hashlib.sha256()
|
|
|
|
sha256.update(byte_str)
|
|
|
|
sha256d = hashlib.sha256()
|
|
|
|
sha256d.update(sha256.digest())
|
|
|
|
return sha256d.digest()[::-1]
|
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def hex_str_to_bytes(hex_str):
|
|
|
|
return unhexlify(hex_str.encode('ascii'))
|
2018-04-18 13:48:59 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def str_to_b64str(string):
|
|
|
|
return b64encode(string.encode('utf-8')).decode('ascii')
|
2018-04-18 13:48:59 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def satoshi_round(amount):
|
|
|
|
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2019-12-06 10:05:58 +01:00
|
|
|
def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf'), sleep=0.05, lock=None, do_assert=True, allow_exception=False):
|
2017-08-23 23:11:33 +02:00
|
|
|
if attempts == float('inf') and timeout == float('inf'):
|
|
|
|
timeout = 60
|
|
|
|
attempt = 0
|
2020-07-12 21:32:38 +02:00
|
|
|
timeout *= Options.timeout_scale
|
2020-01-11 02:31:25 +01:00
|
|
|
time_end = time.time() + timeout
|
2017-08-23 23:11:33 +02:00
|
|
|
|
2020-01-11 02:31:25 +01:00
|
|
|
while attempt < attempts and time.time() < time_end:
|
2019-12-06 10:05:58 +01:00
|
|
|
try:
|
|
|
|
if lock:
|
|
|
|
with lock:
|
|
|
|
if predicate():
|
|
|
|
return True
|
|
|
|
else:
|
2017-08-23 23:11:33 +02:00
|
|
|
if predicate():
|
2019-12-06 10:05:58 +01:00
|
|
|
return True
|
|
|
|
except:
|
|
|
|
if not allow_exception:
|
|
|
|
raise
|
2017-08-23 23:11:33 +02:00
|
|
|
attempt += 1
|
|
|
|
time.sleep(sleep)
|
|
|
|
|
2019-12-06 10:05:58 +01:00
|
|
|
if do_assert:
|
|
|
|
# Print the cause of the timeout
|
2020-01-11 02:31:25 +01:00
|
|
|
predicate_source = inspect.getsourcelines(predicate)
|
|
|
|
logger.error("wait_until() failed. Predicate: {}".format(predicate_source))
|
|
|
|
if attempt >= attempts:
|
|
|
|
raise AssertionError("Predicate {} not true after {} attempts".format(predicate_source, attempts))
|
|
|
|
elif time.time() >= time_end:
|
|
|
|
raise AssertionError("Predicate {} not true after {} seconds".format(predicate_source, timeout))
|
2019-12-06 10:05:58 +01:00
|
|
|
raise RuntimeError('Unreachable')
|
|
|
|
else:
|
|
|
|
return False
|
2017-08-23 23:11:33 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# RPC/P2P connection constants and functions
|
|
|
|
############################################
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# The maximum number of nodes a single test can spawn
|
|
|
|
MAX_NODES = 15
|
|
|
|
# Don't assign rpc or p2p ports lower than this
|
|
|
|
PORT_MIN = 11000
|
|
|
|
# The number of ports to "reserve" for p2p and rpc, each
|
|
|
|
PORT_RANGE = 5000
|
|
|
|
|
|
|
|
class PortSeed:
|
|
|
|
# Must be initialized with a unique integer for each process
|
|
|
|
n = None
|
|
|
|
|
2019-10-08 10:29:21 +02:00
|
|
|
def get_rpc_proxy(url, node_number, *, timeout=None, coveragedir=None):
|
2015-10-11 07:41:19 +02:00
|
|
|
"""
|
|
|
|
Args:
|
|
|
|
url (str): URL of the RPC server to call
|
|
|
|
node_number (int): the node number (or id) that this calls to
|
|
|
|
|
|
|
|
Kwargs:
|
|
|
|
timeout (int): HTTP timeout in seconds
|
2019-10-08 10:29:21 +02:00
|
|
|
coveragedir (str): Directory
|
2015-10-11 07:41:19 +02:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
AuthServiceProxy. convenience object for making RPC calls.
|
|
|
|
|
|
|
|
"""
|
|
|
|
proxy_kwargs = {}
|
|
|
|
if timeout is not None:
|
|
|
|
proxy_kwargs['timeout'] = timeout
|
|
|
|
|
|
|
|
proxy = AuthServiceProxy(url, **proxy_kwargs)
|
|
|
|
proxy.url = url # store URL on proxy for info
|
|
|
|
|
|
|
|
coverage_logfile = coverage.get_filename(
|
2017-06-29 17:37:19 +02:00
|
|
|
coveragedir, node_number) if coveragedir else None
|
2015-10-11 07:41:19 +02:00
|
|
|
|
|
|
|
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
|
|
|
|
|
2014-03-14 17:19:52 +01:00
|
|
|
def p2p_port(n):
|
2016-05-09 17:01:55 +02:00
|
|
|
assert(n <= MAX_NODES)
|
2016-05-10 18:27:31 +02:00
|
|
|
return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
|
2016-05-09 17:01:55 +02:00
|
|
|
|
2014-03-14 17:19:52 +01:00
|
|
|
def rpc_port(n):
|
2016-05-10 18:27:31 +02:00
|
|
|
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2021-01-22 15:58:07 +01:00
|
|
|
def rpc_url(datadir, i, chain, rpchost=None):
|
|
|
|
rpc_u, rpc_p = get_auth_cookie(datadir, chain)
|
2017-06-29 17:37:19 +02:00
|
|
|
host = '127.0.0.1'
|
|
|
|
port = rpc_port(i)
|
|
|
|
if rpchost:
|
|
|
|
parts = rpchost.split(':')
|
|
|
|
if len(parts) == 2:
|
|
|
|
host, port = parts
|
|
|
|
else:
|
|
|
|
host = rpchost
|
|
|
|
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
|
2016-08-19 13:53:49 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Node functions
|
|
|
|
################
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2021-01-22 15:58:07 +01:00
|
|
|
def initialize_datadir(dirname, n, chain):
|
2018-03-22 11:04:37 +01:00
|
|
|
datadir = get_datadir_path(dirname, n)
|
2014-03-14 17:19:52 +01:00
|
|
|
if not os.path.isdir(datadir):
|
|
|
|
os.makedirs(datadir)
|
2021-01-22 15:58:07 +01:00
|
|
|
# Translate chain name to config name
|
|
|
|
if chain == 'testnet3':
|
|
|
|
chain_name_conf_arg = 'testnet'
|
|
|
|
chain_name_conf_section = 'test'
|
|
|
|
chain_name_conf_arg_value = '1'
|
|
|
|
elif chain == 'devnet':
|
|
|
|
chain_name_conf_arg = 'devnet'
|
|
|
|
chain_name_conf_section = 'devnet'
|
|
|
|
chain_name_conf_arg_value = 'devnet1'
|
|
|
|
else:
|
|
|
|
chain_name_conf_arg = chain
|
|
|
|
chain_name_conf_section = chain
|
|
|
|
chain_name_conf_arg_value = '1'
|
2016-09-30 12:34:37 +02:00
|
|
|
with open(os.path.join(datadir, "dash.conf"), 'w', encoding='utf8') as f:
|
2021-01-22 15:58:07 +01:00
|
|
|
f.write("{}={}]\n".format(chain_name_conf_arg, chain_name_conf_arg_value))
|
|
|
|
f.write("[{}]\n".format(chain_name_conf_section))
|
2017-06-29 17:37:19 +02:00
|
|
|
f.write("port=" + str(p2p_port(n)) + "\n")
|
|
|
|
f.write("rpcport=" + str(rpc_port(n)) + "\n")
|
2020-12-11 03:08:07 +01:00
|
|
|
f.write("server=1\n")
|
|
|
|
f.write("keypool=1\n")
|
|
|
|
f.write("discover=0\n")
|
2015-12-02 18:12:23 +01:00
|
|
|
f.write("listenonion=0\n")
|
2018-05-09 20:43:09 +02:00
|
|
|
f.write("printtoconsole=0\n")
|
2021-06-17 19:05:11 +02:00
|
|
|
os.makedirs(os.path.join(datadir, 'stderr'), exist_ok=True)
|
|
|
|
os.makedirs(os.path.join(datadir, 'stdout'), exist_ok=True)
|
2014-03-17 13:19:54 +01:00
|
|
|
return datadir
|
2014-03-13 22:51:05 +01:00
|
|
|
|
2017-06-21 14:26:10 +02:00
|
|
|
def get_datadir_path(dirname, n):
|
2017-06-29 17:37:19 +02:00
|
|
|
return os.path.join(dirname, "node" + str(n))
|
2017-06-21 14:26:10 +02:00
|
|
|
|
2018-03-22 11:04:37 +01:00
|
|
|
def append_config(datadir, options):
|
2020-07-09 11:32:43 +02:00
|
|
|
with open(os.path.join(datadir, "dash.conf"), 'a', encoding='utf8') as f:
|
2018-03-07 14:51:58 +01:00
|
|
|
for option in options:
|
|
|
|
f.write(option + "\n")
|
|
|
|
|
2021-01-22 15:58:07 +01:00
|
|
|
def get_auth_cookie(datadir, chain):
|
2017-06-21 14:26:10 +02:00
|
|
|
user = None
|
|
|
|
password = None
|
2019-07-10 16:45:09 +02:00
|
|
|
if os.path.isfile(os.path.join(datadir, "dash.conf")):
|
2017-07-07 13:28:44 +02:00
|
|
|
with open(os.path.join(datadir, "dash.conf"), 'r', encoding='utf8') as f:
|
2017-06-21 14:26:10 +02:00
|
|
|
for line in f:
|
|
|
|
if line.startswith("rpcuser="):
|
2017-06-29 17:37:19 +02:00
|
|
|
assert user is None # Ensure that there is only one rpcuser line
|
2017-06-21 14:26:10 +02:00
|
|
|
user = line.split("=")[1].strip("\n")
|
|
|
|
if line.startswith("rpcpassword="):
|
2017-06-29 17:37:19 +02:00
|
|
|
assert password is None # Ensure that there is only one rpcpassword line
|
2017-06-21 14:26:10 +02:00
|
|
|
password = line.split("=")[1].strip("\n")
|
2021-01-22 15:58:07 +01:00
|
|
|
chain = get_chain_folder(datadir, chain)
|
|
|
|
if os.path.isfile(os.path.join(datadir, chain, ".cookie")):
|
|
|
|
with open(os.path.join(datadir, chain, ".cookie"), 'r', encoding="ascii") as f:
|
2017-06-21 14:26:10 +02:00
|
|
|
userpass = f.read()
|
|
|
|
split_userpass = userpass.split(':')
|
|
|
|
user = split_userpass[0]
|
|
|
|
password = split_userpass[1]
|
|
|
|
if user is None or password is None:
|
|
|
|
raise ValueError("No RPC credentials")
|
|
|
|
return user, password
|
|
|
|
|
2021-01-22 15:58:07 +01:00
|
|
|
def copy_datadir(from_node, to_node, dirname, chain):
|
|
|
|
from_datadir = os.path.join(dirname, "node"+str(from_node), chain)
|
|
|
|
to_datadir = os.path.join(dirname, "node"+str(to_node), chain)
|
2019-08-09 01:19:22 +02:00
|
|
|
|
|
|
|
dirs = ["blocks", "chainstate", "evodb", "llmq"]
|
|
|
|
for d in dirs:
|
|
|
|
try:
|
|
|
|
src = os.path.join(from_datadir, d)
|
|
|
|
dst = os.path.join(to_datadir, d)
|
|
|
|
shutil.copytree(src, dst)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
2018-04-10 01:11:07 +02:00
|
|
|
# If a cookie file exists in the given datadir, delete it.
|
2021-01-22 15:58:07 +01:00
|
|
|
def delete_cookie_file(datadir, chain):
|
|
|
|
chain = get_chain_folder(datadir, chain)
|
|
|
|
if os.path.isfile(os.path.join(datadir, chain, ".cookie")):
|
2018-04-10 01:11:07 +02:00
|
|
|
logger.debug("Deleting leftover cookie file")
|
2021-01-22 15:58:07 +01:00
|
|
|
os.remove(os.path.join(datadir, chain, ".cookie"))
|
|
|
|
|
|
|
|
"""
|
|
|
|
since devnets can be named we won't always know what the folders name is unless we would pass it through all functions,
|
|
|
|
which shouldn't be needed as if we are to test multiple different devnets we would just override setup_chain and make our own configs files.
|
|
|
|
"""
|
|
|
|
def get_chain_folder(datadir, chain):
|
|
|
|
# if try fails the directory doesn't exist
|
|
|
|
try:
|
|
|
|
for i in range(len(os.listdir(datadir))):
|
|
|
|
if chain in os.listdir(datadir)[i]:
|
|
|
|
chain = os.listdir(datadir)[i]
|
|
|
|
break
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
return chain
|
2018-04-10 01:11:07 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def get_bip9_status(node, key):
|
|
|
|
info = node.getblockchaininfo()
|
|
|
|
return info['bip9_softforks'][key]
|
2014-03-13 22:51:05 +01:00
|
|
|
|
2014-11-13 19:27:13 +01:00
|
|
|
def set_node_times(nodes, t):
|
|
|
|
for node in nodes:
|
2020-04-17 07:52:06 +02:00
|
|
|
node.mocktime = t
|
2014-11-13 19:27:13 +01:00
|
|
|
node.setmocktime(t)
|
|
|
|
|
2017-05-02 20:02:55 +02:00
|
|
|
def disconnect_nodes(from_connection, node_num):
|
|
|
|
for peer_id in [peer['id'] for peer in from_connection.getpeerinfo() if "testnode%d" % node_num in peer['subver']]:
|
2018-05-10 16:31:01 +02:00
|
|
|
try:
|
|
|
|
from_connection.disconnectnode(nodeid=peer_id)
|
|
|
|
except JSONRPCException as e:
|
|
|
|
# If this node is disconnected between calculating the peer id
|
|
|
|
# and issuing the disconnect, don't worry about it.
|
|
|
|
# This avoids a race condition if we're mass-disconnecting peers.
|
|
|
|
if e.error['code'] != -29: # RPC_CLIENT_NODE_NOT_CONNECTED
|
|
|
|
raise
|
2017-05-02 20:02:55 +02:00
|
|
|
|
2018-03-19 17:10:29 +01:00
|
|
|
# wait to disconnect
|
|
|
|
wait_until(lambda: [peer['id'] for peer in from_connection.getpeerinfo() if "testnode%d" % node_num in peer['subver']] == [], timeout=5)
|
2017-05-02 20:02:55 +02:00
|
|
|
|
2014-02-26 22:31:18 +01:00
|
|
|
def connect_nodes(from_connection, node_num):
|
2017-06-29 17:37:19 +02:00
|
|
|
ip_port = "127.0.0.1:" + str(p2p_port(node_num))
|
2014-02-26 22:31:18 +01:00
|
|
|
from_connection.addnode(ip_port, "onetry")
|
2014-06-23 17:41:52 +02:00
|
|
|
# poll until version handshake complete to avoid race conditions
|
|
|
|
# with transaction relaying
|
2018-03-19 17:10:29 +01:00
|
|
|
wait_until(lambda: all(peer['version'] != 0 for peer in from_connection.getpeerinfo()))
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2014-10-24 09:06:37 +02:00
|
|
|
def connect_nodes_bi(nodes, a, b):
|
|
|
|
connect_nodes(nodes[a], b)
|
|
|
|
connect_nodes(nodes[b], a)
|
|
|
|
|
2019-05-06 16:58:38 +02:00
|
|
|
def isolate_node(node, timeout=5):
|
|
|
|
node.setnetworkactive(False)
|
|
|
|
st = time.time()
|
|
|
|
while time.time() < st + timeout:
|
|
|
|
if node.getconnectioncount() == 0:
|
|
|
|
return
|
|
|
|
time.sleep(0.5)
|
|
|
|
raise AssertionError("disconnect_node timed out")
|
|
|
|
|
|
|
|
def reconnect_isolated_node(node, node_num):
|
|
|
|
node.setnetworkactive(True)
|
|
|
|
connect_nodes(node, node_num)
|
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def sync_blocks(rpc_connections, *, wait=1, timeout=60):
|
|
|
|
"""
|
|
|
|
Wait until everybody has the same tip.
|
|
|
|
|
|
|
|
sync_blocks needs to be called with an rpc_connections set that has least
|
|
|
|
one node already synced to the latest, stable tip, otherwise there's a
|
|
|
|
chance it might return before all nodes are stably synced.
|
|
|
|
"""
|
2020-07-12 21:32:38 +02:00
|
|
|
timeout *= Options.timeout_scale
|
2018-03-13 17:45:06 +01:00
|
|
|
|
|
|
|
stop_time = time.time() + timeout
|
|
|
|
while time.time() <= stop_time:
|
2017-06-29 17:37:19 +02:00
|
|
|
best_hash = [x.getbestblockhash() for x in rpc_connections]
|
2018-03-13 17:45:06 +01:00
|
|
|
if best_hash.count(best_hash[0]) == len(rpc_connections):
|
2017-06-29 17:37:19 +02:00
|
|
|
return
|
|
|
|
time.sleep(wait)
|
2018-03-13 17:45:06 +01:00
|
|
|
raise AssertionError("Block sync timed out:{}".format("".join("\n {!r}".format(b) for b in best_hash)))
|
2017-06-29 17:37:19 +02:00
|
|
|
|
2018-01-18 14:26:21 +01:00
|
|
|
def sync_mempools(rpc_connections, *, wait=1, timeout=60, flush_scheduler=True, wait_func=None):
|
2017-06-29 17:37:19 +02:00
|
|
|
"""
|
|
|
|
Wait until everybody has the same transactions in their memory
|
|
|
|
pools
|
|
|
|
"""
|
2020-07-12 21:32:38 +02:00
|
|
|
timeout *= Options.timeout_scale
|
2018-03-13 17:45:06 +01:00
|
|
|
stop_time = time.time() + timeout
|
|
|
|
while time.time() <= stop_time:
|
|
|
|
pool = [set(r.getrawmempool()) for r in rpc_connections]
|
|
|
|
if pool.count(pool[0]) == len(rpc_connections):
|
2018-01-18 14:26:21 +01:00
|
|
|
if flush_scheduler:
|
|
|
|
for r in rpc_connections:
|
|
|
|
r.syncwithvalidationinterfacequeue()
|
2017-06-29 17:37:19 +02:00
|
|
|
return
|
2020-04-08 22:13:54 +02:00
|
|
|
if wait_func is not None:
|
|
|
|
wait_func()
|
2017-06-29 17:37:19 +02:00
|
|
|
time.sleep(wait)
|
2018-03-13 17:45:06 +01:00
|
|
|
raise AssertionError("Mempool sync timed out:{}".format("".join("\n {!r}".format(m) for m in pool)))
|
2017-06-29 17:37:19 +02:00
|
|
|
|
2019-10-09 18:48:12 +02:00
|
|
|
def force_finish_mnsync(node):
|
|
|
|
"""
|
|
|
|
Masternodes won't accept incoming connections while IsSynced is false.
|
|
|
|
Force them to switch to this state to speed things up.
|
|
|
|
"""
|
|
|
|
while True:
|
|
|
|
if node.mnsync("status")['IsSynced']:
|
|
|
|
break
|
|
|
|
node.mnsync("next")
|
2019-08-09 01:19:22 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Transaction/Block functions
|
|
|
|
#############################
|
|
|
|
|
2014-03-17 13:19:54 +01:00
|
|
|
def find_output(node, txid, amount):
|
|
|
|
"""
|
|
|
|
Return index to output of txid with value amount
|
|
|
|
Raises exception if there is none.
|
|
|
|
"""
|
|
|
|
txdata = node.getrawtransaction(txid, 1)
|
|
|
|
for i in range(len(txdata["vout"])):
|
|
|
|
if txdata["vout"][i]["value"] == amount:
|
|
|
|
return i
|
2017-06-29 17:37:19 +02:00
|
|
|
raise RuntimeError("find_output txid %s : %s not found" % (txid, str(amount)))
|
2014-11-19 21:55:40 +01:00
|
|
|
|
|
|
|
def gather_inputs(from_node, amount_needed, confirmations_required=1):
|
2014-03-17 13:19:54 +01:00
|
|
|
"""
|
|
|
|
Return a random set of unspent txouts that are enough to pay amount_needed
|
|
|
|
"""
|
2017-06-29 17:37:19 +02:00
|
|
|
assert(confirmations_required >= 0)
|
2014-11-19 21:55:40 +01:00
|
|
|
utxo = from_node.listunspent(confirmations_required)
|
2014-03-17 13:19:54 +01:00
|
|
|
random.shuffle(utxo)
|
|
|
|
inputs = []
|
|
|
|
total_in = Decimal("0.00000000")
|
|
|
|
while total_in < amount_needed and len(utxo) > 0:
|
|
|
|
t = utxo.pop()
|
|
|
|
total_in += t["amount"]
|
2017-06-29 17:37:19 +02:00
|
|
|
inputs.append({"txid": t["txid"], "vout": t["vout"], "address": t["address"]})
|
2014-03-17 13:19:54 +01:00
|
|
|
if total_in < amount_needed:
|
2017-06-29 17:37:19 +02:00
|
|
|
raise RuntimeError("Insufficient funds: need %d, have %d" % (amount_needed, total_in))
|
2014-03-17 13:19:54 +01:00
|
|
|
return (total_in, inputs)
|
|
|
|
|
|
|
|
def make_change(from_node, amount_in, amount_out, fee):
|
|
|
|
"""
|
|
|
|
Create change output(s), return them
|
|
|
|
"""
|
|
|
|
outputs = {}
|
2017-06-29 17:37:19 +02:00
|
|
|
amount = amount_out + fee
|
2014-03-17 13:19:54 +01:00
|
|
|
change = amount_in - amount
|
2017-06-29 17:37:19 +02:00
|
|
|
if change > amount * 2:
|
2014-03-17 13:19:54 +01:00
|
|
|
# Create an extra change output to break up big inputs
|
2014-09-03 21:07:43 +02:00
|
|
|
change_address = from_node.getnewaddress()
|
|
|
|
# Split change in two, being careful of rounding:
|
2017-06-29 17:37:19 +02:00
|
|
|
outputs[change_address] = Decimal(change / 2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
|
2014-09-03 21:07:43 +02:00
|
|
|
change = amount_in - amount - outputs[change_address]
|
2014-03-17 13:19:54 +01:00
|
|
|
if change > 0:
|
2014-09-03 21:07:43 +02:00
|
|
|
outputs[from_node.getnewaddress()] = change
|
2014-03-17 13:19:54 +01:00
|
|
|
return outputs
|
|
|
|
|
|
|
|
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
|
|
|
|
"""
|
|
|
|
Create a random transaction.
|
|
|
|
Returns (txid, hex-encoded-transaction-data, fee)
|
|
|
|
"""
|
|
|
|
from_node = random.choice(nodes)
|
|
|
|
to_node = random.choice(nodes)
|
2017-06-29 17:37:19 +02:00
|
|
|
fee = min_fee + fee_increment * random.randint(0, fee_variants)
|
2014-03-17 13:19:54 +01:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
(total_in, inputs) = gather_inputs(from_node, amount + fee)
|
2014-03-17 13:19:54 +01:00
|
|
|
outputs = make_change(from_node, total_in, amount, fee)
|
|
|
|
outputs[to_node.getnewaddress()] = float(amount)
|
|
|
|
|
|
|
|
rawtx = from_node.createrawtransaction(inputs, outputs)
|
2018-02-20 03:29:22 +01:00
|
|
|
signresult = from_node.signrawtransactionwithwallet(rawtx)
|
2014-03-17 13:19:54 +01:00
|
|
|
txid = from_node.sendrawtransaction(signresult["hex"], True)
|
|
|
|
|
|
|
|
return (txid, signresult["hex"], fee)
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2016-03-01 15:28:16 +01:00
|
|
|
# Helper to create at least "count" utxos
|
|
|
|
# Pass in a fee that is sufficient for relay and mining new transactions.
|
2015-11-30 15:42:27 +01:00
|
|
|
def create_confirmed_utxos(fee, node, count):
|
2017-06-29 17:37:19 +02:00
|
|
|
to_generate = int(0.5 * count) + 101
|
2017-07-03 09:35:31 +02:00
|
|
|
while to_generate > 0:
|
|
|
|
node.generate(min(25, to_generate))
|
|
|
|
to_generate -= 25
|
2015-11-30 15:42:27 +01:00
|
|
|
utxos = node.listunspent()
|
|
|
|
iterations = count - len(utxos)
|
|
|
|
addr1 = node.getnewaddress()
|
|
|
|
addr2 = node.getnewaddress()
|
|
|
|
if iterations <= 0:
|
|
|
|
return utxos
|
2016-05-06 11:23:48 +02:00
|
|
|
for i in range(iterations):
|
2015-11-30 15:42:27 +01:00
|
|
|
t = utxos.pop()
|
|
|
|
inputs = []
|
2017-06-29 17:37:19 +02:00
|
|
|
inputs.append({"txid": t["txid"], "vout": t["vout"]})
|
2015-11-30 15:42:27 +01:00
|
|
|
outputs = {}
|
|
|
|
send_value = t['amount'] - fee
|
2017-06-29 17:37:19 +02:00
|
|
|
outputs[addr1] = satoshi_round(send_value / 2)
|
|
|
|
outputs[addr2] = satoshi_round(send_value / 2)
|
2015-11-30 15:42:27 +01:00
|
|
|
raw_tx = node.createrawtransaction(inputs, outputs)
|
2018-02-20 03:29:22 +01:00
|
|
|
signed_tx = node.signrawtransactionwithwallet(raw_tx)["hex"]
|
2017-06-29 17:37:19 +02:00
|
|
|
node.sendrawtransaction(signed_tx)
|
2015-11-30 15:42:27 +01:00
|
|
|
|
|
|
|
while (node.getmempoolinfo()['size'] > 0):
|
|
|
|
node.generate(1)
|
|
|
|
|
|
|
|
utxos = node.listunspent()
|
|
|
|
assert(len(utxos) >= count)
|
|
|
|
return utxos
|
|
|
|
|
2016-03-01 15:28:16 +01:00
|
|
|
# Create large OP_RETURN txouts that can be appended to a transaction
|
|
|
|
# to make it large (helper for constructing large transactions).
|
2015-12-24 11:58:41 +01:00
|
|
|
def gen_return_txouts():
|
|
|
|
# Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
|
|
|
|
# So we have big transactions (and therefore can't fit very many into each block)
|
|
|
|
# create one script_pubkey
|
2017-06-29 17:37:19 +02:00
|
|
|
script_pubkey = "6a4d0200" # OP_RETURN OP_PUSH2 512 bytes
|
|
|
|
for i in range(512):
|
2015-12-24 11:58:41 +01:00
|
|
|
script_pubkey = script_pubkey + "01"
|
|
|
|
# concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
|
2019-07-15 14:02:00 +02:00
|
|
|
txouts = []
|
|
|
|
from .messages import CTxOut
|
|
|
|
txout = CTxOut()
|
|
|
|
txout.nValue = 0
|
|
|
|
txout.scriptPubKey = hex_str_to_bytes(script_pubkey)
|
2016-05-06 11:23:48 +02:00
|
|
|
for k in range(128):
|
2019-07-15 14:02:00 +02:00
|
|
|
txouts.append(txout)
|
2015-12-24 11:58:41 +01:00
|
|
|
return txouts
|
|
|
|
|
2016-03-01 15:28:16 +01:00
|
|
|
# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
|
|
|
|
# transaction to make it large. See gen_return_txouts() above.
|
2016-12-06 12:05:31 +01:00
|
|
|
def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
|
2015-11-30 15:42:27 +01:00
|
|
|
addr = node.getnewaddress()
|
|
|
|
txids = []
|
2019-07-15 14:02:00 +02:00
|
|
|
from .messages import CTransaction
|
2016-12-06 12:05:31 +01:00
|
|
|
for _ in range(num):
|
2015-11-30 15:42:27 +01:00
|
|
|
t = utxos.pop()
|
2017-06-29 17:37:19 +02:00
|
|
|
inputs = [{"txid": t["txid"], "vout": t["vout"]}]
|
2015-11-30 15:42:27 +01:00
|
|
|
outputs = {}
|
2016-12-02 20:17:07 +01:00
|
|
|
change = t['amount'] - fee
|
|
|
|
outputs[addr] = satoshi_round(change)
|
2015-11-30 15:42:27 +01:00
|
|
|
rawtx = node.createrawtransaction(inputs, outputs)
|
2019-07-15 14:02:00 +02:00
|
|
|
tx = CTransaction()
|
|
|
|
tx.deserialize(BytesIO(hex_str_to_bytes(rawtx)))
|
|
|
|
for txout in txouts:
|
|
|
|
tx.vout.append(txout)
|
|
|
|
newtx = tx.serialize().hex()
|
2018-02-20 03:29:22 +01:00
|
|
|
signresult = node.signrawtransactionwithwallet(newtx, None, "NONE")
|
2015-11-30 15:42:27 +01:00
|
|
|
txid = node.sendrawtransaction(signresult["hex"], True)
|
|
|
|
txids.append(txid)
|
2015-12-04 13:24:12 +01:00
|
|
|
return txids
|
2016-04-07 20:33:08 +02:00
|
|
|
|
2016-12-06 12:05:31 +01:00
|
|
|
def mine_large_block(node, utxos=None):
|
2016-12-02 20:17:07 +01:00
|
|
|
# generate a 66k transaction,
|
|
|
|
# and 14 of them is close to the 1MB block limit
|
2016-12-06 12:05:31 +01:00
|
|
|
num = 14
|
2016-12-02 20:17:07 +01:00
|
|
|
txouts = gen_return_txouts()
|
2016-12-06 12:05:31 +01:00
|
|
|
utxos = utxos if utxos is not None else []
|
|
|
|
if len(utxos) < num:
|
|
|
|
utxos.clear()
|
|
|
|
utxos.extend(node.listunspent())
|
2016-12-02 20:17:07 +01:00
|
|
|
fee = 100 * node.getnetworkinfo()["relayfee"]
|
2016-12-06 12:05:31 +01:00
|
|
|
create_lots_of_big_transactions(node, txouts, utxos, num, fee=fee)
|
2016-12-02 20:17:07 +01:00
|
|
|
node.generate(1)
|
2018-05-09 10:12:45 +02:00
|
|
|
|
|
|
|
def find_vout_for_address(node, txid, addr):
|
|
|
|
"""
|
|
|
|
Locate the vout index of the given transaction sending to the
|
|
|
|
given address. Raises runtime error exception if not found.
|
|
|
|
"""
|
|
|
|
tx = node.getrawtransaction(txid, True)
|
|
|
|
for i in range(len(tx["vout"])):
|
|
|
|
if any([addr == a for a in tx["vout"][i]["scriptPubKey"]["addresses"]]):
|
|
|
|
return i
|
|
|
|
raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr))
|