Skip to content

Commit

Permalink
Update test/functional
Browse files Browse the repository at this point in the history
  • Loading branch information
wu-emma committed Mar 19, 2024
1 parent 4000bbe commit 5272d98
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 35 deletions.
6 changes: 4 additions & 2 deletions contrib/linearize/linearize-data.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import re
import os
import os.path
import sha3
import sys
import hashlib
import datetime
Expand All @@ -20,8 +21,9 @@
settings = {}

def calc_hash_str(blk_hdr):
blk_hdr_hash = hashlib.sha256(hashlib.sha256(blk_hdr).digest()).digest()
return blk_hdr_hash[::-1].hex()
blk_hdr_hash = sha3.keccak_256()
blk_hdr_hash.update(blk_hdr)
return blk_hdr_hash.digest()[::-1].hex()

def get_blk_dt(blk_hdr):
members = struct.unpack("<I", blk_hdr[68:68+4])
Expand Down
7 changes: 5 additions & 2 deletions test/functional/feature_addrman.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import os
import re
import sha3
import struct

from test_framework.messages import ser_uint256, hash256
Expand Down Expand Up @@ -38,7 +39,9 @@ def serialize_addrman(
r += struct.pack("<i", ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30))
for _ in range(ADDRMAN_NEW_BUCKET_COUNT):
r += struct.pack("<i", 0)
checksum = hash256(r)
checksum = sha3.keccak_256()
checksum.update(r)
checksum = checksum.digest()
r += mock_checksum or checksum
return r

Expand Down Expand Up @@ -95,7 +98,7 @@ def run_test(self):
with open(peers_dat, "wb") as f:
f.write(serialize_addrman()[:-1])
self.nodes[0].assert_start_raises_init_error(
expected_msg=init_error("CAutoFile::read: end of file.*"),
expected_msg=init_error("AutoFile::read: end of file.*"),
match=ErrorMatch.FULL_REGEX,
)

Expand Down
10 changes: 8 additions & 2 deletions test/functional/feature_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,13 @@ def run_test(self):
self.move_tip(39)
b40 = self.next_block(40, spend=out[12])
sigops = get_legacy_sigopcount_block(b40)
numTxes = (MAX_BLOCK_SIGOPS - sigops) // b39_sigops_per_output
# BGL max block weight is ten times smaller than Bitcoin, and even that consensus defines the same
# maximum number of SIGOPS in the block, due to signatures and transactions overhead, measured
# empirically using bisection, real maximum number of numTxes in sigops test for BGL is ~9 times
# less than the Bitcoin. The exact maximum measured is 371 numTxes for the maximum value b39
# block size 399784 bytes.
BGL_SIGOPS_COEFFICIENT = 9
numTxes = int(MAX_BLOCK_SIGOPS - sigops) // (b39_sigops_per_output * BGL_SIGOPS_COEFFICIENT)
assert_equal(numTxes <= b39_outputs, True)

lastOutpoint = COutPoint(b40.vtx[1].sha256, 0)
Expand Down Expand Up @@ -809,7 +815,7 @@ def run_test(self):
self.log.info("Reject a block with a transaction with outputs > inputs")
self.move_tip(57)
b59 = self.next_block(59)
tx = self.create_and_sign_transaction(out[17], 51 * COIN)
tx = self.create_and_sign_transaction(out[17], 201 * COIN)
b59 = self.update_block(59, [tx])
self.send_blocks([b59], success=False, reject_reason='bad-txns-in-belowout', reconnect=True)

Expand Down
12 changes: 6 additions & 6 deletions test/functional/feature_config_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_config_file_parser(self):
self.log.info('Test config file parser')
self.stop_node(0)

# Check that startup fails if conf= is set in bitcoin.conf or in an included conf file
# Check that startup fails if conf= is set in BGL.conf or in an included conf file
bad_conf_file_path = self.nodes[0].datadir_path / "BGL_bad.conf"
util.write_config(bad_conf_file_path, n=0, chain='', extra_config=f'conf=some.conf\n')
conf_in_config_file_err = 'Error: Error reading configuration file: conf cannot be set in the configuration file; use includeconf= if you want to include additional config files'
Expand Down Expand Up @@ -123,11 +123,11 @@ def test_config_file_log(self):
self.log.info('Test that correct configuration path is changed when configuration file changes the datadir')

# Create a temporary directory that will be treated as the default data
# directory by bitcoind.
# directory by BGL.
env, default_datadir = util.get_temp_default_datadir(pathlib.Path(self.options.tmpdir, "test_config_file_log"))
default_datadir.mkdir(parents=True)

# Write a bitcoin.conf file in the default data directory containing a
# Write a BGL.conf file in the default data directory containing a
# datadir= line pointing at the node datadir.
node = self.nodes[0]
conf_text = pathlib.Path(node.BGLconf).read_text()
Expand Down Expand Up @@ -354,10 +354,10 @@ def test_ignored_default_conf(self):
env, default_datadir = util.get_temp_default_datadir(pathlib.Path(self.options.tmpdir, "home"))
default_datadir.mkdir(parents=True)

# Write a bitcoin.conf file in the default data directory containing a
# Write a BGL.conf file in the default data directory containing a
# datadir= line pointing at the node datadir. This will trigger a
# startup error because the node datadir contains a different
# bitcoin.conf that would be ignored.
# BGL.conf that would be ignored.
node = self.nodes[0]
(default_datadir / "BGL.conf").write_text(f"datadir={node.datadir}\n")

Expand All @@ -374,7 +374,7 @@ def test_ignored_default_conf(self):

def test_acceptstalefeeestimates_arg_support(self):
self.log.info("Test -acceptstalefeeestimates option support")
conf_file = self.nodes[0].datadir_path / "bitcoin.conf"
conf_file = self.nodes[0].datadir_path / "BGL.conf"
for chain, chain_name in {("main", ""), ("test", "testnet3"), ("signet", "signet")}:
util.write_config(conf_file, n=0, chain=chain_name, extra_config='acceptstalefeeestimates=1\n')
self.nodes[0].assert_start_raises_init_error(expected_msg=f'Error: acceptstalefeeestimates is not supported on {chain} chain.')
Expand Down
2 changes: 1 addition & 1 deletion test/functional/feature_loadblock.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def run_test(self):
cfg.write(f"host={node_url.hostname}\n")
cfg.write(f"output_file={bootstrap_file}\n")
cfg.write(f"max_height=100\n")
cfg.write(f"netmagic=fabfb5da\n")
cfg.write(f"netmagic=d98cbfba\n")
cfg.write(f"input={blocks_dir}\n")
cfg.write(f"genesis={genesis_block}\n")
cfg.write(f"hashlist={hash_list.name}\n")
Expand Down
6 changes: 3 additions & 3 deletions test/functional/feature_maxuploadtarget.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,20 +94,20 @@ def run_test(self):
getdata_request.inv.append(CInv(MSG_BLOCK, big_old_block))

max_bytes_per_day = 800*1024*1024
daily_buffer = 144 * 4000000
daily_buffer = 144 * 400000
max_bytes_available = max_bytes_per_day - daily_buffer
success_count = max_bytes_available // old_block_size

# 576MB will be reserved for relaying new blocks, so expect this to
# succeed for ~235 tries.
# succeed for ~8120 tries.
for i in range(success_count):
p2p_conns[0].send_and_ping(getdata_request)
assert_equal(p2p_conns[0].block_receive_map[big_old_block], i+1)

assert_equal(len(self.nodes[0].getpeerinfo()), 3)
# At most a couple more tries should succeed (depending on how long
# the test has been running so far).
for _ in range(3):
for _ in range(100):
p2p_conns[0].send_message(getdata_request)
p2p_conns[0].wait_for_disconnect()
assert_equal(len(self.nodes[0].getpeerinfo()), 2)
Expand Down
2 changes: 1 addition & 1 deletion test/functional/feature_taproot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1738,7 +1738,7 @@ def pr(node):
aux = tx_test.setdefault("auxiliary", {})
aux['fullySignedTx'] = tx.serialize().hex()
keypath_tests.append(tx_test)
assert_equal(hashlib.sha256(tx.serialize()).hexdigest(), "31bd332c65d7cc5303377b84db007e4d6a27942a52546fb03377496448426d7a")
assert_equal(hashlib.sha256(tx.serialize()).hexdigest(), "9edad9338a58341384422264bd17b7597cd22be06a458cb6cae5ed72ecb9fc3f")
# Mine the spending transaction
#self.block_submit(self.nodes[0], [tx], "Spending txn", None, sigops_weight=10000, accept=True, witness=True)

Expand Down
2 changes: 1 addition & 1 deletion test/functional/test_framework/blocktools.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def script_BIP34_coinbase_height(height):
return CScript([CScriptNum(height)])


def create_coinbase(height, pubkey=None, *, script_pubkey=None, extra_output_script=None, fees=0, nValue=50):
def create_coinbase(height, pubkey=None, *, script_pubkey=None, extra_output_script=None, fees=0, nValue=200):
"""Create a coinbase transaction.
If pubkey is passed in, the coinbase output will be a P2PK output;
Expand Down
14 changes: 7 additions & 7 deletions test/functional/test_framework/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,7 @@ def LegacySignatureHash(*args, **kwargs):
if msg is None:
return (HASH_ONE, err)
else:
return (hash256(msg), err)
return (keccak256(msg), err)

def sign_input_legacy(tx, input_index, input_scriptpubkey, privkey, sighash_type=SIGHASH_ALL):
"""Add legacy ECDSA signature for a given transaction input. Note that the signature
Expand Down Expand Up @@ -746,7 +746,7 @@ def SegwitV0SignatureMsg(script, txTo, inIdx, hashtype, amount):
return ss

def SegwitV0SignatureHash(*args, **kwargs):
return hash256(SegwitV0SignatureMsg(*args, **kwargs))
return keccak256(SegwitV0SignatureMsg(*args, **kwargs))

class TestFrameworkScript(unittest.TestCase):
def test_bn2vch(self):
Expand Down Expand Up @@ -777,19 +777,19 @@ def test_cscriptnum_encoding(self):
self.assertEqual(CScriptNum.decode(CScriptNum.encode(CScriptNum(value))), value)

def BIP341_sha_prevouts(txTo):
return sha256(b"".join(i.prevout.serialize() for i in txTo.vin))
return keccak256(b"".join(i.prevout.serialize() for i in txTo.vin))

def BIP341_sha_amounts(spent_utxos):
return sha256(b"".join(struct.pack("<q", u.nValue) for u in spent_utxos))
return keccak256(b"".join(struct.pack("<q", u.nValue) for u in spent_utxos))

def BIP341_sha_scriptpubkeys(spent_utxos):
return sha256(b"".join(ser_string(u.scriptPubKey) for u in spent_utxos))
return keccak256(b"".join(ser_string(u.scriptPubKey) for u in spent_utxos))

def BIP341_sha_sequences(txTo):
return sha256(b"".join(struct.pack("<I", i.nSequence) for i in txTo.vin))
return keccak256(b"".join(struct.pack("<I", i.nSequence) for i in txTo.vin))

def BIP341_sha_outputs(txTo):
return sha256(b"".join(o.serialize() for o in txTo.vout))
return keccak256(b"".join(o.serialize() for o in txTo.vout))

def TaprootSignatureMsg(txTo, spent_utxos, hash_type, input_index = 0, scriptpath = False, script = CScript(), codeseparator_pos = -1, annex = None, leaf_ver = LEAF_VERSION_TAPSCRIPT):
assert (len(txTo.vin) == len(spent_utxos))
Expand Down
10 changes: 5 additions & 5 deletions test/functional/test_framework/test_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ def _start_logging(self):
# User can provide log level as a number or string (eg DEBUG). loglevel was caught as a string, so try to convert it to an int
ll = int(self.options.loglevel) if self.options.loglevel.isdigit() else self.options.loglevel.upper()
ch.setLevel(ll)
# Format logs the same as bitcoind's debug.log with microprecision (so log files can be concatenated and sorted)
# Format logs the same as BGLd's debug.log with microprecision (so log files can be concatenated and sorted)
formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d000Z %(name)s (%(levelname)s): %(message)s', datefmt='%Y-%m-%dT%H:%M:%S')
formatter.converter = time.gmtime
fh.setFormatter(formatter)
Expand Down Expand Up @@ -904,7 +904,7 @@ def skip_if_no_bdb(self):
raise SkipTest("BDB has not been compiled.")

def skip_if_no_wallet_tool(self):
"""Skip the running test if bitcoin-wallet has not been compiled."""
"""Skip the running test if BGL-wallet has not been compiled."""
if not self.is_wallet_tool_compiled():
raise SkipTest("BGL-wallet has not been compiled")

Expand All @@ -914,7 +914,7 @@ def skip_if_no_BGL_util(self):
raise SkipTest("BGL-util has not been compiled")

def skip_if_no_cli(self):
"""Skip the running test if bitcoin-cli has not been compiled."""
"""Skip the running test if BGL-cli has not been compiled."""
if not self.is_cli_compiled():
raise SkipTest("BGL-cli has not been compiled.")

Expand All @@ -937,7 +937,7 @@ def skip_if_no_external_signer(self):
raise SkipTest("external signer support has not been compiled.")

def is_cli_compiled(self):
"""Checks whether bitcoin-cli was compiled."""
"""Checks whether BGL-cli was compiled."""
return self.config["components"].getboolean("ENABLE_CLI")

def is_external_signer_compiled(self):
Expand Down Expand Up @@ -978,4 +978,4 @@ def is_sqlite_compiled(self):

def is_bdb_compiled(self):
"""Checks whether the wallet module was compiled with BDB support."""
return self.config["components"].getboolean("USE_BDB")
return self.config["components"].getboolean("USE_BDB")
2 changes: 1 addition & 1 deletion test/functional/wallet_importdescriptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ def run_test(self):
txid2 = w0.sendtoaddress(addr2, 10)
vout2 = find_vout_for_address(self.nodes[0], txid2, addr2)

self.generate(self.nodes[0], 6)
self.generate(self.nodes[0], 6)
assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance())
# Make sure that descriptor wallets containing multiple xpubs in a single descriptor load correctly
wmulti_pub.unloadwallet()
Expand Down
5 changes: 1 addition & 4 deletions test/functional/wallet_taproot.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def compute_taproot_address(pubkey, scripts):
return output_key_to_p2tr(taproot_construct(pubkey, scripts).output_pubkey)

def compute_raw_taproot_address(pubkey):
return encode_segwit_address("bcrt", 1, pubkey)
return encode_segwit_address("rbgl", 1, pubkey)

class WalletTaprootTest(BGLTestFramework):
"""Test generation and spending of P2TR address outputs."""
Expand Down Expand Up @@ -335,9 +335,6 @@ def do_test_psbt(self, comment, pattern, privmap, treefn, keys_pay, keys_change)
assert result[0]['success']
result = psbt_offline.importdescriptors([{"desc": desc_change, "active": True, "timestamp": "now", "internal": True}])
assert result[0]['success']
for key in keys_pay + keys_change:
result = key_only_wallet.importdescriptors([{"desc": descsum_create(f"wpkh({key['xprv']}/*)"), "timestamp":"now"}])
assert result[0]["success"]
address_type = "bech32m" if "tr" in pattern else "bech32"
for i in range(4):
addr_g = psbt_online.getnewaddress(address_type=address_type)
Expand Down

0 comments on commit 5272d98

Please sign in to comment.