merge #14954: Require python 3.5

This commit is contained in:
Kittywhiskers Van Gogh 2021-08-28 00:33:02 +05:30
parent def36ab1f4
commit 0b13db2ac5
88 changed files with 461 additions and 635 deletions

View File

@ -1 +1 @@
3.4.9 3.5.6

View File

@ -205,7 +205,7 @@ after_success:
env: env:
cache: false cache: false
language: python 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: install:
- set -o errexit; source .travis/lint_04_install.sh - set -o errexit; source .travis/lint_04_install.sh
before_script: before_script:
@ -313,7 +313,7 @@ after_success:
name: 'macOS 10.12 [GOAL: deploy]' name: 'macOS 10.12 [GOAL: deploy]'
env: >- env: >-
HOST=x86_64-apple-darwin16 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 OSX_SDK=10.11
RUN_UNIT_TESTS=false RUN_UNIT_TESTS=false
RUN_FUNCTIONAL_TESTS=false RUN_FUNCTIONAL_TESTS=false

View File

@ -99,8 +99,8 @@ AC_PATH_TOOL(RANLIB, ranlib)
AC_PATH_TOOL(STRIP, strip) AC_PATH_TOOL(STRIP, strip)
AC_PATH_TOOL(GCOV, gcov) AC_PATH_TOOL(GCOV, gcov)
AC_PATH_PROG(LCOV, lcov) AC_PATH_PROG(LCOV, lcov)
dnl Python 3.4 is specified in .python-version and should be used if available, see doc/dependencies.md dnl Python 3.5 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]) AC_PATH_PROGS([PYTHON], [python3.5 python3.6 python3.7 python3.8 python3 python])
AC_PATH_PROG(GENHTML, genhtml) AC_PATH_PROG(GENHTML, genhtml)
AC_PATH_PROG([GIT], [git]) AC_PATH_PROG([GIT], [git])
AC_PATH_PROG(CCACHE,ccache) AC_PATH_PROG(CCACHE,ccache)

View File

@ -170,7 +170,7 @@ still compatible with the minimum supported Linux distribution versions.
Example usage after a Gitian build: 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. If only supported symbols are used the return value will be 0 and the output will be empty.

View File

@ -9,7 +9,7 @@ still compatible with the minimum supported Linux distribution versions.
Example usage: 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 subprocess
import re import re

View File

@ -26,7 +26,6 @@ packages:
- "faketime" - "faketime"
- "bsdmainutils" - "bsdmainutils"
- "ca-certificates" - "ca-certificates"
- "python"
- "python3" - "python3"
- "libxkbcommon0" - "libxkbcommon0"
- "ccache" - "ccache"

View File

@ -22,8 +22,6 @@ packages:
- "libcap-dev" - "libcap-dev"
- "libz-dev" - "libz-dev"
- "libbz2-dev" - "libbz2-dev"
- "python"
- "python-dev"
- "python3" - "python3"
- "python3-dev" - "python3-dev"
- "python3-setuptools" - "python3-setuptools"

View File

@ -20,7 +20,6 @@ packages:
- "nsis" - "nsis"
- "zip" - "zip"
- "ca-certificates" - "ca-certificates"
- "python"
- "python3" - "python3"
- "rename" - "rename"
- "ccache" - "ccache"

View File

@ -1,6 +1,5 @@
# Linearize # Linearize
Construct a linear, no-fork, best version of the Dash blockchain. The scripts Construct a linear, no-fork, best version of the Dash blockchain.
run using Python 3 but are compatible with Python 2.
## Step 0: Install dash_hash ## Step 0: Install dash_hash

View File

@ -17,7 +17,7 @@ import datetime
import time import time
import glob import glob
from collections import namedtuple from collections import namedtuple
from binascii import hexlify, unhexlify from binascii import unhexlify
settings = {} settings = {}
@ -64,7 +64,7 @@ def calc_hash_str(blk_hdr):
hash = calc_hdr_hash(blk_hdr) hash = calc_hdr_hash(blk_hdr)
hash = bufreverse(hash) hash = bufreverse(hash)
hash = wordreverse(hash) hash = wordreverse(hash)
hash_str = hexlify(hash).decode('utf-8') hash_str = hash.hex()
return hash_str return hash_str
def get_blk_dt(blk_hdr): def get_blk_dt(blk_hdr):
@ -242,7 +242,7 @@ class BlockDataCopier:
inMagic = inhdr[:4] inMagic = inhdr[:4]
if (inMagic != self.settings['netmagic']): if (inMagic != self.settings['netmagic']):
print("Invalid magic: " + hexlify(inMagic).decode('utf-8')) print("Invalid magic: " + inMagic.hex())
return return
inLenLE = inhdr[4:] inLenLE = inhdr[4:]
su = struct.unpack("<I", inLenLE) su = struct.unpack("<I", inLenLE)

View File

@ -22,7 +22,6 @@
https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py
""" """
import binascii
import asyncio import asyncio
import zmq import zmq
import zmq.asyncio import zmq.asyncio
@ -72,52 +71,52 @@ class ZMQHandler():
if topic == b"hashblock": if topic == b"hashblock":
print('- HASH BLOCK ('+sequence+') -') print('- HASH BLOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"hashchainlock": elif topic == b"hashchainlock":
print('- HASH CHAINLOCK ('+sequence+') -') print('- HASH CHAINLOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"hashtx": elif topic == b"hashtx":
print ('- HASH TX ('+sequence+') -') print ('- HASH TX ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"hashtxlock": elif topic == b"hashtxlock":
print('- HASH TX LOCK ('+sequence+') -') print('- HASH TX LOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"hashgovernancevote": elif topic == b"hashgovernancevote":
print('- HASH GOVERNANCE VOTE ('+sequence+') -') print('- HASH GOVERNANCE VOTE ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"hashgovernanceobject": elif topic == b"hashgovernanceobject":
print('- HASH GOVERNANCE OBJECT ('+sequence+') -') print('- HASH GOVERNANCE OBJECT ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"hashinstantsenddoublespend": elif topic == b"hashinstantsenddoublespend":
print('- HASH IS DOUBLE SPEND ('+sequence+') -') print('- HASH IS DOUBLE SPEND ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"rawblock": elif topic == b"rawblock":
print('- RAW BLOCK HEADER ('+sequence+') -') print('- RAW BLOCK HEADER ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8")) print(body[:80].hex())
elif topic == b"rawchainlock": elif topic == b"rawchainlock":
print('- RAW CHAINLOCK ('+sequence+') -') print('- RAW CHAINLOCK ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8")) print(body[:80].hex())
elif topic == b"rawchainlocksig": elif topic == b"rawchainlocksig":
print('- RAW CHAINLOCK SIG ('+sequence+') -') print('- RAW CHAINLOCK SIG ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8")) print(body[:80].hex())
elif topic == b"rawtx": elif topic == b"rawtx":
print('- RAW TX ('+sequence+') -') print('- RAW TX ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"rawtxlock": elif topic == b"rawtxlock":
print('- RAW TX LOCK ('+sequence+') -') print('- RAW TX LOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"rawtxlocksig": elif topic == b"rawtxlocksig":
print('- RAW TX LOCK SIG ('+sequence+') -') print('- RAW TX LOCK SIG ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"rawgovernancevote": elif topic == b"rawgovernancevote":
print('- RAW GOVERNANCE VOTE ('+sequence+') -') print('- RAW GOVERNANCE VOTE ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"rawgovernanceobject": elif topic == b"rawgovernanceobject":
print('- RAW GOVERNANCE OBJECT ('+sequence+') -') print('- RAW GOVERNANCE OBJECT ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
elif topic == b"rawinstantsenddoublespend": elif topic == b"rawinstantsenddoublespend":
print('- RAW IS DOUBLE SPEND ('+sequence+') -') print('- RAW IS DOUBLE SPEND ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8")) print(body.hex())
# schedule ourselves to receive the next message # schedule ourselves to receive the next message
asyncio.ensure_future(self.handle()) asyncio.ensure_future(self.handle())

View File

@ -1,137 +0,0 @@
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
ZMQ example using python3's asyncio
Dash should be started with the command line arguments:
dashd -testnet -daemon \
-zmqpubrawtx=tcp://127.0.0.1:28332 \
-zmqpubrawblock=tcp://127.0.0.1:28332 \
-zmqpubhashtx=tcp://127.0.0.1:28332 \
-zmqpubhashblock=tcp://127.0.0.1:28332
We use the asyncio library here. `self.handle()` installs itself as a
future at the end of the function. Since it never returns with the event
loop having an empty stack of futures, this creates an infinite loop. An
alternative is to wrap the contents of `handle` inside `while True`.
The `@asyncio.coroutine` decorator and the `yield from` syntax found here
was introduced in python 3.4 and has been deprecated in favor of the `async`
and `await` keywords respectively.
A blocking example using python 2.7 can be obtained from the git history:
https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py
"""
import binascii
import asyncio
import zmq
import zmq.asyncio
import signal
import struct
import sys
if (sys.version_info.major, sys.version_info.minor) < (3, 4):
print("This example only works with Python 3.4 and greater")
sys.exit(1)
port = 28332
class ZMQHandler():
def __init__(self):
self.loop = asyncio.get_event_loop()
self.zmqContext = zmq.asyncio.Context()
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashchainlock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtx")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtxlock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashgovernancevote")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashgovernanceobject")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashinstantsenddoublespend")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawblock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawchainlock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawchainlocksig")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtx")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtxlock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtxlocksig")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawgovernancevote")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawgovernanceobject")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawinstantsenddoublespend")
self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % port)
@asyncio.coroutine
def handle(self) :
msg = yield from self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
sequence = "Unknown"
if len(msg[-1]) == 4:
msgSequence = struct.unpack('<I', msg[-1])[-1]
sequence = str(msgSequence)
if topic == b"hashblock":
print('- HASH BLOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"hashchainlock":
print('- HASH CHAINLOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"hashtx":
print ('- HASH TX ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"hashtxlock":
print('- HASH TX LOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"hashgovernancevote":
print('- HASH GOVERNANCE VOTE ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"hashgovernanceobject":
print('- HASH GOVERNANCE OBJECT ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"hashinstantsenddoublespend":
print('- HASH IS DOUBLE SPEND ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"rawblock":
print('- RAW BLOCK HEADER ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8"))
elif topic == b"rawchainlock":
print('- RAW CHAINLOCK ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8"))
elif topic == b"rawchainlocksig":
print('- RAW CHAINLOCK SIG ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8"))
elif topic == b"rawtx":
print('- RAW TX ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"rawtxlock":
print('- RAW TX LOCK ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"rawtxlocksig":
print('- RAW TX LOCK SIG ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"rawgovernancevote":
print('- RAW GOVERNANCE VOTE ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"rawgovernanceobject":
print('- RAW GOVERNANCE OBJECT ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
elif topic == b"rawinstantsenddoublespend":
print('- RAW IS DOUBLE SPEND ('+sequence+') -')
print(binascii.hexlify(body).decode("utf-8"))
# schedule ourselves to receive the next message
asyncio.ensure_future(self.handle())
def start(self):
self.loop.add_signal_handler(signal.SIGINT, self.stop)
self.loop.create_task(self.handle())
self.loop.run_forever()
def stop(self):
self.loop.stop()
self.zmqContext.destroy()
daemon = ZMQHandler()
daemon.start()

View File

@ -35,7 +35,7 @@ Install the required dependencies: Ubuntu & Debian
For macOS cross compilation: For macOS cross compilation:
sudo apt-get install curl librsvg2-bin libtiff-tools bsdmainutils imagemagick libcap-dev libz-dev libbz2-dev python-setuptools sudo apt-get install curl librsvg2-bin libtiff-tools bsdmainutils imagemagick libcap-dev libz-dev libbz2-dev python3-setuptools
For Win32/Win64 cross compilation: For Win32/Win64 cross compilation:

View File

@ -136,7 +136,7 @@ class AddressIndexTest(BitcoinTestFramework):
tx.vout = [CTxOut(10, scriptPubKey), CTxOut(11, scriptPubKey)] tx.vout = [CTxOut(10, scriptPubKey), CTxOut(11, scriptPubKey)]
tx.rehash() tx.rehash()
signed_tx = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) signed_tx = self.nodes[0].signrawtransactionwithwallet(tx.serialize().hex())
sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True) sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
self.nodes[0].generate(1) self.nodes[0].generate(1)
@ -166,7 +166,7 @@ class AddressIndexTest(BitcoinTestFramework):
amount = int(unspent[0]["amount"] * 100000000) - tx_fee_sat amount = int(unspent[0]["amount"] * 100000000) - tx_fee_sat
tx.vout = [CTxOut(amount, scriptPubKey2)] tx.vout = [CTxOut(amount, scriptPubKey2)]
tx.rehash() tx.rehash()
signed_tx = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) signed_tx = self.nodes[0].signrawtransactionwithwallet(tx.serialize().hex())
spending_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True) spending_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
@ -180,7 +180,7 @@ class AddressIndexTest(BitcoinTestFramework):
tx.vout = [CTxOut(change_amount, scriptPubKey2), CTxOut(send_amount, scriptPubKey)] tx.vout = [CTxOut(change_amount, scriptPubKey2), CTxOut(send_amount, scriptPubKey)]
tx.rehash() tx.rehash()
signed_tx = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) signed_tx = self.nodes[0].signrawtransactionwithwallet(tx.serialize().hex())
sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True) sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
@ -261,7 +261,7 @@ class AddressIndexTest(BitcoinTestFramework):
amount = int(unspent[0]["amount"] * 100000000) - tx_fee_sat amount = int(unspent[0]["amount"] * 100000000) - tx_fee_sat
tx.vout = [CTxOut(amount, scriptPubKey3)] tx.vout = [CTxOut(amount, scriptPubKey3)]
tx.rehash() tx.rehash()
signed_tx = self.nodes[2].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) signed_tx = self.nodes[2].signrawtransactionwithwallet(tx.serialize().hex())
memtxid1 = self.nodes[2].sendrawtransaction(signed_tx["hex"], True) memtxid1 = self.nodes[2].sendrawtransaction(signed_tx["hex"], True)
self.bump_mocktime(2) self.bump_mocktime(2)
@ -275,7 +275,7 @@ class AddressIndexTest(BitcoinTestFramework):
CTxOut(int(amount / 4), scriptPubKey4) CTxOut(int(amount / 4), scriptPubKey4)
] ]
tx2.rehash() tx2.rehash()
signed_tx2 = self.nodes[2].signrawtransactionwithwallet(binascii.hexlify(tx2.serialize()).decode("utf-8")) signed_tx2 = self.nodes[2].signrawtransactionwithwallet(tx2.serialize().hex())
memtxid2 = self.nodes[2].sendrawtransaction(signed_tx2["hex"], True) memtxid2 = self.nodes[2].sendrawtransaction(signed_tx2["hex"], True)
self.bump_mocktime(2) self.bump_mocktime(2)
@ -302,7 +302,7 @@ class AddressIndexTest(BitcoinTestFramework):
tx.vout = [CTxOut(int(amount / 2 - 10000), scriptPubKey2)] tx.vout = [CTxOut(int(amount / 2 - 10000), scriptPubKey2)]
tx.rehash() tx.rehash()
self.nodes[2].importprivkey(privKey3) self.nodes[2].importprivkey(privKey3)
signed_tx3 = self.nodes[2].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) signed_tx3 = self.nodes[2].signrawtransactionwithwallet(tx.serialize().hex())
self.nodes[2].sendrawtransaction(signed_tx3["hex"], True) self.nodes[2].sendrawtransaction(signed_tx3["hex"], True)
self.bump_mocktime(2) self.bump_mocktime(2)
@ -334,7 +334,7 @@ class AddressIndexTest(BitcoinTestFramework):
tx.vout = [CTxOut(amount, address1script)] tx.vout = [CTxOut(amount, address1script)]
tx.rehash() tx.rehash()
self.nodes[0].importprivkey(privkey1) self.nodes[0].importprivkey(privkey1)
signed_tx = self.nodes[0].signrawtransactionwithwallet(binascii.hexlify(tx.serialize()).decode("utf-8")) signed_tx = self.nodes[0].signrawtransactionwithwallet(tx.serialize().hex())
self.nodes[0].sendrawtransaction(signed_tx["hex"], True) self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
self.sync_all() self.sync_all()

View File

@ -58,7 +58,7 @@ class BIP68Test(BitcoinTestFramework):
self.nodes[0].sendtoaddress(new_addr, 2) # send 2 BTC self.nodes[0].sendtoaddress(new_addr, 2) # send 2 BTC
utxos = self.nodes[0].listunspent(0, 0) utxos = self.nodes[0].listunspent(0, 0)
assert(len(utxos) > 0) assert len(utxos) > 0
utxo = utxos[0] utxo = utxos[0]
@ -248,7 +248,7 @@ class BIP68Test(BitcoinTestFramework):
self.nodes[0].generate(1) self.nodes[0].generate(1)
cur_time += 600 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=True)
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) 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 # Advance the time on the node so that we can test timelocks
self.nodes[0].setmocktime(cur_time+600) self.nodes[0].setmocktime(cur_time+600)
self.nodes[0].generate(1) 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 # Now that tx2 is not in the mempool, a sequence locked spend should
# succeed # succeed
tx3 = test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) 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) 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 # One more test, this time using height locks
tx4 = test_nonzero_locks(tx3, self.nodes[0], self.relayfee, use_height_lock=True) 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 # Now try combining confirmed and unconfirmed inputs
tx5 = test_nonzero_locks(tx4, self.nodes[0], self.relayfee, use_height_lock=True) 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() utxos = self.nodes[0].listunspent()
tx5.vin.append(CTxIn(COutPoint(int(utxos[0]["txid"], 16), utxos[0]["vout"]), nSequence=1)) 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 # If we invalidate the tip, tx3 should get added to the mempool, causing
# tx4 to be removed (fails sequence-lock). # tx4 to be removed (fails sequence-lock).
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
assert(tx4.hash not in self.nodes[0].getrawmempool()) assert tx4.hash not in self.nodes[0].getrawmempool()
assert(tx3.hash 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 # Now mine 2 empty blocks to reorg out the current tip (labeled tip-1 in
# diagram above). # diagram above).
@ -314,8 +314,8 @@ class BIP68Test(BitcoinTestFramework):
cur_time += 1 cur_time += 1
mempool = self.nodes[0].getrawmempool() mempool = self.nodes[0].getrawmempool()
assert(tx3.hash not in mempool) assert tx3.hash not in mempool
assert(tx2.hash in mempool) assert tx2.hash in mempool
# Reset the chain and get rid of the mocktimed-blocks # Reset the chain and get rid of the mocktimed-blocks
self.nodes[0].setmocktime(self.mocktime) 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 # being run, then it's possible the test has activated the soft fork, and
# this test should be moved to run earlier, or deleted. # this test should be moved to run earlier, or deleted.
def test_bip68_not_consensus(self): 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) txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 2)
tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid)) tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid))

View File

@ -726,7 +726,7 @@ class FullBlockTest(BitcoinTestFramework):
self.move_tip(57) self.move_tip(57)
b58 = self.next_block(58, spend=out[17]) b58 = self.next_block(58, spend=out[17])
tx = CTransaction() 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.vin.append(CTxIn(COutPoint(out[17].sha256, 42), CScript([OP_TRUE]), 0xffffffff))
tx.vout.append(CTxOut(0, b"")) tx.vout.append(CTxOut(0, b""))
tx.calc_sha256() tx.calc_sha256()
@ -777,7 +777,7 @@ class FullBlockTest(BitcoinTestFramework):
tx.nLockTime = 0xffffffff # this locktime is non-final tx.nLockTime = 0xffffffff # this locktime is non-final
tx.vin.append(CTxIn(COutPoint(out[18].sha256, 0))) # don't set nSequence tx.vin.append(CTxIn(COutPoint(out[18].sha256, 0))) # don't set nSequence
tx.vout.append(CTxOut(0, CScript([OP_TRUE]))) tx.vout.append(CTxOut(0, CScript([OP_TRUE])))
assert(tx.vin[0].nSequence < 0xffffffff) assert tx.vin[0].nSequence < 0xffffffff
tx.calc_sha256() tx.calc_sha256()
b62 = self.update_block(62, [tx]) b62 = self.update_block(62, [tx])
self.send_blocks([b62], success=False, reject_code=16, reject_reason=b'bad-txns-nonfinal') 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 # now check that tx78 and tx79 have been put back into the peer's mempool
mempool = self.nodes[0].getrawmempool() mempool = self.nodes[0].getrawmempool()
assert_equal(len(mempool), 2) assert_equal(len(mempool), 2)
assert(tx78.hash in mempool) assert tx78.hash in mempool
assert(tx79.hash in mempool) assert tx79.hash in mempool
# Test invalid opcodes in dead execution paths. # Test invalid opcodes in dead execution paths.
# #

View File

@ -13,7 +13,7 @@ from test_framework.messages import CTransaction, msg_block, ToHex
from test_framework.mininode import mininode_lock, P2PInterface from test_framework.mininode import mininode_lock, P2PInterface
from test_framework.script import CScript, OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP, CScriptNum from test_framework.script import CScript, OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP, CScriptNum
from test_framework.test_framework import BitcoinTestFramework 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 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 # First we show that this tx is valid except for CLTV by getting it
# rejected from the mempool for exactly that reason. # 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. # Now we verify that a block with this transaction is also invalid.
block.vtx.append(spendtx) block.vtx.append(spendtx)

View File

@ -106,7 +106,7 @@ def send_generic_input_tx(node, coinbases, address):
def create_bip68txs(node, bip68inputs, txversion, address, locktime_delta=0): def create_bip68txs(node, bip68inputs, txversion, address, locktime_delta=0):
"""Returns a list of bip68 transactions with different bits set.""" """Returns a list of bip68 transactions with different bits set."""
txs = [] txs = []
assert(len(bip68inputs) >= 16) assert len(bip68inputs) >= 16
for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)):
locktime = relative_locktime(sdf, srhb, stf, srlb) locktime = relative_locktime(sdf, srhb, stf, srlb)
tx = create_transaction(node, bip68inputs[i], address, Decimal("499.98")) 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): def create_bip112txs(node, bip112inputs, varyOP_CSV, txversion, address, locktime_delta=0):
"""Returns a list of bip68 transactions with different bits set.""" """Returns a list of bip68 transactions with different bits set."""
txs = [] txs = []
assert(len(bip112inputs) >= 16) assert len(bip112inputs) >= 16
for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)):
locktime = relative_locktime(sdf, srhb, stf, srlb) locktime = relative_locktime(sdf, srhb, stf, srlb)
tx = create_transaction(node, bip112inputs[i], address, Decimal("499.98")) tx = create_transaction(node, bip112inputs[i], address, Decimal("499.98"))

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test recovery from a crash during chainstate writing. """Test recovery from a crash during chainstate writing.
@ -28,18 +28,12 @@
import errno import errno
import http.client import http.client
import random import random
import sys
import time import time
from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex
from test_framework.test_framework import BitcoinTestFramework from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, create_confirmed_utxos, hex_str_to_bytes 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): class ChainstateWriteCrashTest(BitcoinTestFramework):
def set_test_params(self): def set_test_params(self):
@ -106,14 +100,7 @@ class ChainstateWriteCrashTest(BitcoinTestFramework):
try: try:
self.nodes[node_index].submitblock(block) self.nodes[node_index].submitblock(block)
return True return True
except http.client.BadStatusLine as e: except (http.client.CannotSendRequest, http.client.RemoteDisconnected) 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:
self.log.debug("node %d submitblock raised exception: %s", node_index, e) self.log.debug("node %d submitblock raised exception: %s", node_index, e)
return False return False
except OSError as e: except OSError as e:

View File

@ -12,7 +12,7 @@ from test_framework.messages import msg_block
from test_framework.mininode import mininode_lock, P2PInterface from test_framework.mininode import mininode_lock, P2PInterface
from test_framework.script import CScript from test_framework.script import CScript
from test_framework.test_framework import BitcoinTestFramework 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 DERSIG_HEIGHT = 1251
@ -114,7 +114,7 @@ class BIP66Test(BitcoinTestFramework):
# First we show that this tx is valid except for DERSIG by getting it # First we show that this tx is valid except for DERSIG by getting it
# rejected from the mempool for exactly that reason. # 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. # Now we verify that a block with this transaction is also invalid.
block.vtx.append(spendtx) block.vtx.append(spendtx)

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, ToHex
@ -26,7 +26,7 @@ class DIP0020ActivationTest(BitcoinTestFramework):
# We should have some coins already # We should have some coins already
utxos = self.node.listunspent() utxos = self.node.listunspent()
assert (len(utxos) > 0) assert len(utxos) > 0
# Send some coins to a P2SH address constructed using disabled opcodes # Send some coins to a P2SH address constructed using disabled opcodes
utxo = utxos[len(utxos) - 1] utxo = utxos[len(utxos) - 1]
@ -38,9 +38,9 @@ class DIP0020ActivationTest(BitcoinTestFramework):
txid = self.node.sendrawtransaction(tx_signed_hex) txid = self.node.sendrawtransaction(tx_signed_hex)
# This tx should be completely valid, should be included in mempool and mined in the next block # 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) self.node.generate(1)
assert (txid not in set(self.node.getrawmempool())) assert txid not in set(self.node.getrawmempool())
# Create spending tx # Create spending tx
value = int(value - self.relayfee * COIN) value = int(value - self.relayfee * COIN)
@ -64,7 +64,7 @@ class DIP0020ActivationTest(BitcoinTestFramework):
# Should be spendable now # Should be spendable now
tx0id = self.node.sendrawtransaction(tx0_hex) tx0id = self.node.sendrawtransaction(tx0_hex)
assert (tx0id in set(self.node.getrawmempool())) assert tx0id in set(self.node.getrawmempool())
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # 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) # Make sure we're below block 135 (which activates dip3)
self.log.info("testing rejection of ProTx before dip3 activation") 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 = [] mns = []
@ -60,7 +60,7 @@ class DIP3Test(BitcoinTestFramework):
# block 150 starts enforcing DIP3 MN payments # block 150 starts enforcing DIP3 MN payments
self.nodes[0].generate(150 - self.nodes[0].getblockcount()) 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.log.info("mining final block for DIP3 activation")
self.nodes[0].generate(1) self.nodes[0].generate(1)
@ -163,7 +163,7 @@ class DIP3Test(BitcoinTestFramework):
if 'addresses' in out['scriptPubKey']: if 'addresses' in out['scriptPubKey']:
if expected_payee in out['scriptPubKey']['addresses'] and out['valueSat'] == expected_amount: if expected_payee in out['scriptPubKey']['addresses'] and out['valueSat'] == expected_amount:
found_multisig_payee = True found_multisig_payee = True
assert(found_multisig_payee) assert found_multisig_payee
self.log.info("testing reusing of collaterals for replaced MNs") self.log.info("testing reusing of collaterals for replaced MNs")
for i in range(0, 5): for i in range(0, 5):
@ -192,7 +192,7 @@ class DIP3Test(BitcoinTestFramework):
old_dmnState = mn.node.masternode("status")["dmnState"] old_dmnState = mn.node.masternode("status")["dmnState"]
old_voting_address = old_dmnState["votingAddress"] old_voting_address = old_dmnState["votingAddress"]
new_voting_address = node.getnewaddress() 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 # also check if funds from payout address are used when no fee source address is specified
node.sendtoaddress(mn.rewards_address, 0.001) node.sendtoaddress(mn.rewards_address, 0.001)
node.protx('update_registrar', mn.protx_hash, "", new_voting_address, "") node.protx('update_registrar', mn.protx_hash, "", new_voting_address, "")
@ -200,9 +200,9 @@ class DIP3Test(BitcoinTestFramework):
self.sync_all() self.sync_all()
new_dmnState = mn.node.masternode("status")["dmnState"] new_dmnState = mn.node.masternode("status")["dmnState"]
new_voting_address_from_rpc = new_dmnState["votingAddress"] 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 # 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): def prepare_mn(self, node, idx, alias):
mn = Masternode() mn = Masternode()
@ -230,7 +230,7 @@ class DIP3Test(BitcoinTestFramework):
if txout['value'] == Decimal(1000): if txout['value'] == Decimal(1000):
mn.collateral_vout = txout['n'] mn.collateral_vout = txout['n']
break break
assert(mn.collateral_vout != -1) assert mn.collateral_vout != -1
# register a protx MN and also fund it (using collateral inside ProRegTx) # register a protx MN and also fund it (using collateral inside ProRegTx)
def register_fund_mn(self, node, mn): def register_fund_mn(self, node, mn):
@ -247,7 +247,7 @@ class DIP3Test(BitcoinTestFramework):
if txout['value'] == Decimal(1000): if txout['value'] == Decimal(1000):
mn.collateral_vout = txout['n'] mn.collateral_vout = txout['n']
break break
assert(mn.collateral_vout != -1) assert mn.collateral_vout != -1
# create a protx MN which refers to an existing collateral # create a protx MN which refers to an existing collateral
def register_mn(self, node, mn): def register_mn(self, node, mn):
@ -276,7 +276,7 @@ class DIP3Test(BitcoinTestFramework):
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
info = self.nodes[0].protx('info', mn.protx_hash) 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): def test_protx_update_service(self, mn):
self.nodes[0].sendtoaddress(mn.fundsAddr, 0.001) self.nodes[0].sendtoaddress(mn.fundsAddr, 0.001)

View File

@ -64,11 +64,11 @@ class LLMQCoinbaseCommitmentsTest(DashTestFramework):
expectedDeleted = [] expectedDeleted = []
expectedUpdated = [new_mn.proTxHash] expectedUpdated = [new_mn.proTxHash]
mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated) 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 # Now let the MN get enough confirmations and verify that the MNLISTDIFF now has confirmedHash != 0
self.confirm_mns() self.confirm_mns()
mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated) 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" # Spend the collateral of the previously added MN and test if it appears in "deletedMNs"
expectedDeleted = [new_mn.proTxHash] expectedDeleted = [new_mn.proTxHash]
@ -252,18 +252,18 @@ class LLMQCoinbaseCommitmentsTest(DashTestFramework):
self.wait_for_sporks_same() self.wait_for_sporks_same()
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0] 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) self.activate_dip8(slow_mode)
# Assert that merkleRootQuorums is present and 0 (we have no quorums yet) # Assert that merkleRootQuorums is present and 0 (we have no quorums yet)
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0] cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert_equal(cbtx["cbTx"]["version"], 2) assert_equal(cbtx["cbTx"]["version"], 2)
assert("merkleRootQuorums" in cbtx["cbTx"]) assert "merkleRootQuorums" in cbtx["cbTx"]
merkleRootQuorums = int(cbtx["cbTx"]["merkleRootQuorums"], 16) merkleRootQuorums = int(cbtx["cbTx"]["merkleRootQuorums"], 16)
if with_initial_quorum: if with_initial_quorum:
assert(merkleRootQuorums != 0) assert merkleRootQuorums != 0
else: else:
assert_equal(merkleRootQuorums, 0) assert_equal(merkleRootQuorums, 0)
@ -274,7 +274,7 @@ class LLMQCoinbaseCommitmentsTest(DashTestFramework):
# Mine quorum and verify that merkleRootQuorums has changed # Mine quorum and verify that merkleRootQuorums has changed
quorum = self.mine_quorum() quorum = self.mine_quorum()
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0] 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 return quorum

View File

@ -50,7 +50,7 @@ class LLMQChainLocksTest(DashTestFramework):
self.log.info("Assert that all blocks up until the tip are chainlocked") self.log.info("Assert that all blocks up until the tip are chainlocked")
for h in range(1, self.nodes[0].getblockcount()): for h in range(1, self.nodes[0].getblockcount()):
block = self.nodes[0].getblock(self.nodes[0].getblockhash(h)) 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") self.log.info("Isolate node, mine on another, and reconnect")
isolate_node(self.nodes[0]) isolate_node(self.nodes[0])
@ -58,7 +58,7 @@ class LLMQChainLocksTest(DashTestFramework):
node0_tip = self.nodes[0].getbestblockhash() node0_tip = self.nodes[0].getbestblockhash()
self.nodes[1].generatetoaddress(5, node0_mining_addr) self.nodes[1].generatetoaddress(5, node0_mining_addr)
self.wait_for_chainlocked_block(self.nodes[1], self.nodes[1].getbestblockhash()) 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) reconnect_isolated_node(self.nodes[0], 1)
self.nodes[1].generatetoaddress(1, node0_mining_addr) self.nodes[1].generatetoaddress(1, node0_mining_addr)
self.wait_for_chainlocked_block_all_nodes(self.nodes[1].getbestblockhash()) 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) self.nodes[1].generatetoaddress(1, node0_mining_addr)
good_tip = self.nodes[1].getbestblockhash() good_tip = self.nodes[1].getbestblockhash()
self.wait_for_chainlocked_block(self.nodes[1], good_tip) 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) reconnect_isolated_node(self.nodes[0], 1)
self.nodes[1].generatetoaddress(1, node0_mining_addr) self.nodes[1].generatetoaddress(1, node0_mining_addr)
self.wait_for_chainlocked_block_all_nodes(self.nodes[1].getbestblockhash()) 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[0].getblock(self.nodes[0].getbestblockhash())["previousblockhash"] == good_tip
assert(self.nodes[1].getblock(self.nodes[1].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") self.log.info("The tip mined while this node was isolated should be marked conflicting now")
found = False found = False
for tip in self.nodes[0].getchaintips(2): for tip in self.nodes[0].getchaintips(2):
if tip["hash"] == bad_tip: if tip["hash"] == bad_tip:
assert(tip["status"] == "conflicting") assert tip["status"] == "conflicting"
found = True found = True
break break
assert(found) assert found
self.log.info("Keep node connected and let it try to reorg the chain") self.log.info("Keep node connected and let it try to reorg the chain")
good_tip = self.nodes[0].getbestblockhash() good_tip = self.nodes[0].getbestblockhash()
@ -91,41 +91,41 @@ class LLMQChainLocksTest(DashTestFramework):
self.stop_node(0) self.stop_node(0)
self.start_node(0) self.start_node(0)
connect_nodes(self.nodes[0], 1) 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.nodes[0].invalidateblock(good_tip)
self.log.info("Now try to reorg the chain") self.log.info("Now try to reorg the chain")
self.nodes[0].generate(2) self.nodes[0].generate(2)
time.sleep(6) 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] bad_tip = self.nodes[0].generate(2)[-1]
time.sleep(6) time.sleep(6)
assert(self.nodes[0].getbestblockhash() == bad_tip) assert self.nodes[0].getbestblockhash() == bad_tip
assert(self.nodes[1].getbestblockhash() == good_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.log.info("Now let the node which is on the wrong chain reorg back to the locked chain")
self.nodes[0].reconsiderblock(good_tip) 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_fork = good_tip
good_tip = self.nodes[1].generatetoaddress(1, node0_mining_addr)[-1] # this should mark bad_tip as conflicting 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) 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 found = False
for tip in self.nodes[0].getchaintips(2): for tip in self.nodes[0].getchaintips(2):
if tip["hash"] == bad_tip: if tip["hash"] == bad_tip:
assert(tip["status"] == "conflicting") assert tip["status"] == "conflicting"
found = True found = True
break break
assert(found) assert found
self.log.info("Should switch to the best non-conflicting tip (not to the most work chain) on restart") 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.stop_node(0)
self.start_node(0) self.start_node(0)
self.nodes[0].invalidateblock(good_fork) self.nodes[0].invalidateblock(good_fork)
self.stop_node(0) self.stop_node(0)
self.start_node(0) self.start_node(0)
time.sleep(1) 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") self.log.info("Isolate a node and let it create some transactions which won't get IS locked")
isolate_node(self.nodes[0]) isolate_node(self.nodes[0])
@ -137,11 +137,11 @@ class LLMQChainLocksTest(DashTestFramework):
node0_tip = self.nodes[0].generate(1)[-1] node0_tip = self.nodes[0].generate(1)[-1]
for txid in txs: for txid in txs:
tx = self.nodes[0].getrawtransaction(txid, 1) tx = self.nodes[0].getrawtransaction(txid, 1)
assert("confirmations" not in tx) assert "confirmations" not in tx
time.sleep(1) time.sleep(1)
node0_tip_block = self.nodes[0].getblock(node0_tip) node0_tip_block = self.nodes[0].getblock(node0_tip)
assert(not node0_tip_block["chainlock"]) assert not node0_tip_block["chainlock"]
assert(node0_tip_block["previousblockhash"] == good_tip) 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.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.nodes[0].spork("SPORK_2_INSTANTSEND_ENABLED", 4070908800)
self.log.info("Now the TXs should be included") 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") self.log.info("Assert that TXs got included now")
for txid in txs: for txid in txs:
tx = self.nodes[0].getrawtransaction(txid, 1) 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 # 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 # 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") self.log.info("Re-enable network on first node and wait for chainlock")

View File

@ -33,7 +33,7 @@ class LLMQConnections(DashTestFramework):
count = self.get_mn_connection_count(mn.node) count = self.get_mn_connection_count(mn.node)
total_count += count total_count += count
assert_greater_than_or_equal(count, 2) assert_greater_than_or_equal(count, 2)
assert(total_count < 40) assert total_count < 40
self.check_reconnects(2) self.check_reconnects(2)

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
@ -75,11 +75,11 @@ class LLMQDKGErrors(DashTestFramework):
for m in q['members']: for m in q['members']:
if m['proTxHash'] == proTxHash: if m['proTxHash'] == proTxHash:
if expectedValid: if expectedValid:
assert(m['valid']) assert m['valid']
else: else:
assert(not m['valid']) assert not m['valid']
else: else:
assert(m['valid']) assert m['valid']
def heal_masternodes(self, blockCount): def heal_masternodes(self, blockCount):
# We're not testing PoSe here, so lets heal the MNs :) # We're not testing PoSe here, so lets heal the MNs :)

View File

@ -108,7 +108,7 @@ class LLMQ_IS_CL_Conflicts(DashTestFramework):
if test_block_conflict: if test_block_conflict:
# The block shouldn't be accepted/connected but it should be known to node 0 now # The block shouldn't be accepted/connected but it should be known to node 0 now
submit_result = self.nodes[0].submitblock(ToHex(block)) 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) 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)) submit_result = self.nodes[1].submitblock(ToHex(block))
if test_block_conflict: if test_block_conflict:
# Node 1 should receive the block from node 0 and should not accept it again via submitblock # 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: else:
# The block should get accepted now, and at the same time prune the conflicting ISLOCKs # 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) self.wait_for_chainlocked_block_all_nodes(block.hash)
@ -217,7 +217,7 @@ class LLMQ_IS_CL_Conflicts(DashTestFramework):
self.sync_all() self.sync_all()
# Assert that the conflicting tx got mined and the locked TX is not valid # 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) 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 # 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) self.test_node.send_islock(islock)
time.sleep(5) time.sleep(5)
assert(self.nodes[0].getbestblockhash() == good_tip) assert self.nodes[0].getbestblockhash() == good_tip
assert(self.nodes[1].getbestblockhash() == good_tip) assert self.nodes[1].getbestblockhash() == good_tip
# Send the actual transaction and mine it # Send the actual transaction and mine it
self.nodes[0].sendrawtransaction(rawtx2) self.nodes[0].sendrawtransaction(rawtx2)
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
assert(self.nodes[0].getrawtransaction(rawtx2_txid, True)['confirmations'] > 0) assert self.nodes[0].getrawtransaction(rawtx2_txid, True)['confirmations'] > 0
assert(self.nodes[1].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[0].getrawtransaction(rawtx2_txid, True)['instantlock']
assert(self.nodes[1].getrawtransaction(rawtx2_txid, True)['instantlock']) assert self.nodes[1].getrawtransaction(rawtx2_txid, True)['instantlock']
assert(self.nodes[0].getbestblockhash() != good_tip) assert self.nodes[0].getbestblockhash() != good_tip
assert(self.nodes[1].getbestblockhash() != good_tip) assert self.nodes[1].getbestblockhash() != good_tip
# Check that the CL-ed block overrides the one with islocks # 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 self.nodes[0].spork("SPORK_19_CHAINLOCKS_ENABLED", 0) # Re-enable ChainLocks to accept clsig

View File

@ -116,7 +116,7 @@ class LLMQ_IS_RetroactiveSigning(DashTestFramework):
# Make node0 consider the TX as safe # Make node0 consider the TX as safe
self.bump_mocktime(10 * 60 + 1) self.bump_mocktime(10 * 60 + 1)
block = self.nodes[0].generate(1)[0] 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.wait_for_chainlocked_block_all_nodes(block)
self.log.info("testing retroactive signing with partially known TX and all nodes session timeout") 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 # Make node 0 consider the TX as safe
self.bump_mocktime(10 * 60 + 1) self.bump_mocktime(10 * 60 + 1)
block = self.nodes[0].generate(1)[0] 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.wait_for_chainlocked_block_all_nodes(block)
def test_single_node_session_timeout(self, do_cycle_llmqs): 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 # Make node 0 consider the TX as safe
self.bump_mocktime(10 * 60 + 1) self.bump_mocktime(10 * 60 + 1)
block = self.nodes[0].generate(1)[0] 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.wait_for_chainlocked_block_all_nodes(block)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -55,7 +55,7 @@ class LLMQSigningTest(DashTestFramework):
wait_until(lambda: check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout) wait_until(lambda: check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout)
def assert_sigs_nochange(hasrecsigs, isconflicting1, isconflicting2, 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 # Initial state
wait_for_sigs(False, False, False, 1) wait_for_sigs(False, False, False, 1)
@ -65,11 +65,11 @@ class LLMQSigningTest(DashTestFramework):
assert_sigs_nochange(False, False, False, 3) assert_sigs_nochange(False, False, False, 3)
# Sign second share and test optional quorumHash parameter, should not result in recovered sig # 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 # 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) assert_sigs_nochange(False, False, False, 3)
# 2. Providing a valid quorum hash should succeed and cause no changes for sigss # 2. Providing a valid quorum hash should succeed and cause no changes for sigss
quorumHash = self.mninfo[1].node.quorum("selectquorum", 100, id)["quorumHash"] 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) assert_sigs_nochange(False, False, False, 3)
# Sign third share and test optional submit parameter if spork21 is enabled, should result in recovered sig # Sign third share and test optional submit parameter if spork21 is enabled, should result in recovered sig
# and conflict for msgHashConflict # and conflict for msgHashConflict
@ -115,13 +115,13 @@ class LLMQSigningTest(DashTestFramework):
height = node.getblockcount() height = node.getblockcount()
height_bad = node.getblockheader(recsig["quorumHash"])["height"] height_bad = node.getblockheader(recsig["quorumHash"])["height"]
hash_bad = node.getblockhash(0) hash_bad = node.getblockhash(0)
assert(node.quorum("verify", 100, id, msgHash, recsig["sig"])) assert node.quorum("verify", 100, id, msgHash, recsig["sig"])
assert(node.quorum("verify", 100, id, msgHash, recsig["sig"], "", height)) 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, msgHashConflict, recsig["sig"])
assert not node.quorum("verify", 100, id, msgHash, recsig["sig"], "", height_bad) assert not node.quorum("verify", 100, id, msgHash, recsig["sig"], "", height_bad)
# Use specific quorum # Use specific quorum
assert(node.quorum("verify", 100, id, msgHash, 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 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) 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 # Mine one more quorum, so that we have 2 active ones, nothing should change

View File

@ -90,7 +90,7 @@ class LLMQSimplePoSeTest(DashTestFramework):
for i in range(3): for i in range(3):
self.mine_quorum(expected_connections=expected_connections) self.mine_quorum(expected_connections=expected_connections)
for mn in self.mninfo: 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): def test_banning(self, invalidate_proc, expected_connections):
mninfos_online = self.mninfo.copy() mninfos_online = self.mninfo.copy()
@ -108,7 +108,7 @@ class LLMQSimplePoSeTest(DashTestFramework):
self.reset_probe_timeouts() 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) 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: if not went_offline:
# we do not include PoSe banned mns in quorums, so the next one should have 1 contributor less # 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 # Make sure this tx "safe" to mine even when InstantSend and ChainLocks are no longer functional
self.bump_mocktime(60 * 10 + 1) self.bump_mocktime(60 * 10 + 1)
self.nodes[0].generate(1) self.nodes[0].generate(1)
assert(not self.check_banned(mn)) assert not self.check_banned(mn)
if restart: if restart:
self.stop_node(mn.node.index) self.stop_node(mn.node.index)

View File

@ -77,7 +77,7 @@ class MultiKeySporkTest(BitcoinTestFramework):
def test_spork(self, spork_name, final_value): def test_spork(self, spork_name, final_value):
# check test spork default state # check test spork default state
for node in self.nodes: 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) self.bump_mocktime(1)
# first and second signers set spork value # first and second signers set spork value
@ -86,11 +86,11 @@ class MultiKeySporkTest(BitcoinTestFramework):
# spork change requires at least 3 signers # spork change requires at least 3 signers
time.sleep(10) time.sleep(10)
for node in self.nodes: 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 # restart with no extra args to trigger CheckAndRemove
self.restart_node(0) 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 # restart again with corect_params, should resync spork parts from other nodes
self.restart_node(0, self.node0_extra_args) 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 # restart with no extra args to trigger CheckAndRemove, should reset the spork back to its default
self.restart_node(0) 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 # restart again with corect_params, should resync sporks from other nodes
self.restart_node(0, self.node0_extra_args) 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_2_INSTANTSEND_ENABLED', 2)
self.test_spork('SPORK_3_INSTANTSEND_BLOCK_FILTERING', 3) self.test_spork('SPORK_3_INSTANTSEND_BLOCK_FILTERING', 3)
for node in self.nodes: 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_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_3_INSTANTSEND_BLOCK_FILTERING') == 3
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework 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') assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'started')
ql = self.nodes[0].quorum("list") ql = self.nodes[0].quorum("list")
assert_equal(len(ql), 1) assert_equal(len(ql), 1)
assert("llmq_test_v17" not in ql) assert "llmq_test_v17" not in ql
self.nodes[0].generate(10) self.nodes[0].generate(10)
assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'locked_in') assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'locked_in')
ql = self.nodes[0].quorum("list") ql = self.nodes[0].quorum("list")
assert_equal(len(ql), 1) assert_equal(len(ql), 1)
assert("llmq_test_v17" not in ql) assert "llmq_test_v17" not in ql
self.nodes[0].generate(10) self.nodes[0].generate(10)
assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'active') assert_equal(get_bip9_status(self.nodes[0], 'dip0020')['status'], 'active')
ql = self.nodes[0].quorum("list") ql = self.nodes[0].quorum("list")
assert_equal(len(ql), 2) assert_equal(len(ql), 2)
assert("llmq_test_v17" in ql) assert "llmq_test_v17" in ql
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -17,7 +17,7 @@ from test_framework.blocktools import create_coinbase, create_block, create_tran
from test_framework.messages import CTransaction from test_framework.messages import CTransaction
from test_framework.script import CScript from test_framework.script import CScript
from test_framework.test_framework import BitcoinTestFramework 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)" NULLDUMMY_ERROR = "non-mandatory-script-verify-flag (Dummy CHECKMULTISIG argument must be zero) (code 64)"
@ -27,7 +27,7 @@ def trueDummy(tx):
newscript = [] newscript = []
for i in scriptSig: for i in scriptSig:
if (len(newscript) == 0): if (len(newscript) == 0):
assert(len(i) == 0) assert len(i) == 0
newscript.append(b'\x51') newscript.append(b'\x51')
else: else:
newscript.append(i) 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]") 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)] 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)) 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.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") 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) test2tx = create_transaction(self.nodes[0], txid2, self.ms_address, 47)
trueDummy(test2tx) 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.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) 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) test4tx = create_transaction(self.nodes[0], test2tx.hash, self.address, 46)
test6txs=[CTransaction(test4tx)] test6txs=[CTransaction(test4tx)]
trueDummy(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.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]") self.log.info("Test 6: NULLDUMMY compliant transactions should be accepted to mempool and in block after activation [432]")
for i in test6txs: 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) self.block_submit(self.nodes[0], test6txs, True)
@ -93,7 +93,7 @@ class NULLDUMMYTest(BitcoinTestFramework):
block.hashMerkleRoot = block.calc_merkle_root() block.hashMerkleRoot = block.calc_merkle_root()
block.rehash() block.rehash()
block.solve() block.solve()
node.submitblock(bytes_to_hex_str(block.serialize())) node.submitblock(block.serialize().hex())
if (accept): if (accept):
assert_equal(node.getbestblockhash(), block.hash) assert_equal(node.getbestblockhash(), block.hash)
self.tip = block.sha256 self.tip = block.sha256

View File

@ -94,7 +94,7 @@ class ProxyTest(BitcoinTestFramework):
# Test: outgoing IPv4 connection through node # Test: outgoing IPv4 connection through node
node.addnode("15.61.23.23:1234", "onetry") node.addnode("15.61.23.23:1234", "onetry")
cmd = proxies[0].queue.get() 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 # 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.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"15.61.23.23") assert_equal(cmd.addr, b"15.61.23.23")
@ -108,7 +108,7 @@ class ProxyTest(BitcoinTestFramework):
# Test: outgoing IPv6 connection through node # Test: outgoing IPv6 connection through node
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry") node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
cmd = proxies[1].queue.get() 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 # 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.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534") 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 # Test: outgoing onion connection through node
node.addnode("bitcoinostk4e4re.onion:8333", "onetry") node.addnode("bitcoinostk4e4re.onion:8333", "onetry")
cmd = proxies[2].queue.get() cmd = proxies[2].queue.get()
assert(isinstance(cmd, Socks5Command)) assert isinstance(cmd, Socks5Command)
assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"bitcoinostk4e4re.onion") assert_equal(cmd.addr, b"bitcoinostk4e4re.onion")
assert_equal(cmd.port, 8333) assert_equal(cmd.port, 8333)
@ -134,7 +134,7 @@ class ProxyTest(BitcoinTestFramework):
# Test: outgoing DNS name connection through node # Test: outgoing DNS name connection through node
node.addnode("node.noumenon:8333", "onetry") node.addnode("node.noumenon:8333", "onetry")
cmd = proxies[3].queue.get() cmd = proxies[3].queue.get()
assert(isinstance(cmd, Socks5Command)) assert isinstance(cmd, Socks5Command)
assert_equal(cmd.atyp, AddressType.DOMAINNAME) assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"node.noumenon") assert_equal(cmd.addr, b"node.noumenon")
assert_equal(cmd.port, 8333) assert_equal(cmd.port, 8333)

View File

@ -144,7 +144,7 @@ class PruneTest(BitcoinTestFramework):
self.nodes[1].invalidateblock(curhash) self.nodes[1].invalidateblock(curhash)
curhash = self.nodes[1].getblockhash(invalidheight - 1) 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()) self.log.info("New best height: %d" % self.nodes[1].getblockcount())
# Mine one block to avoid automatic recovery from forks on restart # 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 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.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) self.nodes[0].invalidateblock(curchainhash)
assert(self.nodes[0].getblockcount() == self.mainchainheight) assert self.nodes[0].getblockcount() == self.mainchainheight
assert(self.nodes[0].getbestblockhash() == self.mainchainhash2) assert self.nodes[0].getbestblockhash() == self.mainchainhash2
goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1] goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1]
goalbestheight = first_reorg_height + 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") 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 for Node 2 to reorg to proper height
wait_until(lambda: self.nodes[2].getblockcount() >= goalbestheight, timeout=900) 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 # 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): def manual_test(self, node_number, use_timestamp):
# at this point, node has 995 blocks and has not yet run in prune mode # at this point, node has 995 blocks and has not yet run in prune mode

View File

@ -72,7 +72,7 @@ class SpentIndexTest(BitcoinTestFramework):
tx.vout = [CTxOut(amount, scriptPubKey)] tx.vout = [CTxOut(amount, scriptPubKey)]
tx.rehash() 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) txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
@ -107,7 +107,7 @@ class SpentIndexTest(BitcoinTestFramework):
tx2.vout = [CTxOut(amount - int(COIN / 10), scriptPubKey2)] tx2.vout = [CTxOut(amount - int(COIN / 10), scriptPubKey2)]
tx2.rehash() tx2.rehash()
self.nodes[0].importprivkey(privkey) 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) txid2 = self.nodes[0].sendrawtransaction(signed_tx2["hex"], True)
# Check the mempool index # Check the mempool index

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
@ -37,8 +37,8 @@ class SporkTest(BitcoinTestFramework):
def run_test(self): def run_test(self):
spork_default_state = self.get_test_spork_state(self.nodes[0]) spork_default_state = self.get_test_spork_state(self.nodes[0])
# check test spork default state matches on all nodes # 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[1]) == spork_default_state
assert(self.get_test_spork_state(self.nodes[2]) == spork_default_state) assert self.get_test_spork_state(self.nodes[2]) == spork_default_state
# check spork propagation for connected nodes # check spork propagation for connected nodes
spork_new_state = not spork_default_state spork_new_state = not spork_default_state
@ -50,8 +50,8 @@ class SporkTest(BitcoinTestFramework):
self.stop_node(1) self.stop_node(1)
self.start_node(0) self.start_node(0)
self.start_node(1) self.start_node(1)
assert(self.get_test_spork_state(self.nodes[0]) == 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) 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 # Generate one block to kick off masternode sync, which also starts sporks syncing for node2
self.nodes[1].generate(1) self.nodes[1].generate(1)

View File

@ -55,7 +55,7 @@ class TxIndexTest(BitcoinTestFramework):
tx.vout = [CTxOut(amount, scriptPubKey)] tx.vout = [CTxOut(amount, scriptPubKey)]
tx.rehash() 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) txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()

View File

@ -74,8 +74,8 @@ class VersionBitsWarningTest(BitcoinTestFramework):
node.generate(VB_PERIOD - VB_THRESHOLD + 1) node.generate(VB_PERIOD - VB_THRESHOLD + 1)
# Check that we're not getting any versionbit-related errors in get*info() # 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.getmininginfo()["warnings"])
assert(not VB_PATTERN.match(node.getnetworkinfo()["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") 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 # 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) node.generate(VB_PERIOD - VB_THRESHOLD)
# Check that get*info() shows the 51/100 unknown block version error. # 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.getmininginfo()["warnings"]
assert(WARN_UNKNOWN_RULES_MINED in node.getnetworkinfo()["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.") 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 # 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. # Generating one more block will be enough to generate an error.
node.generate(1) node.generate(1)
# Check that get*info() shows the versionbits unknown rules warning # 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.getmininginfo()["warnings"]
assert(WARN_UNKNOWN_RULES_ACTIVE in node.getnetworkinfo()["warnings"]) assert WARN_UNKNOWN_RULES_ACTIVE in node.getnetworkinfo()["warnings"]
# Check that the alert file shows the versionbits unknown rules warning # Check that the alert file shows the versionbits unknown rules warning
wait_until(lambda: self.versionbits_in_alert_file(), timeout=60) wait_until(lambda: self.versionbits_in_alert_file(), timeout=60)

View File

@ -16,7 +16,7 @@ class TestBitcoinCli(BitcoinTestFramework):
"""Main test logic""" """Main test logic"""
cli_response = self.nodes[0].cli("-version").send_cli() 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`") self.log.info("Compare responses from getwalletinfo RPC and `dash-cli getwalletinfo`")
cli_response = self.nodes[0].cli.getwalletinfo() cli_response = self.nodes[0].cli.getwalletinfo()

View File

@ -30,14 +30,14 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read() out1 = conn.getresponse().read()
assert(b'"error":null' in out1) assert b'"error":null' in out1
assert(conn.sock!=None) #according to http/1.1 connection must still be open! assert conn.sock!=None #according to http/1.1 connection must still be open!
#send 2nd request without closing connection #send 2nd request without closing connection
conn.request('POST', '/', '{"method": "getchaintips"}', headers) conn.request('POST', '/', '{"method": "getchaintips"}', headers)
out1 = conn.getresponse().read() out1 = conn.getresponse().read()
assert(b'"error":null' in out1) #must also response with a correct json-rpc message 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 conn.sock!=None #according to http/1.1 connection must still be open!
conn.close() conn.close()
#same should be if we add keep-alive because this should be the std. behaviour #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.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read() out1 = conn.getresponse().read()
assert(b'"error":null' in out1) assert b'"error":null' in out1
assert(conn.sock!=None) #according to http/1.1 connection must still be open! assert conn.sock!=None #according to http/1.1 connection must still be open!
#send 2nd request without closing connection #send 2nd request without closing connection
conn.request('POST', '/', '{"method": "getchaintips"}', headers) conn.request('POST', '/', '{"method": "getchaintips"}', headers)
out1 = conn.getresponse().read() out1 = conn.getresponse().read()
assert(b'"error":null' in out1) #must also response with a correct json-rpc message 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 conn.sock!=None #according to http/1.1 connection must still be open!
conn.close() conn.close()
#now do the same with "Connection: close" #now do the same with "Connection: close"
@ -64,8 +64,8 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read() out1 = conn.getresponse().read()
assert(b'"error":null' in out1) assert b'"error":null' in out1
assert(conn.sock==None) #now the connection must be closed after the response assert conn.sock==None #now the connection must be closed after the response
#node1 (2nd node) is running with disabled keep-alive option #node1 (2nd node) is running with disabled keep-alive option
urlNode1 = urllib.parse.urlparse(self.nodes[1].url) urlNode1 = urllib.parse.urlparse(self.nodes[1].url)
@ -76,7 +76,7 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read() 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 #node2 (third node) is running with standard keep-alive parameters which means keep-alive is on
urlNode2 = urllib.parse.urlparse(self.nodes[2].url) urlNode2 = urllib.parse.urlparse(self.nodes[2].url)
@ -87,8 +87,8 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect() conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read() out1 = conn.getresponse().read()
assert(b'"error":null' in out1) assert b'"error":null' in out1
assert(conn.sock!=None) #connection must be closed because dashd should use keep-alive by default assert conn.sock!=None #connection must be closed because dashd should use keep-alive by default
# Check excessive request size # Check excessive request size
conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port) conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port)

View File

@ -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) 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) output = BytesIO(bin_response)
chain_height, = unpack("i", output.read(4)) 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(bb_hash, response_hash) # check if getutxo's chaintip during calculation was fine
assert_equal(chain_height, 102) # chain height must be 102 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) 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) 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) 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) assert_equal(blockhash, bb_hash)
# Check invalid blockhashbyheight requests # Check invalid blockhashbyheight requests

View File

@ -11,7 +11,6 @@ from test_framework.test_framework import (
BitcoinTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq) BitcoinTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq)
from test_framework.messages import dashhash from test_framework.messages import dashhash
from test_framework.util import (assert_equal, from test_framework.util import (assert_equal,
bytes_to_hex_str,
hash256, hash256,
) )
@ -95,10 +94,10 @@ class ZMQTest (BitcoinTestFramework):
assert_equal(hash256(hex), txid) assert_equal(hash256(hex), txid)
# Should receive the generated block hash. # Should receive the generated block hash.
hash = bytes_to_hex_str(self.hashblock.receive()) hash = self.hashblock.receive().hex()
assert_equal(genhashes[x], hash) assert_equal(genhashes[x], hash)
# The block should only have the coinbase txid. # 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. # Should receive the generated raw block.
block = self.rawblock.receive() block = self.rawblock.receive()
@ -110,11 +109,11 @@ class ZMQTest (BitcoinTestFramework):
# Should receive the broadcasted txid. # Should receive the broadcasted txid.
txid = self.hashtx.receive() 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. # Should receive the broadcasted raw transaction.
hex = self.rawtx.receive() 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") self.log.info("Test the getzmqnotifications RPC")
assert_equal(self.nodes[0].getzmqnotifications(), [ assert_equal(self.nodes[0].getzmqnotifications(), [

View File

@ -19,7 +19,7 @@ finally:
from test_framework.test_framework import ( from test_framework.test_framework import (
DashTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq) DashTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq)
from test_framework.mininode import P2PInterface 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 ( from test_framework.messages import (
CBlock, CBlock,
CGovernanceObject, CGovernanceObject,
@ -154,7 +154,7 @@ class DashZMQTest (DashTestFramework):
# Make sure the recovered sig exists by RPC # Make sure the recovered sig exists by RPC
rpc_recovered_sig = self.get_recovered_sig(request_id, msg_hash) rpc_recovered_sig = self.get_recovered_sig(request_id, msg_hash)
# Validate hashrecoveredsig # 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) assert_equal(zmq_recovered_sig_hash, msg_hash)
# Validate rawrecoveredsig # Validate rawrecoveredsig
zmq_recovered_sig_raw = CRecoveredSig() 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.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.id), rpc_recovered_sig['id'])
assert_equal(uint256_to_string(zmq_recovered_sig_raw.msgHash), rpc_recovered_sig['msgHash']) 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 = [ recovered_sig_publishers = [
ZMQPublisher.hash_recovered_sig, ZMQPublisher.hash_recovered_sig,
@ -208,24 +208,24 @@ class DashZMQTest (DashTestFramework):
rpc_chain_lock_hash = rpc_chain_locked_block["hash"] rpc_chain_lock_hash = rpc_chain_locked_block["hash"]
assert_equal(generated_hash, rpc_chain_lock_hash) assert_equal(generated_hash, rpc_chain_lock_hash)
# Validate hashchainlock # 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) assert_equal(zmq_chain_lock_hash, rpc_best_chain_lock_hash)
# Validate rawchainlock # Validate rawchainlock
zmq_chain_locked_block = CBlock() zmq_chain_locked_block = CBlock()
zmq_chain_locked_block.deserialize(self.receive(ZMQPublisher.raw_chain_lock)) 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) assert_equal(zmq_chain_locked_block.hash, rpc_chain_lock_hash)
# Validate rawchainlocksig # Validate rawchainlocksig
zmq_chain_lock_sig_stream = self.receive(ZMQPublisher.raw_chain_lock_sig) zmq_chain_lock_sig_stream = self.receive(ZMQPublisher.raw_chain_lock_sig)
zmq_chain_locked_block = CBlock() zmq_chain_locked_block = CBlock()
zmq_chain_locked_block.deserialize(zmq_chain_lock_sig_stream) 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 = msg_clsig()
zmq_chain_lock.deserialize(zmq_chain_lock_sig_stream) zmq_chain_lock.deserialize(zmq_chain_lock_sig_stream)
assert_equal(zmq_chain_lock.height, rpc_chain_lock_height) 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(uint256_to_string(zmq_chain_lock.blockHash), rpc_chain_lock_hash)
assert_equal(zmq_chain_locked_block.hash, 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 # Unsubscribe from ChainLock messages
self.unsubscribe(chain_lock_publishers) 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']) 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]) self.wait_for_instantlock(rpc_raw_tx_1_hash, self.nodes[0])
# Validate hashtxlock # 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']) assert_equal(zmq_tx_lock_hash, rpc_raw_tx_1['txid'])
# Validate rawtxlock # Validate rawtxlock
zmq_tx_lock_raw = CTransaction() zmq_tx_lock_raw = CTransaction()
zmq_tx_lock_raw.deserialize(self.receive(ZMQPublisher.raw_tx_lock)) 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']) assert_equal(zmq_tx_lock_raw.hash, rpc_raw_tx_1['txid'])
# Validate rawtxlocksig # Validate rawtxlocksig
zmq_tx_lock_sig_stream = self.receive(ZMQPublisher.raw_tx_lock_sig) zmq_tx_lock_sig_stream = self.receive(ZMQPublisher.raw_tx_lock_sig)
zmq_tx_lock_tx = CTransaction() zmq_tx_lock_tx = CTransaction()
zmq_tx_lock_tx.deserialize(zmq_tx_lock_sig_stream) 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']) assert_equal(zmq_tx_lock_tx.hash, rpc_raw_tx_1['txid'])
zmq_tx_lock = msg_islock() zmq_tx_lock = msg_islock()
zmq_tx_lock.deserialize(zmq_tx_lock_sig_stream) zmq_tx_lock.deserialize(zmq_tx_lock_sig_stream)
@ -271,18 +271,18 @@ class DashZMQTest (DashTestFramework):
# which already got the InstantSend lock. # which already got the InstantSend lock.
assert_raises_rpc_error(-26, "tx-txlock-conflict", self.nodes[0].sendrawtransaction, rpc_raw_tx_2['hex']) assert_raises_rpc_error(-26, "tx-txlock-conflict", self.nodes[0].sendrawtransaction, rpc_raw_tx_2['hex'])
# Validate hashinstantsenddoublespend # Validate hashinstantsenddoublespend
zmq_double_spend_hash2 = 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 = bytes_to_hex_str(self.receive(ZMQPublisher.hash_instantsend_doublespend).read(32)) 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_hash2, rpc_raw_tx_2['txid'])
assert_equal(zmq_double_spend_hash1, rpc_raw_tx_1['txid']) assert_equal(zmq_double_spend_hash1, rpc_raw_tx_1['txid'])
# Validate rawinstantsenddoublespend # Validate rawinstantsenddoublespend
zmq_double_spend_tx_2 = CTransaction() zmq_double_spend_tx_2 = CTransaction()
zmq_double_spend_tx_2.deserialize(self.receive(ZMQPublisher.raw_instantsend_doublespend)) 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']) assert_equal(zmq_double_spend_tx_2.hash, rpc_raw_tx_2['txid'])
zmq_double_spend_tx_1 = CTransaction() zmq_double_spend_tx_1 = CTransaction()
zmq_double_spend_tx_1.deserialize(self.receive(ZMQPublisher.raw_instantsend_doublespend)) 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']) assert_equal(zmq_double_spend_tx_1.hash, rpc_raw_tx_1['txid'])
# No islock notifications when tx is not received yet # No islock notifications when tx is not received yet
self.nodes[0].generate(1) self.nodes[0].generate(1)
@ -293,7 +293,7 @@ class DashZMQTest (DashTestFramework):
time.sleep(1) time.sleep(1)
try: try:
self.receive(ZMQPublisher.hash_tx_lock, zmq.NOBLOCK) self.receive(ZMQPublisher.hash_tx_lock, zmq.NOBLOCK)
assert(False) assert False
except zmq.ZMQError: except zmq.ZMQError:
# this is expected # this is expected
pass pass
@ -301,7 +301,7 @@ class DashZMQTest (DashTestFramework):
self.test_node.send_tx(FromHex(msg_tx(), rpc_raw_tx_3['hex'])) 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]) self.wait_for_instantlock(rpc_raw_tx_3['txid'], self.nodes[0])
# Validate hashtxlock # 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']) assert_equal(zmq_tx_lock_hash, rpc_raw_tx_3['txid'])
# Drop test node connection # Drop test node connection
self.nodes[0].disconnect_p2ps() self.nodes[0].disconnect_p2ps()
@ -337,7 +337,7 @@ class DashZMQTest (DashTestFramework):
self.sync_blocks() self.sync_blocks()
rpc_proposal_hash = self.nodes[0].gobject("submit", "0", proposal_rev, proposal_time, proposal_hex, collateral) rpc_proposal_hash = self.nodes[0].gobject("submit", "0", proposal_rev, proposal_time, proposal_hex, collateral)
# Validate hashgovernanceobject # 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) assert_equal(zmq_governance_object_hash, rpc_proposal_hash)
zmq_governance_object_raw = CGovernanceObject() zmq_governance_object_raw = CGovernanceObject()
zmq_governance_object_raw.deserialize(self.receive(ZMQPublisher.raw_governance_object)) 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]) 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) rpc_proposal_votes = self.nodes[0].gobject('getcurrentvotes', rpc_proposal_hash)
# Validate hashgovernancevote # Validate hashgovernancevote
zmq_governance_vote_hash = bytes_to_hex_str(self.receive(ZMQPublisher.hash_governance_vote).read(32)) zmq_governance_vote_hash = self.receive(ZMQPublisher.hash_governance_vote).read(32).hex()
assert(zmq_governance_vote_hash in rpc_proposal_votes) assert zmq_governance_vote_hash in rpc_proposal_votes
# Validate rawgovernancevote # Validate rawgovernancevote
zmq_governance_vote_raw = CGovernanceVote() zmq_governance_vote_raw = CGovernanceVote()
zmq_governance_vote_raw.deserialize(self.receive(ZMQPublisher.raw_governance_vote)) zmq_governance_vote_raw.deserialize(self.receive(ZMQPublisher.raw_governance_vote))

View File

@ -26,7 +26,6 @@ from test_framework.script import (
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_rpc_error, assert_raises_rpc_error,
bytes_to_hex_str,
hex_str_to_bytes, hex_str_to_bytes,
wait_until, wait_until,
) )
@ -99,7 +98,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0)))
tx.vout[0].nValue -= int(fee * COIN) # Double the fee tx.vout[0].nValue -= int(fee * COIN) # Double the fee
tx.vin[0].nSequence = BIP125_SEQUENCE_NUMBER + 1 # Now, opt out of RBF 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))) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0_reject)))
txid_0_reject = tx.rehash() txid_0_reject = tx.rehash()
self.check_mempool_result( self.check_mempool_result(
@ -110,14 +109,14 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
self.log.info('A transaction that conflicts with an unconfirmed tx') self.log.info('A transaction that conflicts with an unconfirmed tx')
# Send the transaction that replaces the mempool transaction and opts out of replaceability # 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 # take original raw_tx_0
tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0))) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_0)))
tx.vout[0].nValue -= int(4 * fee * COIN) # Set more fee tx.vout[0].nValue -= int(4 * fee * COIN) # Set more fee
# skip re-signing the tx # skip re-signing the tx
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '18: txn-mempool-conflict'}], 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, allowhighfees=True,
) )
@ -127,13 +126,13 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
# skip re-signing the tx # skip re-signing the tx
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': 'missing-inputs'}], 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') 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.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 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) 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 # 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( raw_tx_spend_both = node.signrawtransactionwithwallet(node.createrawtransaction(
@ -165,17 +164,17 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
# Reference tx should be valid on itself # Reference tx should be valid on itself
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': True}], 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') self.log.info('A transaction with no outputs')
tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference))) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference)))
tx.vout = [] tx.vout = []
# Skip re-signing the transaction for context independent checks from now on # 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( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-empty'}], 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') 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())) tx.vin = [tx.vin[0]] * math.ceil(MAX_BLOCK_SIZE / len(tx.vin[0].serialize()))
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-oversize'}], 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') self.log.info('A transaction with negative output value')
@ -191,7 +190,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.vout[0].nValue *= -1 tx.vout[0].nValue *= -1
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-negative'}], 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') self.log.info('A transaction with too large output value')
@ -199,7 +198,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.vout[0].nValue = 21000000 * COIN + 1 tx.vout[0].nValue = 21000000 * COIN + 1
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-vout-toolarge'}], 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') 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 tx.vout[0].nValue = 21000000 * COIN
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-txouttotal-toolarge'}], 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') self.log.info('A transaction with duplicate inputs')
@ -216,7 +215,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.vin = [tx.vin[0]] * 2 tx.vin = [tx.vin[0]] * 2
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: bad-txns-inputs-duplicate'}], 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') self.log.info('A coinbase transaction')
@ -225,7 +224,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_coinbase_spent))) tx.deserialize(BytesIO(hex_str_to_bytes(raw_tx_coinbase_spent)))
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '16: coinbase'}], 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') self.log.info('Some nonstandard transactions')
@ -233,19 +232,19 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.nVersion = 4 # A version currently non-standard tx.nVersion = 4 # A version currently non-standard
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: version'}], 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.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference)))
tx.vout[0].scriptPubKey = CScript([OP_0]) # Some non-standard script tx.vout[0].scriptPubKey = CScript([OP_0]) # Some non-standard script
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptpubkey'}], 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.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference)))
tx.vin[0].scriptSig = CScript([OP_HASH160]) # Some not-pushonly scriptSig tx.vin[0].scriptSig = CScript([OP_HASH160]) # Some not-pushonly scriptSig
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: scriptsig-not-pushonly'}], 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.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference)))
tx.vin[0].scriptSig = CScript([b'a' * 1648]) # Some too large scriptSig (>1650 bytes) 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 tx.vout = [output_p2sh_burn] * num_scripts
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: tx-size'}], 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.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference)))
tx.vout[0] = output_p2sh_burn tx.vout[0] = output_p2sh_burn
tx.vout[0].nValue -= 1 # Make output smaller, such that it is dust for our policy tx.vout[0].nValue -= 1 # Make output smaller, such that it is dust for our policy
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: dust'}], 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.deserialize(BytesIO(hex_str_to_bytes(raw_tx_reference)))
tx.vout[0].scriptPubKey = CScript([OP_RETURN, b'\xff']) tx.vout[0].scriptPubKey = CScript([OP_RETURN, b'\xff'])
tx.vout = [tx.vout[0]] * 2 tx.vout = [tx.vout[0]] * 2
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: multi-op-return'}], 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') self.log.info('A timelocked transaction')
@ -282,7 +281,7 @@ class MempoolAcceptanceTest(BitcoinTestFramework):
tx.nLockTime = node.getblockcount() + 1 tx.nLockTime = node.getblockcount() + 1
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-final'}], 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') 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 # Can skip re-signing the tx because of early rejection
self.check_mempool_result( self.check_mempool_result(
result_expected=[{'txid': tx.rehash(), 'allowed': False, 'reject-reason': '64: non-BIP68-final'}], 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, allowhighfees=True,
) )

View File

@ -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) 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') 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) 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') self.log.info('Check that mempoolminfee is larger than minrelytxfee')
assert_equal(self.nodes[0].getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000')) assert_equal(self.nodes[0].getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000'))

View File

@ -30,7 +30,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
signedtx = node.signrawtransactionwithwallet(rawtx) signedtx = node.signrawtransactionwithwallet(rawtx)
txid = node.sendrawtransaction(signedtx['hex']) txid = node.sendrawtransaction(signedtx['hex'])
fulltx = node.getrawtransaction(txid, 1) 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) return (txid, send_value)
def run_test(self): def run_test(self):
@ -122,13 +122,13 @@ class MempoolPackagesTest(BitcoinTestFramework):
assert_equal(len(v_ancestors), len(chain)-1) assert_equal(len(v_ancestors), len(chain)-1)
for x in v_ancestors.keys(): for x in v_ancestors.keys():
assert_equal(mempool[x], v_ancestors[x]) 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) v_descendants = self.nodes[0].getmempooldescendants(chain[0], True)
assert_equal(len(v_descendants), len(chain)-1) assert_equal(len(v_descendants), len(chain)-1)
for x in v_descendants.keys(): for x in v_descendants.keys():
assert_equal(mempool[x], v_descendants[x]) 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 # Check that ancestor modified fees includes fee deltas from
# prioritisetransaction # prioritisetransaction

View File

@ -42,7 +42,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
assert_equal(set(self.nodes[0].getrawmempool()), set()) assert_equal(set(self.nodes[0].getrawmempool()), set())
for txid in spends1_id+spends2_id: for txid in spends1_id+spends2_id:
tx = self.nodes[0].gettransaction(txid) tx = self.nodes[0].gettransaction(txid)
assert(tx["confirmations"] > 0) assert tx["confirmations"] > 0
# Use invalidateblock to re-org back # Use invalidateblock to re-org back
for node in self.nodes: for node in self.nodes:
@ -52,7 +52,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
assert_equal(set(self.nodes[0].getrawmempool()), set(spends1_id+spends2_id)) assert_equal(set(self.nodes[0].getrawmempool()), set(spends1_id+spends2_id))
for txid in spends1_id+spends2_id: for txid in spends1_id+spends2_id:
tx = self.nodes[0].gettransaction(txid) tx = self.nodes[0].gettransaction(txid)
assert(tx["confirmations"] == 0) assert tx["confirmations"] == 0
# Generate another block, they should all get mined # Generate another block, they should all get mined
self.nodes[0].generate(1) self.nodes[0].generate(1)
@ -60,7 +60,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
assert_equal(set(self.nodes[0].getrawmempool()), set()) assert_equal(set(self.nodes[0].getrawmempool()), set())
for txid in spends1_id+spends2_id: for txid in spends1_id+spends2_id:
tx = self.nodes[0].gettransaction(txid) tx = self.nodes[0].gettransaction(txid)
assert(tx["confirmations"] > 0) assert tx["confirmations"] > 0
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -23,7 +23,6 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import ( from test_framework.util import (
assert_equal, assert_equal,
assert_raises_rpc_error, assert_raises_rpc_error,
bytes_to_hex_str as b2x,
) )
from test_framework.script import CScriptNum from test_framework.script import CScriptNum
@ -31,7 +30,7 @@ from test_framework.script import CScriptNum
def assert_template(node, block, expect, rehash=True): def assert_template(node, block, expect, rehash=True):
if rehash: if rehash:
block.hashMerkleRoot = block.calc_merkle_root() 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) assert_equal(rsp, expect)
@ -85,7 +84,7 @@ class MiningTest(BitcoinTestFramework):
assert_template(node, block, None) assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure") 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") self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block) bad_block = copy.deepcopy(block)
@ -94,10 +93,10 @@ class MiningTest(BitcoinTestFramework):
assert_template(node, bad_block, 'bad-cb-missing') assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction") 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") 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") self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block) bad_block = copy.deepcopy(block)
@ -124,7 +123,7 @@ class MiningTest(BitcoinTestFramework):
bad_block_sn = bytearray(block.serialize()) bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1)
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") self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block) bad_block = copy.deepcopy(block)
@ -169,22 +168,22 @@ class MiningTest(BitcoinTestFramework):
def chain_tip(b_hash, *, status='headers-only', branchlen=1): def chain_tip(b_hash, *, status='headers-only', branchlen=1):
return {'hash': b_hash, 'height': 202, 'branchlen': branchlen, 'status': status} return {'hash': b_hash, 'height': 202, 'branchlen': branchlen, 'status': status}
assert chain_tip(block.hash) not in filter_tip_keys(node.getchaintips()) 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()) 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()) assert chain_tip(block.hash) in filter_tip_keys(node.getchaintips())
bad_block_root = copy.deepcopy(block) bad_block_root = copy.deepcopy(block)
bad_block_root.hashMerkleRoot += 2 bad_block_root.hashMerkleRoot += 2
bad_block_root.solve() bad_block_root.solve()
assert chain_tip(bad_block_root.hash) not in filter_tip_keys(node.getchaintips()) 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()) assert chain_tip(bad_block_root.hash) in filter_tip_keys(node.getchaintips())
# Should still reject invalid blocks, even if we have the header: # 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()) 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: # 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()) assert chain_tip(bad_block_root.hash) in filter_tip_keys(node.getchaintips())
bad_block_lock = copy.deepcopy(block) bad_block_lock = copy.deepcopy(block)
@ -192,18 +191,18 @@ class MiningTest(BitcoinTestFramework):
bad_block_lock.vtx[0].rehash() bad_block_lock.vtx[0].rehash()
bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root() bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root()
bad_block_lock.solve() 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 # Build a "good" block on top of the submitted bad block
bad_block2 = copy.deepcopy(block) bad_block2 = copy.deepcopy(block)
bad_block2.hashPrevBlock = bad_block_lock.sha256 bad_block2.hashPrevBlock = bad_block_lock.sha256
bad_block2.solve() 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 # Should reject invalid header right away
bad_block_time = copy.deepcopy(block) bad_block_time = copy.deepcopy(block)
bad_block_time.nTime = 1 bad_block_time.nTime = 1
bad_block_time.solve() 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: # Should ask for the block from a p2p node, if they announce the header as well:
node.add_p2p_connection(P2PDataStore()) node.add_p2p_connection(P2PDataStore())
@ -214,10 +213,10 @@ class MiningTest(BitcoinTestFramework):
# Building a few blocks should give the same results # Building a few blocks should give the same results
node.generate(10) 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, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
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()))
node.submitheader(hexdata=b2x(CBlockHeader(block).serialize())) node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
node.submitheader(hexdata=b2x(CBlockHeader(bad_block_root).serialize())) node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -35,27 +35,27 @@ class GetBlockTemplateLPTest(BitcoinTestFramework):
longpollid = template['longpollid'] longpollid = template['longpollid']
# longpollid should not change between successive invocations if nothing else happens # longpollid should not change between successive invocations if nothing else happens
template2 = self.nodes[0].getblocktemplate() template2 = self.nodes[0].getblocktemplate()
assert(template2['longpollid'] == longpollid) assert template2['longpollid'] == longpollid
# Test 1: test that the longpolling wait if we do nothing # Test 1: test that the longpolling wait if we do nothing
thr = LongpollThread(self.nodes[0]) thr = LongpollThread(self.nodes[0])
thr.start() thr.start()
# check that thread still lives # check that thread still lives
thr.join(5) # wait 5 seconds or until thread exits 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 # Test 2: test that longpoll will terminate if another node generates a block
self.nodes[1].generate(1) # generate a block on another node self.nodes[1].generate(1) # generate a block on another node
# check that thread will exit now that new transaction entered mempool # check that thread will exit now that new transaction entered mempool
thr.join(5) # wait 5 seconds or until thread exits 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 # Test 3: test that longpoll will terminate if we generate a block ourselves
thr = LongpollThread(self.nodes[0]) thr = LongpollThread(self.nodes[0])
thr.start() thr.start()
self.nodes[0].generate(1) # generate a block on another node self.nodes[0].generate(1) # generate a block on another node
thr.join(5) # wait 5 seconds or until thread exits 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 # Test 4: test that introducing a new transaction into the mempool will terminate the longpoll
thr = LongpollThread(self.nodes[0]) thr = LongpollThread(self.nodes[0])

View File

@ -54,9 +54,9 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
sizes = [0, 0, 0] sizes = [0, 0, 0]
for i in range(3): for i in range(3):
for j in txids[i]: for j in txids[i]:
assert(j in mempool) assert j in mempool
sizes[i] += mempool[j]['size'] 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 # 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 # 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() mempool = self.nodes[0].getrawmempool()
self.log.info("Assert that prioritised transaction was mined") self.log.info("Assert that prioritised transaction was mined")
assert(txids[0][0] not in mempool) assert txids[0][0] not in mempool
assert(txids[0][1] in mempool) assert txids[0][1] in mempool
high_fee_tx = None high_fee_tx = None
for x in txids[2]: for x in txids[2]:
@ -75,7 +75,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
high_fee_tx = x high_fee_tx = x
# Something high-fee should have been mined! # 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 # Add a prioritisation before a tx is in the mempool (de-prioritising a
# high-fee transaction so that it's now low fee). # 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 # Check to make sure our high fee rate tx is back in the mempool
mempool = self.nodes[0].getrawmempool() 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 # Now verify the modified-high feerate transaction isn't mined before
# the other high fee transactions. Keep mining until our mempool has # the other high fee transactions. Keep mining until our mempool has
@ -98,14 +98,14 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
# transactions should have been. # transactions should have been.
mempool = self.nodes[0].getrawmempool() mempool = self.nodes[0].getrawmempool()
self.log.info("Assert that de-prioritised transaction is still in mempool") 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]: for x in txids[2]:
if (x != high_fee_tx): if (x != high_fee_tx):
assert(x not in mempool) assert x not in mempool
# Create a free transaction. Should be rejected. # Create a free transaction. Should be rejected.
utxo_list = self.nodes[0].listunspent() utxo_list = self.nodes[0].listunspent()
assert(len(utxo_list) > 0) assert len(utxo_list) > 0
utxo = utxo_list[0] utxo = utxo_list[0]
inputs = [] inputs = []
@ -118,7 +118,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
# This will raise an exception due to min relay fee not being met # 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_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 # 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 # 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") self.log.info("Assert that prioritised free transaction is accepted to mempool")
assert_equal(self.nodes[0].sendrawtransaction(tx_hex), tx_id) 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 # Test that calling prioritisetransaction is sufficient to trigger
# getblocktemplate to (eventually) return a new block. # getblocktemplate to (eventually) return a new block.
@ -137,7 +137,7 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
self.nodes[0].setmocktime(self.mocktime+10) self.nodes[0].setmocktime(self.mocktime+10)
new_template = self.nodes[0].getblocktemplate() new_template = self.nodes[0].getblocktemplate()
assert(template != new_template) assert template != new_template
if __name__ == '__main__': if __name__ == '__main__':
PrioritiseTransactionTest().main() PrioritiseTransactionTest().main()

View File

@ -26,7 +26,7 @@ class AddrReceiver(P2PInterface):
for addr in message.addrs: for addr in message.addrs:
assert_equal(addr.nServices, 1) assert_equal(addr.nServices, 1)
assert addr.ip.startswith('123.123.123.') assert addr.ip.startswith('123.123.123.')
assert (8333 <= addr.port < 8343) assert 8333 <= addr.port < 8343
self.addrv2_received_and_checked = True self.addrv2_received_and_checked = True
def wait_for_addrv2(self): def wait_for_addrv2(self):

View File

@ -109,7 +109,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Doesn't matter which node we use, just use node0. # Doesn't matter which node we use, just use node0.
block = self.build_block_on_tip(self.nodes[0]) block = self.build_block_on_tip(self.nodes[0])
self.test_node.send_and_ping(msg_block(block)) 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) self.nodes[0].generate(100)
total_value = block.vtx[0].vout[0].nValue total_value = block.vtx[0].vout[0].nValue
@ -153,7 +153,7 @@ class CompactBlocksTest(BitcoinTestFramework):
peer.clear_block_announcement() peer.clear_block_announcement()
block_hash = int(node.generate(1)[0], 16) block_hash = int(node.generate(1)[0], 16)
peer.wait_for_block_announcement(block_hash, timeout=30) peer.wait_for_block_announcement(block_hash, timeout=30)
assert(peer.block_announced) assert peer.block_announced
with mininode_lock: with mininode_lock:
assert predicate(peer), ( assert predicate(peer), (
@ -271,7 +271,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Now fetch and check the compact block # Now fetch and check the compact block
header_and_shortids = None header_and_shortids = None
with mininode_lock: 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 # Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids) 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) 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 # Now fetch and check the compact block
header_and_shortids = None header_and_shortids = None
with mininode_lock: 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 # Convert the on-the-wire representation to absolute indexes
header_and_shortids = HeaderAndShortIDs(test_node.last_message["cmpctblock"].header_and_shortids) 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) 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) assert_equal(header_and_shortids.header.sha256, block_hash)
# Make sure the prefilled_txn appears to have included the coinbase # 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) assert_equal(header_and_shortids.prefilled_txn[0].index, 0)
# Check that all prefilled_txn entries match what's in the block. # 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) assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
# Expect a getblocktxn message. # Expect a getblocktxn message.
with mininode_lock: 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() absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute()
assert_equal(absolute_indexes, [0]) # should be a coinbase request assert_equal(absolute_indexes, [0]) # should be a coinbase request
@ -396,7 +396,7 @@ class CompactBlocksTest(BitcoinTestFramework):
msg = msg_cmpctblock(compact_block.to_p2p()) msg = msg_cmpctblock(compact_block.to_p2p())
peer.send_and_ping(msg) peer.send_and_ping(msg)
with mininode_lock: 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() absolute_indexes = peer.last_message["getblocktxn"].block_txn_request.to_absolute()
assert_equal(absolute_indexes, expected_result) assert_equal(absolute_indexes, expected_result)
@ -434,7 +434,7 @@ class CompactBlocksTest(BitcoinTestFramework):
block = self.build_block_with_transactions(node, utxo, 5) block = self.build_block_with_transactions(node, utxo, 5)
self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue]) self.utxos.append([block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue])
test_node.send_and_ping(msg_tx(block.vtx[1])) 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 # Prefill 4 out of the 6 transactions, and verify that only the one
# that was not in the mempool is requested. # that was not in the mempool is requested.
@ -455,7 +455,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Make sure all transactions were accepted. # Make sure all transactions were accepted.
mempool = node.getrawmempool() mempool = node.getrawmempool()
for tx in block.vtx[1:]: for tx in block.vtx[1:]:
assert(tx.hash in mempool) assert tx.hash in mempool
# Clear out last request. # Clear out last request.
with mininode_lock: 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) test_tip_after_message(node, test_node, msg_cmpctblock(comp_block.to_p2p()), block.sha256)
with mininode_lock: with mininode_lock:
# Shouldn't have gotten a request for any transaction # 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 # Incorrectly responding to a getblocktxn shouldn't cause the block to be
# permanently failed. # permanently failed.
@ -484,7 +484,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Make sure all transactions were accepted. # Make sure all transactions were accepted.
mempool = node.getrawmempool() mempool = node.getrawmempool()
for tx in block.vtx[1:6]: for tx in block.vtx[1:6]:
assert(tx.hash in mempool) assert tx.hash in mempool
# Send compact block # Send compact block
comp_block = HeaderAndShortIDs() comp_block = HeaderAndShortIDs()
@ -492,7 +492,7 @@ class CompactBlocksTest(BitcoinTestFramework):
test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p())) test_node.send_and_ping(msg_cmpctblock(comp_block.to_p2p()))
absolute_indexes = [] absolute_indexes = []
with mininode_lock: 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() absolute_indexes = test_node.last_message["getblocktxn"].block_txn_request.to_absolute()
assert_equal(absolute_indexes, [6, 7, 8, 9, 10]) assert_equal(absolute_indexes, [6, 7, 8, 9, 10])
@ -514,7 +514,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# We should receive a getdata request # We should receive a getdata request
wait_until(lambda: "getdata" in test_node.last_message, timeout=10, lock=mininode_lock) 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_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) assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
# Deliver the block # Deliver the block
@ -605,7 +605,7 @@ class CompactBlocksTest(BitcoinTestFramework):
assert_equal(x["status"], "headers-only") assert_equal(x["status"], "headers-only")
found = True found = True
break break
assert(found) assert found
# Requesting this block via getblocktxn should silently fail # Requesting this block via getblocktxn should silently fail
# (to avoid fingerprinting attacks). # (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, # Test that we don't get disconnected if we relay a compact block with valid header,
# but invalid transactions. # but invalid transactions.
def test_invalid_tx_in_compactblock(self, node, test_node): def test_invalid_tx_in_compactblock(self, node, test_node):
assert(len(self.utxos)) assert len(self.utxos)
utxo = self.utxos[0] utxo = self.utxos[0]
block = self.build_block_with_transactions(node, utxo, 5) block = self.build_block_with_transactions(node, utxo, 5)
@ -653,7 +653,7 @@ class CompactBlocksTest(BitcoinTestFramework):
test_node.send_and_ping(msg) test_node.send_and_ping(msg)
# Check that the tip didn't advance # 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() test_node.sync_with_ping()
# Helper for enabling cb announcements # Helper for enabling cb announcements
@ -668,7 +668,7 @@ class CompactBlocksTest(BitcoinTestFramework):
peer.send_and_ping(msg) peer.send_and_ping(msg)
def test_compactblock_reconstruction_multiple_peers(self, node, stalling_peer, delivery_peer): 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): def announce_cmpct_block(node, peer):
utxo = self.utxos.pop(0) utxo = self.utxos.pop(0)
@ -689,7 +689,7 @@ class CompactBlocksTest(BitcoinTestFramework):
delivery_peer.sync_with_ping() delivery_peer.sync_with_ping()
mempool = node.getrawmempool() mempool = node.getrawmempool()
for tx in block.vtx[1:]: 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())) delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p()))
assert_equal(int(node.getbestblockhash(), 16), block.sha256) assert_equal(int(node.getbestblockhash(), 16), block.sha256)
@ -706,7 +706,7 @@ class CompactBlocksTest(BitcoinTestFramework):
cmpct_block.prefilled_txn[0].tx = CTxIn() cmpct_block.prefilled_txn[0].tx = CTxIn()
delivery_peer.send_and_ping(msg_cmpctblock(cmpct_block.to_p2p())) 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 = msg_blocktxn()
msg.block_transactions.blockhash = block.sha256 msg.block_transactions.blockhash = block.sha256

View File

@ -1,10 +1,10 @@
#!/usr/bin/env python3 #!/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 # Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import DashTestFramework 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 p2p_instantsend.py
@ -67,7 +67,7 @@ class InstantSendTest(DashTestFramework):
if i == self.isolated_idx: if i == self.isolated_idx:
continue continue
res = self.nodes[i].waitforblock(wrong_block, timeout) 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 # wait for long time only for first node
timeout = 1 timeout = 1
# send coins back to the controller node without waiting for confirmations # 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 # create doublespending transaction, but don't relay it
dblspnd_tx = self.create_raw_tx(sender, isolated, 0.5, 1, 100) 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 one node from network
isolate_node(isolated) isolate_node(isolated)
# send doublespend transaction to isolated node # send doublespend transaction to isolated node

View File

@ -134,9 +134,9 @@ class P2PLeakTest(BitcoinTestFramework):
wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0) wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0)
# Make sure no unexpected messages came in # Make sure no unexpected messages came in
assert(no_version_bannode.unexpected_msg == False) assert no_version_bannode.unexpected_msg == False
assert(no_version_idlenode.unexpected_msg == False) assert no_version_idlenode.unexpected_msg == False
assert(no_verack_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') self.log.info('Check that the version message does not leak the local address of the node')
time_begin = int(time.time()) time_begin = int(time.time())

View File

@ -113,7 +113,7 @@ class AcceptBlockTest(BitcoinTestFramework):
if x['hash'] == block_h1f.hash: if x['hash'] == block_h1f.hash:
assert_equal(x['status'], "headers-only") assert_equal(x['status'], "headers-only")
tip_entry_found = True 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) 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. # 4. Send another two block that build on the fork.
@ -130,7 +130,7 @@ class AcceptBlockTest(BitcoinTestFramework):
if x['hash'] == block_h2f.hash: if x['hash'] == block_h2f.hash:
assert_equal(x['status'], "headers-only") assert_equal(x['status'], "headers-only")
tip_entry_found = True 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. # But this block should be accepted by node since it has equal work.
self.nodes[0].getblock(block_h2f.hash) self.nodes[0].getblock(block_h2f.hash)
@ -149,7 +149,7 @@ class AcceptBlockTest(BitcoinTestFramework):
if x['hash'] == block_h3.hash: if x['hash'] == block_h3.hash:
assert_equal(x['status'], "headers-only") assert_equal(x['status'], "headers-only")
tip_entry_found = True tip_entry_found = True
assert(tip_entry_found) assert tip_entry_found
self.nodes[0].getblock(block_h3.hash) self.nodes[0].getblock(block_h3.hash)
# But this block should be accepted by node since it has more work. # 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: if x['hash'] == block_292.hash:
assert_equal(x['status'], "headers-only") assert_equal(x['status'], "headers-only")
tip_entry_found = True 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) 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)) test_node.send_message(msg_block(block_289f))

View File

@ -171,9 +171,9 @@ class BlockchainTest(BitcoinTestFramework):
assert_equal(chaintxstats['window_final_block_hash'], b1_hash) assert_equal(chaintxstats['window_final_block_hash'], b1_hash)
assert_equal(chaintxstats['window_final_block_height'], 1) assert_equal(chaintxstats['window_final_block_height'], 1)
assert_equal(chaintxstats['window_block_count'], 0) assert_equal(chaintxstats['window_block_count'], 0)
assert('window_tx_count' not in chaintxstats) assert 'window_tx_count' not in chaintxstats
assert('window_interval' not in chaintxstats) assert 'window_interval' not in chaintxstats
assert('txrate' not in chaintxstats) assert 'txrate' not in chaintxstats
def _test_gettxoutsetinfo(self): def _test_gettxoutsetinfo(self):
node = self.nodes[0] node = self.nodes[0]

View File

@ -6,7 +6,7 @@
from test_framework.messages import CTransaction from test_framework.messages import CTransaction
from test_framework.test_framework import BitcoinTestFramework 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 from io import BytesIO
@ -142,7 +142,7 @@ class DecodeScriptTest(BitcoinTestFramework):
# some more full transaction tests of varying specific scriptSigs. used instead of # some more full transaction tests of varying specific scriptSigs. used instead of
# tests in decodescript_script_sig because the decodescript RPC is specifically # tests in decodescript_script_sig because the decodescript RPC is specifically
# for working on scriptPubKeys (argh!). # 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:] signature = push_signature[2:]
der_signature = signature[:-2] der_signature = signature[:-2]
signature_sighash_decoded = der_signature + '[ALL]' signature_sighash_decoded = der_signature + '[ALL]'
@ -152,23 +152,23 @@ class DecodeScriptTest(BitcoinTestFramework):
# 1) P2PK scriptSig # 1) P2PK scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature) 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']) 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. # 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) 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']) assert_equal(signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 2) multisig scriptSig # 2) multisig scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes('00' + push_signature + push_signature_2) 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']) 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. # 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. # 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') 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']) assert_equal('OP_RETURN 3011020701010101010101020601010101010101', rpc_result['vin'][0]['scriptSig']['asm'])
def run_test(self): def run_test(self):

View File

@ -92,7 +92,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee'] fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) 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 # # simple test with two coins #
@ -105,7 +105,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee'] fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) 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 # # simple test with two coins #
@ -118,7 +118,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee'] fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) 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'], '') assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
@ -137,7 +137,7 @@ class RawTransactionsTest(BitcoinTestFramework):
for out in dec_tx['vout']: for out in dec_tx['vout']:
totalOut += out['value'] totalOut += out['value']
assert(len(dec_tx['vin']) > 0) assert len(dec_tx['vin']) > 0
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
@ -348,7 +348,7 @@ class RawTransactionsTest(BitcoinTestFramework):
#compare fee #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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(len(res_dec["vin"]), 1)
assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) 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) assert_greater_than(result["changepos"], -1)
############################################################### ###############################################################
@ -617,16 +617,16 @@ class RawTransactionsTest(BitcoinTestFramework):
result = self.nodes[3].fundrawtransaction(rawtx, True) result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"]) res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 2) 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["fee"], 0)
assert_greater_than(result["changepos"], -1) assert_greater_than(result["changepos"], -1)
assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10)
signedtx = self.nodes[3].signrawtransactionwithwallet(result["hex"]) signedtx = self.nodes[3].signrawtransactionwithwallet(result["hex"])
assert(not signedtx["complete"]) assert not signedtx["complete"]
signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"]) signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"])
assert(signedtx["complete"]) assert signedtx["complete"]
self.nodes[0].sendrawtransaction(signedtx["hex"]) self.nodes[0].sendrawtransaction(signedtx["hex"])
self.nodes[0].generate(1) self.nodes[0].generate(1)
self.sync_all() self.sync_all()
@ -658,10 +658,10 @@ class RawTransactionsTest(BitcoinTestFramework):
for out in res_dec['vout']: for out in res_dec['vout']:
if out['value'] > 1.0: if out['value'] > 1.0:
changeaddress += out['scriptPubKey']['addresses'][0] changeaddress += out['scriptPubKey']['addresses'][0]
assert(changeaddress != "") assert changeaddress != ""
nextaddr = self.nodes[3].getnewaddress() nextaddr = self.nodes[3].getnewaddress()
# Now the change address key should be removed from the keypool # Now the change address key should be removed from the keypool
assert(changeaddress != nextaddr) assert changeaddress != nextaddr
###################################### ######################################
# Test subtractFeeFromOutputs option # # Test subtractFeeFromOutputs option #

View File

@ -71,7 +71,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee'] fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) 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 # # simple test with two coins #
@ -84,7 +84,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee'] fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) 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 # # simple test with two coins #
@ -97,7 +97,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee'] fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) 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'], '') assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
@ -116,7 +116,7 @@ class RawTransactionsTest(BitcoinTestFramework):
for out in dec_tx['vout']: for out in dec_tx['vout']:
totalOut += out['value'] totalOut += out['value']
assert(len(dec_tx['vin']) > 0) assert len(dec_tx['vin']) > 0
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
@ -130,7 +130,7 @@ class RawTransactionsTest(BitcoinTestFramework):
utx = aUtx utx = aUtx
break break
assert(utx!=False) assert utx!=False
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 } outputs = { self.nodes[0].getnewaddress() : 10 }
@ -158,7 +158,7 @@ class RawTransactionsTest(BitcoinTestFramework):
utx = aUtx utx = aUtx
break break
assert(utx!=False) assert utx!=False
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance } outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance }
@ -187,7 +187,7 @@ class RawTransactionsTest(BitcoinTestFramework):
utx = aUtx utx = aUtx
break break
assert(utx!=False) assert utx!=False
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 } outputs = { self.nodes[0].getnewaddress() : 10 }
@ -232,7 +232,7 @@ class RawTransactionsTest(BitcoinTestFramework):
utx2 = aUtx utx2 = aUtx
assert(utx!=False) assert utx!=False
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60 } outputs = { self.nodes[0].getnewaddress() : 60 }
@ -274,7 +274,7 @@ class RawTransactionsTest(BitcoinTestFramework):
utx2 = aUtx utx2 = aUtx
assert(utx!=False) assert utx!=False
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 } outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 }
@ -308,7 +308,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawtxfund = self.nodes[2].fundrawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
raise AssertionError("Spent more than available") raise AssertionError("Spent more than available")
except JSONRPCException as e: 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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 #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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) fundedTx = self.nodes[1].fundrawtransaction(rawTx)
raise AssertionError("Wallet unlocked without passphrase") raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e: except JSONRPCException as e:
assert('Keypool ran out' in e.error['message']) assert 'Keypool ran out' in e.error['message']
#refill the keypool #refill the keypool
self.nodes[1].walletpassphrase("test", 100) self.nodes[1].walletpassphrase("test", 100)
@ -477,7 +477,7 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12) self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12)
raise AssertionError("Wallet unlocked without passphrase") raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e: except JSONRPCException as e:
assert('walletpassphrase' in e.error['message']) assert 'walletpassphrase' in e.error['message']
oldBalance = self.nodes[0].getbalance() oldBalance = self.nodes[0].getbalance()
@ -526,7 +526,7 @@ class RawTransactionsTest(BitcoinTestFramework):
#compare fee #compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) 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(len(res_dec["vin"]), 1)
assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) 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) assert_greater_than(result["changepos"], -1)
############################################################### ###############################################################
@ -603,16 +603,16 @@ class RawTransactionsTest(BitcoinTestFramework):
result = self.nodes[3].fundrawtransaction(rawtx, True) result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"]) res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 2) 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["fee"], 0)
assert_greater_than(result["changepos"], -1) assert_greater_than(result["changepos"], -1)
assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10)
signedtx = self.nodes[3].signrawtransactionwithwallet(result["hex"]) signedtx = self.nodes[3].signrawtransactionwithwallet(result["hex"])
assert(not signedtx["complete"]) assert not signedtx["complete"]
signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"]) signedtx = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"])
assert(signedtx["complete"]) assert signedtx["complete"]
self.nodes[0].sendrawtransaction(signedtx["hex"]) self.nodes[0].sendrawtransaction(signedtx["hex"])

View File

@ -21,17 +21,17 @@ class InvalidateTest(BitcoinTestFramework):
self.log.info("Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:") self.log.info("Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:")
self.log.info("Mine 4 blocks on Node 0") self.log.info("Mine 4 blocks on Node 0")
self.nodes[0].generate(4) self.nodes[0].generate(4)
assert(self.nodes[0].getblockcount() == 4) assert self.nodes[0].getblockcount() == 4
besthash = self.nodes[0].getbestblockhash() besthash = self.nodes[0].getbestblockhash()
self.log.info("Mine competing 6 blocks on Node 1") self.log.info("Mine competing 6 blocks on Node 1")
self.nodes[1].generate(6) 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") self.log.info("Connect nodes to force a reorg")
connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,0,1)
self.sync_blocks(self.nodes[0:2]) 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) 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") 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) connect_nodes_bi(self.nodes,1,2)
self.log.info("Sync node 2 to node 1 so both have 6 blocks") self.log.info("Sync node 2 to node 1 so both have 6 blocks")
self.sync_blocks(self.nodes[1:3]) 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.log.info("Invalidate block 5 on node 1 so its tip is now at 4")
self.nodes[1].invalidateblock(self.nodes[1].getblockhash(5)) 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.log.info("Invalidate block 3 on node 2, so its tip is now 2")
self.nodes[2].invalidateblock(self.nodes[2].getblockhash(3)) 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.log.info("..and then mine a block")
self.nodes[2].generate(1) self.nodes[2].generate(1)
self.log.info("Verify all nodes are at the right height") self.log.info("Verify all nodes are at the right height")

View File

@ -6,7 +6,7 @@
from test_framework.messages import hash256 from test_framework.messages import hash256
from test_framework.mininode import P2PInterface from test_framework.mininode import P2PInterface
from test_framework.test_framework import DashTestFramework 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 rpc_mnauth.py
@ -28,17 +28,17 @@ class FakeMNAUTHTest(DashTestFramework):
public_key = masternode.pubKeyOperator public_key = masternode.pubKeyOperator
# The peerinfo should not yet contain verified_proregtx_hash/verified_pubkey_hash # The peerinfo should not yet contain verified_proregtx_hash/verified_pubkey_hash
assert("verified_proregtx_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]) assert "verified_pubkey_hash" not in masternode.node.getpeerinfo()[-1]
# Fake-Authenticate the P2P connection to the masternode # Fake-Authenticate the P2P connection to the masternode
node_id = masternode.node.getpeerinfo()[-1]["id"] 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 # The peerinfo should now contain verified_proregtx_hash and verified_pubkey_hash
peerinfo = masternode.node.getpeerinfo()[-1] peerinfo = masternode.node.getpeerinfo()[-1]
assert("verified_proregtx_hash" in peerinfo) assert "verified_proregtx_hash" in peerinfo
assert("verified_pubkey_hash" in peerinfo) assert "verified_pubkey_hash" in peerinfo
assert_equal(peerinfo["verified_proregtx_hash"], protx_hash) 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 # Test some error cases
null_hash = "0000000000000000000000000000000000000000000000000000000000000000" null_hash = "0000000000000000000000000000000000000000000000000000000000000000"
assert_raises_rpc_error(-8, "proTxHash invalid", masternode.node.mnauth, assert_raises_rpc_error(-8, "proTxHash invalid", masternode.node.mnauth,
@ -49,7 +49,7 @@ class FakeMNAUTHTest(DashTestFramework):
node_id, node_id,
protx_hash, protx_hash,
null_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__': if __name__ == '__main__':

View File

@ -17,7 +17,7 @@ class NamedArgumentTest(BitcoinTestFramework):
def run_test(self): def run_test(self):
node = self.nodes[0] node = self.nodes[0]
h = node.help(command='getblockchaininfo') 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') assert_raises_rpc_error(-8, 'Unknown named parameter', node.help, random='getblockchaininfo')

View File

@ -47,7 +47,7 @@ class HTTPBasicsTest(BitcoinTestFramework):
conn.request('POST', '/', json.dumps(body), {"Authorization": "Basic " + str_to_b64str(auth)}) conn.request('POST', '/', json.dumps(body), {"Authorization": "Basic " + str_to_b64str(auth)})
resp = conn.getresponse() resp = conn.getresponse()
if should_not_match: if should_not_match:
assert(resp.status != expexted_status) assert resp.status != expexted_status
else: else:
assert_equal(resp.status, expexted_status) assert_equal(resp.status, expexted_status)
conn.close() conn.close()

View File

@ -16,7 +16,7 @@ def unidirectional_node_sync_via_rpc(node_src, node_dest):
blockhash = node_src.getbestblockhash() blockhash = node_src.getbestblockhash()
while True: while True:
try: try:
assert(len(node_dest.getblock(blockhash, False)) > 0) assert len(node_dest.getblock(blockhash, False)) > 0
break break
except: except:
blocks_to_copy.append(blockhash) blocks_to_copy.append(blockhash)
@ -24,7 +24,7 @@ def unidirectional_node_sync_via_rpc(node_src, node_dest):
blocks_to_copy.reverse() blocks_to_copy.reverse()
for blockhash in blocks_to_copy: for blockhash in blocks_to_copy:
blockdata = node_src.getblock(blockhash, False) 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): def node_sync_via_rpc(nodes):
for node_src in 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") self.log.info("Mine competing blocks E-F-G on Node 1")
hashG = self.nodes[1].generate(3)[-1] hashG = self.nodes[1].generate(3)[-1]
assert_equal(self.nodes[1].getblockcount(), 5) assert_equal(self.nodes[1].getblockcount(), 5)
assert(hashC != hashG) assert hashC != hashG
self.log.info("Connect nodes and check no reorg occurs") 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) # 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]) node_sync_via_rpc(self.nodes[0:2])

View File

@ -17,7 +17,7 @@ from decimal import Decimal
from io import BytesIO from io import BytesIO
from test_framework.messages import CTransaction, ToHex from test_framework.messages import CTransaction, ToHex
from test_framework.test_framework import BitcoinTestFramework 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): class multidict(dict):
"""Dictionary that allows duplicate keys. """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})))) 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(len(tx.vout), 1)
assert_equal( assert_equal(
bytes_to_hex_str(tx.serialize()), tx.serialize().hex(),
self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}]), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}]),
) )
# Two outputs # Two outputs
tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=OrderedDict([(address, 99), (address2, 99)]))))) 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(len(tx.vout), 2)
assert_equal( 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}]), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {address2: 99}]),
) )
# Two data outputs # 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')]))))) 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(len(tx.vout), 2)
assert_equal( 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'}]), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{'data': '99'}, {'data': '99'}]),
) )
# Multiple mixed outputs # 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')]))))) 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(len(tx.vout), 3)
assert_equal( 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'}]), self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {'data': '99'}, {'data': '99'}]),
) )

View File

@ -20,7 +20,7 @@ class SetBanTests(BitcoinTestFramework):
# Node 0 connects to Node 1, check that the noban permission is not granted # Node 0 connects to Node 1, check that the noban permission is not granted
connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 1)
peerinfo = self.nodes[1].getpeerinfo()[0] 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 # Node 0 get banned by Node 1
self.nodes[1].setban("127.0.0.1", "add") 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']) self.restart_node(1, ['-whitelist=127.0.0.1'])
connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 1)
peerinfo = self.nodes[1].getpeerinfo()[0] 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 # 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.nodes[1].setban("127.0.0.1", "remove")
self.restart_node(1, []) self.restart_node(1, [])
connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 1)
peerinfo = self.nodes[1].getpeerinfo()[0] peerinfo = self.nodes[1].getpeerinfo()[0]
assert(not 'noban' in peerinfo['permissions']) assert not 'noban' in peerinfo['permissions']
if __name__ == '__main__': if __name__ == '__main__':
SetBanTests().main() SetBanTests().main()

View File

@ -21,18 +21,18 @@ class SignMessagesTest(BitcoinTestFramework):
expected_signature = 'ICzMhjIUmmXcPWy2+9nw01zQMawo+s5FIy6F7VMkL+TmIeNq1j3AMEuw075os29kh5KYLbysKkDlDD+EAqERBd4=' expected_signature = 'ICzMhjIUmmXcPWy2+9nw01zQMawo+s5FIy6F7VMkL+TmIeNq1j3AMEuw075os29kh5KYLbysKkDlDD+EAqERBd4='
signature = self.nodes[0].signmessagewithprivkey(priv_key, message) signature = self.nodes[0].signmessagewithprivkey(priv_key, message)
assert_equal(expected_signature, signature) 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') self.log.info('test signing with an address with wallet')
address = self.nodes[0].getnewaddress() address = self.nodes[0].getnewaddress()
signature = self.nodes[0].signmessage(address, message) 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') self.log.info('test verifying with another address should not work')
other_address = self.nodes[0].getnewaddress() other_address = self.nodes[0].getnewaddress()
other_signature = self.nodes[0].signmessage(other_address, message) 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(other_address, signature, message)
assert(not self.nodes[0].verifymessage(address, other_signature, message)) assert not self.nodes[0].verifymessage(address, other_signature, message)
if __name__ == '__main__': if __name__ == '__main__':
SignMessagesTest().main() SignMessagesTest().main()

View File

@ -23,7 +23,7 @@ class UptimeTest(BitcoinTestFramework):
def _test_uptime(self): def _test_uptime(self):
wait_time = 10 wait_time = 10
self.nodes[0].setmocktime(int(time.time() + wait_time)) 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__': if __name__ == '__main__':

View File

@ -5,7 +5,7 @@
from test_framework.messages import CTransaction, FromHex, hash256, ser_compact_size, ser_string from test_framework.messages import CTransaction, FromHex, hash256, ser_compact_size, ser_string
from test_framework.test_framework import DashTestFramework 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 rpc_verifyislock.py
@ -43,15 +43,15 @@ class RPCVerifyISLockTest(DashTestFramework):
wait_until(lambda: node.quorum("hasrecsig", 100, request_id, txid)) wait_until(lambda: node.quorum("hasrecsig", 100, request_id, txid))
rec_sig = node.quorum("getrecsig", 100, request_id, txid)['sig'] 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 # Not mined, should use maxHeight
assert not node.verifyislock(request_id, txid, rec_sig, 1) assert not node.verifyislock(request_id, txid, rec_sig, 1)
node.generate(1) node.generate(1)
assert(txid not in node.getrawmempool()) assert txid not in node.getrawmempool()
# Mined but at higher height, should use maxHeight # Mined but at higher height, should use maxHeight
assert not node.verifyislock(request_id, txid, rec_sig, 1) assert not node.verifyislock(request_id, txid, rec_sig, 1)
# Mined, should ignore higher maxHeight # 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 # Mine one more quorum to have a full active set
self.mine_quorum() self.mine_quorum()
@ -88,10 +88,10 @@ class RPCVerifyISLockTest(DashTestFramework):
# Verify the ISLOCK for a transaction that is not yet known by the node # Verify the ISLOCK for a transaction that is not yet known by the node
rawtx_txid = node.decoderawtransaction(rawtx)["txid"] rawtx_txid = node.decoderawtransaction(rawtx)["txid"]
assert_raises_rpc_error(-5, "No such mempool or blockchain transaction", node.getrawtransaction, 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 # Send the tx and verify the ISLOCK for a now known transaction
assert rawtx_txid == node.sendrawtransaction(rawtx) 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__': if __name__ == '__main__':

View File

@ -10,15 +10,15 @@
# #
from .script import hash256, hash160, CScript 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' chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def byte_to_base58(b, version): def byte_to_base58(b, version):
result = '' result = ''
str = bytes_to_hex_str(b) str = b.hex()
str = bytes_to_hex_str(chr(version).encode('latin-1')) + str str = chr(version).encode('latin-1').hex() + str
checksum = bytes_to_hex_str(hash256(hex_str_to_bytes(str))) checksum = hash256(hex_str_to_bytes(str)).hex()
str += checksum[:8] str += checksum[:8]
value = int('0x'+str,0) value = int('0x'+str,0)
while value > 0: while value > 0:
@ -32,12 +32,12 @@ def byte_to_base58(b, version):
# TODO: def base58_decode # TODO: def base58_decode
def keyhash_to_p2pkh(hash, main = False): def keyhash_to_p2pkh(hash, main = False):
assert (len(hash) == 20) assert len(hash) == 20
version = 76 if main else 140 version = 76 if main else 140
return byte_to_base58(hash, version) return byte_to_base58(hash, version)
def scripthash_to_p2sh(hash, main = False): def scripthash_to_p2sh(hash, main = False):
assert (len(hash) == 20) assert len(hash) == 20
version = 16 if main else 19 version = 16 if main else 19
return byte_to_base58(hash, version) 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 key = hex_str_to_bytes(key) # Assuming this is hex string
if (type(key) is bytes and (len(key) == 33 or len(key) == 65)): if (type(key) is bytes and (len(key) == 33 or len(key) == 65)):
return key return key
assert(False) assert False
def check_script(script): def check_script(script):
if (type(script) is str): if (type(script) is str):
script = hex_str_to_bytes(script) # Assuming this is hex string script = hex_str_to_bytes(script) # Assuming this is hex string
if (type(script) is bytes or type(script) is CScript): if (type(script) is bytes or type(script) is CScript):
return script return script
assert(False) assert False

View File

@ -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. Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output.
""" """
tx = CTransaction() tx = CTransaction()
assert(n < len(prevtx.vout)) assert n < len(prevtx.vout)
tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff)) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff))
tx.vout.append(CTxOut(amount, script_pub_key)) tx.vout.append(CTxOut(amount, script_pub_key))
tx.calc_sha256() tx.calc_sha256()

View File

@ -27,7 +27,7 @@ import struct
import time import time
from test_framework.siphash import siphash256 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 import dash_hash
@ -199,7 +199,7 @@ def FromHex(obj, hex_string):
# Convert a binary-serializable object to hex (eg for submission via RPC) # Convert a binary-serializable object to hex (eg for submission via RPC)
def ToHex(obj): 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 # Objects that map to dashd objects, which can be serialized/deserialized
@ -401,7 +401,7 @@ class CTxIn:
def __repr__(self): def __repr__(self):
return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \ 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) self.nSequence)
@ -425,7 +425,7 @@ class CTxOut:
def __repr__(self): def __repr__(self):
return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \ return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \
% (self.nValue // COIN, self.nValue % COIN, % (self.nValue // COIN, self.nValue % COIN,
bytes_to_hex_str(self.scriptPubKey)) self.scriptPubKey.hex())
class CTransaction: class CTransaction:

View File

@ -260,10 +260,7 @@ class P2PConnection(asyncio.Protocol):
def maybe_write(): def maybe_write():
if not self._transport: if not self._transport:
return return
# Python <3.4.4 does not have is_closing, so we have to check for if self._transport.is_closing():
# 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():
return return
self._transport.write(raw_message_bytes) self._transport.write(raw_message_bytes)
NetworkThread.network_event_loop.call_soon_threadsafe(maybe_write) NetworkThread.network_event_loop.call_soon_threadsafe(maybe_write)

View File

@ -12,7 +12,7 @@ import socket
import struct import struct
import array import array
import os import os
from binascii import unhexlify, hexlify from binascii import unhexlify
# STATE_ESTABLISHED = '01' # STATE_ESTABLISHED = '01'
# STATE_SYN_SENT = '02' # 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 if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end
continue continue
x += 1 # :: skips to suffix x += 1 # :: skips to suffix
assert(x < 2) assert x < 2
else: # two bytes per component else: # two bytes per component
val = int(comp, 16) val = int(comp, 16)
sub[x].append(val >> 8) sub[x].append(val >> 8)
sub[x].append(val & 0xff) sub[x].append(val & 0xff)
nullbytes = 16 - len(sub[0]) - len(sub[1]) 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] addr = sub[0] + ([0] * nullbytes) + sub[1]
else: else:
raise ValueError('Could not parse address %s' % addr) raise ValueError('Could not parse address %s' % addr)
return hexlify(bytearray(addr)).decode('ascii') return bytearray(addr).hex()
def test_ipv6_local(): def test_ipv6_local():
''' '''

View File

@ -7,7 +7,6 @@
This file is modified from python-bitcoinlib. This file is modified from python-bitcoinlib.
""" """
from binascii import hexlify
import hashlib import hashlib
import struct import struct
@ -451,10 +450,6 @@ class CScript(bytes):
# join makes no sense for a CScript() # join makes no sense for a CScript()
raise NotImplementedError raise NotImplementedError
# Python 3.4 compatibility
def hex(self):
return hexlify(self).decode('ascii')
def __new__(cls, value=b''): def __new__(cls, value=b''):
if isinstance(value, bytes) or isinstance(value, bytearray): if isinstance(value, bytes) or isinstance(value, bytearray):
return super(CScript, cls).__new__(cls, value) return super(CScript, cls).__new__(cls, value)
@ -546,7 +541,7 @@ class CScript(bytes):
def __repr__(self): def __repr__(self):
def _repr(o): def _repr(o):
if isinstance(o, bytes): if isinstance(o, bytes):
return "x('%s')" % hexlify(o).decode('ascii') return "x('%s')" % o.hex()
else: else:
return repr(o) return repr(o)

View File

@ -144,7 +144,7 @@ class Socks5Server():
thread.start() thread.start()
def start(self): def start(self):
assert(not self.running) assert not self.running
self.running = True self.running = True
self.thread = threading.Thread(None, self.run) self.thread = threading.Thread(None, self.run)
self.thread.daemon = True self.thread.daemon = True

View File

@ -806,12 +806,12 @@ class DashTestFramework(BitcoinTestFramework):
self.bump_mocktime(1) self.bump_mocktime(1)
mn_info = self.nodes[0].masternodelist("status") 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(): 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): 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 # fill inputs
inputs = [] inputs = []
balances = node_from.listunspent() balances = node_from.listunspent()
@ -841,9 +841,9 @@ class DashTestFramework(BitcoinTestFramework):
inputs[-1] = input inputs[-1] = input
last_amount = float(tx['amount']) last_amount = float(tx['amount'])
assert (len(inputs) >= min_inputs) assert len(inputs) >= min_inputs
assert (len(inputs) <= max_inputs) assert len(inputs) <= max_inputs
assert (in_amount >= amount) assert in_amount >= amount
# fill outputs # fill outputs
receiver_address = node_to.getnewaddress() receiver_address = node_to.getnewaddress()
change_address = node_from.getnewaddress() change_address = node_from.getnewaddress()

View File

@ -32,9 +32,6 @@ from .util import (
Options Options
) )
# For Python 3.4 compatibility
JSONDecodeError = getattr(json, "JSONDecodeError", ValueError)
BITCOIND_PROC_WAIT_TIMEOUT = 60 BITCOIND_PROC_WAIT_TIMEOUT = 60
@ -581,5 +578,5 @@ class TestNodeCLI():
raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr) raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr)
try: try:
return json.loads(cli_stdout, parse_float=decimal.Decimal) return json.loads(cli_stdout, parse_float=decimal.Decimal)
except JSONDecodeError: except json.JSONDecodeError:
return cli_stdout.rstrip("\n") return cli_stdout.rstrip("\n")

View File

@ -6,7 +6,7 @@
"""Helpful routines for regression testing.""" """Helpful routines for regression testing."""
from base64 import b64encode from base64 import b64encode
from binascii import hexlify, unhexlify from binascii import unhexlify
from decimal import Decimal, ROUND_DOWN from decimal import Decimal, ROUND_DOWN
import hashlib import hashlib
import inspect import inspect
@ -194,9 +194,6 @@ def check_json_precision():
def count_bytes(hex_string): def count_bytes(hex_string):
return len(bytearray.fromhex(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): def hash256(byte_str):
sha256 = hashlib.sha256() sha256 = hashlib.sha256()
sha256.update(byte_str) 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) return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
def p2p_port(n): 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) return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
def rpc_port(n): 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 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) utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo) random.shuffle(utxo)
inputs = [] inputs = []
@ -601,7 +598,7 @@ def create_confirmed_utxos(fee, node, count):
node.generate(1) node.generate(1)
utxos = node.listunspent() utxos = node.listunspent()
assert(len(utxos) >= count) assert len(utxos) >= count
return utxos return utxos
# Create large OP_RETURN txouts that can be appended to a transaction # Create large OP_RETURN txouts that can be appended to a transaction

View File

@ -21,9 +21,9 @@ class DisableWalletTest (BitcoinTestFramework):
# Make sure wallet is really disabled # Make sure wallet is really disabled
assert_raises_rpc_error(-32601, 'Method not found', self.nodes[0].getwalletinfo) assert_raises_rpc_error(-32601, 'Method not found', self.nodes[0].getwalletinfo)
x = self.nodes[0].validateaddress('7TSBtVu959hGEGPKyHjJz9k55RpWrPffXz') x = self.nodes[0].validateaddress('7TSBtVu959hGEGPKyHjJz9k55RpWrPffXz')
assert(x['isvalid'] == False) assert x['isvalid'] == False
x = self.nodes[0].validateaddress('ycwedq2f3sz2Yf9JqZsBCQPxp18WU3Hp4J') 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 # Checking mining to an address without a wallet. Generating to a valid address should succeed
# but generating to an invalid address will fail. # but generating to an invalid address will fail.

View File

@ -34,8 +34,8 @@ class DisablePrivateKeysTest(BitcoinTestFramework):
privkey = w2.dumpprivkey(addr) privkey = w2.dumpprivkey(addr)
assert_raises_rpc_error(-4, 'Cannot import private keys to a wallet with private keys disabled', w1.importprivkey, privkey) 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]}]) result = w1.importmulti([{'scriptPubKey': {'address': addr}, 'timestamp': 'now', 'keys': [privkey]}])
assert(not result[0]['success']) assert not result[0]['success']
assert('warning' not in result[0]) assert 'warning' not in result[0]
assert_equal(result[0]['error']['code'], -4) assert_equal(result[0]['error']['code'], -4)
assert_equal(result[0]['error']['message'], 'Cannot import private keys to a wallet with private keys disabled') assert_equal(result[0]['error']['message'], 'Cannot import private keys to a wallet with private keys disabled')

View File

@ -44,10 +44,10 @@ def read_dump(file_name, addrs, script_addrs, hd_master_addr_old):
keypath = None keypath = None
if keytype == "inactivehdseed=1": if keytype == "inactivehdseed=1":
# ensure the old master is still available # ensure the old master is still available
assert (hd_master_addr_old == addr) assert hd_master_addr_old == addr
elif keytype == "hdseed=1": elif keytype == "hdseed=1":
# ensure we have generated a new hd master key # 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 hd_master_addr_ret = addr
elif keytype == "script=1": elif keytype == "script=1":
# scripts don't have keypaths # scripts don't have keypaths
@ -148,13 +148,13 @@ class WalletDumpTest(BitcoinTestFramework):
# Make sure the address is not IsMine before import # Make sure the address is not IsMine before import
result = self.nodes[0].getaddressinfo(multisig_addr) result = self.nodes[0].getaddressinfo(multisig_addr)
assert(result['ismine'] == False) assert result['ismine'] == False
self.nodes[0].importwallet(wallet_unenc_dump) self.nodes[0].importwallet(wallet_unenc_dump)
# Now check IsMine is true # Now check IsMine is true
result = self.nodes[0].getaddressinfo(multisig_addr) result = self.nodes[0].getaddressinfo(multisig_addr)
assert(result['ismine'] == True) assert result['ismine'] == True
if __name__ == '__main__': if __name__ == '__main__':
WalletDumpTest().main() WalletDumpTest().main()

View File

@ -10,7 +10,6 @@ from test_framework.util import (
assert_equal, assert_equal,
assert_greater_than, assert_greater_than,
assert_raises_rpc_error, assert_raises_rpc_error,
bytes_to_hex_str,
) )
@ -88,7 +87,7 @@ class ImportMultiTest(BitcoinTestFramework):
# Nonstandard scriptPubKey + !internal # Nonstandard scriptPubKey + !internal
self.log.info("Should not import a nonstandard scriptPubKey without internal flag") 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()) address = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress())
result = self.nodes[1].importmulti([{ result = self.nodes[1].importmulti([{
"scriptPubKey": nonstandardScriptPubKey, "scriptPubKey": nonstandardScriptPubKey,

View File

@ -35,7 +35,7 @@ class KeyPoolTest(BitcoinTestFramework):
addr.add(nodes[0].getrawchangeaddress()) addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress()) addr.add(nodes[0].getrawchangeaddress())
# assert that three unique addresses were returned # assert that three unique addresses were returned
assert(len(addr) == 3) assert len(addr) == 3
# the next one should fail # the next one should fail
assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getrawchangeaddress) assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getrawchangeaddress)

View File

@ -25,7 +25,7 @@ class KeyPoolTest(BitcoinTestFramework):
addr_before_encrypting = nodes[0].getnewaddress() addr_before_encrypting = nodes[0].getnewaddress()
addr_before_encrypting_data = nodes[0].getaddressinfo(addr_before_encrypting) addr_before_encrypting_data = nodes[0].getaddressinfo(addr_before_encrypting)
wallet_info_old = nodes[0].getwalletinfo() 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 # Encrypt wallet and wait to terminate
nodes[0].encryptwallet('test') nodes[0].encryptwallet('test')
@ -33,14 +33,14 @@ class KeyPoolTest(BitcoinTestFramework):
addr = nodes[0].getnewaddress() addr = nodes[0].getnewaddress()
addr_data = nodes[0].getaddressinfo(addr) addr_data = nodes[0].getaddressinfo(addr)
wallet_info = nodes[0].getwalletinfo() wallet_info = nodes[0].getwalletinfo()
assert(addr_before_encrypting_data['hdchainid'] == wallet_info['hdchainid']) assert addr_before_encrypting_data['hdchainid'] == wallet_info['hdchainid']
assert(addr_data['hdchainid'] == wallet_info['hdchainid']) assert addr_data['hdchainid'] == wallet_info['hdchainid']
try: try:
addr = nodes[0].getnewaddress() addr = nodes[0].getnewaddress()
raise AssertionError('Keypool should be exhausted after one address') raise AssertionError('Keypool should be exhausted after one address')
except JSONRPCException as e: 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) # put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min)
nodes[0].walletpassphrase('test', 12000) nodes[0].walletpassphrase('test', 12000)
@ -62,7 +62,7 @@ class KeyPoolTest(BitcoinTestFramework):
nodes[0].getrawchangeaddress() nodes[0].getrawchangeaddress()
raise AssertionError('Keypool should be exhausted after six addresses') raise AssertionError('Keypool should be exhausted after six addresses')
except JSONRPCException as e: except JSONRPCException as e:
assert(e.error['code']==-12) assert e.error['code']==-12
addr = set() addr = set()
# drain the external keys # 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()) 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 # the next one should fail
try: try:
addr = nodes[0].getnewaddress() addr = nodes[0].getnewaddress()
raise AssertionError('Keypool should be exhausted after six addresses') raise AssertionError('Keypool should be exhausted after six addresses')
except JSONRPCException as e: except JSONRPCException as e:
assert(e.error['code']==-12) assert e.error['code']==-12
# refill keypool with three new addresses # refill keypool with three new addresses
nodes[0].walletpassphrase('test', 1) nodes[0].walletpassphrase('test', 1)
@ -95,7 +95,7 @@ class KeyPoolTest(BitcoinTestFramework):
nodes[0].generate(1) nodes[0].generate(1)
raise AssertionError('Keypool should be exhausted after three addesses') raise AssertionError('Keypool should be exhausted after three addesses')
except JSONRPCException as e: except JSONRPCException as e:
assert(e.error['code']==-12) assert e.error['code']==-12
nodes[0].walletpassphrase('test', 100) nodes[0].walletpassphrase('test', 100)
nodes[0].keypoolrefill(100) nodes[0].keypoolrefill(100)

View File

@ -32,16 +32,16 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
self.stop_node(0) self.stop_node(0)
shutil.copyfile(os.path.join(node.datadir, "non_hd.bak"), os.path.join(node.datadir, "regtest", "wallet.dat")) shutil.copyfile(os.path.join(node.datadir, "non_hd.bak"), os.path.join(node.datadir, "regtest", "wallet.dat"))
self.start_node(0) self.start_node(0)
assert('hdchainid' not in node.getwalletinfo()) assert 'hdchainid' not in node.getwalletinfo()
def run_test(self): def run_test(self):
node = self.nodes[0] node = self.nodes[0]
node.backupwallet(os.path.join(node.datadir, "non_hd.bak")) node.backupwallet(os.path.join(node.datadir, "non_hd.bak"))
self.log.info("No mnemonic, no mnemonic passphrase, no wallet passphrase") 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() balance_before = node.getbalance()
assert(node.upgradetohd()) assert node.upgradetohd()
mnemonic = node.dumphdinfo()['mnemonic'] mnemonic = node.dumphdinfo()['mnemonic']
chainid = node.getwalletinfo()['hdchainid'] chainid = node.getwalletinfo()['hdchainid']
assert_equal(len(chainid), 64) assert_equal(len(chainid), 64)
@ -72,12 +72,12 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
# We spent some coins from non-HD keys to HD ones earlier # We spent some coins from non-HD keys to HD ones earlier
balance_non_HD = node.getbalance() 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") self.log.info("No mnemonic, no mnemonic passphrase, no wallet passphrase, should result in completely different keys")
assert(node.upgradetohd()) assert node.upgradetohd()
assert(mnemonic != node.dumphdinfo()['mnemonic']) assert mnemonic != node.dumphdinfo()['mnemonic']
assert(chainid != node.getwalletinfo()['hdchainid']) assert chainid != node.getwalletinfo()['hdchainid']
assert_equal(balance_non_HD, node.getbalance()) assert_equal(balance_non_HD, node.getbalance())
node.keypoolrefill(5) node.keypoolrefill(5)
node.rescanblockchain() 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") self.log.info("Same mnemonic, another mnemonic passphrase, no wallet passphrase, should result in a different set of keys")
new_mnemonic_passphrase = "somewords" new_mnemonic_passphrase = "somewords"
assert(node.upgradetohd(mnemonic, new_mnemonic_passphrase)) assert node.upgradetohd(mnemonic, new_mnemonic_passphrase)
assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) assert_equal(mnemonic, node.dumphdinfo()['mnemonic'])
new_chainid = node.getwalletinfo()['hdchainid'] new_chainid = node.getwalletinfo()['hdchainid']
assert(chainid != new_chainid) assert chainid != new_chainid
assert_equal(balance_non_HD, node.getbalance()) assert_equal(balance_non_HD, node.getbalance())
node.keypoolrefill(5) node.keypoolrefill(5)
node.rescanblockchain() node.rescanblockchain()
@ -102,7 +102,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
self.recover_non_hd() self.recover_non_hd()
self.log.info("Same mnemonic, another mnemonic passphrase, no wallet passphrase, should result in a different set of keys (again)") 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(mnemonic, node.dumphdinfo()['mnemonic'])
assert_equal(new_chainid, node.getwalletinfo()['hdchainid']) assert_equal(new_chainid, node.getwalletinfo()['hdchainid'])
assert_equal(balance_non_HD, node.getbalance()) assert_equal(balance_non_HD, node.getbalance())
@ -115,7 +115,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
self.recover_non_hd() self.recover_non_hd()
self.log.info("Same mnemonic, no mnemonic passphrase, no wallet passphrase, should recover all coins after rescan") 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(mnemonic, node.dumphdinfo()['mnemonic'])
assert_equal(chainid, node.getwalletinfo()['hdchainid']) assert_equal(chainid, node.getwalletinfo()['hdchainid'])
node.keypoolrefill(5) 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.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.stop_node(0)
self.start_node(0, extra_args=['-keypool=10']) self.start_node(0, extra_args=['-keypool=10'])
assert(node.upgradetohd(mnemonic)) assert node.upgradetohd(mnemonic)
assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) assert_equal(mnemonic, node.dumphdinfo()['mnemonic'])
assert_equal(chainid, node.getwalletinfo()['hdchainid']) assert_equal(chainid, node.getwalletinfo()['hdchainid'])
# All coins should be recovered # All coins should be recovered
@ -148,7 +148,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
# Note: wallet encryption results in additional keypool topup, # Note: wallet encryption results in additional keypool topup,
# so we can't compare new balance to balance_non_HD here, # so we can't compare new balance to balance_non_HD here,
# assert_equal(balance_non_HD, node.getbalance()) # won't work # 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.keypoolrefill(4)
node.rescanblockchain() node.rescanblockchain()
# All coins should be recovered # All coins should be recovered
@ -164,7 +164,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
self.start_node(0, extra_args=['-rescan']) 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, "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_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) assert_raises_rpc_error(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.", node.dumphdinfo)
node.walletpassphrase(walletpass, 100) node.walletpassphrase(walletpass, 100)
assert_equal(mnemonic, node.dumphdinfo()['mnemonic']) assert_equal(mnemonic, node.dumphdinfo()['mnemonic'])
@ -172,7 +172,7 @@ class WalletUpgradeToHDTest(BitcoinTestFramework):
# Note: wallet encryption results in additional keypool topup, # Note: wallet encryption results in additional keypool topup,
# so we can't compare new balance to balance_non_HD here, # so we can't compare new balance to balance_non_HD here,
# assert_equal(balance_non_HD, node.getbalance()) # won't work # 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.keypoolrefill(4)
node.rescanblockchain() node.rescanblockchain()
# All coins should be recovered # All coins should be recovered

View File

@ -46,7 +46,7 @@ def parse_function_calls(function_name, source_code):
>>> len(parse_function_calls("foo", "#define FOO foo();")) >>> len(parse_function_calls("foo", "#define FOO foo();"))
0 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() lines = [re.sub("// .*", " ", line).strip()
for line in source_code.split("\n") for line in source_code.split("\n")
if not line.strip().startswith("#")] if not line.strip().startswith("#")]
@ -60,7 +60,7 @@ def normalize(s):
>>> normalize(" /* nothing */ foo\tfoo /* bar */ foo ") >>> normalize(" /* nothing */ foo\tfoo /* bar */ foo ")
'foo foo foo' 'foo foo foo'
""" """
assert(type(s) is str) assert type(s) is str
s = s.replace("\n", " ") s = s.replace("\n", " ")
s = s.replace("\t", " ") s = s.replace("\t", " ")
s = re.sub("/\*.*?\*/", " ", s) s = re.sub("/\*.*?\*/", " ", s)
@ -84,7 +84,7 @@ def escape(s):
>>> escape(r'foo \\t foo \\n foo \\\\ foo \\ foo \\"bar\\"') >>> escape(r'foo \\t foo \\n foo \\\\ foo \\ foo \\"bar\\"')
'foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]' '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(): for raw_value, escaped_value in ESCAPE_MAP.items():
s = s.replace(raw_value, escaped_value) s = s.replace(raw_value, escaped_value)
return s return s
@ -99,7 +99,7 @@ def unescape(s):
>>> unescape("foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]") >>> unescape("foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]")
'foo \\\\t foo \\\\n foo \\\\\\\\ foo \\\\ foo \\\\"bar\\\\"' '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(): for raw_value, escaped_value in ESCAPE_MAP.items():
s = s.replace(escaped_value, raw_value) s = s.replace(escaped_value, raw_value)
return s 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)'); >>> 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', ')'] ['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)) remaining = normalize(escape(function_call))
expected_function_call = "{}(".format(function_name) expected_function_call = "{}(".format(function_name)
assert(remaining.startswith(expected_function_call)) assert remaining.startswith(expected_function_call)
parts = [expected_function_call] parts = [expected_function_call]
remaining = remaining[len(expected_function_call):] remaining = remaining[len(expected_function_call):]
open_parentheses = 1 open_parentheses = 1
@ -220,7 +220,7 @@ def parse_string_content(argument):
>>> parse_string_content('1 2 3') >>> parse_string_content('1 2 3')
'' ''
""" """
assert(type(argument) is str) assert type(argument) is str
string_content = "" string_content = ""
in_string = False in_string = False
for char in normalize(escape(argument)): 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") >>> count_format_specifiers("foo %d bar %i foo %% foo %*d foo")
4 4
""" """
assert(type(format_string) is str) assert type(format_string) is str
format_string = format_string.replace('%%', 'X') format_string = format_string.replace('%%', 'X')
n = 0 n = 0
in_specifier = False in_specifier = False