diff --git a/.python-version b/.python-version index 7bcbb3808b..c49282585a 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.4.9 +3.5.6 diff --git a/.travis.yml b/.travis.yml index b1ae558a90..7d14cf813d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -205,7 +205,7 @@ after_success: env: cache: false language: python - python: '3.4' # Oldest supported version according to doc/dependencies.md + python: '3.5' # Oldest supported version according to doc/dependencies.md install: - set -o errexit; source .travis/lint_04_install.sh before_script: @@ -313,7 +313,7 @@ after_success: name: 'macOS 10.12 [GOAL: deploy]' env: >- HOST=x86_64-apple-darwin16 - PACKAGES="cmake imagemagick libcap-dev librsvg2-bin libz-dev libbz2-dev libtiff-tools python-dev python3-setuptools-git" + PACKAGES="cmake imagemagick libcap-dev librsvg2-bin libz-dev libbz2-dev libtiff-tools python3-dev python3-setuptools" OSX_SDK=10.11 RUN_UNIT_TESTS=false RUN_FUNCTIONAL_TESTS=false diff --git a/configure.ac b/configure.ac index 9d16f0d49e..d77ee1bb9d 100644 --- a/configure.ac +++ b/configure.ac @@ -99,8 +99,8 @@ AC_PATH_TOOL(RANLIB, ranlib) AC_PATH_TOOL(STRIP, strip) AC_PATH_TOOL(GCOV, gcov) AC_PATH_PROG(LCOV, lcov) -dnl Python 3.4 is specified in .python-version and should be used if available, see doc/dependencies.md -AC_PATH_PROGS([PYTHON], [python3.4 python3.5 python3.6 python3.7 python3 python]) +dnl Python 3.5 is specified in .python-version and should be used if available, see doc/dependencies.md +AC_PATH_PROGS([PYTHON], [python3.5 python3.6 python3.7 python3.8 python3 python]) AC_PATH_PROG(GENHTML, genhtml) AC_PATH_PROG([GIT], [git]) AC_PATH_PROG(CCACHE,ccache) diff --git a/contrib/devtools/README.md b/contrib/devtools/README.md index 9782dab0c0..3613c9b3f9 100644 --- a/contrib/devtools/README.md +++ b/contrib/devtools/README.md @@ -170,7 +170,7 @@ still compatible with the minimum supported Linux distribution versions. Example usage after a Gitian build: - find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py + find ../gitian-builder/build -type f -executable | xargs python3 contrib/devtools/symbol-check.py If only supported symbols are used the return value will be 0 and the output will be empty. diff --git a/contrib/devtools/symbol-check.py b/contrib/devtools/symbol-check.py index 9cf94e8f56..77ae51c68e 100755 --- a/contrib/devtools/symbol-check.py +++ b/contrib/devtools/symbol-check.py @@ -9,7 +9,7 @@ still compatible with the minimum supported Linux distribution versions. Example usage: - find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py + find ../gitian-builder/build -type f -executable | xargs python3 contrib/devtools/symbol-check.py ''' import subprocess import re diff --git a/contrib/gitian-descriptors/gitian-linux.yml b/contrib/gitian-descriptors/gitian-linux.yml index ff68f0deb4..b7be3f4c8f 100755 --- a/contrib/gitian-descriptors/gitian-linux.yml +++ b/contrib/gitian-descriptors/gitian-linux.yml @@ -26,7 +26,6 @@ packages: - "faketime" - "bsdmainutils" - "ca-certificates" -- "python" - "python3" - "libxkbcommon0" - "ccache" diff --git a/contrib/gitian-descriptors/gitian-osx.yml b/contrib/gitian-descriptors/gitian-osx.yml index ced7e75349..eb8a150055 100644 --- a/contrib/gitian-descriptors/gitian-osx.yml +++ b/contrib/gitian-descriptors/gitian-osx.yml @@ -22,8 +22,6 @@ packages: - "libcap-dev" - "libz-dev" - "libbz2-dev" -- "python" -- "python-dev" - "python3" - "python3-dev" - "python3-setuptools" diff --git a/contrib/gitian-descriptors/gitian-win.yml b/contrib/gitian-descriptors/gitian-win.yml index d9af1a5970..d264c49171 100755 --- a/contrib/gitian-descriptors/gitian-win.yml +++ b/contrib/gitian-descriptors/gitian-win.yml @@ -20,7 +20,6 @@ packages: - "nsis" - "zip" - "ca-certificates" -- "python" - "python3" - "rename" - "ccache" diff --git a/contrib/linearize/README.md b/contrib/linearize/README.md index 15e86312ee..9369030c33 100644 --- a/contrib/linearize/README.md +++ b/contrib/linearize/README.md @@ -1,6 +1,5 @@ # Linearize -Construct a linear, no-fork, best version of the Dash blockchain. The scripts -run using Python 3 but are compatible with Python 2. +Construct a linear, no-fork, best version of the Dash blockchain. ## Step 0: Install dash_hash diff --git a/contrib/linearize/linearize-data.py b/contrib/linearize/linearize-data.py index 55c807432b..9f970ee5c8 100755 --- a/contrib/linearize/linearize-data.py +++ b/contrib/linearize/linearize-data.py @@ -17,7 +17,7 @@ import datetime import time import glob from collections import namedtuple -from binascii import hexlify, unhexlify +from binascii import unhexlify settings = {} @@ -64,7 +64,7 @@ def calc_hash_str(blk_hdr): hash = calc_hdr_hash(blk_hdr) hash = bufreverse(hash) hash = wordreverse(hash) - hash_str = hexlify(hash).decode('utf-8') + hash_str = hash.hex() return hash_str def get_blk_dt(blk_hdr): @@ -242,7 +242,7 @@ class BlockDataCopier: inMagic = inhdr[:4] if (inMagic != self.settings['netmagic']): - print("Invalid magic: " + hexlify(inMagic).decode('utf-8')) + print("Invalid magic: " + inMagic.hex()) return inLenLE = inhdr[4:] su = struct.unpack(" 0) + assert len(utxos) > 0 utxo = utxos[0] @@ -248,7 +248,7 @@ class BIP68Test(BitcoinTestFramework): self.nodes[0].generate(1) cur_time += 600 - assert(tx2.hash in self.nodes[0].getrawmempool()) + assert tx2.hash in self.nodes[0].getrawmempool() test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True) test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) @@ -259,23 +259,23 @@ class BIP68Test(BitcoinTestFramework): # Advance the time on the node so that we can test timelocks self.nodes[0].setmocktime(cur_time+600) self.nodes[0].generate(1) - assert(tx2.hash not in self.nodes[0].getrawmempool()) + assert tx2.hash not in self.nodes[0].getrawmempool() # Now that tx2 is not in the mempool, a sequence locked spend should # succeed tx3 = test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) - assert(tx3.hash in self.nodes[0].getrawmempool()) + assert tx3.hash in self.nodes[0].getrawmempool() self.nodes[0].generate(1) - assert(tx3.hash not in self.nodes[0].getrawmempool()) + assert tx3.hash not in self.nodes[0].getrawmempool() # One more test, this time using height locks tx4 = test_nonzero_locks(tx3, self.nodes[0], self.relayfee, use_height_lock=True) - assert(tx4.hash in self.nodes[0].getrawmempool()) + assert tx4.hash in self.nodes[0].getrawmempool() # Now try combining confirmed and unconfirmed inputs tx5 = test_nonzero_locks(tx4, self.nodes[0], self.relayfee, use_height_lock=True) - assert(tx5.hash not in self.nodes[0].getrawmempool()) + assert tx5.hash not in self.nodes[0].getrawmempool() utxos = self.nodes[0].listunspent() tx5.vin.append(CTxIn(COutPoint(int(utxos[0]["txid"], 16), utxos[0]["vout"]), nSequence=1)) @@ -294,8 +294,8 @@ class BIP68Test(BitcoinTestFramework): # If we invalidate the tip, tx3 should get added to the mempool, causing # tx4 to be removed (fails sequence-lock). self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) - assert(tx4.hash not in self.nodes[0].getrawmempool()) - assert(tx3.hash in self.nodes[0].getrawmempool()) + assert tx4.hash not in self.nodes[0].getrawmempool() + assert tx3.hash in self.nodes[0].getrawmempool() # Now mine 2 empty blocks to reorg out the current tip (labeled tip-1 in # diagram above). @@ -314,8 +314,8 @@ class BIP68Test(BitcoinTestFramework): cur_time += 1 mempool = self.nodes[0].getrawmempool() - assert(tx3.hash not in mempool) - assert(tx2.hash in mempool) + assert tx3.hash not in mempool + assert tx2.hash in mempool # Reset the chain and get rid of the mocktimed-blocks self.nodes[0].setmocktime(self.mocktime) @@ -327,7 +327,7 @@ class BIP68Test(BitcoinTestFramework): # being run, then it's possible the test has activated the soft fork, and # this test should be moved to run earlier, or deleted. def test_bip68_not_consensus(self): - assert(get_bip9_status(self.nodes[0], 'csv')['status'] != 'active') + assert get_bip9_status(self.nodes[0], 'csv')['status'] != 'active' txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 2) tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid)) diff --git a/test/functional/feature_block.py b/test/functional/feature_block.py index db24dd1f05..418f983b36 100755 --- a/test/functional/feature_block.py +++ b/test/functional/feature_block.py @@ -726,7 +726,7 @@ class FullBlockTest(BitcoinTestFramework): self.move_tip(57) b58 = self.next_block(58, spend=out[17]) tx = CTransaction() - assert(len(out[17].vout) < 42) + assert len(out[17].vout) < 42 tx.vin.append(CTxIn(COutPoint(out[17].sha256, 42), CScript([OP_TRUE]), 0xffffffff)) tx.vout.append(CTxOut(0, b"")) tx.calc_sha256() @@ -777,7 +777,7 @@ class FullBlockTest(BitcoinTestFramework): tx.nLockTime = 0xffffffff # this locktime is non-final tx.vin.append(CTxIn(COutPoint(out[18].sha256, 0))) # don't set nSequence tx.vout.append(CTxOut(0, CScript([OP_TRUE]))) - assert(tx.vin[0].nSequence < 0xffffffff) + assert tx.vin[0].nSequence < 0xffffffff tx.calc_sha256() b62 = self.update_block(62, [tx]) self.send_blocks([b62], success=False, reject_code=16, reject_reason=b'bad-txns-nonfinal') @@ -1096,8 +1096,8 @@ class FullBlockTest(BitcoinTestFramework): # now check that tx78 and tx79 have been put back into the peer's mempool mempool = self.nodes[0].getrawmempool() assert_equal(len(mempool), 2) - assert(tx78.hash in mempool) - assert(tx79.hash in mempool) + assert tx78.hash in mempool + assert tx79.hash in mempool # Test invalid opcodes in dead execution paths. # diff --git a/test/functional/feature_cltv.py b/test/functional/feature_cltv.py index da8605485c..6389531532 100755 --- a/test/functional/feature_cltv.py +++ b/test/functional/feature_cltv.py @@ -13,7 +13,7 @@ from test_framework.messages import CTransaction, msg_block, ToHex from test_framework.mininode import mininode_lock, P2PInterface from test_framework.script import CScript, OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP, CScriptNum from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str, hex_str_to_bytes, wait_until +from test_framework.util import assert_equal, assert_raises_rpc_error, hex_str_to_bytes, wait_until from io import BytesIO @@ -124,7 +124,7 @@ class BIP65Test(BitcoinTestFramework): # First we show that this tx is valid except for CLTV by getting it # rejected from the mempool for exactly that reason. - assert_raises_rpc_error(-26, 'non-mandatory-script-verify-flag (Negative locktime) (code 64)', self.nodes[0].sendrawtransaction, bytes_to_hex_str(spendtx.serialize()), True) + assert_raises_rpc_error(-26, 'non-mandatory-script-verify-flag (Negative locktime) (code 64)', self.nodes[0].sendrawtransaction, spendtx.serialize().hex(), True) # Now we verify that a block with this transaction is also invalid. block.vtx.append(spendtx) diff --git a/test/functional/feature_csv_activation.py b/test/functional/feature_csv_activation.py index 7c0af3fc68..95fc98d45d 100755 --- a/test/functional/feature_csv_activation.py +++ b/test/functional/feature_csv_activation.py @@ -106,7 +106,7 @@ def send_generic_input_tx(node, coinbases, address): def create_bip68txs(node, bip68inputs, txversion, address, locktime_delta=0): """Returns a list of bip68 transactions with different bits set.""" txs = [] - assert(len(bip68inputs) >= 16) + assert len(bip68inputs) >= 16 for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): locktime = relative_locktime(sdf, srhb, stf, srlb) tx = create_transaction(node, bip68inputs[i], address, Decimal("499.98")) @@ -121,7 +121,7 @@ def create_bip68txs(node, bip68inputs, txversion, address, locktime_delta=0): def create_bip112txs(node, bip112inputs, varyOP_CSV, txversion, address, locktime_delta=0): """Returns a list of bip68 transactions with different bits set.""" txs = [] - assert(len(bip112inputs) >= 16) + assert len(bip112inputs) >= 16 for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): locktime = relative_locktime(sdf, srhb, stf, srlb) tx = create_transaction(node, bip112inputs[i], address, Decimal("499.98")) diff --git a/test/functional/feature_dbcrash.py b/test/functional/feature_dbcrash.py index ba9ffa19c1..f93eb4716d 100755 --- a/test/functional/feature_dbcrash.py +++ b/test/functional/feature_dbcrash.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2017 The Bitcoin Core developers +# Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test recovery from a crash during chainstate writing. @@ -28,18 +28,12 @@ import errno import http.client import random -import sys import time from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, create_confirmed_utxos, hex_str_to_bytes -HTTP_DISCONNECT_ERRORS = [http.client.CannotSendRequest] -try: - HTTP_DISCONNECT_ERRORS.append(http.client.RemoteDisconnected) -except AttributeError: - pass class ChainstateWriteCrashTest(BitcoinTestFramework): def set_test_params(self): @@ -106,14 +100,7 @@ class ChainstateWriteCrashTest(BitcoinTestFramework): try: self.nodes[node_index].submitblock(block) return True - except http.client.BadStatusLine as e: - # Prior to 3.5 BadStatusLine('') was raised for a remote disconnect error. - if sys.version_info[0] == 3 and sys.version_info[1] < 5 and e.line == "''": - self.log.debug("node %d submitblock raised exception: %s", node_index, e) - return False - else: - raise - except tuple(HTTP_DISCONNECT_ERRORS) as e: + except (http.client.CannotSendRequest, http.client.RemoteDisconnected) as e: self.log.debug("node %d submitblock raised exception: %s", node_index, e) return False except OSError as e: diff --git a/test/functional/feature_dersig.py b/test/functional/feature_dersig.py index 8829be1b58..bd573f1723 100755 --- a/test/functional/feature_dersig.py +++ b/test/functional/feature_dersig.py @@ -12,7 +12,7 @@ from test_framework.messages import msg_block from test_framework.mininode import mininode_lock, P2PInterface from test_framework.script import CScript from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str, wait_until +from test_framework.util import assert_equal, assert_raises_rpc_error, wait_until DERSIG_HEIGHT = 1251 @@ -114,7 +114,7 @@ class BIP66Test(BitcoinTestFramework): # First we show that this tx is valid except for DERSIG by getting it # rejected from the mempool for exactly that reason. - assert_raises_rpc_error(-26, 'non-mandatory-script-verify-flag (Non-canonical DER signature) (code 64)', self.nodes[0].sendrawtransaction, bytes_to_hex_str(spendtx.serialize()), True) + assert_raises_rpc_error(-26, 'non-mandatory-script-verify-flag (Non-canonical DER signature) (code 64)', self.nodes[0].sendrawtransaction, spendtx.serialize().hex(), True) # Now we verify that a block with this transaction is also invalid. block.vtx.append(spendtx) diff --git a/test/functional/feature_dip0020_activation.py b/test/functional/feature_dip0020_activation.py index 1e65cb36f8..1273395712 100755 --- a/test/functional/feature_dip0020_activation.py +++ b/test/functional/feature_dip0020_activation.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2015-2020 The Dash Core developers +# Copyright (c) 2015-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex @@ -26,7 +26,7 @@ class DIP0020ActivationTest(BitcoinTestFramework): # We should have some coins already utxos = self.node.listunspent() - assert (len(utxos) > 0) + assert len(utxos) > 0 # Send some coins to a P2SH address constructed using disabled opcodes utxo = utxos[len(utxos) - 1] @@ -38,9 +38,9 @@ class DIP0020ActivationTest(BitcoinTestFramework): txid = self.node.sendrawtransaction(tx_signed_hex) # This tx should be completely valid, should be included in mempool and mined in the next block - assert (txid in set(self.node.getrawmempool())) + assert txid in set(self.node.getrawmempool()) self.node.generate(1) - assert (txid not in set(self.node.getrawmempool())) + assert txid not in set(self.node.getrawmempool()) # Create spending tx value = int(value - self.relayfee * COIN) @@ -64,7 +64,7 @@ class DIP0020ActivationTest(BitcoinTestFramework): # Should be spendable now tx0id = self.node.sendrawtransaction(tx0_hex) - assert (tx0id in set(self.node.getrawmempool())) + assert tx0id in set(self.node.getrawmempool()) if __name__ == '__main__': diff --git a/test/functional/feature_dip3_deterministicmns.py b/test/functional/feature_dip3_deterministicmns.py index 0773e7e9b7..1f78d3169e 100755 --- a/test/functional/feature_dip3_deterministicmns.py +++ b/test/functional/feature_dip3_deterministicmns.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2015-2020 The Dash Core developers +# Copyright (c) 2015-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -48,7 +48,7 @@ class DIP3Test(BitcoinTestFramework): # Make sure we're below block 135 (which activates dip3) self.log.info("testing rejection of ProTx before dip3 activation") - assert(self.nodes[0].getblockchaininfo()['blocks'] < 135) + assert self.nodes[0].getblockchaininfo()['blocks'] < 135 mns = [] @@ -60,7 +60,7 @@ class DIP3Test(BitcoinTestFramework): # block 150 starts enforcing DIP3 MN payments self.nodes[0].generate(150 - self.nodes[0].getblockcount()) - assert(self.nodes[0].getblockcount() == 150) + assert self.nodes[0].getblockcount() == 150 self.log.info("mining final block for DIP3 activation") self.nodes[0].generate(1) @@ -163,7 +163,7 @@ class DIP3Test(BitcoinTestFramework): if 'addresses' in out['scriptPubKey']: if expected_payee in out['scriptPubKey']['addresses'] and out['valueSat'] == expected_amount: found_multisig_payee = True - assert(found_multisig_payee) + assert found_multisig_payee self.log.info("testing reusing of collaterals for replaced MNs") for i in range(0, 5): @@ -192,7 +192,7 @@ class DIP3Test(BitcoinTestFramework): old_dmnState = mn.node.masternode("status")["dmnState"] old_voting_address = old_dmnState["votingAddress"] new_voting_address = node.getnewaddress() - assert(old_voting_address != new_voting_address) + assert old_voting_address != new_voting_address # also check if funds from payout address are used when no fee source address is specified node.sendtoaddress(mn.rewards_address, 0.001) node.protx('update_registrar', mn.protx_hash, "", new_voting_address, "") @@ -200,9 +200,9 @@ class DIP3Test(BitcoinTestFramework): self.sync_all() new_dmnState = mn.node.masternode("status")["dmnState"] new_voting_address_from_rpc = new_dmnState["votingAddress"] - assert(new_voting_address_from_rpc == new_voting_address) + assert new_voting_address_from_rpc == new_voting_address # make sure payoutAddress is the same as before - assert(old_dmnState["payoutAddress"] == new_dmnState["payoutAddress"]) + assert old_dmnState["payoutAddress"] == new_dmnState["payoutAddress"] def prepare_mn(self, node, idx, alias): mn = Masternode() @@ -230,7 +230,7 @@ class DIP3Test(BitcoinTestFramework): if txout['value'] == Decimal(1000): mn.collateral_vout = txout['n'] break - assert(mn.collateral_vout != -1) + assert mn.collateral_vout != -1 # register a protx MN and also fund it (using collateral inside ProRegTx) def register_fund_mn(self, node, mn): @@ -247,7 +247,7 @@ class DIP3Test(BitcoinTestFramework): if txout['value'] == Decimal(1000): mn.collateral_vout = txout['n'] break - assert(mn.collateral_vout != -1) + assert mn.collateral_vout != -1 # create a protx MN which refers to an existing collateral def register_mn(self, node, mn): @@ -276,7 +276,7 @@ class DIP3Test(BitcoinTestFramework): self.nodes[0].generate(1) self.sync_all() info = self.nodes[0].protx('info', mn.protx_hash) - assert(info['state']['payoutAddress'] == payee) + assert info['state']['payoutAddress'] == payee def test_protx_update_service(self, mn): self.nodes[0].sendtoaddress(mn.fundsAddr, 0.001) diff --git a/test/functional/feature_dip4_coinbasemerkleroots.py b/test/functional/feature_dip4_coinbasemerkleroots.py index 618608ede9..8a409a64c6 100755 --- a/test/functional/feature_dip4_coinbasemerkleroots.py +++ b/test/functional/feature_dip4_coinbasemerkleroots.py @@ -64,11 +64,11 @@ class LLMQCoinbaseCommitmentsTest(DashTestFramework): expectedDeleted = [] expectedUpdated = [new_mn.proTxHash] mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated) - assert(mnList[new_mn.proTxHash].confirmedHash == 0) + assert mnList[new_mn.proTxHash].confirmedHash == 0 # Now let the MN get enough confirmations and verify that the MNLISTDIFF now has confirmedHash != 0 self.confirm_mns() mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated) - assert(mnList[new_mn.proTxHash].confirmedHash != 0) + assert mnList[new_mn.proTxHash].confirmedHash != 0 # Spend the collateral of the previously added MN and test if it appears in "deletedMNs" expectedDeleted = [new_mn.proTxHash] @@ -252,18 +252,18 @@ class LLMQCoinbaseCommitmentsTest(DashTestFramework): self.wait_for_sporks_same() cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0] - assert(cbtx["cbTx"]["version"] == 1) + assert cbtx["cbTx"]["version"] == 1 self.activate_dip8(slow_mode) # Assert that merkleRootQuorums is present and 0 (we have no quorums yet) cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0] assert_equal(cbtx["cbTx"]["version"], 2) - assert("merkleRootQuorums" in cbtx["cbTx"]) + assert "merkleRootQuorums" in cbtx["cbTx"] merkleRootQuorums = int(cbtx["cbTx"]["merkleRootQuorums"], 16) if with_initial_quorum: - assert(merkleRootQuorums != 0) + assert merkleRootQuorums != 0 else: assert_equal(merkleRootQuorums, 0) @@ -274,7 +274,7 @@ class LLMQCoinbaseCommitmentsTest(DashTestFramework): # Mine quorum and verify that merkleRootQuorums has changed quorum = self.mine_quorum() cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0] - assert(int(cbtx["cbTx"]["merkleRootQuorums"], 16) != merkleRootQuorums) + assert int(cbtx["cbTx"]["merkleRootQuorums"], 16) != merkleRootQuorums return quorum diff --git a/test/functional/feature_llmq_chainlocks.py b/test/functional/feature_llmq_chainlocks.py index 38ebe65e7f..fc58293f00 100755 --- a/test/functional/feature_llmq_chainlocks.py +++ b/test/functional/feature_llmq_chainlocks.py @@ -50,7 +50,7 @@ class LLMQChainLocksTest(DashTestFramework): self.log.info("Assert that all blocks up until the tip are chainlocked") for h in range(1, self.nodes[0].getblockcount()): block = self.nodes[0].getblock(self.nodes[0].getblockhash(h)) - assert(block['chainlock']) + assert block['chainlock'] self.log.info("Isolate node, mine on another, and reconnect") isolate_node(self.nodes[0]) @@ -58,7 +58,7 @@ class LLMQChainLocksTest(DashTestFramework): node0_tip = self.nodes[0].getbestblockhash() self.nodes[1].generatetoaddress(5, node0_mining_addr) self.wait_for_chainlocked_block(self.nodes[1], self.nodes[1].getbestblockhash()) - assert(self.nodes[0].getbestblockhash() == node0_tip) + assert self.nodes[0].getbestblockhash() == node0_tip reconnect_isolated_node(self.nodes[0], 1) self.nodes[1].generatetoaddress(1, node0_mining_addr) self.wait_for_chainlocked_block_all_nodes(self.nodes[1].getbestblockhash()) @@ -69,21 +69,21 @@ class LLMQChainLocksTest(DashTestFramework): self.nodes[1].generatetoaddress(1, node0_mining_addr) good_tip = self.nodes[1].getbestblockhash() self.wait_for_chainlocked_block(self.nodes[1], good_tip) - assert(not self.nodes[0].getblock(self.nodes[0].getbestblockhash())["chainlock"]) + assert not self.nodes[0].getblock(self.nodes[0].getbestblockhash())["chainlock"] reconnect_isolated_node(self.nodes[0], 1) self.nodes[1].generatetoaddress(1, node0_mining_addr) self.wait_for_chainlocked_block_all_nodes(self.nodes[1].getbestblockhash()) - assert(self.nodes[0].getblock(self.nodes[0].getbestblockhash())["previousblockhash"] == good_tip) - assert(self.nodes[1].getblock(self.nodes[1].getbestblockhash())["previousblockhash"] == good_tip) + assert self.nodes[0].getblock(self.nodes[0].getbestblockhash())["previousblockhash"] == good_tip + assert self.nodes[1].getblock(self.nodes[1].getbestblockhash())["previousblockhash"] == good_tip self.log.info("The tip mined while this node was isolated should be marked conflicting now") found = False for tip in self.nodes[0].getchaintips(2): if tip["hash"] == bad_tip: - assert(tip["status"] == "conflicting") + assert tip["status"] == "conflicting" found = True break - assert(found) + assert found self.log.info("Keep node connected and let it try to reorg the chain") good_tip = self.nodes[0].getbestblockhash() @@ -91,41 +91,41 @@ class LLMQChainLocksTest(DashTestFramework): self.stop_node(0) self.start_node(0) connect_nodes(self.nodes[0], 1) - assert(self.nodes[0].getbestblockhash() == good_tip) + assert self.nodes[0].getbestblockhash() == good_tip self.nodes[0].invalidateblock(good_tip) self.log.info("Now try to reorg the chain") self.nodes[0].generate(2) time.sleep(6) - assert(self.nodes[1].getbestblockhash() == good_tip) + assert self.nodes[1].getbestblockhash() == good_tip bad_tip = self.nodes[0].generate(2)[-1] time.sleep(6) - assert(self.nodes[0].getbestblockhash() == bad_tip) - assert(self.nodes[1].getbestblockhash() == good_tip) + assert self.nodes[0].getbestblockhash() == bad_tip + assert self.nodes[1].getbestblockhash() == good_tip self.log.info("Now let the node which is on the wrong chain reorg back to the locked chain") self.nodes[0].reconsiderblock(good_tip) - assert(self.nodes[0].getbestblockhash() != good_tip) + assert self.nodes[0].getbestblockhash() != good_tip good_fork = good_tip good_tip = self.nodes[1].generatetoaddress(1, node0_mining_addr)[-1] # this should mark bad_tip as conflicting self.wait_for_chainlocked_block_all_nodes(good_tip) - assert(self.nodes[0].getbestblockhash() == good_tip) + assert self.nodes[0].getbestblockhash() == good_tip found = False for tip in self.nodes[0].getchaintips(2): if tip["hash"] == bad_tip: - assert(tip["status"] == "conflicting") + assert tip["status"] == "conflicting" found = True break - assert(found) + assert found self.log.info("Should switch to the best non-conflicting tip (not to the most work chain) on restart") - assert(int(self.nodes[0].getblock(bad_tip)["chainwork"], 16) > int(self.nodes[1].getblock(good_tip)["chainwork"], 16)) + assert int(self.nodes[0].getblock(bad_tip)["chainwork"], 16) > int(self.nodes[1].getblock(good_tip)["chainwork"], 16) self.stop_node(0) self.start_node(0) self.nodes[0].invalidateblock(good_fork) self.stop_node(0) self.start_node(0) time.sleep(1) - assert(self.nodes[0].getbestblockhash() == good_tip) + assert self.nodes[0].getbestblockhash() == good_tip self.log.info("Isolate a node and let it create some transactions which won't get IS locked") isolate_node(self.nodes[0]) @@ -137,11 +137,11 @@ class LLMQChainLocksTest(DashTestFramework): node0_tip = self.nodes[0].generate(1)[-1] for txid in txs: tx = self.nodes[0].getrawtransaction(txid, 1) - assert("confirmations" not in tx) + assert "confirmations" not in tx time.sleep(1) node0_tip_block = self.nodes[0].getblock(node0_tip) - assert(not node0_tip_block["chainlock"]) - assert(node0_tip_block["previousblockhash"] == good_tip) + assert not node0_tip_block["chainlock"] + assert node0_tip_block["previousblockhash"] == good_tip self.log.info("Disable LLMQ based InstantSend for a very short time (this never gets propagated to other nodes)") self.nodes[0].spork("SPORK_2_INSTANTSEND_ENABLED", 4070908800) self.log.info("Now the TXs should be included") @@ -150,7 +150,7 @@ class LLMQChainLocksTest(DashTestFramework): self.log.info("Assert that TXs got included now") for txid in txs: tx = self.nodes[0].getrawtransaction(txid, 1) - assert("confirmations" in tx and tx["confirmations"] > 0) + assert "confirmations" in tx and tx["confirmations"] > 0 # Enable network on first node again, which will cause the blocks to propagate and IS locks to happen retroactively # for the mined TXs, which will then allow the network to create a CLSIG self.log.info("Re-enable network on first node and wait for chainlock") diff --git a/test/functional/feature_llmq_connections.py b/test/functional/feature_llmq_connections.py index a0feaee7a0..51852b1e11 100755 --- a/test/functional/feature_llmq_connections.py +++ b/test/functional/feature_llmq_connections.py @@ -33,7 +33,7 @@ class LLMQConnections(DashTestFramework): count = self.get_mn_connection_count(mn.node) total_count += count assert_greater_than_or_equal(count, 2) - assert(total_count < 40) + assert total_count < 40 self.check_reconnects(2) diff --git a/test/functional/feature_llmq_dkgerrors.py b/test/functional/feature_llmq_dkgerrors.py index 92605a2fe4..61e7b837c6 100755 --- a/test/functional/feature_llmq_dkgerrors.py +++ b/test/functional/feature_llmq_dkgerrors.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2015-2020 The Dash Core developers +# Copyright (c) 2015-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -75,11 +75,11 @@ class LLMQDKGErrors(DashTestFramework): for m in q['members']: if m['proTxHash'] == proTxHash: if expectedValid: - assert(m['valid']) + assert m['valid'] else: - assert(not m['valid']) + assert not m['valid'] else: - assert(m['valid']) + assert m['valid'] def heal_masternodes(self, blockCount): # We're not testing PoSe here, so lets heal the MNs :) diff --git a/test/functional/feature_llmq_is_cl_conflicts.py b/test/functional/feature_llmq_is_cl_conflicts.py index ba173cf31e..ee46e13d99 100755 --- a/test/functional/feature_llmq_is_cl_conflicts.py +++ b/test/functional/feature_llmq_is_cl_conflicts.py @@ -108,7 +108,7 @@ class LLMQ_IS_CL_Conflicts(DashTestFramework): if test_block_conflict: # The block shouldn't be accepted/connected but it should be known to node 0 now submit_result = self.nodes[0].submitblock(ToHex(block)) - assert(submit_result == "conflict-tx-lock") + assert submit_result == "conflict-tx-lock" cl = self.create_chainlock(self.nodes[0].getblockcount() + 1, block) @@ -140,10 +140,10 @@ class LLMQ_IS_CL_Conflicts(DashTestFramework): submit_result = self.nodes[1].submitblock(ToHex(block)) if test_block_conflict: # Node 1 should receive the block from node 0 and should not accept it again via submitblock - assert(submit_result == "duplicate") + assert submit_result == "duplicate" else: # The block should get accepted now, and at the same time prune the conflicting ISLOCKs - assert(submit_result is None) + assert submit_result is None self.wait_for_chainlocked_block_all_nodes(block.hash) @@ -217,7 +217,7 @@ class LLMQ_IS_CL_Conflicts(DashTestFramework): self.sync_all() # Assert that the conflicting tx got mined and the locked TX is not valid - assert(self.nodes[0].getrawtransaction(rawtx1_txid, True)['confirmations'] > 0) + assert self.nodes[0].getrawtransaction(rawtx1_txid, True)['confirmations'] > 0 assert_raises_rpc_error(-25, "Missing inputs", self.nodes[0].sendrawtransaction, rawtx2) # Create the block and the corresponding clsig but do not relay clsig yet @@ -232,20 +232,20 @@ class LLMQ_IS_CL_Conflicts(DashTestFramework): self.test_node.send_islock(islock) time.sleep(5) - assert(self.nodes[0].getbestblockhash() == good_tip) - assert(self.nodes[1].getbestblockhash() == good_tip) + assert self.nodes[0].getbestblockhash() == good_tip + assert self.nodes[1].getbestblockhash() == good_tip # Send the actual transaction and mine it self.nodes[0].sendrawtransaction(rawtx2) self.nodes[0].generate(1) self.sync_all() - assert(self.nodes[0].getrawtransaction(rawtx2_txid, True)['confirmations'] > 0) - assert(self.nodes[1].getrawtransaction(rawtx2_txid, True)['confirmations'] > 0) - assert(self.nodes[0].getrawtransaction(rawtx2_txid, True)['instantlock']) - assert(self.nodes[1].getrawtransaction(rawtx2_txid, True)['instantlock']) - assert(self.nodes[0].getbestblockhash() != good_tip) - assert(self.nodes[1].getbestblockhash() != good_tip) + assert self.nodes[0].getrawtransaction(rawtx2_txid, True)['confirmations'] > 0 + assert self.nodes[1].getrawtransaction(rawtx2_txid, True)['confirmations'] > 0 + assert self.nodes[0].getrawtransaction(rawtx2_txid, True)['instantlock'] + assert self.nodes[1].getrawtransaction(rawtx2_txid, True)['instantlock'] + assert self.nodes[0].getbestblockhash() != good_tip + assert self.nodes[1].getbestblockhash() != good_tip # Check that the CL-ed block overrides the one with islocks self.nodes[0].spork("SPORK_19_CHAINLOCKS_ENABLED", 0) # Re-enable ChainLocks to accept clsig diff --git a/test/functional/feature_llmq_is_retroactive.py b/test/functional/feature_llmq_is_retroactive.py index 020dbd2e9e..ad8daa9c5b 100755 --- a/test/functional/feature_llmq_is_retroactive.py +++ b/test/functional/feature_llmq_is_retroactive.py @@ -116,7 +116,7 @@ class LLMQ_IS_RetroactiveSigning(DashTestFramework): # Make node0 consider the TX as safe self.bump_mocktime(10 * 60 + 1) block = self.nodes[0].generate(1)[0] - assert(txid in self.nodes[0].getblock(block, 1)['tx']) + assert txid in self.nodes[0].getblock(block, 1)['tx'] self.wait_for_chainlocked_block_all_nodes(block) self.log.info("testing retroactive signing with partially known TX and all nodes session timeout") @@ -162,7 +162,7 @@ class LLMQ_IS_RetroactiveSigning(DashTestFramework): # Make node 0 consider the TX as safe self.bump_mocktime(10 * 60 + 1) block = self.nodes[0].generate(1)[0] - assert(txid in self.nodes[0].getblock(block, 1)['tx']) + assert txid in self.nodes[0].getblock(block, 1)['tx'] self.wait_for_chainlocked_block_all_nodes(block) def test_single_node_session_timeout(self, do_cycle_llmqs): @@ -194,7 +194,7 @@ class LLMQ_IS_RetroactiveSigning(DashTestFramework): # Make node 0 consider the TX as safe self.bump_mocktime(10 * 60 + 1) block = self.nodes[0].generate(1)[0] - assert(txid in self.nodes[0].getblock(block, 1)['tx']) + assert txid in self.nodes[0].getblock(block, 1)['tx'] self.wait_for_chainlocked_block_all_nodes(block) if __name__ == '__main__': diff --git a/test/functional/feature_llmq_signing.py b/test/functional/feature_llmq_signing.py index f2e747a64f..e51e34bff1 100755 --- a/test/functional/feature_llmq_signing.py +++ b/test/functional/feature_llmq_signing.py @@ -55,7 +55,7 @@ class LLMQSigningTest(DashTestFramework): wait_until(lambda: check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout) def assert_sigs_nochange(hasrecsigs, isconflicting1, isconflicting2, timeout): - assert(not wait_until(lambda: not check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout, do_assert = False)) + assert not wait_until(lambda: not check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout, do_assert = False) # Initial state wait_for_sigs(False, False, False, 1) @@ -65,11 +65,11 @@ class LLMQSigningTest(DashTestFramework): assert_sigs_nochange(False, False, False, 3) # Sign second share and test optional quorumHash parameter, should not result in recovered sig # 1. Providing an invalid quorum hash should fail and cause no changes for sigs - assert(not self.mninfo[1].node.quorum("sign", 100, id, msgHash, msgHash)) + assert not self.mninfo[1].node.quorum("sign", 100, id, msgHash, msgHash) assert_sigs_nochange(False, False, False, 3) # 2. Providing a valid quorum hash should succeed and cause no changes for sigss quorumHash = self.mninfo[1].node.quorum("selectquorum", 100, id)["quorumHash"] - assert(self.mninfo[1].node.quorum("sign", 100, id, msgHash, quorumHash)) + assert self.mninfo[1].node.quorum("sign", 100, id, msgHash, quorumHash) assert_sigs_nochange(False, False, False, 3) # Sign third share and test optional submit parameter if spork21 is enabled, should result in recovered sig # and conflict for msgHashConflict @@ -115,13 +115,13 @@ class LLMQSigningTest(DashTestFramework): height = node.getblockcount() height_bad = node.getblockheader(recsig["quorumHash"])["height"] hash_bad = node.getblockhash(0) - assert(node.quorum("verify", 100, id, msgHash, recsig["sig"])) - assert(node.quorum("verify", 100, id, msgHash, recsig["sig"], "", height)) - assert(not node.quorum("verify", 100, id, msgHashConflict, recsig["sig"])) + assert node.quorum("verify", 100, id, msgHash, recsig["sig"]) + assert node.quorum("verify", 100, id, msgHash, recsig["sig"], "", height) + assert not node.quorum("verify", 100, id, msgHashConflict, recsig["sig"]) assert not node.quorum("verify", 100, id, msgHash, recsig["sig"], "", height_bad) # Use specific quorum - assert(node.quorum("verify", 100, id, msgHash, recsig["sig"], recsig["quorumHash"])) - assert(not node.quorum("verify", 100, id, msgHashConflict, recsig["sig"], recsig["quorumHash"])) + assert node.quorum("verify", 100, id, msgHash, recsig["sig"], recsig["quorumHash"]) + assert not node.quorum("verify", 100, id, msgHashConflict, recsig["sig"], recsig["quorumHash"]) assert_raises_rpc_error(-8, "quorum not found", node.quorum, "verify", 100, id, msgHash, recsig["sig"], hash_bad) # Mine one more quorum, so that we have 2 active ones, nothing should change diff --git a/test/functional/feature_llmq_simplepose.py b/test/functional/feature_llmq_simplepose.py index 54e2eced61..56c0d67f6f 100755 --- a/test/functional/feature_llmq_simplepose.py +++ b/test/functional/feature_llmq_simplepose.py @@ -90,7 +90,7 @@ class LLMQSimplePoSeTest(DashTestFramework): for i in range(3): self.mine_quorum(expected_connections=expected_connections) for mn in self.mninfo: - assert(not self.check_punished(mn) and not self.check_banned(mn)) + assert not self.check_punished(mn) and not self.check_banned(mn) def test_banning(self, invalidate_proc, expected_connections): mninfos_online = self.mninfo.copy() @@ -108,7 +108,7 @@ class LLMQSimplePoSeTest(DashTestFramework): self.reset_probe_timeouts() self.mine_quorum(expected_connections=expected_connections, expected_members=expected_contributors, expected_contributions=expected_contributors, expected_complaints=expected_contributors-1, expected_commitments=expected_contributors, mninfos_online=mninfos_online, mninfos_valid=mninfos_valid) - assert(self.check_banned(mn)) + assert self.check_banned(mn) if not went_offline: # we do not include PoSe banned mns in quorums, so the next one should have 1 contributor less @@ -124,7 +124,7 @@ class LLMQSimplePoSeTest(DashTestFramework): # Make sure this tx "safe" to mine even when InstantSend and ChainLocks are no longer functional self.bump_mocktime(60 * 10 + 1) self.nodes[0].generate(1) - assert(not self.check_banned(mn)) + assert not self.check_banned(mn) if restart: self.stop_node(mn.node.index) diff --git a/test/functional/feature_multikeysporks.py b/test/functional/feature_multikeysporks.py index 5419a6b92f..fe889a9966 100755 --- a/test/functional/feature_multikeysporks.py +++ b/test/functional/feature_multikeysporks.py @@ -77,7 +77,7 @@ class MultiKeySporkTest(BitcoinTestFramework): def test_spork(self, spork_name, final_value): # check test spork default state for node in self.nodes: - assert(self.get_test_spork_value(node, spork_name) == 4070908800) + assert self.get_test_spork_value(node, spork_name) == 4070908800 self.bump_mocktime(1) # first and second signers set spork value @@ -86,11 +86,11 @@ class MultiKeySporkTest(BitcoinTestFramework): # spork change requires at least 3 signers time.sleep(10) for node in self.nodes: - assert(self.get_test_spork_value(node, spork_name) != 1) + assert self.get_test_spork_value(node, spork_name) != 1 # restart with no extra args to trigger CheckAndRemove self.restart_node(0) - assert(self.get_test_spork_value(self.nodes[0], spork_name) != 1) + assert self.get_test_spork_value(self.nodes[0], spork_name) != 1 # restart again with corect_params, should resync spork parts from other nodes self.restart_node(0, self.node0_extra_args) @@ -105,7 +105,7 @@ class MultiKeySporkTest(BitcoinTestFramework): # restart with no extra args to trigger CheckAndRemove, should reset the spork back to its default self.restart_node(0) - assert(self.get_test_spork_value(self.nodes[0], spork_name) == 4070908800) + assert self.get_test_spork_value(self.nodes[0], spork_name) == 4070908800 # restart again with corect_params, should resync sporks from other nodes self.restart_node(0, self.node0_extra_args) @@ -127,8 +127,8 @@ class MultiKeySporkTest(BitcoinTestFramework): self.test_spork('SPORK_2_INSTANTSEND_ENABLED', 2) self.test_spork('SPORK_3_INSTANTSEND_BLOCK_FILTERING', 3) for node in self.nodes: - assert(self.get_test_spork_value(node, 'SPORK_2_INSTANTSEND_ENABLED') == 2) - assert(self.get_test_spork_value(node, 'SPORK_3_INSTANTSEND_BLOCK_FILTERING') == 3) + assert self.get_test_spork_value(node, 'SPORK_2_INSTANTSEND_ENABLED') == 2 + assert self.get_test_spork_value(node, 'SPORK_3_INSTANTSEND_BLOCK_FILTERING') == 3 if __name__ == '__main__': diff --git a/test/functional/feature_new_quorum_type_activation.py b/test/functional/feature_new_quorum_type_activation.py index ff69ce50a0..42636b039d 100755 --- a/test/functional/feature_new_quorum_type_activation.py +++ b/test/functional/feature_new_quorum_type_activation.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2020 The Dash Core developers +# Copyright (c) 2020-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework @@ -25,17 +25,17 @@ class NewQuorumTypeActivationTest(BitcoinTestFramework): assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'started') ql = self.nodes[0].quorum("list") assert_equal(len(ql), 1) - assert("llmq_test_v17" not in ql) + assert "llmq_test_v17" not in ql self.nodes[0].generate(10) assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'locked_in') ql = self.nodes[0].quorum("list") assert_equal(len(ql), 1) - assert("llmq_test_v17" not in ql) + assert "llmq_test_v17" not in ql self.nodes[0].generate(10) assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'active') ql = self.nodes[0].quorum("list") assert_equal(len(ql), 2) - assert("llmq_test_v17" in ql) + assert "llmq_test_v17" in ql if __name__ == '__main__': diff --git a/test/functional/feature_nulldummy.py b/test/functional/feature_nulldummy.py index 94484ebf55..451a454e20 100755 --- a/test/functional/feature_nulldummy.py +++ b/test/functional/feature_nulldummy.py @@ -17,7 +17,7 @@ from test_framework.blocktools import create_coinbase, create_block, create_tran from test_framework.messages import CTransaction from test_framework.script import CScript from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str +from test_framework.util import assert_equal, assert_raises_rpc_error NULLDUMMY_ERROR = "non-mandatory-script-verify-flag (Dummy CHECKMULTISIG argument must be zero) (code 64)" @@ -27,7 +27,7 @@ def trueDummy(tx): newscript = [] for i in scriptSig: if (len(newscript) == 0): - assert(len(i) == 0) + assert len(i) == 0 newscript.append(b'\x51') else: newscript.append(i) @@ -57,15 +57,15 @@ class NULLDUMMYTest(BitcoinTestFramework): self.log.info("Test 1: NULLDUMMY compliant base transactions should be accepted to mempool and mined before activation [430]") test1txs = [create_transaction(self.nodes[0], coinbase_txid[0], self.ms_address, 49)] - txid1 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[0].serialize()), True) + txid1 = self.nodes[0].sendrawtransaction(test1txs[0].serialize().hex(), True) test1txs.append(create_transaction(self.nodes[0], txid1, self.ms_address, 48)) - txid2 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[1].serialize()), True) + txid2 = self.nodes[0].sendrawtransaction(test1txs[1].serialize().hex(), True) self.block_submit(self.nodes[0], test1txs, True) self.log.info("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation") test2tx = create_transaction(self.nodes[0], txid2, self.ms_address, 47) trueDummy(test2tx) - assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test2tx.serialize()), True) + assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, test2tx.serialize().hex(), True) self.log.info("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]") self.block_submit(self.nodes[0], [test2tx], True) @@ -74,12 +74,12 @@ class NULLDUMMYTest(BitcoinTestFramework): test4tx = create_transaction(self.nodes[0], test2tx.hash, self.address, 46) test6txs=[CTransaction(test4tx)] trueDummy(test4tx) - assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test4tx.serialize()), True) + assert_raises_rpc_error(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, test4tx.serialize().hex(), True) self.block_submit(self.nodes[0], [test4tx]) self.log.info("Test 6: NULLDUMMY compliant transactions should be accepted to mempool and in block after activation [432]") for i in test6txs: - self.nodes[0].sendrawtransaction(bytes_to_hex_str(i.serialize()), True) + self.nodes[0].sendrawtransaction(i.serialize().hex(), True) self.block_submit(self.nodes[0], test6txs, True) @@ -93,7 +93,7 @@ class NULLDUMMYTest(BitcoinTestFramework): block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() - node.submitblock(bytes_to_hex_str(block.serialize())) + node.submitblock(block.serialize().hex()) if (accept): assert_equal(node.getbestblockhash(), block.hash) self.tip = block.sha256 diff --git a/test/functional/feature_proxy.py b/test/functional/feature_proxy.py index 707f4fc7f3..75259b49b3 100755 --- a/test/functional/feature_proxy.py +++ b/test/functional/feature_proxy.py @@ -94,7 +94,7 @@ class ProxyTest(BitcoinTestFramework): # Test: outgoing IPv4 connection through node node.addnode("15.61.23.23:1234", "onetry") cmd = proxies[0].queue.get() - assert(isinstance(cmd, Socks5Command)) + assert isinstance(cmd, Socks5Command) # Note: dashd's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6 assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"15.61.23.23") @@ -108,7 +108,7 @@ class ProxyTest(BitcoinTestFramework): # Test: outgoing IPv6 connection through node node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry") cmd = proxies[1].queue.get() - assert(isinstance(cmd, Socks5Command)) + assert isinstance(cmd, Socks5Command) # Note: dashd's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6 assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534") @@ -122,7 +122,7 @@ class ProxyTest(BitcoinTestFramework): # Test: outgoing onion connection through node node.addnode("bitcoinostk4e4re.onion:8333", "onetry") cmd = proxies[2].queue.get() - assert(isinstance(cmd, Socks5Command)) + assert isinstance(cmd, Socks5Command) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"bitcoinostk4e4re.onion") assert_equal(cmd.port, 8333) @@ -134,7 +134,7 @@ class ProxyTest(BitcoinTestFramework): # Test: outgoing DNS name connection through node node.addnode("node.noumenon:8333", "onetry") cmd = proxies[3].queue.get() - assert(isinstance(cmd, Socks5Command)) + assert isinstance(cmd, Socks5Command) assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.addr, b"node.noumenon") assert_equal(cmd.port, 8333) diff --git a/test/functional/feature_pruning.py b/test/functional/feature_pruning.py index 9a10dcfa6f..046357b796 100755 --- a/test/functional/feature_pruning.py +++ b/test/functional/feature_pruning.py @@ -144,7 +144,7 @@ class PruneTest(BitcoinTestFramework): self.nodes[1].invalidateblock(curhash) curhash = self.nodes[1].getblockhash(invalidheight - 1) - assert(self.nodes[1].getblockcount() == invalidheight - 1) + assert self.nodes[1].getblockcount() == invalidheight - 1 self.log.info("New best height: %d" % self.nodes[1].getblockcount()) # Mine one block to avoid automatic recovery from forks on restart @@ -214,17 +214,17 @@ class PruneTest(BitcoinTestFramework): blocks_to_mine = first_reorg_height + 1 - self.mainchainheight self.log.info("Rewind node 0 to prev main chain to mine longer chain to trigger redownload. Blocks needed: %d" % blocks_to_mine) self.nodes[0].invalidateblock(curchainhash) - assert(self.nodes[0].getblockcount() == self.mainchainheight) - assert(self.nodes[0].getbestblockhash() == self.mainchainhash2) + assert self.nodes[0].getblockcount() == self.mainchainheight + assert self.nodes[0].getbestblockhash() == self.mainchainhash2 goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1] goalbestheight = first_reorg_height + 1 self.log.info("Verify node 2 reorged back to the main chain, some blocks of which it had to redownload") # Wait for Node 2 to reorg to proper height wait_until(lambda: self.nodes[2].getblockcount() >= goalbestheight, timeout=900) - assert(self.nodes[2].getbestblockhash() == goalbesthash) + assert self.nodes[2].getbestblockhash() == goalbesthash # Verify we can now have the data for a block previously pruned - assert(self.nodes[2].getblock(self.forkhash)["height"] == self.forkheight) + assert self.nodes[2].getblock(self.forkhash)["height"] == self.forkheight def manual_test(self, node_number, use_timestamp): # at this point, node has 995 blocks and has not yet run in prune mode diff --git a/test/functional/feature_spentindex.py b/test/functional/feature_spentindex.py index 913f872312..ad83842889 100755 --- a/test/functional/feature_spentindex.py +++ b/test/functional/feature_spentindex.py @@ -72,7 +72,7 @@ class SpentIndexTest(BitcoinTestFramework): tx.vout = [CTxOut(amount, scriptPubKey)] tx.rehash() - signed_tx = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) + signed_tx = self.nodes[0].signrawtransactionwithwallet(tx.serialize().hex()) txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True) self.nodes[0].generate(1) self.sync_all() @@ -107,7 +107,7 @@ class SpentIndexTest(BitcoinTestFramework): tx2.vout = [CTxOut(amount - int(COIN / 10), scriptPubKey2)] tx2.rehash() self.nodes[0].importprivkey(privkey) - signed_tx2 = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx2.serialize()).decode("utf-8")) + signed_tx2 = self.nodes[0].signrawtransactionwithwallet(tx2.serialize().hex()) txid2 = self.nodes[0].sendrawtransaction(signed_tx2["hex"], True) # Check the mempool index diff --git a/test/functional/feature_sporks.py b/test/functional/feature_sporks.py index 13e507c96d..0f1d2d1da7 100755 --- a/test/functional/feature_sporks.py +++ b/test/functional/feature_sporks.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (c) 2018-2020 The Dash Core developers +# Copyright (c) 2018-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -37,8 +37,8 @@ class SporkTest(BitcoinTestFramework): def run_test(self): spork_default_state = self.get_test_spork_state(self.nodes[0]) # check test spork default state matches on all nodes - assert(self.get_test_spork_state(self.nodes[1]) == spork_default_state) - assert(self.get_test_spork_state(self.nodes[2]) == spork_default_state) + assert self.get_test_spork_state(self.nodes[1]) == spork_default_state + assert self.get_test_spork_state(self.nodes[2]) == spork_default_state # check spork propagation for connected nodes spork_new_state = not spork_default_state @@ -50,8 +50,8 @@ class SporkTest(BitcoinTestFramework): self.stop_node(1) self.start_node(0) self.start_node(1) - assert(self.get_test_spork_state(self.nodes[0]) == spork_new_state) - assert(self.get_test_spork_state(self.nodes[1]) == spork_new_state) + assert self.get_test_spork_state(self.nodes[0]) == spork_new_state + assert self.get_test_spork_state(self.nodes[1]) == spork_new_state # Generate one block to kick off masternode sync, which also starts sporks syncing for node2 self.nodes[1].generate(1) diff --git a/test/functional/feature_txindex.py b/test/functional/feature_txindex.py index 25eca0251f..d8c64d8f44 100755 --- a/test/functional/feature_txindex.py +++ b/test/functional/feature_txindex.py @@ -55,7 +55,7 @@ class TxIndexTest(BitcoinTestFramework): tx.vout = [CTxOut(amount, scriptPubKey)] tx.rehash() - signed_tx = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) + signed_tx = self.nodes[0].signrawtransactionwithwallet(tx.serialize().hex()) txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True) self.nodes[0].generate(1) self.sync_all() diff --git a/test/functional/feature_versionbits_warning.py b/test/functional/feature_versionbits_warning.py index 4b88ecfd47..4152b60524 100755 --- a/test/functional/feature_versionbits_warning.py +++ b/test/functional/feature_versionbits_warning.py @@ -74,8 +74,8 @@ class VersionBitsWarningTest(BitcoinTestFramework): node.generate(VB_PERIOD - VB_THRESHOLD + 1) # Check that we're not getting any versionbit-related errors in get*info() - assert(not VB_PATTERN.match(node.getmininginfo()["warnings"])) - assert(not VB_PATTERN.match(node.getnetworkinfo()["warnings"])) + assert not VB_PATTERN.match(node.getmininginfo()["warnings"]) + assert not VB_PATTERN.match(node.getnetworkinfo()["warnings"]) self.log.info("Check that there is a warning if >50 blocks in the last 100 were an unknown version") # Build one period of blocks with VB_THRESHOLD blocks signaling some unknown bit @@ -83,8 +83,8 @@ class VersionBitsWarningTest(BitcoinTestFramework): node.generate(VB_PERIOD - VB_THRESHOLD) # Check that get*info() shows the 51/100 unknown block version error. - assert(WARN_UNKNOWN_RULES_MINED in node.getmininginfo()["warnings"]) - assert(WARN_UNKNOWN_RULES_MINED in node.getnetworkinfo()["warnings"]) + assert WARN_UNKNOWN_RULES_MINED in node.getmininginfo()["warnings"] + assert WARN_UNKNOWN_RULES_MINED in node.getnetworkinfo()["warnings"] self.log.info("Check that there is a warning if previous VB_BLOCKS have >=VB_THRESHOLD blocks with unknown versionbits version.") # Mine a period worth of expected blocks so the generic block-version warning @@ -100,8 +100,8 @@ class VersionBitsWarningTest(BitcoinTestFramework): # Generating one more block will be enough to generate an error. node.generate(1) # Check that get*info() shows the versionbits unknown rules warning - assert(WARN_UNKNOWN_RULES_ACTIVE in node.getmininginfo()["warnings"]) - assert(WARN_UNKNOWN_RULES_ACTIVE in node.getnetworkinfo()["warnings"]) + assert WARN_UNKNOWN_RULES_ACTIVE in node.getmininginfo()["warnings"] + assert WARN_UNKNOWN_RULES_ACTIVE in node.getnetworkinfo()["warnings"] # Check that the alert file shows the versionbits unknown rules warning wait_until(lambda: self.versionbits_in_alert_file(), timeout=60) diff --git a/test/functional/interface_bitcoin_cli.py b/test/functional/interface_bitcoin_cli.py index 7f2646797a..6f052df990 100755 --- a/test/functional/interface_bitcoin_cli.py +++ b/test/functional/interface_bitcoin_cli.py @@ -16,7 +16,7 @@ class TestBitcoinCli(BitcoinTestFramework): """Main test logic""" cli_response = self.nodes[0].cli("-version").send_cli() - assert("Dash Core RPC client version" in cli_response) + assert "Dash Core RPC client version" in cli_response self.log.info("Compare responses from getwalletinfo RPC and `dash-cli getwalletinfo`") cli_response = self.nodes[0].cli.getwalletinfo() diff --git a/test/functional/interface_http.py b/test/functional/interface_http.py index 0222e6c77e..f7d46cae54 100755 --- a/test/functional/interface_http.py +++ b/test/functional/interface_http.py @@ -30,14 +30,14 @@ class HTTPBasicsTest (BitcoinTestFramework): conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) - assert(conn.sock!=None) #according to http/1.1 connection must still be open! + assert b'"error":null' in out1 + assert conn.sock!=None #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) #must also response with a correct json-rpc message - assert(conn.sock!=None) #according to http/1.1 connection must still be open! + assert b'"error":null' in out1 #must also response with a correct json-rpc message + assert conn.sock!=None #according to http/1.1 connection must still be open! conn.close() #same should be if we add keep-alive because this should be the std. behaviour @@ -47,14 +47,14 @@ class HTTPBasicsTest (BitcoinTestFramework): conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) - assert(conn.sock!=None) #according to http/1.1 connection must still be open! + assert b'"error":null' in out1 + assert conn.sock!=None #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) #must also response with a correct json-rpc message - assert(conn.sock!=None) #according to http/1.1 connection must still be open! + assert b'"error":null' in out1 #must also response with a correct json-rpc message + assert conn.sock!=None #according to http/1.1 connection must still be open! conn.close() #now do the same with "Connection: close" @@ -64,8 +64,8 @@ class HTTPBasicsTest (BitcoinTestFramework): conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) - assert(conn.sock==None) #now the connection must be closed after the response + assert b'"error":null' in out1 + assert conn.sock==None #now the connection must be closed after the response #node1 (2nd node) is running with disabled keep-alive option urlNode1 = urllib.parse.urlparse(self.nodes[1].url) @@ -76,7 +76,7 @@ class HTTPBasicsTest (BitcoinTestFramework): conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) + assert b'"error":null' in out1 #node2 (third node) is running with standard keep-alive parameters which means keep-alive is on urlNode2 = urllib.parse.urlparse(self.nodes[2].url) @@ -87,8 +87,8 @@ class HTTPBasicsTest (BitcoinTestFramework): conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() - assert(b'"error":null' in out1) - assert(conn.sock!=None) #connection must be closed because dashd should use keep-alive by default + assert b'"error":null' in out1 + assert conn.sock!=None #connection must be closed because dashd should use keep-alive by default # Check excessive request size conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port) diff --git a/test/functional/interface_rest.py b/test/functional/interface_rest.py index 1ea4a9aa94..6ca1a1666f 100755 --- a/test/functional/interface_rest.py +++ b/test/functional/interface_rest.py @@ -141,7 +141,7 @@ class RESTTest (BitcoinTestFramework): bin_response = self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body=bin_request, ret_type=RetType.BYTES) output = BytesIO(bin_response) chain_height, = unpack("i", output.read(4)) - response_hash = binascii.hexlify(output.read(32)[::-1]).decode('ascii') + response_hash = output.read(32)[::-1].hex() assert_equal(bb_hash, response_hash) # check if getutxo's chaintip during calculation was fine assert_equal(chain_height, 102) # chain height must be 102 @@ -241,7 +241,7 @@ class RESTTest (BitcoinTestFramework): resp_hex = self.test_rest_request("/blockhashbyheight/{}".format(block_json_obj['height']), req_type=ReqType.HEX, ret_type=RetType.OBJ) assert_equal(resp_hex.read().decode('utf-8').rstrip(), bb_hash) resp_bytes = self.test_rest_request("/blockhashbyheight/{}".format(block_json_obj['height']), req_type=ReqType.BIN, ret_type=RetType.BYTES) - blockhash = binascii.hexlify(resp_bytes[::-1]).decode('utf-8') + blockhash = resp_bytes[::-1].hex() assert_equal(blockhash, bb_hash) # Check invalid blockhashbyheight requests diff --git a/test/functional/interface_zmq.py b/test/functional/interface_zmq.py index dabae122fc..79bc98438f 100755 --- a/test/functional/interface_zmq.py +++ b/test/functional/interface_zmq.py @@ -11,7 +11,6 @@ from test_framework.test_framework import ( BitcoinTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq) from test_framework.messages import dashhash from test_framework.util import (assert_equal, - bytes_to_hex_str, hash256, ) @@ -95,10 +94,10 @@ class ZMQTest (BitcoinTestFramework): assert_equal(hash256(hex), txid) # Should receive the generated block hash. - hash = bytes_to_hex_str(self.hashblock.receive()) + hash = self.hashblock.receive().hex() assert_equal(genhashes[x], hash) # The block should only have the coinbase txid. - assert_equal([bytes_to_hex_str(txid)], self.nodes[1].getblock(hash)["tx"]) + assert_equal([txid.hex()], self.nodes[1].getblock(hash)["tx"]) # Should receive the generated raw block. block = self.rawblock.receive() @@ -110,11 +109,11 @@ class ZMQTest (BitcoinTestFramework): # Should receive the broadcasted txid. txid = self.hashtx.receive() - assert_equal(payment_txid, bytes_to_hex_str(txid)) + assert_equal(payment_txid, txid.hex()) # Should receive the broadcasted raw transaction. hex = self.rawtx.receive() - assert_equal(payment_txid, bytes_to_hex_str(hash256(hex))) + assert_equal(payment_txid, hash256(hex).hex()) self.log.info("Test the getzmqnotifications RPC") assert_equal(self.nodes[0].getzmqnotifications(), [ diff --git a/test/functional/interface_zmq_dash.py b/test/functional/interface_zmq_dash.py index 6894b65515..4941eaa38a 100755 --- a/test/functional/interface_zmq_dash.py +++ b/test/functional/interface_zmq_dash.py @@ -19,7 +19,7 @@ finally: from test_framework.test_framework import ( DashTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq) from test_framework.mininode import P2PInterface -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str +from test_framework.util import assert_equal, assert_raises_rpc_error from test_framework.messages import ( CBlock, CGovernanceObject, @@ -154,7 +154,7 @@ class DashZMQTest (DashTestFramework): # Make sure the recovered sig exists by RPC rpc_recovered_sig = self.get_recovered_sig(request_id, msg_hash) # Validate hashrecoveredsig - zmq_recovered_sig_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_recovered_sig).read(32)) + zmq_recovered_sig_hash = self.receive(ZMQPublisher.hash_recovered_sig).read(32).hex() assert_equal(zmq_recovered_sig_hash, msg_hash) # Validate rawrecoveredsig zmq_recovered_sig_raw = CRecoveredSig() @@ -163,7 +163,7 @@ class DashZMQTest (DashTestFramework): assert_equal(uint256_to_string(zmq_recovered_sig_raw.quorumHash), rpc_recovered_sig['quorumHash']) assert_equal(uint256_to_string(zmq_recovered_sig_raw.id), rpc_recovered_sig['id']) assert_equal(uint256_to_string(zmq_recovered_sig_raw.msgHash), rpc_recovered_sig['msgHash']) - assert_equal(bytes_to_hex_str(zmq_recovered_sig_raw.sig), rpc_recovered_sig['sig']) + assert_equal(zmq_recovered_sig_raw.sig.hex(), rpc_recovered_sig['sig']) recovered_sig_publishers = [ ZMQPublisher.hash_recovered_sig, @@ -208,24 +208,24 @@ class DashZMQTest (DashTestFramework): rpc_chain_lock_hash = rpc_chain_locked_block["hash"] assert_equal(generated_hash, rpc_chain_lock_hash) # Validate hashchainlock - zmq_chain_lock_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_chain_lock).read(32)) + zmq_chain_lock_hash = self.receive(ZMQPublisher.hash_chain_lock).read(32).hex() assert_equal(zmq_chain_lock_hash, rpc_best_chain_lock_hash) # Validate rawchainlock zmq_chain_locked_block = CBlock() zmq_chain_locked_block.deserialize(self.receive(ZMQPublisher.raw_chain_lock)) - assert(zmq_chain_locked_block.is_valid()) + assert zmq_chain_locked_block.is_valid() assert_equal(zmq_chain_locked_block.hash, rpc_chain_lock_hash) # Validate rawchainlocksig zmq_chain_lock_sig_stream = self.receive(ZMQPublisher.raw_chain_lock_sig) zmq_chain_locked_block = CBlock() zmq_chain_locked_block.deserialize(zmq_chain_lock_sig_stream) - assert(zmq_chain_locked_block.is_valid()) + assert zmq_chain_locked_block.is_valid() zmq_chain_lock = msg_clsig() zmq_chain_lock.deserialize(zmq_chain_lock_sig_stream) assert_equal(zmq_chain_lock.height, rpc_chain_lock_height) assert_equal(uint256_to_string(zmq_chain_lock.blockHash), rpc_chain_lock_hash) assert_equal(zmq_chain_locked_block.hash, rpc_chain_lock_hash) - assert_equal(bytes_to_hex_str(zmq_chain_lock.sig), rpc_best_chain_lock_sig) + assert_equal(zmq_chain_lock.sig.hex(), rpc_best_chain_lock_sig) # Unsubscribe from ChainLock messages self.unsubscribe(chain_lock_publishers) @@ -251,18 +251,18 @@ class DashZMQTest (DashTestFramework): rpc_raw_tx_1_hash = self.nodes[0].sendrawtransaction(rpc_raw_tx_1['hex']) self.wait_for_instantlock(rpc_raw_tx_1_hash, self.nodes[0]) # Validate hashtxlock - zmq_tx_lock_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_tx_lock).read(32)) + zmq_tx_lock_hash = self.receive(ZMQPublisher.hash_tx_lock).read(32).hex() assert_equal(zmq_tx_lock_hash, rpc_raw_tx_1['txid']) # Validate rawtxlock zmq_tx_lock_raw = CTransaction() zmq_tx_lock_raw.deserialize(self.receive(ZMQPublisher.raw_tx_lock)) - assert(zmq_tx_lock_raw.is_valid()) + assert zmq_tx_lock_raw.is_valid() assert_equal(zmq_tx_lock_raw.hash, rpc_raw_tx_1['txid']) # Validate rawtxlocksig zmq_tx_lock_sig_stream = self.receive(ZMQPublisher.raw_tx_lock_sig) zmq_tx_lock_tx = CTransaction() zmq_tx_lock_tx.deserialize(zmq_tx_lock_sig_stream) - assert(zmq_tx_lock_tx.is_valid()) + assert zmq_tx_lock_tx.is_valid() assert_equal(zmq_tx_lock_tx.hash, rpc_raw_tx_1['txid']) zmq_tx_lock = msg_islock() zmq_tx_lock.deserialize(zmq_tx_lock_sig_stream) @@ -271,18 +271,18 @@ class DashZMQTest (DashTestFramework): # which already got the InstantSend lock. assert_raises_rpc_error(-26, "tx-txlock-conflict", self.nodes[0].sendrawtransaction, rpc_raw_tx_2['hex']) # Validate hashinstantsenddoublespend - zmq_double_spend_hash2 = bytes_to_hex_str(self.receive(ZMQPublisher.hash_instantsend_doublespend).read(32)) - zmq_double_spend_hash1 = bytes_to_hex_str(self.receive(ZMQPublisher.hash_instantsend_doublespend).read(32)) + zmq_double_spend_hash2 = self.receive(ZMQPublisher.hash_instantsend_doublespend).read(32).hex() + zmq_double_spend_hash1 = self.receive(ZMQPublisher.hash_instantsend_doublespend).read(32).hex() assert_equal(zmq_double_spend_hash2, rpc_raw_tx_2['txid']) assert_equal(zmq_double_spend_hash1, rpc_raw_tx_1['txid']) # Validate rawinstantsenddoublespend zmq_double_spend_tx_2 = CTransaction() zmq_double_spend_tx_2.deserialize(self.receive(ZMQPublisher.raw_instantsend_doublespend)) - assert (zmq_double_spend_tx_2.is_valid()) + assert zmq_double_spend_tx_2.is_valid() assert_equal(zmq_double_spend_tx_2.hash, rpc_raw_tx_2['txid']) zmq_double_spend_tx_1 = CTransaction() zmq_double_spend_tx_1.deserialize(self.receive(ZMQPublisher.raw_instantsend_doublespend)) - assert(zmq_double_spend_tx_1.is_valid()) + assert zmq_double_spend_tx_1.is_valid() assert_equal(zmq_double_spend_tx_1.hash, rpc_raw_tx_1['txid']) # No islock notifications when tx is not received yet self.nodes[0].generate(1) @@ -293,7 +293,7 @@ class DashZMQTest (DashTestFramework): time.sleep(1) try: self.receive(ZMQPublisher.hash_tx_lock, zmq.NOBLOCK) - assert(False) + assert False except zmq.ZMQError: # this is expected pass @@ -301,7 +301,7 @@ class DashZMQTest (DashTestFramework): self.test_node.send_tx(FromHex(msg_tx(), rpc_raw_tx_3['hex'])) self.wait_for_instantlock(rpc_raw_tx_3['txid'], self.nodes[0]) # Validate hashtxlock - zmq_tx_lock_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_tx_lock).read(32)) + zmq_tx_lock_hash = self.receive(ZMQPublisher.hash_tx_lock).read(32).hex() assert_equal(zmq_tx_lock_hash, rpc_raw_tx_3['txid']) # Drop test node connection self.nodes[0].disconnect_p2ps() @@ -337,7 +337,7 @@ class DashZMQTest (DashTestFramework): self.sync_blocks() rpc_proposal_hash = self.nodes[0].gobject("submit", "0", proposal_rev, proposal_time, proposal_hex, collateral) # Validate hashgovernanceobject - zmq_governance_object_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_governance_object).read(32)) + zmq_governance_object_hash = self.receive(ZMQPublisher.hash_governance_object).read(32).hex() assert_equal(zmq_governance_object_hash, rpc_proposal_hash) zmq_governance_object_raw = CGovernanceObject() zmq_governance_object_raw.deserialize(self.receive(ZMQPublisher.raw_governance_object)) @@ -365,8 +365,8 @@ class DashZMQTest (DashTestFramework): self.nodes[0].gobject("vote-many", rpc_proposal_hash, map_vote_signals[1], map_vote_outcomes[1]) rpc_proposal_votes = self.nodes[0].gobject('getcurrentvotes', rpc_proposal_hash) # Validate hashgovernancevote - zmq_governance_vote_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_governance_vote).read(32)) - assert(zmq_governance_vote_hash in rpc_proposal_votes) + zmq_governance_vote_hash = self.receive(ZMQPublisher.hash_governance_vote).read(32).hex() + assert zmq_governance_vote_hash in rpc_proposal_votes # Validate rawgovernancevote zmq_governance_vote_raw = CGovernanceVote() zmq_governance_vote_raw.deserialize(self.receive(ZMQPublisher.raw_governance_vote)) diff --git a/test/functional/mempool_accept.py b/test/functional/mempool_accept.py index 2fb6e81542..0da10ed65e 100755 --- a/test/functional/mempool_accept.py +++ b/test/functional/mempool_accept.py @@ -26,7 +26,6 @@ from test_framework.script import ( from test_framework.util import ( assert_equal, assert_raises_rpc_error, - bytes_to_hex_str, hex_str_to_bytes, wait_until, ) @@ -99,7 +98,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vout[0].nValue -= int(fee * COIN) # Double the fee tx.vin[0].nSequence = BIP125_SEQUENCE_NUMBER + 1 # Now, opt out of RBF - raw_tx_0_reject = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex'] + raw_tx_0_reject = node.signrawtransactionwithwallet(tx.serialize().hex())['hex'] tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0_reject))) txid_0_reject = tx.rehash() self.check_mempool_result( @@ -110,14 +109,14 @@ class MempoolAcceptanceTest(BitcoinTestFramework): self.log.info('A transaction that conflicts with an unconfirmed tx') # Send the transaction that replaces the mempool transaction and opts out of replaceability - # node.sendrawtransaction(hexstring=bytes_to_hex_str(tx.serialize()), allowhighfees=True) + # node.sendrawtransaction(hexstring=tx.serialize().hex(), allowhighfees=True) # take original raw_tx_0 tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vout[0].nValue -= int(4 * fee * COIN) # Set more fee # skip re-signing the tx self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '18: txn-mempool-conflict'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], allowhighfees=True, ) @@ -127,13 +126,13 @@ class MempoolAcceptanceTest(BitcoinTestFramework): # skip re-signing the tx self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'missing-inputs'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction with missing inputs, that existed once in the past') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.vin[0].prevout.n = 1 # Set vout to 1, to spend the other outpoint (49 coins) of the in-chain-tx we want to double spend - raw_tx_1 = node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex'] + raw_tx_1 = node.signrawtransactionwithwallet(tx.serialize().hex())['hex'] txid_1 = node.sendrawtransaction(hexstring=raw_tx_1, allowhighfees=True) # Now spend both to "clearly hide" the outputs, ie. remove the coins from the utxo set by spending them raw_tx_spend_both = node.signrawtransactionwithwallet(node.createrawtransaction( @@ -165,17 +164,17 @@ class MempoolAcceptanceTest(BitcoinTestFramework): # Reference tx should be valid on itself self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': True}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction with no outputs') tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout = [] # Skip re-signing the transaction for context independent checks from now on - # tx.deserialize(BytesIO(hex_str_to_bytes(node.signrawtransactionwithwallet(bytes_to_hex_str(tx.serialize()))['hex']))) + # tx.deserialize(BytesIO(hex_str_to_bytes(node.signrawtransactionwithwallet(tx.serialize().hex())['hex']))) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-empty'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A really large transaction') @@ -183,7 +182,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vin = [tx.vin[0]] * math.ceil(MAX_BLOCK_SIZE / len(tx.vin[0].serialize())) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-oversize'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction with negative output value') @@ -191,7 +190,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout[0].nValue *= -1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-negative'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction with too large output value') @@ -199,7 +198,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout[0].nValue = 21000000 * COIN + 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-toolarge'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction with too large sum of output values') @@ -208,7 +207,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout[0].nValue = 21000000 * COIN self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-txouttotal-toolarge'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction with duplicate inputs') @@ -216,7 +215,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vin = [tx.vin[0]] * 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-inputs-duplicate'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A coinbase transaction') @@ -225,7 +224,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_coinbase_spent))) self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: coinbase'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('Some nonstandard transactions') @@ -233,19 +232,19 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.nVersion = 4 # A version currently non-standard self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: version'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].scriptPubKey = CScript([OP_0]) # Some non-standard script self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptpubkey'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].scriptSig = CScript([OP_HASH160]) # Some not-pushonly scriptSig self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptsig-not-pushonly'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vin[0].scriptSig = CScript([b'a' * 1648]) # Some too large scriptSig (>1650 bytes) @@ -259,21 +258,21 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.vout = [output_p2sh_burn] * num_scripts self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: tx-size'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0] = output_p2sh_burn tx.vout[0].nValue -= 1 # Make output smaller, such that it is dust for our policy self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: dust'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.vout[0].scriptPubKey = CScript([OP_RETURN, b'\xff']) tx.vout = [tx.vout[0]] * 2 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: multi-op-return'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A timelocked transaction') @@ -282,7 +281,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): tx.nLockTime = node.getblockcount() + 1 self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-final'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], ) self.log.info('A transaction that is locked by BIP68 sequence logic') @@ -291,7 +290,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework): # Can skip re-signing the tx because of early rejection self.check_mempool_result( result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-BIP68-final'}], - rawtxs=[bytes_to_hex_str(tx.serialize())], + rawtxs=[tx.serialize().hex()], allowhighfees=True, ) diff --git a/test/functional/mempool_limit.py b/test/functional/mempool_limit.py index d459bdbf70..b8aa1bfbe3 100755 --- a/test/functional/mempool_limit.py +++ b/test/functional/mempool_limit.py @@ -44,9 +44,9 @@ class MempoolLimitTest(BitcoinTestFramework): txids[i] = create_lots_of_big_transactions(self.nodes[0], txouts, utxos[30*i:30*i+30], 30, (i+1)*base_fee) self.log.info('The tx should be evicted by now') - assert(txid not in self.nodes[0].getrawmempool()) + assert txid not in self.nodes[0].getrawmempool() txdata = self.nodes[0].gettransaction(txid) - assert(txdata['confirmations'] == 0) #confirmation should still be 0 + assert txdata['confirmations'] == 0 #confirmation should still be 0 self.log.info('Check that mempoolminfee is larger than minrelytxfee') assert_equal(self.nodes[0].getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000')) diff --git a/test/functional/mempool_packages.py b/test/functional/mempool_packages.py index 5a657efc5b..ec34d16e09 100755 --- a/test/functional/mempool_packages.py +++ b/test/functional/mempool_packages.py @@ -30,7 +30,7 @@ class MempoolPackagesTest(BitcoinTestFramework): 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 + assert len(fulltx['vout']) == num_outputs # make sure we didn't generate a change output return (txid, send_value) def run_test(self): @@ -122,13 +122,13 @@ class MempoolPackagesTest(BitcoinTestFramework): assert_equal(len(v_ancestors), len(chain)-1) for x in v_ancestors.keys(): assert_equal(mempool[x], v_ancestors[x]) - assert(chain[-1] not in v_ancestors.keys()) + assert chain[-1] not in v_ancestors.keys() v_descendants = self.nodes[0].getmempooldescendants(chain[0], True) assert_equal(len(v_descendants), len(chain)-1) for x in v_descendants.keys(): assert_equal(mempool[x], v_descendants[x]) - assert(chain[0] not in v_descendants.keys()) + assert chain[0] not in v_descendants.keys() # Check that ancestor modified fees includes fee deltas from # prioritisetransaction diff --git a/test/functional/mempool_resurrect.py b/test/functional/mempool_resurrect.py index 94b038f8c3..841ba728ad 100755 --- a/test/functional/mempool_resurrect.py +++ b/test/functional/mempool_resurrect.py @@ -42,7 +42,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): assert_equal(set(self.nodes[0].getrawmempool()), set()) for txid in spends1_id+spends2_id: tx = self.nodes[0].gettransaction(txid) - assert(tx["confirmations"] > 0) + assert tx["confirmations"] > 0 # Use invalidateblock to re-org back for node in self.nodes: @@ -52,7 +52,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): assert_equal(set(self.nodes[0].getrawmempool()), set(spends1_id+spends2_id)) for txid in spends1_id+spends2_id: tx = self.nodes[0].gettransaction(txid) - assert(tx["confirmations"] == 0) + assert tx["confirmations"] == 0 # Generate another block, they should all get mined self.nodes[0].generate(1) @@ -60,7 +60,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework): assert_equal(set(self.nodes[0].getrawmempool()), set()) for txid in spends1_id+spends2_id: tx = self.nodes[0].gettransaction(txid) - assert(tx["confirmations"] > 0) + assert tx["confirmations"] > 0 if __name__ == '__main__': diff --git a/test/functional/mining_basic.py b/test/functional/mining_basic.py index 1072e0af0c..9af9838077 100755 --- a/test/functional/mining_basic.py +++ b/test/functional/mining_basic.py @@ -23,7 +23,6 @@ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, - bytes_to_hex_str as b2x, ) from test_framework.script import CScriptNum @@ -31,7 +30,7 @@ from test_framework.script import CScriptNum def assert_template(node, block, expect, rehash=True): if rehash: block.hashMerkleRoot = block.calc_merkle_root() - rsp = node.getblocktemplate(template_request={'data': b2x(block.serialize()), 'mode': 'proposal'}) + rsp = node.getblocktemplate(template_request={'data': block.serialize().hex(), 'mode': 'proposal'}) assert_equal(rsp, expect) @@ -85,7 +84,7 @@ class MiningTest(BitcoinTestFramework): assert_template(node, block, None) self.log.info("submitblock: Test block decode failure") - assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15])) + assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex()) self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) @@ -94,10 +93,10 @@ class MiningTest(BitcoinTestFramework): assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test invalid coinbase transaction") - assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize())) + assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex()) self.log.info("getblocktemplate: Test truncated final transaction") - assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'}) + assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': block.serialize()[:-1].hex(), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test duplicate transaction") bad_block = copy.deepcopy(block) @@ -124,7 +123,7 @@ class MiningTest(BitcoinTestFramework): bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 - assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'}) + assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': bad_block_sn.hex(), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) @@ -169,22 +168,22 @@ class MiningTest(BitcoinTestFramework): def chain_tip(b_hash, *, status='headers-only', branchlen=1): return {'hash': b_hash, 'height': 202, 'branchlen': branchlen, 'status': status} assert chain_tip(block.hash) not in filter_tip_keys(node.getchaintips()) - node.submitheader(hexdata=b2x(block.serialize())) + node.submitheader(hexdata=block.serialize().hex()) assert chain_tip(block.hash) in filter_tip_keys(node.getchaintips()) - node.submitheader(hexdata=b2x(CBlockHeader(block).serialize())) # Noop + node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) # Noop assert chain_tip(block.hash) in filter_tip_keys(node.getchaintips()) bad_block_root = copy.deepcopy(block) bad_block_root.hashMerkleRoot += 2 bad_block_root.solve() assert chain_tip(bad_block_root.hash) not in filter_tip_keys(node.getchaintips()) - node.submitheader(hexdata=b2x(CBlockHeader(bad_block_root).serialize())) + node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex()) assert chain_tip(bad_block_root.hash) in filter_tip_keys(node.getchaintips()) # Should still reject invalid blocks, even if we have the header: - assert_equal(node.submitblock(hexdata=b2x(bad_block_root.serialize())), 'invalid') + assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'invalid') assert chain_tip(bad_block_root.hash) in filter_tip_keys(node.getchaintips()) # We know the header for this invalid block, so should just return early without error: - node.submitheader(hexdata=b2x(CBlockHeader(bad_block_root).serialize())) + node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex()) assert chain_tip(bad_block_root.hash) in filter_tip_keys(node.getchaintips()) bad_block_lock = copy.deepcopy(block) @@ -192,18 +191,18 @@ class MiningTest(BitcoinTestFramework): bad_block_lock.vtx[0].rehash() bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root() bad_block_lock.solve() - assert_equal(node.submitblock(hexdata=b2x(bad_block_lock.serialize())), 'invalid') + assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'invalid') # Build a "good" block on top of the submitted bad block bad_block2 = copy.deepcopy(block) bad_block2.hashPrevBlock = bad_block_lock.sha256 bad_block2.solve() - assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=b2x(CBlockHeader(bad_block2).serialize()))) + assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex())) # Should reject invalid header right away bad_block_time = copy.deepcopy(block) bad_block_time.nTime = 1 bad_block_time.solve() - assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=b2x(CBlockHeader(bad_block_time).serialize()))) + assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex())) # Should ask for the block from a p2p node, if they announce the header as well: node.add_p2p_connection(P2PDataStore()) @@ -214,10 +213,10 @@ class MiningTest(BitcoinTestFramework): # Building a few blocks should give the same results node.generate(10) - assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=b2x(CBlockHeader(bad_block_time).serialize()))) - assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=b2x(CBlockHeader(bad_block2).serialize()))) - node.submitheader(hexdata=b2x(CBlockHeader(block).serialize())) - node.submitheader(hexdata=b2x(CBlockHeader(bad_block_root).serialize())) + assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex())) + assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex())) + node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) + node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex()) if __name__ == '__main__': diff --git a/test/functional/mining_getblocktemplate_longpoll.py b/test/functional/mining_getblocktemplate_longpoll.py index 7c99e612ce..6228b1f2f4 100755 --- a/test/functional/mining_getblocktemplate_longpoll.py +++ b/test/functional/mining_getblocktemplate_longpoll.py @@ -35,27 +35,27 @@ class GetBlockTemplateLPTest(BitcoinTestFramework): longpollid = template['longpollid'] # longpollid should not change between successive invocations if nothing else happens template2 = self.nodes[0].getblocktemplate() - assert(template2['longpollid'] == longpollid) + assert template2['longpollid'] == longpollid # Test 1: test that the longpolling wait if we do nothing thr = LongpollThread(self.nodes[0]) thr.start() # check that thread still lives thr.join(5) # wait 5 seconds or until thread exits - assert(thr.is_alive()) + assert thr.is_alive() # Test 2: test that longpoll will terminate if another node generates a block self.nodes[1].generate(1) # generate a block on another node # check that thread will exit now that new transaction entered mempool thr.join(5) # wait 5 seconds or until thread exits - assert(not thr.is_alive()) + assert not thr.is_alive() # Test 3: test that longpoll will terminate if we generate a block ourselves thr = LongpollThread(self.nodes[0]) thr.start() self.nodes[0].generate(1) # generate a block on another node thr.join(5) # wait 5 seconds or until thread exits - assert(not thr.is_alive()) + assert not thr.is_alive() # Test 4: test that introducing a new transaction into the mempool will terminate the longpoll thr = LongpollThread(self.nodes[0]) diff --git a/test/functional/mining_prioritisetransaction.py b/test/functional/mining_prioritisetransaction.py index 79e0066cc2..383f85c8fd 100755 --- a/test/functional/mining_prioritisetransaction.py +++ b/test/functional/mining_prioritisetransaction.py @@ -54,9 +54,9 @@ class PrioritiseTransactionTest(BitcoinTestFramework): sizes = [0, 0, 0] for i in range(3): for j in txids[i]: - assert(j in mempool) + assert j in mempool sizes[i] += mempool[j]['size'] - assert(sizes[i] > MAX_BLOCK_SIZE) # Fail => raise utxo_count + assert sizes[i] > MAX_BLOCK_SIZE # Fail => raise utxo_count # add a fee delta to something in the cheapest bucket and make sure it gets mined # also check that a different entry in the cheapest bucket is NOT mined @@ -66,8 +66,8 @@ class PrioritiseTransactionTest(BitcoinTestFramework): mempool = self.nodes[0].getrawmempool() self.log.info("Assert that prioritised transaction was mined") - assert(txids[0][0] not in mempool) - assert(txids[0][1] in mempool) + assert txids[0][0] not in mempool + assert txids[0][1] in mempool high_fee_tx = None for x in txids[2]: @@ -75,7 +75,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework): high_fee_tx = x # Something high-fee should have been mined! - assert(high_fee_tx != None) + assert high_fee_tx != None # Add a prioritisation before a tx is in the mempool (de-prioritising a # high-fee transaction so that it's now low fee). @@ -86,7 +86,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework): # Check to make sure our high fee rate tx is back in the mempool mempool = self.nodes[0].getrawmempool() - assert(high_fee_tx in mempool) + assert high_fee_tx in mempool # Now verify the modified-high feerate transaction isn't mined before # the other high fee transactions. Keep mining until our mempool has @@ -98,14 +98,14 @@ class PrioritiseTransactionTest(BitcoinTestFramework): # transactions should have been. mempool = self.nodes[0].getrawmempool() self.log.info("Assert that de-prioritised transaction is still in mempool") - assert(high_fee_tx in mempool) + assert high_fee_tx in mempool for x in txids[2]: if (x != high_fee_tx): - assert(x not in mempool) + assert x not in mempool # Create a free transaction. Should be rejected. utxo_list = self.nodes[0].listunspent() - assert(len(utxo_list) > 0) + assert len(utxo_list) > 0 utxo = utxo_list[0] inputs = [] @@ -118,7 +118,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework): # This will raise an exception due to min relay fee not being met assert_raises_rpc_error(-26, "min relay fee not met", self.nodes[0].sendrawtransaction, tx_hex) - assert(tx_id not in self.nodes[0].getrawmempool()) + assert tx_id not in self.nodes[0].getrawmempool() # This is a less than 1000-byte transaction, so just set the fee # to be the minimum for a 1000-byte transaction and check that it is @@ -127,7 +127,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework): self.log.info("Assert that prioritised free transaction is accepted to mempool") assert_equal(self.nodes[0].sendrawtransaction(tx_hex), tx_id) - assert(tx_id in self.nodes[0].getrawmempool()) + assert tx_id in self.nodes[0].getrawmempool() # Test that calling prioritisetransaction is sufficient to trigger # getblocktemplate to (eventually) return a new block. @@ -137,7 +137,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework): self.nodes[0].setmocktime(self.mocktime+10) new_template = self.nodes[0].getblocktemplate() - assert(template != new_template) + assert template != new_template if __name__ == '__main__': PrioritiseTransactionTest().main() diff --git a/test/functional/p2p_addrv2_relay.py b/test/functional/p2p_addrv2_relay.py index bd5a28637c..2ec2cb05b1 100755 --- a/test/functional/p2p_addrv2_relay.py +++ b/test/functional/p2p_addrv2_relay.py @@ -26,7 +26,7 @@ class AddrReceiver(P2PInterface): for addr in message.addrs: assert_equal(addr.nServices, 1) assert addr.ip.startswith('123.123.123.') - assert (8333 <= addr.port < 8343) + assert 8333 <= addr.port < 8343 self.addrv2_received_and_checked = True def wait_for_addrv2(self): diff --git a/test/functional/p2p_compactblocks.py b/test/functional/p2p_compactblocks.py index 9f80fea788..c5d26ecd1e 100755 --- a/test/functional/p2p_compactblocks.py +++ b/test/functional/p2p_compactblocks.py @@ -109,7 +109,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Doesn't matter which node we use, just use node0. block = self.build_block_on_tip(self.nodes[0]) self.test_node.send_and_ping(msg_block(block)) - assert(int(self.nodes[0].getbestblockhash(), 16) == block.sha256) + assert int(self.nodes[0].getbestblockhash(), 16) == block.sha256 self.nodes[0].generate(100) total_value = block.vtx[0].vout[0].nValue @@ -153,7 +153,7 @@ class CompactBlocksTest(BitcoinTestFramework): peer.clear_block_announcement() block_hash = int(node.generate(1)[0], 16) peer.wait_for_block_announcement(block_hash, timeout=30) - assert(peer.block_announced) + assert peer.block_announced with mininode_lock: assert predicate(peer), ( @@ -271,7 +271,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Now fetch and check the compact block header_and_shortids = None with mininode_lock: - assert("cmpctblock" in test_node.last_message) + assert "cmpctblock" in test_node.last_message # Convert the on-the-wire representation to absolute indexes header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids) self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block) @@ -287,7 +287,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Now fetch and check the compact block header_and_shortids = None with mininode_lock: - assert("cmpctblock" in test_node.last_message) + assert "cmpctblock" in test_node.last_message # Convert the on-the-wire representation to absolute indexes header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids) self.check_compactblock_construction_from_block(version, header_and_shortids, block_hash, block) @@ -298,7 +298,7 @@ class CompactBlocksTest(BitcoinTestFramework): assert_equal(header_and_shortids.header.sha256, block_hash) # Make sure the prefilled_txn appears to have included the coinbase - assert(len(header_and_shortids.prefilled_txn) >= 1) + assert len(header_and_shortids.prefilled_txn) >= 1 assert_equal(header_and_shortids.prefilled_txn[0].index, 0) # Check that all prefilled_txn entries match what's in the block. @@ -360,7 +360,7 @@ class CompactBlocksTest(BitcoinTestFramework): assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock) # Expect a getblocktxn message. with mininode_lock: - assert("getblocktxn" in test_node.last_message) + assert "getblocktxn" in test_node.last_message absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute() assert_equal(absolute_indexes, [0]) # should be a coinbase request @@ -396,7 +396,7 @@ class CompactBlocksTest(BitcoinTestFramework): msg = msg_cmpctblock(compact_block.to_p2p()) peer.send_and_ping(msg) with mininode_lock: - assert("getblocktxn" in peer.last_message) + assert "getblocktxn" in peer.last_message absolute_indexes = peer.last_message["getblocktxn"].block_txn_request.to_absolute() assert_equal(absolute_indexes, expected_result) @@ -434,7 +434,7 @@ class CompactBlocksTest(BitcoinTestFramework): block = self.build_block_with_transactions(node, utxo, 5) self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) test_node.send_and_ping(msg_tx(block.vtx[1])) - assert(block.vtx[1].hash in node.getrawmempool()) + assert block.vtx[1].hash in node.getrawmempool() # Prefill 4 out of the 6 transactions, and verify that only the one # that was not in the mempool is requested. @@ -455,7 +455,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Make sure all transactions were accepted. mempool = node.getrawmempool() for tx in block.vtx[1:]: - assert(tx.hash in mempool) + assert tx.hash in mempool # Clear out last request. with mininode_lock: @@ -466,7 +466,7 @@ class CompactBlocksTest(BitcoinTestFramework): test_tip_after_message(node, test_node, msg_cmpctblock(comp_block.to_p2p()), block.sha256) with mininode_lock: # Shouldn't have gotten a request for any transaction - assert("getblocktxn" not in test_node.last_message) + assert "getblocktxn" not in test_node.last_message # Incorrectly responding to a getblocktxn shouldn't cause the block to be # permanently failed. @@ -484,7 +484,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Make sure all transactions were accepted. mempool = node.getrawmempool() for tx in block.vtx[1:6]: - assert(tx.hash in mempool) + assert tx.hash in mempool # Send compact block comp_block = HeaderAndShortIDs() @@ -492,7 +492,7 @@ class CompactBlocksTest(BitcoinTestFramework): test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p())) absolute_indexes = [] with mininode_lock: - assert("getblocktxn" in test_node.last_message) + assert "getblocktxn" in test_node.last_message absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute() assert_equal(absolute_indexes, [6, 7, 8, 9, 10]) @@ -514,7 +514,7 @@ class CompactBlocksTest(BitcoinTestFramework): # We should receive a getdata request wait_until(lambda: "getdata" in test_node.last_message, timeout=10, lock=mininode_lock) assert_equal(len(test_node.last_message["getdata"].inv), 1) - assert(test_node.last_message["getdata"].inv[0].type == 2) + assert test_node.last_message["getdata"].inv[0].type == 2 assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256) # Deliver the block @@ -605,7 +605,7 @@ class CompactBlocksTest(BitcoinTestFramework): assert_equal(x["status"], "headers-only") found = True break - assert(found) + assert found # Requesting this block via getblocktxn should silently fail # (to avoid fingerprinting attacks). @@ -637,7 +637,7 @@ class CompactBlocksTest(BitcoinTestFramework): # Test that we don't get disconnected if we relay a compact block with valid header, # but invalid transactions. def test_invalid_tx_in_compactblock(self, node, test_node): - assert(len(self.utxos)) + assert len(self.utxos) utxo = self.utxos[0] block = self.build_block_with_transactions(node, utxo, 5) @@ -653,7 +653,7 @@ class CompactBlocksTest(BitcoinTestFramework): test_node.send_and_ping(msg) # Check that the tip didn't advance - assert(int(node.getbestblockhash(), 16) is not block.sha256) + assert int(node.getbestblockhash(), 16) is not block.sha256 test_node.sync_with_ping() # Helper for enabling cb announcements @@ -668,7 +668,7 @@ class CompactBlocksTest(BitcoinTestFramework): peer.send_and_ping(msg) def test_compactblock_reconstruction_multiple_peers(self, node, stalling_peer, delivery_peer): - assert(len(self.utxos)) + assert len(self.utxos) def announce_cmpct_block(node, peer): utxo = self.utxos.pop(0) @@ -689,7 +689,7 @@ class CompactBlocksTest(BitcoinTestFramework): delivery_peer.sync_with_ping() mempool = node.getrawmempool() for tx in block.vtx[1:]: - assert(tx.hash in mempool) + assert tx.hash in mempool delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p())) assert_equal(int(node.getbestblockhash(), 16), block.sha256) @@ -706,7 +706,7 @@ class CompactBlocksTest(BitcoinTestFramework): cmpct_block.prefilled_txn[0].tx = CTxIn() delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p())) - assert(int(node.getbestblockhash(), 16) != block.sha256) + assert int(node.getbestblockhash(), 16) != block.sha256 msg = msg_blocktxn() msg.block_transactions.blockhash = block.sha256 diff --git a/test/functional/p2p_instantsend.py b/test/functional/p2p_instantsend.py index 00dab217f8..012083c91c 100755 --- a/test/functional/p2p_instantsend.py +++ b/test/functional/p2p_instantsend.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 -# Copyright (c) 2018-2020 The Dash Core developers +# Copyright (c) 2018-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import DashTestFramework -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str, hash256, hex_str_to_bytes, isolate_node, reconnect_isolated_node +from test_framework.util import assert_equal, assert_raises_rpc_error, hash256, hex_str_to_bytes, isolate_node, reconnect_isolated_node ''' p2p_instantsend.py @@ -67,7 +67,7 @@ class InstantSendTest(DashTestFramework): if i == self.isolated_idx: continue res = self.nodes[i].waitforblock(wrong_block, timeout) - assert (res['hash'] != wrong_block) + assert res['hash'] != wrong_block # wait for long time only for first node timeout = 1 # send coins back to the controller node without waiting for confirmations @@ -95,7 +95,7 @@ class InstantSendTest(DashTestFramework): # create doublespending transaction, but don't relay it dblspnd_tx = self.create_raw_tx(sender, isolated, 0.5, 1, 100) - dblspnd_txid = bytes_to_hex_str(hash256(hex_str_to_bytes(dblspnd_tx['hex']))[::-1]) + dblspnd_txid = hash256(hex_str_to_bytes(dblspnd_tx['hex']))[::-1].hex() # isolate one node from network isolate_node(isolated) # send doublespend transaction to isolated node diff --git a/test/functional/p2p_leak.py b/test/functional/p2p_leak.py index 40a3405970..47d612af13 100755 --- a/test/functional/p2p_leak.py +++ b/test/functional/p2p_leak.py @@ -134,9 +134,9 @@ class P2PLeakTest(BitcoinTestFramework): wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0) # Make sure no unexpected messages came in - assert(no_version_bannode.unexpected_msg == False) - assert(no_version_idlenode.unexpected_msg == False) - assert(no_verack_idlenode.unexpected_msg == False) + assert no_version_bannode.unexpected_msg == False + assert no_version_idlenode.unexpected_msg == False + assert no_verack_idlenode.unexpected_msg == False self.log.info('Check that the version message does not leak the local address of the node') time_begin = int(time.time()) diff --git a/test/functional/p2p_unrequested_blocks.py b/test/functional/p2p_unrequested_blocks.py index 137de5f724..3bde33623c 100755 --- a/test/functional/p2p_unrequested_blocks.py +++ b/test/functional/p2p_unrequested_blocks.py @@ -113,7 +113,7 @@ class AcceptBlockTest(BitcoinTestFramework): if x['hash'] == block_h1f.hash: assert_equal(x['status'], "headers-only") tip_entry_found = True - assert(tip_entry_found) + assert tip_entry_found assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_h1f.hash) # 4. Send another two block that build on the fork. @@ -130,7 +130,7 @@ class AcceptBlockTest(BitcoinTestFramework): if x['hash'] == block_h2f.hash: assert_equal(x['status'], "headers-only") tip_entry_found = True - assert(tip_entry_found) + assert tip_entry_found # But this block should be accepted by node since it has equal work. self.nodes[0].getblock(block_h2f.hash) @@ -149,7 +149,7 @@ class AcceptBlockTest(BitcoinTestFramework): if x['hash'] == block_h3.hash: assert_equal(x['status'], "headers-only") tip_entry_found = True - assert(tip_entry_found) + assert tip_entry_found self.nodes[0].getblock(block_h3.hash) # But this block should be accepted by node since it has more work. @@ -262,7 +262,7 @@ class AcceptBlockTest(BitcoinTestFramework): if x['hash'] == block_292.hash: assert_equal(x['status'], "headers-only") tip_entry_found = True - assert(tip_entry_found) + assert tip_entry_found assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_292.hash) test_node.send_message(msg_block(block_289f)) diff --git a/test/functional/rpc_blockchain.py b/test/functional/rpc_blockchain.py index 58d84f76c0..772aa5a435 100755 --- a/test/functional/rpc_blockchain.py +++ b/test/functional/rpc_blockchain.py @@ -171,9 +171,9 @@ class BlockchainTest(BitcoinTestFramework): assert_equal(chaintxstats['window_final_block_hash'], b1_hash) assert_equal(chaintxstats['window_final_block_height'], 1) assert_equal(chaintxstats['window_block_count'], 0) - assert('window_tx_count' not in chaintxstats) - assert('window_interval' not in chaintxstats) - assert('txrate' not in chaintxstats) + assert 'window_tx_count' not in chaintxstats + assert 'window_interval' not in chaintxstats + assert 'txrate' not in chaintxstats def _test_gettxoutsetinfo(self): node = self.nodes[0] diff --git a/test/functional/rpc_decodescript.py b/test/functional/rpc_decodescript.py index e67a9f5cd3..f0d84aae60 100755 --- a/test/functional/rpc_decodescript.py +++ b/test/functional/rpc_decodescript.py @@ -6,7 +6,7 @@ from test_framework.messages import CTransaction from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import assert_equal, bytes_to_hex_str, hex_str_to_bytes +from test_framework.util import assert_equal, hex_str_to_bytes from io import BytesIO @@ -142,7 +142,7 @@ class DecodeScriptTest(BitcoinTestFramework): # some more full transaction tests of varying specific scriptSigs. used instead of # tests in decodescript_script_sig because the decodescript RPC is specifically # for working on scriptPubKeys (argh!). - push_signature = bytes_to_hex_str(txSave.vin[0].scriptSig)[2:(0x48*2+4)] + push_signature = txSave.vin[0].scriptSig.hex()[2:(0x48*2+4)] signature = push_signature[2:] der_signature = signature[:-2] signature_sighash_decoded = der_signature + '[ALL]' @@ -152,23 +152,23 @@ class DecodeScriptTest(BitcoinTestFramework): # 1) P2PK scriptSig txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature) - rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize())) + rpc_result = self.nodes[0].decoderawtransaction(txSave.serialize().hex()) assert_equal(signature_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm']) # make sure that the sighash decodes come out correctly for a more complex / lesser used case. txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature_2) - rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize())) + rpc_result = self.nodes[0].decoderawtransaction(txSave.serialize().hex()) assert_equal(signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm']) # 2) multisig scriptSig txSave.vin[0].scriptSig = hex_str_to_bytes('00' + push_signature + push_signature_2) - rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize())) + rpc_result = self.nodes[0].decoderawtransaction(txSave.serialize().hex()) assert_equal('0 ' + signature_sighash_decoded + ' ' + signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm']) # 3) test a scriptSig that contains more than push operations. # in fact, it contains an OP_RETURN with data specially crafted to cause improper decode if the code does not catch it. txSave.vin[0].scriptSig = hex_str_to_bytes('6a143011020701010101010101020601010101010101') - rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize())) + rpc_result = self.nodes[0].decoderawtransaction(txSave.serialize().hex()) assert_equal('OP_RETURN 3011020701010101010101020601010101010101', rpc_result['vin'][0]['scriptSig']['asm']) def run_test(self): diff --git a/test/functional/rpc_fundrawtransaction.py b/test/functional/rpc_fundrawtransaction.py index 7b0e56171b..febd280464 100755 --- a/test/functional/rpc_fundrawtransaction.py +++ b/test/functional/rpc_fundrawtransaction.py @@ -92,7 +92,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) - assert(len(dec_tx['vin']) > 0) #test that we have enough inputs + assert len(dec_tx['vin']) > 0 #test that we have enough inputs ############################## # simple test with two coins # @@ -105,7 +105,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) - assert(len(dec_tx['vin']) > 0) #test if we have enough inputs + assert len(dec_tx['vin']) > 0 #test if we have enough inputs ############################## # simple test with two coins # @@ -118,7 +118,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) - assert(len(dec_tx['vin']) > 0) + assert len(dec_tx['vin']) > 0 assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') @@ -137,7 +137,7 @@ class RawTransactionsTest(BitcoinTestFramework): for out in dec_tx['vout']: totalOut += out['value'] - assert(len(dec_tx['vin']) > 0) + assert len(dec_tx['vin']) > 0 assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') @@ -348,7 +348,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ ############################################################ @@ -363,7 +363,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ @@ -390,7 +390,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ @@ -423,7 +423,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ @@ -540,7 +540,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs + assert feeDelta >= 0 and feeDelta <= feeTolerance*19 #~19 inputs ############################################# @@ -602,7 +602,7 @@ class RawTransactionsTest(BitcoinTestFramework): assert_equal(len(res_dec["vin"]), 1) assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) - assert("fee" in result.keys()) + assert "fee" in result.keys() assert_greater_than(result["changepos"], -1) ############################################################### @@ -617,16 +617,16 @@ class RawTransactionsTest(BitcoinTestFramework): result = self.nodes[3].fundrawtransaction(rawtx, True) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 2) - assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid) + assert res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid assert_greater_than(result["fee"], 0) assert_greater_than(result["changepos"], -1) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) signedtx = self.nodes[3].signrawtransactionwithwallet(result["hex"]) - assert(not signedtx["complete"]) + assert not signedtx["complete"] signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"]) - assert(signedtx["complete"]) + assert signedtx["complete"] self.nodes[0].sendrawtransaction(signedtx["hex"]) self.nodes[0].generate(1) self.sync_all() @@ -658,10 +658,10 @@ class RawTransactionsTest(BitcoinTestFramework): for out in res_dec['vout']: if out['value'] > 1.0: changeaddress += out['scriptPubKey']['addresses'][0] - assert(changeaddress != "") + assert changeaddress != "" nextaddr = self.nodes[3].getnewaddress() # Now the change address key should be removed from the keypool - assert(changeaddress != nextaddr) + assert changeaddress != nextaddr ###################################### # Test subtractFeeFromOutputs option # diff --git a/test/functional/rpc_fundrawtransaction_hd.py b/test/functional/rpc_fundrawtransaction_hd.py index 701d6e57e9..8e468b4d0a 100755 --- a/test/functional/rpc_fundrawtransaction_hd.py +++ b/test/functional/rpc_fundrawtransaction_hd.py @@ -71,7 +71,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) - assert(len(dec_tx['vin']) > 0) #test if we have enough inputs + assert len(dec_tx['vin']) > 0 #test if we have enough inputs ############################## # simple test with two coins # @@ -84,7 +84,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) - assert(len(dec_tx['vin']) > 0) #test if we have enough inputs + assert len(dec_tx['vin']) > 0 #test if we have enough inputs ############################## # simple test with two coins # @@ -97,7 +97,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) - assert(len(dec_tx['vin']) > 0) + assert len(dec_tx['vin']) > 0 assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') @@ -116,7 +116,7 @@ class RawTransactionsTest(BitcoinTestFramework): for out in dec_tx['vout']: totalOut += out['value'] - assert(len(dec_tx['vin']) > 0) + assert len(dec_tx['vin']) > 0 assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') @@ -130,7 +130,7 @@ class RawTransactionsTest(BitcoinTestFramework): utx = aUtx break - assert(utx!=False) + assert utx!=False inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 10 } @@ -158,7 +158,7 @@ class RawTransactionsTest(BitcoinTestFramework): utx = aUtx break - assert(utx!=False) + assert utx!=False inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance } @@ -187,7 +187,7 @@ class RawTransactionsTest(BitcoinTestFramework): utx = aUtx break - assert(utx!=False) + assert utx!=False inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 10 } @@ -232,7 +232,7 @@ class RawTransactionsTest(BitcoinTestFramework): utx2 = aUtx - assert(utx!=False) + assert utx!=False inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 60 } @@ -274,7 +274,7 @@ class RawTransactionsTest(BitcoinTestFramework): utx2 = aUtx - assert(utx!=False) + assert utx!=False inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 } @@ -308,7 +308,7 @@ class RawTransactionsTest(BitcoinTestFramework): rawtxfund = self.nodes[2].fundrawtransaction(rawtx) raise AssertionError("Spent more than available") except JSONRPCException as e: - assert("Insufficient" in e.error['message']) + assert "Insufficient" in e.error['message'] ############################################################ @@ -324,7 +324,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ ############################################################ @@ -339,7 +339,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ @@ -366,7 +366,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ @@ -399,7 +399,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance) + assert feeDelta >= 0 and feeDelta <= feeTolerance ############################################################ @@ -466,7 +466,7 @@ class RawTransactionsTest(BitcoinTestFramework): fundedTx = self.nodes[1].fundrawtransaction(rawTx) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: - assert('Keypool ran out' in e.error['message']) + assert 'Keypool ran out' in e.error['message'] #refill the keypool self.nodes[1].walletpassphrase("test", 100) @@ -477,7 +477,7 @@ class RawTransactionsTest(BitcoinTestFramework): self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: - assert('walletpassphrase' in e.error['message']) + assert 'walletpassphrase' in e.error['message'] oldBalance = self.nodes[0].getbalance() @@ -526,7 +526,7 @@ class RawTransactionsTest(BitcoinTestFramework): #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) - assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs + assert feeDelta >= 0 and feeDelta <= feeTolerance*19 #~19 inputs ############################################# @@ -589,7 +589,7 @@ class RawTransactionsTest(BitcoinTestFramework): assert_equal(len(res_dec["vin"]), 1) assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) - assert("fee" in result.keys()) + assert "fee" in result.keys() assert_greater_than(result["changepos"], -1) ############################################################### @@ -603,16 +603,16 @@ class RawTransactionsTest(BitcoinTestFramework): result = self.nodes[3].fundrawtransaction(rawtx, True) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 2) - assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid) + assert res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid assert_greater_than(result["fee"], 0) assert_greater_than(result["changepos"], -1) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) signedtx = self.nodes[3].signrawtransactionwithwallet(result["hex"]) - assert(not signedtx["complete"]) + assert not signedtx["complete"] signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"]) - assert(signedtx["complete"]) + assert signedtx["complete"] self.nodes[0].sendrawtransaction(signedtx["hex"]) diff --git a/test/functional/rpc_invalidateblock.py b/test/functional/rpc_invalidateblock.py index 2d16c248e6..465cecd766 100755 --- a/test/functional/rpc_invalidateblock.py +++ b/test/functional/rpc_invalidateblock.py @@ -21,17 +21,17 @@ class InvalidateTest(BitcoinTestFramework): self.log.info("Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:") self.log.info("Mine 4 blocks on Node 0") self.nodes[0].generate(4) - assert(self.nodes[0].getblockcount() == 4) + assert self.nodes[0].getblockcount() == 4 besthash = self.nodes[0].getbestblockhash() self.log.info("Mine competing 6 blocks on Node 1") self.nodes[1].generate(6) - assert(self.nodes[1].getblockcount() == 6) + assert self.nodes[1].getblockcount() == 6 self.log.info("Connect nodes to force a reorg") connect_nodes_bi(self.nodes,0,1) self.sync_blocks(self.nodes[0:2]) - assert(self.nodes[0].getblockcount() == 6) + assert self.nodes[0].getblockcount() == 6 badhash = self.nodes[1].getblockhash(2) self.log.info("Invalidate block 2 on node 0 and verify we reorg to node 0's original chain") @@ -45,13 +45,13 @@ class InvalidateTest(BitcoinTestFramework): connect_nodes_bi(self.nodes,1,2) self.log.info("Sync node 2 to node 1 so both have 6 blocks") self.sync_blocks(self.nodes[1:3]) - assert(self.nodes[2].getblockcount() == 6) + assert self.nodes[2].getblockcount() == 6 self.log.info("Invalidate block 5 on node 1 so its tip is now at 4") self.nodes[1].invalidateblock(self.nodes[1].getblockhash(5)) - assert(self.nodes[1].getblockcount() == 4) + assert self.nodes[1].getblockcount() == 4 self.log.info("Invalidate block 3 on node 2, so its tip is now 2") self.nodes[2].invalidateblock(self.nodes[2].getblockhash(3)) - assert(self.nodes[2].getblockcount() == 2) + assert self.nodes[2].getblockcount() == 2 self.log.info("..and then mine a block") self.nodes[2].generate(1) self.log.info("Verify all nodes are at the right height") diff --git a/test/functional/rpc_mnauth.py b/test/functional/rpc_mnauth.py index e97d070cfa..6a3b417e5e 100755 --- a/test/functional/rpc_mnauth.py +++ b/test/functional/rpc_mnauth.py @@ -6,7 +6,7 @@ from test_framework.messages import hash256 from test_framework.mininode import P2PInterface from test_framework.test_framework import DashTestFramework -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str, hex_str_to_bytes +from test_framework.util import assert_equal, assert_raises_rpc_error, hex_str_to_bytes ''' rpc_mnauth.py @@ -28,17 +28,17 @@ class FakeMNAUTHTest(DashTestFramework): public_key = masternode.pubKeyOperator # The peerinfo should not yet contain verified_proregtx_hash/verified_pubkey_hash - assert("verified_proregtx_hash" not in masternode.node.getpeerinfo()[-1]) - assert("verified_pubkey_hash" not in masternode.node.getpeerinfo()[-1]) + assert "verified_proregtx_hash" not in masternode.node.getpeerinfo()[-1] + assert "verified_pubkey_hash" not in masternode.node.getpeerinfo()[-1] # Fake-Authenticate the P2P connection to the masternode node_id = masternode.node.getpeerinfo()[-1]["id"] - assert(masternode.node.mnauth(node_id, protx_hash, public_key)) + assert masternode.node.mnauth(node_id, protx_hash, public_key) # The peerinfo should now contain verified_proregtx_hash and verified_pubkey_hash peerinfo = masternode.node.getpeerinfo()[-1] - assert("verified_proregtx_hash" in peerinfo) - assert("verified_pubkey_hash" in peerinfo) + assert "verified_proregtx_hash" in peerinfo + assert "verified_pubkey_hash" in peerinfo assert_equal(peerinfo["verified_proregtx_hash"], protx_hash) - assert_equal(peerinfo["verified_pubkey_hash"], bytes_to_hex_str(hash256(hex_str_to_bytes(public_key))[::-1])) + assert_equal(peerinfo["verified_pubkey_hash"], hash256(hex_str_to_bytes(public_key))[::-1].hex()) # Test some error cases null_hash = "0000000000000000000000000000000000000000000000000000000000000000" assert_raises_rpc_error(-8, "proTxHash invalid", masternode.node.mnauth, @@ -49,7 +49,7 @@ class FakeMNAUTHTest(DashTestFramework): node_id, protx_hash, null_hash) - assert(not masternode.node.mnauth(-1, protx_hash, public_key)) + assert not masternode.node.mnauth(-1, protx_hash, public_key) if __name__ == '__main__': diff --git a/test/functional/rpc_named_arguments.py b/test/functional/rpc_named_arguments.py index c47212bddb..570fd137de 100755 --- a/test/functional/rpc_named_arguments.py +++ b/test/functional/rpc_named_arguments.py @@ -17,7 +17,7 @@ class NamedArgumentTest(BitcoinTestFramework): def run_test(self): node = self.nodes[0] h = node.help(command='getblockchaininfo') - assert(h.startswith('getblockchaininfo\n')) + assert h.startswith('getblockchaininfo\n') assert_raises_rpc_error(-8, 'Unknown named parameter', node.help, random='getblockchaininfo') diff --git a/test/functional/rpc_platform_filter.py b/test/functional/rpc_platform_filter.py index a22a2eece0..337a3d3af9 100755 --- a/test/functional/rpc_platform_filter.py +++ b/test/functional/rpc_platform_filter.py @@ -47,7 +47,7 @@ class HTTPBasicsTest(BitcoinTestFramework): conn.request('POST', '/', json.dumps(body), {"Authorization": "Basic " + str_to_b64str(auth)}) resp = conn.getresponse() if should_not_match: - assert(resp.status != expexted_status) + assert resp.status != expexted_status else: assert_equal(resp.status, expexted_status) conn.close() diff --git a/test/functional/rpc_preciousblock.py b/test/functional/rpc_preciousblock.py index 4b8b23468d..35dee2dce0 100755 --- a/test/functional/rpc_preciousblock.py +++ b/test/functional/rpc_preciousblock.py @@ -16,7 +16,7 @@ def unidirectional_node_sync_via_rpc(node_src, node_dest): blockhash = node_src.getbestblockhash() while True: try: - assert(len(node_dest.getblock(blockhash, False)) > 0) + assert len(node_dest.getblock(blockhash, False)) > 0 break except: blocks_to_copy.append(blockhash) @@ -24,7 +24,7 @@ def unidirectional_node_sync_via_rpc(node_src, node_dest): blocks_to_copy.reverse() for blockhash in blocks_to_copy: blockdata = node_src.getblock(blockhash, False) - assert(node_dest.submitblock(blockdata) in (None, 'inconclusive')) + assert node_dest.submitblock(blockdata) in (None, 'inconclusive') def node_sync_via_rpc(nodes): for node_src in nodes: @@ -56,7 +56,7 @@ class PreciousTest(BitcoinTestFramework): self.log.info("Mine competing blocks E-F-G on Node 1") hashG = self.nodes[1].generate(3)[-1] assert_equal(self.nodes[1].getblockcount(), 5) - assert(hashC != hashG) + assert hashC != hashG self.log.info("Connect nodes and check no reorg occurs") # Submit competing blocks via RPC so any reorg should occur before we proceed (no way to wait on inaction for p2p sync) node_sync_via_rpc(self.nodes[0:2]) diff --git a/test/functional/rpc_rawtransaction.py b/test/functional/rpc_rawtransaction.py index c813b110d4..3eebc6215d 100755 --- a/test/functional/rpc_rawtransaction.py +++ b/test/functional/rpc_rawtransaction.py @@ -17,7 +17,7 @@ from decimal import Decimal from io import BytesIO from test_framework.messages import CTransaction, ToHex from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import assert_equal, assert_raises_rpc_error, bytes_to_hex_str, connect_nodes_bi, hex_str_to_bytes +from test_framework.util import assert_equal, assert_raises_rpc_error, connect_nodes_bi, hex_str_to_bytes class multidict(dict): """Dictionary that allows duplicate keys. @@ -111,28 +111,28 @@ class RawTransactionsTest(BitcoinTestFramework): tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs={address: 99})))) assert_equal(len(tx.vout), 1) assert_equal( - bytes_to_hex_str(tx.serialize()), + tx.serialize().hex(), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}]), ) # Two outputs tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=OrderedDict([(address, 99), (address2, 99)]))))) assert_equal(len(tx.vout), 2) assert_equal( - bytes_to_hex_str(tx.serialize()), + tx.serialize().hex(), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {address2: 99}]), ) # Two data outputs tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=multidict([('data', '99'), ('data', '99')]))))) assert_equal(len(tx.vout), 2) assert_equal( - bytes_to_hex_str(tx.serialize()), + tx.serialize().hex(), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{'data': '99'}, {'data': '99'}]), ) # Multiple mixed outputs tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=multidict([(address, 99), ('data', '99'), ('data', '99')]))))) assert_equal(len(tx.vout), 3) assert_equal( - bytes_to_hex_str(tx.serialize()), + tx.serialize().hex(), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {'data': '99'}, {'data': '99'}]), ) diff --git a/test/functional/rpc_setban.py b/test/functional/rpc_setban.py index a1a8196557..2c3b6a2a4b 100755 --- a/test/functional/rpc_setban.py +++ b/test/functional/rpc_setban.py @@ -20,7 +20,7 @@ class SetBanTests(BitcoinTestFramework): # Node 0 connects to Node 1, check that the noban permission is not granted connect_nodes(self.nodes[0], 1) peerinfo = self.nodes[1].getpeerinfo()[0] - assert(not 'noban' in peerinfo['permissions']) + assert not 'noban' in peerinfo['permissions'] # Node 0 get banned by Node 1 self.nodes[1].setban("127.0.0.1", "add") @@ -34,14 +34,14 @@ class SetBanTests(BitcoinTestFramework): self.restart_node(1, ['-whitelist=127.0.0.1']) connect_nodes(self.nodes[0], 1) peerinfo = self.nodes[1].getpeerinfo()[0] - assert('noban' in peerinfo['permissions']) + assert 'noban' in peerinfo['permissions'] # If we remove the ban, Node 0 should be able to reconnect even without noban permission self.nodes[1].setban("127.0.0.1", "remove") self.restart_node(1, []) connect_nodes(self.nodes[0], 1) peerinfo = self.nodes[1].getpeerinfo()[0] - assert(not 'noban' in peerinfo['permissions']) + assert not 'noban' in peerinfo['permissions'] if __name__ == '__main__': SetBanTests().main() diff --git a/test/functional/rpc_signmessage.py b/test/functional/rpc_signmessage.py index be74b6586d..4d76f6d9de 100755 --- a/test/functional/rpc_signmessage.py +++ b/test/functional/rpc_signmessage.py @@ -21,18 +21,18 @@ class SignMessagesTest(BitcoinTestFramework): expected_signature = 'ICzMhjIUmmXcPWy2+9nw01zQMawo+s5FIy6F7VMkL+TmIeNq1j3AMEuw075os29kh5KYLbysKkDlDD+EAqERBd4=' signature = self.nodes[0].signmessagewithprivkey(priv_key, message) assert_equal(expected_signature, signature) - assert(self.nodes[0].verifymessage(address, signature, message)) + assert self.nodes[0].verifymessage(address, signature, message) self.log.info('test signing with an address with wallet') address = self.nodes[0].getnewaddress() signature = self.nodes[0].signmessage(address, message) - assert(self.nodes[0].verifymessage(address, signature, message)) + assert self.nodes[0].verifymessage(address, signature, message) self.log.info('test verifying with another address should not work') other_address = self.nodes[0].getnewaddress() other_signature = self.nodes[0].signmessage(other_address, message) - assert(not self.nodes[0].verifymessage(other_address, signature, message)) - assert(not self.nodes[0].verifymessage(address, other_signature, message)) + assert not self.nodes[0].verifymessage(other_address, signature, message) + assert not self.nodes[0].verifymessage(address, other_signature, message) if __name__ == '__main__': SignMessagesTest().main() diff --git a/test/functional/rpc_uptime.py b/test/functional/rpc_uptime.py index 78236b2393..f7c9e4611d 100755 --- a/test/functional/rpc_uptime.py +++ b/test/functional/rpc_uptime.py @@ -23,7 +23,7 @@ class UptimeTest(BitcoinTestFramework): def _test_uptime(self): wait_time = 10 self.nodes[0].setmocktime(int(time.time() + wait_time)) - assert(self.nodes[0].uptime() >= wait_time) + assert self.nodes[0].uptime() >= wait_time if __name__ == '__main__': diff --git a/test/functional/rpc_verifyislock.py b/test/functional/rpc_verifyislock.py index f062d18c17..2a84090202 100755 --- a/test/functional/rpc_verifyislock.py +++ b/test/functional/rpc_verifyislock.py @@ -5,7 +5,7 @@ from test_framework.messages import CTransaction, FromHex, hash256, ser_compact_size, ser_string from test_framework.test_framework import DashTestFramework -from test_framework.util import assert_raises_rpc_error, bytes_to_hex_str, satoshi_round, wait_until +from test_framework.util import assert_raises_rpc_error, satoshi_round, wait_until ''' rpc_verifyislock.py @@ -43,15 +43,15 @@ class RPCVerifyISLockTest(DashTestFramework): wait_until(lambda: node.quorum("hasrecsig", 100, request_id, txid)) rec_sig = node.quorum("getrecsig", 100, request_id, txid)['sig'] - assert(node.verifyislock(request_id, txid, rec_sig)) + assert node.verifyislock(request_id, txid, rec_sig) # Not mined, should use maxHeight assert not node.verifyislock(request_id, txid, rec_sig, 1) node.generate(1) - assert(txid not in node.getrawmempool()) + assert txid not in node.getrawmempool() # Mined but at higher height, should use maxHeight assert not node.verifyislock(request_id, txid, rec_sig, 1) # Mined, should ignore higher maxHeight - assert(node.verifyislock(request_id, txid, rec_sig, node.getblockcount() + 100)) + assert node.verifyislock(request_id, txid, rec_sig, node.getblockcount() + 100) # Mine one more quorum to have a full active set self.mine_quorum() @@ -88,10 +88,10 @@ class RPCVerifyISLockTest(DashTestFramework): # Verify the ISLOCK for a transaction that is not yet known by the node rawtx_txid = node.decoderawtransaction(rawtx)["txid"] assert_raises_rpc_error(-5, "No such mempool or blockchain transaction", node.getrawtransaction, rawtx_txid) - assert node.verifyislock(request_id, rawtx_txid, bytes_to_hex_str(islock.sig), node.getblockcount()) + assert node.verifyislock(request_id, rawtx_txid, islock.sig.hex(), node.getblockcount()) # Send the tx and verify the ISLOCK for a now known transaction assert rawtx_txid == node.sendrawtransaction(rawtx) - assert node.verifyislock(request_id, rawtx_txid, bytes_to_hex_str(islock.sig), node.getblockcount()) + assert node.verifyislock(request_id, rawtx_txid, islock.sig.hex(), node.getblockcount()) if __name__ == '__main__': diff --git a/test/functional/test_framework/address.py b/test/functional/test_framework/address.py index 08876fce33..ac945c54b2 100644 --- a/test/functional/test_framework/address.py +++ b/test/functional/test_framework/address.py @@ -10,15 +10,15 @@ # from .script import hash256, hash160, CScript -from .util import bytes_to_hex_str, hex_str_to_bytes +from .util import hex_str_to_bytes chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def byte_to_base58(b, version): result = '' - str = bytes_to_hex_str(b) - str = bytes_to_hex_str(chr(version).encode('latin-1')) + str - checksum = bytes_to_hex_str(hash256(hex_str_to_bytes(str))) + str = b.hex() + str = chr(version).encode('latin-1').hex() + str + checksum = hash256(hex_str_to_bytes(str)).hex() str += checksum[:8] value = int('0x'+str,0) while value > 0: @@ -32,12 +32,12 @@ def byte_to_base58(b, version): # TODO: def base58_decode def keyhash_to_p2pkh(hash, main = False): - assert (len(hash) == 20) + assert len(hash) == 20 version = 76 if main else 140 return byte_to_base58(hash, version) def scripthash_to_p2sh(hash, main = False): - assert (len(hash) == 20) + assert len(hash) == 20 version = 16 if main else 19 return byte_to_base58(hash, version) @@ -54,11 +54,11 @@ def check_key(key): key = hex_str_to_bytes(key) # Assuming this is hex string if (type(key) is bytes and (len(key) == 33 or len(key) == 65)): return key - assert(False) + assert False def check_script(script): if (type(script) is str): script = hex_str_to_bytes(script) # Assuming this is hex string if (type(script) is bytes or type(script) is CScript): return script - assert(False) + assert False diff --git a/test/functional/test_framework/blocktools.py b/test/functional/test_framework/blocktools.py index 7e1b49976d..385dfe3383 100644 --- a/test/functional/test_framework/blocktools.py +++ b/test/functional/test_framework/blocktools.py @@ -80,7 +80,7 @@ def create_tx_with_script(prevtx, n, script_sig=b"", amount=1, script_pub_key=CS Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output. """ tx = CTransaction() - assert(n < len(prevtx.vout)) + assert n < len(prevtx.vout) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff)) tx.vout.append(CTxOut(amount, script_pub_key)) tx.calc_sha256() diff --git a/test/functional/test_framework/messages.py b/test/functional/test_framework/messages.py index 148c52d449..b990b2178f 100755 --- a/test/functional/test_framework/messages.py +++ b/test/functional/test_framework/messages.py @@ -27,7 +27,7 @@ import struct import time from test_framework.siphash import siphash256 -from test_framework.util import hex_str_to_bytes, bytes_to_hex_str +from test_framework.util import hex_str_to_bytes import dash_hash @@ -199,7 +199,7 @@ def FromHex(obj, hex_string): # Convert a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj): - return bytes_to_hex_str(obj.serialize()) + return obj.serialize().hex() # Objects that map to dashd objects, which can be serialized/deserialized @@ -401,7 +401,7 @@ class CTxIn: def __repr__(self): return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \ - % (repr(self.prevout), bytes_to_hex_str(self.scriptSig), + % (repr(self.prevout), self.scriptSig.hex(), self.nSequence) @@ -425,7 +425,7 @@ class CTxOut: def __repr__(self): return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \ % (self.nValue // COIN, self.nValue % COIN, - bytes_to_hex_str(self.scriptPubKey)) + self.scriptPubKey.hex()) class CTransaction: diff --git a/test/functional/test_framework/mininode.py b/test/functional/test_framework/mininode.py index c9c53d2c93..92578dac96 100755 --- a/test/functional/test_framework/mininode.py +++ b/test/functional/test_framework/mininode.py @@ -260,10 +260,7 @@ class P2PConnection(asyncio.Protocol): def maybe_write(): if not self._transport: return - # Python <3.4.4 does not have is_closing, so we have to check for - # its existence explicitly as long as Dash Core supports all - # Python 3.4 versions. - if hasattr(self._transport, 'is_closing') and self._transport.is_closing(): + if self._transport.is_closing(): return self._transport.write(raw_message_bytes) NetworkThread.network_event_loop.call_soon_threadsafe(maybe_write) diff --git a/test/functional/test_framework/netutil.py b/test/functional/test_framework/netutil.py index 0bac633008..c3566abcbc 100644 --- a/test/functional/test_framework/netutil.py +++ b/test/functional/test_framework/netutil.py @@ -12,7 +12,7 @@ import socket import struct import array import os -from binascii import unhexlify, hexlify +from binascii import unhexlify # STATE_ESTABLISHED = '01' # STATE_SYN_SENT = '02' @@ -129,17 +129,17 @@ def addr_to_hex(addr): if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end continue x += 1 # :: skips to suffix - assert(x < 2) + assert x < 2 else: # two bytes per component val = int(comp, 16) sub[x].append(val >> 8) sub[x].append(val & 0xff) nullbytes = 16 - len(sub[0]) - len(sub[1]) - assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) + assert (x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0) addr = sub[0] + ([0] * nullbytes) + sub[1] else: raise ValueError('Could not parse address %s' % addr) - return hexlify(bytearray(addr)).decode('ascii') + return bytearray(addr).hex() def test_ipv6_local(): ''' diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py index 2ef9c59e53..943b404deb 100644 --- a/test/functional/test_framework/script.py +++ b/test/functional/test_framework/script.py @@ -7,7 +7,6 @@ This file is modified from python-bitcoinlib. """ -from binascii import hexlify import hashlib import struct @@ -451,10 +450,6 @@ class CScript(bytes): # join makes no sense for a CScript() raise NotImplementedError - # Python 3.4 compatibility - def hex(self): - return hexlify(self).decode('ascii') - def __new__(cls, value=b''): if isinstance(value, bytes) or isinstance(value, bytearray): return super(CScript, cls).__new__(cls, value) @@ -546,7 +541,7 @@ class CScript(bytes): def __repr__(self): def _repr(o): if isinstance(o, bytes): - return "x('%s')" % hexlify(o).decode('ascii') + return "x('%s')" % o.hex() else: return repr(o) diff --git a/test/functional/test_framework/socks5.py b/test/functional/test_framework/socks5.py index 39c75ca495..1783de17c4 100644 --- a/test/functional/test_framework/socks5.py +++ b/test/functional/test_framework/socks5.py @@ -144,7 +144,7 @@ class Socks5Server(): thread.start() def start(self): - assert(not self.running) + assert not self.running self.running = True self.thread = threading.Thread(None, self.run) self.thread.daemon = True diff --git a/test/functional/test_framework/test_framework.py b/test/functional/test_framework/test_framework.py index 840ce004ab..d1e1f063aa 100755 --- a/test/functional/test_framework/test_framework.py +++ b/test/functional/test_framework/test_framework.py @@ -806,12 +806,12 @@ class DashTestFramework(BitcoinTestFramework): self.bump_mocktime(1) mn_info = self.nodes[0].masternodelist("status") - assert (len(mn_info) == self.mn_count) + assert len(mn_info) == self.mn_count for status in mn_info.values(): - assert (status == 'ENABLED') + assert status == 'ENABLED' def create_raw_tx(self, node_from, node_to, amount, min_inputs, max_inputs): - assert (min_inputs <= max_inputs) + assert min_inputs <= max_inputs # fill inputs inputs = [] balances = node_from.listunspent() @@ -841,9 +841,9 @@ class DashTestFramework(BitcoinTestFramework): inputs[-1] = input last_amount = float(tx['amount']) - assert (len(inputs) >= min_inputs) - assert (len(inputs) <= max_inputs) - assert (in_amount >= amount) + assert len(inputs) >= min_inputs + assert len(inputs) <= max_inputs + assert in_amount >= amount # fill outputs receiver_address = node_to.getnewaddress() change_address = node_from.getnewaddress() diff --git a/test/functional/test_framework/test_node.py b/test/functional/test_framework/test_node.py index 6afb156f8c..9643f571fb 100755 --- a/test/functional/test_framework/test_node.py +++ b/test/functional/test_framework/test_node.py @@ -32,9 +32,6 @@ from .util import ( Options ) -# For Python 3.4 compatibility -JSONDecodeError = getattr(json, "JSONDecodeError", ValueError) - BITCOIND_PROC_WAIT_TIMEOUT = 60 @@ -581,5 +578,5 @@ class TestNodeCLI(): raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr) try: return json.loads(cli_stdout, parse_float=decimal.Decimal) - except JSONDecodeError: + except json.JSONDecodeError: return cli_stdout.rstrip("\n") diff --git a/test/functional/test_framework/util.py b/test/functional/test_framework/util.py index afec6fc6de..1d10b04b8f 100644 --- a/test/functional/test_framework/util.py +++ b/test/functional/test_framework/util.py @@ -6,7 +6,7 @@ """Helpful routines for regression testing.""" from base64 import b64encode -from binascii import hexlify, unhexlify +from binascii import unhexlify from decimal import Decimal, ROUND_DOWN import hashlib import inspect @@ -194,9 +194,6 @@ def check_json_precision(): def count_bytes(hex_string): return len(bytearray.fromhex(hex_string)) -def bytes_to_hex_str(byte_str): - return hexlify(byte_str).decode('ascii') - def hash256(byte_str): sha256 = hashlib.sha256() sha256.update(byte_str) @@ -288,7 +285,7 @@ def get_rpc_proxy(url, node_number, *, timeout=None, coveragedir=None): return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile) def p2p_port(n): - assert(n <= MAX_NODES) + assert n <= MAX_NODES return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES) def rpc_port(n): @@ -523,7 +520,7 @@ def gather_inputs(from_node, amount_needed, confirmations_required=1): """ Return a random set of unspent txouts that are enough to pay amount_needed """ - assert(confirmations_required >= 0) + assert confirmations_required >= 0 utxo = from_node.listunspent(confirmations_required) random.shuffle(utxo) inputs = [] @@ -601,7 +598,7 @@ def create_confirmed_utxos(fee, node, count): node.generate(1) utxos = node.listunspent() - assert(len(utxos) >= count) + assert len(utxos) >= count return utxos # Create large OP_RETURN txouts that can be appended to a transaction diff --git a/test/functional/wallet_disable.py b/test/functional/wallet_disable.py index 51656fdb23..99ea3c7975 100755 --- a/test/functional/wallet_disable.py +++ b/test/functional/wallet_disable.py @@ -21,9 +21,9 @@ class DisableWalletTest (BitcoinTestFramework): # Make sure wallet is really disabled assert_raises_rpc_error(-32601, 'Method not found', self.nodes[0].getwalletinfo) x = self.nodes[0].validateaddress('7TSBtVu959hGEGPKyHjJz9k55RpWrPffXz') - assert(x['isvalid'] == False) + assert x['isvalid'] == False x = self.nodes[0].validateaddress('ycwedq2f3sz2Yf9JqZsBCQPxp18WU3Hp4J') - assert(x['isvalid'] == True) + assert x['isvalid'] == True # Checking mining to an address without a wallet. Generating to a valid address should succeed # but generating to an invalid address will fail. diff --git a/test/functional/wallet_disableprivatekeys.py b/test/functional/wallet_disableprivatekeys.py index 1ac3bedc14..f411abadb7 100755 --- a/test/functional/wallet_disableprivatekeys.py +++ b/test/functional/wallet_disableprivatekeys.py @@ -34,8 +34,8 @@ class DisablePrivateKeysTest(BitcoinTestFramework): privkey = w2.dumpprivkey(addr) assert_raises_rpc_error(-4, 'Cannot import private keys to a wallet with private keys disabled', w1.importprivkey, privkey) result = w1.importmulti([{'scriptPubKey': {'address': addr}, 'timestamp': 'now', 'keys': [privkey]}]) - assert(not result[0]['success']) - assert('warning' not in result[0]) + assert not result[0]['success'] + assert 'warning' not in result[0] assert_equal(result[0]['error']['code'], -4) assert_equal(result[0]['error']['message'], 'Cannot import private keys to a wallet with private keys disabled') diff --git a/test/functional/wallet_dump.py b/test/functional/wallet_dump.py index 0dda8d16ca..4eb9217368 100755 --- a/test/functional/wallet_dump.py +++ b/test/functional/wallet_dump.py @@ -44,10 +44,10 @@ def read_dump(file_name, addrs, script_addrs, hd_master_addr_old): keypath = None if keytype == "inactivehdseed=1": # ensure the old master is still available - assert (hd_master_addr_old == addr) + assert hd_master_addr_old == addr elif keytype == "hdseed=1": # ensure we have generated a new hd master key - assert (hd_master_addr_old != addr) + assert hd_master_addr_old != addr hd_master_addr_ret = addr elif keytype == "script=1": # scripts don't have keypaths @@ -148,13 +148,13 @@ class WalletDumpTest(BitcoinTestFramework): # Make sure the address is not IsMine before import result = self.nodes[0].getaddressinfo(multisig_addr) - assert(result['ismine'] == False) + assert result['ismine'] == False self.nodes[0].importwallet(wallet_unenc_dump) # Now check IsMine is true result = self.nodes[0].getaddressinfo(multisig_addr) - assert(result['ismine'] == True) + assert result['ismine'] == True if __name__ == '__main__': WalletDumpTest().main() diff --git a/test/functional/wallet_importmulti.py b/test/functional/wallet_importmulti.py index d963c5b657..9802d6e55f 100755 --- a/test/functional/wallet_importmulti.py +++ b/test/functional/wallet_importmulti.py @@ -10,7 +10,6 @@ from test_framework.util import ( assert_equal, assert_greater_than, assert_raises_rpc_error, - bytes_to_hex_str, ) @@ -88,7 +87,7 @@ class ImportMultiTest(BitcoinTestFramework): # Nonstandard scriptPubKey + !internal self.log.info("Should not import a nonstandard scriptPubKey without internal flag") - nonstandardScriptPubKey = address['scriptPubKey'] + bytes_to_hex_str(script.CScript([script.OP_NOP])) + nonstandardScriptPubKey = address['scriptPubKey'] + script.CScript([script.OP_NOP]).hex() address = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress()) result = self.nodes[1].importmulti([{ "scriptPubKey": nonstandardScriptPubKey, diff --git a/test/functional/wallet_keypool.py b/test/functional/wallet_keypool.py index 62cc293c4c..fa8234aedf 100755 --- a/test/functional/wallet_keypool.py +++ b/test/functional/wallet_keypool.py @@ -35,7 +35,7 @@ class KeyPoolTest(BitcoinTestFramework): addr.add(nodes[0].getrawchangeaddress()) addr.add(nodes[0].getrawchangeaddress()) # assert that three unique addresses were returned - assert(len(addr) == 3) + assert len(addr) == 3 # the next one should fail assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getrawchangeaddress) diff --git a/test/functional/wallet_keypool_hd.py b/test/functional/wallet_keypool_hd.py index 81bf2088a4..7b393b02f0 100755 --- a/test/functional/wallet_keypool_hd.py +++ b/test/functional/wallet_keypool_hd.py @@ -25,7 +25,7 @@ class KeyPoolTest(BitcoinTestFramework): addr_before_encrypting = nodes[0].getnewaddress() addr_before_encrypting_data = nodes[0].getaddressinfo(addr_before_encrypting) wallet_info_old = nodes[0].getwalletinfo() - assert(addr_before_encrypting_data['hdchainid'] == wallet_info_old['hdchainid']) + assert addr_before_encrypting_data['hdchainid'] == wallet_info_old['hdchainid'] # Encrypt wallet and wait to terminate nodes[0].encryptwallet('test') @@ -33,14 +33,14 @@ class KeyPoolTest(BitcoinTestFramework): addr = nodes[0].getnewaddress() addr_data = nodes[0].getaddressinfo(addr) wallet_info = nodes[0].getwalletinfo() - assert(addr_before_encrypting_data['hdchainid'] == wallet_info['hdchainid']) - assert(addr_data['hdchainid'] == wallet_info['hdchainid']) + assert addr_before_encrypting_data['hdchainid'] == wallet_info['hdchainid'] + assert addr_data['hdchainid'] == wallet_info['hdchainid'] try: addr = nodes[0].getnewaddress() raise AssertionError('Keypool should be exhausted after one address') except JSONRPCException as e: - assert(e.error['code']==-12) + assert e.error['code']==-12 # put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min) nodes[0].walletpassphrase('test', 12000) @@ -62,7 +62,7 @@ class KeyPoolTest(BitcoinTestFramework): nodes[0].getrawchangeaddress() raise AssertionError('Keypool should be exhausted after six addresses') except JSONRPCException as e: - assert(e.error['code']==-12) + assert e.error['code']==-12 addr = set() # drain the external keys @@ -72,13 +72,13 @@ class KeyPoolTest(BitcoinTestFramework): addr.add(nodes[0].getnewaddress()) addr.add(nodes[0].getnewaddress()) addr.add(nodes[0].getnewaddress()) - assert(len(addr) == 6) + assert len(addr) == 6 # the next one should fail try: addr = nodes[0].getnewaddress() raise AssertionError('Keypool should be exhausted after six addresses') except JSONRPCException as e: - assert(e.error['code']==-12) + assert e.error['code']==-12 # refill keypool with three new addresses nodes[0].walletpassphrase('test', 1) @@ -95,7 +95,7 @@ class KeyPoolTest(BitcoinTestFramework): nodes[0].generate(1) raise AssertionError('Keypool should be exhausted after three addesses') except JSONRPCException as e: - assert(e.error['code']==-12) + assert e.error['code']==-12 nodes[0].walletpassphrase('test', 100) nodes[0].keypoolrefill(100) diff --git a/test/functional/wallet_upgradetohd.py b/test/functional/wallet_upgradetohd.py index 7cd21e0f56..2f200547f3 100755 --- a/test/functional/wallet_upgradetohd.py +++ b/test/functional/wallet_upgradetohd.py @@ -32,16 +32,16 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): self.stop_node(0) shutil.copyfile(os.path.join(node.datadir, "non_hd.bak"), os.path.join(node.datadir, "regtest", "wallet.dat")) self.start_node(0) - assert('hdchainid' not in node.getwalletinfo()) + assert 'hdchainid' not in node.getwalletinfo() def run_test(self): node = self.nodes[0] node.backupwallet(os.path.join(node.datadir, "non_hd.bak")) self.log.info("No mnemonic, no mnemonic passphrase, no wallet passphrase") - assert('hdchainid' not in node.getwalletinfo()) + assert 'hdchainid' not in node.getwalletinfo() balance_before = node.getbalance() - assert(node.upgradetohd()) + assert node.upgradetohd() mnemonic = node.dumphdinfo()['mnemonic'] chainid = node.getwalletinfo()['hdchainid'] assert_equal(len(chainid), 64) @@ -72,12 +72,12 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): # We spent some coins from non-HD keys to HD ones earlier balance_non_HD = node.getbalance() - assert(balance_before != balance_non_HD) + assert balance_before != balance_non_HD self.log.info("No mnemonic, no mnemonic passphrase, no wallet passphrase, should result in completely different keys") - assert(node.upgradetohd()) - assert(mnemonic != node.dumphdinfo()['mnemonic']) - assert(chainid != node.getwalletinfo()['hdchainid']) + assert node.upgradetohd() + assert mnemonic != node.dumphdinfo()['mnemonic'] + assert chainid != node.getwalletinfo()['hdchainid'] assert_equal(balance_non_HD, node.getbalance()) node.keypoolrefill(5) node.rescanblockchain() @@ -88,10 +88,10 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): self.log.info("Same mnemonic, another mnemonic passphrase, no wallet passphrase, should result in a different set of keys") new_mnemonic_passphrase = "somewords" - assert(node.upgradetohd(mnemonic, new_mnemonic_passphrase)) + assert node.upgradetohd(mnemonic, new_mnemonic_passphrase) assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) new_chainid = node.getwalletinfo()['hdchainid'] - assert(chainid != new_chainid) + assert chainid != new_chainid assert_equal(balance_non_HD, node.getbalance()) node.keypoolrefill(5) node.rescanblockchain() @@ -102,7 +102,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): self.recover_non_hd() self.log.info("Same mnemonic, another mnemonic passphrase, no wallet passphrase, should result in a different set of keys (again)") - assert(node.upgradetohd(mnemonic, new_mnemonic_passphrase)) + assert node.upgradetohd(mnemonic, new_mnemonic_passphrase) assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) assert_equal(new_chainid, node.getwalletinfo()['hdchainid']) assert_equal(balance_non_HD, node.getbalance()) @@ -115,7 +115,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): self.recover_non_hd() self.log.info("Same mnemonic, no mnemonic passphrase, no wallet passphrase, should recover all coins after rescan") - assert(node.upgradetohd(mnemonic)) + assert node.upgradetohd(mnemonic) assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) assert_equal(chainid, node.getwalletinfo()['hdchainid']) node.keypoolrefill(5) @@ -127,7 +127,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): self.log.info("Same mnemonic, no mnemonic passphrase, no wallet passphrase, large enough keepool, should recover all coins with no extra rescan") self.stop_node(0) self.start_node(0, extra_args=['-keypool=10']) - assert(node.upgradetohd(mnemonic)) + assert node.upgradetohd(mnemonic) assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) assert_equal(chainid, node.getwalletinfo()['hdchainid']) # All coins should be recovered @@ -148,7 +148,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): # Note: wallet encryption results in additional keypool topup, # so we can't compare new balance to balance_non_HD here, # assert_equal(balance_non_HD, node.getbalance()) # won't work - assert(balance_non_HD != node.getbalance()) + assert balance_non_HD != node.getbalance() node.keypoolrefill(4) node.rescanblockchain() # All coins should be recovered @@ -164,7 +164,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): self.start_node(0, extra_args=['-rescan']) assert_raises_rpc_error(-14, "Cannot upgrade encrypted wallet to HD without the wallet passphrase", node.upgradetohd, mnemonic) assert_raises_rpc_error(-14, "The wallet passphrase entered was incorrect", node.upgradetohd, mnemonic, "", "wrongpass") - assert(node.upgradetohd(mnemonic, "", walletpass)) + assert node.upgradetohd(mnemonic, "", walletpass) assert_raises_rpc_error(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.", node.dumphdinfo) node.walletpassphrase(walletpass, 100) assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) @@ -172,7 +172,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework): # Note: wallet encryption results in additional keypool topup, # so we can't compare new balance to balance_non_HD here, # assert_equal(balance_non_HD, node.getbalance()) # won't work - assert(balance_non_HD != node.getbalance()) + assert balance_non_HD != node.getbalance() node.keypoolrefill(4) node.rescanblockchain() # All coins should be recovered diff --git a/test/lint/lint-format-strings.py b/test/lint/lint-format-strings.py index 54249d5102..07dc5bfd4c 100755 --- a/test/lint/lint-format-strings.py +++ b/test/lint/lint-format-strings.py @@ -46,7 +46,7 @@ def parse_function_calls(function_name, source_code): >>> len(parse_function_calls("foo", "#define FOO foo();")) 0 """ - assert(type(function_name) is str and type(source_code) is str and function_name) + assert type(function_name) is str and type(source_code) is str and function_name lines = [re.sub("// .*", " ", line).strip() for line in source_code.split("\n") if not line.strip().startswith("#")] @@ -60,7 +60,7 @@ def normalize(s): >>> normalize(" /* nothing */ foo\tfoo /* bar */ foo ") 'foo foo foo' """ - assert(type(s) is str) + assert type(s) is str s = s.replace("\n", " ") s = s.replace("\t", " ") s = re.sub("/\*.*?\*/", " ", s) @@ -84,7 +84,7 @@ def escape(s): >>> escape(r'foo \\t foo \\n foo \\\\ foo \\ foo \\"bar\\"') 'foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]' """ - assert(type(s) is str) + assert type(s) is str for raw_value, escaped_value in ESCAPE_MAP.items(): s = s.replace(raw_value, escaped_value) return s @@ -99,7 +99,7 @@ def unescape(s): >>> unescape("foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]") 'foo \\\\t foo \\\\n foo \\\\\\\\ foo \\\\ foo \\\\"bar\\\\"' """ - assert(type(s) is str) + assert type(s) is str for raw_value, escaped_value in ESCAPE_MAP.items(): s = s.replace(escaped_value, raw_value) return s @@ -158,10 +158,10 @@ def parse_function_call_and_arguments(function_name, function_call): >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo>foo<1,2>(1,2),err)'); ['strprintf(', '"%s (%d)",', ' foo>foo<1,2>(1,2),', 'err', ')'] """ - assert(type(function_name) is str and type(function_call) is str and function_name) + assert type(function_name) is str and type(function_call) is str and function_name remaining = normalize(escape(function_call)) expected_function_call = "{}(".format(function_name) - assert(remaining.startswith(expected_function_call)) + assert remaining.startswith(expected_function_call) parts = [expected_function_call] remaining = remaining[len(expected_function_call):] open_parentheses = 1 @@ -220,7 +220,7 @@ def parse_string_content(argument): >>> parse_string_content('1 2 3') '' """ - assert(type(argument) is str) + assert type(argument) is str string_content = "" in_string = False for char in normalize(escape(argument)): @@ -247,7 +247,7 @@ def count_format_specifiers(format_string): >>> count_format_specifiers("foo %d bar %i foo %% foo %*d foo") 4 """ - assert(type(format_string) is str) + assert type(format_string) is str format_string = format_string.replace('%%', 'X') n = 0 in_specifier = False