2016-05-06 11:23:48 +02:00
|
|
|
#!/usr/bin/env python3
|
2023-08-16 19:27:31 +02:00
|
|
|
# Copyright (c) 2014-2020 The Bitcoin Core developers
|
2023-12-31 01:00:00 +01:00
|
|
|
# Copyright (c) 2014-2023 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
|
2014-09-03 21:07:43 +02:00
|
|
|
from decimal import Decimal, ROUND_DOWN
|
2019-09-22 16:14:45 +02:00
|
|
|
from subprocess import CalledProcessError
|
Merge #18836: wallet: upgradewallet fixes and additional tests
5f9c0b6360215636cfa62a70d3a70f1feb3977ab wallet: Remove -upgradewallet from dummywallet (MarcoFalke)
a314271f08215feba53ead27096ac7fda34acb3c test: Remove unused wallet.dat (MarcoFalke)
bf7635963c03203e7189ddaa56c6b086a0108cbf tests: Test specific upgradewallet scenarios and that upgrades work (Andrew Chow)
4b418a9decc3e855ee4b0bbf9e61121c8e9904e5 test: Add test_framework/bdb.py module for inspecting bdb files (Andrew Chow)
092fc434854f881330771a93a1280ac67b1d3549 tests: Add a sha256sum_file function to util (Andrew Chow)
0bd995aa19be65b0dd23df1df571c71428c2bc32 wallet: upgrade the CHDChain version number when upgrading to split hd (Andrew Chow)
8e32e1c41c995e832e643f605d35a7aa112837e6 wallet: remove nWalletMaxVersion (Andrew Chow)
bd7398cc6258c258e9f4411c50630ec4a552341b wallet: have ScriptPubKeyMan::Upgrade check against the new version (Andrew Chow)
5f720544f34dedf75b063b962845fa8eca604514 wallet: Add GetClosestWalletFeature function (Andrew Chow)
842ae3842df489f1b8d68e67a234788966218184 wallet: Add utility method for CanSupportFeature (Andrew Chow)
Pull request description:
This PR cleans up the wallet upgrade mechanism a bit, fixes some probably bugs, and adds more test cases.
The `nWalletMaxVersion` member variable has been removed as it made `CanSupportFeature` unintuitive and was causing a couple of bugs. The reason this was introduced originally was to allow a wallet upgrade to only occur when the new feature is first used. While this makes sense for the old `-upgradewallet` option, for an RPC, this does not quite make sense. It's more intuitive for an upgrade to occur if possible if the `upgradewallet` RPC is used as that's an explicit request to upgrade a particular wallet to a newer version. `nWalletMaxVersion` was only relevant for upgrades to `FEATURE_WALLETCRYPT` and `FEATURE_COMPRPUBKEY` both of which are incredibly old features. So for such wallets, the behavior of `upgradewallet` will be that the feature is enabled immediately without the wallet needing to be encrypted at that time (note that `FEATURE_WALLETCRYPT` indicates support for encryption, not that the wallet is encrypted) or for a new key to be generated.
`CanSupportFeature` would previously indicate whether we could upgrade to `nWalletMaxVersion` not just whether the current wallet version supported a feature. While this property was being used to determine whether we should upgrade to HD and HD chain split, it was also causing a few bugs. Determining whether we should upgrade to HD or HD chain split is resolved by passing into `ScriptPubKeyMan::Upgrade` the version we are upgrading to and checking against that. By removing `nWalletMaxVersion` we also fix a bug where you could upgrade to HD chain split without the pre-split keypool.
`nWalletMaxVersion` was also the version that was being reported by `getwalletinfo` which meant that the version reported was not always consistent across restarts as it depended on whether `upgradewallet` was used. Additionally to make the wallet versions consistent with actually supported versions, instead of just setting the wallet version to whatever is given to `upgradewallet`, we normalize the version number to the closest supported version number. For example, if given 150000, we would store and report 139900.
Another bug where CHDChain was not being upgraded to the version supporting HD chain split is also fixed by this PR.
Lastly several more tests have been added. Some refactoring to the test was made to make these tests easier. These tests check specific upgrading scenarios, such as from non-HD (version 60000) to HD to pre-split keypool. Although not specifically related to `upgradewallet`, `UpgradeKeyMetadata` is now being tested too.
Part of the new tests is checking that the wallet files are identical before and after failed upgrades. To facilitate this, a utility function `sha256sum_file` has been added. Another part of the tests is to examine the wallet file itself to ensure that the records in the wallet.dat file have been correctly modified. So a new `bdb.py` module has been added to deserialize the BDB db of the wallet.dat file. This format isn't explicitly documented anywhere, but the code and comments in BDB's source code in file `dbinc/db_page.h` describe it. This module just dumps all of the fields into a dict.
ACKs for top commit:
MarcoFalke:
approach ACK 5f9c0b6360
laanwj:
Code review ACK 5f9c0b6360215636cfa62a70d3a70f1feb3977ab
jonatack:
ACK 5f9c0b6360215636cfa62a70d3a70f1feb3977ab, approach seems fine, code review, only skimmed the test changes but they look well done, rebased on current master, debug built and verified the `wallet_upgradewallet.py` test runs green both before and after running `test/get_previous_releases.py -b v0.19.1 v0.18.1 v0.17.2 v0.16.3 v0.15.2`
Tree-SHA512: 7c4ebf420850d596a586cb6dd7f2ef39c6477847d12d105fcd362abb07f2a8aa4f7afc5bfd36cbc8b8c72fcdd1de8d2d3f16ad8e8ba736b6f4f31f133fe5feba
2020-04-29 20:48:43 +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
|
2019-08-13 21:48:24 +02:00
|
|
|
import shutil
|
2014-04-07 17:29:36 +02:00
|
|
|
import re
|
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
|
2021-06-07 07:05:05 +02:00
|
|
|
from typing import Callable, Optional
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2017-03-09 21:16:20 +01:00
|
|
|
logger = logging.getLogger("TestFramework.utils")
|
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Assert functions
|
|
|
|
##################
|
2016-05-09 17:01:55 +02:00
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2019-09-20 10:42:24 +02:00
|
|
|
def assert_approx(v, vexp, vspan=0.00001):
|
|
|
|
"""Assert that `v` is within `vspan` of `vexp`"""
|
|
|
|
if v < vexp - vspan:
|
|
|
|
raise AssertionError("%s < [%s..%s]" % (str(v), str(vexp - vspan), str(vexp + vspan)))
|
|
|
|
if v > vexp + vspan:
|
|
|
|
raise AssertionError("%s > [%s..%s]" % (str(v), str(vexp - vspan), str(vexp + vspan)))
|
|
|
|
|
2020-06-16 22:28:04 +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
|
|
|
|
2020-06-16 22:28:04 +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
|
|
|
|
2020-06-16 22:28:04 +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)))
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def assert_greater_than_or_equal(thing1, thing2):
|
|
|
|
if thing1 < thing2:
|
|
|
|
raise AssertionError("%s < %s" % (str(thing1), str(thing2)))
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def assert_raises(exc, fun, *args, **kwds):
|
|
|
|
assert_raises_message(exc, None, fun, *args, **kwds)
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
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']:
|
2021-12-12 14:27:02 +01:00
|
|
|
raise AssertionError(
|
|
|
|
"Expected substring not found in error message:\nsubstring: '{}'\nerror message: '{}'.".format(
|
|
|
|
message, e.error['message']))
|
2017-06-29 17:37:19 +02:00
|
|
|
except Exception as e:
|
|
|
|
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
|
|
|
|
else:
|
|
|
|
raise AssertionError("No exception raised")
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2021-06-07 07:05:05 +02:00
|
|
|
def assert_raises_process_error(returncode: int, output: str, fun: Callable, *args, **kwds):
|
2017-09-06 17:35:57 +02:00
|
|
|
"""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:
|
2021-06-07 07:05:05 +02:00
|
|
|
returncode: the process return code.
|
|
|
|
output: [a substring of] the process output.
|
|
|
|
fun: the function to call. This should execute a process.
|
2017-09-06 17:35:57 +02:00
|
|
|
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")
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2021-06-07 07:05:05 +02:00
|
|
|
def assert_raises_rpc_error(code: Optional[int], message: Optional[str], fun: Callable, *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:
|
2021-06-07 07:05:05 +02:00
|
|
|
code: 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: [a substring of] the error string returned by the RPC call.
|
|
|
|
Set to None if checking the error string is not required.
|
|
|
|
fun: the function to call. This should be the name of an RPC.
|
2017-06-29 17:37:19 +02:00
|
|
|
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"
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-07-12 16:29:02 +02:00
|
|
|
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']):
|
2021-12-12 14:27:02 +01:00
|
|
|
raise AssertionError(
|
|
|
|
"Expected substring not found in error message:\nsubstring: '{}'\nerror message: '{}'.".format(
|
|
|
|
message, 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
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
def assert_is_hex_string(string):
|
|
|
|
try:
|
|
|
|
int(string, 16)
|
|
|
|
except Exception as e:
|
2020-06-16 22:28:04 +02:00
|
|
|
raise AssertionError("Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
|
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
|
|
|
|
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:
|
2020-06-16 22:28:04 +02:00
|
|
|
raise AssertionError("String of length %d expected; got %d" % (length, len(string)))
|
2017-06-29 17:37:19 +02:00
|
|
|
elif not re.match('[abcdef0-9]+$', string):
|
2020-06-16 22:28:04 +02:00
|
|
|
raise AssertionError("String %r contains invalid characters for a hash." % string)
|
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
|
|
|
|
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
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Utility functions
|
|
|
|
###################
|
2015-12-05 18:02:02 +01:00
|
|
|
|
2020-06-16 22:28:04 +02: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
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2019-12-12 02:10:59 +01:00
|
|
|
def EncodeDecimal(o):
|
|
|
|
if isinstance(o, Decimal):
|
|
|
|
return str(o)
|
|
|
|
raise TypeError(repr(o) + " is not JSON serializable")
|
|
|
|
|
2020-06-16 22:28:04 +02: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-09-29 19:44:10 +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
|
|
|
|
2020-06-16 22:28:04 +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
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2020-09-03 05:47:08 +02:00
|
|
|
def wait_until_helper(predicate, *, attempts=float('inf'), timeout=float('inf'), sleep=0.5, timeout_factor=1.0, lock=None, do_assert=True, allow_exception=False):
|
2020-08-27 08:21:53 +02:00
|
|
|
"""Sleep until the predicate resolves to be True.
|
|
|
|
|
|
|
|
Warning: Note that this method is not recommended to be used in tests as it is
|
2020-09-03 05:47:08 +02:00
|
|
|
not aware of the context of the test framework. Using the `wait_until()` members
|
|
|
|
from `BitcoinTestFramework` or `P2PInterface` class ensures the timeout is
|
|
|
|
properly scaled. Furthermore, `wait_until()` from `P2PInterface` class in
|
|
|
|
`p2p.py` has a preset lock.
|
2020-08-27 08:21:53 +02:00
|
|
|
"""
|
2017-08-23 23:11:33 +02:00
|
|
|
if attempts == float('inf') and timeout == float('inf'):
|
|
|
|
timeout = 60
|
2020-05-19 02:00:24 +02:00
|
|
|
timeout = timeout * timeout_factor
|
2017-08-23 23:11:33 +02:00
|
|
|
attempt = 0
|
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
|
2019-05-16 18:44:54 +02:00
|
|
|
predicate_source = "''''\n" + inspect.getsource(predicate) + "'''"
|
2020-01-11 02:31:25 +01:00
|
|
|
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
|
|
|
|
2021-10-28 14:42:13 +02:00
|
|
|
|
Merge #18836: wallet: upgradewallet fixes and additional tests
5f9c0b6360215636cfa62a70d3a70f1feb3977ab wallet: Remove -upgradewallet from dummywallet (MarcoFalke)
a314271f08215feba53ead27096ac7fda34acb3c test: Remove unused wallet.dat (MarcoFalke)
bf7635963c03203e7189ddaa56c6b086a0108cbf tests: Test specific upgradewallet scenarios and that upgrades work (Andrew Chow)
4b418a9decc3e855ee4b0bbf9e61121c8e9904e5 test: Add test_framework/bdb.py module for inspecting bdb files (Andrew Chow)
092fc434854f881330771a93a1280ac67b1d3549 tests: Add a sha256sum_file function to util (Andrew Chow)
0bd995aa19be65b0dd23df1df571c71428c2bc32 wallet: upgrade the CHDChain version number when upgrading to split hd (Andrew Chow)
8e32e1c41c995e832e643f605d35a7aa112837e6 wallet: remove nWalletMaxVersion (Andrew Chow)
bd7398cc6258c258e9f4411c50630ec4a552341b wallet: have ScriptPubKeyMan::Upgrade check against the new version (Andrew Chow)
5f720544f34dedf75b063b962845fa8eca604514 wallet: Add GetClosestWalletFeature function (Andrew Chow)
842ae3842df489f1b8d68e67a234788966218184 wallet: Add utility method for CanSupportFeature (Andrew Chow)
Pull request description:
This PR cleans up the wallet upgrade mechanism a bit, fixes some probably bugs, and adds more test cases.
The `nWalletMaxVersion` member variable has been removed as it made `CanSupportFeature` unintuitive and was causing a couple of bugs. The reason this was introduced originally was to allow a wallet upgrade to only occur when the new feature is first used. While this makes sense for the old `-upgradewallet` option, for an RPC, this does not quite make sense. It's more intuitive for an upgrade to occur if possible if the `upgradewallet` RPC is used as that's an explicit request to upgrade a particular wallet to a newer version. `nWalletMaxVersion` was only relevant for upgrades to `FEATURE_WALLETCRYPT` and `FEATURE_COMPRPUBKEY` both of which are incredibly old features. So for such wallets, the behavior of `upgradewallet` will be that the feature is enabled immediately without the wallet needing to be encrypted at that time (note that `FEATURE_WALLETCRYPT` indicates support for encryption, not that the wallet is encrypted) or for a new key to be generated.
`CanSupportFeature` would previously indicate whether we could upgrade to `nWalletMaxVersion` not just whether the current wallet version supported a feature. While this property was being used to determine whether we should upgrade to HD and HD chain split, it was also causing a few bugs. Determining whether we should upgrade to HD or HD chain split is resolved by passing into `ScriptPubKeyMan::Upgrade` the version we are upgrading to and checking against that. By removing `nWalletMaxVersion` we also fix a bug where you could upgrade to HD chain split without the pre-split keypool.
`nWalletMaxVersion` was also the version that was being reported by `getwalletinfo` which meant that the version reported was not always consistent across restarts as it depended on whether `upgradewallet` was used. Additionally to make the wallet versions consistent with actually supported versions, instead of just setting the wallet version to whatever is given to `upgradewallet`, we normalize the version number to the closest supported version number. For example, if given 150000, we would store and report 139900.
Another bug where CHDChain was not being upgraded to the version supporting HD chain split is also fixed by this PR.
Lastly several more tests have been added. Some refactoring to the test was made to make these tests easier. These tests check specific upgrading scenarios, such as from non-HD (version 60000) to HD to pre-split keypool. Although not specifically related to `upgradewallet`, `UpgradeKeyMetadata` is now being tested too.
Part of the new tests is checking that the wallet files are identical before and after failed upgrades. To facilitate this, a utility function `sha256sum_file` has been added. Another part of the tests is to examine the wallet file itself to ensure that the records in the wallet.dat file have been correctly modified. So a new `bdb.py` module has been added to deserialize the BDB db of the wallet.dat file. This format isn't explicitly documented anywhere, but the code and comments in BDB's source code in file `dbinc/db_page.h` describe it. This module just dumps all of the fields into a dict.
ACKs for top commit:
MarcoFalke:
approach ACK 5f9c0b6360
laanwj:
Code review ACK 5f9c0b6360215636cfa62a70d3a70f1feb3977ab
jonatack:
ACK 5f9c0b6360215636cfa62a70d3a70f1feb3977ab, approach seems fine, code review, only skimmed the test changes but they look well done, rebased on current master, debug built and verified the `wallet_upgradewallet.py` test runs green both before and after running `test/get_previous_releases.py -b v0.19.1 v0.18.1 v0.17.2 v0.16.3 v0.15.2`
Tree-SHA512: 7c4ebf420850d596a586cb6dd7f2ef39c6477847d12d105fcd362abb07f2a8aa4f7afc5bfd36cbc8b8c72fcdd1de8d2d3f16ad8e8ba736b6f4f31f133fe5feba
2020-04-29 20:48:43 +02:00
|
|
|
def sha256sum_file(filename):
|
|
|
|
h = hashlib.sha256()
|
|
|
|
with open(filename, 'rb') as f:
|
|
|
|
d = f.read(4096)
|
|
|
|
while len(d) > 0:
|
|
|
|
h.update(d)
|
|
|
|
d = f.read(4096)
|
|
|
|
return h.digest()
|
2020-06-16 22:28:04 +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
|
2022-04-16 16:46:04 +02:00
|
|
|
MAX_NODES = 20
|
2017-06-29 17:37:19 +02:00
|
|
|
# Don't assign rpc or p2p ports lower than this
|
2019-09-22 16:14:45 +02:00
|
|
|
PORT_MIN = int(os.getenv('TEST_RUNNER_PORT_MIN', default=11000))
|
2017-06-29 17:37:19 +02:00
|
|
|
# The number of ports to "reserve" for p2p and rpc, each
|
|
|
|
PORT_RANGE = 5000
|
|
|
|
|
2019-09-22 16:14:45 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
class PortSeed:
|
|
|
|
# Must be initialized with a unique integer for each process
|
|
|
|
n = None
|
|
|
|
|
2021-07-29 09:52:10 +02:00
|
|
|
|
|
|
|
def get_rpc_proxy(url: str, node_number: int, *, timeout: int=None, coveragedir: str=None) -> coverage.AuthServiceProxyWrapper:
|
2015-10-11 07:41:19 +02:00
|
|
|
"""
|
|
|
|
Args:
|
2021-07-29 09:52:10 +02:00
|
|
|
url: URL of the RPC server to call
|
|
|
|
node_number: the node number (or id) that this calls to
|
2015-10-11 07:41:19 +02:00
|
|
|
|
|
|
|
Kwargs:
|
2021-07-29 09:52:10 +02:00
|
|
|
timeout: HTTP timeout in seconds
|
|
|
|
coveragedir: Directory
|
2015-10-11 07:41:19 +02:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
AuthServiceProxy. convenience object for making RPC calls.
|
|
|
|
|
|
|
|
"""
|
|
|
|
proxy_kwargs = {}
|
|
|
|
if timeout is not None:
|
2020-05-03 14:58:48 +02:00
|
|
|
proxy_kwargs['timeout'] = int(timeout)
|
2015-10-11 07:41:19 +02:00
|
|
|
|
|
|
|
proxy = AuthServiceProxy(url, **proxy_kwargs)
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
coverage_logfile = coverage.get_filename(coveragedir, node_number) if coveragedir else None
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2021-07-29 09:52:10 +02:00
|
|
|
return coverage.AuthServiceProxyWrapper(proxy, url, coverage_logfile)
|
2015-10-11 07:41:19 +02:00
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2014-03-14 17:19:52 +01:00
|
|
|
def p2p_port(n):
|
2021-08-27 21:03:02 +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
|
|
|
|
2020-06-16 22:28:04 +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
|
|
|
|
2020-06-16 22:28:04 +02: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
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2017-06-29 17:37:19 +02:00
|
|
|
# Node functions
|
|
|
|
################
|
2014-02-26 22:31:18 +01:00
|
|
|
|
2020-06-16 22:28:04 +02: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-21 16:48:24 +01:00
|
|
|
write_config(os.path.join(datadir, "dash.conf"), n=n, chain=chain)
|
|
|
|
os.makedirs(os.path.join(datadir, 'stderr'), exist_ok=True)
|
|
|
|
os.makedirs(os.path.join(datadir, 'stdout'), exist_ok=True)
|
|
|
|
return datadir
|
|
|
|
|
|
|
|
|
|
|
|
def write_config(config_path, *, n, chain, extra_config=""):
|
|
|
|
# Translate chain subdirectory name to config name
|
2021-01-22 15:58:07 +01:00
|
|
|
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'
|
2021-01-21 16:48:24 +01:00
|
|
|
with open(config_path, 'w', encoding='utf8') as f:
|
|
|
|
if chain_name_conf_arg:
|
|
|
|
f.write("{}={}\n".format(chain_name_conf_arg, chain_name_conf_arg_value))
|
|
|
|
if chain_name_conf_section:
|
|
|
|
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")
|
2019-10-02 19:42:47 +02:00
|
|
|
f.write("fallbackfee=0.00001\n")
|
2020-12-11 03:08:07 +01:00
|
|
|
f.write("server=1\n")
|
|
|
|
f.write("keypool=1\n")
|
|
|
|
f.write("discover=0\n")
|
2024-03-23 16:31:06 +01:00
|
|
|
f.write("dnsseed=0\n")
|
2021-02-21 11:01:20 +01:00
|
|
|
f.write("fixedseeds=0\n")
|
2015-12-02 18:12:23 +01:00
|
|
|
f.write("listenonion=0\n")
|
2024-03-25 12:05:21 +01:00
|
|
|
# Increase peertimeout to avoid disconnects while using mocktime.
|
2024-03-25 16:54:04 +01:00
|
|
|
# peertimeout is measured in mock time, so setting it large enough to
|
|
|
|
# cover any duration in mock time is sufficient. It can be overridden
|
|
|
|
# in tests.
|
|
|
|
f.write("peertimeout=999999999\n")
|
2018-05-09 20:43:09 +02:00
|
|
|
f.write("printtoconsole=0\n")
|
2019-08-19 11:22:18 +02:00
|
|
|
f.write("upnp=0\n")
|
2022-02-26 13:19:13 +01:00
|
|
|
f.write("natpmp=0\n")
|
2019-10-31 19:57:42 +01:00
|
|
|
f.write("shrinkdebugfile=0\n")
|
2021-04-08 02:55:09 +02:00
|
|
|
# To improve SQLite wallet performance so that the tests don't timeout, use -unsafesqlitesync
|
|
|
|
f.write("unsafesqlitesync=1\n")
|
2021-01-21 16:48:24 +01:00
|
|
|
f.write(extra_config)
|
2014-03-13 22:51:05 +01:00
|
|
|
|
2020-04-29 17:08:32 +02: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
|
|
|
|
2020-06-16 22:28:04 +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")
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
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)
|
2019-04-09 16:46:36 +02:00
|
|
|
try:
|
2021-01-22 15:58:07 +01:00
|
|
|
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]
|
2019-04-09 16:46:36 +02:00
|
|
|
except OSError:
|
|
|
|
pass
|
2017-06-21 14:26:10 +02:00
|
|
|
if user is None or password is None:
|
|
|
|
raise ValueError("No RPC credentials")
|
|
|
|
return user, password
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
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"))
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2021-01-22 15:58:07 +01:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
2019-08-15 22:02:02 +02:00
|
|
|
def get_bip9_details(node, key):
|
|
|
|
"""Return extra info about bip9 softfork"""
|
|
|
|
return node.getblockchaininfo()['softforks'][key]['bip9']
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2019-08-15 22:02:02 +02:00
|
|
|
def softfork_active(node, key):
|
|
|
|
"""Return whether a softfork is active."""
|
|
|
|
return node.getblockchaininfo()['softforks'][key]['active']
|
2014-03-13 22:51:05 +01:00
|
|
|
|
2020-06-16 22:28:04 +02: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)
|
|
|
|
|
2021-10-28 14:42:13 +02:00
|
|
|
def check_node_connections(*, node, num_in, num_out):
|
|
|
|
info = node.getnetworkinfo()
|
|
|
|
assert_equal(info["connections_in"], num_in)
|
|
|
|
assert_equal(info["connections_out"], num_out)
|
|
|
|
|
2020-06-16 22:28:04 +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
|
|
|
|
#############################
|
|
|
|
|
2020-04-21 16:57:52 +02:00
|
|
|
|
2019-02-19 16:30:36 +01:00
|
|
|
def find_output(node, txid, amount, *, blockhash=None):
|
2014-03-17 13:19:54 +01:00
|
|
|
"""
|
|
|
|
Return index to output of txid with value amount
|
|
|
|
Raises exception if there is none.
|
|
|
|
"""
|
2019-02-19 16:30:36 +01:00
|
|
|
txdata = node.getrawtransaction(txid, 1, blockhash)
|
2014-03-17 13:19:54 +01:00
|
|
|
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
|
|
|
|
2020-06-16 22:28:04 +02: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.
|
2024-09-26 21:17:04 +02:00
|
|
|
def create_confirmed_utxos(test_framework, fee, node, count, **kwargs):
|
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:
|
2024-09-26 21:17:04 +02:00
|
|
|
test_framework.generate(node, min(25, to_generate), **kwargs)
|
2017-07-03 09:35:31 +02:00
|
|
|
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
|
2020-08-11 02:50:34 +02:00
|
|
|
for _ 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):
|
2024-09-26 21:17:04 +02:00
|
|
|
test_framework.generate(node, 1, **kwargs)
|
2015-11-30 15:42:27 +01:00
|
|
|
|
|
|
|
utxos = node.listunspent()
|
2021-08-27 21:03:02 +02:00
|
|
|
assert len(utxos) >= count
|
2015-11-30 15:42:27 +01:00
|
|
|
return utxos
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2021-06-13 18:27:27 +02:00
|
|
|
def chain_transaction(node, parent_txids, vouts, value, fee, num_outputs):
|
|
|
|
"""Build and send a transaction that spends the given inputs (specified
|
|
|
|
by lists of parent_txid:vout each), with the desired total value and fee,
|
|
|
|
equally divided up to the desired number of outputs.
|
|
|
|
|
|
|
|
Returns a tuple with the txid and the amount sent per output.
|
|
|
|
"""
|
|
|
|
send_value = satoshi_round((value - fee)/num_outputs)
|
|
|
|
inputs = []
|
|
|
|
for (txid, vout) in zip(parent_txids, vouts):
|
|
|
|
inputs.append({'txid' : txid, 'vout' : vout})
|
|
|
|
outputs = {}
|
|
|
|
for _ in range(num_outputs):
|
|
|
|
outputs[node.getnewaddress()] = send_value
|
|
|
|
rawtx = node.createrawtransaction(inputs, outputs)
|
|
|
|
signedtx = node.signrawtransactionwithwallet(rawtx)
|
|
|
|
txid = node.sendrawtransaction(signedtx['hex'])
|
|
|
|
fulltx = node.getrawtransaction(txid, 1)
|
|
|
|
assert len(fulltx['vout']) == num_outputs # make sure we didn't generate a change output
|
|
|
|
return (txid, send_value)
|
|
|
|
|
|
|
|
|
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
|
2020-08-11 02:50:34 +02:00
|
|
|
for _ 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
|
2021-07-31 21:23:16 +02:00
|
|
|
txout.scriptPubKey = bytes.fromhex(script_pubkey)
|
2020-08-11 02:50:34 +02:00
|
|
|
for _ in range(128):
|
2019-07-15 14:02:00 +02:00
|
|
|
txouts.append(txout)
|
2015-12-24 11:58:41 +01:00
|
|
|
return txouts
|
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
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 = []
|
2021-06-24 12:47:04 +02:00
|
|
|
from .messages import tx_from_hex
|
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)
|
2021-06-24 12:47:04 +02:00
|
|
|
tx = tx_from_hex(rawtx)
|
2019-07-15 14:02:00 +02:00
|
|
|
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")
|
2021-12-12 07:27:44 +01:00
|
|
|
txid = node.sendrawtransaction(signresult["hex"], 0)
|
2015-11-30 15:42:27 +01:00
|
|
|
txids.append(txid)
|
2015-12-04 13:24:12 +01:00
|
|
|
return txids
|
2016-04-07 20:33:08 +02:00
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2024-09-26 21:13:22 +02:00
|
|
|
def mine_large_block(test_framework, 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)
|
2024-09-26 21:13:22 +02:00
|
|
|
test_framework.generate(node, 1)
|
2018-05-09 10:12:45 +02:00
|
|
|
|
2020-06-16 22:28:04 +02:00
|
|
|
|
2024-09-26 21:13:22 +02:00
|
|
|
def generate_to_height(test_framework, node, target_height):
|
2021-07-26 00:26:55 +02:00
|
|
|
"""Generates blocks until a given target block height has been reached.
|
|
|
|
To prevent timeouts, only up to 200 blocks are generated per RPC call.
|
|
|
|
Can be used to activate certain soft-forks (e.g. CSV, CLTV)."""
|
|
|
|
current_height = node.getblockcount()
|
|
|
|
while current_height < target_height:
|
|
|
|
nblocks = min(200, target_height - current_height)
|
2024-09-26 21:13:22 +02:00
|
|
|
current_height += len(test_framework.generate(node, nblocks))
|
2021-07-26 00:26:55 +02:00
|
|
|
assert_equal(node.getblockcount(), target_height)
|
|
|
|
|
|
|
|
|
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"])):
|
2024-06-23 17:51:21 +02:00
|
|
|
if addr == tx["vout"][i]["scriptPubKey"]["address"]:
|
2018-05-09 10:12:45 +02:00
|
|
|
return i
|
|
|
|
raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr))
|