aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml4
-rw-r--r--configure.ac9
-rw-r--r--doc/README.md2
-rw-r--r--doc/gitian-building.md2
-rwxr-xr-xqa/rpc-tests/bip65-cltv.py8
-rwxr-xr-xqa/rpc-tests/bip68-sequence.py46
-rwxr-xr-xqa/rpc-tests/bipdersig.py8
-rwxr-xr-xqa/rpc-tests/blockchain.py6
-rwxr-xr-xqa/rpc-tests/disablewallet.py17
-rwxr-xr-xqa/rpc-tests/getblocktemplate_proposals.py4
-rwxr-xr-xqa/rpc-tests/importmulti.py19
-rwxr-xr-xqa/rpc-tests/keypool.py18
-rwxr-xr-xqa/rpc-tests/mempool_packages.py29
-rwxr-xr-xqa/rpc-tests/mempool_reorg.py16
-rwxr-xr-xqa/rpc-tests/mempool_spendcoinbase.py2
-rwxr-xr-xqa/rpc-tests/nulldummy.py31
-rwxr-xr-xqa/rpc-tests/prioritise_transaction.py10
-rwxr-xr-xqa/rpc-tests/replace-by-fee.py105
-rwxr-xr-xqa/rpc-tests/rpcbind_test.py6
-rwxr-xr-xqa/rpc-tests/segwit.py58
-rwxr-xr-xqa/rpc-tests/wallet.py20
-rw-r--r--src/Makefile.qttest.include22
-rw-r--r--src/Makefile.test.include1
-rw-r--r--src/bitcoin-tx.cpp16
-rw-r--r--src/chainparams.cpp3
-rw-r--r--src/chainparams.h3
-rw-r--r--src/coins.h1
-rw-r--r--src/compat.h11
-rw-r--r--src/dbwrapper.h4
-rw-r--r--src/httpserver.cpp7
-rw-r--r--src/net.cpp12
-rw-r--r--src/net.h2
-rw-r--r--src/netbase.cpp2
-rw-r--r--src/qt/forms/debugwindow.ui2
-rw-r--r--src/qt/forms/sendcoinsdialog.ui16
-rw-r--r--src/qt/sendcoinsdialog.cpp10
-rw-r--r--src/qt/test/rpcnestedtests.cpp4
-rw-r--r--src/qt/test/test_main.cpp40
-rw-r--r--src/qt/test/wallettests.cpp104
-rw-r--r--src/qt/test/wallettests.h15
-rw-r--r--src/qt/walletmodel.cpp5
-rw-r--r--src/qt/walletmodel.h2
-rw-r--r--src/rpc/server.h1
-rw-r--r--src/sync.cpp2
-rw-r--r--src/sync.h1
-rw-r--r--src/test/key_tests.cpp28
-rw-r--r--src/test/script_tests.cpp5
-rw-r--r--src/test/test_bitcoin.cpp28
-rw-r--r--src/test/test_bitcoin_main.cpp26
-rw-r--r--src/util.h4
-rw-r--r--src/wallet/coincontrol.h4
-rw-r--r--src/wallet/rpcdump.cpp10
-rw-r--r--src/wallet/wallet.cpp3
-rw-r--r--src/wallet/wallet.h1
54 files changed, 409 insertions, 406 deletions
diff --git a/.travis.yml b/.travis.yml
index 8d20a7e1bb..ba250ec83b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -32,7 +32,7 @@ env:
# bitcoind
- HOST=x86_64-unknown-linux-gnu PACKAGES="bc python3-zmq" DEP_OPTS="NO_QT=1 NO_UPNP=1 DEBUG=1" RUN_TESTS=true GOAL="install" BITCOIN_CONFIG="--enable-zmq --enable-glibc-back-compat --enable-reduce-exports CPPFLAGS=-DDEBUG_LOCKORDER"
# No wallet
- - HOST=x86_64-unknown-linux-gnu PACKAGES="python3" DEP_OPTS="NO_WALLET=1" RUN_TESTS=true GOAL="install" BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports"
+ - HOST=x86_64-unknown-linux-gnu PACKAGES="python3 xvfb" DEP_OPTS="NO_WALLET=1" RUN_TESTS=true GOAL="install" BITCOIN_CONFIG="--enable-glibc-back-compat --enable-reduce-exports"
# Cross-Mac
- HOST=x86_64-apple-darwin11 PACKAGES="cmake imagemagick libcap-dev librsvg2-bin libz-dev libbz2-dev libtiff-tools python-dev" BITCOIN_CONFIG="--enable-gui --enable-reduce-exports" OSX_SDK=10.11 GOAL="deploy"
@@ -50,6 +50,8 @@ before_script:
- if [ -n "$OSX_SDK" -a ! -f depends/sdk-sources/MacOSX${OSX_SDK}.sdk.tar.gz ]; then curl --location --fail $SDK_URL/MacOSX${OSX_SDK}.sdk.tar.gz -o depends/sdk-sources/MacOSX${OSX_SDK}.sdk.tar.gz; fi
- if [ -n "$OSX_SDK" -a -f depends/sdk-sources/MacOSX${OSX_SDK}.sdk.tar.gz ]; then tar -C depends/SDKs -xf depends/sdk-sources/MacOSX${OSX_SDK}.sdk.tar.gz; fi
- make $MAKEJOBS -C depends HOST=$HOST $DEP_OPTS
+ # Start xvfb if needed, as documented at https://docs.travis-ci.com/user/gui-and-headless-browsers/#Using-xvfb-to-Run-Tests-That-Require-a-GUI
+ - if [ "$RUN_TESTS" = "true" -a "${DEP_OPTS#*NO_QT=1}" = "$DEP_OPTS" ]; then export DISPLAY=:99.0; /sbin/start-stop-daemon --start --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac; fi
script:
- if [ "$CHECK_DOC" = 1 -a "$TRAVIS_REPO_SLUG" = "bitcoin/bitcoin" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then while read LINE; do travis_retry gpg --keyserver hkp://subset.pool.sks-keyservers.net --recv-keys $LINE; done < contrib/verify-commits/trusted-keys; fi
- if [ "$CHECK_DOC" = 1 -a "$TRAVIS_REPO_SLUG" = "bitcoin/bitcoin" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then git fetch --unshallow; fi
diff --git a/configure.ac b/configure.ac
index d25bebeb1a..220fc62f8e 100644
--- a/configure.ac
+++ b/configure.ac
@@ -558,6 +558,15 @@ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/socket.h>]],
[ AC_MSG_RESULT(no)]
)
+dnl Check for MSG_DONTWAIT
+AC_MSG_CHECKING(for MSG_DONTWAIT)
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/socket.h>]],
+ [[ int f = MSG_DONTWAIT; ]])],
+ [ AC_MSG_RESULT(yes); AC_DEFINE(HAVE_MSG_DONTWAIT, 1,[Define this symbol if you have MSG_DONTWAIT]) ],
+ [ AC_MSG_RESULT(no)]
+)
+
+
AC_MSG_CHECKING([for visibility attribute])
AC_LINK_IFELSE([AC_LANG_SOURCE([
int foo_def( void ) __attribute__((visibility("default")));
diff --git a/doc/README.md b/doc/README.md
index 09f32bc09e..5c00ab9150 100644
--- a/doc/README.md
+++ b/doc/README.md
@@ -3,7 +3,7 @@ Bitcoin Core 0.14.99
Setup
---------------------
-Bitcoin Core is the original Bitcoin client and it builds the backbone of the network. However, it downloads and stores the entire history of Bitcoin transactions (which is currently several GBs); depending on the speed of your computer and network connection, the synchronization process can take anywhere from a few hours to a day or more.
+Bitcoin Core is the original Bitcoin client and it builds the backbone of the network. It downloads and, by default, stores the entire history of Bitcoin transactions (which is currently more than 100 GBs); depending on the speed of your computer and network connection, the synchronization process can take anywhere from a few hours to a day or more.
To download Bitcoin Core, visit [bitcoincore.org](https://bitcoincore.org/en/releases/).
diff --git a/doc/gitian-building.md b/doc/gitian-building.md
index 442d2d605f..c2f55b5796 100644
--- a/doc/gitian-building.md
+++ b/doc/gitian-building.md
@@ -336,7 +336,7 @@ There will be a lot of warnings printed during the build of the image. These can
Getting and building the inputs
--------------------------------
-At this point you have two options, you can either use the automated script (found in [contrib/gitian-build.sh](/contrib/gitian-build.sh)) or you could manually do everything by following this guide. If you're using the automated script, then run it with the "--setup" command. Afterwards, run it with the "--build" command (example: "contrib/gitian-building.sh -b signer 0.13.0"). Otherwise ignore this.
+At this point you have two options, you can either use the automated script (found in [contrib/gitian-build.sh](/contrib/gitian-build.sh)) or you could manually do everything by following this guide. If you're using the automated script, then run it with the "--setup" command. Afterwards, run it with the "--build" command (example: "contrib/gitian-build.sh -b signer 0.13.0"). Otherwise ignore this.
Follow the instructions in [doc/release-process.md](release-process.md#fetch-and-create-inputs-first-time-or-when-dependency-versions-change)
in the bitcoin repository under 'Fetch and create inputs' to install sources which require
diff --git a/qa/rpc-tests/bip65-cltv.py b/qa/rpc-tests/bip65-cltv.py
index c9d02a98f3..7f13bb9952 100755
--- a/qa/rpc-tests/bip65-cltv.py
+++ b/qa/rpc-tests/bip65-cltv.py
@@ -69,12 +69,8 @@ class BIP65Test(BitcoinTestFramework):
if (self.nodes[0].getblockcount() != cnt + 1051):
raise AssertionError("Failed to mine a version=4 block")
- # Mine 1 old-version blocks
- try:
- self.nodes[1].generate(1)
- raise AssertionError("Succeeded to mine a version=3 block after 950 version=4 blocks")
- except JSONRPCException:
- pass
+ # Mine 1 old-version blocks. This should fail
+ assert_raises_jsonrpc(-1,"CreateNewBlock: TestBlockValidity failed: bad-version(0x00000003)", self.nodes[1].generate, 1)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 1051):
raise AssertionError("Accepted a version=3 block after 950 version=4 blocks")
diff --git a/qa/rpc-tests/bip68-sequence.py b/qa/rpc-tests/bip68-sequence.py
index ffd461ccb0..3ed6ebe044 100755
--- a/qa/rpc-tests/bip68-sequence.py
+++ b/qa/rpc-tests/bip68-sequence.py
@@ -90,12 +90,7 @@ class BIP68Test(BitcoinTestFramework):
tx2.vout = [CTxOut(int(value-self.relayfee*COIN), CScript([b'a']))]
tx2.rehash()
- try:
- self.nodes[0].sendrawtransaction(ToHex(tx2))
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], NOT_FINAL_ERROR)
- else:
- assert(False)
+ assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx2))
# Setting the version back down to 1 should disable the sequence lock,
# so this should be accepted.
@@ -190,14 +185,12 @@ class BIP68Test(BitcoinTestFramework):
tx.vout.append(CTxOut(int(value-self.relayfee*tx_size*COIN/1000), CScript([b'a'])))
rawtx = self.nodes[0].signrawtransaction(ToHex(tx))["hex"]
- try:
- self.nodes[0].sendrawtransaction(rawtx)
- except JSONRPCException as exp:
- assert(not should_pass and using_sequence_locks)
- assert_equal(exp.error["message"], NOT_FINAL_ERROR)
+ if (using_sequence_locks and not should_pass):
+ # This transaction should be rejected
+ assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, rawtx)
else:
- assert(should_pass or not using_sequence_locks)
- # Recalculate utxos if we successfully sent the transaction
+ # This raw transaction should be accepted
+ self.nodes[0].sendrawtransaction(rawtx)
utxos = self.nodes[0].listunspent()
# Test that sequence locks on unconfirmed inputs must have nSequence
@@ -239,14 +232,13 @@ class BIP68Test(BitcoinTestFramework):
tx.vout = [CTxOut(int(orig_tx.vout[0].nValue - relayfee*COIN), CScript([b'a']))]
tx.rehash()
- try:
- node.sendrawtransaction(ToHex(tx))
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], NOT_FINAL_ERROR)
- assert(orig_tx.hash in node.getrawmempool())
+ if (orig_tx.hash in node.getrawmempool()):
+ # sendrawtransaction should fail if the tx is in the mempool
+ assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx))
else:
- # orig_tx must not be in mempool
- assert(orig_tx.hash not in node.getrawmempool())
+ # sendrawtransaction should succeed if the tx is not in the mempool
+ node.sendrawtransaction(ToHex(tx))
+
return tx
test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True)
@@ -295,12 +287,7 @@ class BIP68Test(BitcoinTestFramework):
tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN)
raw_tx5 = self.nodes[0].signrawtransaction(ToHex(tx5))["hex"]
- try:
- self.nodes[0].sendrawtransaction(raw_tx5)
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], NOT_FINAL_ERROR)
- else:
- assert(False)
+ assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, raw_tx5)
# Test mempool-BIP68 consistency after reorg
#
@@ -373,12 +360,7 @@ class BIP68Test(BitcoinTestFramework):
tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))]
tx3.rehash()
- try:
- self.nodes[0].sendrawtransaction(ToHex(tx3))
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], NOT_FINAL_ERROR)
- else:
- assert(False)
+ assert_raises_jsonrpc(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx3))
# make a block that violates bip68; ensure that the tip updates
tip = int(self.nodes[0].getbestblockhash(), 16)
diff --git a/qa/rpc-tests/bipdersig.py b/qa/rpc-tests/bipdersig.py
index fa54bc2749..371cc41bb7 100755
--- a/qa/rpc-tests/bipdersig.py
+++ b/qa/rpc-tests/bipdersig.py
@@ -68,12 +68,8 @@ class BIP66Test(BitcoinTestFramework):
if (self.nodes[0].getblockcount() != cnt + 1051):
raise AssertionError("Failed to mine a version=3 block")
- # Mine 1 old-version blocks
- try:
- self.nodes[1].generate(1)
- raise AssertionError("Succeeded to mine a version=2 block after 950 version=3 blocks")
- except JSONRPCException:
- pass
+ # Mine 1 old-version blocks. This should fail
+ assert_raises_jsonrpc(-1, "CreateNewBlock: TestBlockValidity failed: bad-version(0x00000002)", self.nodes[1].generate, 1)
self.sync_all()
if (self.nodes[0].getblockcount() != cnt + 1051):
raise AssertionError("Accepted a version=2 block after 950 version=3 blocks")
diff --git a/qa/rpc-tests/blockchain.py b/qa/rpc-tests/blockchain.py
index 67b5826840..596aed50ec 100755
--- a/qa/rpc-tests/blockchain.py
+++ b/qa/rpc-tests/blockchain.py
@@ -14,10 +14,9 @@ Tests correspond to code in rpc/blockchain.cpp.
from decimal import Decimal
from test_framework.test_framework import BitcoinTestFramework
-from test_framework.authproxy import JSONRPCException
from test_framework.util import (
assert_equal,
- assert_raises,
+ assert_raises_jsonrpc,
assert_is_hex_string,
assert_is_hash_string,
start_nodes,
@@ -58,8 +57,7 @@ class BlockchainTest(BitcoinTestFramework):
def _test_getblockheader(self):
node = self.nodes[0]
- assert_raises(
- JSONRPCException, lambda: node.getblockheader('nonsense'))
+ assert_raises_jsonrpc(-5, "Block not found", node.getblockheader, "nonsense")
besthash = node.getbestblockhash()
secondbesthash = node.getblockhash(199)
diff --git a/qa/rpc-tests/disablewallet.py b/qa/rpc-tests/disablewallet.py
index ff7121659b..2f729e19bf 100755
--- a/qa/rpc-tests/disablewallet.py
+++ b/qa/rpc-tests/disablewallet.py
@@ -30,19 +30,10 @@ class DisableWalletTest (BitcoinTestFramework):
x = self.nodes[0].validateaddress('mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
assert(x['isvalid'] == True)
- # Checking mining to an address without a wallet
- try:
- self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
- except JSONRPCException as e:
- assert("Invalid address" not in e.error['message'])
- assert("ProcessNewBlock, block not accepted" not in e.error['message'])
- assert("Couldn't create new block" not in e.error['message'])
-
- try:
- self.nodes[0].generatetoaddress(1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
- raise AssertionError("Must not mine to invalid address!")
- except JSONRPCException as e:
- assert("Invalid address" in e.error['message'])
+ # Checking mining to an address without a wallet. Generating to a valid address should succeed
+ # but generating to an invalid address will fail.
+ self.nodes[0].generatetoaddress(1, 'mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
+ assert_raises_jsonrpc(-5, "Invalid address", self.nodes[0].generatetoaddress, 1, '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
if __name__ == '__main__':
DisableWalletTest ().main ()
diff --git a/qa/rpc-tests/getblocktemplate_proposals.py b/qa/rpc-tests/getblocktemplate_proposals.py
index 3b17dfcfb5..67745f77d1 100755
--- a/qa/rpc-tests/getblocktemplate_proposals.py
+++ b/qa/rpc-tests/getblocktemplate_proposals.py
@@ -105,7 +105,7 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
# Test 3: Truncated final tx
lastbyte = txlist[-1].pop()
- assert_raises(JSONRPCException, assert_template, node, tmpl, txlist, 'n/a')
+ assert_raises_jsonrpc(-22, "Block decode failed", assert_template, node, tmpl, txlist, 'n/a')
txlist[-1].append(lastbyte)
# Test 4: Add an invalid tx to the end (duplicate of gen tx)
@@ -126,7 +126,7 @@ class GetBlockTemplateProposalTest(BitcoinTestFramework):
# Test 7: Bad tx count
txlist.append(b'')
- assert_raises(JSONRPCException, assert_template, node, tmpl, txlist, 'n/a')
+ assert_raises_jsonrpc(-22, 'Block decode failed', assert_template, node, tmpl, txlist, 'n/a')
txlist.pop()
# Test 8: Bad bits
diff --git a/qa/rpc-tests/importmulti.py b/qa/rpc-tests/importmulti.py
index 298b6e9b86..ca5d42eced 100755
--- a/qa/rpc-tests/importmulti.py
+++ b/qa/rpc-tests/importmulti.py
@@ -314,6 +314,7 @@ class ImportMultiTest (BitcoinTestFramework):
self.nodes[1].generate(100)
transactionid = self.nodes[1].sendtoaddress(multi_sig_script['address'], 10.00)
self.nodes[1].generate(1)
+ timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
transaction = self.nodes[1].gettransaction(transactionid)
self.log.info("Should import a p2sh with respective redeem script and private keys")
@@ -409,6 +410,24 @@ class ImportMultiTest (BitcoinTestFramework):
assert_equal(address_assert['ismine'], False)
assert_equal('timestamp' in address_assert, False)
+
+ # Importing existing watch only address with new timestamp should replace saved timestamp.
+ assert_greater_than(timestamp, watchonly_timestamp)
+ print("Should replace previously saved watch only timestamp.")
+ result = self.nodes[1].importmulti([{
+ "scriptPubKey": {
+ "address": watchonly_address,
+ },
+ "timestamp": "now",
+ }])
+ assert_equal(result[0]['success'], True)
+ address_assert = self.nodes[1].validateaddress(watchonly_address)
+ assert_equal(address_assert['iswatchonly'], True)
+ assert_equal(address_assert['ismine'], False)
+ assert_equal(address_assert['timestamp'], timestamp)
+ watchonly_timestamp = timestamp
+
+
# restart nodes to check for proper serialization/deserialization of watch only address
stop_nodes(self.nodes)
self.nodes = start_nodes(2, self.options.tmpdir)
diff --git a/qa/rpc-tests/keypool.py b/qa/rpc-tests/keypool.py
index 4b9936a1fd..cee58563f0 100755
--- a/qa/rpc-tests/keypool.py
+++ b/qa/rpc-tests/keypool.py
@@ -28,11 +28,7 @@ class KeyPoolTest(BitcoinTestFramework):
assert(addr_before_encrypting_data['hdmasterkeyid'] != wallet_info['hdmasterkeyid'])
assert(addr_data['hdmasterkeyid'] == wallet_info['hdmasterkeyid'])
- try:
- addr = nodes[0].getnewaddress()
- raise AssertionError('Keypool should be exhausted after one address')
- except JSONRPCException as e:
- assert(e.error['code']==-12)
+ assert_raises_jsonrpc(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
# put three new keys in the keypool
nodes[0].walletpassphrase('test', 12000)
@@ -48,11 +44,7 @@ class KeyPoolTest(BitcoinTestFramework):
# assert that four unique addresses were returned
assert(len(addr) == 4)
# the next one should fail
- try:
- addr = nodes[0].getrawchangeaddress()
- raise AssertionError('Keypool should be exhausted after three addresses')
- except JSONRPCException as e:
- assert(e.error['code']==-12)
+ assert_raises_jsonrpc(-12, "Keypool ran out", nodes[0].getrawchangeaddress)
# refill keypool with three new addresses
nodes[0].walletpassphrase('test', 1)
@@ -66,11 +58,7 @@ class KeyPoolTest(BitcoinTestFramework):
nodes[0].generate(1)
nodes[0].generate(1)
nodes[0].generate(1)
- try:
- nodes[0].generate(1)
- raise AssertionError('Keypool should be exhausted after three addesses')
- except JSONRPCException as e:
- assert(e.error['code']==-12)
+ assert_raises_jsonrpc(-12, "Keypool ran out", nodes[0].generate, 1)
def __init__(self):
super().__init__()
diff --git a/qa/rpc-tests/mempool_packages.py b/qa/rpc-tests/mempool_packages.py
index 915d174052..17e3a9a967 100755
--- a/qa/rpc-tests/mempool_packages.py
+++ b/qa/rpc-tests/mempool_packages.py
@@ -112,10 +112,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN + 1000)
# Adding one more transaction on to the chain should fail.
- try:
- self.chain_transaction(self.nodes[0], txid, vout, value, fee, 1)
- except JSONRPCException as e:
- self.log.info("too-long-ancestor-chain successfully rejected")
+ assert_raises_jsonrpc(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], txid, vout, value, fee, 1)
# Check that prioritising a tx before it's added to the mempool works
# First clear the mempool by mining a block.
@@ -155,19 +152,19 @@ class MempoolPackagesTest(BitcoinTestFramework):
for i in range(10):
transaction_package.append({'txid': txid, 'vout': i, 'amount': sent_value})
- for i in range(MAX_DESCENDANTS):
+ # Sign and send up to MAX_DESCENDANT transactions chained off the parent tx
+ for i in range(MAX_DESCENDANTS - 1):
utxo = transaction_package.pop(0)
- try:
- (txid, sent_value) = self.chain_transaction(self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
- for j in range(10):
- transaction_package.append({'txid': txid, 'vout': j, 'amount': sent_value})
- if i == MAX_DESCENDANTS - 2:
- mempool = self.nodes[0].getrawmempool(True)
- assert_equal(mempool[parent_transaction]['descendantcount'], MAX_DESCENDANTS)
- except JSONRPCException as e:
- self.log.info(e.error['message'])
- assert_equal(i, MAX_DESCENDANTS - 1)
- self.log.info("tx that would create too large descendant package successfully rejected")
+ (txid, sent_value) = self.chain_transaction(self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
+ for j in range(10):
+ transaction_package.append({'txid': txid, 'vout': j, 'amount': sent_value})
+
+ mempool = self.nodes[0].getrawmempool(True)
+ assert_equal(mempool[parent_transaction]['descendantcount'], MAX_DESCENDANTS)
+
+ # Sending one more chained transaction will fail
+ utxo = transaction_package.pop(0)
+ assert_raises_jsonrpc(-26, "too-long-mempool-chain", self.chain_transaction, self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10)
# TODO: check that node1's mempool is as expected
diff --git a/qa/rpc-tests/mempool_reorg.py b/qa/rpc-tests/mempool_reorg.py
index 585e4147b2..812b54ffcb 100755
--- a/qa/rpc-tests/mempool_reorg.py
+++ b/qa/rpc-tests/mempool_reorg.py
@@ -30,9 +30,10 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
self.sync_all()
def run_test(self):
- start_count = self.nodes[0].getblockcount()
+ # Start with a 200 block chain
+ assert_equal(self.nodes[0].getblockcount(), 200)
- # Mine three blocks. After this, nodes[0] blocks
+ # Mine four blocks. After this, nodes[0] blocks
# 101, 102, and 103 are spend-able.
new_blocks = self.nodes[1].generate(4)
self.sync_all()
@@ -52,19 +53,21 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
spend_102_raw = create_tx(self.nodes[0], coinbase_txids[2], node0_address, 49.99)
spend_103_raw = create_tx(self.nodes[0], coinbase_txids[3], node0_address, 49.99)
- # Create a block-height-locked transaction which will be invalid after reorg
+ # Create a transaction which is time-locked to two blocks in the future
timelock_tx = self.nodes[0].createrawtransaction([{"txid": coinbase_txids[0], "vout": 0}], {node0_address: 49.99})
# Set the time lock
timelock_tx = timelock_tx.replace("ffffffff", "11111191", 1)
timelock_tx = timelock_tx[:-8] + hex(self.nodes[0].getblockcount() + 2)[2:] + "000000"
timelock_tx = self.nodes[0].signrawtransaction(timelock_tx)["hex"]
- assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, timelock_tx)
+ # This will raise an exception because the timelock transaction is too immature to spend
+ assert_raises_jsonrpc(-26, "non-final", self.nodes[0].sendrawtransaction, timelock_tx)
# Broadcast and mine spend_102 and 103:
spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw)
spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw)
self.nodes[0].generate(1)
- assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, timelock_tx)
+ # Time-locked transaction is still too immature to spend
+ assert_raises_jsonrpc(-26,'non-final', self.nodes[0].sendrawtransaction, timelock_tx)
# Create 102_1 and 103_1:
spend_102_1_raw = create_tx(self.nodes[0], spend_102_id, node1_address, 49.98)
@@ -73,6 +76,7 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
# Broadcast and mine 103_1:
spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw)
last_block = self.nodes[0].generate(1)
+ # Time-locked transaction can now be spent
timelock_tx_id = self.nodes[0].sendrawtransaction(timelock_tx)
# ... now put spend_101 and spend_102_1 in memory pools:
@@ -85,6 +89,8 @@ class MempoolCoinbaseTest(BitcoinTestFramework):
for node in self.nodes:
node.invalidateblock(last_block[0])
+ # Time-locked transaction is now too immature and has been removed from the mempool
+ # spend_103_1 has been re-orged out of the chain and is back in the mempool
assert_equal(set(self.nodes[0].getrawmempool()), {spend_101_id, spend_102_1_id, spend_103_1_id})
# Use invalidateblock to re-org back and make all those coinbase spends
diff --git a/qa/rpc-tests/mempool_spendcoinbase.py b/qa/rpc-tests/mempool_spendcoinbase.py
index 4818ad8bda..f562a93d86 100755
--- a/qa/rpc-tests/mempool_spendcoinbase.py
+++ b/qa/rpc-tests/mempool_spendcoinbase.py
@@ -45,7 +45,7 @@ class MempoolSpendCoinbaseTest(BitcoinTestFramework):
spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0])
# coinbase at height 102 should be too immature to spend
- assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, spends_raw[1])
+ assert_raises_jsonrpc(-26,"bad-txns-premature-spend-of-coinbase", self.nodes[0].sendrawtransaction, spends_raw[1])
# mempool should have just spend_101:
assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ])
diff --git a/qa/rpc-tests/nulldummy.py b/qa/rpc-tests/nulldummy.py
index 4b215a70b0..7b19fbfd82 100755
--- a/qa/rpc-tests/nulldummy.py
+++ b/qa/rpc-tests/nulldummy.py
@@ -66,38 +66,38 @@ class NULLDUMMYTest(BitcoinTestFramework):
self.log.info("Test 1: NULLDUMMY compliant base transactions should be accepted to mempool and mined before activation [430]")
test1txs = [self.create_transaction(self.nodes[0], coinbase_txid[0], self.ms_address, 49)]
- txid1 = self.tx_submit(self.nodes[0], test1txs[0])
+ txid1 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[0].serialize_with_witness()), True)
test1txs.append(self.create_transaction(self.nodes[0], txid1, self.ms_address, 48))
- txid2 = self.tx_submit(self.nodes[0], test1txs[1])
+ txid2 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[1].serialize_with_witness()), True)
test1txs.append(self.create_transaction(self.nodes[0], coinbase_txid[1], self.wit_ms_address, 49))
- txid3 = self.tx_submit(self.nodes[0], test1txs[2])
+ txid3 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[2].serialize_with_witness()), True)
self.block_submit(self.nodes[0], test1txs, False, True)
self.log.info("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation")
test2tx = self.create_transaction(self.nodes[0], txid2, self.ms_address, 47)
trueDummy(test2tx)
- txid4 = self.tx_submit(self.nodes[0], test2tx, NULLDUMMY_ERROR)
+ assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test2tx.serialize_with_witness()), True)
self.log.info("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]")
self.block_submit(self.nodes[0], [test2tx], False, True)
- self.log.info("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation")
- test4tx = self.create_transaction(self.nodes[0], txid4, self.address, 46)
+ self.log.info ("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation")
+ test4tx = self.create_transaction(self.nodes[0], test2tx.hash, self.address, 46)
test6txs=[CTransaction(test4tx)]
trueDummy(test4tx)
- self.tx_submit(self.nodes[0], test4tx, NULLDUMMY_ERROR)
+ assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test4tx.serialize_with_witness()), True)
self.block_submit(self.nodes[0], [test4tx])
- self.log.info("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
+ print ("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
test5tx = self.create_transaction(self.nodes[0], txid3, self.wit_address, 48)
test6txs.append(CTransaction(test5tx))
test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01'
- self.tx_submit(self.nodes[0], test5tx, NULLDUMMY_ERROR)
+ assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test5tx.serialize_with_witness()), True)
self.block_submit(self.nodes[0], [test5tx], True)
self.log.info("Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [432]")
for i in test6txs:
- self.tx_submit(self.nodes[0], i)
+ self.nodes[0].sendrawtransaction(bytes_to_hex_str(i.serialize_with_witness()), True)
self.block_submit(self.nodes[0], test6txs, True, True)
@@ -112,17 +112,6 @@ class NULLDUMMYTest(BitcoinTestFramework):
return tx
- def tx_submit(self, node, tx, msg = ""):
- tx.rehash()
- try:
- node.sendrawtransaction(bytes_to_hex_str(tx.serialize_with_witness()), True)
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], msg)
- else:
- assert_equal('', msg)
- return tx.hash
-
-
def block_submit(self, node, txs, witness = False, accept = False):
block = create_block(self.tip, create_coinbase(self.lastblockheight + 1), self.lastblocktime + 1)
block.nVersion = 4
diff --git a/qa/rpc-tests/prioritise_transaction.py b/qa/rpc-tests/prioritise_transaction.py
index 10f596b2cb..0b04ad17ab 100755
--- a/qa/rpc-tests/prioritise_transaction.py
+++ b/qa/rpc-tests/prioritise_transaction.py
@@ -107,13 +107,9 @@ class PrioritiseTransactionTest(BitcoinTestFramework):
tx_hex = self.nodes[0].signrawtransaction(raw_tx)["hex"]
tx_id = self.nodes[0].decoderawtransaction(tx_hex)["txid"]
- try:
- self.nodes[0].sendrawtransaction(tx_hex)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26) # insufficient fee
- assert(tx_id not in self.nodes[0].getrawmempool())
- else:
- assert(False)
+ # This will raise an exception due to min relay fee not being met
+ assert_raises_jsonrpc(-26, "66: min relay fee not met", self.nodes[0].sendrawtransaction, tx_hex)
+ assert(tx_id not in self.nodes[0].getrawmempool())
# This is a less than 1000-byte transaction, so just set the fee
# to be the minimum for a 1000 byte transaction and check that it is
diff --git a/qa/rpc-tests/replace-by-fee.py b/qa/rpc-tests/replace-by-fee.py
index 8e2abea6a5..163c304eba 100755
--- a/qa/rpc-tests/replace-by-fee.py
+++ b/qa/rpc-tests/replace-by-fee.py
@@ -125,12 +125,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b.vout = [CTxOut(1*COIN, CScript([b'b']))]
tx1b_hex = txToHex(tx1b)
- try:
- tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26) # insufficient fee
- else:
- assert(False)
+ # This will raise an exception due to insufficient fee
+ assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True)
# Extra 0.1 BTC fee
tx1b = CTransaction()
@@ -172,12 +168,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
dbl_tx.vout = [CTxOut(initial_nValue - 30*COIN, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
- try:
- self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26) # insufficient fee
- else:
- assert(False) # transaction mistakenly accepted!
+ # This will raise an exception due to insufficient fee
+ assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True)
# Accepted with sufficient fee
dbl_tx = CTransaction()
@@ -237,12 +229,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(initial_nValue - fee*n, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
- try:
- self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26) # insufficient fee
- else:
- assert(False)
+ # This will raise an exception due to insufficient fee
+ assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, dbl_tx_hex, True)
# 1 BTC fee is enough
dbl_tx = CTransaction()
@@ -269,13 +257,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]
dbl_tx.vout = [CTxOut(initial_nValue - 2*fee*n, CScript([1]))]
dbl_tx_hex = txToHex(dbl_tx)
- try:
- self.nodes[0].sendrawtransaction(dbl_tx_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- assert_equal("too many potential replacements" in exp.error['message'], True)
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, dbl_tx_hex, True)
for tx in tree_txs:
tx.rehash()
@@ -298,12 +281,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b.vout = [CTxOut(int(0.001*COIN), CScript([b'a'*999000]))]
tx1b_hex = txToHex(tx1b)
- try:
- tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26) # insufficient fee
- else:
- assert(False)
+ # This will raise an exception due to insufficient fee
+ assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True)
def test_spends_of_conflicting_outputs(self):
"""Replacements that spend conflicting tx outputs are rejected"""
@@ -325,12 +304,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2.vout = tx1a.vout
tx2_hex = txToHex(tx2)
- try:
- tx2_txid = self.nodes[0].sendrawtransaction(tx2_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True)
# Spend tx1a's output to test the indirect case.
tx1b = CTransaction()
@@ -346,12 +321,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2.vout = tx1a.vout
tx2_hex = txToHex(tx2)
- try:
- tx2_txid = self.nodes[0].sendrawtransaction(tx2_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "bad-txns-spends-conflicting-tx", self.nodes[0].sendrawtransaction, tx2_hex, True)
def test_new_unconfirmed_inputs(self):
"""Replacements that add new unconfirmed inputs are rejected"""
@@ -369,12 +340,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2.vout = tx1.vout
tx2_hex = txToHex(tx2)
- try:
- tx2_txid = self.nodes[0].sendrawtransaction(tx2_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "replacement-adds-unconfirmed", self.nodes[0].sendrawtransaction, tx2_hex, True)
def test_too_many_replacements(self):
"""Replacements that evict too many transactions are rejected"""
@@ -419,13 +386,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))]
double_tx_hex = txToHex(double_tx)
- try:
- self.nodes[0].sendrawtransaction(double_tx_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- assert_equal("too many potential replacements" in exp.error['message'], True)
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "too many potential replacements", self.nodes[0].sendrawtransaction, double_tx_hex, True)
# If we remove an input, it should pass
double_tx = CTransaction()
@@ -451,13 +413,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))]
tx1b_hex = txToHex(tx1b)
- try:
- tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- self.log.info(tx1b_txid)
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx1b_hex, True)
tx1_outpoint = make_utxo(self.nodes[0], int(1.1*COIN))
@@ -474,12 +431,8 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2b.vout = [CTxOut(int(0.9*COIN), CScript([b'b']))]
tx2b_hex = txToHex(tx2b)
- try:
- tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-26, "txn-mempool-conflict", self.nodes[0].sendrawtransaction, tx2b_hex, True)
# Now create a new transaction that spends from tx1a and tx2a
# opt-in on one of the inputs
@@ -531,12 +484,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1b_hex = txToHex(tx1b)
# Verify tx1b cannot replace tx1a.
- try:
- tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- assert(False)
+ assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx1b_hex, True)
# Use prioritisetransaction to set tx1a's fee to 0.
self.nodes[0].prioritisetransaction(tx1a_txid, int(-0.1*COIN))
@@ -563,12 +511,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2b_hex = txToHex(tx2b)
# Verify tx2b cannot replace tx2a.
- try:
- tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, True)
- except JSONRPCException as exp:
- assert_equal(exp.error['code'], -26)
- else:
- assert(False)
+ assert_raises_jsonrpc(-26, "insufficient fee", self.nodes[0].sendrawtransaction, tx2b_hex, True)
# Now prioritise tx2b to have a higher modified fee
self.nodes[0].prioritisetransaction(tx2b.hash, int(0.1*COIN))
diff --git a/qa/rpc-tests/rpcbind_test.py b/qa/rpc-tests/rpcbind_test.py
index 220bf4ddd0..8720a345ce 100755
--- a/qa/rpc-tests/rpcbind_test.py
+++ b/qa/rpc-tests/rpcbind_test.py
@@ -92,11 +92,7 @@ class RPCBindTest(BitcoinTestFramework):
# Check that with invalid rpcallowip, we are denied
self.run_allowip_test([non_loopback_ip], non_loopback_ip, defaultport)
- try:
- self.run_allowip_test(['1.1.1.1'], non_loopback_ip, defaultport)
- assert(not 'Connection not denied by rpcallowip as expected')
- except JSONRPCException:
- pass
+ assert_raises_jsonrpc(-342, "non-JSON HTTP response with '403 Forbidden' from server", self.run_allowip_test, ['1.1.1.1'], non_loopback_ip, defaultport)
if __name__ == '__main__':
RPCBindTest().main()
diff --git a/qa/rpc-tests/segwit.py b/qa/rpc-tests/segwit.py
index a6e3c29bd2..5b1fba8eec 100755
--- a/qa/rpc-tests/segwit.py
+++ b/qa/rpc-tests/segwit.py
@@ -105,22 +105,12 @@ class SegWitTest(BitcoinTestFramework):
assert_equal(len(node.getblock(block[0])["tx"]), 1)
sync_blocks(self.nodes)
- def fail_accept(self, node, txid, sign, redeem_script=""):
- try:
- send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
- except JSONRPCException as exp:
- assert(exp.error["code"] == -26)
- else:
- raise AssertionError("Tx should not have been accepted")
+ def fail_accept(self, node, error_msg, txid, sign, redeem_script=""):
+ assert_raises_jsonrpc(-26, error_msg, send_to_witness, 1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
def fail_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
- try:
- node.generate(1)
- except JSONRPCException as exp:
- assert(exp.error["code"] == -1)
- else:
- raise AssertionError("Created valid block when TestBlockValidity should have failed")
+ assert_raises_jsonrpc(-1, "CreateNewBlock: TestBlockValidity failed", node.generate, 1)
sync_blocks(self.nodes)
def run_test(self):
@@ -177,18 +167,18 @@ class SegWitTest(BitcoinTestFramework):
self.log.info("Verify default node can't accept any witness format txs before fork")
# unsigned, no scriptsig
- self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], False)
- self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], False)
- self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], False)
- self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], False)
+ self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V0][0], False)
+ self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V1][0], False)
+ self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False)
+ self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False)
# unsigned with redeem script
- self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], False, witness_script(False, self.pubkey[0]))
- self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], False, witness_script(True, self.pubkey[0]))
+ self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False, witness_script(False, self.pubkey[0]))
+ self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False, witness_script(True, self.pubkey[0]))
# signed
- self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], True)
- self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], True)
- self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], True)
- self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], True)
+ self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V0][0], True)
+ self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V1][0], True)
+ self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V0][0], True)
+ self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V1][0], True)
self.log.info("Verify witness txs are skipped for mining before the fork")
self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][0], True) #block 424
@@ -203,8 +193,8 @@ class SegWitTest(BitcoinTestFramework):
self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][1], False) #block 429
self.log.info("Verify unsigned p2sh witness txs without a redeem script are invalid")
- self.fail_accept(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False)
- self.fail_accept(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][1], False)
+ self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V0][1], False)
+ self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V1][1], False)
self.log.info("Verify unsigned p2sh witness txs with a redeem script in versionbits-settings blocks are valid before the fork")
self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False, witness_script(False, self.pubkey[2])) #block 430
@@ -457,10 +447,13 @@ class SegWitTest(BitcoinTestFramework):
importlist.append(bytes_to_hex_str(p2wshop1))
for i in importlist:
+ # import all generated addresses. The wallet already has the private keys for some of these, so catch JSON RPC
+ # exceptions and continue.
try:
self.nodes[0].importaddress(i,"",False,True)
except JSONRPCException as exp:
assert_equal(exp.error["message"], "The wallet already contains the private key for this address or script")
+ assert_equal(exp.error["code"], -4)
self.nodes[0].importaddress(script_to_p2sh(op0)) # import OP_0 as address only
self.nodes[0].importaddress(multisig_without_privkey_address) # Test multisig_without_privkey
@@ -475,12 +468,7 @@ class SegWitTest(BitcoinTestFramework):
# note that no witness address should be returned by unsolvable addresses
# the multisig_without_privkey_address will fail because its keys were not added with importpubkey
for i in uncompressed_spendable_address + uncompressed_solvable_address + unknown_address + unsolvable_address + [multisig_without_privkey_address]:
- try:
- self.nodes[0].addwitnessaddress(i)
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], "Public key or redeemscript not known to wallet, or the key is uncompressed")
- else:
- assert(False)
+ assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
for i in compressed_spendable_address + compressed_solvable_address:
witaddress = self.nodes[0].addwitnessaddress(i)
@@ -559,12 +547,8 @@ class SegWitTest(BitcoinTestFramework):
# note that a multisig address returned by addmultisigaddress is not solvable until it is added with importaddress
# premature_witaddress are not accepted until the script is added with addwitnessaddress first
for i in uncompressed_spendable_address + uncompressed_solvable_address + premature_witaddress + [compressed_solvable_address[1]]:
- try:
- self.nodes[0].addwitnessaddress(i)
- except JSONRPCException as exp:
- assert_equal(exp.error["message"], "Public key or redeemscript not known to wallet, or the key is uncompressed")
- else:
- assert(False)
+ # This will raise an exception
+ assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
# after importaddress it should pass addwitnessaddress
v = self.nodes[0].validateaddress(compressed_solvable_address[1])
diff --git a/qa/rpc-tests/wallet.py b/qa/rpc-tests/wallet.py
index 00fe37563b..80f74fa108 100755
--- a/qa/rpc-tests/wallet.py
+++ b/qa/rpc-tests/wallet.py
@@ -71,7 +71,7 @@ class WalletTest (BitcoinTestFramework):
unspent_0 = self.nodes[2].listunspent()[0]
unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]}
self.nodes[2].lockunspent(False, [unspent_0])
- assert_raises_message(JSONRPCException, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
+ assert_raises_jsonrpc(-4, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
assert_equal([unspent_0], self.nodes[2].listlockunspent())
self.nodes[2].lockunspent(True, [unspent_0])
assert_equal(len(self.nodes[2].listlockunspent()), 0)
@@ -251,19 +251,11 @@ class WalletTest (BitcoinTestFramework):
txObj = self.nodes[0].gettransaction(txId)
assert_equal(txObj['amount'], Decimal('-0.0001'))
- try:
- txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "1f-4")
- except JSONRPCException as e:
- assert("Invalid amount" in e.error['message'])
- else:
- raise AssertionError("Must not parse invalid amounts")
+ # This will raise an exception because the amount type is wrong
+ assert_raises_jsonrpc(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")
-
- try:
- self.nodes[0].generate("2")
- raise AssertionError("Must not accept strings as numeric")
- except JSONRPCException as e:
- assert("not an integer" in e.error['message'])
+ # This will raise an exception since generate does not accept a string
+ assert_raises_jsonrpc(-1, "not an integer", self.nodes[0].generate, "2")
# Import address and private key to check correct behavior of spendable unspents
# 1. Send some coins to generate new UTXO
@@ -394,7 +386,7 @@ class WalletTest (BitcoinTestFramework):
node0_balance = self.nodes[0].getbalance()
# With walletrejectlongchains we will not create the tx and store it in our wallet.
- assert_raises_message(JSONRPCException, "mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
+ assert_raises_jsonrpc(-4, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
# Verify nothing new in wallet
assert_equal(total_txs, len(self.nodes[0].listtransactions("*",99999)))
diff --git a/src/Makefile.qttest.include b/src/Makefile.qttest.include
index 039f8ac547..948e13a9e1 100644
--- a/src/Makefile.qttest.include
+++ b/src/Makefile.qttest.include
@@ -11,7 +11,9 @@ TEST_QT_MOC_CPP = \
qt/test/moc_uritests.cpp
if ENABLE_WALLET
-TEST_QT_MOC_CPP += qt/test/moc_paymentservertests.cpp
+TEST_QT_MOC_CPP += \
+ qt/test/moc_paymentservertests.cpp \
+ qt/test/moc_wallettests.cpp
endif
TEST_QT_H = \
@@ -19,7 +21,16 @@ TEST_QT_H = \
qt/test/rpcnestedtests.h \
qt/test/uritests.h \
qt/test/paymentrequestdata.h \
- qt/test/paymentservertests.h
+ qt/test/paymentservertests.h \
+ qt/test/wallettests.h
+
+TEST_BITCOIN_CPP = \
+ test/test_bitcoin.cpp \
+ test/testutil.cpp
+
+TEST_BITCOIN_H = \
+ test/test_bitcoin.h \
+ test/testutil.h
qt_test_test_bitcoin_qt_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
$(QT_INCLUDES) $(QT_TEST_INCLUDES) $(PROTOBUF_CFLAGS)
@@ -29,10 +40,13 @@ qt_test_test_bitcoin_qt_SOURCES = \
qt/test/rpcnestedtests.cpp \
qt/test/test_main.cpp \
qt/test/uritests.cpp \
- $(TEST_QT_H)
+ $(TEST_QT_H) \
+ $(TEST_BITCOIN_CPP) \
+ $(TEST_BITCOIN_H)
if ENABLE_WALLET
qt_test_test_bitcoin_qt_SOURCES += \
- qt/test/paymentservertests.cpp
+ qt/test/paymentservertests.cpp \
+ qt/test/wallettests.cpp
endif
nodist_qt_test_test_bitcoin_qt_SOURCES = $(TEST_QT_MOC_CPP)
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index 5517132465..cfd08b8238 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -127,6 +127,7 @@ BITCOIN_TESTS =\
test/streams_tests.cpp \
test/test_bitcoin.cpp \
test/test_bitcoin.h \
+ test/test_bitcoin_main.cpp \
test/test_random.h \
test/testutil.cpp \
test/testutil.h \
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index 3c3646523a..61e0eb74e6 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -483,22 +483,6 @@ static bool findSighashFlags(int& flags, const std::string& flagStr)
return false;
}
-uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
-{
- if (!o.count(strKey))
- return uint256();
- return ParseHashUV(o[strKey], strKey);
-}
-
-std::vector<unsigned char> ParseHexUO(std::map<std::string,UniValue>& o, std::string strKey)
-{
- if (!o.count(strKey)) {
- std::vector<unsigned char> emptyVec;
- return emptyVec;
- }
- return ParseHexUV(o[strKey], strKey);
-}
-
static CAmount AmountFromValue(const UniValue& value)
{
if (!value.isNum() && !value.isStr())
diff --git a/src/chainparams.cpp b/src/chainparams.cpp
index 8c38558829..1dc29826af 100644
--- a/src/chainparams.cpp
+++ b/src/chainparams.cpp
@@ -135,7 +135,6 @@ public:
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
- fMiningRequiresPeers = true;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
@@ -235,7 +234,6 @@ public:
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
- fMiningRequiresPeers = true;
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fMineBlocksOnDemand = false;
@@ -307,7 +305,6 @@ public:
vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds.
- fMiningRequiresPeers = false;
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
diff --git a/src/chainparams.h b/src/chainparams.h
index db524e8f8e..4fe88c691c 100644
--- a/src/chainparams.h
+++ b/src/chainparams.h
@@ -61,8 +61,6 @@ public:
int GetDefaultPort() const { return nDefaultPort; }
const CBlock& GenesisBlock() const { return genesis; }
- /** Make miner wait to have peers to avoid wasting work */
- bool MiningRequiresPeers() const { return fMiningRequiresPeers; }
/** Default value for -checkmempool and -checkblockindex argument */
bool DefaultConsistencyChecks() const { return fDefaultConsistencyChecks; }
/** Policy: Filter transactions that do not match well-defined patterns */
@@ -89,7 +87,6 @@ protected:
std::string strNetworkID;
CBlock genesis;
std::vector<SeedSpec6> vFixedSeeds;
- bool fMiningRequiresPeers;
bool fDefaultConsistencyChecks;
bool fRequireStandard;
bool fMineBlocksOnDemand;
diff --git a/src/coins.h b/src/coins.h
index d921f5c2a5..8ee49b33ae 100644
--- a/src/coins.h
+++ b/src/coins.h
@@ -290,7 +290,6 @@ public:
virtual bool GetKey(uint256 &key) const = 0;
virtual bool GetValue(CCoins &coins) const = 0;
- /* Don't care about GetKeySize here */
virtual unsigned int GetValueSize() const = 0;
virtual bool Valid() const = 0;
diff --git a/src/compat.h b/src/compat.h
index 28aa77eea2..e76ab94c82 100644
--- a/src/compat.h
+++ b/src/compat.h
@@ -47,10 +47,8 @@
#include <unistd.h>
#endif
-#ifdef WIN32
-#define MSG_DONTWAIT 0
-#else
-typedef u_int SOCKET;
+#ifndef WIN32
+typedef unsigned int SOCKET;
#include "errno.h"
#define WSAGetLastError() errno
#define WSAEINVAL EINVAL
@@ -74,11 +72,6 @@ typedef u_int SOCKET;
#define MAX_PATH 1024
#endif
-// As Solaris does not have the MSG_NOSIGNAL flag for send(2) syscall, it is defined as 0
-#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
-#define MSG_NOSIGNAL 0
-#endif
-
#if HAVE_DECL_STRNLEN == 0
size_t strnlen( const char *start, size_t max_len);
#endif // HAVE_DECL_STRNLEN
diff --git a/src/dbwrapper.h b/src/dbwrapper.h
index dd59cc00ff..414df76a7c 100644
--- a/src/dbwrapper.h
+++ b/src/dbwrapper.h
@@ -132,10 +132,6 @@ public:
return true;
}
- unsigned int GetKeySize() {
- return piter->key().size();
- }
-
template<typename V> bool GetValue(V& value) {
leveldb::Slice slValue = piter->value();
try {
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index e1763c6ad2..dbd08ff2e1 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -146,13 +146,6 @@ public:
while (numThreads > 0)
cond.wait(lock);
}
-
- /** Return current depth of queue */
- size_t Depth()
- {
- std::unique_lock<std::mutex> lock(cs);
- return queue.size();
- }
};
struct HTTPPathHandler
diff --git a/src/net.cpp b/src/net.cpp
index 4434793c4c..4c5b04b785 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -44,10 +44,15 @@
// We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
#define FEELER_SLEEP_WINDOW 1
-#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
+#if !defined(HAVE_MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
+// MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
+#if !defined(HAVE_MSG_DONTWAIT)
+#define MSG_DONTWAIT 0
+#endif
+
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
@@ -2406,11 +2411,6 @@ void CConnman::MarkAddressGood(const CAddress& addr)
addrman.Good(addr);
}
-void CConnman::AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty)
-{
- addrman.Add(addr, addrFrom, nTimePenalty);
-}
-
void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
{
addrman.Add(vAddr, addrFrom, nTimePenalty);
diff --git a/src/net.h b/src/net.h
index 29b6a44c88..3bbe386173 100644
--- a/src/net.h
+++ b/src/net.h
@@ -207,10 +207,8 @@ public:
size_t GetAddressCount() const;
void SetServices(const CService &addr, ServiceFlags nServices);
void MarkAddressGood(const CAddress& addr);
- void AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
std::vector<CAddress> GetAddresses();
- void AddressCurrentlyConnected(const CService& addr);
// Denial-of-service detection/prevention
// The idea is to detect peers that are behaving
diff --git a/src/netbase.cpp b/src/netbase.cpp
index fc9a6ed0be..0f02e93e46 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -25,7 +25,7 @@
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
-#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
+#if !defined(HAVE_MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
diff --git a/src/qt/forms/debugwindow.ui b/src/qt/forms/debugwindow.ui
index 8be4a955b3..093e644bdc 100644
--- a/src/qt/forms/debugwindow.ui
+++ b/src/qt/forms/debugwindow.ui
@@ -645,7 +645,7 @@
<item>
<widget class="QPushButton" name="btnClearTrafficGraph">
<property name="text">
- <string>&amp;Clear</string>
+ <string>&amp;Reset</string>
</property>
<property name="autoDefault">
<bool>false</bool>
diff --git a/src/qt/forms/sendcoinsdialog.ui b/src/qt/forms/sendcoinsdialog.ui
index ca2da6bf37..cc183908d4 100644
--- a/src/qt/forms/sendcoinsdialog.ui
+++ b/src/qt/forms/sendcoinsdialog.ui
@@ -762,7 +762,7 @@
<item>
<widget class="QLabel" name="fallbackFeeWarningLabel">
<property name="toolTip">
- <string>Using the fallbackfee can result in sending a transaction that will take serval hours or days (or never) to confirm. Consider choosing your fee manually or wait until your have validated the complete chain.</string>
+ <string>Using the fallbackfee can result in sending a transaction that will take several hours or days (or never) to confirm. Consider choosing your fee manually or wait until your have validated the complete chain.</string>
</property>
<property name="font">
<font>
@@ -1180,6 +1180,16 @@
</item>
</layout>
</item>
+ <item>
+ <widget class="QCheckBox" name="optInRBF">
+ <property name="text">
+ <string>Request Replace-By-Fee</string>
+ </property>
+ <property name="toolTip">
+ <string>Indicates that the sender may wish to replace this transaction with a new one paying higher fees (prior to being confirmed).</string>
+ </property>
+ </widget>
+ </item>
</layout>
</widget>
</item>
@@ -1190,8 +1200,8 @@
</property>
<property name="sizeHint" stdset="0">
<size>
- <width>800</width>
- <height>1</height>
+ <width>40</width>
+ <height>5</height>
</size>
</property>
</spacer>
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index 65ca007552..ed7eab03f3 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -114,6 +114,7 @@ SendCoinsDialog::SendCoinsDialog(const PlatformStyle *_platformStyle, QWidget *p
ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true);
ui->customFee->setValue(settings.value("nTransactionFee").toLongLong());
ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool());
+ ui->optInRBF->setCheckState(model->getDefaultWalletRbf() ? Qt::Checked : Qt::Unchecked);
minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool());
}
@@ -247,6 +248,8 @@ void SendCoinsDialog::on_sendButton_clicked()
else
ctrl.nConfirmTarget = 0;
+ ctrl.signalRbf = ui->optInRBF->isChecked();
+
prepareStatus = model->prepareTransaction(currentTransaction, &ctrl);
// process prepareStatus and on error generate message shown to user
@@ -326,6 +329,13 @@ void SendCoinsDialog::on_sendButton_clicked()
questionString.append(QString("<span style='font-size:10pt;font-weight:normal;'><br />(=%2)</span>")
.arg(alternativeUnits.join(" " + tr("or") + "<br />")));
+ if (ui->optInRBF->isChecked())
+ {
+ questionString.append("<hr /><span>");
+ questionString.append(tr("This transaction signals replaceability (optin-RBF)."));
+ questionString.append("</span>");
+ }
+
SendConfirmationDialog confirmationDialog(tr("Confirm send coins"),
questionString.arg(formatted.join("<br />")), SEND_CONFIRM_DELAY, this);
confirmationDialog.exec();
diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp
index bd496f149c..a7b82117d8 100644
--- a/src/qt/test/rpcnestedtests.cpp
+++ b/src/qt/test/rpcnestedtests.cpp
@@ -148,9 +148,13 @@ void RPCNestedTests::rpcNestedTests()
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
+ UnloadBlockIndex();
delete pcoinsTip;
+ pcoinsTip = nullptr;
delete pcoinsdbview;
+ pcoinsdbview = nullptr;
delete pblocktree;
+ pblocktree = nullptr;
boost::filesystem::remove_all(boost::filesystem::path(path));
}
diff --git a/src/qt/test/test_main.cpp b/src/qt/test/test_main.cpp
index d44d711315..d8bcfedb7c 100644
--- a/src/qt/test/test_main.cpp
+++ b/src/qt/test/test_main.cpp
@@ -7,7 +7,6 @@
#endif
#include "chainparams.h"
-#include "key.h"
#include "rpcnestedtests.h"
#include "util.h"
#include "uritests.h"
@@ -15,20 +14,31 @@
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
+#include "wallettests.h"
#endif
-#include <QCoreApplication>
+#include <QApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
-#if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000
+#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
+#if QT_VERSION < 0x050000
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
+#else
+#if defined(QT_QPA_PLATFORM_XCB)
+Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
+#elif defined(QT_QPA_PLATFORM_WINDOWS)
+Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
+#elif defined(QT_QPA_PLATFORM_COCOA)
+Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
+#endif
+#endif
#endif
extern void noui_connect();
@@ -36,7 +46,6 @@ extern void noui_connect();
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
- ECC_Start();
SetupEnvironment();
SetupNetworking();
SelectParams(CBaseChainParams::MAIN);
@@ -45,27 +54,36 @@ int main(int argc, char *argv[])
bool fInvalid = false;
// Don't remove this, it's needed to access
- // QCoreApplication:: in the tests
- QCoreApplication app(argc, argv);
+ // QApplication:: and QCoreApplication:: in the tests
+ QApplication app(argc, argv);
app.setApplicationName("Bitcoin-Qt-test");
SSL_library_init();
URITests test1;
- if (QTest::qExec(&test1) != 0)
+ if (QTest::qExec(&test1) != 0) {
fInvalid = true;
+ }
#ifdef ENABLE_WALLET
PaymentServerTests test2;
- if (QTest::qExec(&test2) != 0)
+ if (QTest::qExec(&test2) != 0) {
fInvalid = true;
+ }
#endif
RPCNestedTests test3;
- if (QTest::qExec(&test3) != 0)
+ if (QTest::qExec(&test3) != 0) {
fInvalid = true;
+ }
CompatTests test4;
- if (QTest::qExec(&test4) != 0)
+ if (QTest::qExec(&test4) != 0) {
fInvalid = true;
+ }
+#ifdef ENABLE_WALLET
+ WalletTests test5;
+ if (QTest::qExec(&test5) != 0) {
+ fInvalid = true;
+ }
+#endif
- ECC_Stop();
return fInvalid;
}
diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp
new file mode 100644
index 0000000000..2bb7f01fdd
--- /dev/null
+++ b/src/qt/test/wallettests.cpp
@@ -0,0 +1,104 @@
+#include "wallettests.h"
+
+#include "qt/bitcoinamountfield.h"
+#include "qt/optionsmodel.h"
+#include "qt/platformstyle.h"
+#include "qt/qvalidatedlineedit.h"
+#include "qt/sendcoinsdialog.h"
+#include "qt/sendcoinsentry.h"
+#include "qt/transactiontablemodel.h"
+#include "qt/walletmodel.h"
+#include "test/test_bitcoin.h"
+#include "validation.h"
+#include "wallet/wallet.h"
+
+#include <QAbstractButton>
+#include <QApplication>
+#include <QTimer>
+#include <QVBoxLayout>
+
+namespace
+{
+//! Press "Yes" button in modal send confirmation dialog.
+void ConfirmSend()
+{
+ QTimer::singleShot(0, Qt::PreciseTimer, []() {
+ for (QWidget* widget : QApplication::topLevelWidgets()) {
+ if (widget->inherits("SendConfirmationDialog")) {
+ SendConfirmationDialog* dialog = qobject_cast<SendConfirmationDialog*>(widget);
+ QAbstractButton* button = dialog->button(QMessageBox::Yes);
+ button->setEnabled(true);
+ button->click();
+ }
+ }
+ });
+}
+
+//! Send coins to address and return txid.
+uint256 SendCoins(CWallet& wallet, SendCoinsDialog& sendCoinsDialog, const CBitcoinAddress& address, CAmount amount)
+{
+ QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries");
+ SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget());
+ entry->findChild<QValidatedLineEdit*>("payTo")->setText(QString::fromStdString(address.ToString()));
+ entry->findChild<BitcoinAmountField*>("payAmount")->setValue(amount);
+ uint256 txid;
+ boost::signals2::scoped_connection c = wallet.NotifyTransactionChanged.connect([&txid](CWallet*, const uint256& hash, ChangeType status) {
+ if (status == CT_NEW) txid = hash;
+ });
+ ConfirmSend();
+ QMetaObject::invokeMethod(&sendCoinsDialog, "on_sendButton_clicked");
+ return txid;
+}
+
+//! Find index of txid in transaction list.
+QModelIndex FindTx(const QAbstractItemModel& model, const uint256& txid)
+{
+ QString hash = QString::fromStdString(txid.ToString());
+ int rows = model.rowCount({});
+ for (int row = 0; row < rows; ++row) {
+ QModelIndex index = model.index(row, 0, {});
+ if (model.data(index, TransactionTableModel::TxHashRole) == hash) {
+ return index;
+ }
+ }
+ return {};
+}
+}
+
+//! Simple qt wallet tests.
+void WalletTests::walletTests()
+{
+ // Set up wallet and chain with 101 blocks (1 mature block for spending).
+ TestChain100Setup test;
+ test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey()));
+ bitdb.MakeMock();
+ CWallet wallet("wallet_test.dat");
+ bool firstRun;
+ wallet.LoadWallet(firstRun);
+ {
+ LOCK(wallet.cs_wallet);
+ wallet.SetAddressBook(test.coinbaseKey.GetPubKey().GetID(), "", "receive");
+ wallet.AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey());
+ }
+ wallet.ScanForWalletTransactions(chainActive.Genesis(), true);
+ wallet.SetBroadcastTransactions(true);
+
+ // Create widgets for sending coins and listing transactions.
+ std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
+ SendCoinsDialog sendCoinsDialog(platformStyle.get());
+ OptionsModel optionsModel;
+ WalletModel walletModel(platformStyle.get(), &wallet, &optionsModel);
+ sendCoinsDialog.setModel(&walletModel);
+
+ // Send two transactions, and verify they are added to transaction list.
+ TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel();
+ QCOMPARE(transactionTableModel->rowCount({}), 101);
+ uint256 txid1 = SendCoins(wallet, sendCoinsDialog, CBitcoinAddress(CKeyID()), 5 * COIN);
+ uint256 txid2 = SendCoins(wallet, sendCoinsDialog, CBitcoinAddress(CKeyID()), 10 * COIN);
+ QCOMPARE(transactionTableModel->rowCount({}), 103);
+ QVERIFY(FindTx(*transactionTableModel, txid1).isValid());
+ QVERIFY(FindTx(*transactionTableModel, txid2).isValid());
+
+ bitdb.Flush(true);
+ bitdb.Reset();
+}
diff --git a/src/qt/test/wallettests.h b/src/qt/test/wallettests.h
new file mode 100644
index 0000000000..342f7916c3
--- /dev/null
+++ b/src/qt/test/wallettests.h
@@ -0,0 +1,15 @@
+#ifndef BITCOIN_QT_TEST_WALLETTESTS_H
+#define BITCOIN_QT_TEST_WALLETTESTS_H
+
+#include <QObject>
+#include <QTest>
+
+class WalletTests : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void walletTests();
+};
+
+#endif // BITCOIN_QT_TEST_WALLETTESTS_H
diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp
index 878b7d58ae..ebcac53c25 100644
--- a/src/qt/walletmodel.cpp
+++ b/src/qt/walletmodel.cpp
@@ -706,3 +706,8 @@ int WalletModel::getDefaultConfirmTarget() const
{
return nTxConfirmTarget;
}
+
+bool WalletModel::getDefaultWalletRbf() const
+{
+ return fWalletRbf;
+}
diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h
index cd7585635f..78e45dc369 100644
--- a/src/qt/walletmodel.h
+++ b/src/qt/walletmodel.h
@@ -213,6 +213,8 @@ public:
int getDefaultConfirmTarget() const;
+ bool getDefaultWalletRbf() const;
+
private:
CWallet *wallet;
bool fHaveWatchOnly;
diff --git a/src/rpc/server.h b/src/rpc/server.h
index 68d8a6ec96..ad064e5690 100644
--- a/src/rpc/server.h
+++ b/src/rpc/server.h
@@ -28,7 +28,6 @@ namespace RPCServer
void OnStarted(boost::function<void ()> slot);
void OnStopped(boost::function<void ()> slot);
void OnPreCommand(boost::function<void (const CRPCCommand&)> slot);
- void OnPostCommand(boost::function<void (const CRPCCommand&)> slot);
}
class CBlockIndex;
diff --git a/src/sync.cpp b/src/sync.cpp
index fce57f1df9..552682ab67 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -46,8 +46,6 @@ struct CLockLocation {
return mutexName + " " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : "");
}
- std::string MutexName() const { return mutexName; }
-
bool fTry;
private:
std::string mutexName;
diff --git a/src/sync.h b/src/sync.h
index 3b29050e0e..9274f50d8b 100644
--- a/src/sync.h
+++ b/src/sync.h
@@ -97,7 +97,6 @@ public:
}
};
-typedef CCriticalSection CDynamicCriticalSection;
/** Wrapped boost mutex: supports waiting but not recursive locking */
typedef AnnotatedMixin<boost::mutex> CWaitableCriticalSection;
diff --git a/src/test/key_tests.cpp b/src/test/key_tests.cpp
index 40a7fdf11d..559b3caf1c 100644
--- a/src/test/key_tests.cpp
+++ b/src/test/key_tests.cpp
@@ -29,34 +29,6 @@ static const CBitcoinAddress addr2C("1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs");
static const std::string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF");
-#ifdef KEY_TESTS_DUMPINFO
-void dumpKeyInfo(uint256 privkey)
-{
- CKey key;
- key.resize(32);
- memcpy(&secret[0], &privkey, 32);
- std::vector<unsigned char> sec;
- sec.resize(32);
- memcpy(&sec[0], &secret[0], 32);
- printf(" * secret (hex): %s\n", HexStr(sec).c_str());
-
- for (int nCompressed=0; nCompressed<2; nCompressed++)
- {
- bool fCompressed = nCompressed == 1;
- printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed");
- CBitcoinSecret bsecret;
- bsecret.SetSecret(secret, fCompressed);
- printf(" * secret (base58): %s\n", bsecret.ToString().c_str());
- CKey key;
- key.SetSecret(secret, fCompressed);
- std::vector<unsigned char> vchPubKey = key.GetPubKey();
- printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
- printf(" * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str());
- }
-}
-#endif
-
-
BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(key_test1)
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 32184165f7..c365ad7555 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -455,11 +455,6 @@ public:
{
return comment;
}
-
- const CScript& GetScriptPubKey()
- {
- return creditTx->vout[0].scriptPubKey;
- }
};
std::string JSONPrettyPrint(const UniValue& univalue)
diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp
index 2297644c0b..abaec45cd7 100644
--- a/src/test/test_bitcoin.cpp
+++ b/src/test/test_bitcoin.cpp
@@ -2,8 +2,6 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#define BOOST_TEST_MODULE Bitcoin Test Suite
-
#include "test_bitcoin.h"
#include "chainparams.h"
@@ -27,10 +25,8 @@
#include <memory>
#include <boost/filesystem.hpp>
-#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
-std::unique_ptr<CConnman> g_connman;
FastRandomContext insecure_rand_ctx(true);
extern bool fPrintToConsole;
@@ -69,11 +65,14 @@ TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(cha
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
- BOOST_REQUIRE(InitBlockIndex(chainparams));
+ if (!InitBlockIndex(chainparams)) {
+ throw std::runtime_error("InitBlockIndex failed.");
+ }
{
CValidationState state;
- bool ok = ActivateBestChain(state, chainparams);
- BOOST_REQUIRE(ok);
+ if (!ActivateBestChain(state, chainparams)) {
+ throw std::runtime_error("ActivateBestChain failed.");
+ }
}
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
@@ -150,18 +149,3 @@ CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransaction &txn) {
return CTxMemPoolEntry(MakeTransactionRef(txn), nFee, nTime, nHeight,
spendsCoinbase, sigOpCost, lp);
}
-
-void Shutdown(void* parg)
-{
- exit(EXIT_SUCCESS);
-}
-
-void StartShutdown()
-{
- exit(EXIT_SUCCESS);
-}
-
-bool ShutdownRequested()
-{
- return false;
-}
diff --git a/src/test/test_bitcoin_main.cpp b/src/test/test_bitcoin_main.cpp
new file mode 100644
index 0000000000..34beef5539
--- /dev/null
+++ b/src/test/test_bitcoin_main.cpp
@@ -0,0 +1,26 @@
+// Copyright (c) 2011-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.
+
+#define BOOST_TEST_MODULE Bitcoin Test Suite
+
+#include "net.h"
+
+#include <boost/test/unit_test.hpp>
+
+std::unique_ptr<CConnman> g_connman;
+
+void Shutdown(void* parg)
+{
+ exit(EXIT_SUCCESS);
+}
+
+void StartShutdown()
+{
+ exit(EXIT_SUCCESS);
+}
+
+bool ShutdownRequested()
+{
+ return false;
+}
diff --git a/src/util.h b/src/util.h
index 87eb16c91b..61dc0d366c 100644
--- a/src/util.h
+++ b/src/util.h
@@ -80,9 +80,9 @@ template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt,
std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
try { \
_log_msg_ = tfm::format(__VA_ARGS__); \
- } catch (tinyformat::format_error &e) { \
+ } catch (tinyformat::format_error &fmterr) { \
/* Original format string will have newline so don't add one here */ \
- _log_msg_ = "Error \"" + std::string(e.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
+ _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
} \
LogPrintStr(_log_msg_); \
} while(0)
diff --git a/src/wallet/coincontrol.h b/src/wallet/coincontrol.h
index eaf4ff8062..4e93e929be 100644
--- a/src/wallet/coincontrol.h
+++ b/src/wallet/coincontrol.h
@@ -6,6 +6,7 @@
#define BITCOIN_WALLET_COINCONTROL_H
#include "primitives/transaction.h"
+#include "wallet/wallet.h"
/** Coin Control Features. */
class CCoinControl
@@ -24,6 +25,8 @@ public:
CFeeRate nFeeRate;
//! Override the default confirmation target, 0 = use default
int nConfirmTarget;
+ //! Signal BIP-125 replace by fee.
+ bool signalRbf;
CCoinControl()
{
@@ -40,6 +43,7 @@ public:
nFeeRate = CFeeRate(0);
fOverrideFeeRate = false;
nConfirmTarget = 0;
+ signalRbf = fWalletRbf;
}
bool HasSelected() const
diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp
index 9554f0541e..7ff9e7ae58 100644
--- a/src/wallet/rpcdump.cpp
+++ b/src/wallet/rpcdump.cpp
@@ -743,7 +743,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
pwallet->MarkDirty();
- if (!pwallet->HaveWatchOnly(redeemScript) && !pwallet->AddWatchOnly(redeemScript, timestamp)) {
+ if (!pwallet->AddWatchOnly(redeemScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
@@ -760,7 +760,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
pwallet->MarkDirty();
- if (!pwallet->HaveWatchOnly(redeemDestination) && !pwallet->AddWatchOnly(redeemDestination, timestamp)) {
+ if (!pwallet->AddWatchOnly(redeemDestination, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
@@ -853,7 +853,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
pwallet->MarkDirty();
- if (!pwallet->HaveWatchOnly(pubKeyScript) && !pwallet->AddWatchOnly(pubKeyScript, timestamp)) {
+ if (!pwallet->AddWatchOnly(pubKeyScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
@@ -871,7 +871,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
pwallet->MarkDirty();
- if (!pwallet->HaveWatchOnly(scriptRawPubKey) && !pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) {
+ if (!pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
@@ -945,7 +945,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
pwallet->MarkDirty();
- if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, timestamp)) {
+ if (!pwallet->AddWatchOnly(script, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index 9e3c8be3f2..445e40b043 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -2517,9 +2517,10 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
// to avoid conflicting with other possible uses of nSequence,
// and in the spirit of "smallest possible change from prior
// behavior."
+ bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
for (const auto& coin : setCoins)
txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
- std::numeric_limits<unsigned int>::max() - (fWalletRbf ? 2 : 1)));
+ std::numeric_limits<unsigned int>::max() - (rbf ? 2 : 1)));
// Fill in dummy signatures for fee calculation.
if (!DummySignTx(txNew, setCoins)) {
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index 80201e8ce0..ae4321eef8 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -725,6 +725,7 @@ public:
nLastResend = 0;
nTimeFirstKey = 0;
fBroadcastTransactions = false;
+ nRelockTime = 0;
}
std::map<uint256, CWalletTx> mapWallet;