aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--CONTRIBUTING.md4
-rw-r--r--configure.ac27
-rw-r--r--contrib/README.md2
-rw-r--r--contrib/bitcoind.bash-completion2
-rw-r--r--contrib/debian/examples/bitcoin.conf2
-rwxr-xr-xcontrib/devtools/check-doc.py3
-rwxr-xr-xcontrib/devtools/github-merge.py49
-rwxr-xr-xcontrib/devtools/security-check.py2
-rwxr-xr-xcontrib/devtools/symbol-check.py2
-rwxr-xr-xcontrib/devtools/update-translations.py4
-rwxr-xr-xcontrib/gitian-build.sh6
-rw-r--r--contrib/gitian-descriptors/README.md10
-rw-r--r--contrib/gitian-descriptors/gitian-linux.yml11
-rw-r--r--contrib/gitian-descriptors/gitian-osx.yml11
-rw-r--r--contrib/gitian-descriptors/gitian-win.yml11
-rw-r--r--contrib/gitian-keys/README.md2
-rw-r--r--contrib/gitian-keys/meshcollider-key.pgp51
-rw-r--r--contrib/init/bitcoind.conf4
-rw-r--r--contrib/init/bitcoind.openrc4
-rw-r--r--contrib/linearize/README.md2
-rwxr-xr-xcontrib/linearize/linearize-hashes.py4
-rw-r--r--contrib/rpm/README.md14
-rwxr-xr-xcontrib/seeds/generate-seeds.py2
-rwxr-xr-xcontrib/zmq/zmq_sub.py2
-rwxr-xr-xcontrib/zmq/zmq_sub3.4.py2
-rw-r--r--doc/REST-interface.md12
-rw-r--r--doc/build-openbsd.md14
-rw-r--r--doc/build-osx.md2
-rw-r--r--doc/build-unix.md4
-rw-r--r--doc/build-windows.md3
-rw-r--r--doc/developer-notes.md22
-rw-r--r--doc/init.md28
-rw-r--r--doc/release-notes.md326
-rw-r--r--doc/zmq.md2
-rwxr-xr-xshare/qt/extract_strings_qt.py2
-rw-r--r--src/Makefile.am11
-rw-r--r--src/Makefile.qttest.include6
-rw-r--r--src/Makefile.test.include2
-rw-r--r--src/addrdb.h4
-rw-r--r--src/arith_uint256.h2
-rw-r--r--src/base58.cpp2
-rw-r--r--src/bench/checkqueue.cpp2
-rw-r--r--src/bench/lockedpool.cpp4
-rw-r--r--src/bitcoin-cli.cpp45
-rw-r--r--src/bitcoin-tx.cpp10
-rw-r--r--src/bitcoind.cpp14
-rw-r--r--src/blockencodings.h6
-rw-r--r--src/chain.h4
-rw-r--r--src/chainparamsbase.cpp4
-rw-r--r--src/checkqueue.h2
-rw-r--r--src/coins.cpp2
-rw-r--r--src/compat/byteswap.h2
-rw-r--r--src/compat/endian.h4
-rw-r--r--src/compressor.h4
-rw-r--r--src/core_io.h2
-rw-r--r--src/core_write.cpp6
-rw-r--r--src/crypto/aes.h8
-rw-r--r--src/crypto/common.h2
-rw-r--r--src/crypto/hmac_sha256.h2
-rw-r--r--src/crypto/sha256.cpp4
-rw-r--r--src/cuckoocache.h8
-rw-r--r--src/dbwrapper.cpp6
-rw-r--r--src/dbwrapper.h6
-rw-r--r--src/hash.h2
-rw-r--r--src/httprpc.cpp10
-rw-r--r--src/httpserver.cpp36
-rw-r--r--src/httpserver.h2
-rw-r--r--src/init.cpp231
-rw-r--r--src/key.h2
-rw-r--r--src/keystore.h14
-rw-r--r--src/limitedmap.h2
-rw-r--r--src/merkleblock.h2
-rw-r--r--src/miner.cpp18
-rw-r--r--src/miner.h12
-rw-r--r--src/net.cpp18
-rw-r--r--src/net_processing.cpp22
-rw-r--r--src/net_processing.h2
-rw-r--r--src/netaddress.h8
-rw-r--r--src/netbase.h6
-rw-r--r--src/netmessagemaker.h2
-rw-r--r--src/policy/feerate.h1
-rw-r--r--src/policy/fees.h2
-rw-r--r--src/prevector.h6
-rw-r--r--src/primitives/block.h2
-rw-r--r--src/protocol.h2
-rw-r--r--src/pubkey.h4
-rw-r--r--src/qt/bitcoin.cpp22
-rw-r--r--src/qt/bitcoingui.cpp1
-rw-r--r--src/qt/callback.h2
-rw-r--r--src/qt/coincontroldialog.cpp3
-rw-r--r--src/qt/coincontroldialog.h6
-rw-r--r--src/qt/guiutil.cpp4
-rw-r--r--src/qt/intro.cpp10
-rw-r--r--src/qt/macdockiconhandler.mm8
-rw-r--r--src/qt/macnotificationhandler.mm2
-rw-r--r--src/qt/modaloverlay.h2
-rw-r--r--src/qt/networkstyle.cpp2
-rw-r--r--src/qt/notificator.cpp2
-rw-r--r--src/qt/optionsdialog.cpp6
-rw-r--r--src/qt/optionsmodel.cpp26
-rw-r--r--src/qt/optionsmodel.h14
-rw-r--r--src/qt/overviewpage.cpp2
-rw-r--r--src/qt/paymentrequestplus.cpp4
-rw-r--r--src/qt/paymentserver.cpp4
-rw-r--r--src/qt/paymentserver.h4
-rw-r--r--src/qt/sendcoinsdialog.cpp10
-rw-r--r--src/qt/test/paymentservertests.cpp2
-rw-r--r--src/qt/test/paymentservertests.h2
-rw-r--r--src/qt/test/rpcnestedtests.cpp9
-rw-r--r--src/qt/test/test_main.cpp2
-rw-r--r--src/qt/transactionrecord.cpp2
-rw-r--r--src/qt/transactionrecord.h2
-rw-r--r--src/qt/transactiontablemodel.h2
-rw-r--r--src/qt/utilitydialog.cpp2
-rw-r--r--src/qt/utilitydialog.h2
-rw-r--r--src/qt/walletmodel.cpp9
-rw-r--r--src/qt/walletmodeltransaction.cpp8
-rw-r--r--src/qt/walletmodeltransaction.h8
-rw-r--r--src/random.cpp6
-rw-r--r--src/rest.cpp2
-rw-r--r--src/reverse_iterator.h2
-rw-r--r--src/rpc/blockchain.cpp75
-rw-r--r--src/rpc/mining.cpp33
-rw-r--r--src/rpc/misc.cpp30
-rw-r--r--src/rpc/net.cpp38
-rw-r--r--src/rpc/protocol.cpp21
-rw-r--r--src/rpc/protocol.h2
-rw-r--r--src/rpc/rawtransaction.cpp48
-rw-r--r--src/rpc/safemode.cpp14
-rw-r--r--src/rpc/safemode.h12
-rw-r--r--src/rpc/server.cpp17
-rw-r--r--src/rpc/server.h4
-rw-r--r--src/scheduler.cpp2
-rw-r--r--src/scheduler.h4
-rw-r--r--src/script/interpreter.h2
-rw-r--r--src/script/script.h6
-rw-r--r--src/script/sigcache.cpp2
-rw-r--r--src/script/sign.h4
-rw-r--r--src/script/standard.cpp5
-rw-r--r--src/script/standard.h62
-rw-r--r--src/serialize.h6
-rw-r--r--src/streams.h8
-rw-r--r--src/support/allocators/secure.h8
-rw-r--r--src/support/allocators/zeroafterfree.h8
-rw-r--r--src/support/lockedpool.h4
-rw-r--r--src/sync.cpp2
-rw-r--r--src/sync.h6
-rw-r--r--src/test/DoS_tests.cpp4
-rw-r--r--src/test/addrman_tests.cpp2
-rw-r--r--src/test/base58_tests.cpp4
-rw-r--r--src/test/bip32_tests.cpp2
-rw-r--r--src/test/blockencodings_tests.cpp6
-rw-r--r--src/test/coins_tests.cpp8
-rw-r--r--src/test/data/tx_invalid.json2
-rw-r--r--src/test/data/tx_valid.json2
-rw-r--r--src/test/dbwrapper_tests.cpp2
-rw-r--r--src/test/getarg_tests.cpp112
-rw-r--r--src/test/net_tests.cpp2
-rw-r--r--src/test/prevector_tests.cpp4
-rw-r--r--src/test/script_tests.cpp2
-rw-r--r--src/test/scriptnum_tests.cpp8
-rw-r--r--src/test/sighash_tests.cpp6
-rw-r--r--src/test/test_bitcoin.cpp6
-rw-r--r--src/test/test_bitcoin.h4
-rw-r--r--src/test/test_bitcoin_main.cpp8
-rw-r--r--src/test/testutil.cpp15
-rw-r--r--src/test/testutil.h15
-rw-r--r--src/test/versionbits_tests.cpp8
-rw-r--r--src/timedata.cpp2
-rw-r--r--src/tinyformat.h8
-rw-r--r--src/torcontrol.cpp16
-rw-r--r--src/txdb.cpp6
-rw-r--r--src/txdb.h6
-rw-r--r--src/txmempool.cpp5
-rw-r--r--src/txmempool.h17
-rw-r--r--src/uint256.h4
-rw-r--r--src/undo.h4
-rw-r--r--src/univalue/lib/univalue_utffilter.h2
-rw-r--r--src/util.cpp38
-rw-r--r--src/util.h67
-rw-r--r--src/validation.cpp68
-rw-r--r--src/validation.h2
-rw-r--r--src/validationinterface.cpp2
-rw-r--r--src/versionbits.cpp4
-rw-r--r--src/wallet/crypter.h2
-rw-r--r--src/wallet/db.cpp16
-rw-r--r--src/wallet/db.h2
-rw-r--r--src/wallet/feebumper.cpp16
-rw-r--r--src/wallet/fees.cpp89
-rw-r--r--src/wallet/fees.h34
-rw-r--r--src/wallet/init.cpp247
-rw-r--r--src/wallet/init.h25
-rw-r--r--src/wallet/rpcdump.cpp2
-rw-r--r--src/wallet/rpcwallet.cpp245
-rw-r--r--src/wallet/test/crypto_tests.cpp133
-rw-r--r--src/wallet/test/wallet_test_fixture.h2
-rw-r--r--src/wallet/test/wallet_tests.cpp17
-rw-r--r--src/wallet/wallet.cpp478
-rw-r--r--src/wallet/wallet.h40
-rw-r--r--src/wallet/walletdb.cpp23
-rw-r--r--src/wallet/walletdb.h6
-rw-r--r--src/warnings.cpp2
-rw-r--r--src/zmq/zmqabstractnotifier.h2
-rw-r--r--src/zmq/zmqnotificationinterface.cpp6
-rw-r--r--src/zmq/zmqnotificationinterface.h2
-rw-r--r--src/zmq/zmqpublishnotifier.cpp4
-rw-r--r--test/functional/README.md6
-rwxr-xr-xtest/functional/abandonconflict.py10
-rwxr-xr-xtest/functional/assumevalid.py12
-rwxr-xr-xtest/functional/bip65-cltv-p2p.py8
-rwxr-xr-xtest/functional/bip68-112-113-p2p.py4
-rwxr-xr-xtest/functional/bip68-sequence.py6
-rwxr-xr-xtest/functional/bip9-softforks.py6
-rwxr-xr-xtest/functional/bipdersig-p2p.py8
-rwxr-xr-xtest/functional/bitcoin_cli.py25
-rwxr-xr-xtest/functional/blockchain.py12
-rwxr-xr-xtest/functional/bumpfee.py21
-rwxr-xr-xtest/functional/create_cache.py7
-rwxr-xr-xtest/functional/dbcrash.py11
-rwxr-xr-xtest/functional/decodescript.py4
-rwxr-xr-xtest/functional/disablewallet.py5
-rwxr-xr-xtest/functional/disconnect_ban.py23
-rwxr-xr-xtest/functional/example_test.py18
-rwxr-xr-xtest/functional/forknotify.py18
-rwxr-xr-xtest/functional/fundrawtransaction.py13
-rwxr-xr-xtest/functional/getblocktemplate_longpoll.py8
-rwxr-xr-xtest/functional/getchaintips.py5
-rwxr-xr-xtest/functional/httpbasics.py4
-rwxr-xr-xtest/functional/import-rescan.py7
-rwxr-xr-xtest/functional/importmulti.py18
-rwxr-xr-xtest/functional/importprunedfunds.py10
-rwxr-xr-xtest/functional/invalidateblock.py4
-rwxr-xr-xtest/functional/invalidblockrequest.py4
-rwxr-xr-xtest/functional/invalidtxrequest.py4
-rwxr-xr-xtest/functional/keypool-topup.py9
-rwxr-xr-xtest/functional/keypool.py12
-rwxr-xr-xtest/functional/listsinceblock.py6
-rwxr-xr-xtest/functional/listtransactions.py10
-rwxr-xr-xtest/functional/maxuploadtarget.py5
-rwxr-xr-xtest/functional/mempool_limit.py4
-rwxr-xr-xtest/functional/mempool_packages.py6
-rwxr-xr-xtest/functional/mempool_persist.py22
-rwxr-xr-xtest/functional/mempool_reorg.py4
-rwxr-xr-xtest/functional/mempool_resurrect_test.py6
-rwxr-xr-xtest/functional/mempool_spendcoinbase.py5
-rwxr-xr-xtest/functional/merkle_blocks.py6
-rwxr-xr-xtest/functional/mining.py24
-rwxr-xr-xtest/functional/multi_rpc.py5
-rwxr-xr-xtest/functional/multiwallet.py24
-rwxr-xr-xtest/functional/net.py6
-rwxr-xr-xtest/functional/nulldummy.py3
-rwxr-xr-xtest/functional/p2p-acceptblock.py3
-rwxr-xr-xtest/functional/p2p-compactblocks.py53
-rwxr-xr-xtest/functional/p2p-feefilter.py5
-rwxr-xr-xtest/functional/p2p-fullblocktest.py23
-rwxr-xr-xtest/functional/p2p-leaktests.py17
-rwxr-xr-xtest/functional/p2p-mempool.py4
-rwxr-xr-xtest/functional/p2p-segwit.py11
-rwxr-xr-xtest/functional/p2p-timeouts.py3
-rwxr-xr-xtest/functional/p2p-versionbits-warning.py7
-rwxr-xr-xtest/functional/preciousblock.py9
-rwxr-xr-xtest/functional/prioritise_transaction.py4
-rwxr-xr-xtest/functional/proxy_test.py8
-rwxr-xr-xtest/functional/pruning.py32
-rwxr-xr-xtest/functional/rawtransactions.py8
-rwxr-xr-xtest/functional/receivedby.py11
-rwxr-xr-xtest/functional/reindex.py5
-rwxr-xr-xtest/functional/replace-by-fee.py10
-rwxr-xr-xtest/functional/resendwallettransactions.py8
-rwxr-xr-xtest/functional/rest.py3
-rwxr-xr-xtest/functional/rpcbind_test.py22
-rwxr-xr-xtest/functional/rpcnamedargs.py9
-rwxr-xr-xtest/functional/segwit.py5
-rwxr-xr-xtest/functional/sendheaders.py9
-rwxr-xr-xtest/functional/signmessages.py25
-rwxr-xr-xtest/functional/signrawtransactions.py3
-rwxr-xr-xtest/functional/smartfees.py94
-rw-r--r--test/functional/test_framework/address.py10
-rw-r--r--test/functional/test_framework/bignum.py39
-rw-r--r--test/functional/test_framework/blockstore.py10
-rwxr-xr-xtest/functional/test_framework/comptool.py12
-rwxr-xr-xtest/functional/test_framework/mininode.py44
-rw-r--r--test/functional/test_framework/netutil.py20
-rw-r--r--test/functional/test_framework/script.py245
-rw-r--r--test/functional/test_framework/socks5.py2
-rwxr-xr-xtest/functional/test_framework/test_framework.py269
-rwxr-xr-xtest/functional/test_framework/test_node.py171
-rw-r--r--test/functional/test_framework/util.py26
-rwxr-xr-xtest/functional/test_runner.py6
-rwxr-xr-xtest/functional/txn_clone.py5
-rwxr-xr-xtest/functional/txn_doublespend.py5
-rwxr-xr-xtest/functional/uptime.py4
-rwxr-xr-xtest/functional/wallet-accounts.py4
-rwxr-xr-xtest/functional/wallet-dump.py15
-rwxr-xr-xtest/functional/wallet-encryption.py9
-rwxr-xr-xtest/functional/wallet-hd.py21
-rwxr-xr-xtest/functional/wallet.py94
-rwxr-xr-xtest/functional/walletbackup.py12
-rwxr-xr-xtest/functional/zapwallettxes.py10
-rwxr-xr-xtest/functional/zmq_test.py9
301 files changed, 2519 insertions, 3065 deletions
diff --git a/.travis.yml b/.travis.yml
index 12f91096cc..dadac3165e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -34,7 +34,7 @@ env:
# x86_64 Linux, 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"
# 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"
+ - 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 --enable-werror" OSX_SDK=10.11 GOAL="deploy"
before_install:
- export PATH=$(echo $PATH | tr ':' "\n" | sed '/\/opt\/python/d' | tr "\n" ":" | sed "s|::|:|g")
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4e67af6278..56521a5f7d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -81,6 +81,10 @@ Examples:
Qt: Add feed bump button
Trivial: Fix typo in init.cpp
+Note that translations should not be submitted as pull requests, please see
+[Translation Process](https://github.com/bitcoin/bitcoin/blob/master/doc/translation_process.md)
+for more information on helping with translations.
+
If a pull request is specifically not to be considered for merging (yet) please
prefix the title with [WIP] or use [Tasks Lists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#task-lists)
in the body of the pull request to indicate tasks are pending.
diff --git a/configure.ac b/configure.ac
index fd1396fc9e..e3e71044da 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,7 +1,7 @@
dnl require autoconf 2.60 (AS_ECHO/AS_ECHO_N)
AC_PREREQ([2.60])
define(_CLIENT_VERSION_MAJOR, 0)
-define(_CLIENT_VERSION_MINOR, 14)
+define(_CLIENT_VERSION_MINOR, 15)
define(_CLIENT_VERSION_REVISION, 99)
define(_CLIENT_VERSION_BUILD, 0)
define(_CLIENT_VERSION_IS_RELEASE, false)
@@ -177,14 +177,14 @@ AC_ARG_ENABLE([glibc-back-compat],
[use_glibc_compat=$enableval],
[use_glibc_compat=no])
-AC_ARG_ENABLE([experimental-asm],
- [AS_HELP_STRING([--enable-experimental-asm],
- [Enable experimental assembly routines (default is no)])],
- [experimental_asm=$enableval],
- [experimental_asm=no])
+AC_ARG_ENABLE([asm],
+ [AS_HELP_STRING([--enable-asm],
+ [Enable assembly routines (default is yes)])],
+ [use_asm=$enableval],
+ [use_asm=yes])
-if test "x$experimental_asm" = xyes; then
- AC_DEFINE(EXPERIMENTAL_ASM, 1, [Define this symbol to build in experimental assembly routines])
+if test "x$use_asm" = xyes; then
+ AC_DEFINE(USE_ASM, 1, [Define this symbol to build in assembly routines])
fi
AC_ARG_WITH([system-univalue],
@@ -827,14 +827,14 @@ TEMP_CPPFLAGS="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
AC_MSG_CHECKING([for mismatched boost c++11 scoped enums])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
- #include "boost/config.hpp"
- #include "boost/version.hpp"
+ #include <boost/config.hpp>
+ #include <boost/version.hpp>
#if !defined(BOOST_NO_SCOPED_ENUMS) && !defined(BOOST_NO_CXX11_SCOPED_ENUMS) && BOOST_VERSION < 105700
#define BOOST_NO_SCOPED_ENUMS
#define BOOST_NO_CXX11_SCOPED_ENUMS
#define CHECK
#endif
- #include "boost/filesystem.hpp"
+ #include <boost/filesystem.hpp>
]],[[
#if defined(CHECK)
boost::filesystem::copy_file("foo", "bar");
@@ -1179,7 +1179,7 @@ AM_CONDITIONAL([USE_LCOV],[test x$use_lcov = xyes])
AM_CONDITIONAL([GLIBC_BACK_COMPAT],[test x$use_glibc_compat = xyes])
AM_CONDITIONAL([HARDEN],[test x$use_hardening = xyes])
AM_CONDITIONAL([ENABLE_HWCRC32],[test x$enable_hwcrc32 = xyes])
-AM_CONDITIONAL([EXPERIMENTAL_ASM],[test x$experimental_asm = xyes])
+AM_CONDITIONAL([USE_ASM],[test x$use_asm = xyes])
AC_DEFINE(CLIENT_VERSION_MAJOR, _CLIENT_VERSION_MAJOR, [Major version])
AC_DEFINE(CLIENT_VERSION_MINOR, _CLIENT_VERSION_MINOR, [Minor version])
@@ -1261,7 +1261,7 @@ if test x$need_bundled_univalue = xyes; then
AC_CONFIG_SUBDIRS([src/univalue])
fi
-ac_configure_args="${ac_configure_args} --disable-shared --with-pic --with-bignum=no --enable-module-recovery"
+ac_configure_args="${ac_configure_args} --disable-shared --with-pic --with-bignum=no --enable-module-recovery --disable-jni"
AC_CONFIG_SUBDIRS([src/secp256k1])
AC_OUTPUT
@@ -1297,6 +1297,7 @@ echo " with zmq = $use_zmq"
echo " with test = $use_tests"
echo " with bench = $use_bench"
echo " with upnp = $use_upnp"
+echo " use asm = $use_asm"
echo " debug enabled = $enable_debug"
echo " werror = $enable_werror"
echo
diff --git a/contrib/README.md b/contrib/README.md
index 6f750106e4..34c4cfc55a 100644
--- a/contrib/README.md
+++ b/contrib/README.md
@@ -35,7 +35,7 @@ PGP keys used for signing Bitcoin Core [Gitian release](/doc/release-process.md)
Scripts and notes for Mac builds.
### [RPM](/contrib/rpm) ###
-RPM spec file for building bitcoin-core on RPM based distributions
+RPM spec file for building bitcoin-core on RPM based distributions.
### [Gitian-build](/contrib/gitian-build.sh) ###
Script for running full Gitian builds.
diff --git a/contrib/bitcoind.bash-completion b/contrib/bitcoind.bash-completion
index af87e97d80..cccd4bde0d 100644
--- a/contrib/bitcoind.bash-completion
+++ b/contrib/bitcoind.bash-completion
@@ -30,7 +30,7 @@ _bitcoind() {
;;
*)
- # only parse -help if senseful
+ # only parse -help if sensible
if [[ -z "$cur" || "$cur" =~ ^- ]]; then
local helpopts
helpopts=$($bitcoind -help 2>&1 | awk '$1 ~ /^-/ { sub(/=.*/, "="); print $1 }' )
diff --git a/contrib/debian/examples/bitcoin.conf b/contrib/debian/examples/bitcoin.conf
index 1029a51073..14a59fdf6b 100644
--- a/contrib/debian/examples/bitcoin.conf
+++ b/contrib/debian/examples/bitcoin.conf
@@ -76,7 +76,7 @@
#rpcuser=Ulysseys
#rpcpassword=YourSuperGreatPasswordNumber_DO_NOT_USE_THIS_OR_YOU_WILL_GET_ROBBED_385593
#
-# The second method `rpcauth` can be added to server startup argument. It is set at intialization time
+# The second method `rpcauth` can be added to server startup argument. It is set at initialization time
# using the output from the script in share/rpcuser/rpcuser.py after providing a username:
#
# ./share/rpcuser/rpcuser.py alice
diff --git a/contrib/devtools/check-doc.py b/contrib/devtools/check-doc.py
index 3b7a8f9a61..3279dc3612 100755
--- a/contrib/devtools/check-doc.py
+++ b/contrib/devtools/check-doc.py
@@ -12,6 +12,7 @@ Author: @MarcoFalke
from subprocess import check_output
import re
+import sys
FOLDER_GREP = 'src'
FOLDER_TEST = 'src/test/'
@@ -39,7 +40,7 @@ def main():
print "Args unknown : %s" % len(args_unknown)
print args_unknown
- exit(len(args_need_doc))
+ sys.exit(len(args_need_doc))
if __name__ == "__main__":
main()
diff --git a/contrib/devtools/github-merge.py b/contrib/devtools/github-merge.py
index c664cf81fa..2941d2cb6d 100755
--- a/contrib/devtools/github-merge.py
+++ b/contrib/devtools/github-merge.py
@@ -20,6 +20,7 @@ from sys import stdin,stdout,stderr
import argparse
import hashlib
import subprocess
+import sys
import json,codecs
try:
from urllib.request import Request,urlopen
@@ -158,11 +159,11 @@ def main():
if repo is None:
print("ERROR: No repository configured. Use this command to set:", file=stderr)
print("git config githubmerge.repository <owner>/<repo>", file=stderr)
- exit(1)
+ sys.exit(1)
if signingkey is None:
print("ERROR: No GPG signing key set. Set one using:",file=stderr)
print("git config --global user.signingkey <key>",file=stderr)
- exit(1)
+ sys.exit(1)
host_repo = host+":"+repo # shortcut for push/pull target
@@ -173,7 +174,7 @@ def main():
# Receive pull information from github
info = retrieve_pr_info(repo,pull)
if info is None:
- exit(1)
+ sys.exit(1)
title = info['title'].strip()
body = info['body'].strip()
# precedence order for destination branch argument:
@@ -194,27 +195,23 @@ def main():
subprocess.check_call([GIT,'checkout','-q',branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot check out branch %s." % (branch), file=stderr)
- exit(3)
+ sys.exit(3)
try:
- subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/pull/'+pull+'/*:refs/heads/pull/'+pull+'/*'])
+ subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/pull/'+pull+'/*:refs/heads/pull/'+pull+'/*',
+ '+refs/heads/'+branch+':refs/heads/'+base_branch])
except subprocess.CalledProcessError as e:
- print("ERROR: Cannot find pull request #%s on %s." % (pull,host_repo), file=stderr)
- exit(3)
+ print("ERROR: Cannot find pull request #%s or branch %s on %s." % (pull,branch,host_repo), file=stderr)
+ sys.exit(3)
try:
subprocess.check_call([GIT,'log','-q','-1','refs/heads/'+head_branch], stdout=devnull, stderr=stdout)
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find head of pull request #%s on %s." % (pull,host_repo), file=stderr)
- exit(3)
+ sys.exit(3)
try:
subprocess.check_call([GIT,'log','-q','-1','refs/heads/'+merge_branch], stdout=devnull, stderr=stdout)
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find merge of pull request #%s on %s." % (pull,host_repo), file=stderr)
- exit(3)
- try:
- subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/heads/'+branch+':refs/heads/'+base_branch])
- except subprocess.CalledProcessError as e:
- print("ERROR: Cannot find branch %s on %s." % (branch,host_repo), file=stderr)
- exit(3)
+ sys.exit(3)
subprocess.check_call([GIT,'checkout','-q',base_branch])
subprocess.call([GIT,'branch','-q','-D',local_merge_branch], stderr=devnull)
subprocess.check_call([GIT,'checkout','-q','-b',local_merge_branch])
@@ -236,30 +233,30 @@ def main():
except subprocess.CalledProcessError as e:
print("ERROR: Cannot be merged cleanly.",file=stderr)
subprocess.check_call([GIT,'merge','--abort'])
- exit(4)
+ sys.exit(4)
logmsg = subprocess.check_output([GIT,'log','--pretty=format:%s','-n','1']).decode('utf-8')
if logmsg.rstrip() != firstline.rstrip():
print("ERROR: Creating merge failed (already merged?).",file=stderr)
- exit(4)
+ sys.exit(4)
symlink_files = get_symlink_files()
for f in symlink_files:
print("ERROR: File %s was a symlink" % f)
if len(symlink_files) > 0:
- exit(4)
+ sys.exit(4)
# Put tree SHA512 into the message
try:
first_sha512 = tree_sha512sum()
message += '\n\nTree-SHA512: ' + first_sha512
except subprocess.CalledProcessError as e:
- printf("ERROR: Unable to compute tree hash")
- exit(4)
+ print("ERROR: Unable to compute tree hash")
+ sys.exit(4)
try:
subprocess.check_call([GIT,'commit','--amend','-m',message.encode('utf-8')])
except subprocess.CalledProcessError as e:
- printf("ERROR: Cannot update message.",file=stderr)
- exit(4)
+ print("ERROR: Cannot update message.", file=stderr)
+ sys.exit(4)
print_merge_details(pull, title, branch, base_branch, head_branch)
print()
@@ -268,7 +265,7 @@ def main():
if testcmd:
if subprocess.call(testcmd,shell=True):
print("ERROR: Running %s failed." % testcmd,file=stderr)
- exit(5)
+ sys.exit(5)
# Show the created merge.
diff = subprocess.check_output([GIT,'diff',merge_branch+'..'+local_merge_branch])
@@ -279,7 +276,7 @@ def main():
if reply.lower() == 'ignore':
print("Difference with github ignored.",file=stderr)
else:
- exit(6)
+ sys.exit(6)
else:
# Verify the result manually.
print("Dropping you on a shell so you can try building/testing the merged source.",file=stderr)
@@ -292,7 +289,7 @@ def main():
second_sha512 = tree_sha512sum()
if first_sha512 != second_sha512:
print("ERROR: Tree hash changed unexpectedly",file=stderr)
- exit(8)
+ sys.exit(8)
# Sign the merge commit.
print_merge_details(pull, title, branch, base_branch, head_branch)
@@ -306,7 +303,7 @@ def main():
print("Error while signing, asking again.",file=stderr)
elif reply == 'x':
print("Not signing off on merge, exiting.",file=stderr)
- exit(1)
+ sys.exit(1)
# Put the result in branch.
subprocess.check_call([GIT,'checkout','-q',branch])
@@ -326,7 +323,7 @@ def main():
subprocess.check_call([GIT,'push',host_repo,'refs/heads/'+branch])
break
elif reply == 'x':
- exit(1)
+ sys.exit(1)
if __name__ == '__main__':
main()
diff --git a/contrib/devtools/security-check.py b/contrib/devtools/security-check.py
index c90541e271..6eb5667453 100755
--- a/contrib/devtools/security-check.py
+++ b/contrib/devtools/security-check.py
@@ -212,5 +212,5 @@ if __name__ == '__main__':
except IOError:
print('%s: cannot open' % filename)
retval = 1
- exit(retval)
+ sys.exit(retval)
diff --git a/contrib/devtools/symbol-check.py b/contrib/devtools/symbol-check.py
index 8f8685006e..98daa1bd76 100755
--- a/contrib/devtools/symbol-check.py
+++ b/contrib/devtools/symbol-check.py
@@ -159,6 +159,6 @@ if __name__ == '__main__':
print('%s: NEEDED library %s is not allowed' % (filename, library_name.decode('utf-8')))
retval = 1
- exit(retval)
+ sys.exit(retval)
diff --git a/contrib/devtools/update-translations.py b/contrib/devtools/update-translations.py
index 2011841005..e1924749d2 100755
--- a/contrib/devtools/update-translations.py
+++ b/contrib/devtools/update-translations.py
@@ -36,12 +36,12 @@ def check_at_repository_root():
if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
- exit(1)
+ sys.exit(1)
def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f', '-a']):
print('Error while fetching translations', file=sys.stderr)
- exit(1)
+ sys.exit(1)
def find_format_specifiers(s):
'''Find all format specifiers in a string.'''
diff --git a/contrib/gitian-build.sh b/contrib/gitian-build.sh
index 6ee5df4703..d94c7f4f8e 100755
--- a/contrib/gitian-build.sh
+++ b/contrib/gitian-build.sh
@@ -40,15 +40,15 @@ version Version number, commit, or branch to build. If building a commit or bra
Options:
-c|--commit Indicate that the version argument is for a commit or branch
-u|--url Specify the URL of the repository. Default is https://github.com/bitcoin/bitcoin
--v|--verify Verify the gitian build
--b|--build Do a gitian build
+-v|--verify Verify the Gitian build
+-b|--build Do a Gitian build
-s|--sign Make signed binaries for Windows and Mac OSX
-B|--buildsign Build both signed and unsigned binaries
-o|--os Specify which Operating Systems the build is for. Default is lwx. l for linux, w for windows, x for osx
-j Number of processes to use. Default 2
-m Memory to allocate in MiB. Default 2000
--kvm Use KVM instead of LXC
---setup Setup the gitian building environment. Uses KVM. If you want to use lxc, use the --lxc option. Only works on Debian-based systems (Ubuntu, Debian)
+--setup Set up the Gitian building environment. Uses KVM. If you want to use lxc, use the --lxc option. Only works on Debian-based systems (Ubuntu, Debian)
--detach-sign Create the assert file for detached signing. Will not commit anything.
--no-commit Do not commit anything to git
-h|--help Print this help message
diff --git a/contrib/gitian-descriptors/README.md b/contrib/gitian-descriptors/README.md
index 6149706596..d9dbfd3cb3 100644
--- a/contrib/gitian-descriptors/README.md
+++ b/contrib/gitian-descriptors/README.md
@@ -1,4 +1,4 @@
-### Gavin's notes on getting gitian builds up and running using KVM
+### Gavin's notes on getting Gitian builds up and running using KVM
These instructions distilled from
[https://help.ubuntu.com/community/KVM/Installation](https://help.ubuntu.com/community/KVM/Installation).
@@ -56,10 +56,10 @@ Here's a description of Gavin's setup on OSX 10.6:
4. Inside the running Ubuntu desktop, install:
- sudo apt-get install debootstrap lxc ruby apache2 git apt-cacher-ng python-vm-builder
+ sudo apt-get install debootstrap lxc ruby apache2 git apt-cacher-ng python-vm-builder
5. Still inside Ubuntu, tell gitian-builder to use LXC, then follow the "Once you've got the right hardware and software" instructions above:
- export USE_LXC=1
- git clone git://github.com/bitcoin/bitcoin.git
- ... etc
+ export USE_LXC=1
+ git clone git://github.com/bitcoin/bitcoin.git
+ ... etc
diff --git a/contrib/gitian-descriptors/gitian-linux.yml b/contrib/gitian-descriptors/gitian-linux.yml
index 3da8510cfb..c80e19edbb 100644
--- a/contrib/gitian-descriptors/gitian-linux.yml
+++ b/contrib/gitian-descriptors/gitian-linux.yml
@@ -1,5 +1,5 @@
---
-name: "bitcoin-linux-0.15"
+name: "bitcoin-linux-0.16"
enable_cache: true
suites:
- "trusty"
@@ -132,7 +132,6 @@ script: |
export PATH=${WRAP_DIR}:${PATH}
# Create the release tarball using (arbitrarily) the first host
- export GIT_DIR="$PWD/.git"
./autogen.sh
CONFIG_SITE=${BASEPREFIX}/`echo "${HOSTS}" | awk '{print $1;}'`/share/config.site ./configure --prefix=/
make dist
@@ -145,6 +144,9 @@ script: |
find bitcoin-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ../$SOURCEDIST
popd
+ # Workaround for tarball not building with the bare tag version (prep)
+ make -C src obj/build.h
+
ORIGPATH="$PATH"
# Extract the release tarball into a dir for each host and build
for i in ${HOSTS}; do
@@ -155,6 +157,11 @@ script: |
mkdir -p ${INSTALLPATH}
tar --strip-components=1 -xf ../$SOURCEDIST
+ # Workaround for tarball not building with the bare tag version
+ echo '#!/bin/true' >share/genbuild.sh
+ mkdir src/obj
+ cp ../src/obj/build.h src/obj/
+
CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}" LDFLAGS="${HOST_LDFLAGS}"
make ${MAKEOPTS}
make ${MAKEOPTS} -C src check-security
diff --git a/contrib/gitian-descriptors/gitian-osx.yml b/contrib/gitian-descriptors/gitian-osx.yml
index 206db7c19e..cbf286d2cd 100644
--- a/contrib/gitian-descriptors/gitian-osx.yml
+++ b/contrib/gitian-descriptors/gitian-osx.yml
@@ -1,5 +1,5 @@
---
-name: "bitcoin-osx-0.15"
+name: "bitcoin-osx-0.16"
enable_cache: true
suites:
- "trusty"
@@ -101,7 +101,6 @@ script: |
export PATH=${WRAP_DIR}:${PATH}
# Create the release tarball using (arbitrarily) the first host
- export GIT_DIR="$PWD/.git"
./autogen.sh
CONFIG_SITE=${BASEPREFIX}/`echo "${HOSTS}" | awk '{print $1;}'`/share/config.site ./configure --prefix=/
make dist
@@ -115,6 +114,9 @@ script: |
find bitcoin-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ../$SOURCEDIST
popd
+ # Workaround for tarball not building with the bare tag version (prep)
+ make -C src obj/build.h
+
ORIGPATH="$PATH"
# Extract the release tarball into a dir for each host and build
for i in ${HOSTS}; do
@@ -125,6 +127,11 @@ script: |
mkdir -p ${INSTALLPATH}
tar --strip-components=1 -xf ../$SOURCEDIST
+ # Workaround for tarball not building with the bare tag version
+ echo '#!/bin/true' >share/genbuild.sh
+ mkdir src/obj
+ cp ../src/obj/build.h src/obj/
+
CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS}
make ${MAKEOPTS}
make install-strip DESTDIR=${INSTALLPATH}
diff --git a/contrib/gitian-descriptors/gitian-win.yml b/contrib/gitian-descriptors/gitian-win.yml
index 1d4d70494b..95ff9759c7 100644
--- a/contrib/gitian-descriptors/gitian-win.yml
+++ b/contrib/gitian-descriptors/gitian-win.yml
@@ -1,5 +1,5 @@
---
-name: "bitcoin-win-0.15"
+name: "bitcoin-win-0.16"
enable_cache: true
suites:
- "trusty"
@@ -116,7 +116,6 @@ script: |
export PATH=${WRAP_DIR}:${PATH}
# Create the release tarball using (arbitrarily) the first host
- export GIT_DIR="$PWD/.git"
./autogen.sh
CONFIG_SITE=${BASEPREFIX}/`echo "${HOSTS}" | awk '{print $1;}'`/share/config.site ./configure --prefix=/
make dist
@@ -132,6 +131,9 @@ script: |
cp ../$SOURCEDIST $OUTDIR/src
popd
+ # Workaround for tarball not building with the bare tag version (prep)
+ make -C src obj/build.h
+
ORIGPATH="$PATH"
# Extract the release tarball into a dir for each host and build
for i in ${HOSTS}; do
@@ -142,6 +144,11 @@ script: |
mkdir -p ${INSTALLPATH}
tar --strip-components=1 -xf ../$SOURCEDIST
+ # Workaround for tarball not building with the bare tag version
+ echo '#!/bin/true' >share/genbuild.sh
+ mkdir src/obj
+ cp ../src/obj/build.h src/obj/
+
CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}"
make ${MAKEOPTS}
make ${MAKEOPTS} -C src check-security
diff --git a/contrib/gitian-keys/README.md b/contrib/gitian-keys/README.md
index 439910330d..4b0b7a2615 100644
--- a/contrib/gitian-keys/README.md
+++ b/contrib/gitian-keys/README.md
@@ -3,7 +3,7 @@ PGP keys
This folder contains the public keys of developers and active contributors.
-The keys are mainly used to sign git commits or the build results of gitian
+The keys are mainly used to sign git commits or the build results of Gitian
builds.
You can import the keys into gpg as follows. Also, make sure to fetch the
diff --git a/contrib/gitian-keys/meshcollider-key.pgp b/contrib/gitian-keys/meshcollider-key.pgp
new file mode 100644
index 0000000000..20963e7e25
--- /dev/null
+++ b/contrib/gitian-keys/meshcollider-key.pgp
@@ -0,0 +1,51 @@
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+mQINBFlm5UcBEADFhn2Tcfr7gtsLRj9dzHGPoZYjc8Jy7wceqT8918lqaULJKgDW
+vkEWCVOHRlrr/h1ugldouTRv3k8cdzhCR9YBakVJ3vBmn73CvHQl57jGRSogyqm5
+hb6IXJkBdualnZVFvCDV37VYeyuSYkJ+DL3c2wEjC2gdQKUsc8ePrJZZEMJVScdD
+hoXR/sPnu8P5yHOi56XGJi9395GUmmxJKNucD4HXjSq+7yTTs5GXm4niaKfcKyBy
+kIGN4aEeV8sqzkN8JzNH9fc8i8MPDYLW7SGljpLSnIvIsdBRjXXBHwRnfmGEO7lF
+sVTyepUUYX3GhLcCNhZjoMkpagVjSpQPj1gylSM4EFkmU2AgK/iEzqB7Ay4WC8EE
+E2HrcN0ysjyhuyntFwMa1cze99vtfOIQnVJ8E58AvsOs9+xYz8DkbYntCHDD+Zcv
+y200/knT1jJSZMXkiDciLjGSeFFbh6H+VpaFUKjy3G3yJC4BTXwnACga5/WPsgmK
++Y9gpTXRsZ8Op2teiwl8wI85mNF+2QmQw3uvymfojI8YPmjx2LOCbzkFYIJt20nw
+iP1QMH3vtk+iSbcnexQlOPh03ZtDp3NbkBvBOy7cOc57Nc6IX7TllZicQj0FUjWq
+ctUAU+f5pQuVgS8H3B4XE+Pk1u6/5zX9H0sTi0LzeQ0OdWFcvmZ8mYK5lQARAQAB
+tCNNZXNoQ29sbGlkZXIgPGRvYnNvbnNhNjhAZ21haWwuY29tPokCOAQTAQgALAUC
+WWblRwkQ0wARbhyHWj0CGwMFCR4TOAACGQEECwcJAwUVCAoCAwQWAAECAABJ2Q/8
+D6FMutVLsz55vwy2FjWojcvSpk+BV50YMGYTCdnXZod7V0dP1iQ5+NMcYfpWgJKM
+YbJ2eaWpW2TgsBd12LTjA6BKX3FquN8Y3nKZiknGCLiimDiys0+VuO9ieEH0flhC
+olhGysRmPO5clNmZOzn3yiPgUekw6ejLVUEY8vPCbjojSuLZyjctQR3s/9oOMyvm
+tldJ0waLi3KSOPEDQ8gXfE0QfDf2eMTdlMkbOHS6BlDIre6P5RZ5IJaLwCdzne+W
+aS96CUqVcR3aqil4mG+T+kHf1wF99TZwY+tSXtweGENjc+QGEaR30to+catSc0nz
+KQi3dGCH2Y+rc4VHE1S2Id88M38883mHXUeDMqzV9mHwMA50r/jzcLPybrJA1Qhn
+ZQNWr8zGilmZfWnf2VyiPqZCIAEEFcwg6uNg9Rwy2N3Q/5+vhAVcVNJamMA/dpHa
+hnq8HmZjraPWHL5Q9oL3Ggtc1Jahb8skaUMV26PHkXOxNFhVynghw3ujC3mocKqQ
+stmsg+2m5Wf+TZtmbd8geMWcRpuxovYX2ZmeFPWIU+6p9XpwyiPR4mp5hWn/20dQ
+YAyN/cQhWjDRU2i/HJB1lVnQIsSVsy3eWUJk4htQNHmk8crYocsXb5hgQ2C+JZ0L
+gY2AxoGjqtzKkydTd5GbiCmqqFdW9ngmVerZ6yCbyRK5Ag0EWWblRwEQALdMSVUR
+fCXTW2zCiP7g0Aj6yvyi1Wg1zK0CeRRljXKfgFoAI6IGW9QSSpXPmdsnAQOf7L0Q
+wTTqwWNhKOLV0IWLenbpgIVwfLMkrwn71q9MBJFHiL+PgZLaRxqF5pmW34ZReUj5
+k55Bg49kB98rfyz9K6qNxKLzY0j/8zsCvCgDMpr7U61xfz8Xo3Ds8bRdaFoH3RWR
+wm3ePTe/8Rpm/LWWLlzhnfTpyZCUcOPh5+2yt0twHQ5zlzj7Gp8Il8XNlP6hvfx3
+QGDuFTQ++Utom7T3QLa5E5Yx2iTD7qaNLdpQLZmcHUvdQV0QWSILccEvSJ+vXiE0
+NvlgQIAE1pUuyTGpm97+mBeDC+4PvXUxQqFoOTJiwJxCpIAA0yvloUaZyeT0Toar
+mowVOn0JXfbZRFFdxNUXgz9RbzANB+twGJ/ySh3mQz+Mur/1HqnCpHEjy73yOA9e
+alN2LNvJt92hMdq+QU7I0bNqUS456h6Ft6mOpqG2y57qpl8ZL/MIvMaw3s45hA6p
+7gzi7/TOnoqAkDUPf7lRbYjGgLkcGlimRxyL1SAYKuFgpNnhxk6BNPKdly7MRWF5
+I+oUc5W7HkNefbHw5sdLgYZBQk8JoSwF1K/ES5gvJHWZjCiLAcbyum2W843etfU3
+Qa/3YNt4Gri5zhAoD7U2kAs1ct3hQ6cLmDrxABEBAAGJAjUEGAEIACkFAllm5UcJ
+ENMAEW4ch1o9AhsMBQkeEzgABAsHCQMFFQgKAgMEFgABAgAAWWcP/1ErBIqJ+SFZ
+bL3YyLB9iObLEAUxNQP8bEV6lI9V0XUBhReasxQrMUFEXsFoFU6i/qlyfQFsBN8J
+2QJFJT1pNE+Pleuz4yMuK5Ddcuuyl9ZklfEclmkLpSEwapFMm9IOgaGhucBMpvkC
+2FE05oc0dEyTCdt1rBppGXvx2aw1khSiuWU13bWXw4hWfJaYKDKdTQyJLsjKGe0u
+qjaR6yHWHbjlchQWKGUWLHomTKG6wZx9k5YbEy5LN7HnyCHos4SiWyaSpXSjCtNn
+15i0JdH68fpKAtaGtkUYtoEJIg8qg7u4B6wM70BK2WCZr8T5yWK0c7NrojMIYjEu
+HwEA9XPkcF9TF7V1VOZMze1ZOWSNzGOfq1yJf6hpUNrw+B3TbYsqJkuJmVSYoamH
+0QBy0sHxlUtsALMnuKIQt8Sp20bJZLwpudXF+ZSRwrjmYc2RMc5AWaBHTGz2IGte
+AvH+SOOaRWj+UvhSFZVKVOZHWqErzKG+NfqQzEaEL4h/6QU64h5GLhocYHCiCbFm
+X1t01eKoDfOhwQlSlPjpDxxr7yi60ntt1R7DpgwqMNIdyXylxsc4SCvM6NDRXVM1
+DoaPHI7GRuT1w6zEtkCGQoGsy1OBrnjeIy40mzh8L5q8L7n3jNtN/d6YCYDzP/P6
+gb52/WPhR6CJQ2/7y3Uj7u8sPNpb7BGI
+=as33
+-----END PGP PUBLIC KEY BLOCK-----
diff --git a/contrib/init/bitcoind.conf b/contrib/init/bitcoind.conf
index f9554eecde..de4ea0ed52 100644
--- a/contrib/init/bitcoind.conf
+++ b/contrib/init/bitcoind.conf
@@ -30,12 +30,12 @@ pre-start script
echo
echo "This password is security critical to securing wallets "
echo "and must not be the same as the rpcuser setting."
- echo "You can generate a suitable random password using the following"
+ echo "You can generate a suitable random password using the following "
echo "command from the shell:"
echo
echo "bash -c 'tr -dc a-zA-Z0-9 < /dev/urandom | head -c32 && echo'"
echo
- echo "It is also recommended that you also set alertnotify so you are "
+ echo "It is recommended that you also set alertnotify so you are "
echo "notified of problems:"
echo
echo "ie: alertnotify=echo %%s | mail -s \"Bitcoin Alert\"" \
diff --git a/contrib/init/bitcoind.openrc b/contrib/init/bitcoind.openrc
index eda1a96fb4..50377c0995 100644
--- a/contrib/init/bitcoind.openrc
+++ b/contrib/init/bitcoind.openrc
@@ -76,12 +76,12 @@ checkconfig()
eerror ""
eerror "This password is security critical to securing wallets "
eerror "and must not be the same as the rpcuser setting."
- eerror "You can generate a suitable random password using the following"
+ eerror "You can generate a suitable random password using the following "
eerror "command from the shell:"
eerror ""
eerror "bash -c 'tr -dc a-zA-Z0-9 < /dev/urandom | head -c32 && echo'"
eerror ""
- eerror "It is also recommended that you also set alertnotify so you are "
+ eerror "It is recommended that you also set alertnotify so you are "
eerror "notified of problems:"
eerror ""
eerror "ie: alertnotify=echo %%s | mail -s \"Bitcoin Alert\"" \
diff --git a/contrib/linearize/README.md b/contrib/linearize/README.md
index f2a2ab2768..2985106982 100644
--- a/contrib/linearize/README.md
+++ b/contrib/linearize/README.md
@@ -46,7 +46,7 @@ linearize-hashes.py.
(Default: `1000*1000*1000 bytes`)
* `netmagic`: Network magic number.
* `out_of_order_cache_sz`: If out-of-order blocks are being read, the block can
-be written to a cache so that the blockchain doesn't have to be seeked again.
+be written to a cache so that the blockchain doesn't have to be sought again.
This option specifies the cache size. (Default: `100*1000*1000 bytes`)
* `rev_hash_bytes`: If true, the block hash list written by linearize-hashes.py
will be byte-reversed when read by linearize-data.py. See the linearize-hashes
diff --git a/contrib/linearize/linearize-hashes.py b/contrib/linearize/linearize-hashes.py
index db8eb7021e..58fec6dddc 100755
--- a/contrib/linearize/linearize-hashes.py
+++ b/contrib/linearize/linearize-hashes.py
@@ -87,7 +87,7 @@ def get_block_hashes(settings, max_blocks_per_call=10000):
for x,resp_obj in enumerate(reply):
if rpc.response_is_error(resp_obj):
print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)
- exit(1)
+ sys.exit(1)
assert(resp_obj['id'] == x) # assume replies are in-sequence
if settings['rev_hash_bytes'] == 'true':
resp_obj['result'] = hex_switchEndian(resp_obj['result'])
@@ -140,7 +140,7 @@ if __name__ == '__main__':
if 'datadir' in settings and not use_userpass:
use_datadir = True
if not use_userpass and not use_datadir:
- print("Missing datadir or username and/or password in cfg file", file=stderr)
+ print("Missing datadir or username and/or password in cfg file", file=sys.stderr)
sys.exit(1)
settings['port'] = int(settings['port'])
diff --git a/contrib/rpm/README.md b/contrib/rpm/README.md
index 4ab2f35680..e1e0745fd6 100644
--- a/contrib/rpm/README.md
+++ b/contrib/rpm/README.md
@@ -84,16 +84,16 @@ If you would prefer not to build the GUI at all, you can pass the switch
The desktop and KDE meta files are created in the spec file itself with the
`cat` command. This is done to allow easy distribution specific changes without
-needing to use any patches. A specific time stamp is given to the files so that
+needing to use any patches. A specific timestamp is given to the files so that
it does not they do not appear to have been updated every time the package is
-built. If you do make changes to them, you probably should update time stamp
-assigned to them in the `touch` command that specifies the time stamp.
+built. If you do make changes to them, you probably should update timestamp
+assigned to them in the `touch` command that specifies the timestamp.
## SVG, PNG, and XPM Icons
The `bitcoin.svg` file is from the source listed as `Source100`. It is used as
the source for the PNG and XPM files. The generated PNG and XPM files are given
-the same time stamp as the source SVG file as a means of indicating they are
+the same timestamp as the source SVG file as a means of indicating they are
derived from it.
## Systemd
@@ -105,10 +105,10 @@ distributions that still receive vendor updates do in fact use systemd.
The files to control the service are created in the RPM spec file itself using
the `cat` command. This is done to make it easy to modify for other
distributions that may implement things differently without needing to patch
-source. A specific time stamp is given to the files so that they do not appear
+source. A specific timestamp is given to the files so that they do not appear
to have been updated every time the package is built. If you do make changes to
-them, you probably should update the time stamp assigned to them in the `touch`
-command that specifies the time stamp.
+them, you probably should update the timestamp assigned to them in the `touch`
+command that specifies the timestamp.
## SELinux
diff --git a/contrib/seeds/generate-seeds.py b/contrib/seeds/generate-seeds.py
index b0ac92ae03..28068a7523 100755
--- a/contrib/seeds/generate-seeds.py
+++ b/contrib/seeds/generate-seeds.py
@@ -114,7 +114,7 @@ def process_nodes(g, f, structname, defaultport):
def main():
if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
- exit(1)
+ sys.exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n')
diff --git a/contrib/zmq/zmq_sub.py b/contrib/zmq/zmq_sub.py
index ea398a27ea..5cc19761d4 100755
--- a/contrib/zmq/zmq_sub.py
+++ b/contrib/zmq/zmq_sub.py
@@ -32,7 +32,7 @@ import sys
if not (sys.version_info.major >= 3 and sys.version_info.minor >= 5):
print("This example only works with Python 3.5 and greater")
- exit(1)
+ sys.exit(1)
port = 28332
diff --git a/contrib/zmq/zmq_sub3.4.py b/contrib/zmq/zmq_sub3.4.py
index 1cb7eec0c0..bfb7ea9eae 100755
--- a/contrib/zmq/zmq_sub3.4.py
+++ b/contrib/zmq/zmq_sub3.4.py
@@ -36,7 +36,7 @@ import sys
if not (sys.version_info.major >= 3 and sys.version_info.minor >= 4):
print("This example only works with Python 3.4 and greater")
- exit(1)
+ sys.exit(1)
port = 28332
diff --git a/doc/REST-interface.md b/doc/REST-interface.md
index caf6782886..7a17c175bd 100644
--- a/doc/REST-interface.md
+++ b/doc/REST-interface.md
@@ -8,14 +8,14 @@ The interface runs on the same port as the JSON-RPC interface, by default port 8
Supported API
-------------
-####Transactions
+#### Transactions
`GET /rest/tx/<TX-HASH>.<bin|hex|json>`
Given a transaction hash: returns a transaction in binary, hex-encoded binary, or JSON formats.
For full TX query capability, one must enable the transaction index via "txindex=1" command line / configuration option.
-####Blocks
+#### Blocks
`GET /rest/block/<BLOCK-HASH>.<bin|hex|json>`
`GET /rest/block/notxdetails/<BLOCK-HASH>.<bin|hex|json>`
@@ -25,12 +25,12 @@ The HTTP request and response are both handled entirely in-memory, thus making m
With the /notxdetails/ option JSON response will only contain the transaction hash instead of the complete transaction details. The option only affects the JSON response.
-####Blockheaders
+#### Blockheaders
`GET /rest/headers/<COUNT>/<BLOCK-HASH>.<bin|hex|json>`
Given a block hash: returns <COUNT> amount of blockheaders in upward direction.
-####Chaininfos
+#### Chaininfos
`GET /rest/chaininfo.json`
Returns various state info regarding block chain processing.
@@ -48,7 +48,7 @@ Only supports JSON as output format.
* softforks : (array) status of softforks in progress
* bip9_softforks : (object) status of BIP9 softforks in progress
-####Query UTXO set
+#### Query UTXO set
`GET /rest/getutxos/<checkmempool>/<txid>-<n>/<txid>-<n>/.../<txid>-<n>.<bin|hex|json>`
The getutxo command allows querying of the UTXO set given a set of outpoints.
@@ -81,7 +81,7 @@ $ curl localhost:18332/rest/getutxos/checkmempool/b2cdfd7b89def827ff8af7cd9bff76
}
```
-####Memory pool
+#### Memory pool
`GET /rest/mempool/info.json`
Returns various information about the TX mempool.
diff --git a/doc/build-openbsd.md b/doc/build-openbsd.md
index f4a9826d80..cd800464b4 100644
--- a/doc/build-openbsd.md
+++ b/doc/build-openbsd.md
@@ -1,6 +1,6 @@
OpenBSD build guide
======================
-(updated for OpenBSD 6.0)
+(updated for OpenBSD 6.1)
This guide describes how to build bitcoind and command-line utilities on OpenBSD.
@@ -48,13 +48,13 @@ BOOST_PREFIX="${BITCOIN_ROOT}/boost"
mkdir -p $BOOST_PREFIX
# Fetch the source and verify that it is not tampered with
-curl -o boost_1_61_0.tar.bz2 http://heanet.dl.sourceforge.net/project/boost/boost/1.61.0/boost_1_61_0.tar.bz2
-echo 'a547bd06c2fd9a71ba1d169d9cf0339da7ebf4753849a8f7d6fdb8feee99b640 boost_1_61_0.tar.bz2' | sha256 -c
-# MUST output: (SHA256) boost_1_61_0.tar.bz2: OK
-tar -xjf boost_1_61_0.tar.bz2
+curl -o boost_1_64_0.tar.bz2 https://netcologne.dl.sourceforge.net/project/boost/boost/1.64.0/boost_1_64_0.tar.bz2
+echo '7bcc5caace97baa948931d712ea5f37038dbb1c5d89b43ad4def4ed7cb683332 boost_1_64_0.tar.bz2' | sha256 -c
+# MUST output: (SHA256) boost_1_64_0.tar.bz2: OK
+tar -xjf boost_1_64_0.tar.bz2
-# Boost 1.61 needs one small patch for OpenBSD
-cd boost_1_61_0
+# Boost 1.64 needs one small patch for OpenBSD
+cd boost_1_64_0
# Also here: https://gist.githubusercontent.com/laanwj/bf359281dc319b8ff2e1/raw/92250de8404b97bb99d72ab898f4a8cb35ae1ea3/patch-boost_test_impl_execution_monitor_ipp.patch
patch -p0 < /usr/ports/devel/boost/patches/patch-boost_test_impl_execution_monitor_ipp
diff --git a/doc/build-osx.md b/doc/build-osx.md
index 32d7dbd69e..1320d309c4 100644
--- a/doc/build-osx.md
+++ b/doc/build-osx.md
@@ -16,7 +16,7 @@ Then install [Homebrew](https://brew.sh).
Dependencies
----------------------
- brew install automake berkeley-db4 libtool boost --c++11 miniupnpc openssl pkg-config protobuf qt libevent
+ brew install automake berkeley-db4 libtool boost --c++11 miniupnpc openssl pkg-config protobuf python3 qt libevent
If you want to build the disk image with `make deploy` (.dmg / optional), you need RSVG
diff --git a/doc/build-unix.md b/doc/build-unix.md
index b7eae2a630..2e82934cd1 100644
--- a/doc/build-unix.md
+++ b/doc/build-unix.md
@@ -65,7 +65,7 @@ Dependency Build Instructions: Ubuntu & Debian
----------------------------------------------
Build requirements:
- sudo apt-get install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils
+ sudo apt-get install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils python3
Options when installing required Boost library files:
@@ -131,7 +131,7 @@ Dependency Build Instructions: Fedora
-------------------------------------
Build requirements:
- sudo dnf install gcc-c++ libtool make autoconf automake openssl-devel libevent-devel boost-devel libdb4-devel libdb4-cxx-devel
+ sudo dnf install gcc-c++ libtool make autoconf automake openssl-devel libevent-devel boost-devel libdb4-devel libdb4-cxx-devel python3
Optional:
diff --git a/doc/build-windows.md b/doc/build-windows.md
index 9549a4b9da..ca1a05dfb4 100644
--- a/doc/build-windows.md
+++ b/doc/build-windows.md
@@ -6,6 +6,9 @@ Below are some notes on how to build Bitcoin Core for Windows.
Most developers use cross-compilation from Ubuntu to build executables for
Windows. This is also used to build the release binaries.
+Currently only building on Ubuntu Trusty 14.04 is supported.
+Other versions are unsupported or known to be broken (e.g. Ubuntu Xenial 16.04).
+
While there are potentially a number of ways to build on Windows (for example using msys / mingw-w64),
using the Windows Subsystem For Linux is the most straightforward. If you are building with
another method, please contribute the instructions here for others who are running versions
diff --git a/doc/developer-notes.md b/doc/developer-notes.md
index d783a7a8ae..2f04d6ee6c 100644
--- a/doc/developer-notes.md
+++ b/doc/developer-notes.md
@@ -4,7 +4,7 @@ Developer Notes
Various coding styles have been used during the history of the codebase,
and the result is not very consistent. However, we're now trying to converge to
a single style, which is specified below. When writing patches, favor the new
-style over attempting to mimick the surrounding style, except for move-only
+style over attempting to mimic the surrounding style, except for move-only
commits.
Do not submit patches solely to modify the style of existing code.
@@ -37,6 +37,8 @@ code.
- **Miscellaneous**
- `++i` is preferred over `i++`.
+ - `nullptr` is preferred over `NULL` or `(void*)0`.
+ - `static_assert` is preferred over `assert` where possible. Generally; compile-time checking is preferred over run-time checking.
Block style example:
```c++
@@ -275,7 +277,7 @@ Wallet
- *Rationale*: In RPC code that conditionally uses the wallet (such as
`validateaddress`) it is easy to forget that global pointer `pwalletMain`
- can be NULL. See `test/functional/disablewallet.py` for functional tests
+ can be nullptr. See `test/functional/disablewallet.py` for functional tests
exercising the API with `-disablewallet`
- Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
@@ -330,6 +332,12 @@ C++ data structures
- *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
values. Also, static analyzers balk about this.
+- By default, declare single-argument constructors `explicit`.
+
+ - *Rationale*: This is a precaution to avoid unintended conversions that might
+ arise when single-argument constructors are used as implicit conversion
+ functions.
+
- Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
`int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
This type can be signed or unsigned depending on the architecture, which can
@@ -570,16 +578,14 @@ A few guidelines for introducing and reviewing new RPC interfaces:
is specified as-is in BIP22.
- Missing arguments and 'null' should be treated the same: as default values. If there is no
- default value, both cases should fail in the same way.
+ default value, both cases should fail in the same way. The easiest way to follow this
+ guideline is detect unspecified arguments with `params[x].isNull()` instead of
+ `params.size() <= x`. The former returns true if the argument is either null or missing,
+ while the latter returns true if is missing, and false if it is null.
- *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments
are passed as 'null'.
- - *Exception*: Many legacy exceptions to this exist, one of the worst ones is
- `getbalance` which follows a completely different code path based on the
- number of arguments. We are still in the process of cleaning these up. Do not introduce
- new ones.
-
- Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")`
do different things.
diff --git a/doc/init.md b/doc/init.md
index e3db5b05ef..75f9013f29 100644
--- a/doc/init.md
+++ b/doc/init.md
@@ -10,14 +10,14 @@ can be found in the contrib/init folder.
contrib/init/bitcoind.conf: Upstart service configuration file
contrib/init/bitcoind.init: CentOS compatible SysV style init script
-1. Service User
+Service User
---------------------------------
All three Linux startup configurations assume the existence of a "bitcoin" user
and group. They must be created before attempting to use these scripts.
The OS X configuration assumes bitcoind will be set up for the current user.
-2. Configuration
+Configuration
---------------------------------
At a bare minimum, bitcoind requires that the rpcpassword setting be set
@@ -46,10 +46,10 @@ relative to the data directory. `wallet` *only* supports relative paths.
For an example configuration file that describes the configuration settings,
see `contrib/debian/examples/bitcoin.conf`.
-3. Paths
+Paths
---------------------------------
-3a) Linux
+### Linux
All three configurations assume several paths that might need to be adjusted.
@@ -65,17 +65,17 @@ reasons to make the configuration file and data directory only readable by the
bitcoin user and group. Access to bitcoin-cli and other bitcoind rpc clients
can then be controlled by group membership.
-3b) Mac OS X
+### Mac OS X
Binary: `/usr/local/bin/bitcoind`
Configuration file: `~/Library/Application Support/Bitcoin/bitcoin.conf`
-Data directory: `~/Library/Application Support/Bitcoin`
-Lock file: `~/Library/Application Support/Bitcoin/.lock`
+Data directory: `~/Library/Application Support/Bitcoin`
+Lock file: `~/Library/Application Support/Bitcoin/.lock`
-4. Installing Service Configuration
+Installing Service Configuration
-----------------------------------
-4a) systemd
+### systemd
Installing this .service file consists of just copying it to
/usr/lib/systemd/system directory, followed by the command
@@ -84,14 +84,14 @@ Installing this .service file consists of just copying it to
To test, run `systemctl start bitcoind` and to enable for system startup run
`systemctl enable bitcoind`
-4b) OpenRC
+### OpenRC
Rename bitcoind.openrc to bitcoind and drop it in /etc/init.d. Double
check ownership and permissions and make it executable. Test it with
`/etc/init.d/bitcoind start` and configure it to run on startup with
`rc-update add bitcoind`
-4c) Upstart (for Debian/Ubuntu based distributions)
+### Upstart (for Debian/Ubuntu based distributions)
Drop bitcoind.conf in /etc/init. Test by running `service bitcoind start`
it will automatically start on reboot.
@@ -99,7 +99,7 @@ it will automatically start on reboot.
NOTE: This script is incompatible with CentOS 5 and Amazon Linux 2014 as they
use old versions of Upstart and do not supply the start-stop-daemon utility.
-4d) CentOS
+### CentOS
Copy bitcoind.init to /etc/init.d/bitcoind. Test by running `service bitcoind start`.
@@ -107,7 +107,7 @@ Using this script, you can adjust the path and flags to the bitcoind program by
setting the BITCOIND and FLAGS environment variables in the file
/etc/sysconfig/bitcoind. You can also use the DAEMONOPTS environment variable here.
-4e) Mac OS X
+### Mac OS X
Copy org.bitcoin.bitcoind.plist into ~/Library/LaunchAgents. Load the launch agent by
running `launchctl load ~/Library/LaunchAgents/org.bitcoin.bitcoind.plist`.
@@ -118,7 +118,7 @@ NOTE: This approach is intended for those wanting to run bitcoind as the current
You will need to modify org.bitcoin.bitcoind.plist if you intend to use it as a
Launch Daemon with a dedicated bitcoin user.
-5. Auto-respawn
+Auto-respawn
-----------------------------------
Auto respawning is currently only configured for Upstart and systemd.
diff --git a/doc/release-notes.md b/doc/release-notes.md
index 9398a3f8c2..aa1d1bea14 100644
--- a/doc/release-notes.md
+++ b/doc/release-notes.md
@@ -1,9 +1,9 @@
(note: this is a temporary file, to be added-to by anybody, and moved to
release-notes at release time)
-Bitcoin Core version *0.15.0* is now available from:
+Bitcoin Core version *version* is now available from:
- <https://bitcoin.org/bin/bitcoin-core-0.15.0/>
+ <https://bitcoin.org/bin/bitcoin-core-*version*/>
This is a new major version release, including new features, various bugfixes
and performance improvements, as well as updated translations.
@@ -56,332 +56,10 @@ frequently tested on them.
Notable changes
===============
-Performance Improvements
-------------------------
-
-Version 0.15 contains a number of significant performance improvements, which make
-Initial Block Download, startup, transaction and block validation much faster:
-
-- The chainstate database (which is used for tracking UTXOs) has been changed
- from a per-transaction model to a per-output model (See [PR 10195](https://github.com/bitcoin/bitcoin/pull/10195)). Advantages of this model
- are that it:
- - avoids the CPU overhead of deserializing and serializing the unused outputs;
- - has more predictable memory usage;
- - uses simpler code;
- - is adaptable to various future cache flushing strategies.
-
- As a result, validating the blockchain during Initial Block Download (IBD) and reindex
- is ~30-40% faster, uses 10-20% less memory, and flushes to disk far less frequently.
- The only downside is that the on-disk database is 15% larger. During the conversion from the previous format
- a few extra gigabytes may be used.
-- Earlier versions experienced a spike in memory usage while flushing UTXO updates to disk.
- As a result, only half of the available memory was actually used as cache, and the other half was
- reserved to accommodate flushing. This is no longer the case (See [PR 10148](https://github.com/bitcoin/bitcoin/pull/10148)), and the entirety of
- the available cache (see `-dbcache`) is now actually used as cache. This reduces the flushing
- frequency by a factor 2 or more.
-- In previous versions, signature validation for transactions has been cached when the
- transaction is accepted to the mempool. Version 0.15 extends this to cache the entire script
- validity (See [PR 10192](https://github.com/bitcoin/bitcoin/pull/10192)). This means that if a transaction in a block has already been accepted to the
- mempool, the scriptSig does not need to be re-evaluated. Empirical tests show that
- this results in new block validation being 40-50% faster.
-- LevelDB has been upgraded to version 1.20 (See [PR 10544](https://github.com/bitcoin/bitcoin/pull/10544)). This version contains hardware acceleration for CRC
- on architectures supporting SSE 4.2. As a result, synchronization and block validation are now faster.
-- SHA256 hashing has been optimized for architectures supporting SSE 4 (See [PR 10182](https://github.com/bitcoin/bitcoin/pull/10182)). SHA256 is around
- 50% faster on supported hardware, which results in around 5% faster IBD and block
- validation. In version 0.15, SHA256 hardware optimization is disabled in release builds by
- default, but can be enabled by using `--enable-experimental-asm` when building.
-- Refill of the keypool no longer flushes the wallet between each key which resulted in a ~20x speedup in creating a new wallet. Part of this speedup was used to increase the default keypool to 1000 keys to make recovery more robust. (See [PR 10831](https://github.com/bitcoin/bitcoin/pull/10831)).
-
-Fee Estimation Improvements
----------------------------
-
-Fee estimation has been significantly improved in version 0.15, with more accurate fee estimates used by the wallet and a wider range of options for advanced users of the `estimatesmartfee` and `estimaterawfee` RPCs (See [PR 10199](https://github.com/bitcoin/bitcoin/pull/10199)).
-
-### Changes to internal logic and wallet behavior
-
-- Internally, estimates are now tracked on 3 different time horizons. This allows for longer targets and means estimates adjust more quickly to changes in conditions.
-- Estimates can now be *conservative* or *economical*. *Conservative* estimates use longer time horizons to produce an estimate which is less susceptible to rapid changes in fee conditions. *Economical* estimates use shorter time horizons and will be more affected by short-term changes in fee conditions. Economical estimates may be considerably lower during periods of low transaction activity (for example over weekends), but may result in transactions being unconfirmed if prevailing fees increase rapidly.
-- By default, the wallet will use conservative fee estimates to increase the reliability of transactions being confirmed within the desired target. For transactions that are marked as replaceable, the wallet will use an economical estimate by default, since the fee can be 'bumped' if the fee conditions change rapidly (See [PR 10589](https://github.com/bitcoin/bitcoin/pull/10589)).
-- Estimates can now be made for confirmation targets up to 1008 blocks (one week).
-- More data on historical fee rates is stored, leading to more precise fee estimates.
-- Transactions which leave the mempool due to eviction or other non-confirmed reasons are now taken into account by the fee estimation logic, leading to more accurate fee estimates.
-- The fee estimation logic will make sure enough data has been gathered to return a meaningful estimate. If there is insufficient data, a fallback default fee is used.
-
-### Changes to fee estimate RPCs
-
-- The `estimatefee` RPC is now deprecated in favor of using only `estimatesmartfee` (which is the implementation used by the GUI)
-- The `estimatesmartfee` RPC interface has been changed (See [PR 10707](https://github.com/bitcoin/bitcoin/pull/10707)):
- - The `nblocks` argument has been renamed to `conf_target` (to be consistent with other RPC methods).
- - An `estimate_mode` argument has been added. This argument takes one of the following strings: `CONSERVATIVE`, `ECONOMICAL` or `UNSET` (which defaults to `CONSERVATIVE`).
- - The RPC return object now contains an `errors` member, which returns errors encountered during processing.
- - If Bitcoin Core has not been running for long enough and has not seen enough blocks or transactions to produce an accurate fee estimation, an error will be returned (previously a value of -1 was used to indicate an error, which could be confused for a feerate).
-- A new `estimaterawfee` RPC is added to provide raw fee data. External clients can query and use this data in their own fee estimation logic.
-
-Multi-wallet support
---------------------
-
-Bitcoin Core now supports loading multiple, separate wallets (See [PR 8694](https://github.com/bitcoin/bitcoin/pull/8694), [PR 10849](https://github.com/bitcoin/bitcoin/pull/10849)). The wallets are completely separated, with individual balances, keys and received transactions.
-
-Multi-wallet is enabled by using more than one `-wallet` argument when starting Bitcoin, either on the command line or in the Bitcoin config file.
-
-**In Bitcoin-Qt, only the first wallet will be displayed and accessible for creating and signing transactions.** GUI selectable multiple wallets will be supported in a future version. However, even in 0.15 other loaded wallets will continue to remain synchronized to the node's current tip in the background. This can be useful if running a pruned node, since loading a wallet where the most recent sync is beyond the pruned height results in having to download and revalidate the whole blockchain. Continuing to synchronize all wallets in the background avoids this problem.
-
-Bitcoin Core 0.15.0 contains the following changes to the RPC interface and `bitcoin-cli` for multi-wallet:
-
-* When running Bitcoin Core with a single wallet, there are **no** changes to the RPC interface or `bitcoin-cli`. All RPC calls and `bitcoin-cli` commands continue to work as before.
-* When running Bitcoin Core with multi-wallet, all *node-level* RPC methods continue to work as before. HTTP RPC requests should be send to the normal `<RPC IP address>:<RPC port>/` endpoint, and `bitcoin-cli` commands should be run as before. A *node-level* RPC method is any method which does not require access to the wallet.
-* When running Bitcoin Core with multi-wallet, *wallet-level* RPC methods must specify the wallet for which they're intended in every request. HTTP RPC requests should be send to the `<RPC IP address>:<RPC port>/wallet/<wallet name>/` endpoint, for example `127.0.0.1:8332/wallet/wallet1.dat/`. `bitcoin-cli` commands should be run with a `-rpcwallet` option, for example `bitcoin-cli -rpcwallet=wallet1.dat getbalance`.
-* A new *node-level* `listwallets` RPC method is added to display which wallets are currently loaded. The names returned by this method are the same as those used in the HTTP endpoint and for the `rpcwallet` argument.
-
-Note that while multi-wallet is now fully supported, the RPC multi-wallet interface should be considered unstable for version 0.15.0, and there may backwards-incompatible changes in future versions.
-
-Replace-by-fee control in the GUI
----------------------------------
-
-Bitcoin Core has supported creating opt-in replace-by-fee (RBF) transactions
-since version 0.12.0, and since version 0.14.0 has included a `bumpfee` RPC method to
-replace unconfirmed opt-in RBF transactions with a new transaction that pays
-a higher fee.
-
-In version 0.15, creating an opt-in RBF transaction and replacing the unconfirmed
-transaction with a higher-fee transaction are both supported in the GUI (See [PR 9592](https://github.com/bitcoin/bitcoin/pull/9592)).
-
-Removal of Coin Age Priority
-----------------------------
-
-In previous versions of Bitcoin Core, a portion of each block could be reserved for transactions based on the age and value of UTXOs they spent. This concept (Coin Age Priority) is a policy choice by miners, and there are no consensus rules around the inclusion of Coin Age Priority transactions in blocks. In practice, only a few miners continue to use Coin Age Priority for transaction selection in blocks. Bitcoin Core 0.15 removes all remaining support for Coin Age Priority (See [PR 9602](https://github.com/bitcoin/bitcoin/pull/9602)). This has the following implications:
-
-- The concept of *free transactions* has been removed. High Coin Age Priority transactions would previously be allowed to be relayed even if they didn't attach a miner fee. This is no longer possible since there is no concept of Coin Age Priority. The `-limitfreerelay` and `-relaypriority` options which controlled relay of free transactions have therefore been removed.
-- The `-sendfreetransactions` option has been removed, since almost all miners do not include transactions which do not attach a transaction fee.
-- The `-blockprioritysize` option has been removed.
-- The `estimatepriority` and `estimatesmartpriority` RPCs have been removed.
-- The `getmempoolancestors`, `getmempooldescendants`, `getmempooolentry` and `getrawmempool` RPCs no longer return `startingpriority` and `currentpriority`.
-- The `prioritisetransaction` RPC no longer takes a `priority_delta` argument, which is replaced by a `dummy` argument for backwards compatibility with clients using positional arguments. The RPC is still used to change the apparent fee-rate of the transaction by using the `fee_delta` argument.
-- `-minrelaytxfee` can now be set to 0. If `minrelaytxfee` is set, then fees smaller than `minrelaytxfee` (per kB) are rejected from relaying, mining and transaction creation. This defaults to 1000 satoshi/kB.
-- The `-printpriority` option has been updated to only output the fee rate and hash of transactions included in a block by the mining code.
-
-Mempool Persistence Across Restarts
------------------------------------
-
-Version 0.14 introduced mempool persistence across restarts (the mempool is saved to a `mempool.dat` file in the data directory prior to shutdown and restores the mempool when the node is restarted). Version 0.15 allows this feature to be switched on or off using the `-persistmempool` command-line option (See [PR 9966](https://github.com/bitcoin/bitcoin/pull/9966)). By default, the option is set to true, and the mempool is saved on shutdown and reloaded on startup. If set to false, the `mempool.dat` file will not be loaded on startup or saved on shutdown.
-
-New RPC methods
----------------
-
-Version 0.15 introduces several new RPC methods:
-
-- `abortrescan` stops current wallet rescan, e.g. when triggered by an `importprivkey` call (See [PR 10208](https://github.com/bitcoin/bitcoin/pull/10208)).
-- `combinerawtransaction` accepts a JSON array of raw transactions and combines them into a single raw transaction (See [PR 10571](https://github.com/bitcoin/bitcoin/pull/10571)).
-- `estimaterawfee` returns raw fee data so that customized logic can be implemented to analyze the data and calculate estimates. See [Fee Estimation Improvements](#fee-estimation-improvements) for full details on changes to the fee estimation logic and interface.
-- `getchaintxstats` returns statistics about the total number and rate of transactions
- in the chain (See [PR 9733](https://github.com/bitcoin/bitcoin/pull/9733)).
-- `listwallets` lists wallets which are currently loaded. See the *Multi-wallet* section
- of these release notes for full details (See [Multi-wallet support](#multi-wallet-support)).
-- `uptime` returns the total runtime of the `bitcoind` server since its last start (See [PR 10400](https://github.com/bitcoin/bitcoin/pull/10400)).
-
-Low-level RPC changes
----------------------
-
-- When using Bitcoin Core in multi-wallet mode, RPC requests for wallet methods must specify
- the wallet that they're intended for. See [Multi-wallet support](#multi-wallet-support) for full details.
-
-- The new database model no longer stores information about transaction
- versions of unspent outputs (See [Performance improvements](#performance-improvements)). This means that:
- - The `gettxout` RPC no longer has a `version` field in the response.
- - The `gettxoutsetinfo` RPC reports `hash_serialized_2` instead of `hash_serialized`,
- which does not commit to the transaction versions of unspent outputs, but does
- commit to the height and coinbase information.
- - The `getutxos` REST path no longer reports the `txvers` field in JSON format,
- and always reports 0 for transaction versions in the binary format
-
-- The `estimatefee` RPC is deprecated. Clients should switch to using the `estimatesmartfee` RPC, which returns better fee estimates. See [Fee Estimation Improvements](#fee-estimation-improvements) for full details on changes to the fee estimation logic and interface.
-
-- The `gettxoutsetinfo` response now contains `disk_size` and `bogosize` instead of
- `bytes_serialized`. The first is a more accurate estimate of actual disk usage, but
- is not deterministic. The second is unrelated to disk usage, but is a
- database-independent metric of UTXO set size: it counts every UTXO entry as 50 + the
- length of its scriptPubKey (See [PR 10426](https://github.com/bitcoin/bitcoin/pull/10426)).
-
-- `signrawtransaction` can no longer be used to combine multiple transactions into a single transaction. Instead, use the new `combinerawtransaction` RPC (See [PR 10571](https://github.com/bitcoin/bitcoin/pull/10571)).
-
-- `fundrawtransaction` no longer accepts a `reserveChangeKey` option. This option used to allow RPC users to fund a raw transaction using an key from the keypool for the change address without removing it from the available keys in the keypool. The key could then be re-used for a `getnewaddress` call, which could potentially result in confusing or dangerous behaviour (See [PR 10784](https://github.com/bitcoin/bitcoin/pull/10784)).
-
-- `estimatepriority` and `estimatesmartpriority` have been removed. See [Removal of Coin Age Priority](#removal-of-coin-age-priority).
-
-- The `listunspent` RPC now takes a `query_options` argument (see [PR 8952](https://github.com/bitcoin/bitcoin/pull/8952)), which is a JSON object
- containing one or more of the following members:
- - `minimumAmount` - a number specifying the minimum value of each UTXO
- - `maximumAmount` - a number specifying the maximum value of each UTXO
- - `maximumCount` - a number specifying the minimum number of UTXOs
- - `minimumSumAmount` - a number specifying the minimum sum value of all UTXOs
-
-- The `getmempoolancestors`, `getmempooldescendants`, `getmempooolentry` and `getrawmempool` RPCs no longer return `startingpriority` and `currentpriority`. See [Removal of Coin Age Priority](#removal-of-coin-age-priority).
-
-- The `dumpwallet` RPC now returns the full absolute path to the dumped wallet. (it
- used to return no value, even if successful (See [PR 9740](https://github.com/bitcoin/bitcoin/pull/9740)).
-
-- In the `getpeerinfo` RPC, the return object for each peer now returns an `addrbind` member, which contains the ip address and port of the connection to the peer. This is in addition to the `addrlocal` member which contains the ip address and port of the local node as reported by the peer (See [PR 10478](https://github.com/bitcoin/bitcoin/pull/10478)).
-
-- The `disconnectnode` RPC can now disconnect a node specified by node ID (as well as by IP address/port). To disconnect a node based on node ID, call the RPC with the new `nodeid` argument (See [PR 10143](https://github.com/bitcoin/bitcoin/pull/10143)).
-
-- The second argument in `prioritisetransaction` has been renamed from `priority_delta` to `dummy` since Bitcoin Core no longer has a concept of coin age priority. The `dummy` argument has no functional effect, but is retained for positional argument compatibility. See [Removal of Coin Age Priority](#removal-of-coin-age-priority).
-
-- The `resendwallettransactions` RPC throws an error if the `-walletbroadcast` option is set to false (See [PR 10995](https://github.com/bitcoin/bitcoin/pull/10995)).
-
-- The second argument in the `submitblock` RPC argument has been renamed from `parameters` to `dummy`. This argument never had any effect, and the renaming is simply to communicate this fact to the user (See [PR 10191](https://github.com/bitcoin/bitcoin/pull/10191))
- (Clients should, however, use positional arguments for `submitblock` in order to be compatible with BIP 22.)
-
-- The `verbose` argument of `getblock` has been renamed to `verbosity` and now takes an integer from 0-2. Verbose level 0 is equivalent to `verbose=false`. Verbose level 1 is equivalent to `verbose=true`. Verbose level 2 will give the full transaction details of each transaction in the output as given by `getrawtransaction`. The old behavior of using the `verbose` named argument and a boolean value is still maintained for compatibility.
-
-- Error codes have been updated to be more accurate for the following error cases (See [PR 9853](https://github.com/bitcoin/bitcoin/pull/9853)):
- - `getblock` now returns RPC_MISC_ERROR if the block can't be found on disk (for
- example if the block has been pruned). Previously returned RPC_INTERNAL_ERROR.
- - `pruneblockchain` now returns RPC_MISC_ERROR if the blocks cannot be pruned
- because the node is not in pruned mode. Previously returned RPC_METHOD_NOT_FOUND.
- - `pruneblockchain` now returns RPC_INVALID_PARAMETER if the blocks cannot be pruned
- because the supplied timestamp is too late. Previously returned RPC_INTERNAL_ERROR.
- - `pruneblockchain` now returns RPC_MISC_ERROR if the blocks cannot be pruned
- because the blockchain is too short. Previously returned RPC_INTERNAL_ERROR.
- - `setban` now returns RPC_CLIENT_INVALID_IP_OR_SUBNET if the supplied IP address
- or subnet is invalid. Previously returned RPC_CLIENT_NODE_ALREADY_ADDED.
- - `setban` now returns RPC_CLIENT_INVALID_IP_OR_SUBNET if the user tries to unban
- a node that has not previously been banned. Previously returned RPC_MISC_ERROR.
- - `removeprunedfunds` now returns RPC_WALLET_ERROR if `bitcoind` is unable to remove
- the transaction. Previously returned RPC_INTERNAL_ERROR.
- - `removeprunedfunds` now returns RPC_INVALID_PARAMETER if the transaction does not
- exist in the wallet. Previously returned RPC_INTERNAL_ERROR.
- - `fundrawtransaction` now returns RPC_INVALID_ADDRESS_OR_KEY if an invalid change
- address is provided. Previously returned RPC_INVALID_PARAMETER.
- - `fundrawtransaction` now returns RPC_WALLET_ERROR if `bitcoind` is unable to create
- the transaction. The error message provides further details. Previously returned
- RPC_INTERNAL_ERROR.
- - `bumpfee` now returns RPC_INVALID_PARAMETER if the provided transaction has
- descendants in the wallet. Previously returned RPC_MISC_ERROR.
- - `bumpfee` now returns RPC_INVALID_PARAMETER if the provided transaction has
- descendants in the mempool. Previously returned RPC_MISC_ERROR.
- - `bumpfee` now returns RPC_WALLET_ERROR if the provided transaction has
- has been mined or conflicts with a mined transaction. Previously returned
- RPC_INVALID_ADDRESS_OR_KEY.
- - `bumpfee` now returns RPC_WALLET_ERROR if the provided transaction is not
- BIP 125 replaceable. Previously returned RPC_INVALID_ADDRESS_OR_KEY.
- - `bumpfee` now returns RPC_WALLET_ERROR if the provided transaction has already
- been bumped by a different transaction. Previously returned RPC_INVALID_REQUEST.
- - `bumpfee` now returns RPC_WALLET_ERROR if the provided transaction contains
- inputs which don't belong to this wallet. Previously returned RPC_INVALID_ADDRESS_OR_KEY.
- - `bumpfee` now returns RPC_WALLET_ERROR if the provided transaction has multiple change
- outputs. Previously returned RPC_MISC_ERROR.
- - `bumpfee` now returns RPC_WALLET_ERROR if the provided transaction has no change
- output. Previously returned RPC_MISC_ERROR.
- - `bumpfee` now returns RPC_WALLET_ERROR if the fee is too high. Previously returned
- RPC_MISC_ERROR.
- - `bumpfee` now returns RPC_WALLET_ERROR if the fee is too low. Previously returned
- RPC_MISC_ERROR.
- - `bumpfee` now returns RPC_WALLET_ERROR if the change output is too small to bump the
- fee. Previously returned RPC_MISC_ERROR.
-
Credits
=======
Thanks to everyone who directly contributed to this release:
-- ロハン ダル
-- Ahmad Kazi
-- aideca
-- Akio Nakamura
-- Alex Morcos
-- Allan Doensen
-- Andres G. Aragoneses
-- Andrew Chow
-- Awemany
-- Bob McElrath
-- Brian McMichael
-- BtcDrak
-- Charlie Lee
-- Chris Gavin
-- Chris Stewart
-- Cory Fields
-- CryptAxe
-- Dag Robole
-- Daniel Aleksandersen
-- Daniel Cousens
-- darksh1ne
-- Dimitris Tsapakidis
-- Eric Shaw Jr
-- Evan Klitzke
-- fanquake
-- Felix Weis
-- flack
-- Greg Griffith
-- Gregory Maxwell
-- Gregory Sanders
-- gubatron
-- Ian Kelling
-- Jack Grigg
-- James Evans
-- James Hilliard
-- Jameson Lopp
-- Jeremy Rubin
-- Jimmy Song
-- João Barbosa
-- Johnathan Corgan
-- John Newbery
-- Jonas Schnelli
-- jonnynewbs
-- Jorge Timón
-- Kalle Alm
-- Karl-Johan Alm
-- Kewde
-- keystrike
-- KibbledJiveElkZoo
-- Kibbled Jive Elk Zoo
-- kirit93
-- kobake
-- Kyle Honeycutt
-- Lawrence Nahum
-- Luke Dashjr
-- Marco Falke
-- Marcos Mayorga
-- Marijn Stollenga
-- Mario Dian
-- Mark Friedenbach
-- Marko Bencun
-- Masahiko Hyuga
-- Matt Corallo
-- Matthew Zipkin
-- Matthias Grundmann
-- Michael Goldstein
-- Michael Rotarius
-- Mikerah
-- Mike van Rossum
-- Mitchell Cash
-- NicolasDorier
-- Nicolas Dorier
-- Patrick Strateman
-- Pavel Janík
-- Pavlos Antoniou
-- Pavol Rusnak
-- Pedro Branco
-- Peter Todd
-- Pieter Wuille
-- practicalswift
-- René Nyffenegger
-- Ricardo Velhote
-- romanornr
-- Russell Yanofsky
-- Rusty Russell
-- Ryan Havar
-- shaolinfry
-- Shigeya Suzuki
-- Simone Madeo
-- Spencer Lievens
-- Steven D. Lander
-- Suhas Daftuar
-- Takashi Mitsuta
-- Thomas Snider
-- Timothy Redaelli
-- tintinweb
-- tnaka
-- Warren Togami
-- Wladimir J. van der Laan
As well as everyone that helped translating on [Transifex](https://www.transifex.com/projects/p/bitcoin/).
diff --git a/doc/zmq.md b/doc/zmq.md
index 1019ff6653..38c58fb7fd 100644
--- a/doc/zmq.md
+++ b/doc/zmq.md
@@ -72,7 +72,7 @@ For instance:
Each PUB notification has a topic and body, where the header
corresponds to the notification type. For instance, for the
notification `-zmqpubhashtx` the topic is `hashtx` (no null
-terminator) and the body is the hexadecimal transaction hash (32
+terminator) and the body is the transaction hash (32
bytes).
These options can also be provided in bitcoin.conf.
diff --git a/share/qt/extract_strings_qt.py b/share/qt/extract_strings_qt.py
index 5492fdb8c5..e3be18205d 100755
--- a/share/qt/extract_strings_qt.py
+++ b/share/qt/extract_strings_qt.py
@@ -58,7 +58,7 @@ XGETTEXT=os.getenv('XGETTEXT', 'xgettext')
if not XGETTEXT:
print('Cannot extract strings: xgettext utility is not installed or not configured.',file=sys.stderr)
print('Please install package "gettext" and re-run \'./configure\'.',file=sys.stderr)
- exit(1)
+ sys.exit(1)
child = Popen([XGETTEXT,'--output=-','-n','--keyword=_'] + files, stdout=PIPE)
(out, err) = child.communicate()
diff --git a/src/Makefile.am b/src/Makefile.am
index f7abab482e..ebae53a8c1 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -18,7 +18,6 @@ else
LIBUNIVALUE = $(UNIVALUE_LIBS)
endif
-BITCOIN_CONFIG_INCLUDES=-I$(builddir)/config
BITCOIN_INCLUDES=-I$(builddir) -I$(builddir)/obj $(BDB_CPPFLAGS) $(BOOST_CPPFLAGS) $(LEVELDB_CPPFLAGS) $(CRYPTO_CFLAGS) $(SSL_CFLAGS)
BITCOIN_INCLUDES += -I$(srcdir)/secp256k1/include
@@ -130,6 +129,7 @@ BITCOIN_CORE_H = \
rpc/client.h \
rpc/mining.h \
rpc/protocol.h \
+ rpc/safemode.h \
rpc/server.h \
rpc/register.h \
scheduler.h \
@@ -162,6 +162,8 @@ BITCOIN_CORE_H = \
wallet/crypter.h \
wallet/db.h \
wallet/feebumper.h \
+ wallet/fees.h \
+ wallet/init.h \
wallet/rpcwallet.h \
wallet/wallet.h \
wallet/walletdb.h \
@@ -208,6 +210,7 @@ libbitcoin_server_a_SOURCES = \
rpc/misc.cpp \
rpc/net.cpp \
rpc/rawtransaction.cpp \
+ rpc/safemode.cpp \
rpc/server.cpp \
script/sigcache.cpp \
script/ismine.cpp \
@@ -239,6 +242,8 @@ libbitcoin_wallet_a_SOURCES = \
wallet/crypter.cpp \
wallet/db.cpp \
wallet/feebumper.cpp \
+ wallet/fees.cpp \
+ wallet/init.cpp \
wallet/rpcdump.cpp \
wallet/rpcwallet.cpp \
wallet/wallet.cpp \
@@ -246,7 +251,7 @@ libbitcoin_wallet_a_SOURCES = \
$(BITCOIN_CORE_H)
# crypto primitives library
-crypto_libbitcoin_crypto_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_CONFIG_INCLUDES)
+crypto_libbitcoin_crypto_a_CPPFLAGS = $(AM_CPPFLAGS)
crypto_libbitcoin_crypto_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
crypto_libbitcoin_crypto_a_SOURCES = \
crypto/aes.cpp \
@@ -267,7 +272,7 @@ crypto_libbitcoin_crypto_a_SOURCES = \
crypto/sha512.cpp \
crypto/sha512.h
-if EXPERIMENTAL_ASM
+if USE_ASM
crypto_libbitcoin_crypto_a_SOURCES += crypto/sha256_sse4.cpp
endif
diff --git a/src/Makefile.qttest.include b/src/Makefile.qttest.include
index 02f30bc952..ea2ed17472 100644
--- a/src/Makefile.qttest.include
+++ b/src/Makefile.qttest.include
@@ -25,12 +25,10 @@ TEST_QT_H = \
qt/test/wallettests.h
TEST_BITCOIN_CPP = \
- test/test_bitcoin.cpp \
- test/testutil.cpp
+ test/test_bitcoin.cpp
TEST_BITCOIN_H = \
- test/test_bitcoin.h \
- test/testutil.h
+ test/test_bitcoin.h
qt_test_test_bitcoin_qt_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(BITCOIN_QT_INCLUDES) \
$(QT_INCLUDES) $(QT_TEST_INCLUDES) $(PROTOBUF_CFLAGS)
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index 6415b3d2e3..01ab0134fe 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -74,8 +74,6 @@ BITCOIN_TESTS =\
test/test_bitcoin.cpp \
test/test_bitcoin.h \
test/test_bitcoin_main.cpp \
- test/testutil.cpp \
- test/testutil.h \
test/timedata_tests.cpp \
test/torcontrol_tests.cpp \
test/transaction_tests.cpp \
diff --git a/src/addrdb.h b/src/addrdb.h
index 6cb36dfac4..d930de204d 100644
--- a/src/addrdb.h
+++ b/src/addrdb.h
@@ -37,7 +37,7 @@ public:
SetNull();
}
- CBanEntry(int64_t nCreateTimeIn)
+ explicit CBanEntry(int64_t nCreateTimeIn)
{
SetNull();
nCreateTime = nCreateTimeIn;
@@ -61,7 +61,7 @@ public:
banReason = BanReasonUnknown;
}
- std::string banReasonToString()
+ std::string banReasonToString() const
{
switch (banReason) {
case BanReasonNodeMisbehaving:
diff --git a/src/arith_uint256.h b/src/arith_uint256.h
index 6223e4afeb..5fd4fe96cf 100644
--- a/src/arith_uint256.h
+++ b/src/arith_uint256.h
@@ -250,7 +250,7 @@ public:
uint64_t GetLow64() const
{
- assert(WIDTH >= 2);
+ static_assert(WIDTH >= 2, "Assertion WIDTH >= 2 failed (WIDTH = BITS / 32). BITS is a template parameter.");
return pn[0] | (uint64_t)pn[1] << 32;
}
};
diff --git a/src/base58.cpp b/src/base58.cpp
index c70e358ebb..3802f953f9 100644
--- a/src/base58.cpp
+++ b/src/base58.cpp
@@ -218,7 +218,7 @@ private:
CBitcoinAddress* addr;
public:
- CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
+ explicit CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
diff --git a/src/bench/checkqueue.cpp b/src/bench/checkqueue.cpp
index 88a2a570f9..b7ae5c2d57 100644
--- a/src/bench/checkqueue.cpp
+++ b/src/bench/checkqueue.cpp
@@ -67,7 +67,7 @@ static void CCheckQueueSpeedPrevectorJob(benchmark::State& state)
prevector<PREVECTOR_SIZE, uint8_t> p;
PrevectorJob(){
}
- PrevectorJob(FastRandomContext& insecure_rand){
+ explicit PrevectorJob(FastRandomContext& insecure_rand){
p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2));
}
bool operator()()
diff --git a/src/bench/lockedpool.cpp b/src/bench/lockedpool.cpp
index 43a1422795..c6a05567be 100644
--- a/src/bench/lockedpool.cpp
+++ b/src/bench/lockedpool.cpp
@@ -21,14 +21,14 @@ static void BenchLockedPool(benchmark::State& state)
std::vector<void*> addr;
for (int x=0; x<ASIZE; ++x)
- addr.push_back(0);
+ addr.push_back(nullptr);
uint32_t s = 0x12345678;
while (state.KeepRunning()) {
for (int x=0; x<BITER; ++x) {
int idx = s & (addr.size()-1);
if (s & 0x80000000) {
b.free(addr[idx]);
- addr[idx] = 0;
+ addr[idx] = nullptr;
} else if(!addr[idx]) {
addr[idx] = b.alloc((s >> 16) & (MSIZE-1));
}
diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
index 0b74f31bfe..fca6083ea8 100644
--- a/src/bitcoin-cli.cpp
+++ b/src/bitcoin-cli.cpp
@@ -45,7 +45,8 @@ std::string HelpMessageCli()
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
- strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
+ strUsage += HelpMessageOpt("-stdinrpcpass", strprintf(_("Read RPC password from standard input as a single line. When combined with -stdin, the first line from standard input is used for the RPC password.")));
+ strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases). When combined with -stdinrpcpass, the first line from standard input is used for the RPC password."));
strUsage += HelpMessageOpt("-rpcwallet=<walletname>", _("Send RPC for non-default wallet on RPC server (argument is wallet filename in bitcoind directory, required if bitcoind/-Qt runs with multiple wallets)"));
return strUsage;
@@ -79,10 +80,10 @@ static int AppInitRPC(int argc, char* argv[])
//
// Parameters
//
- ParseParameters(argc, argv);
- if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
+ gArgs.ParseParameters(argc, argv);
+ if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
- if (!IsArgSet("-version")) {
+ if (!gArgs.IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoin-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
@@ -100,11 +101,11 @@ static int AppInitRPC(int argc, char* argv[])
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
- fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
+ fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
- ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
+ gArgs.ReadConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
@@ -116,7 +117,7 @@ static int AppInitRPC(int argc, char* argv[])
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
- if (GetBoolArg("-rpcssl", false))
+ if (gArgs.GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
@@ -190,7 +191,7 @@ static void http_error_cb(enum evhttp_request_error err, void *ctx)
}
#endif
-UniValue CallRPC(const std::string& strMethod, const UniValue& params)
+static UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host;
// In preference order, we choose the following for the port:
@@ -198,15 +199,15 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
// 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
// 3. default port for chain
int port = BaseParams().RPCPort();
- SplitHostPort(GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
- port = GetArg("-rpcport", port);
+ SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
+ port = gArgs.GetArg("-rpcport", port);
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
- evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
+ evhttp_connection_set_timeout(evcon.get(), gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
@@ -218,16 +219,16 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
// Get credentials
std::string strRPCUserColonPass;
- if (GetArg("-rpcpassword", "") == "") {
+ if (gArgs.GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
- _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
- GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
+ _("Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)"),
+ GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
- strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
+ strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
@@ -244,7 +245,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
// check if we should use a special wallet endpoint
std::string endpoint = "/";
- std::string walletName = GetArg("-rpcwallet", "");
+ std::string walletName = gArgs.GetArg("-rpcwallet", "");
if (!walletName.empty()) {
char *encodedURI = evhttp_uriencode(walletName.c_str(), walletName.size(), false);
if (encodedURI) {
@@ -293,8 +294,14 @@ int CommandLineRPC(int argc, char *argv[])
argc--;
argv++;
}
+ std::string rpcPass;
+ if (gArgs.GetBoolArg("-stdinrpcpass", false)) {
+ if(!std::getline(std::cin,rpcPass))
+ throw std::runtime_error("-stdinrpcpass specified but failed to read from standard input");
+ gArgs.ForceSetArg("-rpcpassword", rpcPass);
+ }
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
- if (GetBoolArg("-stdin", false)) {
+ if (gArgs.GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
@@ -306,14 +313,14 @@ int CommandLineRPC(int argc, char *argv[])
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
- if(GetBoolArg("-named", DEFAULT_NAMED)) {
+ if(gArgs.GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
- const bool fWait = GetBoolArg("-rpcwait", false);
+ const bool fWait = gArgs.GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index e5ea9f3228..cff90d13af 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -39,7 +39,7 @@ static int AppInitRawTx(int argc, char* argv[])
//
// Parameters
//
- ParseParameters(argc, argv);
+ gArgs.ParseParameters(argc, argv);
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
@@ -49,9 +49,9 @@ static int AppInitRawTx(int argc, char* argv[])
return EXIT_FAILURE;
}
- fCreateBlank = GetBoolArg("-create", false);
+ fCreateBlank = gArgs.GetBoolArg("-create", false);
- if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help"))
+ if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help"))
{
// First part of help message is specific to this utility
std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
@@ -737,9 +737,9 @@ static void OutputTxHex(const CTransaction& tx)
static void OutputTx(const CTransaction& tx)
{
- if (GetBoolArg("-json", false))
+ if (gArgs.GetBoolArg("-json", false))
OutputTxJSON(tx);
- else if (GetBoolArg("-txid", false))
+ else if (gArgs.GetBoolArg("-txid", false))
OutputTxHash(tx);
else
OutputTxHex(tx);
diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp
index eaef7a903b..543eba0e69 100644
--- a/src/bitcoind.cpp
+++ b/src/bitcoind.cpp
@@ -71,14 +71,14 @@ bool AppInit(int argc, char* argv[])
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
- ParseParameters(argc, argv);
+ gArgs.ParseParameters(argc, argv);
// Process help and version before taking care about datadir
- if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
+ if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version"))
{
std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";
- if (IsArgSet("-version"))
+ if (gArgs.IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo());
}
@@ -98,12 +98,12 @@ bool AppInit(int argc, char* argv[])
{
if (!fs::is_directory(GetDataDir(false)))
{
- fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
+ fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
return false;
}
try
{
- ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
+ gArgs.ReadConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
@@ -125,7 +125,7 @@ bool AppInit(int argc, char* argv[])
}
// -server defaults to true for bitcoind but not for the GUI so do this here
- SoftSetBoolArg("-server", true);
+ gArgs.SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
@@ -144,7 +144,7 @@ bool AppInit(int argc, char* argv[])
// InitError will have been called with detailed error, which ends up on console
exit(EXIT_FAILURE);
}
- if (GetBoolArg("-daemon", false))
+ if (gArgs.GetBoolArg("-daemon", false))
{
#if HAVE_DECL_DAEMON
fprintf(stdout, "Bitcoin server starting\n");
diff --git a/src/blockencodings.h b/src/blockencodings.h
index 5a1d80d421..50478f9f32 100644
--- a/src/blockencodings.h
+++ b/src/blockencodings.h
@@ -16,7 +16,7 @@ struct TransactionCompressor {
private:
CTransactionRef& tx;
public:
- TransactionCompressor(CTransactionRef& txIn) : tx(txIn) {}
+ explicit TransactionCompressor(CTransactionRef& txIn) : tx(txIn) {}
ADD_SERIALIZE_METHODS;
@@ -75,7 +75,7 @@ public:
std::vector<CTransactionRef> txn;
BlockTransactions() {}
- BlockTransactions(const BlockTransactionsRequest& req) :
+ explicit BlockTransactions(const BlockTransactionsRequest& req) :
blockhash(req.blockhash), txn(req.indexes.size()) {}
ADD_SERIALIZE_METHODS;
@@ -198,7 +198,7 @@ protected:
CTxMemPool* pool;
public:
CBlockHeader header;
- PartiallyDownloadedBlock(CTxMemPool* poolIn) : pool(poolIn) {}
+ explicit PartiallyDownloadedBlock(CTxMemPool* poolIn) : pool(poolIn) {}
// extra_txn is a list of extra transactions to look at, in <witness hash, reference> form
ReadStatus InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn);
diff --git a/src/chain.h b/src/chain.h
index 1223539e73..ef7e6f9554 100644
--- a/src/chain.h
+++ b/src/chain.h
@@ -216,7 +216,7 @@ public:
//! (memory only) Sequential id assigned to distinguish order in which blocks are received.
int32_t nSequenceId;
- //! (memory only) Maximum nTime in the chain upto and including this block.
+ //! (memory only) Maximum nTime in the chain up to and including this block.
unsigned int nTimeMax;
void SetNull()
@@ -247,7 +247,7 @@ public:
SetNull();
}
- CBlockIndex(const CBlockHeader& block)
+ explicit CBlockIndex(const CBlockHeader& block)
{
SetNull();
diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp
index 43c9a13c54..224c9eb0ea 100644
--- a/src/chainparamsbase.cpp
+++ b/src/chainparamsbase.cpp
@@ -89,8 +89,8 @@ void SelectBaseParams(const std::string& chain)
std::string ChainNameFromCommandLine()
{
- bool fRegTest = GetBoolArg("-regtest", false);
- bool fTestNet = GetBoolArg("-testnet", false);
+ bool fRegTest = gArgs.GetBoolArg("-regtest", false);
+ bool fTestNet = gArgs.GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
throw std::runtime_error("Invalid combination of -regtest and -testnet.");
diff --git a/src/checkqueue.h b/src/checkqueue.h
index 4bc6be45f8..6377fbe942 100644
--- a/src/checkqueue.h
+++ b/src/checkqueue.h
@@ -131,7 +131,7 @@ public:
boost::mutex ControlMutex;
//! Create a new check queue
- CCheckQueue(unsigned int nBatchSizeIn) : nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
+ explicit CCheckQueue(unsigned int nBatchSizeIn) : nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
//! Worker thread
void Thread()
diff --git a/src/coins.cpp b/src/coins.cpp
index e30bda930a..b45dfc3342 100644
--- a/src/coins.cpp
+++ b/src/coins.cpp
@@ -14,7 +14,7 @@ bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return f
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
-CCoinsViewCursor *CCoinsView::Cursor() const { return 0; }
+CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; }
bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
{
diff --git a/src/compat/byteswap.h b/src/compat/byteswap.h
index 3c5a5c0837..d93ff7413a 100644
--- a/src/compat/byteswap.h
+++ b/src/compat/byteswap.h
@@ -35,7 +35,7 @@
#if HAVE_DECL_BSWAP_16 == 0
inline uint16_t bswap_16(uint16_t x)
{
- return (x >> 8) | ((x & 0x00ff) << 8);
+ return (x >> 8) | (x << 8);
}
#endif // HAVE_DECL_BSWAP16
diff --git a/src/compat/endian.h b/src/compat/endian.h
index 79d6b2fdbb..dbf178f53c 100644
--- a/src/compat/endian.h
+++ b/src/compat/endian.h
@@ -9,10 +9,10 @@
#include "config/bitcoin-config.h"
#endif
-#include <stdint.h>
-
#include "compat/byteswap.h"
+#include <stdint.h>
+
#if defined(HAVE_ENDIAN_H)
#include <endian.h>
#elif defined(HAVE_SYS_ENDIAN_H)
diff --git a/src/compressor.h b/src/compressor.h
index 015911484a..094c1bcfe1 100644
--- a/src/compressor.h
+++ b/src/compressor.h
@@ -53,7 +53,7 @@ protected:
unsigned int GetSpecialSize(unsigned int nSize) const;
bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
public:
- CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
+ explicit CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
template<typename Stream>
void Serialize(Stream &s) const {
@@ -99,7 +99,7 @@ public:
static uint64_t CompressAmount(uint64_t nAmount);
static uint64_t DecompressAmount(uint64_t nAmount);
- CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
+ explicit CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
ADD_SERIALIZE_METHODS;
diff --git a/src/core_io.h b/src/core_io.h
index 3f25faf0ec..ccc72ebb32 100644
--- a/src/core_io.h
+++ b/src/core_io.h
@@ -31,6 +31,6 @@ UniValue ValueFromAmount(const CAmount& amount);
std::string FormatScript(const CScript& script);
std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags = 0);
void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
-void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry);
+void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0);
#endif // BITCOIN_CORE_IO_H
diff --git a/src/core_write.cpp b/src/core_write.cpp
index 0eae4703ab..1431fa0c9b 100644
--- a/src/core_write.cpp
+++ b/src/core_write.cpp
@@ -153,7 +153,7 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey,
out.pushKV("addresses", a);
}
-void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry)
+void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
@@ -207,5 +207,7 @@ void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry)
if (!hashBlock.IsNull())
entry.pushKV("blockhash", hashBlock.GetHex());
- entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction".
+ if (include_hex) {
+ entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction".
+ }
}
diff --git a/src/crypto/aes.h b/src/crypto/aes.h
index e9f1b52e71..a7b63b19df 100644
--- a/src/crypto/aes.h
+++ b/src/crypto/aes.h
@@ -22,7 +22,7 @@ private:
AES128_ctx ctx;
public:
- AES128Encrypt(const unsigned char key[16]);
+ explicit AES128Encrypt(const unsigned char key[16]);
~AES128Encrypt();
void Encrypt(unsigned char ciphertext[16], const unsigned char plaintext[16]) const;
};
@@ -34,7 +34,7 @@ private:
AES128_ctx ctx;
public:
- AES128Decrypt(const unsigned char key[16]);
+ explicit AES128Decrypt(const unsigned char key[16]);
~AES128Decrypt();
void Decrypt(unsigned char plaintext[16], const unsigned char ciphertext[16]) const;
};
@@ -46,7 +46,7 @@ private:
AES256_ctx ctx;
public:
- AES256Encrypt(const unsigned char key[32]);
+ explicit AES256Encrypt(const unsigned char key[32]);
~AES256Encrypt();
void Encrypt(unsigned char ciphertext[16], const unsigned char plaintext[16]) const;
};
@@ -58,7 +58,7 @@ private:
AES256_ctx ctx;
public:
- AES256Decrypt(const unsigned char key[32]);
+ explicit AES256Decrypt(const unsigned char key[32]);
~AES256Decrypt();
void Decrypt(unsigned char plaintext[16], const unsigned char ciphertext[16]) const;
};
diff --git a/src/crypto/common.h b/src/crypto/common.h
index bcca3d30ea..bd9bc9420b 100644
--- a/src/crypto/common.h
+++ b/src/crypto/common.h
@@ -6,7 +6,7 @@
#define BITCOIN_CRYPTO_COMMON_H
#if defined(HAVE_CONFIG_H)
-#include "bitcoin-config.h"
+#include "config/bitcoin-config.h"
#endif
#include <stdint.h>
diff --git a/src/crypto/hmac_sha256.h b/src/crypto/hmac_sha256.h
index 1519c1457e..8c42fcfe14 100644
--- a/src/crypto/hmac_sha256.h
+++ b/src/crypto/hmac_sha256.h
@@ -10,7 +10,7 @@
#include <stdint.h>
#include <stdlib.h>
-/** A hasher class for HMAC-SHA-512. */
+/** A hasher class for HMAC-SHA-256. */
class CHMAC_SHA256
{
private:
diff --git a/src/crypto/sha256.cpp b/src/crypto/sha256.cpp
index 15d6db90c2..29afe86ec7 100644
--- a/src/crypto/sha256.cpp
+++ b/src/crypto/sha256.cpp
@@ -10,7 +10,7 @@
#include <atomic>
#if defined(__x86_64__) || defined(__amd64__)
-#if defined(EXPERIMENTAL_ASM)
+#if defined(USE_ASM)
#include <cpuid.h>
namespace sha256_sse4
{
@@ -178,7 +178,7 @@ TransformType Transform = sha256::Transform;
std::string SHA256AutoDetect()
{
-#if defined(EXPERIMENTAL_ASM) && (defined(__x86_64__) || defined(__amd64__))
+#if defined(USE_ASM) && (defined(__x86_64__) || defined(__amd64__))
uint32_t eax, ebx, ecx, edx;
if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx >> 19) & 1) {
Transform = sha256_sse4::Transform;
diff --git a/src/cuckoocache.h b/src/cuckoocache.h
index fd24d05ee7..947e1a7185 100644
--- a/src/cuckoocache.h
+++ b/src/cuckoocache.h
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef _BITCOIN_CUCKOOCACHE_H_
-#define _BITCOIN_CUCKOOCACHE_H_
+#ifndef BITCOIN_CUCKOOCACHE_H
+#define BITCOIN_CUCKOOCACHE_H
#include <array>
#include <algorithm>
@@ -58,7 +58,7 @@ public:
* @post All calls to bit_is_set (without subsequent bit_unset) will return
* true.
*/
- bit_packed_atomic_flags(uint32_t size)
+ explicit bit_packed_atomic_flags(uint32_t size)
{
// pad out the size if needed
size = (size + 7) / 8;
@@ -478,4 +478,4 @@ public:
};
} // namespace CuckooCache
-#endif
+#endif // BITCOIN_CUCKOOCACHE_H
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index 27767f90b4..dfc90f3ab9 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -19,7 +19,7 @@ class CBitcoinLevelDBLogger : public leveldb::Logger {
public:
// This code is adapted from posix_logger.h, which is why it is using vsprintf.
// Please do not do this in normal code
- virtual void Logv(const char * format, va_list ap) override {
+ void Logv(const char * format, va_list ap) override {
if (!LogAcceptCategory(BCLog::LEVELDB)) {
return;
}
@@ -115,7 +115,7 @@ CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bo
dbwrapper_private::HandleError(status);
LogPrintf("Opened LevelDB successfully\n");
- if (GetBoolArg("-forcecompactdb", false)) {
+ if (gArgs.GetBoolArg("-forcecompactdb", false)) {
LogPrintf("Starting database compaction of %s\n", path.string());
pdb->CompactRange(nullptr, nullptr);
LogPrintf("Finished database compaction of %s\n", path.string());
@@ -190,7 +190,7 @@ bool CDBWrapper::IsEmpty()
}
CDBIterator::~CDBIterator() { delete piter; }
-bool CDBIterator::Valid() { return piter->Valid(); }
+bool CDBIterator::Valid() const { return piter->Valid(); }
void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
void CDBIterator::Next() { piter->Next(); }
diff --git a/src/dbwrapper.h b/src/dbwrapper.h
index 7575d207ae..e19fde51c1 100644
--- a/src/dbwrapper.h
+++ b/src/dbwrapper.h
@@ -22,7 +22,7 @@ static const size_t DBWRAPPER_PREALLOC_VALUE_SIZE = 1024;
class dbwrapper_error : public std::runtime_error
{
public:
- dbwrapper_error(const std::string& msg) : std::runtime_error(msg) {}
+ explicit dbwrapper_error(const std::string& msg) : std::runtime_error(msg) {}
};
class CDBWrapper;
@@ -61,7 +61,7 @@ public:
/**
* @param[in] _parent CDBWrapper that this batch is to be submitted to
*/
- CDBBatch(const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0) { };
+ explicit CDBBatch(const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0) { };
void Clear()
{
@@ -130,7 +130,7 @@ public:
parent(_parent), piter(_piter) { };
~CDBIterator();
- bool Valid();
+ bool Valid() const;
void SeekToFirst();
diff --git a/src/hash.h b/src/hash.h
index b9952d39fc..ad59bb1817 100644
--- a/src/hash.h
+++ b/src/hash.h
@@ -168,7 +168,7 @@ private:
Source* source;
public:
- CHashVerifier(Source* source_) : CHashWriter(source_->GetType(), source_->GetVersion()), source(source_) {}
+ explicit CHashVerifier(Source* source_) : CHashWriter(source_->GetType(), source_->GetVersion()), source(source_) {}
void read(char* pch, size_t nSize)
{
diff --git a/src/httprpc.cpp b/src/httprpc.cpp
index 69c3e3f49f..91f96ef207 100644
--- a/src/httprpc.cpp
+++ b/src/httprpc.cpp
@@ -43,7 +43,7 @@ private:
class HTTPRPCTimerInterface : public RPCTimerInterface
{
public:
- HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
+ explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
{
}
const char* Name() override
@@ -62,7 +62,7 @@ private:
/* Pre-base64-encoded authentication token */
static std::string strRPCUserColonPass;
/* Stored RPC timer interface (for unregistration) */
-static HTTPRPCTimerInterface* httpRPCTimerInterface = 0;
+static HTTPRPCTimerInterface* httpRPCTimerInterface = nullptr;
static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
{
@@ -210,7 +210,7 @@ static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
static bool InitRPCAuthentication()
{
- if (GetArg("-rpcpassword", "") == "")
+ if (gArgs.GetArg("-rpcpassword", "") == "")
{
LogPrintf("No rpcpassword set - using random cookie authentication\n");
if (!GenerateAuthCookie(&strRPCUserColonPass)) {
@@ -221,7 +221,7 @@ static bool InitRPCAuthentication()
}
} else {
LogPrintf("Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share/rpcuser for rpcauth auth generation.\n");
- strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
+ strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
}
return true;
}
@@ -255,6 +255,6 @@ void StopHTTPRPC()
if (httpRPCTimerInterface) {
RPCUnsetTimerInterface(httpRPCTimerInterface);
delete httpRPCTimerInterface;
- httpRPCTimerInterface = 0;
+ httpRPCTimerInterface = nullptr;
}
}
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 5adfca4094..5923871691 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -40,7 +40,7 @@
static const size_t MAX_HEADERS_SIZE = 8192;
/** HTTP request work item */
-class HTTPWorkItem : public HTTPClosure
+class HTTPWorkItem final : public HTTPClosure
{
public:
HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
@@ -79,7 +79,7 @@ private:
{
public:
WorkQueue &wq;
- ThreadCounter(WorkQueue &w): wq(w)
+ explicit ThreadCounter(WorkQueue &w): wq(w)
{
std::lock_guard<std::mutex> lock(wq.cs);
wq.numThreads += 1;
@@ -93,7 +93,7 @@ private:
};
public:
- WorkQueue(size_t _maxDepth) : running(true),
+ explicit WorkQueue(size_t _maxDepth) : running(true),
maxDepth(_maxDepth),
numThreads(0)
{
@@ -164,13 +164,13 @@ struct HTTPPathHandler
/** HTTP module state */
//! libevent event loop
-static struct event_base* eventBase = 0;
+static struct event_base* eventBase = nullptr;
//! HTTP server
-struct evhttp* eventHTTP = 0;
+struct evhttp* eventHTTP = nullptr;
//! List of subnets to allow RPC connections from
static std::vector<CSubNet> rpc_allow_subnets;
//! Work queue for handling longer requests off the event loop thread
-static WorkQueue<HTTPClosure>* workQueue = 0;
+static WorkQueue<HTTPClosure>* workQueue = nullptr;
//! Handlers for (sub)paths
std::vector<HTTPPathHandler> pathHandlers;
//! Bound listening sockets
@@ -309,14 +309,14 @@ static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
/** Bind HTTP server to specified addresses */
static bool HTTPBindAddresses(struct evhttp* http)
{
- int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
+ int defaultPort = gArgs.GetArg("-rpcport", BaseParams().RPCPort());
std::vector<std::pair<std::string, uint16_t> > endpoints;
// Determine what addresses to bind to
- if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
+ if (!gArgs.IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
endpoints.push_back(std::make_pair("::1", defaultPort));
endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
- if (IsArgSet("-rpcbind")) {
+ if (gArgs.IsArgSet("-rpcbind")) {
LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
}
} else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
@@ -369,7 +369,7 @@ bool InitHTTPServer()
if (!InitHTTPAllowList())
return false;
- if (GetBoolArg("-rpcssl", false)) {
+ if (gArgs.GetBoolArg("-rpcssl", false)) {
uiInterface.ThreadSafeMessageBox(
"SSL mode for RPC (-rpcssl) is no longer supported.",
"", CClientUIInterface::MSG_ERROR);
@@ -401,7 +401,7 @@ bool InitHTTPServer()
return false;
}
- evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
+ evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, MAX_SIZE);
evhttp_set_gencb(http, http_request_cb, nullptr);
@@ -412,11 +412,11 @@ bool InitHTTPServer()
}
LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
- int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
+ int workQueueDepth = std::max((long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
- // tranfer ownership to eventBase/HTTP via .release()
+ // transfer ownership to eventBase/HTTP via .release()
eventBase = base_ctr.release();
eventHTTP = http_ctr.release();
return true;
@@ -442,7 +442,7 @@ std::future<bool> threadResult;
bool StartHTTPServer()
{
LogPrint(BCLog::HTTP, "Starting HTTP server\n");
- int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
+ int rpcThreads = std::max((long)gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
threadResult = task.get_future();
@@ -495,11 +495,11 @@ void StopHTTPServer()
}
if (eventHTTP) {
evhttp_free(eventHTTP);
- eventHTTP = 0;
+ eventHTTP = nullptr;
}
if (eventBase) {
event_base_free(eventBase);
- eventBase = 0;
+ eventBase = nullptr;
}
LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
}
@@ -601,9 +601,9 @@ void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
evbuffer_add(evb, strReply.data(), strReply.size());
HTTPEvent* ev = new HTTPEvent(eventBase, true,
std::bind(evhttp_send_reply, req, nStatus, (const char*)nullptr, (struct evbuffer *)nullptr));
- ev->trigger(0);
+ ev->trigger(nullptr);
replySent = true;
- req = 0; // transferred back to main thread
+ req = nullptr; // transferred back to main thread
}
CService HTTPRequest::GetPeer()
diff --git a/src/httpserver.h b/src/httpserver.h
index 3e434bf0a0..91ce5b4e00 100644
--- a/src/httpserver.h
+++ b/src/httpserver.h
@@ -61,7 +61,7 @@ private:
bool replySent;
public:
- HTTPRequest(struct evhttp_request* req);
+ explicit HTTPRequest(struct evhttp_request* req);
~HTTPRequest();
enum RequestMethod {
diff --git a/src/init.cpp b/src/init.cpp
index cddb42c0ee..6114bbaa2d 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -30,6 +30,7 @@
#include "policy/policy.h"
#include "rpc/server.h"
#include "rpc/register.h"
+#include "rpc/safemode.h"
#include "rpc/blockchain.h"
#include "script/standard.h"
#include "script/sigcache.h"
@@ -43,6 +44,7 @@
#include "utilmoneystr.h"
#include "validationinterface.h"
#ifdef ENABLE_WALLET
+#include "wallet/init.h"
#include "wallet/wallet.h"
#endif
#include "warnings.h"
@@ -69,7 +71,6 @@
bool fFeeEstimatesInitialized = false;
static const bool DEFAULT_PROXYRANDOMIZE = true;
static const bool DEFAULT_REST_ENABLE = false;
-static const bool DEFAULT_DISABLE_SAFEMODE = false;
static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
std::unique_ptr<CConnman> g_connman;
@@ -133,10 +134,10 @@ bool ShutdownRequested()
* chainstate, while keeping user interface out of the common library, which is shared
* between bitcoind, and bitcoin-qt and non-server tools.
*/
-class CCoinsViewErrorCatcher : public CCoinsViewBacked
+class CCoinsViewErrorCatcher final : public CCoinsViewBacked
{
public:
- CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
+ explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
try {
return CCoinsViewBacked::GetCoin(outpoint, coin);
@@ -199,7 +200,7 @@ void Shutdown()
StopTorControl();
UnregisterNodeSignals(GetNodeSignals());
- if (fDumpMempoolLater && GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
+ if (fDumpMempoolLater && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
DumpMempool();
}
@@ -317,22 +318,13 @@ void OnRPCStopped()
LogPrint(BCLog::RPC, "RPC stopped.\n");
}
-void OnRPCPreCommand(const CRPCCommand& cmd)
-{
- // Observe safe mode
- std::string strWarning = GetWarnings("rpc");
- if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
- !cmd.okSafeMode)
- throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
-}
-
std::string HelpMessage(HelpMessageMode mode)
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
- const bool showDebug = GetBoolArg("-help-debug", false);
+ const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
// When adding new options to the categories, please keep and ensure alphabetical ordering.
// Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
@@ -420,7 +412,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
#ifdef ENABLE_WALLET
- strUsage += CWallet::GetWalletHelpString(showDebug);
+ strUsage += GetWalletHelpString(showDebug);
#endif
#if ENABLE_ZMQ
@@ -479,7 +471,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageGroup(_("Node relay options:"));
if (showDebug) {
- strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", defaultChainParams->RequireStandard()));
+ strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()));
strUsage += HelpMessageOpt("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)));
strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
}
@@ -546,7 +538,7 @@ static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex
if (initialSync || !pBlockIndex)
return;
- std::string strCmd = GetArg("-blocknotify", "");
+ std::string strCmd = gArgs.GetArg("-blocknotify", "");
boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
@@ -683,12 +675,12 @@ void ThreadImport(std::vector<fs::path> vImportFiles)
StartShutdown();
}
- if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
+ if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
}
} // End scope of CImportingNow
- if (GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
+ if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
LoadMempool();
fDumpMempoolLater = !fRequestShutdown;
}
@@ -720,14 +712,13 @@ bool AppInitServers(boost::thread_group& threadGroup)
{
RPCServer::OnStarted(&OnRPCStarted);
RPCServer::OnStopped(&OnRPCStopped);
- RPCServer::OnPreCommand(&OnRPCPreCommand);
if (!InitHTTPServer())
return false;
if (!StartRPC())
return false;
if (!StartHTTPRPC())
return false;
- if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
+ if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
return false;
if (!StartHTTPServer())
return false;
@@ -739,61 +730,61 @@ void InitParameterInteraction()
{
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
- if (IsArgSet("-bind")) {
- if (SoftSetBoolArg("-listen", true))
+ if (gArgs.IsArgSet("-bind")) {
+ if (gArgs.SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
}
- if (IsArgSet("-whitebind")) {
- if (SoftSetBoolArg("-listen", true))
+ if (gArgs.IsArgSet("-whitebind")) {
+ if (gArgs.SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
}
if (gArgs.IsArgSet("-connect")) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
- if (SoftSetBoolArg("-dnsseed", false))
+ if (gArgs.SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
- if (SoftSetBoolArg("-listen", false))
+ if (gArgs.SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
}
- if (IsArgSet("-proxy")) {
+ if (gArgs.IsArgSet("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified
- if (SoftSetBoolArg("-listen", false))
+ if (gArgs.SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
// to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
// to listen locally, so don't rely on this happening through -listen below.
- if (SoftSetBoolArg("-upnp", false))
+ if (gArgs.SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
// to protect privacy, do not discover addresses by default
- if (SoftSetBoolArg("-discover", false))
+ if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
}
- if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
+ if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
- if (SoftSetBoolArg("-upnp", false))
+ if (gArgs.SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
- if (SoftSetBoolArg("-discover", false))
+ if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
- if (SoftSetBoolArg("-listenonion", false))
+ if (gArgs.SoftSetBoolArg("-listenonion", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
}
- if (IsArgSet("-externalip")) {
+ if (gArgs.IsArgSet("-externalip")) {
// if an explicit public IP is specified, do not try to find others
- if (SoftSetBoolArg("-discover", false))
+ if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
}
// disable whitelistrelay in blocksonly mode
- if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
- if (SoftSetBoolArg("-whitelistrelay", false))
+ if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
+ if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
}
// Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
- if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
- if (SoftSetBoolArg("-whitelistrelay", true))
+ if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
+ if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
}
}
@@ -805,10 +796,10 @@ static std::string ResolveErrMsg(const char * const optname, const std::string&
void InitLogging()
{
- fPrintToConsole = GetBoolArg("-printtoconsole", false);
- fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
- fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
- fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
+ fPrintToConsole = gArgs.GetBoolArg("-printtoconsole", false);
+ fLogTimestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
+ fLogTimeMicros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
+ fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
LogPrintf("Bitcoin version %s\n", FormatFullVersion());
@@ -865,7 +856,7 @@ bool AppInitBasicSetup()
return InitError("Initializing networking failed");
#ifndef WIN32
- if (!GetBoolArg("-sysperms", false)) {
+ if (!gArgs.GetBoolArg("-sysperms", false)) {
umask(077);
}
@@ -893,8 +884,8 @@ bool AppInitParameterInteraction()
// also see: InitParameterInteraction()
// if using block pruning, then disallow txindex
- if (GetArg("-prune", 0)) {
- if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
+ if (gArgs.GetArg("-prune", 0)) {
+ if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
return InitError(_("Prune mode is incompatible with -txindex."));
}
@@ -906,7 +897,7 @@ bool AppInitParameterInteraction()
// Make sure enough file descriptors are available
int nBind = std::max(nUserBind, size_t(1));
- nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
+ nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
nMaxConnections = std::max(nUserMaxConnections, 0);
// Trim requested connection counts, to fit into system limitations
@@ -947,55 +938,55 @@ bool AppInitParameterInteraction()
}
// Check for -debugnet
- if (GetBoolArg("-debugnet", false))
+ if (gArgs.GetBoolArg("-debugnet", false))
InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
// Check for -socks - as this is a privacy risk to continue, exit here
- if (IsArgSet("-socks"))
+ if (gArgs.IsArgSet("-socks"))
return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
// Check for -tor - as this is a privacy risk to continue, exit here
- if (GetBoolArg("-tor", false))
+ if (gArgs.GetBoolArg("-tor", false))
return InitError(_("Unsupported argument -tor found, use -onion."));
- if (GetBoolArg("-benchmark", false))
+ if (gArgs.GetBoolArg("-benchmark", false))
InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
- if (GetBoolArg("-whitelistalwaysrelay", false))
+ if (gArgs.GetBoolArg("-whitelistalwaysrelay", false))
InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
- if (IsArgSet("-blockminsize"))
+ if (gArgs.IsArgSet("-blockminsize"))
InitWarning("Unsupported argument -blockminsize ignored.");
// Checkmempool and checkblockindex default to true in regtest mode
- int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
+ int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
if (ratio != 0) {
mempool.setSanityCheck(1.0 / ratio);
}
- fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
- fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
+ fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
+ fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
- hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
+ hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
if (!hashAssumeValid.IsNull())
LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
else
LogPrintf("Validating signatures for all blocks.\n");
// mempool limits
- int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
- int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
+ int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
// incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
// and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
- if (IsArgSet("-incrementalrelayfee"))
+ if (gArgs.IsArgSet("-incrementalrelayfee"))
{
CAmount n = 0;
- if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
- return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
+ if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
+ return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
incrementalRelayFee = CFeeRate(n);
}
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
- nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
+ nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += GetNumCores();
if (nScriptCheckThreads <= 1)
@@ -1004,7 +995,7 @@ bool AppInitParameterInteraction()
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// block pruning; get the amount of disk space (in MiB) to allot for block & undo files
- int64_t nPruneArg = GetArg("-prune", 0);
+ int64_t nPruneArg = gArgs.GetArg("-prune", 0);
if (nPruneArg < 0) {
return InitError(_("Prune cannot be configured with a negative value."));
}
@@ -1026,16 +1017,16 @@ bool AppInitParameterInteraction()
RegisterWalletRPCCommands(tableRPC);
#endif
- nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
+ nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
if (nConnectTimeout <= 0)
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
- if (IsArgSet("-minrelaytxfee")) {
+ if (gArgs.IsArgSet("-minrelaytxfee")) {
CAmount n = 0;
- if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
- return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
+ if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
+ return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
}
- // High fee check is done afterward in CWallet::ParameterInteraction()
+ // High fee check is done afterward in WalletParameterInteraction()
::minRelayTxFee = CFeeRate(n);
} else if (incrementalRelayFee > ::minRelayTxFee) {
// Allow only setting incrementalRelayFee to control both
@@ -1045,55 +1036,55 @@ bool AppInitParameterInteraction()
// Sanity check argument for min fee for including tx in block
// TODO: Harmonize which arguments need sanity checking and where that happens
- if (IsArgSet("-blockmintxfee"))
+ if (gArgs.IsArgSet("-blockmintxfee"))
{
CAmount n = 0;
- if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
- return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
+ if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
+ return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
}
// Feerate used to define dust. Shouldn't be changed lightly as old
// implementations may inadvertently create non-standard transactions
- if (IsArgSet("-dustrelayfee"))
+ if (gArgs.IsArgSet("-dustrelayfee"))
{
CAmount n = 0;
- if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
- return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
+ if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n) || 0 == n)
+ return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
dustRelayFee = CFeeRate(n);
}
- fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
+ fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
if (chainparams.RequireStandard() && !fRequireStandard)
return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
- nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
+ nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
#ifdef ENABLE_WALLET
- if (!CWallet::ParameterInteraction())
+ if (!WalletParameterInteraction())
return false;
#endif
- fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
- fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
- nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
+ fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
+ fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
+ nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
// Option to startup with mocktime set (used for regression testing):
- SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
+ SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
- if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
+ if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
- if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
+ if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
return InitError("rpcserialversion must be non-negative.");
- if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
+ if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
return InitError("unknown rpcserialversion requested.");
- nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
+ nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
- fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
- if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
+ fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
+ if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) {
// Minimal effort at forwards compatibility
- std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
+ std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible
std::vector<std::string> vstrReplacementModes;
boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
@@ -1198,7 +1189,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
#ifndef WIN32
CreatePidFile(GetPidFile(), getpid());
#endif
- if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
+ if (gArgs.GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
// Do this first since it both loads a bunch of debug.log into memory,
// and because this needs to happen before any other debug.log printing
ShrinkDebugFile();
@@ -1211,7 +1202,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
LogPrintf("Using data directory %s\n", GetDataDir().string());
- LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
+ LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
InitSignatureCache();
@@ -1234,7 +1225,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
* that the server is there and will be ready later). Warmup mode will
* be disabled when initialisation is finished.
*/
- if (GetBoolArg("-server", false))
+ if (gArgs.GetBoolArg("-server", false))
{
uiInterface.InitMessage.connect(SetRPCWarmupStatus);
if (!AppInitServers(threadGroup))
@@ -1245,7 +1236,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// ********************************************************* Step 5: verify wallet database integrity
#ifdef ENABLE_WALLET
- if (!CWallet::Verify())
+ if (!WalletVerify())
return false;
#endif
// ********************************************************* Step 6: network initialization
@@ -1291,12 +1282,12 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
// Check for host lookup allowed before parsing any network related parameters
- fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
+ fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
- bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
+ bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
// -proxy sets a proxy for all outgoing network traffic
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
- std::string proxyArg = GetArg("-proxy", "");
+ std::string proxyArg = gArgs.GetArg("-proxy", "");
SetLimited(NET_TOR);
if (proxyArg != "" && proxyArg != "0") {
CService proxyAddr;
@@ -1318,7 +1309,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
// -noonion (or -onion=0) disables connecting to .onion entirely
// An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
- std::string onionArg = GetArg("-onion", "");
+ std::string onionArg = gArgs.GetArg("-onion", "");
if (onionArg != "") {
if (onionArg == "0") { // Handle -noonion/-onion=0
SetLimited(NET_TOR); // set onions as unreachable
@@ -1336,9 +1327,9 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
// see Step 2: parameter interactions for more information about these
- fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
- fDiscover = GetBoolArg("-discover", true);
- fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
+ fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
+ fDiscover = gArgs.GetBoolArg("-discover", true);
+ fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
CService addrLocal;
@@ -1358,27 +1349,27 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
- if (IsArgSet("-maxuploadtarget")) {
- nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
+ if (gArgs.IsArgSet("-maxuploadtarget")) {
+ nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
}
// ********************************************************* Step 7: load block chain
- fReindex = GetBoolArg("-reindex", false);
- bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
+ fReindex = gArgs.GetBoolArg("-reindex", false);
+ bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
// cache size calculations
- int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
+ int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
int64_t nBlockTreeDBCache = nTotalCache / 8;
- nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
+ nBlockTreeDBCache = std::min(nBlockTreeDBCache, (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
nTotalCache -= nBlockTreeDBCache;
int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
nTotalCache -= nCoinDBCache;
nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
- int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
@@ -1427,8 +1418,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Check for changed -txindex state
- if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
- strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
+ if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
+ strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
@@ -1493,7 +1484,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
if (!is_coinsview_empty) {
uiInterface.InitMessage(_("Verifying blocks..."));
- if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
+ if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
MIN_BLOCKS_TO_KEEP);
}
@@ -1510,8 +1501,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
}
- if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
- GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
+ if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
+ gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
strLoadError = _("Corrupted block database detected");
break;
}
@@ -1566,7 +1557,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET
- if (!CWallet::InitLoadWallet())
+ if (!InitLoadWallet())
return false;
#else
LogPrintf("No wallet support compiled in!\n");
@@ -1610,7 +1601,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fHaveGenesis = true;
}
- if (IsArgSet("-blocknotify"))
+ if (gArgs.IsArgSet("-blocknotify"))
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
std::vector<fs::path> vImportFiles;
@@ -1634,13 +1625,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
//// debug print
LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
LogPrintf("nBestHeight = %d\n", chainActive.Height());
- if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
+ if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
StartTorControl(threadGroup, scheduler);
Discover(threadGroup);
// Map ports with UPnP
- MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
+ MapPort(gArgs.GetBoolArg("-upnp", DEFAULT_UPNP));
CConnman::Options connOptions;
connOptions.nLocalServices = nLocalServices;
@@ -1651,8 +1642,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
connOptions.nMaxFeeler = 1;
connOptions.nBestHeight = chainActive.Height();
connOptions.uiInterface = &uiInterface;
- connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
- connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
+ connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
+ connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
diff --git a/src/key.h b/src/key.h
index 2c6f151727..151e63531b 100644
--- a/src/key.h
+++ b/src/key.h
@@ -172,6 +172,8 @@ struct CExtKey {
{
unsigned int len = ::ReadCompactSize(s);
unsigned char code[BIP32_EXTKEY_SIZE];
+ if (len != BIP32_EXTKEY_SIZE)
+ throw std::runtime_error("Invalid extended key size\n");
s.read((char *)&code[0], len);
Decode(code);
}
diff --git a/src/keystore.h b/src/keystore.h
index 965ae0c79a..528b6e0834 100644
--- a/src/keystore.h
+++ b/src/keystore.h
@@ -97,14 +97,14 @@ public:
}
return false;
}
- virtual bool AddCScript(const CScript& redeemScript) override;
- virtual bool HaveCScript(const CScriptID &hash) const override;
- virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const override;
+ bool AddCScript(const CScript& redeemScript) override;
+ bool HaveCScript(const CScriptID &hash) const override;
+ bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const override;
- virtual bool AddWatchOnly(const CScript &dest) override;
- virtual bool RemoveWatchOnly(const CScript &dest) override;
- virtual bool HaveWatchOnly(const CScript &dest) const override;
- virtual bool HaveWatchOnly() const override;
+ bool AddWatchOnly(const CScript &dest) override;
+ bool RemoveWatchOnly(const CScript &dest) override;
+ bool HaveWatchOnly(const CScript &dest) const override;
+ bool HaveWatchOnly() const override;
};
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
diff --git a/src/limitedmap.h b/src/limitedmap.h
index e9dcb6defd..7afc8b458d 100644
--- a/src/limitedmap.h
+++ b/src/limitedmap.h
@@ -27,7 +27,7 @@ protected:
size_type nMaxSize;
public:
- limitedmap(size_type nMaxSizeIn)
+ explicit limitedmap(size_type nMaxSizeIn)
{
assert(nMaxSizeIn > 0);
nMaxSize = nMaxSizeIn;
diff --git a/src/merkleblock.h b/src/merkleblock.h
index f590c487de..20f2b36886 100644
--- a/src/merkleblock.h
+++ b/src/merkleblock.h
@@ -63,7 +63,7 @@ protected:
bool fBad;
/** helper function to efficiently calculate the number of nodes at given height in the merkle tree */
- unsigned int CalcTreeWidth(int height) {
+ unsigned int CalcTreeWidth(int height) const {
return (nTransactions+(1 << height)-1) >> height;
}
diff --git a/src/miner.cpp b/src/miner.cpp
index 79016bfd3e..f1942ec570 100644
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -88,20 +88,20 @@ static BlockAssembler::Options DefaultOptions(const CChainParams& params)
options.nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
options.nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
bool fWeightSet = false;
- if (IsArgSet("-blockmaxweight")) {
- options.nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
+ if (gArgs.IsArgSet("-blockmaxweight")) {
+ options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
options.nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
fWeightSet = true;
}
- if (IsArgSet("-blockmaxsize")) {
- options.nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
+ if (gArgs.IsArgSet("-blockmaxsize")) {
+ options.nBlockMaxSize = gArgs.GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
if (!fWeightSet) {
options.nBlockMaxWeight = options.nBlockMaxSize * WITNESS_SCALE_FACTOR;
}
}
- if (IsArgSet("-blockmintxfee")) {
+ if (gArgs.IsArgSet("-blockmintxfee")) {
CAmount n = 0;
- ParseMoney(GetArg("-blockmintxfee", ""), n);
+ ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
options.blockMinFeeRate = CFeeRate(n);
} else {
options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
@@ -151,7 +151,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
- pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
+ pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
@@ -224,7 +224,7 @@ void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
}
}
-bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
+bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
@@ -272,7 +272,7 @@ void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
nFees += iter->GetFee();
inBlock.insert(iter);
- bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
+ bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
LogPrintf("fee %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
diff --git a/src/miner.h b/src/miner.h
index 5c9cfd78f0..abd2ff6199 100644
--- a/src/miner.h
+++ b/src/miner.h
@@ -11,8 +11,8 @@
#include <stdint.h>
#include <memory>
-#include "boost/multi_index_container.hpp"
-#include "boost/multi_index/ordered_index.hpp"
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/ordered_index.hpp>
class CBlockIndex;
class CChainParams;
@@ -33,7 +33,7 @@ struct CBlockTemplate
// Container for tracking updates to ancestor feerate as we include (parent)
// transactions in a block
struct CTxMemPoolModifiedEntry {
- CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
+ explicit CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
{
iter = entry;
nSizeWithAncestors = entry->GetSizeWithAncestors();
@@ -116,7 +116,7 @@ typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator
struct update_for_parent_inclusion
{
- update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
+ explicit update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
void operator() (CTxMemPoolModifiedEntry &e)
{
@@ -164,7 +164,7 @@ public:
CFeeRate blockMinFeeRate;
};
- BlockAssembler(const CChainParams& params);
+ explicit BlockAssembler(const CChainParams& params);
BlockAssembler(const CChainParams& params, const Options& options);
/** Construct a new block template with coinbase to scriptPubKeyIn */
@@ -187,7 +187,7 @@ private:
/** Remove confirmed (inBlock) entries from given set */
void onlyUnconfirmed(CTxMemPool::setEntries& testSet);
/** Test if a new package would "fit" in the block */
- bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost);
+ bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const;
/** Perform checks on each transaction in a package:
* locktime, premature-witness, serialized size (if necessary)
* These checks should always succeed, and they're here
diff --git a/src/net.cpp b/src/net.cpp
index 0ed2196063..1af317726a 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -101,7 +101,7 @@ void CConnman::AddOneShot(const std::string& strDest)
unsigned short GetListenPort()
{
- return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
+ return (unsigned short)(gArgs.GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
@@ -514,7 +514,7 @@ void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t ba
banEntry.banReason = banReason;
if (bantimeoffset <= 0)
{
- bantimeoffset = GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
+ bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
sinceUnixEpoch = false;
}
banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
@@ -1438,9 +1438,9 @@ void CConnman::WakeMessageHandler()
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
- const char * multicastif = 0;
- const char * minissdpdpath = 0;
- struct UPNPDev * devlist = 0;
+ const char * multicastif = nullptr;
+ const char * minissdpdpath = nullptr;
+ struct UPNPDev * devlist = nullptr;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
@@ -1510,13 +1510,13 @@ void ThreadMapPort()
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
- freeUPNPDevlist(devlist); devlist = 0;
+ freeUPNPDevlist(devlist); devlist = nullptr;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
- freeUPNPDevlist(devlist); devlist = 0;
+ freeUPNPDevlist(devlist); devlist = nullptr;
if (r != 0)
FreeUPNPUrls(&urls);
}
@@ -1575,7 +1575,7 @@ void CConnman::ThreadDNSAddressSeed()
// creating fewer identifying DNS requests, reduces trust by giving seeds
// less influence on the network topology, and reduces traffic to the seeds.
if ((addrman.size() > 0) &&
- (!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
+ (!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
if (!interruptNet.sleep_for(std::chrono::seconds(11)))
return;
@@ -2336,7 +2336,7 @@ bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
// Send and receive from sockets, accept connections
threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
- if (!GetBoolArg("-dnsseed", true))
+ if (!gArgs.GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 766618130c..596ae1139b 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -581,7 +581,7 @@ void UnregisterNodeSignals(CNodeSignals& nodeSignals)
void AddToCompactExtraTransactions(const CTransactionRef& tx)
{
- size_t max_extra_txn = GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
+ size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
if (max_extra_txn <= 0)
return;
if (!vExtraTxnForCompact.size())
@@ -704,7 +704,7 @@ void Misbehaving(NodeId pnode, int howmuch)
return;
state->nMisbehavior += howmuch;
- int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
+ int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
{
LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
@@ -1175,7 +1175,7 @@ inline void static SendBlockTransactions(const CBlock& block, const BlockTransac
bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
{
LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
- if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
+ if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
@@ -1541,7 +1541,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
bool fBlocksOnly = !fRelayTxes;
// Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
- if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
+ if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
fBlocksOnly = false;
LOCK(cs_main);
@@ -1782,7 +1782,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
{
// Stop processing the transaction early if
// We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
- if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
+ if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
{
LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
return true;
@@ -1901,7 +1901,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
AddOrphanTx(ptx, pfrom->GetId());
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
- unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
+ unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
if (nEvicted > 0) {
LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
@@ -1926,7 +1926,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
AddToCompactExtraTransactions(ptx);
}
- if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
+ if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
// Always relay transactions received from whitelisted peers, even
// if they were already in the mempool or rejected from it due
// to policy, allowing the node to function as a gateway for
@@ -2783,7 +2783,7 @@ class CompareInvMempoolOrder
{
CTxMemPool *mp;
public:
- CompareInvMempoolOrder(CTxMemPool *_mempool)
+ explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
{
mp = _mempool;
}
@@ -3297,9 +3297,9 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
// Message: feefilter
//
// We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
- if (pto->nVersion >= FEEFILTER_VERSION && GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
- !(pto->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
- CAmount currentFilter = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
+ if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
+ !(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
+ CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
int64_t timeNow = GetTimeMicros();
if (timeNow > pto->nextSendTimeFeeFilter) {
static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
diff --git a/src/net_processing.h b/src/net_processing.h
index db6d81e6b6..f4a43980a5 100644
--- a/src/net_processing.h
+++ b/src/net_processing.h
@@ -32,7 +32,7 @@ private:
CConnman* connman;
public:
- PeerLogicValidation(CConnman* connmanIn);
+ explicit PeerLogicValidation(CConnman* connmanIn);
void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected, const std::vector<CTransactionRef>& vtxConflicted) override;
void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override;
diff --git a/src/netaddress.h b/src/netaddress.h
index 57ce897db5..6ca99b36b5 100644
--- a/src/netaddress.h
+++ b/src/netaddress.h
@@ -36,7 +36,7 @@ class CNetAddr
public:
CNetAddr();
- CNetAddr(const struct in_addr& ipv4Addr);
+ explicit CNetAddr(const struct in_addr& ipv4Addr);
void Init();
void SetIP(const CNetAddr& ip);
@@ -82,7 +82,7 @@ class CNetAddr
std::vector<unsigned char> GetGroup() const;
int GetReachabilityFrom(const CNetAddr *paddrPartner = nullptr) const;
- CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
+ explicit CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
friend bool operator==(const CNetAddr& a, const CNetAddr& b);
@@ -146,7 +146,7 @@ class CService : public CNetAddr
CService();
CService(const CNetAddr& ip, unsigned short port);
CService(const struct in_addr& ipv4Addr, unsigned short port);
- CService(const struct sockaddr_in& addr);
+ explicit CService(const struct sockaddr_in& addr);
void Init();
unsigned short GetPort() const;
bool GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const;
@@ -160,7 +160,7 @@ class CService : public CNetAddr
std::string ToStringIPPort() const;
CService(const struct in6_addr& ipv6Addr, unsigned short port);
- CService(const struct sockaddr_in6& addr);
+ explicit CService(const struct sockaddr_in6& addr);
ADD_SERIALIZE_METHODS;
diff --git a/src/netbase.h b/src/netbase.h
index 941da31f9c..6572f0a12e 100644
--- a/src/netbase.h
+++ b/src/netbase.h
@@ -29,7 +29,7 @@ class proxyType
{
public:
proxyType(): randomize_credentials(false) {}
- proxyType(const CService &_proxy, bool _randomize_credentials=false): proxy(_proxy), randomize_credentials(_randomize_credentials) {}
+ explicit proxyType(const CService &_proxy, bool _randomize_credentials=false): proxy(_proxy), randomize_credentials(_randomize_credentials) {}
bool IsValid() const { return proxy.IsValid(); }
@@ -50,8 +50,8 @@ bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLoo
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions);
CService LookupNumeric(const char *pszName, int portDefault = 0);
bool LookupSubNet(const char *pszName, CSubNet& subnet);
-bool ConnectSocket(const CService &addr, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed = 0);
-bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed = 0);
+bool ConnectSocket(const CService &addr, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed = nullptr);
+bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed = nullptr);
/** Return readable error string for a network error code */
std::string NetworkErrorString(int err);
/** Close socket and set hSocket to INVALID_SOCKET */
diff --git a/src/netmessagemaker.h b/src/netmessagemaker.h
index 8e8a6e4a02..79b2501c5d 100644
--- a/src/netmessagemaker.h
+++ b/src/netmessagemaker.h
@@ -12,7 +12,7 @@
class CNetMsgMaker
{
public:
- CNetMsgMaker(int nVersionIn) : nVersion(nVersionIn){}
+ explicit CNetMsgMaker(int nVersionIn) : nVersion(nVersionIn){}
template <typename... Args>
CSerializedNetMsg Make(int nFlags, std::string sCommand, Args&&... args) const
diff --git a/src/policy/feerate.h b/src/policy/feerate.h
index 565da6c154..7e519e3efa 100644
--- a/src/policy/feerate.h
+++ b/src/policy/feerate.h
@@ -26,7 +26,6 @@ public:
explicit CFeeRate(const CAmount& _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { }
/** Constructor for a fee rate in satoshis per kB. The size in bytes must not exceed (2^63 - 1)*/
CFeeRate(const CAmount& nFeePaid, size_t nBytes);
- CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; }
/**
* Return the fee in satoshis for the given size in bytes.
*/
diff --git a/src/policy/fees.h b/src/policy/fees.h
index f4ef793643..6edaf28714 100644
--- a/src/policy/fees.h
+++ b/src/policy/fees.h
@@ -284,7 +284,7 @@ private:
public:
/** Create new FeeFilterRounder */
- FeeFilterRounder(const CFeeRate& minIncrementalFee);
+ explicit FeeFilterRounder(const CFeeRate& minIncrementalFee);
/** Quantize a minimum fee for privacy purpose before broadcast **/
CAmount round(CAmount currentMinFee);
diff --git a/src/prevector.h b/src/prevector.h
index f7bde8911a..eb29b3ae7e 100644
--- a/src/prevector.h
+++ b/src/prevector.h
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef _BITCOIN_PREVECTOR_H_
-#define _BITCOIN_PREVECTOR_H_
+#ifndef BITCOIN_PREVECTOR_H
+#define BITCOIN_PREVECTOR_H
#include <assert.h>
#include <stdlib.h>
@@ -514,4 +514,4 @@ public:
};
#pragma pack(pop)
-#endif
+#endif // BITCOIN_PREVECTOR_H
diff --git a/src/primitives/block.h b/src/primitives/block.h
index c90a1dfa64..292df40896 100644
--- a/src/primitives/block.h
+++ b/src/primitives/block.h
@@ -129,7 +129,7 @@ struct CBlockLocator
CBlockLocator() {}
- CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {}
+ explicit CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {}
ADD_SERIALIZE_METHODS;
diff --git a/src/protocol.h b/src/protocol.h
index 7890bb627d..67e01d9606 100644
--- a/src/protocol.h
+++ b/src/protocol.h
@@ -39,7 +39,7 @@ public:
};
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
- CMessageHeader(const MessageStartChars& pchMessageStartIn);
+ explicit CMessageHeader(const MessageStartChars& pchMessageStartIn);
CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn);
std::string GetCommand() const;
diff --git a/src/pubkey.h b/src/pubkey.h
index dbf0e23f20..65738d8fe2 100644
--- a/src/pubkey.h
+++ b/src/pubkey.h
@@ -30,7 +30,7 @@ class CKeyID : public uint160
{
public:
CKeyID() : uint160() {}
- CKeyID(const uint160& in) : uint160(in) {}
+ explicit CKeyID(const uint160& in) : uint160(in) {}
};
typedef uint256 ChainCode;
@@ -88,7 +88,7 @@ public:
}
//! Construct a public key from a byte vector.
- CPubKey(const std::vector<unsigned char>& _vch)
+ explicit CPubKey(const std::vector<unsigned char>& _vch)
{
Set(_vch.begin(), _vch.end());
}
diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp
index b6cfdf8887..3fd58a2f9a 100644
--- a/src/qt/bitcoin.cpp
+++ b/src/qt/bitcoin.cpp
@@ -106,7 +106,7 @@ static QString GetLangTerritory()
if(!lang_territory_qsettings.isEmpty())
lang_territory = lang_territory_qsettings;
// 3) -lang command line argument
- lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString()));
+ lang_territory = QString::fromStdString(gArgs.GetArg("-lang", lang_territory.toStdString()));
return lang_territory;
}
@@ -227,7 +227,7 @@ public:
void requestShutdown();
/// Get process return value
- int getReturnValue() { return returnValue; }
+ int getReturnValue() const { return returnValue; }
/// Get window identifier of QMainWindow (BitcoinGUI)
WId getMainWinId() const;
@@ -345,7 +345,7 @@ BitcoinApplication::BitcoinApplication(int &argc, char **argv):
// This must be done inside the BitcoinApplication constructor, or after it, because
// PlatformStyle::instantiate requires a QApplication
std::string platformName;
- platformName = GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
+ platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName));
if (!platformStyle) // Fall back to "other" if specified name not found
platformStyle = PlatformStyle::instantiate("other");
@@ -498,7 +498,7 @@ void BitcoinApplication::initializeResult(bool success)
#endif
// If -min option passed, start window minimized.
- if(GetBoolArg("-min", false))
+ if(gArgs.GetBoolArg("-min", false))
{
window->showMinimized();
}
@@ -550,7 +550,7 @@ int main(int argc, char *argv[])
/// 1. Parse command-line options. These take precedence over anything else.
// Command-line options take precedence:
- ParseParameters(argc, argv);
+ gArgs.ParseParameters(argc, argv);
// Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
@@ -606,9 +606,9 @@ int main(int argc, char *argv[])
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
- if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
+ if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version"))
{
- HelpMessageDialog help(nullptr, IsArgSet("-version"));
+ HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version"));
help.showOrPrint();
return EXIT_SUCCESS;
}
@@ -623,11 +623,11 @@ int main(int argc, char *argv[])
if (!fs::is_directory(GetDataDir(false)))
{
QMessageBox::critical(0, QObject::tr(PACKAGE_NAME),
- QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(GetArg("-datadir", ""))));
+ QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(gArgs.GetArg("-datadir", ""))));
return EXIT_FAILURE;
}
try {
- ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
+ gArgs.ReadConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
QMessageBox::critical(0, QObject::tr(PACKAGE_NAME),
QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
@@ -691,12 +691,12 @@ int main(int argc, char *argv[])
// Allow parameter interaction before we create the options model
app.parameterSetup();
// Load GUI settings from QSettings
- app.createOptionsModel(IsArgSet("-resetguisettings"));
+ app.createOptionsModel(gArgs.IsArgSet("-resetguisettings"));
// Subscribe to global signals from core
uiInterface.InitMessage.connect(InitMessage);
- if (GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !GetBoolArg("-min", false))
+ if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());
int rv = EXIT_SUCCESS;
diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp
index e3970298e6..be2d21daee 100644
--- a/src/qt/bitcoingui.cpp
+++ b/src/qt/bitcoingui.cpp
@@ -454,6 +454,7 @@ void BitcoinGUI::createToolBars()
if(walletFrame)
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
+ toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
toolbar->setMovable(false);
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
diff --git a/src/qt/callback.h b/src/qt/callback.h
index a8b593a652..da6b0c4c2e 100644
--- a/src/qt/callback.h
+++ b/src/qt/callback.h
@@ -16,7 +16,7 @@ class FunctionCallback : public Callback
F f;
public:
- FunctionCallback(F f_) : f(std::move(f_)) {}
+ explicit FunctionCallback(F f_) : f(std::move(f_)) {}
~FunctionCallback() override {}
void call() override { f(this); }
};
diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp
index f3ee0fbe39..562c361799 100644
--- a/src/qt/coincontroldialog.cpp
+++ b/src/qt/coincontroldialog.cpp
@@ -18,6 +18,7 @@
#include "policy/fees.h"
#include "policy/policy.h"
#include "validation.h" // For mempool
+#include "wallet/fees.h"
#include "wallet/wallet.h"
#include <QApplication>
@@ -510,7 +511,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
nBytes -= 34;
// Fee
- nPayFee = CWallet::GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
+ nPayFee = GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
if (nPayAmount > 0)
{
diff --git a/src/qt/coincontroldialog.h b/src/qt/coincontroldialog.h
index 99a9f893ff..4949c91771 100644
--- a/src/qt/coincontroldialog.h
+++ b/src/qt/coincontroldialog.h
@@ -30,9 +30,9 @@ namespace Ui {
class CCoinControlWidgetItem : public QTreeWidgetItem
{
public:
- CCoinControlWidgetItem(QTreeWidget *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
- CCoinControlWidgetItem(int type = Type) : QTreeWidgetItem(type) {}
- CCoinControlWidgetItem(QTreeWidgetItem *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
+ explicit CCoinControlWidgetItem(QTreeWidget *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
+ explicit CCoinControlWidgetItem(int type = Type) : QTreeWidgetItem(type) {}
+ explicit CCoinControlWidgetItem(QTreeWidgetItem *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
bool operator<(const QTreeWidgetItem &other) const;
};
diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp
index 28ffda9981..f3c5daebec 100644
--- a/src/qt/guiutil.cpp
+++ b/src/qt/guiutil.cpp
@@ -651,7 +651,7 @@ bool SetStartOnSystemStartup(bool fAutoStart)
// Start client minimized
QString strArgs = "-min";
// Set -testnet /-regtest options
- strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false)));
+ strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false)));
#ifdef UNICODE
boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
@@ -760,7 +760,7 @@ bool SetStartOnSystemStartup(bool fAutoStart)
optionFile << "Name=Bitcoin\n";
else
optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
- optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false));
+ optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false));
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp
index 231a715753..0ff95d8502 100644
--- a/src/qt/intro.cpp
+++ b/src/qt/intro.cpp
@@ -43,7 +43,7 @@ class FreespaceChecker : public QObject
Q_OBJECT
public:
- FreespaceChecker(Intro *intro);
+ explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
@@ -131,7 +131,7 @@ Intro::Intro(QWidget *parent) :
);
ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));
- uint64_t pruneTarget = std::max<int64_t>(0, GetArg("-prune", 0));
+ uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0));
requiredSpace = BLOCK_CHAIN_SIZE;
QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
if (pruneTarget) {
@@ -191,14 +191,14 @@ bool Intro::pickDataDirectory()
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
- if(!GetArg("-datadir", "").empty())
+ if(!gArgs.GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
- if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || GetBoolArg("-resetguisettings", false))
+ if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
@@ -231,7 +231,7 @@ bool Intro::pickDataDirectory()
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
- SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
+ gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
return true;
}
diff --git a/src/qt/macdockiconhandler.mm b/src/qt/macdockiconhandler.mm
index a41d39d51e..9e7de0f98f 100644
--- a/src/qt/macdockiconhandler.mm
+++ b/src/qt/macdockiconhandler.mm
@@ -18,7 +18,7 @@
extern void qt_mac_set_dock_menu(QMenu *);
#endif
-static MacDockIconHandler *s_instance = NULL;
+static MacDockIconHandler *s_instance = nullptr;
bool dockClickHandler(id self,SEL _cmd,...) {
Q_UNUSED(self)
@@ -34,7 +34,7 @@ void setupDockClickHandler() {
Class cls = objc_getClass("NSApplication");
id appInst = objc_msgSend((id)cls, sel_registerName("sharedApplication"));
- if (appInst != NULL) {
+ if (appInst != nullptr) {
id delegate = objc_msgSend(appInst, sel_registerName("delegate"));
Class delClass = (Class)objc_msgSend(delegate, sel_registerName("class"));
SEL shouldHandle = sel_registerName("applicationShouldHandleReopen:hasVisibleWindows:");
@@ -53,7 +53,7 @@ MacDockIconHandler::MacDockIconHandler() : QObject()
setupDockClickHandler();
this->m_dummyWidget = new QWidget();
this->m_dockMenu = new QMenu(this->m_dummyWidget);
- this->setMainWindow(NULL);
+ this->setMainWindow(nullptr);
#if QT_VERSION < 0x050000
qt_mac_set_dock_menu(this->m_dockMenu);
#elif QT_VERSION >= 0x050200
@@ -69,7 +69,7 @@ void MacDockIconHandler::setMainWindow(QMainWindow *window) {
MacDockIconHandler::~MacDockIconHandler()
{
delete this->m_dummyWidget;
- this->setMainWindow(NULL);
+ this->setMainWindow(nullptr);
}
QMenu *MacDockIconHandler::dockMenu()
diff --git a/src/qt/macnotificationhandler.mm b/src/qt/macnotificationhandler.mm
index dd3f622818..4c96d08c8a 100644
--- a/src/qt/macnotificationhandler.mm
+++ b/src/qt/macnotificationhandler.mm
@@ -75,7 +75,7 @@ bool MacNotificationHandler::hasUserNotificationCenterSupport(void)
MacNotificationHandler *MacNotificationHandler::instance()
{
- static MacNotificationHandler *s_instance = NULL;
+ static MacNotificationHandler *s_instance = nullptr;
if (!s_instance) {
s_instance = new MacNotificationHandler();
diff --git a/src/qt/modaloverlay.h b/src/qt/modaloverlay.h
index 21ccdbd839..cda23f9540 100644
--- a/src/qt/modaloverlay.h
+++ b/src/qt/modaloverlay.h
@@ -32,7 +32,7 @@ public Q_SLOTS:
// will show or hide the modal layer
void showHide(bool hide = false, bool userRequested = false);
void closeClicked();
- bool isLayerVisible() { return layerIsVisible; }
+ bool isLayerVisible() const { return layerIsVisible; }
protected:
bool eventFilter(QObject * obj, QEvent * ev);
diff --git a/src/qt/networkstyle.cpp b/src/qt/networkstyle.cpp
index 93092501c9..4b81c54d36 100644
--- a/src/qt/networkstyle.cpp
+++ b/src/qt/networkstyle.cpp
@@ -44,7 +44,7 @@ NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift,
// loop through pixels
for(int x=0;x<img.width();x++)
{
- // preserve alpha because QColor::getHsl doesen't return the alpha value
+ // preserve alpha because QColor::getHsl doesn't return the alpha value
a = qAlpha(scL[x]);
QColor col(scL[x]);
diff --git a/src/qt/notificator.cpp b/src/qt/notificator.cpp
index 8718929c6a..a7a7a4ce11 100644
--- a/src/qt/notificator.cpp
+++ b/src/qt/notificator.cpp
@@ -93,7 +93,7 @@ class FreedesktopImage
{
public:
FreedesktopImage() {}
- FreedesktopImage(const QImage &img);
+ explicit FreedesktopImage(const QImage &img);
static int metaType();
diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp
index b80b6541dd..53e2e5053c 100644
--- a/src/qt/optionsdialog.cpp
+++ b/src/qt/optionsdialog.cpp
@@ -17,10 +17,6 @@
#include "netbase.h"
#include "txdb.h" // for -dbcache defaults
-#ifdef ENABLE_WALLET
-#include "wallet/wallet.h" // for CWallet::GetRequiredFee()
-#endif
-
#include <QDataWidgetMapper>
#include <QDir>
#include <QIntValidator>
@@ -80,6 +76,8 @@ OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) :
ui->bitcoinAtStartup->setToolTip(ui->bitcoinAtStartup->toolTip().arg(tr(PACKAGE_NAME)));
ui->bitcoinAtStartup->setText(ui->bitcoinAtStartup->text().arg(tr(PACKAGE_NAME)));
+ ui->openBitcoinConfButton->setToolTip(ui->openBitcoinConfButton->toolTip().arg(tr(PACKAGE_NAME)));
+
ui->lang->setToolTip(ui->lang->toolTip().arg(tr(PACKAGE_NAME)));
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
for (const QString &langStr : translations.entryList())
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index d6e740ee9c..e9960a01b1 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -36,7 +36,7 @@ OptionsModel::OptionsModel(QObject *parent, bool resetSettings) :
void OptionsModel::addOverriddenOption(const std::string &option)
{
- strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(GetArg(option, "")) + " ";
+ strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(gArgs.GetArg(option, "")) + " ";
}
// Writes all missing QSettings with their default values
@@ -86,18 +86,18 @@ void OptionsModel::Init(bool resetSettings)
//
// If setting doesn't exist create it with defaults.
//
- // If SoftSetArg() or SoftSetBoolArg() return false we were overridden
+ // If gArgs.SoftSetArg() or gArgs.SoftSetBoolArg() return false we were overridden
// by command-line and show this in the UI.
// Main
if (!settings.contains("nDatabaseCache"))
settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache);
- if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
+ if (!gArgs.SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
addOverriddenOption("-dbcache");
if (!settings.contains("nThreadsScriptVerif"))
settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS);
- if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
+ if (!gArgs.SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
addOverriddenOption("-par");
if (!settings.contains("strDataDir"))
@@ -107,19 +107,19 @@ void OptionsModel::Init(bool resetSettings)
#ifdef ENABLE_WALLET
if (!settings.contains("bSpendZeroConfChange"))
settings.setValue("bSpendZeroConfChange", true);
- if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
+ if (!gArgs.SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
addOverriddenOption("-spendzeroconfchange");
#endif
// Network
if (!settings.contains("fUseUPnP"))
settings.setValue("fUseUPnP", DEFAULT_UPNP);
- if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
+ if (!gArgs.SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
addOverriddenOption("-upnp");
if (!settings.contains("fListen"))
settings.setValue("fListen", DEFAULT_LISTEN);
- if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
+ if (!gArgs.SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
addOverriddenOption("-listen");
if (!settings.contains("fUseProxy"))
@@ -127,9 +127,9 @@ void OptionsModel::Init(bool resetSettings)
if (!settings.contains("addrProxy"))
settings.setValue("addrProxy", "127.0.0.1:9050");
// Only try to set -proxy, if user has enabled fUseProxy
- if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
+ if (settings.value("fUseProxy").toBool() && !gArgs.SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
addOverriddenOption("-proxy");
- else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty())
+ else if(!settings.value("fUseProxy").toBool() && !gArgs.GetArg("-proxy", "").empty())
addOverriddenOption("-proxy");
if (!settings.contains("fUseSeparateProxyTor"))
@@ -137,15 +137,15 @@ void OptionsModel::Init(bool resetSettings)
if (!settings.contains("addrSeparateProxyTor"))
settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050");
// Only try to set -onion, if user has enabled fUseSeparateProxyTor
- if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString()))
+ if (settings.value("fUseSeparateProxyTor").toBool() && !gArgs.SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString()))
addOverriddenOption("-onion");
- else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty())
+ else if(!settings.value("fUseSeparateProxyTor").toBool() && !gArgs.GetArg("-onion", "").empty())
addOverriddenOption("-onion");
// Display
if (!settings.contains("language"))
settings.setValue("language", "");
- if (!SoftSetArg("-lang", settings.value("language").toString().toStdString()))
+ if (!gArgs.SoftSetArg("-lang", settings.value("language").toString().toStdString()))
addOverriddenOption("-lang");
language = settings.value("language").toString();
@@ -441,7 +441,7 @@ void OptionsModel::setRestartRequired(bool fRequired)
return settings.setValue("fRestartRequired", fRequired);
}
-bool OptionsModel::isRestartRequired()
+bool OptionsModel::isRestartRequired() const
{
QSettings settings;
return settings.value("fRestartRequired", false).toBool();
diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h
index 78529fbdcc..0ac82a4148 100644
--- a/src/qt/optionsmodel.h
+++ b/src/qt/optionsmodel.h
@@ -59,18 +59,18 @@ public:
void setDisplayUnit(const QVariant &value);
/* Explicit getters */
- bool getHideTrayIcon() { return fHideTrayIcon; }
- bool getMinimizeToTray() { return fMinimizeToTray; }
- bool getMinimizeOnClose() { return fMinimizeOnClose; }
- int getDisplayUnit() { return nDisplayUnit; }
- QString getThirdPartyTxUrls() { return strThirdPartyTxUrls; }
+ bool getHideTrayIcon() const { return fHideTrayIcon; }
+ bool getMinimizeToTray() const { return fMinimizeToTray; }
+ bool getMinimizeOnClose() const { return fMinimizeOnClose; }
+ int getDisplayUnit() const { return nDisplayUnit; }
+ QString getThirdPartyTxUrls() const { return strThirdPartyTxUrls; }
bool getProxySettings(QNetworkProxy& proxy) const;
- bool getCoinControlFeatures() { return fCoinControlFeatures; }
+ bool getCoinControlFeatures() const { return fCoinControlFeatures; }
const QString& getOverriddenByCommandLine() { return strOverriddenByCommandLine; }
/* Restart flag helper */
void setRestartRequired(bool fRequired);
- bool isRestartRequired();
+ bool isRestartRequired() const;
private:
/* Qt-only settings */
diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp
index ba344f4dbf..ba1839e7b4 100644
--- a/src/qt/overviewpage.cpp
+++ b/src/qt/overviewpage.cpp
@@ -25,7 +25,7 @@ class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
- TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):
+ explicit TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):
QAbstractItemDelegate(parent), unit(BitcoinUnits::BTC),
platformStyle(_platformStyle)
{
diff --git a/src/qt/paymentrequestplus.cpp b/src/qt/paymentrequestplus.cpp
index 897762b1a7..d3799f59ab 100644
--- a/src/qt/paymentrequestplus.cpp
+++ b/src/qt/paymentrequestplus.cpp
@@ -22,7 +22,7 @@
class SSLVerifyError : public std::runtime_error
{
public:
- SSLVerifyError(std::string err) : std::runtime_error(err) { }
+ explicit SSLVerifyError(std::string err) : std::runtime_error(err) { }
};
bool PaymentRequestPlus::parse(const QByteArray& data)
@@ -145,7 +145,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
int error = X509_STORE_CTX_get_error(store_ctx);
// For testing payment requests, we allow self signed root certs!
// This option is just shown in the UI options, if -help-debug is enabled.
- if (!(error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && GetBoolArg("-allowselfsignedrootcertificates", DEFAULT_SELFSIGNED_ROOTCERTS))) {
+ if (!(error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && gArgs.GetBoolArg("-allowselfsignedrootcertificates", DEFAULT_SELFSIGNED_ROOTCERTS))) {
throw SSLVerifyError(X509_verify_cert_error_string(error));
} else {
qDebug() << "PaymentRequestPlus::getMerchant: Allowing self signed root certificate, because -allowselfsignedrootcertificates is true.";
diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp
index c5e2b78c54..d4137d280f 100644
--- a/src/qt/paymentserver.cpp
+++ b/src/qt/paymentserver.cpp
@@ -122,7 +122,7 @@ void PaymentServer::LoadRootCAs(X509_STORE* _store)
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
- QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
+ QString certFile = QString::fromStdString(gArgs.GetArg("-rootcertificates", "-system-"));
// Empty store
if (certFile.isEmpty()) {
@@ -620,7 +620,7 @@ void PaymentServer::fetchRequest(const QUrl& url)
netManager->get(netRequest);
}
-void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
+void PaymentServer::fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
diff --git a/src/qt/paymentserver.h b/src/qt/paymentserver.h
index 2fe6e3e7b1..98b2364b92 100644
--- a/src/qt/paymentserver.h
+++ b/src/qt/paymentserver.h
@@ -72,7 +72,7 @@ public:
static bool ipcSendCommandLine();
// parent should be QApplication object
- PaymentServer(QObject* parent, bool startLocalServer = true);
+ explicit PaymentServer(QObject* parent, bool startLocalServer = true);
~PaymentServer();
// Load root certificate authorities. Pass nullptr (default)
@@ -113,7 +113,7 @@ public Q_SLOTS:
void uiReady();
// Submit Payment message to a merchant, get back PaymentACK:
- void fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction);
+ void fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction);
// Handle an incoming URI, URI with local file scheme or file
void handleURIOrFile(const QString& s);
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index c59111abd5..a056e858a7 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -22,7 +22,7 @@
#include "ui_interface.h"
#include "txmempool.h"
#include "policy/fees.h"
-#include "wallet/wallet.h"
+#include "wallet/fees.h"
#include <QFontMetrics>
#include <QMessageBox>
@@ -185,7 +185,7 @@ void SendCoinsDialog::setModel(WalletModel *_model)
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(updateSmartFeeLabel()));
connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
- ui->customFee->setSingleStep(CWallet::GetRequiredFee(1000));
+ ui->customFee->setSingleStep(GetRequiredFee(1000));
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
@@ -610,7 +610,7 @@ void SendCoinsDialog::on_buttonMinimizeFee_clicked()
void SendCoinsDialog::setMinimumFee()
{
ui->radioCustomPerKilobyte->setChecked(true);
- ui->customFee->setValue(CWallet::GetRequiredFee(1000));
+ ui->customFee->setValue(GetRequiredFee(1000));
}
void SendCoinsDialog::updateFeeSectionControls()
@@ -643,7 +643,7 @@ void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the required fee of %1").arg(
- BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::GetRequiredFee(1000)) + "/kB")
+ BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), GetRequiredFee(1000)) + "/kB")
);
}
@@ -668,7 +668,7 @@ void SendCoinsDialog::updateSmartFeeLabel()
updateCoinControlState(coin_control);
coin_control.m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels
FeeCalculation feeCalc;
- CFeeRate feeRate = CFeeRate(CWallet::GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
+ CFeeRate feeRate = CFeeRate(GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
diff --git a/src/qt/test/paymentservertests.cpp b/src/qt/test/paymentservertests.cpp
index d9fb869821..c7830071ed 100644
--- a/src/qt/test/paymentservertests.cpp
+++ b/src/qt/test/paymentservertests.cpp
@@ -205,7 +205,7 @@ void PaymentServerTests::paymentServerTests()
delete server;
}
-void RecipientCatcher::getRecipient(SendCoinsRecipient r)
+void RecipientCatcher::getRecipient(const SendCoinsRecipient& r)
{
recipient = r;
}
diff --git a/src/qt/test/paymentservertests.h b/src/qt/test/paymentservertests.h
index 9ffcbb02ac..faf167f2c6 100644
--- a/src/qt/test/paymentservertests.h
+++ b/src/qt/test/paymentservertests.h
@@ -26,7 +26,7 @@ class RecipientCatcher : public QObject
Q_OBJECT
public Q_SLOTS:
- void getRecipient(SendCoinsRecipient r);
+ void getRecipient(const SendCoinsRecipient& r);
public:
SendCoinsRecipient recipient;
diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp
index fbad9e544a..00edd64f72 100644
--- a/src/qt/test/rpcnestedtests.cpp
+++ b/src/qt/test/rpcnestedtests.cpp
@@ -11,7 +11,6 @@
#include "rpc/register.h"
#include "rpc/server.h"
#include "rpcconsole.h"
-#include "test/testutil.h"
#include "test/test_bitcoin.h"
#include "univalue.h"
#include "util.h"
@@ -29,7 +28,7 @@ static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
static const CRPCCommand vRPCCommands[] =
{
- { "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} },
+ { "test", "rpcNestedTest", &rpcNestedTest_rpc, {} },
};
void RPCNestedTests::rpcNestedTests()
@@ -41,7 +40,7 @@ void RPCNestedTests::rpcNestedTests()
std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
QDir dir(QString::fromStdString(path));
dir.mkpath(".");
- ForceSetArg("-datadir", path);
+ gArgs.ForceSetArg("-datadir", path);
//mempool.setSanityCheck(1.0);
TestingSetup test;
@@ -69,13 +68,13 @@ void RPCNestedTests::rpcNestedTests()
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
- (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key
+ (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
- (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed
+ (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered);
diff --git a/src/qt/test/test_main.cpp b/src/qt/test/test_main.cpp
index 1b28a285f1..80a00a634a 100644
--- a/src/qt/test/test_main.cpp
+++ b/src/qt/test/test_main.cpp
@@ -57,7 +57,7 @@ int main(int argc, char *argv[])
bool fInvalid = false;
// Prefer the "minimal" platform for the test instead of the normal default
- // platform ("xcb", "windows", or "cocoa") so tests can't unintentially
+ // platform ("xcb", "windows", or "cocoa") so tests can't unintentionally
// interfere with any background GUIs and don't require extra resources.
#if defined(WIN32)
_putenv_s("QT_QPA_PLATFORM", "minimal");
diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp
index 2ece0d0f28..36d98ce49d 100644
--- a/src/qt/transactionrecord.cpp
+++ b/src/qt/transactionrecord.cpp
@@ -248,7 +248,7 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx)
status.needsUpdate = false;
}
-bool TransactionRecord::statusUpdateNeeded()
+bool TransactionRecord::statusUpdateNeeded() const
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != chainActive.Height() || status.needsUpdate;
diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h
index 59f681224f..a26e676142 100644
--- a/src/qt/transactionrecord.h
+++ b/src/qt/transactionrecord.h
@@ -140,7 +140,7 @@ public:
/** Return whether a status update is needed.
*/
- bool statusUpdateNeeded();
+ bool statusUpdateNeeded() const;
};
#endif // BITCOIN_QT_TRANSACTIONRECORD_H
diff --git a/src/qt/transactiontablemodel.h b/src/qt/transactiontablemodel.h
index 80aeb64c41..b1f81498b2 100644
--- a/src/qt/transactiontablemodel.h
+++ b/src/qt/transactiontablemodel.h
@@ -79,7 +79,7 @@ public:
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- bool processingQueuedTransactions() { return fProcessingQueuedTransactions; }
+ bool processingQueuedTransactions() const { return fProcessingQueuedTransactions; }
private:
CWallet* wallet;
diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp
index c9b344fbd8..5d8c23d13c 100644
--- a/src/qt/utilitydialog.cpp
+++ b/src/qt/utilitydialog.cpp
@@ -78,7 +78,7 @@ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
cursor.insertBlock();
std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
- const bool showDebug = GetBoolArg("-help-debug", false);
+ const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
if (showDebug) {
strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS));
diff --git a/src/qt/utilitydialog.h b/src/qt/utilitydialog.h
index acaa864148..738eeed136 100644
--- a/src/qt/utilitydialog.h
+++ b/src/qt/utilitydialog.h
@@ -41,7 +41,7 @@ class ShutdownWindow : public QWidget
Q_OBJECT
public:
- ShutdownWindow(QWidget *parent=0, Qt::WindowFlags f=0);
+ explicit ShutdownWindow(QWidget *parent=0, Qt::WindowFlags f=0);
static QWidget *showShutdownWindow(BitcoinGUI *window);
protected:
diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp
index 5b63af617d..a3f243a25f 100644
--- a/src/qt/walletmodel.cpp
+++ b/src/qt/walletmodel.cpp
@@ -577,10 +577,11 @@ void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vect
LOCK2(cs_main, wallet->cs_wallet);
for (const COutPoint& outpoint : vOutpoints)
{
- if (!wallet->mapWallet.count(outpoint.hash)) continue;
- int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
+ auto it = wallet->mapWallet.find(outpoint.hash);
+ if (it == wallet->mapWallet.end()) continue;
+ int nDepth = it->second.GetDepthInMainChain();
if (nDepth < 0) continue;
- COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true /* spendable */, true /* solvable */, true /* safe */);
+ COutput out(&it->second, outpoint.n, nDepth, true /* spendable */, true /* solvable */, true /* safe */);
vOutputs.push_back(out);
}
}
@@ -739,7 +740,7 @@ bool WalletModel::bumpFee(uint256 hash)
bool WalletModel::isWalletEnabled()
{
- return !GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET);
+ return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET);
}
bool WalletModel::hdEnabled() const
diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp
index 8bc9ef725e..eae2c27f8a 100644
--- a/src/qt/walletmodeltransaction.cpp
+++ b/src/qt/walletmodeltransaction.cpp
@@ -22,12 +22,12 @@ WalletModelTransaction::~WalletModelTransaction()
delete walletTransaction;
}
-QList<SendCoinsRecipient> WalletModelTransaction::getRecipients()
+QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const
{
return recipients;
}
-CWalletTx *WalletModelTransaction::getTransaction()
+CWalletTx *WalletModelTransaction::getTransaction() const
{
return walletTransaction;
}
@@ -37,7 +37,7 @@ unsigned int WalletModelTransaction::getTransactionSize()
return (!walletTransaction ? 0 : ::GetVirtualTransactionSize(*walletTransaction));
}
-CAmount WalletModelTransaction::getTransactionFee()
+CAmount WalletModelTransaction::getTransactionFee() const
{
return fee;
}
@@ -79,7 +79,7 @@ void WalletModelTransaction::reassignAmounts(int nChangePosRet)
}
}
-CAmount WalletModelTransaction::getTotalTransactionAmount()
+CAmount WalletModelTransaction::getTotalTransactionAmount() const
{
CAmount totalTransactionAmount = 0;
for (const SendCoinsRecipient &rcp : recipients)
diff --git a/src/qt/walletmodeltransaction.h b/src/qt/walletmodeltransaction.h
index 64922efada..d7ecd7aa8c 100644
--- a/src/qt/walletmodeltransaction.h
+++ b/src/qt/walletmodeltransaction.h
@@ -22,15 +22,15 @@ public:
explicit WalletModelTransaction(const QList<SendCoinsRecipient> &recipients);
~WalletModelTransaction();
- QList<SendCoinsRecipient> getRecipients();
+ QList<SendCoinsRecipient> getRecipients() const;
- CWalletTx *getTransaction();
+ CWalletTx *getTransaction() const;
unsigned int getTransactionSize();
void setTransactionFee(const CAmount& newFee);
- CAmount getTransactionFee();
+ CAmount getTransactionFee() const;
- CAmount getTotalTransactionAmount();
+ CAmount getTotalTransactionAmount() const;
void newPossibleKeyChange(CWallet *wallet);
CReserveKey *getPossibleKeyChange();
diff --git a/src/random.cpp b/src/random.cpp
index b004bfa91e..7e0e94439e 100644
--- a/src/random.cpp
+++ b/src/random.cpp
@@ -46,10 +46,10 @@
#include <openssl/err.h>
#include <openssl/rand.h>
-static void RandFailure()
+[[noreturn]] static void RandFailure()
{
LogPrintf("Failed to read randomness, aborting\n");
- abort();
+ std::abort();
}
static inline int64_t GetPerformanceCounter()
@@ -242,7 +242,7 @@ void GetOSRand(unsigned char *ent32)
}
#elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
// We need a fallback for OSX < 10.12
- if (&getentropy != NULL) {
+ if (&getentropy != nullptr) {
if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
RandFailure();
}
diff --git a/src/rest.cpp b/src/rest.cpp
index 6a4b005f90..154ee04eed 100644
--- a/src/rest.cpp
+++ b/src/rest.cpp
@@ -48,7 +48,7 @@ struct CCoin {
ADD_SERIALIZE_METHODS;
CCoin() : nHeight(0) {}
- CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
+ explicit CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
diff --git a/src/reverse_iterator.h b/src/reverse_iterator.h
index 46789e5417..ab467f07c9 100644
--- a/src/reverse_iterator.h
+++ b/src/reverse_iterator.h
@@ -17,7 +17,7 @@ class reverse_range
T &m_x;
public:
- reverse_range(T &x) : m_x(x) {}
+ explicit reverse_range(T &x) : m_x(x) {}
auto begin() const -> decltype(this->m_x.rbegin())
{
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index 701608e132..ef61e5a55d 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -125,7 +125,7 @@ UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool tx
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
- TxToUniv(*tx, uint256(), objTx);
+ TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());
txs.push_back(objTx);
}
else
@@ -944,9 +944,10 @@ UniValue gettxout(const JSONRPCRequest& request)
"gettxout \"txid\" n ( include_mempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
- "1. \"txid\" (string, required) The transaction id\n"
- "2. n (numeric, required) vout number\n"
- "3. include_mempool (boolean, optional) Whether to include the mempool\n"
+ "1. \"txid\" (string, required) The transaction id\n"
+ "2. \"n\" (numeric, required) vout number\n"
+ "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true."
+ " Note that an unspent output that is spent in the mempool won't appear.\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
@@ -1018,8 +1019,8 @@ UniValue gettxout(const JSONRPCRequest& request)
UniValue verifychain(const JSONRPCRequest& request)
{
- int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL);
- int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
+ int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
+ int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
"verifychain ( checklevel nblocks )\n"
@@ -1324,7 +1325,7 @@ UniValue mempoolInfoToJSON()
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
- size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
@@ -1343,7 +1344,7 @@ UniValue getmempoolinfo(const JSONRPCRequest& request)
" \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
- " \"mempoolminfee\": xxxxx (numeric) Minimum feerate (" + CURRENCY_UNIT + " per KB) for tx to be accepted\n"
+ " \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
@@ -1489,11 +1490,11 @@ UniValue getchaintxstats(const JSONRPCRequest& request)
const CBlockIndex* pindex;
int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month
- if (request.params.size() > 0 && !request.params[0].isNull()) {
+ if (!request.params[0].isNull()) {
blockcount = request.params[0].get_int();
}
- bool havehash = request.params.size() > 1 && !request.params[1].isNull();
+ bool havehash = !request.params[1].isNull();
uint256 hash;
if (havehash) {
hash = uint256S(request.params[1].get_str());
@@ -1532,35 +1533,35 @@ UniValue getchaintxstats(const JSONRPCRequest& request)
}
static const CRPCCommand commands[] =
-{ // category name actor (function) okSafe argNames
- // --------------------- ------------------------ ----------------------- ------ ----------
- { "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} },
- { "blockchain", "getchaintxstats", &getchaintxstats, true, {"nblocks", "blockhash"} },
- { "blockchain", "getbestblockhash", &getbestblockhash, true, {} },
- { "blockchain", "getblockcount", &getblockcount, true, {} },
- { "blockchain", "getblock", &getblock, true, {"blockhash","verbosity|verbose"} },
- { "blockchain", "getblockhash", &getblockhash, true, {"height"} },
- { "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose"} },
- { "blockchain", "getchaintips", &getchaintips, true, {} },
- { "blockchain", "getdifficulty", &getdifficulty, true, {} },
- { "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} },
- { "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} },
- { "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} },
- { "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} },
- { "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} },
- { "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} },
- { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} },
- { "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} },
- { "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} },
-
- { "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} },
+{ // category name actor (function) argNames
+ // --------------------- ------------------------ ----------------------- ----------
+ { "blockchain", "getblockchaininfo", &getblockchaininfo, {} },
+ { "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} },
+ { "blockchain", "getbestblockhash", &getbestblockhash, {} },
+ { "blockchain", "getblockcount", &getblockcount, {} },
+ { "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} },
+ { "blockchain", "getblockhash", &getblockhash, {"height"} },
+ { "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} },
+ { "blockchain", "getchaintips", &getchaintips, {} },
+ { "blockchain", "getdifficulty", &getdifficulty, {} },
+ { "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} },
+ { "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} },
+ { "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} },
+ { "blockchain", "getmempoolinfo", &getmempoolinfo, {} },
+ { "blockchain", "getrawmempool", &getrawmempool, {"verbose"} },
+ { "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} },
+ { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} },
+ { "blockchain", "pruneblockchain", &pruneblockchain, {"height"} },
+ { "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} },
+
+ { "blockchain", "preciousblock", &preciousblock, {"blockhash"} },
/* Not shown in help */
- { "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} },
- { "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} },
- { "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} },
- { "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} },
- { "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} },
+ { "hidden", "invalidateblock", &invalidateblock, {"blockhash"} },
+ { "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} },
+ { "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} },
+ { "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} },
+ { "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} },
};
void RegisterBlockchainRPCCommands(CRPCTable &t)
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index f498b5c8ea..73860f375f 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -336,7 +336,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
" n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
" ,...\n"
" ],\n"
- " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
+ " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
" \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
" \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
" \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
@@ -346,7 +346,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
" \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
" \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
" },\n"
- " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
+ " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)\n"
" \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
" \"target\" : \"xxxx\", (string) The hash target\n"
" \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
@@ -686,7 +686,7 @@ public:
bool found;
CValidationState state;
- submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
+ explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
protected:
void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
@@ -825,7 +825,7 @@ UniValue estimatesmartfee(const JSONRPCRequest& request)
" \"CONSERVATIVE\"\n"
"\nResult:\n"
"{\n"
- " \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in BTC)\n"
+ " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
" \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
" \"blocks\" : n (numeric) block number where estimate was found\n"
"}\n"
@@ -842,7 +842,7 @@ UniValue estimatesmartfee(const JSONRPCRequest& request)
RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
unsigned int conf_target = ParseConfirmTarget(request.params[0]);
bool conservative = true;
- if (request.params.size() > 1 && !request.params[1].isNull()) {
+ if (!request.params[1].isNull()) {
FeeEstimateMode fee_mode;
if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
@@ -884,7 +884,7 @@ UniValue estimaterawfee(const JSONRPCRequest& request)
"\nResult:\n"
"{\n"
" \"short\" : { (json object, optional) estimate for short time horizon\n"
- " \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in BTC)\n"
+ " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
" \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
" \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
" \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
@@ -967,20 +967,21 @@ UniValue estimaterawfee(const JSONRPCRequest& request)
}
static const CRPCCommand commands[] =
-{ // category name actor (function) okSafeMode
+{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
- { "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} },
- { "mining", "getmininginfo", &getmininginfo, true, {} },
- { "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","dummy","fee_delta"} },
- { "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} },
- { "mining", "submitblock", &submitblock, true, {"hexdata","dummy"} },
+ { "mining", "getnetworkhashps", &getnetworkhashps, {"nblocks","height"} },
+ { "mining", "getmininginfo", &getmininginfo, {} },
+ { "mining", "prioritisetransaction", &prioritisetransaction, {"txid","dummy","fee_delta"} },
+ { "mining", "getblocktemplate", &getblocktemplate, {"template_request"} },
+ { "mining", "submitblock", &submitblock, {"hexdata","dummy"} },
+
- { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} },
+ { "generating", "generatetoaddress", &generatetoaddress, {"nblocks","address","maxtries"} },
- { "util", "estimatefee", &estimatefee, true, {"nblocks"} },
- { "util", "estimatesmartfee", &estimatesmartfee, true, {"conf_target", "estimate_mode"} },
+ { "util", "estimatefee", &estimatefee, {"nblocks"} },
+ { "util", "estimatesmartfee", &estimatesmartfee, {"nblocks", "estimate_mode"} },
- { "hidden", "estimaterawfee", &estimaterawfee, true, {"conf_target", "threshold"} },
+ { "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} },
};
void RegisterMiningRPCCommands(CRPCTable &t)
diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp
index efff4a99ae..76eefabd29 100644
--- a/src/rpc/misc.cpp
+++ b/src/rpc/misc.cpp
@@ -125,7 +125,7 @@ class DescribeAddressVisitor : public boost::static_visitor<UniValue>
public:
CWallet * const pwallet;
- DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
+ explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
@@ -552,7 +552,7 @@ UniValue getmemoryinfo(const JSONRPCRequest& request)
+ HelpExampleRpc("getmemoryinfo", "")
);
- std::string mode = (request.params.size() < 1 || request.params[0].isNull()) ? "stats" : request.params[0].get_str();
+ std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
if (mode == "stats") {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
@@ -603,11 +603,11 @@ UniValue logging(const JSONRPCRequest& request)
}
uint32_t originalLogCategories = logCategories;
- if (request.params.size() > 0 && request.params[0].isArray()) {
+ if (request.params[0].isArray()) {
logCategories |= getCategoryMask(request.params[0]);
}
- if (request.params.size() > 1 && request.params[1].isArray()) {
+ if (request.params[1].isArray()) {
logCategories &= ~getCategoryMask(request.params[1]);
}
@@ -649,20 +649,20 @@ UniValue echo(const JSONRPCRequest& request)
}
static const CRPCCommand commands[] =
-{ // category name actor (function) okSafeMode
+{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
- { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */
- { "control", "getmemoryinfo", &getmemoryinfo, true, {"mode"} },
- { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */
- { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} },
- { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} },
- { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} },
+ { "control", "getinfo", &getinfo, {} }, /* uses wallet if enabled */
+ { "control", "getmemoryinfo", &getmemoryinfo, {"mode"} },
+ { "util", "validateaddress", &validateaddress, {"address"} }, /* uses wallet if enabled */
+ { "util", "createmultisig", &createmultisig, {"nrequired","keys"} },
+ { "util", "verifymessage", &verifymessage, {"address","signature","message"} },
+ { "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} },
/* Not shown in help */
- { "hidden", "setmocktime", &setmocktime, true, {"timestamp"}},
- { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
- { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
- { "hidden", "logging", &logging, true, {"include", "exclude"}},
+ { "hidden", "setmocktime", &setmocktime, {"timestamp"}},
+ { "hidden", "echo", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
+ { "hidden", "echojson", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
+ { "hidden", "logging", &logging, {"include", "exclude"}},
};
void RegisterMiscRPCCommands(CRPCTable &t)
diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
index e463a4eda4..7faf216047 100644
--- a/src/rpc/net.cpp
+++ b/src/rpc/net.cpp
@@ -193,7 +193,7 @@ UniValue getpeerinfo(const JSONRPCRequest& request)
UniValue addnode(const JSONRPCRequest& request)
{
std::string strCommand;
- if (request.params.size() == 2)
+ if (!request.params[1].isNull())
strCommand = request.params[1].get_str();
if (request.fHelp || request.params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
@@ -258,7 +258,7 @@ UniValue disconnectnode(const JSONRPCRequest& request)
bool success;
const UniValue &address_arg = request.params[0];
- const UniValue &id_arg = request.params.size() < 2 ? NullUniValue : request.params[1];
+ const UniValue &id_arg = request.params[1];
if (!address_arg.isNull() && id_arg.isNull()) {
/* handle disconnect-by-address */
@@ -311,7 +311,7 @@ UniValue getaddednodeinfo(const JSONRPCRequest& request)
std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo();
- if (request.params.size() == 1 && !request.params[0].isNull()) {
+ if (!request.params[0].isNull()) {
bool found = false;
for (const AddedNodeInfo& info : vInfo) {
if (info.strAddedNode == request.params[0].get_str()) {
@@ -490,7 +490,7 @@ UniValue getnetworkinfo(const JSONRPCRequest& request)
UniValue setban(const JSONRPCRequest& request)
{
std::string strCommand;
- if (request.params.size() >= 2)
+ if (!request.params[1].isNull())
strCommand = request.params[1].get_str();
if (request.fHelp || request.params.size() < 2 ||
(strCommand != "add" && strCommand != "remove"))
@@ -534,11 +534,11 @@ UniValue setban(const JSONRPCRequest& request)
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
int64_t banTime = 0; //use standard bantime if not specified
- if (request.params.size() >= 3 && !request.params[2].isNull())
+ if (!request.params[2].isNull())
banTime = request.params[2].get_int64();
bool absolute = false;
- if (request.params.size() == 4 && request.params[3].isTrue())
+ if (request.params[3].isTrue())
absolute = true;
isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute);
@@ -623,20 +623,20 @@ UniValue setnetworkactive(const JSONRPCRequest& request)
}
static const CRPCCommand commands[] =
-{ // category name actor (function) okSafeMode
+{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
- { "network", "getconnectioncount", &getconnectioncount, true, {} },
- { "network", "ping", &ping, true, {} },
- { "network", "getpeerinfo", &getpeerinfo, true, {} },
- { "network", "addnode", &addnode, true, {"node","command"} },
- { "network", "disconnectnode", &disconnectnode, true, {"address", "nodeid"} },
- { "network", "getaddednodeinfo", &getaddednodeinfo, true, {"node"} },
- { "network", "getnettotals", &getnettotals, true, {} },
- { "network", "getnetworkinfo", &getnetworkinfo, true, {} },
- { "network", "setban", &setban, true, {"subnet", "command", "bantime", "absolute"} },
- { "network", "listbanned", &listbanned, true, {} },
- { "network", "clearbanned", &clearbanned, true, {} },
- { "network", "setnetworkactive", &setnetworkactive, true, {"state"} },
+ { "network", "getconnectioncount", &getconnectioncount, {} },
+ { "network", "ping", &ping, {} },
+ { "network", "getpeerinfo", &getpeerinfo, {} },
+ { "network", "addnode", &addnode, {"node","command"} },
+ { "network", "disconnectnode", &disconnectnode, {"address", "nodeid"} },
+ { "network", "getaddednodeinfo", &getaddednodeinfo, {"node"} },
+ { "network", "getnettotals", &getnettotals, {} },
+ { "network", "getnetworkinfo", &getnetworkinfo, {} },
+ { "network", "setban", &setban, {"subnet", "command", "bantime", "absolute"} },
+ { "network", "listbanned", &listbanned, {} },
+ { "network", "clearbanned", &clearbanned, {} },
+ { "network", "setnetworkactive", &setnetworkactive, {"state"} },
};
void RegisterNetRPCCommands(CRPCTable &t)
diff --git a/src/rpc/protocol.cpp b/src/rpc/protocol.cpp
index 823a5775f6..dc6bcec382 100644
--- a/src/rpc/protocol.cpp
+++ b/src/rpc/protocol.cpp
@@ -66,9 +66,14 @@ static const std::string COOKIEAUTH_USER = "__cookie__";
/** Default name for auth cookie file */
static const std::string COOKIEAUTH_FILE = ".cookie";
-fs::path GetAuthCookieFile()
+/** Get name of RPC authentication cookie file */
+static fs::path GetAuthCookieFile(bool temp=false)
{
- fs::path path(GetArg("-rpccookiefile", COOKIEAUTH_FILE));
+ std::string arg = gArgs.GetArg("-rpccookiefile", COOKIEAUTH_FILE);
+ if (temp) {
+ arg += ".tmp";
+ }
+ fs::path path(arg);
if (!path.is_complete()) path = GetDataDir() / path;
return path;
}
@@ -84,14 +89,20 @@ bool GenerateAuthCookie(std::string *cookie_out)
* these are set to 077 in init.cpp unless overridden with -sysperms.
*/
std::ofstream file;
- fs::path filepath = GetAuthCookieFile();
- file.open(filepath.string().c_str());
+ fs::path filepath_tmp = GetAuthCookieFile(true);
+ file.open(filepath_tmp.string().c_str());
if (!file.is_open()) {
- LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath.string());
+ LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath_tmp.string());
return false;
}
file << cookie;
file.close();
+
+ fs::path filepath = GetAuthCookieFile(false);
+ if (!RenameOver(filepath_tmp, filepath)) {
+ LogPrintf("Unable to rename cookie authentication file %s to %s\n", filepath_tmp.string(), filepath.string());
+ return false;
+ }
LogPrintf("Generated RPC authentication cookie %s\n", filepath.string());
if (cookie_out)
diff --git a/src/rpc/protocol.h b/src/rpc/protocol.h
index 4bd4702d62..5c9c64f67d 100644
--- a/src/rpc/protocol.h
+++ b/src/rpc/protocol.h
@@ -91,8 +91,6 @@ UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const Un
std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id);
UniValue JSONRPCError(int code, const std::string& message);
-/** Get name of RPC authentication cookie file */
-fs::path GetAuthCookieFile();
/** Generate a new RPC authentication cookie and write it to disk */
bool GenerateAuthCookie(std::string *cookie_out);
/** Read the RPC authentication cookie from disk */
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 8100511854..27daefaf5a 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -16,6 +16,7 @@
#include "policy/policy.h"
#include "policy/rbf.h"
#include "primitives/transaction.h"
+#include "rpc/safemode.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/script_error.h"
@@ -41,7 +42,7 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
// Blockchain contextual information (confirmations and blocktime) is not
// available to code in bitcoin-common, so we query them here and push the
// data into the returned UniValue.
- TxToUniv(tx, uint256(), entry);
+ TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
@@ -160,13 +161,10 @@ UniValue getrawtransaction(const JSONRPCRequest& request)
: "No such mempool transaction. Use -txindex to enable blockchain transaction queries") +
". Use gettransaction for wallet transactions.");
- std::string strHex = EncodeHexTx(*tx, RPCSerializationFlags());
-
if (!fVerbose)
- return strHex;
+ return EncodeHexTx(*tx, RPCSerializationFlags());
UniValue result(UniValue::VOBJ);
- result.push_back(Pair("hex", strHex));
TxToJSON(*tx, hashBlock, result);
return result;
}
@@ -339,14 +337,14 @@ UniValue createrawtransaction(const JSONRPCRequest& request)
CMutableTransaction rawTx;
- if (request.params.size() > 2 && !request.params[2].isNull()) {
+ if (!request.params[2].isNull()) {
int64_t nLockTime = request.params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
- bool rbfOptIn = request.params.size() > 3 ? request.params[3].isTrue() : false;
+ bool rbfOptIn = request.params[3].isTrue();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
@@ -483,7 +481,7 @@ UniValue decoderawtransaction(const JSONRPCRequest& request)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
- TxToUniv(CTransaction(std::move(mtx)), uint256(), result);
+ TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
return result;
}
@@ -572,7 +570,7 @@ UniValue combinerawtransaction(const JSONRPCRequest& request)
" ]\n"
"\nResult:\n"
- "\"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
+ "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
"\nExamples:\n"
+ HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
@@ -706,6 +704,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
+ ObserveSafeMode();
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
#else
@@ -735,7 +734,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
- if (request.params.size() > 2 && !request.params[2].isNull()) {
+ if (!request.params[2].isNull()) {
fGivenKeys = true;
UniValue keys = request.params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
@@ -757,7 +756,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
#endif
// Add previous txouts given in the RPC call:
- if (request.params.size() > 1 && !request.params[1].isNull()) {
+ if (!request.params[1].isNull()) {
UniValue prevTxs = request.params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
@@ -828,7 +827,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
#endif
int nHashType = SIGHASH_ALL;
- if (request.params.size() > 3 && !request.params[3].isNull()) {
+ if (!request.params[3].isNull()) {
static std::map<std::string, int> mapSigHashValues = {
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
@@ -911,6 +910,7 @@ UniValue sendrawtransaction(const JSONRPCRequest& request)
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
+ ObserveSafeMode();
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
@@ -922,7 +922,7 @@ UniValue sendrawtransaction(const JSONRPCRequest& request)
const uint256& hashTx = tx->GetHash();
CAmount nMaxRawTxFee = maxTxFee;
- if (request.params.size() > 1 && request.params[1].get_bool())
+ if (!request.params[1].isNull() && request.params[1].get_bool())
nMaxRawTxFee = 0;
CCoinsViewCache &view = *pcoinsTip;
@@ -962,18 +962,18 @@ UniValue sendrawtransaction(const JSONRPCRequest& request)
}
static const CRPCCommand commands[] =
-{ // category name actor (function) okSafeMode
+{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
- { "rawtransactions", "getrawtransaction", &getrawtransaction, true, {"txid","verbose"} },
- { "rawtransactions", "createrawtransaction", &createrawtransaction, true, {"inputs","outputs","locktime","replaceable"} },
- { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true, {"hexstring"} },
- { "rawtransactions", "decodescript", &decodescript, true, {"hexstring"} },
- { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false, {"hexstring","allowhighfees"} },
- { "rawtransactions", "combinerawtransaction", &combinerawtransaction, true, {"txs"} },
- { "rawtransactions", "signrawtransaction", &signrawtransaction, false, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
-
- { "blockchain", "gettxoutproof", &gettxoutproof, true, {"txids", "blockhash"} },
- { "blockchain", "verifytxoutproof", &verifytxoutproof, true, {"proof"} },
+ { "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose"} },
+ { "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime","replaceable"} },
+ { "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring"} },
+ { "rawtransactions", "decodescript", &decodescript, {"hexstring"} },
+ { "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees"} },
+ { "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
+ { "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
+
+ { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
+ { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
};
void RegisterRawTransactionRPCCommands(CRPCTable &t)
diff --git a/src/rpc/safemode.cpp b/src/rpc/safemode.cpp
new file mode 100644
index 0000000000..24770ad47f
--- /dev/null
+++ b/src/rpc/safemode.cpp
@@ -0,0 +1,14 @@
+#include "safemode.h"
+
+#include "rpc/protocol.h"
+#include "util.h"
+#include "warnings.h"
+
+void ObserveSafeMode()
+{
+ std::string warning = GetWarnings("rpc");
+ if (warning != "" && !gArgs.GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE)) {
+ throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + warning);
+ }
+}
+
diff --git a/src/rpc/safemode.h b/src/rpc/safemode.h
new file mode 100644
index 0000000000..8466d6b2f9
--- /dev/null
+++ b/src/rpc/safemode.h
@@ -0,0 +1,12 @@
+// Copyright (c) 2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_RPC_SAFEMODE_H
+#define BITCOIN_RPC_SAFEMODE_H
+
+static const bool DEFAULT_DISABLE_SAFEMODE = true;
+
+void ObserveSafeMode();
+
+#endif // BITCOIN_RPC_SAFEMODE_H
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index 1799c8e98e..428ab3b9b0 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -51,11 +51,6 @@ void RPCServer::OnStopped(std::function<void ()> slot)
g_rpcSignals.Stopped.connect(slot);
}
-void RPCServer::OnPreCommand(std::function<void (const CRPCCommand&)> slot)
-{
- g_rpcSignals.PreCommand.connect(boost::bind(slot, _1));
-}
-
void RPCTypeCheck(const UniValue& params,
const std::list<UniValue::VType>& typesExpected,
bool fAllowNull)
@@ -267,12 +262,12 @@ UniValue uptime(const JSONRPCRequest& jsonRequest)
* Call Table
*/
static const CRPCCommand vRPCCommands[] =
-{ // category name actor (function) okSafe argNames
- // --------------------- ------------------------ ----------------------- ------ ----------
+{ // category name actor (function) argNames
+ // --------------------- ------------------------ ----------------------- ----------
/* Overall control/query calls */
- { "control", "help", &help, true, {"command"} },
- { "control", "stop", &stop, true, {} },
- { "control", "uptime", &uptime, true, {} },
+ { "control", "help", &help, {"command"} },
+ { "control", "stop", &stop, {} },
+ { "control", "uptime", &uptime, {} },
};
CRPCTable::CRPCTable()
@@ -552,7 +547,7 @@ void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_
int RPCSerializationFlags()
{
int flag = 0;
- if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
+ if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
flag |= SERIALIZE_TRANSACTION_NO_WITNESS;
return flag;
}
diff --git a/src/rpc/server.h b/src/rpc/server.h
index dd6f763245..777acbcb94 100644
--- a/src/rpc/server.h
+++ b/src/rpc/server.h
@@ -25,13 +25,12 @@ namespace RPCServer
{
void OnStarted(std::function<void ()> slot);
void OnStopped(std::function<void ()> slot);
- void OnPreCommand(std::function<void (const CRPCCommand&)> slot);
}
/** Wrapper for UniValue::VType, which includes typeAny:
* Used to denote don't care type. Only used by RPCTypeCheckObj */
struct UniValueType {
- UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
+ explicit UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
UniValueType() : typeAny(true) {}
bool typeAny;
UniValue::VType type;
@@ -134,7 +133,6 @@ public:
std::string category;
std::string name;
rpcfn_type actor;
- bool okSafeMode;
std::vector<std::string> argNames;
};
diff --git a/src/scheduler.cpp b/src/scheduler.cpp
index 1d3fb1f6ea..4edb2c6d9b 100644
--- a/src/scheduler.cpp
+++ b/src/scheduler.cpp
@@ -174,7 +174,7 @@ void SingleThreadedSchedulerClient::ProcessQueue() {
// to ensure both happen safely even if callback() throws.
struct RAIICallbacksRunning {
SingleThreadedSchedulerClient* instance;
- RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {}
+ explicit RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {}
~RAIICallbacksRunning() {
{
LOCK(instance->m_cs_callbacks_pending);
diff --git a/src/scheduler.h b/src/scheduler.h
index 0365d668b2..db93bcb21e 100644
--- a/src/scheduler.h
+++ b/src/scheduler.h
@@ -81,7 +81,7 @@ private:
int nThreadsServicingQueue;
bool stopRequested;
bool stopWhenEmpty;
- bool shouldStop() { return stopRequested || (stopWhenEmpty && taskQueue.empty()); }
+ bool shouldStop() const { return stopRequested || (stopWhenEmpty && taskQueue.empty()); }
};
/**
@@ -102,7 +102,7 @@ private:
void ProcessQueue();
public:
- SingleThreadedSchedulerClient(CScheduler *pschedulerIn) : m_pscheduler(pschedulerIn) {}
+ explicit SingleThreadedSchedulerClient(CScheduler *pschedulerIn) : m_pscheduler(pschedulerIn) {}
void AddToProcessQueue(std::function<void (void)> func);
// Processes all remaining queue members on the calling thread, blocking until queue is empty
diff --git a/src/script/interpreter.h b/src/script/interpreter.h
index 437826b5dd..f845e1943b 100644
--- a/src/script/interpreter.h
+++ b/src/script/interpreter.h
@@ -114,7 +114,7 @@ struct PrecomputedTransactionData
{
uint256 hashPrevouts, hashSequence, hashOutputs;
- PrecomputedTransactionData(const CTransaction& tx);
+ explicit PrecomputedTransactionData(const CTransaction& tx);
};
enum SigVersion
diff --git a/src/script/script.h b/src/script/script.h
index 711ffa97f8..587f2d26eb 100644
--- a/src/script/script.h
+++ b/src/script/script.h
@@ -377,6 +377,12 @@ private:
int64_t m_value;
};
+/**
+ * We use a prevector for the script to reduce the considerable memory overhead
+ * of vectors in cases where they normally contain a small number of small elements.
+ * Tests in October 2015 showed use of this reduced dbcache memory usage by 23%
+ * and made an initial sync 13% faster.
+ */
typedef prevector<28, unsigned char> CScriptBase;
/** Serialized script, used inside transaction inputs and outputs */
diff --git a/src/script/sigcache.cpp b/src/script/sigcache.cpp
index ceb573b2ec..4cc7afa2f5 100644
--- a/src/script/sigcache.cpp
+++ b/src/script/sigcache.cpp
@@ -74,7 +74,7 @@ void InitSignatureCache()
{
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
- size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
+ size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = signatureCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu/2 requested for signature cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
diff --git a/src/script/sign.h b/src/script/sign.h
index bd45862892..a0d8ee4ff9 100644
--- a/src/script/sign.h
+++ b/src/script/sign.h
@@ -21,7 +21,7 @@ protected:
const CKeyStore* keystore;
public:
- BaseSignatureCreator(const CKeyStore* keystoreIn) : keystore(keystoreIn) {}
+ explicit BaseSignatureCreator(const CKeyStore* keystoreIn) : keystore(keystoreIn) {}
const CKeyStore& KeyStore() const { return *keystore; };
virtual ~BaseSignatureCreator() {}
virtual const BaseSignatureChecker& Checker() const =0;
@@ -54,7 +54,7 @@ public:
/** A signature creator that just produces 72-byte empty signatures. */
class DummySignatureCreator : public BaseSignatureCreator {
public:
- DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {}
+ explicit DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {}
const BaseSignatureChecker& Checker() const override;
bool CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override;
};
diff --git a/src/script/standard.cpp b/src/script/standard.cpp
index 9570b8c8d9..2aed393921 100644
--- a/src/script/standard.cpp
+++ b/src/script/standard.cpp
@@ -34,9 +34,6 @@ const char* GetTxnOutputType(txnouttype t)
return nullptr;
}
-/**
- * Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
- */
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
{
// Templates
@@ -253,7 +250,7 @@ class CScriptVisitor : public boost::static_visitor<bool>
private:
CScript *script;
public:
- CScriptVisitor(CScript *scriptin) { script = scriptin; }
+ explicit CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();
diff --git a/src/script/standard.h b/src/script/standard.h
index 097e0c3748..7619192264 100644
--- a/src/script/standard.h
+++ b/src/script/standard.h
@@ -27,8 +27,19 @@ public:
CScriptID(const uint160& in) : uint160(in) {}
};
-static const unsigned int MAX_OP_RETURN_RELAY = 83; //!< bytes (+1 for OP_RETURN, +2 for the pushdata opcodes)
+/**
+ * Default setting for nMaxDatacarrierBytes. 80 bytes of data, +1 for OP_RETURN,
+ * +2 for the pushdata opcodes.
+ */
+static const unsigned int MAX_OP_RETURN_RELAY = 83;
+
+/**
+ * A data carrying output is an unspendable output containing data. The script
+ * type is designated as TX_NULL_DATA.
+ */
extern bool fAcceptDatacarrier;
+
+/** Maximum size of TX_NULL_DATA scripts that this node considers standard. */
extern unsigned nMaxDatacarrierBytes;
/**
@@ -36,7 +47,7 @@ extern unsigned nMaxDatacarrierBytes;
* them to be valid. (but old blocks may not comply with) Currently just P2SH,
* but in the future other flags may be added, such as a soft-fork to enforce
* strict DER encoding.
- *
+ *
* Failing one of these tests may trigger a DoS ban - see CheckInputs() for
* details.
*/
@@ -50,7 +61,7 @@ enum txnouttype
TX_PUBKEYHASH,
TX_SCRIPTHASH,
TX_MULTISIG,
- TX_NULL_DATA,
+ TX_NULL_DATA, //!< unspendable OP_RETURN script that carries data
TX_WITNESS_V0_SCRIPTHASH,
TX_WITNESS_V0_KEYHASH,
};
@@ -61,7 +72,7 @@ public:
friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
};
-/**
+/**
* A txout script template with a specific destination. It is either:
* * CNoDestination: no destination set
* * CKeyID: TX_PUBKEYHASH destination
@@ -70,15 +81,58 @@ public:
*/
typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
+/** Get the name of a txnouttype as a C string, or nullptr if unknown. */
const char* GetTxnOutputType(txnouttype t);
+/**
+ * Parse a scriptPubKey and identify script type for standard scripts. If
+ * successful, returns script type and parsed pubkeys or hashes, depending on
+ * the type. For example, for a P2SH script, vSolutionsRet will contain the
+ * script hash, for P2PKH it will contain the key hash, etc.
+ *
+ * @param[in] scriptPubKey Script to parse
+ * @param[out] typeRet The script type
+ * @param[out] vSolutionsRet Vector of parsed pubkeys and hashes
+ * @return True if script matches standard template
+ */
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
+
+/**
+ * Parse a standard scriptPubKey for the destination address. Assigns result to
+ * the addressRet parameter and returns true if successful. For multisig
+ * scripts, instead use ExtractDestinations. Currently only works for P2PK,
+ * P2PKH, and P2SH scripts.
+ */
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
+
+/**
+ * Parse a standard scriptPubKey with one or more destination addresses. For
+ * multisig scripts, this populates the addressRet vector with the pubkey IDs
+ * and nRequiredRet with the n required to spend. For other destinations,
+ * addressRet is populated with a single value and nRequiredRet is set to 1.
+ * Returns true if successful. Currently does not extract address from
+ * pay-to-witness scripts.
+ */
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
+/**
+ * Generate a Bitcoin scriptPubKey for the given CTxDestination. Returns a P2PKH
+ * script for a CKeyID destination, a P2SH script for a CScriptID, and an empty
+ * script for CNoDestination.
+ */
CScript GetScriptForDestination(const CTxDestination& dest);
+
+/** Generate a P2PK script for the given pubkey. */
CScript GetScriptForRawPubKey(const CPubKey& pubkey);
+
+/** Generate a multisig script. */
CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys);
+
+/**
+ * Generate a pay-to-witness script for the given redeem script. If the redeem
+ * script is P2PK or P2PKH, this returns a P2WPKH script, otherwise it returns a
+ * P2WSH script.
+ */
CScript GetScriptForWitness(const CScript& redeemscript);
#endif // BITCOIN_SCRIPT_STANDARD_H
diff --git a/src/serialize.h b/src/serialize.h
index 8b86a07a76..eeb05fa76c 100644
--- a/src/serialize.h
+++ b/src/serialize.h
@@ -402,7 +402,7 @@ class CVarInt
protected:
I &n;
public:
- CVarInt(I& nIn) : n(nIn) { }
+ explicit CVarInt(I& nIn) : n(nIn) { }
template<typename Stream>
void Serialize(Stream &s) const {
@@ -420,7 +420,7 @@ class CCompactSize
protected:
uint64_t &n;
public:
- CCompactSize(uint64_t& nIn) : n(nIn) { }
+ explicit CCompactSize(uint64_t& nIn) : n(nIn) { }
template<typename Stream>
void Serialize(Stream &s) const {
@@ -439,7 +439,7 @@ class LimitedString
protected:
std::string& string;
public:
- LimitedString(std::string& _string) : string(_string) {}
+ explicit LimitedString(std::string& _string) : string(_string) {}
template<typename Stream>
void Unserialize(Stream& s)
diff --git a/src/streams.h b/src/streams.h
index a9668b68bc..159847279d 100644
--- a/src/streams.h
+++ b/src/streams.h
@@ -82,7 +82,7 @@ class CVectorWriter
* @param[in] nVersionIn Serialization Version (including any flags)
* @param[in] vchDataIn Referenced byte vector to overwrite/append
* @param[in] nPosIn Starting position. Vector index where writes should start. The vector will initially
- * grow as necessary to max(index, vec.size()). So to append, use vec.size().
+ * grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
*/
CVectorWriter(int nTypeIn, int nVersionIn, std::vector<unsigned char>& vchDataIn, size_t nPosIn) : nType(nTypeIn), nVersion(nVersionIn), vchData(vchDataIn), nPos(nPosIn)
{
@@ -91,7 +91,7 @@ class CVectorWriter
}
/*
* (other params same as above)
- * @param[in] args A list of items to serialize starting at nPos.
+ * @param[in] args A list of items to serialize starting at nPosIn.
*/
template <typename... Args>
CVectorWriter(int nTypeIn, int nVersionIn, std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : CVectorWriter(nTypeIn, nVersionIn, vchDataIn, nPosIn)
@@ -332,7 +332,7 @@ public:
//
bool eof() const { return size() == 0; }
CDataStream* rdbuf() { return this; }
- int in_avail() { return size(); }
+ int in_avail() const { return size(); }
void SetType(int n) { nType = n; }
int GetType() const { return nType; }
@@ -648,7 +648,7 @@ public:
}
// return the current reading position
- uint64_t GetPos() {
+ uint64_t GetPos() const {
return nReadPos;
}
diff --git a/src/support/allocators/secure.h b/src/support/allocators/secure.h
index f20f424941..39347c73bb 100644
--- a/src/support/allocators/secure.h
+++ b/src/support/allocators/secure.h
@@ -26,13 +26,13 @@ struct secure_allocator : public std::allocator<T> {
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::value_type value_type;
- secure_allocator() throw() {}
- secure_allocator(const secure_allocator& a) throw() : base(a) {}
+ secure_allocator() noexcept {}
+ secure_allocator(const secure_allocator& a) noexcept : base(a) {}
template <typename U>
- secure_allocator(const secure_allocator<U>& a) throw() : base(a)
+ secure_allocator(const secure_allocator<U>& a) noexcept : base(a)
{
}
- ~secure_allocator() throw() {}
+ ~secure_allocator() noexcept {}
template <typename _Other>
struct rebind {
typedef secure_allocator<_Other> other;
diff --git a/src/support/allocators/zeroafterfree.h b/src/support/allocators/zeroafterfree.h
index 581d5d6318..618874ceee 100644
--- a/src/support/allocators/zeroafterfree.h
+++ b/src/support/allocators/zeroafterfree.h
@@ -22,13 +22,13 @@ struct zero_after_free_allocator : public std::allocator<T> {
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::value_type value_type;
- zero_after_free_allocator() throw() {}
- zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
+ zero_after_free_allocator() noexcept {}
+ zero_after_free_allocator(const zero_after_free_allocator& a) noexcept : base(a) {}
template <typename U>
- zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a)
+ zero_after_free_allocator(const zero_after_free_allocator<U>& a) noexcept : base(a)
{
}
- ~zero_after_free_allocator() throw() {}
+ ~zero_after_free_allocator() noexcept {}
template <typename _Other>
struct rebind {
typedef zero_after_free_allocator<_Other> other;
diff --git a/src/support/lockedpool.h b/src/support/lockedpool.h
index f5212bc266..cecbdec1aa 100644
--- a/src/support/lockedpool.h
+++ b/src/support/lockedpool.h
@@ -150,7 +150,7 @@ public:
* If this callback is provided and returns false, the allocation fails (hard fail), if
* it returns true the allocation proceeds, but it could warn.
*/
- LockedPool(std::unique_ptr<LockedPageAllocator> allocator, LockingFailed_Callback lf_cb_in = 0);
+ explicit LockedPool(std::unique_ptr<LockedPageAllocator> allocator, LockingFailed_Callback lf_cb_in = nullptr);
~LockedPool();
/** Allocate size bytes from this arena.
@@ -217,7 +217,7 @@ public:
}
private:
- LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator);
+ explicit LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator);
/** Create a new LockedPoolManager specialized to the OS */
static void CreateInstance();
diff --git a/src/sync.cpp b/src/sync.cpp
index b82f3770e4..9c351ea487 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -162,7 +162,7 @@ void DeleteLock(void* cs)
return;
}
boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
- std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
+ std::pair<void*, void*> item = std::make_pair(cs, nullptr);
LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
while (it != lockdata.lockorders.end() && it->first.first == cs) {
std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
diff --git a/src/sync.h b/src/sync.h
index 4921aedf39..0871c5fb4d 100644
--- a/src/sync.h
+++ b/src/sync.h
@@ -196,7 +196,7 @@ private:
int value;
public:
- CSemaphore(int init) : value(init) {}
+ explicit CSemaphore(int init) : value(init) {}
void wait()
{
@@ -267,7 +267,7 @@ public:
CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {}
- CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false)
+ explicit CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false)
{
if (fTry)
TryAcquire();
@@ -280,7 +280,7 @@ public:
Release();
}
- operator bool()
+ operator bool() const
{
return fHaveGrant;
}
diff --git a/src/test/DoS_tests.cpp b/src/test/DoS_tests.cpp
index 4a284517a1..ffbeeb7d91 100644
--- a/src/test/DoS_tests.cpp
+++ b/src/test/DoS_tests.cpp
@@ -78,7 +78,7 @@ BOOST_AUTO_TEST_CASE(DoS_banscore)
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
- ForceSetArg("-banscore", "111"); // because 11 is my favorite number
+ gArgs.ForceSetArg("-banscore", "111"); // because 11 is my favorite number
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, CAddress(), "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
@@ -94,7 +94,7 @@ BOOST_AUTO_TEST_CASE(DoS_banscore)
Misbehaving(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
- ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
+ gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
}
BOOST_AUTO_TEST_CASE(DoS_bantime)
diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp
index 2ad22d34ad..7be29c6d6b 100644
--- a/src/test/addrman_tests.cpp
+++ b/src/test/addrman_tests.cpp
@@ -15,7 +15,7 @@ class CAddrManTest : public CAddrMan
uint64_t state;
public:
- CAddrManTest(bool makeDeterministic = true)
+ explicit CAddrManTest(bool makeDeterministic = true)
{
state = 1;
diff --git a/src/test/base58_tests.cpp b/src/test/base58_tests.cpp
index b33cdb9fe6..ee633249e9 100644
--- a/src/test/base58_tests.cpp
+++ b/src/test/base58_tests.cpp
@@ -78,7 +78,7 @@ class TestAddrTypeVisitor : public boost::static_visitor<bool>
private:
std::string exp_addrType;
public:
- TestAddrTypeVisitor(const std::string &_exp_addrType) : exp_addrType(_exp_addrType) { }
+ explicit TestAddrTypeVisitor(const std::string &_exp_addrType) : exp_addrType(_exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
@@ -99,7 +99,7 @@ class TestPayloadVisitor : public boost::static_visitor<bool>
private:
std::vector<unsigned char> exp_payload;
public:
- TestPayloadVisitor(std::vector<unsigned char> &_exp_payload) : exp_payload(_exp_payload) { }
+ explicit TestPayloadVisitor(std::vector<unsigned char> &_exp_payload) : exp_payload(_exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
diff --git a/src/test/bip32_tests.cpp b/src/test/bip32_tests.cpp
index 6bcd550d7b..c851ab2849 100644
--- a/src/test/bip32_tests.cpp
+++ b/src/test/bip32_tests.cpp
@@ -24,7 +24,7 @@ struct TestVector {
std::string strHexMaster;
std::vector<TestDerivation> vDerive;
- TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}
+ explicit TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}
TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {
vDerive.push_back(TestDerivation());
diff --git a/src/test/blockencodings_tests.cpp b/src/test/blockencodings_tests.cpp
index 10a40fea3c..f2d5b385d0 100644
--- a/src/test/blockencodings_tests.cpp
+++ b/src/test/blockencodings_tests.cpp
@@ -51,7 +51,7 @@ static CBlock BuildBlockTestCase() {
return block;
}
-// Number of shared use_counts we expect for a tx we havent touched
+// Number of shared use_counts we expect for a tx we haven't touched
// == 2 (mempool + our copy from the GetSharedTx call)
#define SHARED_TX_OFFSET 2
@@ -118,12 +118,12 @@ public:
std::vector<uint64_t> shorttxids;
std::vector<PrefilledTransaction> prefilledtxn;
- TestHeaderAndShortIDs(const CBlockHeaderAndShortTxIDs& orig) {
+ explicit TestHeaderAndShortIDs(const CBlockHeaderAndShortTxIDs& orig) {
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << orig;
stream >> *this;
}
- TestHeaderAndShortIDs(const CBlock& block) :
+ explicit TestHeaderAndShortIDs(const CBlock& block) :
TestHeaderAndShortIDs(CBlockHeaderAndShortTxIDs(block, true)) {}
uint64_t GetShortID(const uint256& txhash) const {
diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
index e24431528a..dc358bff95 100644
--- a/src/test/coins_tests.cpp
+++ b/src/test/coins_tests.cpp
@@ -74,7 +74,7 @@ public:
class CCoinsViewCacheTest : public CCoinsViewCache
{
public:
- CCoinsViewCacheTest(CCoinsView* _base) : CCoinsViewCache(_base) {}
+ explicit CCoinsViewCacheTest(CCoinsView* _base) : CCoinsViewCache(_base) {}
void SelfTest() const
{
@@ -89,8 +89,8 @@ public:
BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);
}
- CCoinsMap& map() { return cacheCoins; }
- size_t& usage() { return cachedCoinsUsage; }
+ CCoinsMap& map() const { return cacheCoins; }
+ size_t& usage() const { return cachedCoinsUsage; }
};
} // namespace
@@ -275,7 +275,7 @@ UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
// except the emphasis is on testing the functionality of UpdateCoins
// random txs are created and UpdateCoins is used to update the cache stack
// In particular it is tested that spending a duplicate coinbase tx
-// has the expected effect (the other duplicate is overwitten at all cache levels)
+// has the expected effect (the other duplicate is overwritten at all cache levels)
BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
{
bool spent_a_duplicate_coinbase = false;
diff --git a/src/test/data/tx_invalid.json b/src/test/data/tx_invalid.json
index 2235bd0ae7..09442b7f9f 100644
--- a/src/test/data/tx_invalid.json
+++ b/src/test/data/tx_invalid.json
@@ -205,7 +205,7 @@
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "4259839 CHECKSEQUENCEVERIFY 1"]],
"020000000100010000000000000000000000000000000000000000000000000000000000000000000000feff40000100000000000000000000000000", "P2SH,CHECKSEQUENCEVERIFY"],
-["By-time locks, with argument just beyond txin.nSequence (but within numerical boundries)"],
+["By-time locks, with argument just beyond txin.nSequence (but within numerical boundaries)"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "4194305 CHECKSEQUENCEVERIFY 1"]],
"020000000100010000000000000000000000000000000000000000000000000000000000000000000000000040000100000000000000000000000000", "P2SH,CHECKSEQUENCEVERIFY"],
[[["0000000000000000000000000000000000000000000000000000000000000100", 0, "4259839 CHECKSEQUENCEVERIFY 1"]],
diff --git a/src/test/data/tx_valid.json b/src/test/data/tx_valid.json
index e6b382af13..ad74b7cf1b 100644
--- a/src/test/data/tx_valid.json
+++ b/src/test/data/tx_valid.json
@@ -45,7 +45,7 @@
"01000000010001000000000000000000000000000000000000000000000000000000000000000000006a473044022067288ea50aa799543a536ff9306f8e1cba05b9c6b10951175b924f96732555ed022026d7b5265f38d21541519e4a1e55044d5b9e17e15cdbaf29ae3792e99e883e7a012103ba8c8b86dea131c22ab967e6dd99bdae8eff7a1f75a2c35f1f944109e3fe5e22ffffffff010000000000000000015100000000", "P2SH"],
["The following is f7fdd091fa6d8f5e7a8c2458f5c38faffff2d3f1406b6e4fe2c99dcc0d2d1cbb"],
-["It caught a bug in the workaround for 23b397edccd3740a74adb603c9756370fafcde9bcc4483eb271ecad09a94dd63 in an overly simple implementation"],
+["It caught a bug in the workaround for 23b397edccd3740a74adb603c9756370fafcde9bcc4483eb271ecad09a94dd63 in an overly simple implementation. In a signature, it contains an ASN1 integer which isn't strict-DER conformant due to being negative, which doesn't make sense in a signature. Before BIP66 activated, it was a valid signature. After it activated, it's not valid any more."],
[[["b464e85df2a238416f8bdae11d120add610380ea07f4ef19c5f9dfd472f96c3d", 0, "DUP HASH160 0x14 0xbef80ecf3a44500fda1bc92176e442891662aed2 EQUALVERIFY CHECKSIG"],
["b7978cc96e59a8b13e0865d3f95657561a7f725be952438637475920bac9eb21", 1, "DUP HASH160 0x14 0xbef80ecf3a44500fda1bc92176e442891662aed2 EQUALVERIFY CHECKSIG"]],
"01000000023d6cf972d4dff9c519eff407ea800361dd0a121de1da8b6f4138a2f25de864b4000000008a4730440220ffda47bfc776bcd269da4832626ac332adfca6dd835e8ecd83cd1ebe7d709b0e022049cffa1cdc102a0b56e0e04913606c70af702a1149dc3b305ab9439288fee090014104266abb36d66eb4218a6dd31f09bb92cf3cfa803c7ea72c1fc80a50f919273e613f895b855fb7465ccbc8919ad1bd4a306c783f22cd3227327694c4fa4c1c439affffffff21ebc9ba20594737864352e95b727f1a565756f9d365083eb1a8596ec98c97b7010000008a4730440220503ff10e9f1e0de731407a4a245531c9ff17676eda461f8ceeb8c06049fa2c810220c008ac34694510298fa60b3f000df01caa244f165b727d4896eb84f81e46bcc4014104266abb36d66eb4218a6dd31f09bb92cf3cfa803c7ea72c1fc80a50f919273e613f895b855fb7465ccbc8919ad1bd4a306c783f22cd3227327694c4fa4c1c439affffffff01f0da5200000000001976a914857ccd42dded6df32949d4646dfa10a92458cfaa88ac00000000", "P2SH"],
diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp
index 6ed6e7744e..251d5a7142 100644
--- a/src/test/dbwrapper_tests.cpp
+++ b/src/test/dbwrapper_tests.cpp
@@ -231,7 +231,7 @@ struct StringContentsSerializer {
// This is a terrible idea
std::string str;
StringContentsSerializer() {}
- StringContentsSerializer(const std::string& inp) : str(inp) {}
+ explicit StringContentsSerializer(const std::string& inp) : str(inp) {}
StringContentsSerializer& operator+=(const std::string& s) {
str += s;
diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp
index c79675f5a6..18a7e59933 100644
--- a/src/test/getarg_tests.cpp
+++ b/src/test/getarg_tests.cpp
@@ -27,135 +27,135 @@ static void ResetArgs(const std::string& strArg)
for (std::string& s : vecArg)
vecChar.push_back(s.c_str());
- ParseParameters(vecChar.size(), &vecChar[0]);
+ gArgs.ParseParameters(vecChar.size(), &vecChar[0]);
}
BOOST_AUTO_TEST_CASE(boolarg)
{
ResetArgs("-foo");
- BOOST_CHECK(GetBoolArg("-foo", false));
- BOOST_CHECK(GetBoolArg("-foo", true));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", true));
- BOOST_CHECK(!GetBoolArg("-fo", false));
- BOOST_CHECK(GetBoolArg("-fo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-fo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-fo", true));
- BOOST_CHECK(!GetBoolArg("-fooo", false));
- BOOST_CHECK(GetBoolArg("-fooo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-fooo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-fooo", true));
ResetArgs("-foo=0");
- BOOST_CHECK(!GetBoolArg("-foo", false));
- BOOST_CHECK(!GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
ResetArgs("-foo=1");
- BOOST_CHECK(GetBoolArg("-foo", false));
- BOOST_CHECK(GetBoolArg("-foo", true));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", true));
// New 0.6 feature: auto-map -nosomething to !-something:
ResetArgs("-nofoo");
- BOOST_CHECK(!GetBoolArg("-foo", false));
- BOOST_CHECK(!GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
ResetArgs("-nofoo=1");
- BOOST_CHECK(!GetBoolArg("-foo", false));
- BOOST_CHECK(!GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
ResetArgs("-foo -nofoo"); // -nofoo should win
- BOOST_CHECK(!GetBoolArg("-foo", false));
- BOOST_CHECK(!GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
ResetArgs("-foo=1 -nofoo=1"); // -nofoo should win
- BOOST_CHECK(!GetBoolArg("-foo", false));
- BOOST_CHECK(!GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
ResetArgs("-foo=0 -nofoo=0"); // -nofoo=0 should win
- BOOST_CHECK(GetBoolArg("-foo", false));
- BOOST_CHECK(GetBoolArg("-foo", true));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", true));
// New 0.6 feature: treat -- same as -:
ResetArgs("--foo=1");
- BOOST_CHECK(GetBoolArg("-foo", false));
- BOOST_CHECK(GetBoolArg("-foo", true));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", true));
ResetArgs("--nofoo=1");
- BOOST_CHECK(!GetBoolArg("-foo", false));
- BOOST_CHECK(!GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
}
BOOST_AUTO_TEST_CASE(stringarg)
{
ResetArgs("");
- BOOST_CHECK_EQUAL(GetArg("-foo", ""), "");
- BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "eleven");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "eleven");
ResetArgs("-foo -bar");
- BOOST_CHECK_EQUAL(GetArg("-foo", ""), "");
- BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "");
ResetArgs("-foo=");
- BOOST_CHECK_EQUAL(GetArg("-foo", ""), "");
- BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "");
ResetArgs("-foo=11");
- BOOST_CHECK_EQUAL(GetArg("-foo", ""), "11");
- BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "11");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "11");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "11");
ResetArgs("-foo=eleven");
- BOOST_CHECK_EQUAL(GetArg("-foo", ""), "eleven");
- BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "eleven");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "eleven");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "eleven");
}
BOOST_AUTO_TEST_CASE(intarg)
{
ResetArgs("");
- BOOST_CHECK_EQUAL(GetArg("-foo", 11), 11);
- BOOST_CHECK_EQUAL(GetArg("-foo", 0), 0);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 11), 11);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 0), 0);
ResetArgs("-foo -bar");
- BOOST_CHECK_EQUAL(GetArg("-foo", 11), 0);
- BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 11), 0);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 0);
ResetArgs("-foo=11 -bar=12");
- BOOST_CHECK_EQUAL(GetArg("-foo", 0), 11);
- BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 0), 11);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 12);
ResetArgs("-foo=NaN -bar=NotANumber");
- BOOST_CHECK_EQUAL(GetArg("-foo", 1), 0);
- BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 1), 0);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 0);
}
BOOST_AUTO_TEST_CASE(doubledash)
{
ResetArgs("--foo");
- BOOST_CHECK_EQUAL(GetBoolArg("-foo", false), true);
+ BOOST_CHECK_EQUAL(gArgs.GetBoolArg("-foo", false), true);
ResetArgs("--foo=verbose --bar=1");
- BOOST_CHECK_EQUAL(GetArg("-foo", ""), "verbose");
- BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "verbose");
+ BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 0), 1);
}
BOOST_AUTO_TEST_CASE(boolargno)
{
ResetArgs("-nofoo");
- BOOST_CHECK(!GetBoolArg("-foo", true));
- BOOST_CHECK(!GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
ResetArgs("-nofoo=1");
- BOOST_CHECK(!GetBoolArg("-foo", true));
- BOOST_CHECK(!GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
ResetArgs("-nofoo=0");
- BOOST_CHECK(GetBoolArg("-foo", true));
- BOOST_CHECK(GetBoolArg("-foo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", true));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", false));
ResetArgs("-foo --nofoo"); // --nofoo should win
- BOOST_CHECK(!GetBoolArg("-foo", true));
- BOOST_CHECK(!GetBoolArg("-foo", false));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", true));
+ BOOST_CHECK(!gArgs.GetBoolArg("-foo", false));
ResetArgs("-nofoo -foo"); // foo always wins:
- BOOST_CHECK(GetBoolArg("-foo", true));
- BOOST_CHECK(GetBoolArg("-foo", false));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", true));
+ BOOST_CHECK(gArgs.GetBoolArg("-foo", false));
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 095d86834c..31b05d868b 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -80,7 +80,7 @@ BOOST_AUTO_TEST_CASE(cnode_listen_port)
BOOST_CHECK(port == Params().GetDefaultPort());
// test set port
unsigned short altPort = 12345;
- SoftSetArg("-port", std::to_string(altPort));
+ gArgs.SoftSetArg("-port", std::to_string(altPort));
port = GetListenPort();
BOOST_CHECK(port == altPort);
}
diff --git a/src/test/prevector_tests.cpp b/src/test/prevector_tests.cpp
index 345c4a2148..841282873f 100644
--- a/src/test/prevector_tests.cpp
+++ b/src/test/prevector_tests.cpp
@@ -152,11 +152,11 @@ public:
pre_vector.assign(n, value);
}
- Size size() {
+ Size size() const {
return real_vector.size();
}
- Size capacity() {
+ Size capacity() const {
return pre_vector.capacity();
}
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 06b8274f2d..17374edcc4 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -450,7 +450,7 @@ public:
return array;
}
- std::string GetComment()
+ std::string GetComment() const
{
return comment;
}
diff --git a/src/test/scriptnum_tests.cpp b/src/test/scriptnum_tests.cpp
index 1d5893bdc3..280eb59ce8 100644
--- a/src/test/scriptnum_tests.cpp
+++ b/src/test/scriptnum_tests.cpp
@@ -29,10 +29,7 @@ static void CheckCreateVch(const int64_t& num)
CScriptNum scriptnum(num);
BOOST_CHECK(verify(bignum, scriptnum));
- std::vector<unsigned char> vch = bignum.getvch();
-
CScriptNum10 bignum2(bignum.getvch(), false);
- vch = scriptnum.getvch();
CScriptNum scriptnum2(scriptnum.getvch(), false);
BOOST_CHECK(verify(bignum2, scriptnum2));
@@ -90,11 +87,10 @@ static void CheckSubtract(const int64_t& num1, const int64_t& num2)
const CScriptNum10 bignum2(num2);
const CScriptNum scriptnum1(num1);
const CScriptNum scriptnum2(num2);
- bool invalid = false;
// int64_t overflow is undefined.
- invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) ||
- (num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2));
+ bool invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) ||
+ (num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2));
if (!invalid)
{
BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - scriptnum2));
diff --git a/src/test/sighash_tests.cpp b/src/test/sighash_tests.cpp
index 1ca83a7cf8..ecbdf57788 100644
--- a/src/test/sighash_tests.cpp
+++ b/src/test/sighash_tests.cpp
@@ -124,11 +124,9 @@ BOOST_AUTO_TEST_CASE(sighash_test)
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
- #endif
+ int nRandomTests = 500;
+ #else
int nRandomTests = 50000;
-
- #if defined(PRINT_SIGHASH_JSON)
- nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = InsecureRand32();
diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp
index 72d7f1b19f..194f62ca11 100644
--- a/src/test/test_bitcoin.cpp
+++ b/src/test/test_bitcoin.cpp
@@ -22,8 +22,6 @@
#include "rpc/register.h"
#include "script/sigcache.h"
-#include "test/testutil.h"
-
#include <memory>
uint256 insecure_rand_seed = GetRandHash();
@@ -61,9 +59,9 @@ TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(cha
RegisterAllCoreRPCCommands(tableRPC);
ClearDatadirCache();
- pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));
+ pathTemp = fs::temp_directory_path() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));
fs::create_directories(pathTemp);
- ForceSetArg("-datadir", pathTemp.string());
+ gArgs.ForceSetArg("-datadir", pathTemp.string());
// Note that because we don't bother running a scheduler thread here,
// callbacks via CValidationInterface are unreliable, but that's OK,
diff --git a/src/test/test_bitcoin.h b/src/test/test_bitcoin.h
index dd3b13c8c8..2ddac2f076 100644
--- a/src/test/test_bitcoin.h
+++ b/src/test/test_bitcoin.h
@@ -41,7 +41,7 @@ static inline bool InsecureRandBool() { return insecure_rand_ctx.randbool(); }
struct BasicTestingSetup {
ECCVerifyHandle globalVerifyHandle;
- BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
+ explicit BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~BasicTestingSetup();
};
@@ -56,7 +56,7 @@ struct TestingSetup: public BasicTestingSetup {
CConnman* connman;
CScheduler scheduler;
- TestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
+ explicit TestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~TestingSetup();
};
diff --git a/src/test/test_bitcoin_main.cpp b/src/test/test_bitcoin_main.cpp
index 34beef5539..b556c953b9 100644
--- a/src/test/test_bitcoin_main.cpp
+++ b/src/test/test_bitcoin_main.cpp
@@ -10,14 +10,14 @@
std::unique_ptr<CConnman> g_connman;
-void Shutdown(void* parg)
+[[noreturn]] void Shutdown(void* parg)
{
- exit(EXIT_SUCCESS);
+ std::exit(EXIT_SUCCESS);
}
-void StartShutdown()
+[[noreturn]] void StartShutdown()
{
- exit(EXIT_SUCCESS);
+ std::exit(EXIT_SUCCESS);
}
bool ShutdownRequested()
diff --git a/src/test/testutil.cpp b/src/test/testutil.cpp
deleted file mode 100644
index 591d0bf302..0000000000
--- a/src/test/testutil.cpp
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright (c) 2009-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.
-
-#include "testutil.h"
-
-#ifdef WIN32
-#include <shlobj.h>
-#endif
-
-#include "fs.h"
-
-fs::path GetTempPath() {
- return fs::temp_directory_path();
-}
diff --git a/src/test/testutil.h b/src/test/testutil.h
deleted file mode 100644
index cbe784d640..0000000000
--- a/src/test/testutil.h
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright (c) 2009-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.
-
-/**
- * Utility functions shared by unit tests
- */
-#ifndef BITCOIN_TEST_TESTUTIL_H
-#define BITCOIN_TEST_TESTUTIL_H
-
-#include "fs.h"
-
-fs::path GetTempPath();
-
-#endif // BITCOIN_TEST_TESTUTIL_H
diff --git a/src/test/versionbits_tests.cpp b/src/test/versionbits_tests.cpp
index f433aad889..882afb2e20 100644
--- a/src/test/versionbits_tests.cpp
+++ b/src/test/versionbits_tests.cpp
@@ -314,20 +314,20 @@ BOOST_AUTO_TEST_CASE(versionbits_computeblockversion)
// Mine one period worth of blocks, and check that the bit will be on for the
// next period.
- lastBlock = secondChain.Mine(2016, nStartTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
+ lastBlock = secondChain.Mine(2016, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
// Mine another period worth of blocks, signaling the new bit.
- lastBlock = secondChain.Mine(4032, nStartTime, VERSIONBITS_TOP_BITS | (1<<bit)).Tip();
+ lastBlock = secondChain.Mine(4032, nTime, VERSIONBITS_TOP_BITS | (1<<bit)).Tip();
// After one period of setting the bit on each block, it should have locked in.
// We keep setting the bit for one more period though, until activation.
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
// Now check that we keep mining the block until the end of this period, and
// then stop at the beginning of the next period.
- lastBlock = secondChain.Mine(6047, nStartTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
+ lastBlock = secondChain.Mine(6047, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK((ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit)) != 0);
- lastBlock = secondChain.Mine(6048, nStartTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
+ lastBlock = secondChain.Mine(6048, nTime, VERSIONBITS_LAST_OLD_BLOCK_VERSION).Tip();
BOOST_CHECK_EQUAL(ComputeBlockVersion(lastBlock, mainnetParams) & (1<<bit), 0);
// Finally, verify that after a soft fork has activated, CBV no longer uses
diff --git a/src/timedata.cpp b/src/timedata.cpp
index 099ed7f042..5113bb60db 100644
--- a/src/timedata.cpp
+++ b/src/timedata.cpp
@@ -81,7 +81,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
- if (abs64(nMedian) <= std::max<int64_t>(0, GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)))
+ if (abs64(nMedian) <= std::max<int64_t>(0, gArgs.GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)))
{
nTimeOffset = nMedian;
}
diff --git a/src/tinyformat.h b/src/tinyformat.h
index 5022d46809..2e453e56bb 100644
--- a/src/tinyformat.h
+++ b/src/tinyformat.h
@@ -167,7 +167,7 @@ namespace tinyformat {
class format_error: public std::runtime_error
{
public:
- format_error(const std::string &what): std::runtime_error(what) {
+ explicit format_error(const std::string &what): std::runtime_error(what) {
}
};
@@ -498,7 +498,7 @@ class FormatArg
FormatArg() {}
template<typename T>
- FormatArg(const T& value)
+ explicit FormatArg(const T& value)
: m_value(static_cast<const void*>(&value)),
m_formatImpl(&formatImpl<T>),
m_toIntImpl(&toIntImpl<T>)
@@ -867,7 +867,7 @@ class FormatListN : public FormatList
public:
#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
template<typename... Args>
- FormatListN(const Args&... args)
+ explicit FormatListN(const Args&... args)
: FormatList(&m_formatterStore[0], N),
m_formatterStore { FormatArg(args)... }
{ static_assert(sizeof...(args) == N, "Number of args must be N"); }
@@ -876,7 +876,7 @@ class FormatListN : public FormatList
# define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n) \
\
template<TINYFORMAT_ARGTYPES(n)> \
- FormatListN(TINYFORMAT_VARARGS(n)) \
+ explicit FormatListN(TINYFORMAT_VARARGS(n)) \
: FormatList(&m_formatterStore[0], n) \
{ assert(n == N); init(0, TINYFORMAT_PASSARGS(n)); } \
\
diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
index 57c22537b2..1cea197666 100644
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -76,7 +76,7 @@ public:
/** Create a new TorControlConnection.
*/
- TorControlConnection(struct event_base *base);
+ explicit TorControlConnection(struct event_base *base);
~TorControlConnection();
/**
@@ -121,7 +121,7 @@ private:
};
TorControlConnection::TorControlConnection(struct event_base *_base):
- base(_base), b_conn(0)
+ base(_base), b_conn(nullptr)
{
}
@@ -227,7 +227,7 @@ bool TorControlConnection::Disconnect()
{
if (b_conn)
bufferevent_free(b_conn);
- b_conn = 0;
+ b_conn = nullptr;
return true;
}
@@ -476,7 +476,7 @@ TorController::~TorController()
{
if (reconnect_ev) {
event_free(reconnect_ev);
- reconnect_ev = 0;
+ reconnect_ev = nullptr;
}
if (service.IsValid()) {
RemoveLocal(service);
@@ -525,7 +525,7 @@ void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply&
// Now that we know Tor is running setup the proxy for onion addresses
// if -onion isn't set to something else.
- if (GetArg("-onion", "") == "") {
+ if (gArgs.GetArg("-onion", "") == "") {
CService resolved(LookupNumeric("127.0.0.1", 9050));
proxyType addrOnion = proxyType(resolved, true);
SetProxy(NET_TOR, addrOnion);
@@ -642,7 +642,7 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro
* cookie: hex-encoded ~/.tor/control_auth_cookie
* password: "password"
*/
- std::string torpassword = GetArg("-torpassword", "");
+ std::string torpassword = gArgs.GetArg("-torpassword", "");
if (!torpassword.empty()) {
if (methods.count("HASHEDPASSWORD")) {
LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
@@ -735,7 +735,7 @@ static boost::thread torControlThread;
static void TorControlThread()
{
- TorController ctrl(gBase, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
+ TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
event_base_dispatch(gBase);
}
@@ -770,7 +770,7 @@ void StopTorControl()
if (gBase) {
torControlThread.join();
event_base_free(gBase);
- gBase = 0;
+ gBase = nullptr;
}
}
diff --git a/src/txdb.cpp b/src/txdb.cpp
index 7f7eb65673..797ae5713f 100644
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -35,7 +35,7 @@ namespace {
struct CoinEntry {
COutPoint* outpoint;
char key;
- CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}
+ explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}
template<typename Stream>
void Serialize(Stream &s) const {
@@ -85,8 +85,8 @@ bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CDBBatch batch(db);
size_t count = 0;
size_t changed = 0;
- size_t batch_size = (size_t)GetArg("-dbbatchsize", nDefaultDbBatchSize);
- int crash_simulate = GetArg("-dbcrashratio", 0);
+ size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize);
+ int crash_simulate = gArgs.GetArg("-dbcrashratio", 0);
assert(!hashBlock.IsNull());
uint256 old_tip = GetBestBlock();
diff --git a/src/txdb.h b/src/txdb.h
index adcbc73380..d1cd5a4250 100644
--- a/src/txdb.h
+++ b/src/txdb.h
@@ -64,12 +64,12 @@ struct CDiskTxPos : public CDiskBlockPos
};
/** CCoinsView backed by the coin database (chainstate/) */
-class CCoinsViewDB : public CCoinsView
+class CCoinsViewDB final : public CCoinsView
{
protected:
CDBWrapper db;
public:
- CCoinsViewDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
+ explicit CCoinsViewDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
bool HaveCoin(const COutPoint &outpoint) const override;
@@ -109,7 +109,7 @@ private:
class CBlockTreeDB : public CDBWrapper
{
public:
- CBlockTreeDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
+ explicit CBlockTreeDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
private:
CBlockTreeDB(const CBlockTreeDB&);
void operator=(const CBlockTreeDB&);
diff --git a/src/txmempool.cpp b/src/txmempool.cpp
index 4a81055231..f68d677646 100644
--- a/src/txmempool.cpp
+++ b/src/txmempool.cpp
@@ -39,11 +39,6 @@ CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFe
nSigOpCostWithAncestors = sigOpCost;
}
-CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
-{
- *this = other;
-}
-
void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
{
nModFeesWithDescendants += newFeeDelta - feeDelta;
diff --git a/src/txmempool.h b/src/txmempool.h
index 6723ea8e6c..b07886579c 100644
--- a/src/txmempool.h
+++ b/src/txmempool.h
@@ -21,11 +21,10 @@
#include "sync.h"
#include "random.h"
-#include "boost/multi_index_container.hpp"
-#include "boost/multi_index/ordered_index.hpp"
-#include "boost/multi_index/hashed_index.hpp"
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
-
#include <boost/signals2/signal.hpp>
class CBlockIndex;
@@ -95,8 +94,6 @@ public:
bool spendsCoinbase,
int64_t nSigOpsCost, LockPoints lp);
- CTxMemPoolEntry(const CTxMemPoolEntry& other);
-
const CTransaction& GetTx() const { return *this->tx; }
CTransactionRef GetSharedTx() const { return this->tx; }
const CAmount& GetFee() const { return nFee; }
@@ -167,7 +164,7 @@ struct update_ancestor_state
struct update_fee_delta
{
- update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
+ explicit update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
@@ -177,7 +174,7 @@ private:
struct update_lock_points
{
- update_lock_points(const LockPoints& _lp) : lp(_lp) { }
+ explicit update_lock_points(const LockPoints& _lp) : lp(_lp) { }
void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
@@ -501,7 +498,7 @@ public:
/** Create a new CTxMemPool.
*/
- CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);
+ explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);
/**
* If sanity-checking is turned on, check makes sure the pool is
@@ -606,7 +603,7 @@ public:
return mapTx.size();
}
- uint64_t GetTotalTxSize()
+ uint64_t GetTotalTxSize() const
{
LOCK(cs);
return totalTxSize;
diff --git a/src/uint256.h b/src/uint256.h
index a92ce07f11..3ed694d723 100644
--- a/src/uint256.h
+++ b/src/uint256.h
@@ -111,7 +111,7 @@ public:
class uint160 : public base_blob<160> {
public:
uint160() {}
- uint160(const base_blob<160>& b) : base_blob<160>(b) {}
+ explicit uint160(const base_blob<160>& b) : base_blob<160>(b) {}
explicit uint160(const std::vector<unsigned char>& vch) : base_blob<160>(vch) {}
};
@@ -123,7 +123,7 @@ public:
class uint256 : public base_blob<256> {
public:
uint256() {}
- uint256(const base_blob<256>& b) : base_blob<256>(b) {}
+ explicit uint256(const base_blob<256>& b) : base_blob<256>(b) {}
explicit uint256(const std::vector<unsigned char>& vch) : base_blob<256>(vch) {}
/** A cheap hash function that just returns 64 bits from the result, it can be
diff --git a/src/undo.h b/src/undo.h
index 0f9d041bbd..a720de4ac5 100644
--- a/src/undo.h
+++ b/src/undo.h
@@ -33,7 +33,7 @@ public:
::Serialize(s, CTxOutCompressor(REF(txout->out)));
}
- TxInUndoSerializer(const Coin* coin) : txout(coin) {}
+ explicit TxInUndoSerializer(const Coin* coin) : txout(coin) {}
};
class TxInUndoDeserializer
@@ -57,7 +57,7 @@ public:
::Unserialize(s, REF(CTxOutCompressor(REF(txout->out))));
}
- TxInUndoDeserializer(Coin* coin) : txout(coin) {}
+ explicit TxInUndoDeserializer(Coin* coin) : txout(coin) {}
};
static const size_t MIN_TRANSACTION_INPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxIn(), SER_NETWORK, PROTOCOL_VERSION);
diff --git a/src/univalue/lib/univalue_utffilter.h b/src/univalue/lib/univalue_utffilter.h
index 0e330dce9c..2fb6a492d1 100644
--- a/src/univalue/lib/univalue_utffilter.h
+++ b/src/univalue/lib/univalue_utffilter.h
@@ -13,7 +13,7 @@
class JSONUTF8StringFilter
{
public:
- JSONUTF8StringFilter(std::string &s):
+ explicit JSONUTF8StringFilter(std::string &s):
str(s), is_valid(true), codepoint(0), state(0), surpair(0)
{
}
diff --git a/src/util.cpp b/src/util.cpp
index fc75b7ef85..4659ff73c6 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -419,49 +419,48 @@ void ArgsManager::ParseParameters(int argc, const char* const argv[])
}
}
-std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg)
+std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
{
LOCK(cs_args);
- if (IsArgSet(strArg))
- return mapMultiArgs.at(strArg);
+ auto it = mapMultiArgs.find(strArg);
+ if (it != mapMultiArgs.end()) return it->second;
return {};
}
-bool ArgsManager::IsArgSet(const std::string& strArg)
+bool ArgsManager::IsArgSet(const std::string& strArg) const
{
LOCK(cs_args);
return mapArgs.count(strArg);
}
-std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault)
+std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
{
LOCK(cs_args);
- if (mapArgs.count(strArg))
- return mapArgs[strArg];
+ auto it = mapArgs.find(strArg);
+ if (it != mapArgs.end()) return it->second;
return strDefault;
}
-int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault)
+int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
{
LOCK(cs_args);
- if (mapArgs.count(strArg))
- return atoi64(mapArgs[strArg]);
+ auto it = mapArgs.find(strArg);
+ if (it != mapArgs.end()) return atoi64(it->second);
return nDefault;
}
-bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault)
+bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
{
LOCK(cs_args);
- if (mapArgs.count(strArg))
- return InterpretBool(mapArgs[strArg]);
+ auto it = mapArgs.find(strArg);
+ if (it != mapArgs.end()) return InterpretBool(it->second);
return fDefault;
}
bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
- if (mapArgs.count(strArg))
- return false;
+ if (IsArgSet(strArg)) return false;
ForceSetArg(strArg, strValue);
return true;
}
@@ -478,8 +477,7 @@ void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strV
{
LOCK(cs_args);
mapArgs[strArg] = strValue;
- mapMultiArgs[strArg].clear();
- mapMultiArgs[strArg].push_back(strValue);
+ mapMultiArgs[strArg] = {strValue};
}
@@ -564,8 +562,8 @@ const fs::path &GetDataDir(bool fNetSpecific)
if (!path.empty())
return path;
- if (IsArgSet("-datadir")) {
- path = fs::system_complete(GetArg("-datadir", ""));
+ if (gArgs.IsArgSet("-datadir")) {
+ path = fs::system_complete(gArgs.GetArg("-datadir", ""));
if (!fs::is_directory(path)) {
path = "";
return path;
@@ -627,7 +625,7 @@ void ArgsManager::ReadConfigFile(const std::string& confPath)
#ifndef WIN32
fs::path GetPidFile()
{
- fs::path pathPidFile(GetArg("-pid", BITCOIN_PID_FILENAME));
+ fs::path pathPidFile(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
diff --git a/src/util.h b/src/util.h
index b01606cb8f..480a80c0a3 100644
--- a/src/util.h
+++ b/src/util.h
@@ -195,13 +195,20 @@ inline bool IsSwitchChar(char c)
class ArgsManager
{
protected:
- CCriticalSection cs_args;
+ mutable CCriticalSection cs_args;
std::map<std::string, std::string> mapArgs;
- std::map<std::string, std::vector<std::string> > mapMultiArgs;
+ std::map<std::string, std::vector<std::string>> mapMultiArgs;
public:
void ParseParameters(int argc, const char*const argv[]);
void ReadConfigFile(const std::string& confPath);
- std::vector<std::string> GetArgs(const std::string& strArg);
+
+ /**
+ * Return a vector of strings of the given argument
+ *
+ * @param strArg Argument to get (e.g. "-foo")
+ * @return command-line arguments
+ */
+ std::vector<std::string> GetArgs(const std::string& strArg) const;
/**
* Return true if the given argument has been manually set
@@ -209,7 +216,7 @@ public:
* @param strArg Argument to get (e.g. "-foo")
* @return true if the argument has been set
*/
- bool IsArgSet(const std::string& strArg);
+ bool IsArgSet(const std::string& strArg) const;
/**
* Return string argument or default value
@@ -218,7 +225,7 @@ public:
* @param strDefault (e.g. "1")
* @return command-line argument or default value
*/
- std::string GetArg(const std::string& strArg, const std::string& strDefault);
+ std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
/**
* Return integer argument or default value
@@ -227,7 +234,7 @@ public:
* @param nDefault (e.g. 1)
* @return command-line argument (0 if invalid number) or default value
*/
- int64_t GetArg(const std::string& strArg, int64_t nDefault);
+ int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
/**
* Return boolean argument or default value
@@ -236,7 +243,7 @@ public:
* @param fDefault (true or false)
* @return command-line argument or default value
*/
- bool GetBoolArg(const std::string& strArg, bool fDefault);
+ bool GetBoolArg(const std::string& strArg, bool fDefault) const;
/**
* Set an argument if it doesn't already have a value
@@ -263,52 +270,6 @@ public:
extern ArgsManager gArgs;
-// wrappers using the global ArgsManager:
-static inline void ParseParameters(int argc, const char*const argv[])
-{
- gArgs.ParseParameters(argc, argv);
-}
-
-static inline void ReadConfigFile(const std::string& confPath)
-{
- gArgs.ReadConfigFile(confPath);
-}
-
-static inline bool SoftSetArg(const std::string& strArg, const std::string& strValue)
-{
- return gArgs.SoftSetArg(strArg, strValue);
-}
-
-static inline void ForceSetArg(const std::string& strArg, const std::string& strValue)
-{
- gArgs.ForceSetArg(strArg, strValue);
-}
-
-static inline bool IsArgSet(const std::string& strArg)
-{
- return gArgs.IsArgSet(strArg);
-}
-
-static inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
-{
- return gArgs.GetArg(strArg, strDefault);
-}
-
-static inline int64_t GetArg(const std::string& strArg, int64_t nDefault)
-{
- return gArgs.GetArg(strArg, nDefault);
-}
-
-static inline bool GetBoolArg(const std::string& strArg, bool fDefault)
-{
- return gArgs.GetBoolArg(strArg, fDefault);
-}
-
-static inline bool SoftSetBoolArg(const std::string& strArg, bool fValue)
-{
- return gArgs.SoftSetBoolArg(strArg, fValue);
-}
-
/**
* Format a string to be used as group of options in help messages
*
diff --git a/src/validation.cpp b/src/validation.cpp
index f21700c673..3b9636839d 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -53,6 +53,9 @@
# error "Bitcoin cannot be compiled without assertions."
#endif
+#define MICRO 0.000001
+#define MILLI 0.001
+
/**
* Global state
*/
@@ -398,7 +401,7 @@ void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool f
// We also need to remove any now-immature transactions
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
// Re-limit mempool size, in case we added any transactions
- LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
+ LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
}
// Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
@@ -456,7 +459,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// Reject transactions with witness before segregated witness activates (override with -prematurewitness)
bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
- if (!GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
+ if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
}
@@ -611,7 +614,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
strprintf("%d", nSigOpsCost));
- CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
+ CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
}
@@ -628,10 +631,10 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// Calculate in-mempool ancestors, up to a limit.
CTxMemPool::setEntries setAncestors;
- size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
- size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
- size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
- size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
+ size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
+ size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
+ size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
+ size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
@@ -783,7 +786,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
if (!chainparams.RequireStandard()) {
- scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
+ scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
}
// Check against previous transactions
@@ -860,7 +863,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// trim mempool and check if tx was trimmed
if (!fOverrideMempoolLimit) {
- LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
+ LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
if (!pool.exists(hash))
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
}
@@ -1061,7 +1064,7 @@ CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
static void AlertNotify(const std::string& strMessage)
{
uiInterface.NotifyAlertChanged();
- std::string strCmd = GetArg("-alertnotify", "");
+ std::string strCmd = gArgs.GetArg("-alertnotify", "");
if (strCmd.empty()) return;
// Alert text should be plain ascii coming from a trusted source, but to
@@ -1216,7 +1219,7 @@ static uint256 scriptExecutionCacheNonce(GetRandHash());
void InitScriptExecutionCache() {
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
- size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
+ size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
@@ -1563,7 +1566,7 @@ private:
int bit;
public:
- WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
+ explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
@@ -1623,6 +1626,7 @@ static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
+static int64_t nBlocksTotal = 0;
/** Apply the effects of this block (with given index) on the UTXO set represented by coins.
* Validity checks that depend on the UTXO set are also done; ConnectBlock()
@@ -1653,6 +1657,8 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
return true;
}
+ nBlocksTotal++;
+
bool fScriptChecks = true;
if (!hashAssumeValid.IsNull()) {
// We've been configured with the hash of a block which has been externally verified to have a valid history.
@@ -1680,7 +1686,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
}
int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
- LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
+ LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
@@ -1729,7 +1735,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
- LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
+ LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
CBlockUndo blockundo;
@@ -1803,7 +1809,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
- LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
+ LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
if (block.vtx[0]->GetValueOut() > blockReward)
@@ -1815,7 +1821,7 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
if (!control.Wait())
return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
- LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
+ LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
if (fJustCheck)
return true;
@@ -1847,10 +1853,10 @@ static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockInd
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
- LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
+ LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
- LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
+ LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
return true;
}
@@ -1900,7 +1906,7 @@ bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &
if (nLastSetChain == 0) {
nLastSetChain = nNow;
}
- int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
+ int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
// The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
@@ -2075,7 +2081,7 @@ bool static DisconnectTip(CValidationState& state, const CChainParams& chainpara
bool flushed = view.Flush();
assert(flushed);
}
- LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
+ LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
return false;
@@ -2135,7 +2141,7 @@ private:
CTxMemPool &pool;
public:
- ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
+ explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
}
@@ -2196,7 +2202,7 @@ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams,
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
- LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
+ LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
{
CCoinsViewCache view(pcoinsTip);
bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
@@ -2207,17 +2213,17 @@ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams,
return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
}
nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
- LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
+ LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
bool flushed = view.Flush();
assert(flushed);
}
int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
- LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
+ LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
return false;
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
- LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
+ LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
// Remove conflicting transactions from the mempool.;
mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
disconnectpool.removeForBlock(blockConnecting.vtx);
@@ -2225,8 +2231,8 @@ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams,
UpdateTip(pindexNew, chainparams);
int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
- LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
- LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
+ LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
+ LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
return true;
@@ -2421,7 +2427,7 @@ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams,
CBlockIndex *pindexMostWork = nullptr;
CBlockIndex *pindexNewTip = nullptr;
- int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
+ int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
do {
boost::this_thread::interruption_point();
if (ShutdownRequested())
@@ -3892,7 +3898,7 @@ bool LoadBlockIndex(const CChainParams& chainparams)
LogPrintf("Initializing databases...\n");
// Use the provided setting for -txindex in the new database
- fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
+ fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
pblocktree->WriteFlag("txindex", fTxIndex);
}
return true;
@@ -4263,7 +4269,7 @@ static const uint64_t MEMPOOL_DUMP_VERSION = 1;
bool LoadMempool(void)
{
const CChainParams& chainparams = Params();
- int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
+ int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
if (file.IsNull()) {
@@ -4367,7 +4373,7 @@ void DumpMempool(void)
file.fclose();
RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
int64_t last = GetTimeMicros();
- LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
+ LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
} catch (const std::exception& e) {
LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
}
diff --git a/src/validation.h b/src/validation.h
index edb8eab894..d0f6cdc135 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -365,7 +365,7 @@ private:
PrecomputedTransactionData *txdata;
public:
- CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
+ CScriptCheck(): amount(0), ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
CScriptCheck(const CScript& scriptPubKeyIn, const CAmount amountIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
scriptPubKey(scriptPubKeyIn), amount(amountIn),
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp
index bf20d606f8..be5029dec3 100644
--- a/src/validationinterface.cpp
+++ b/src/validationinterface.cpp
@@ -30,7 +30,7 @@ struct MainSignalsInstance {
// our own queue here :(
SingleThreadedSchedulerClient m_schedulerClient;
- MainSignalsInstance(CScheduler *pscheduler) : m_schedulerClient(pscheduler) {}
+ explicit MainSignalsInstance(CScheduler *pscheduler) : m_schedulerClient(pscheduler) {}
};
static CMainSignals g_signals;
diff --git a/src/versionbits.cpp b/src/versionbits.cpp
index 04a692d826..64ae939672 100644
--- a/src/versionbits.cpp
+++ b/src/versionbits.cpp
@@ -107,7 +107,7 @@ ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex*
// return the numerical statistics of blocks signalling the specified BIP9 condition in this current period
BIP9Stats AbstractThresholdConditionChecker::GetStateStatisticsFor(const CBlockIndex* pindex, const Consensus::Params& params) const
{
- BIP9Stats stats;
+ BIP9Stats stats = {};
stats.period = Period(params);
stats.threshold = Threshold(params);
@@ -185,7 +185,7 @@ protected:
}
public:
- VersionBitsConditionChecker(Consensus::DeploymentPos id_) : id(id_) {}
+ explicit VersionBitsConditionChecker(Consensus::DeploymentPos id_) : id(id_) {}
uint32_t Mask(const Consensus::Params& params) const { return ((uint32_t)1) << params.vDeployments[id].bit; }
};
diff --git a/src/wallet/crypter.h b/src/wallet/crypter.h
index 1dc44e424f..f1e8a25650 100644
--- a/src/wallet/crypter.h
+++ b/src/wallet/crypter.h
@@ -113,7 +113,6 @@ public:
class CCryptoKeyStore : public CBasicKeyStore
{
private:
- CryptedKeyMap mapCryptedKeys;
CKeyingMaterial vMasterKey;
@@ -131,6 +130,7 @@ protected:
bool EncryptKeys(CKeyingMaterial& vMasterKeyIn);
bool Unlock(const CKeyingMaterial& vMasterKeyIn);
+ CryptedKeyMap mapCryptedKeys;
public:
CCryptoKeyStore() : fUseCrypto(false), fDecryptionThoroughlyChecked(false)
diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp
index 4c06c2c1f9..d2fe4866fa 100644
--- a/src/wallet/db.cpp
+++ b/src/wallet/db.cpp
@@ -78,7 +78,7 @@ bool CDBEnv::Open(const fs::path& pathIn)
LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
- if (GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB))
+ if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB))
nEnvFlags |= DB_PRIVATE;
dbenv->set_lg_dir(pathLogDir.string().c_str());
@@ -101,8 +101,10 @@ bool CDBEnv::Open(const fs::path& pathIn)
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
- if (ret != 0)
+ if (ret != 0) {
+ dbenv->close(0);
return error("CDBEnv::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
+ }
fDbEnvInit = true;
fMockDb = false;
@@ -196,9 +198,9 @@ bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*reco
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
- if (ret > 0)
- {
+ if (ret > 0) {
LogPrintf("Cannot create database file %s\n", filename);
+ pdbCopy->close(0);
return false;
}
@@ -429,7 +431,7 @@ void CDB::Flush()
if (fReadOnly)
nMinutes = 1;
- env->dbenv->txn_checkpoint(nMinutes ? GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
+ env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
}
void CWalletDBWrapper::IncrementUpdateCounter()
@@ -536,8 +538,10 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
env->CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
- delete pdbCopy;
+ } else {
+ pdbCopy->close(0);
}
+ delete pdbCopy;
}
if (fSuccess) {
Db dbA(env->dbenv, 0);
diff --git a/src/wallet/db.h b/src/wallet/db.h
index 3614e34fbb..6f3cfe9557 100644
--- a/src/wallet/db.h
+++ b/src/wallet/db.h
@@ -45,7 +45,7 @@ public:
void Reset();
void MakeMock();
- bool IsMock() { return fMockDb; }
+ bool IsMock() const { return fMockDb; }
/**
* Verify that database file strFile is OK. If it is not,
diff --git a/src/wallet/feebumper.cpp b/src/wallet/feebumper.cpp
index 4bfd8726a5..6abd060714 100644
--- a/src/wallet/feebumper.cpp
+++ b/src/wallet/feebumper.cpp
@@ -5,6 +5,7 @@
#include "consensus/validation.h"
#include "wallet/coincontrol.h"
#include "wallet/feebumper.h"
+#include "wallet/fees.h"
#include "wallet/wallet.h"
#include "policy/fees.h"
#include "policy/policy.h"
@@ -76,12 +77,12 @@ CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, const CCoin
vErrors.clear();
bumpedTxid.SetNull();
AssertLockHeld(pWallet->cs_wallet);
- if (!pWallet->mapWallet.count(txid)) {
+ auto it = pWallet->mapWallet.find(txid);
+ if (it == pWallet->mapWallet.end()) {
vErrors.push_back("Invalid or non-wallet transaction id");
currentResult = BumpFeeResult::INVALID_ADDRESS_OR_KEY;
return;
}
- auto it = pWallet->mapWallet.find(txid);
const CWalletTx& wtx = it->second;
if (!preconditionChecks(pWallet, wtx)) {
@@ -156,7 +157,7 @@ CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, const CCoin
currentResult = BumpFeeResult::INVALID_PARAMETER;
return;
}
- CAmount requiredFee = CWallet::GetRequiredFee(maxNewTxSize);
+ CAmount requiredFee = GetRequiredFee(maxNewTxSize);
if (totalFee < requiredFee) {
vErrors.push_back(strprintf("Insufficient totalFee (cannot be less than required fee %s)",
FormatMoney(requiredFee)));
@@ -166,7 +167,7 @@ CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, const CCoin
nNewFee = totalFee;
nNewFeeRate = CFeeRate(totalFee, maxNewTxSize);
} else {
- nNewFee = CWallet::GetMinimumFee(maxNewTxSize, coin_control, mempool, ::feeEstimator, nullptr /* FeeCalculation */);
+ nNewFee = GetMinimumFee(maxNewTxSize, coin_control, mempool, ::feeEstimator, nullptr /* FeeCalculation */);
nNewFeeRate = CFeeRate(nNewFee, maxNewTxSize);
// New fee rate must be at least old rate + minimum incremental relay rate
@@ -193,7 +194,7 @@ CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, const CCoin
// This may occur if the user set TotalFee or paytxfee too low, if fallbackfee is too low, or, perhaps,
// in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
// moment earlier. In this case, we report an error to the user, who may use totalFee to make an adjustment.
- CFeeRate minMempoolFeeRate = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
+ CFeeRate minMempoolFeeRate = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
if (nNewFeeRate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) {
vErrors.push_back(strprintf("New fee rate (%s) is less than the minimum fee rate (%s) to get into the mempool. totalFee value should to be at least %s or settxfee value should be at least %s to add transaction.", FormatMoney(nNewFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFee(maxNewTxSize)), FormatMoney(minMempoolFeeRate.GetFeePerK())));
currentResult = BumpFeeResult::WALLET_ERROR;
@@ -241,12 +242,13 @@ bool CFeeBumper::commit(CWallet *pWallet)
if (!vErrors.empty() || currentResult != BumpFeeResult::OK) {
return false;
}
- if (txid.IsNull() || !pWallet->mapWallet.count(txid)) {
+ auto it = txid.IsNull() ? pWallet->mapWallet.end() : pWallet->mapWallet.find(txid);
+ if (it == pWallet->mapWallet.end()) {
vErrors.push_back("Invalid or non-wallet transaction id");
currentResult = BumpFeeResult::MISC_ERROR;
return false;
}
- CWalletTx& oldWtx = pWallet->mapWallet[txid];
+ CWalletTx& oldWtx = it->second;
// make sure the transaction still has no descendants and hasn't been mined in the meantime
if (!preconditionChecks(pWallet, oldWtx)) {
diff --git a/src/wallet/fees.cpp b/src/wallet/fees.cpp
new file mode 100644
index 0000000000..76eeeeda05
--- /dev/null
+++ b/src/wallet/fees.cpp
@@ -0,0 +1,89 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "wallet/fees.h"
+
+#include "policy/policy.h"
+#include "txmempool.h"
+#include "util.h"
+#include "validation.h"
+#include "wallet/coincontrol.h"
+#include "wallet/wallet.h"
+
+
+CAmount GetRequiredFee(unsigned int nTxBytes)
+{
+ return std::max(CWallet::minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
+}
+
+
+CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
+{
+ /* User control of how to calculate fee uses the following parameter precedence:
+ 1. coin_control.m_feerate
+ 2. coin_control.m_confirm_target
+ 3. payTxFee (user-set global variable)
+ 4. nTxConfirmTarget (user-set global variable)
+ The first parameter that is set is used.
+ */
+ CAmount fee_needed;
+ if (coin_control.m_feerate) { // 1.
+ fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
+ if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
+ // Allow to override automatic min/max check over coin control instance
+ if (coin_control.fOverrideFeeRate) return fee_needed;
+ }
+ else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
+ fee_needed = ::payTxFee.GetFee(nTxBytes);
+ if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
+ }
+ else { // 2. or 4.
+ // We will use smart fee estimation
+ unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
+ // By default estimates are economical iff we are signaling opt-in-RBF
+ bool conservative_estimate = !coin_control.signalRbf;
+ // Allow to override the default fee estimate mode over the CoinControl instance
+ if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
+ else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
+
+ fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
+ if (fee_needed == 0) {
+ // if we don't have enough data for estimateSmartFee, then use fallbackFee
+ fee_needed = CWallet::fallbackFee.GetFee(nTxBytes);
+ if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
+ }
+ // Obey mempool min fee when using smart fee estimation
+ CAmount min_mempool_fee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
+ if (fee_needed < min_mempool_fee) {
+ fee_needed = min_mempool_fee;
+ if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
+ }
+ }
+
+ // prevent user from paying a fee below minRelayTxFee or minTxFee
+ CAmount required_fee = GetRequiredFee(nTxBytes);
+ if (required_fee > fee_needed) {
+ fee_needed = required_fee;
+ if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
+ }
+ // But always obey the maximum
+ if (fee_needed > maxTxFee) {
+ fee_needed = maxTxFee;
+ if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
+ }
+ return fee_needed;
+}
+
+
+CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
+{
+ unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
+ CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
+ // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
+ discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
+ // Discard rate must be at least dustRelayFee
+ discard_rate = std::max(discard_rate, ::dustRelayFee);
+ return discard_rate;
+}
diff --git a/src/wallet/fees.h b/src/wallet/fees.h
new file mode 100644
index 0000000000..7b8a7dc868
--- /dev/null
+++ b/src/wallet/fees.h
@@ -0,0 +1,34 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_WALLET_FEES_H
+#define BITCOIN_WALLET_FEES_H
+
+#include "amount.h"
+
+class CBlockPolicyEstimator;
+class CCoinControl;
+class CFeeRate;
+class CTxMemPool;
+struct FeeCalculation;
+
+/**
+ * Return the minimum required fee taking into account the
+ * floating relay fee and user set minimum transaction fee
+ */
+CAmount GetRequiredFee(unsigned int nTxBytes);
+
+/**
+ * Estimate the minimum fee considering user set parameters
+ * and the required fee
+ */
+CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc);
+
+/**
+ * Return the maximum feerate for discarding change.
+ */
+CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator);
+
+#endif // BITCOIN_WALLET_FEES_H
diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp
new file mode 100644
index 0000000000..18365b1b72
--- /dev/null
+++ b/src/wallet/init.cpp
@@ -0,0 +1,247 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "wallet/init.h"
+
+#include "net.h"
+#include "util.h"
+#include "utilmoneystr.h"
+#include "validation.h"
+#include "wallet/wallet.h"
+
+std::string GetWalletHelpString(bool showDebug)
+{
+ std::string strUsage = HelpMessageGroup(_("Wallet options:"));
+ strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
+ strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
+ strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
+ CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
+ strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
+ "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target"),
+ CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
+ strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
+ CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
+ strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
+ CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
+ strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
+ strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
+ strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
+ strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
+ strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
+ strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
+ strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
+ strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
+ strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
+ strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
+ strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
+ " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
+
+ if (showDebug)
+ {
+ strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
+
+ strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
+ strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
+ strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
+ strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
+ }
+
+ return strUsage;
+}
+
+bool WalletParameterInteraction()
+{
+ gArgs.SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
+ const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
+
+ if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
+ return true;
+
+ if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
+ LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
+ }
+
+ if (gArgs.GetBoolArg("-salvagewallet", false)) {
+ if (is_multiwallet) {
+ return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
+ }
+ // Rewrite just private keys: rescan to find transactions
+ if (gArgs.SoftSetBoolArg("-rescan", true)) {
+ LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
+ }
+ }
+
+ int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0);
+ // -zapwallettxes implies dropping the mempool on startup
+ if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) {
+ LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
+ }
+
+ // -zapwallettxes implies a rescan
+ if (zapwallettxes != 0) {
+ if (is_multiwallet) {
+ return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
+ }
+ if (gArgs.SoftSetBoolArg("-rescan", true)) {
+ LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
+ }
+ }
+
+ if (is_multiwallet) {
+ if (gArgs.GetBoolArg("-upgradewallet", false)) {
+ return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
+ }
+ }
+
+ if (gArgs.GetBoolArg("-sysperms", false))
+ return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
+ if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false))
+ return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
+
+ if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
+ InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
+ _("The wallet will avoid paying less than the minimum relay fee."));
+
+ if (gArgs.IsArgSet("-mintxfee"))
+ {
+ CAmount n = 0;
+ if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n)
+ return InitError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")));
+ if (n > HIGH_TX_FEE_PER_KB)
+ InitWarning(AmountHighWarn("-mintxfee") + " " +
+ _("This is the minimum transaction fee you pay on every transaction."));
+ CWallet::minTxFee = CFeeRate(n);
+ }
+ if (gArgs.IsArgSet("-fallbackfee"))
+ {
+ CAmount nFeePerK = 0;
+ if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK))
+ return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", "")));
+ if (nFeePerK > HIGH_TX_FEE_PER_KB)
+ InitWarning(AmountHighWarn("-fallbackfee") + " " +
+ _("This is the transaction fee you may pay when fee estimates are not available."));
+ CWallet::fallbackFee = CFeeRate(nFeePerK);
+ }
+ if (gArgs.IsArgSet("-discardfee"))
+ {
+ CAmount nFeePerK = 0;
+ if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK))
+ return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", "")));
+ if (nFeePerK > HIGH_TX_FEE_PER_KB)
+ InitWarning(AmountHighWarn("-discardfee") + " " +
+ _("This is the transaction fee you may discard if change is smaller than dust at this level"));
+ CWallet::m_discard_rate = CFeeRate(nFeePerK);
+ }
+ if (gArgs.IsArgSet("-paytxfee"))
+ {
+ CAmount nFeePerK = 0;
+ if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK))
+ return InitError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")));
+ if (nFeePerK > HIGH_TX_FEE_PER_KB)
+ InitWarning(AmountHighWarn("-paytxfee") + " " +
+ _("This is the transaction fee you will pay if you send a transaction."));
+
+ payTxFee = CFeeRate(nFeePerK, 1000);
+ if (payTxFee < ::minRelayTxFee)
+ {
+ return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
+ gArgs.GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
+ }
+ }
+ if (gArgs.IsArgSet("-maxtxfee"))
+ {
+ CAmount nMaxFee = 0;
+ if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
+ return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
+ if (nMaxFee > HIGH_MAX_TX_FEE)
+ InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
+ maxTxFee = nMaxFee;
+ if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
+ {
+ return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
+ gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
+ }
+ }
+ nTxConfirmTarget = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
+ bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
+ fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
+
+ return true;
+}
+
+bool WalletVerify()
+{
+ if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
+ return true;
+
+ uiInterface.InitMessage(_("Verifying wallet(s)..."));
+
+ // Keep track of each wallet absolute path to detect duplicates.
+ std::set<fs::path> wallet_paths;
+
+ for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
+ if (boost::filesystem::path(walletFile).filename() != walletFile) {
+ return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile));
+ }
+
+ if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
+ return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile));
+ }
+
+ fs::path wallet_path = fs::absolute(walletFile, GetDataDir());
+
+ if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) {
+ return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile));
+ }
+
+ if (!wallet_paths.insert(wallet_path).second) {
+ return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
+ }
+
+ std::string strError;
+ if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
+ return InitError(strError);
+ }
+
+ if (gArgs.GetBoolArg("-salvagewallet", false)) {
+ // Recover readable keypairs:
+ CWallet dummyWallet;
+ std::string backup_filename;
+ if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
+ return false;
+ }
+ }
+
+ std::string strWarning;
+ bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
+ if (!strWarning.empty()) {
+ InitWarning(strWarning);
+ }
+ if (!dbV) {
+ InitError(strError);
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool InitLoadWallet()
+{
+ if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
+ LogPrintf("Wallet disabled!\n");
+ return true;
+ }
+
+ for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
+ CWallet * const pwallet = CWallet::CreateWalletFromFile(walletFile);
+ if (!pwallet) {
+ return false;
+ }
+ vpwallets.push_back(pwallet);
+ }
+
+ return true;
+}
diff --git a/src/wallet/init.h b/src/wallet/init.h
new file mode 100644
index 0000000000..fa2251506d
--- /dev/null
+++ b/src/wallet/init.h
@@ -0,0 +1,25 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_WALLET_INIT_H
+#define BITCOIN_WALLET_INIT_H
+
+#include <string>
+
+//! Return the wallets help message.
+std::string GetWalletHelpString(bool showDebug);
+
+//! Wallets parameter interaction
+bool WalletParameterInteraction();
+
+//! Responsible for reading and validating the -wallet arguments and verifying the wallet database.
+// This function will perform salvage on the wallet if requested, as long as only one wallet is
+// being loaded (CWallet::ParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet).
+bool WalletVerify();
+
+//! Load wallet databases.
+bool InitLoadWallet();
+
+#endif // BITCOIN_WALLET_INIT_H
diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp
index 67c6d9ec64..db6f6b48ac 100644
--- a/src/wallet/rpcdump.cpp
+++ b/src/wallet/rpcdump.cpp
@@ -4,6 +4,7 @@
#include "base58.h"
#include "chain.h"
+#include "rpc/safemode.h"
#include "rpc/server.h"
#include "init.h"
#include "validation.h"
@@ -174,6 +175,7 @@ UniValue abortrescan(const JSONRPCRequest& request)
+ HelpExampleRpc("abortrescan", "")
);
+ ObserveSafeMode();
if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;
pwallet->AbortRescan();
return true;
diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
index 8ef33f248b..e3639e4682 100644
--- a/src/wallet/rpcwallet.cpp
+++ b/src/wallet/rpcwallet.cpp
@@ -8,7 +8,6 @@
#include "chain.h"
#include "consensus/validation.h"
#include "core_io.h"
-#include "init.h"
#include "httpserver.h"
#include "validation.h"
#include "net.h"
@@ -17,6 +16,7 @@
#include "policy/policy.h"
#include "policy/rbf.h"
#include "rpc/mining.h"
+#include "rpc/safemode.h"
#include "rpc/server.h"
#include "script/sign.h"
#include "timedata.h"
@@ -27,6 +27,8 @@
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
+#include <init.h> // For StartShutdown
+
#include <stdint.h>
#include <univalue.h>
@@ -280,7 +282,7 @@ UniValue setaccount(const JSONRPCRequest& request)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
std::string strAccount;
- if (request.params.size() > 1)
+ if (!request.params[1].isNull())
strAccount = AccountFromValue(request.params[1]);
// Only add the account if the address is yours.
@@ -449,6 +451,7 @@ UniValue sendtoaddress(const JSONRPCRequest& request)
+ HelpExampleRpc("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.1, \"donation\", \"seans outpost\"")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
CBitcoinAddress address(request.params[0].get_str());
@@ -462,26 +465,26 @@ UniValue sendtoaddress(const JSONRPCRequest& request)
// Wallet comments
CWalletTx wtx;
- if (request.params.size() > 2 && !request.params[2].isNull() && !request.params[2].get_str().empty())
+ if (!request.params[2].isNull() && !request.params[2].get_str().empty())
wtx.mapValue["comment"] = request.params[2].get_str();
- if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty())
+ if (!request.params[3].isNull() && !request.params[3].get_str().empty())
wtx.mapValue["to"] = request.params[3].get_str();
bool fSubtractFeeFromAmount = false;
- if (request.params.size() > 4 && !request.params[4].isNull()) {
+ if (!request.params[4].isNull()) {
fSubtractFeeFromAmount = request.params[4].get_bool();
}
CCoinControl coin_control;
- if (request.params.size() > 5 && !request.params[5].isNull()) {
+ if (!request.params[5].isNull()) {
coin_control.signalRbf = request.params[5].get_bool();
}
- if (request.params.size() > 6 && !request.params[6].isNull()) {
+ if (!request.params[6].isNull()) {
coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
}
- if (request.params.size() > 7 && !request.params[7].isNull()) {
+ if (!request.params[7].isNull()) {
if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
}
@@ -525,6 +528,7 @@ UniValue listaddressgroupings(const JSONRPCRequest& request)
+ HelpExampleRpc("listaddressgroupings", "")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
@@ -634,6 +638,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request)
+ HelpExampleRpc("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", 6")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
// Bitcoin address
@@ -694,6 +699,7 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request)
+ HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
// Minimum confirmations
@@ -766,20 +772,34 @@ UniValue getbalance(const JSONRPCRequest& request)
+ HelpExampleRpc("getbalance", "\"*\", 6")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
- if (request.params.size() == 0)
- return ValueFromAmount(pwallet->GetBalance());
+ const UniValue& account_value = request.params[0];
+ const UniValue& minconf = request.params[1];
+ const UniValue& include_watchonly = request.params[2];
+
+ if (account_value.isNull()) {
+ if (!minconf.isNull()) {
+ throw JSONRPCError(RPC_INVALID_PARAMETER,
+ "getbalance minconf option is only currently supported if an account is specified");
+ }
+ if (!include_watchonly.isNull()) {
+ throw JSONRPCError(RPC_INVALID_PARAMETER,
+ "getbalance include_watchonly option is only currently supported if an account is specified");
+ }
+ return ValueFromAmount(pwallet->GetBalance());
+ }
- const std::string& account_param = request.params[0].get_str();
+ const std::string& account_param = account_value.get_str();
const std::string* account = account_param != "*" ? &account_param : nullptr;
int nMinDepth = 1;
- if (!request.params[1].isNull())
- nMinDepth = request.params[1].get_int();
+ if (!minconf.isNull())
+ nMinDepth = minconf.get_int();
isminefilter filter = ISMINE_SPENDABLE;
- if(!request.params[2].isNull())
- if(request.params[2].get_bool())
+ if(!include_watchonly.isNull())
+ if(include_watchonly.get_bool())
filter = filter | ISMINE_WATCH_ONLY;
return ValueFromAmount(pwallet->GetLegacyBalance(filter, nMinDepth, account));
@@ -797,6 +817,7 @@ UniValue getunconfirmedbalance(const JSONRPCRequest &request)
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
return ValueFromAmount(pwallet->GetUnconfirmedBalance());
@@ -831,6 +852,7 @@ UniValue movecmd(const JSONRPCRequest& request)
+ HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
std::string strFrom = AccountFromValue(request.params[0]);
@@ -838,11 +860,11 @@ UniValue movecmd(const JSONRPCRequest& request)
CAmount nAmount = AmountFromValue(request.params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
- if (request.params.size() > 3)
+ if (!request.params[3].isNull())
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)request.params[3].get_int();
std::string strComment;
- if (request.params.size() > 4)
+ if (!request.params[4].isNull())
strComment = request.params[4].get_str();
if (!pwallet->AccountMove(strFrom, strTo, nAmount, strComment)) {
@@ -889,6 +911,7 @@ UniValue sendfrom(const JSONRPCRequest& request)
+ HelpExampleRpc("sendfrom", "\"tabby\", \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.01, 6, \"donation\", \"seans outpost\"")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
std::string strAccount = AccountFromValue(request.params[0]);
@@ -899,14 +922,14 @@ UniValue sendfrom(const JSONRPCRequest& request)
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
int nMinDepth = 1;
- if (request.params.size() > 3)
+ if (!request.params[3].isNull())
nMinDepth = request.params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
- if (request.params.size() > 4 && !request.params[4].isNull() && !request.params[4].get_str().empty())
+ if (!request.params[4].isNull() && !request.params[4].get_str().empty())
wtx.mapValue["comment"] = request.params[4].get_str();
- if (request.params.size() > 5 && !request.params[5].isNull() && !request.params[5].get_str().empty())
+ if (!request.params[5].isNull() && !request.params[5].get_str().empty())
wtx.mapValue["to"] = request.params[5].get_str();
EnsureWalletIsUnlocked(pwallet);
@@ -972,6 +995,7 @@ UniValue sendmany(const JSONRPCRequest& request)
+ HelpExampleRpc("sendmany", "\"\", \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\", 6, \"testing\"")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
if (pwallet->GetBroadcastTransactions() && !g_connman) {
@@ -986,23 +1010,23 @@ UniValue sendmany(const JSONRPCRequest& request)
CWalletTx wtx;
wtx.strFromAccount = strAccount;
- if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty())
+ if (!request.params[3].isNull() && !request.params[3].get_str().empty())
wtx.mapValue["comment"] = request.params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
- if (request.params.size() > 4 && !request.params[4].isNull())
+ if (!request.params[4].isNull())
subtractFeeFromAmount = request.params[4].get_array();
CCoinControl coin_control;
- if (request.params.size() > 5 && !request.params[5].isNull()) {
+ if (!request.params[5].isNull()) {
coin_control.signalRbf = request.params[5].get_bool();
}
- if (request.params.size() > 6 && !request.params[6].isNull()) {
+ if (!request.params[6].isNull()) {
coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
}
- if (request.params.size() > 7 && !request.params[7].isNull()) {
+ if (!request.params[7].isNull()) {
if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
}
@@ -1105,7 +1129,7 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
std::string strAccount;
- if (request.params.size() > 2)
+ if (!request.params[2].isNull())
strAccount = AccountFromValue(request.params[2]);
// Construct using pay-to-script-hash:
@@ -1123,7 +1147,7 @@ public:
CWallet * const pwallet;
CScriptID result;
- Witnessifier(CWallet *_pwallet) : pwallet(_pwallet) {}
+ explicit Witnessifier(CWallet *_pwallet) : pwallet(_pwallet) {}
bool operator()(const CNoDestination &dest) const { return false; }
@@ -1134,7 +1158,7 @@ public:
SignatureData sigs;
// This check is to make sure that the script we created can actually be solved for and signed by us
// if we were to have the private keys. This is just to make sure that the script is valid and that,
- // if found in a transaction, we would still accept and relay that transcation.
+ // if found in a transaction, we would still accept and relay that transaction.
if (!ProduceSignature(DummySignatureCreator(pwallet), witscript, sigs) ||
!VerifyScript(sigs.scriptSig, witscript, &sigs.scriptWitness, MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, DummySignatureCreator(pwallet).Checker())) {
return false;
@@ -1159,7 +1183,7 @@ public:
SignatureData sigs;
// This check is to make sure that the script we created can actually be solved for and signed by us
// if we were to have the private keys. This is just to make sure that the script is valid and that,
- // if found in a transaction, we would still accept and relay that transcation.
+ // if found in a transaction, we would still accept and relay that transaction.
if (!ProduceSignature(DummySignatureCreator(pwallet), witscript, sigs) ||
!VerifyScript(sigs.scriptSig, witscript, &sigs.scriptWitness, MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, DummySignatureCreator(pwallet).Checker())) {
return false;
@@ -1197,7 +1221,7 @@ UniValue addwitnessaddress(const JSONRPCRequest& request)
{
LOCK(cs_main);
- if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus()) && !GetBoolArg("-walletprematurewitness", false)) {
+ if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus()) && !gArgs.GetBoolArg("-walletprematurewitness", false)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Segregated witness not enabled on network");
}
}
@@ -1389,6 +1413,7 @@ UniValue listreceivedbyaddress(const JSONRPCRequest& request)
+ HelpExampleRpc("listreceivedbyaddress", "6, true, true")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
return ListReceived(pwallet, request.params, false);
@@ -1428,6 +1453,7 @@ UniValue listreceivedbyaccount(const JSONRPCRequest& request)
+ HelpExampleRpc("listreceivedbyaccount", "6, true, true")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
return ListReceived(pwallet, request.params, true);
@@ -1615,6 +1641,7 @@ UniValue listtransactions(const JSONRPCRequest& request)
+ HelpExampleRpc("listtransactions", "\"*\", 20, 100")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
std::string strAccount = "*";
@@ -1644,10 +1671,10 @@ UniValue listtransactions(const JSONRPCRequest& request)
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
- if (pwtx != 0)
+ if (pwtx != nullptr)
ListTransactions(pwallet, *pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry *const pacentry = (*it).second.second;
- if (pacentry != 0)
+ if (pacentry != nullptr)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
@@ -1708,13 +1735,14 @@ UniValue listaccounts(const JSONRPCRequest& request)
+ HelpExampleRpc("listaccounts", "6")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
int nMinDepth = 1;
- if (request.params.size() > 0)
+ if (!request.params[0].isNull())
nMinDepth = request.params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
- if(request.params.size() > 1)
+ if(!request.params[1].isNull())
if(request.params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
@@ -1816,6 +1844,7 @@ UniValue listsinceblock(const JSONRPCRequest& request)
+ HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
const CBlockIndex* pindex = nullptr; // Block index of the specified block or the common ancestor, if the block provided was in a deactivated chain.
@@ -1874,10 +1903,11 @@ UniValue listsinceblock(const JSONRPCRequest& request)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
}
for (const CTransactionRef& tx : block.vtx) {
- if (pwallet->mapWallet.count(tx->GetHash()) > 0) {
+ auto it = pwallet->mapWallet.find(tx->GetHash());
+ if (it != pwallet->mapWallet.end()) {
// We want all transactions regardless of confirmation count to appear here,
// even negative confirmation ones, hence the big negative.
- ListTransactions(pwallet, pwallet->mapWallet[tx->GetHash()], "*", -100000000, true, removed, filter);
+ ListTransactions(pwallet, it->second, "*", -100000000, true, removed, filter);
}
}
paltindex = paltindex->pprev;
@@ -1946,6 +1976,7 @@ UniValue gettransaction(const JSONRPCRequest& request)
+ HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
uint256 hash;
@@ -1957,10 +1988,11 @@ UniValue gettransaction(const JSONRPCRequest& request)
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
- if (!pwallet->mapWallet.count(hash)) {
+ auto it = pwallet->mapWallet.find(hash);
+ if (it == pwallet->mapWallet.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
}
- const CWalletTx& wtx = pwallet->mapWallet[hash];
+ const CWalletTx& wtx = it->second;
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
@@ -2006,6 +2038,7 @@ UniValue abandontransaction(const JSONRPCRequest& request)
+ HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
uint256 hash;
@@ -2361,19 +2394,18 @@ UniValue lockunspent(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- if (request.params.size() == 1)
- RPCTypeCheck(request.params, {UniValue::VBOOL});
- else
- RPCTypeCheck(request.params, {UniValue::VBOOL, UniValue::VARR});
+ RPCTypeCheckArgument(request.params[0], UniValue::VBOOL);
bool fUnlock = request.params[0].get_bool();
- if (request.params.size() == 1) {
+ if (request.params[1].isNull()) {
if (fUnlock)
pwallet->UnlockAllCoins();
return true;
}
+ RPCTypeCheckArgument(request.params[1], UniValue::VARR);
+
UniValue outputs = request.params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
@@ -2439,6 +2471,7 @@ UniValue listlockunspent(const JSONRPCRequest& request)
+ HelpExampleRpc("listlockunspent", "")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
std::vector<COutPoint> vOutpts;
@@ -2517,6 +2550,7 @@ UniValue getwalletinfo(const JSONRPCRequest& request)
+ HelpExampleRpc("getwalletinfo", "")
);
+ ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
UniValue obj(UniValue::VOBJ);
@@ -2669,20 +2703,22 @@ UniValue listunspent(const JSONRPCRequest& request)
+ HelpExampleRpc("listunspent", "6, 9999999, [] , true, { \"minimumAmount\": 0.005 } ")
);
+ ObserveSafeMode();
+
int nMinDepth = 1;
- if (request.params.size() > 0 && !request.params[0].isNull()) {
+ if (!request.params[0].isNull()) {
RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
nMinDepth = request.params[0].get_int();
}
int nMaxDepth = 9999999;
- if (request.params.size() > 1 && !request.params[1].isNull()) {
+ if (!request.params[1].isNull()) {
RPCTypeCheckArgument(request.params[1], UniValue::VNUM);
nMaxDepth = request.params[1].get_int();
}
std::set<CBitcoinAddress> setAddress;
- if (request.params.size() > 2 && !request.params[2].isNull()) {
+ if (!request.params[2].isNull()) {
RPCTypeCheckArgument(request.params[2], UniValue::VARR);
UniValue inputs = request.params[2].get_array();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
@@ -2697,7 +2733,7 @@ UniValue listunspent(const JSONRPCRequest& request)
}
bool include_unsafe = true;
- if (request.params.size() > 3 && !request.params[3].isNull()) {
+ if (!request.params[3].isNull()) {
RPCTypeCheckArgument(request.params[3], UniValue::VBOOL);
include_unsafe = request.params[3].get_bool();
}
@@ -2797,7 +2833,7 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
" \"changePosition\" (numeric, optional, default random) The index of the change output\n"
" \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n"
" \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n"
- " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific feerate (" + CURRENCY_UNIT + " per KB)\n"
+ " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific fee rate in " + CURRENCY_UNIT + "/kB\n"
" \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n"
" The fee will be equally deducted from the amount of each specified output.\n"
" The outputs are specified by their zero-based index, before any change output is added.\n"
@@ -2830,6 +2866,7 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
+ HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
);
+ ObserveSafeMode();
RPCTypeCheck(request.params, {UniValue::VSTR});
CCoinControl coinControl;
@@ -3112,7 +3149,7 @@ UniValue generate(const JSONRPCRequest& request)
int num_generate = request.params[0].get_int();
uint64_t max_tries = 1000000;
- if (request.params.size() > 1 && !request.params[1].isNull()) {
+ if (!request.params[1].isNull()) {
max_tries = request.params[1].get_int();
}
@@ -3144,65 +3181,65 @@ extern UniValue removeprunedfunds(const JSONRPCRequest& request);
extern UniValue importmulti(const JSONRPCRequest& request);
static const CRPCCommand commands[] =
-{ // category name actor (function) okSafeMode
- // --------------------- ------------------------ ----------------------- ----------
- { "rawtransactions", "fundrawtransaction", &fundrawtransaction, false, {"hexstring","options"} },
- { "hidden", "resendwallettransactions", &resendwallettransactions, true, {} },
- { "wallet", "abandontransaction", &abandontransaction, false, {"txid"} },
- { "wallet", "abortrescan", &abortrescan, false, {} },
- { "wallet", "addmultisigaddress", &addmultisigaddress, true, {"nrequired","keys","account"} },
- { "wallet", "addwitnessaddress", &addwitnessaddress, true, {"address"} },
- { "wallet", "backupwallet", &backupwallet, true, {"destination"} },
- { "wallet", "bumpfee", &bumpfee, true, {"txid", "options"} },
- { "wallet", "dumpprivkey", &dumpprivkey, true, {"address"} },
- { "wallet", "dumpwallet", &dumpwallet, true, {"filename"} },
- { "wallet", "encryptwallet", &encryptwallet, true, {"passphrase"} },
- { "wallet", "getaccountaddress", &getaccountaddress, true, {"account"} },
- { "wallet", "getaccount", &getaccount, true, {"address"} },
- { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, {"account"} },
- { "wallet", "getbalance", &getbalance, false, {"account","minconf","include_watchonly"} },
- { "wallet", "getnewaddress", &getnewaddress, true, {"account"} },
- { "wallet", "getrawchangeaddress", &getrawchangeaddress, true, {} },
- { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, {"account","minconf"} },
- { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, {"address","minconf"} },
- { "wallet", "gettransaction", &gettransaction, false, {"txid","include_watchonly"} },
- { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, {} },
- { "wallet", "getwalletinfo", &getwalletinfo, false, {} },
- { "wallet", "importmulti", &importmulti, true, {"requests","options"} },
- { "wallet", "importprivkey", &importprivkey, true, {"privkey","label","rescan"} },
- { "wallet", "importwallet", &importwallet, true, {"filename"} },
- { "wallet", "importaddress", &importaddress, true, {"address","label","rescan","p2sh"} },
- { "wallet", "importprunedfunds", &importprunedfunds, true, {"rawtransaction","txoutproof"} },
- { "wallet", "importpubkey", &importpubkey, true, {"pubkey","label","rescan"} },
- { "wallet", "keypoolrefill", &keypoolrefill, true, {"newsize"} },
- { "wallet", "listaccounts", &listaccounts, false, {"minconf","include_watchonly"} },
- { "wallet", "listaddressgroupings", &listaddressgroupings, false, {} },
- { "wallet", "listlockunspent", &listlockunspent, false, {} },
- { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, {"minconf","include_empty","include_watchonly"} },
- { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, {"minconf","include_empty","include_watchonly"} },
- { "wallet", "listsinceblock", &listsinceblock, false, {"blockhash","target_confirmations","include_watchonly","include_removed"} },
- { "wallet", "listtransactions", &listtransactions, false, {"account","count","skip","include_watchonly"} },
- { "wallet", "listunspent", &listunspent, false, {"minconf","maxconf","addresses","include_unsafe","query_options"} },
- { "wallet", "listwallets", &listwallets, true, {} },
- { "wallet", "lockunspent", &lockunspent, true, {"unlock","transactions"} },
- { "wallet", "move", &movecmd, false, {"fromaccount","toaccount","amount","minconf","comment"} },
- { "wallet", "sendfrom", &sendfrom, false, {"fromaccount","toaddress","amount","minconf","comment","comment_to"} },
- { "wallet", "sendmany", &sendmany, false, {"fromaccount","amounts","minconf","comment","subtractfeefrom","replaceable","conf_target","estimate_mode"} },
- { "wallet", "sendtoaddress", &sendtoaddress, false, {"address","amount","comment","comment_to","subtractfeefromamount","replaceable","conf_target","estimate_mode"} },
- { "wallet", "setaccount", &setaccount, true, {"address","account"} },
- { "wallet", "settxfee", &settxfee, true, {"amount"} },
- { "wallet", "signmessage", &signmessage, true, {"address","message"} },
- { "wallet", "walletlock", &walletlock, true, {} },
- { "wallet", "walletpassphrasechange", &walletpassphrasechange, true, {"oldpassphrase","newpassphrase"} },
- { "wallet", "walletpassphrase", &walletpassphrase, true, {"passphrase","timeout"} },
- { "wallet", "removeprunedfunds", &removeprunedfunds, true, {"txid"} },
-
- { "generating", "generate", &generate, true, {"nblocks","maxtries"} },
+{ // category name actor (function) argNames
+ // --------------------- ------------------------ ----------------------- ----------
+ { "rawtransactions", "fundrawtransaction", &fundrawtransaction, {"hexstring","options"} },
+ { "hidden", "resendwallettransactions", &resendwallettransactions, {} },
+ { "wallet", "abandontransaction", &abandontransaction, {"txid"} },
+ { "wallet", "abortrescan", &abortrescan, {} },
+ { "wallet", "addmultisigaddress", &addmultisigaddress, {"nrequired","keys","account"} },
+ { "wallet", "addwitnessaddress", &addwitnessaddress, {"address"} },
+ { "wallet", "backupwallet", &backupwallet, {"destination"} },
+ { "wallet", "bumpfee", &bumpfee, {"txid", "options"} },
+ { "wallet", "dumpprivkey", &dumpprivkey, {"address"} },
+ { "wallet", "dumpwallet", &dumpwallet, {"filename"} },
+ { "wallet", "encryptwallet", &encryptwallet, {"passphrase"} },
+ { "wallet", "getaccountaddress", &getaccountaddress, {"account"} },
+ { "wallet", "getaccount", &getaccount, {"address"} },
+ { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, {"account"} },
+ { "wallet", "getbalance", &getbalance, {"account","minconf","include_watchonly"} },
+ { "wallet", "getnewaddress", &getnewaddress, {"account"} },
+ { "wallet", "getrawchangeaddress", &getrawchangeaddress, {} },
+ { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, {"account","minconf"} },
+ { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, {"address","minconf"} },
+ { "wallet", "gettransaction", &gettransaction, {"txid","include_watchonly"} },
+ { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, {} },
+ { "wallet", "getwalletinfo", &getwalletinfo, {} },
+ { "wallet", "importmulti", &importmulti, {"requests","options"} },
+ { "wallet", "importprivkey", &importprivkey, {"privkey","label","rescan"} },
+ { "wallet", "importwallet", &importwallet, {"filename"} },
+ { "wallet", "importaddress", &importaddress, {"address","label","rescan","p2sh"} },
+ { "wallet", "importprunedfunds", &importprunedfunds, {"rawtransaction","txoutproof"} },
+ { "wallet", "importpubkey", &importpubkey, {"pubkey","label","rescan"} },
+ { "wallet", "keypoolrefill", &keypoolrefill, {"newsize"} },
+ { "wallet", "listaccounts", &listaccounts, {"minconf","include_watchonly"} },
+ { "wallet", "listaddressgroupings", &listaddressgroupings, {} },
+ { "wallet", "listlockunspent", &listlockunspent, {} },
+ { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, {"minconf","include_empty","include_watchonly"} },
+ { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, {"minconf","include_empty","include_watchonly"} },
+ { "wallet", "listsinceblock", &listsinceblock, {"blockhash","target_confirmations","include_watchonly","include_removed"} },
+ { "wallet", "listtransactions", &listtransactions, {"account","count","skip","include_watchonly"} },
+ { "wallet", "listunspent", &listunspent, {"minconf","maxconf","addresses","include_unsafe","query_options"} },
+ { "wallet", "listwallets", &listwallets, {} },
+ { "wallet", "lockunspent", &lockunspent, {"unlock","transactions"} },
+ { "wallet", "move", &movecmd, {"fromaccount","toaccount","amount","minconf","comment"} },
+ { "wallet", "sendfrom", &sendfrom, {"fromaccount","toaddress","amount","minconf","comment","comment_to"} },
+ { "wallet", "sendmany", &sendmany, {"fromaccount","amounts","minconf","comment","subtractfeefrom","replaceable","conf_target","estimate_mode"} },
+ { "wallet", "sendtoaddress", &sendtoaddress, {"address","amount","comment","comment_to","subtractfeefromamount","replaceable","conf_target","estimate_mode"} },
+ { "wallet", "setaccount", &setaccount, {"address","account"} },
+ { "wallet", "settxfee", &settxfee, {"amount"} },
+ { "wallet", "signmessage", &signmessage, {"address","message"} },
+ { "wallet", "walletlock", &walletlock, {} },
+ { "wallet", "walletpassphrasechange", &walletpassphrasechange, {"oldpassphrase","newpassphrase"} },
+ { "wallet", "walletpassphrase", &walletpassphrase, {"passphrase","timeout"} },
+ { "wallet", "removeprunedfunds", &removeprunedfunds, {"txid"} },
+
+ { "generating", "generate", &generate, {"nblocks","maxtries"} },
};
void RegisterWalletRPCCommands(CRPCTable &t)
{
- if (GetBoolArg("-disablewallet", false))
+ if (gArgs.GetBoolArg("-disablewallet", false))
return;
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
diff --git a/src/wallet/test/crypto_tests.cpp b/src/wallet/test/crypto_tests.cpp
index 98d957b322..cbd74b6f96 100644
--- a/src/wallet/test/crypto_tests.cpp
+++ b/src/wallet/test/crypto_tests.cpp
@@ -9,86 +9,9 @@
#include <vector>
#include <boost/test/unit_test.hpp>
-#include <openssl/aes.h>
-#include <openssl/evp.h>
BOOST_FIXTURE_TEST_SUITE(wallet_crypto, BasicTestingSetup)
-bool OldSetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod, unsigned char* chKey, unsigned char* chIV)
-{
- if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
- return false;
-
- int i = 0;
- if (nDerivationMethod == 0)
- i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
- (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
-
- if (i != (int)WALLET_CRYPTO_KEY_SIZE)
- {
- memory_cleanse(chKey, WALLET_CRYPTO_KEY_SIZE);
- memory_cleanse(chIV, WALLET_CRYPTO_IV_SIZE);
- return false;
- }
- return true;
-}
-
-bool OldEncrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext, const unsigned char chKey[32], const unsigned char chIV[16])
-{
- // max ciphertext len for a n bytes of plaintext is
- // n + AES_BLOCK_SIZE - 1 bytes
- int nLen = vchPlaintext.size();
- int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
- vchCiphertext = std::vector<unsigned char> (nCLen);
-
- EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
-
- if (!ctx) return false;
-
- bool fOk = true;
-
- EVP_CIPHER_CTX_init(ctx);
- if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, chKey, chIV) != 0;
- if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0;
- if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0;
- EVP_CIPHER_CTX_cleanup(ctx);
-
- EVP_CIPHER_CTX_free(ctx);
-
- if (!fOk) return false;
-
- vchCiphertext.resize(nCLen + nFLen);
- return true;
-}
-
-bool OldDecrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext, const unsigned char chKey[32], const unsigned char chIV[16])
-{
- // plaintext will always be equal to or lesser than length of ciphertext
- int nLen = vchCiphertext.size();
- int nPLen = nLen, nFLen = 0;
-
- vchPlaintext = CKeyingMaterial(nPLen);
-
- EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
-
- if (!ctx) return false;
-
- bool fOk = true;
-
- EVP_CIPHER_CTX_init(ctx);
- if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, chKey, chIV) != 0;
- if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0;
- if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0;
- EVP_CIPHER_CTX_cleanup(ctx);
-
- EVP_CIPHER_CTX_free(ctx);
-
- if (!fOk) return false;
-
- vchPlaintext.resize(nPLen + nFLen);
- return true;
-}
-
class TestCrypter
{
public:
@@ -96,25 +19,15 @@ static void TestPassphraseSingle(const std::vector<unsigned char>& vchSalt, cons
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
- unsigned char chKey[WALLET_CRYPTO_KEY_SIZE];
- unsigned char chIV[WALLET_CRYPTO_IV_SIZE];
-
CCrypter crypt;
crypt.SetKeyFromPassphrase(passphrase, vchSalt, rounds, 0);
- OldSetKeyFromPassphrase(passphrase, vchSalt, rounds, 0, chKey, chIV);
-
- BOOST_CHECK_MESSAGE(memcmp(chKey, crypt.vchKey.data(), crypt.vchKey.size()) == 0, \
- HexStr(chKey, chKey+sizeof(chKey)) + std::string(" != ") + HexStr(crypt.vchKey));
- BOOST_CHECK_MESSAGE(memcmp(chIV, crypt.vchIV.data(), crypt.vchIV.size()) == 0, \
- HexStr(chIV, chIV+sizeof(chIV)) + std::string(" != ") + HexStr(crypt.vchIV));
-
if(!correctKey.empty())
- BOOST_CHECK_MESSAGE(memcmp(chKey, &correctKey[0], sizeof(chKey)) == 0, \
- HexStr(chKey, chKey+sizeof(chKey)) + std::string(" != ") + HexStr(correctKey.begin(), correctKey.end()));
+ BOOST_CHECK_MESSAGE(memcmp(crypt.vchKey.data(), correctKey.data(), crypt.vchKey.size()) == 0, \
+ HexStr(crypt.vchKey.begin(), crypt.vchKey.end()) + std::string(" != ") + HexStr(correctKey.begin(), correctKey.end()));
if(!correctIV.empty())
- BOOST_CHECK_MESSAGE(memcmp(chIV, &correctIV[0], sizeof(chIV)) == 0,
- HexStr(chIV, chIV+sizeof(chIV)) + std::string(" != ") + HexStr(correctIV.begin(), correctIV.end()));
+ BOOST_CHECK_MESSAGE(memcmp(crypt.vchIV.data(), correctIV.data(), crypt.vchIV.size()) == 0,
+ HexStr(crypt.vchIV.begin(), crypt.vchIV.end()) + std::string(" != ") + HexStr(correctIV.begin(), correctIV.end()));
}
static void TestPassphrase(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
@@ -126,50 +39,26 @@ static void TestPassphrase(const std::vector<unsigned char>& vchSalt, const Secu
TestPassphraseSingle(vchSalt, SecureString(i, passphrase.end()), rounds);
}
-
static void TestDecrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchCiphertext, \
const std::vector<unsigned char>& vchPlaintext = std::vector<unsigned char>())
{
- CKeyingMaterial vchDecrypted1;
- CKeyingMaterial vchDecrypted2;
- int result1, result2;
- result1 = crypt.Decrypt(vchCiphertext, vchDecrypted1);
- result2 = OldDecrypt(vchCiphertext, vchDecrypted2, crypt.vchKey.data(), crypt.vchIV.data());
- BOOST_CHECK(result1 == result2);
-
- // These two should be equal. However, OpenSSL 1.0.1j introduced a change
- // that would zero all padding except for the last byte for failed decrypts.
- // This behavior was reverted for 1.0.1k.
- if (vchDecrypted1 != vchDecrypted2 && vchDecrypted1.size() >= AES_BLOCK_SIZE && SSLeay() == 0x100010afL)
- {
- for(CKeyingMaterial::iterator it = vchDecrypted1.end() - AES_BLOCK_SIZE; it != vchDecrypted1.end() - 1; it++)
- *it = 0;
- }
-
- BOOST_CHECK_MESSAGE(vchDecrypted1 == vchDecrypted2, HexStr(vchDecrypted1.begin(), vchDecrypted1.end()) + " != " + HexStr(vchDecrypted2.begin(), vchDecrypted2.end()));
-
+ CKeyingMaterial vchDecrypted;
+ crypt.Decrypt(vchCiphertext, vchDecrypted);
if (vchPlaintext.size())
- BOOST_CHECK(CKeyingMaterial(vchPlaintext.begin(), vchPlaintext.end()) == vchDecrypted2);
+ BOOST_CHECK(CKeyingMaterial(vchPlaintext.begin(), vchPlaintext.end()) == vchDecrypted);
}
static void TestEncryptSingle(const CCrypter& crypt, const CKeyingMaterial& vchPlaintext,
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
- std::vector<unsigned char> vchCiphertext1;
- std::vector<unsigned char> vchCiphertext2;
- int result1 = crypt.Encrypt(vchPlaintext, vchCiphertext1);
-
- int result2 = OldEncrypt(vchPlaintext, vchCiphertext2, crypt.vchKey.data(), crypt.vchIV.data());
- BOOST_CHECK(result1 == result2);
- BOOST_CHECK(vchCiphertext1 == vchCiphertext2);
+ std::vector<unsigned char> vchCiphertext;
+ crypt.Encrypt(vchPlaintext, vchCiphertext);
if (!vchCiphertextCorrect.empty())
- BOOST_CHECK(vchCiphertext2 == vchCiphertextCorrect);
+ BOOST_CHECK(vchCiphertext == vchCiphertextCorrect);
const std::vector<unsigned char> vchPlaintext2(vchPlaintext.begin(), vchPlaintext.end());
-
- if(vchCiphertext1 == vchCiphertext2)
- TestDecrypt(crypt, vchCiphertext1, vchPlaintext2);
+ TestDecrypt(crypt, vchCiphertext, vchPlaintext2);
}
static void TestEncrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchPlaintextIn, \
diff --git a/src/wallet/test/wallet_test_fixture.h b/src/wallet/test/wallet_test_fixture.h
index 97a6d98397..9373b7907c 100644
--- a/src/wallet/test/wallet_test_fixture.h
+++ b/src/wallet/test/wallet_test_fixture.h
@@ -10,7 +10,7 @@
/** Testing setup and teardown for wallet.
*/
struct WalletTestingSetup: public TestingSetup {
- WalletTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
+ explicit WalletTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~WalletTestingSetup();
};
diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp
index 4a2cc9a139..5ebacd57d3 100644
--- a/src/wallet/test/wallet_tests.cpp
+++ b/src/wallet/test/wallet_tests.cpp
@@ -364,6 +364,12 @@ BOOST_AUTO_TEST_CASE(ApproximateBestSubset)
empty_wallet();
}
+static void AddKey(CWallet& wallet, const CKey& key)
+{
+ LOCK(wallet.cs_wallet);
+ wallet.AddKeyPubKey(key, key.GetPubKey());
+}
+
BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
{
LOCK(cs_main);
@@ -379,8 +385,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
// and new block files.
{
CWallet wallet;
- LOCK(wallet.cs_wallet);
- wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
+ AddKey(wallet, coinbaseKey);
BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip));
BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN);
}
@@ -393,8 +398,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
// file.
{
CWallet wallet;
- LOCK(wallet.cs_wallet);
- wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
+ AddKey(wallet, coinbaseKey);
BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip));
BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN);
}
@@ -599,8 +603,7 @@ public:
wallet.reset(new CWallet(std::unique_ptr<CWalletDBWrapper>(new CWalletDBWrapper(&bitdb, "wallet_test.dat"))));
bool firstRun;
wallet->LoadWallet(firstRun);
- LOCK(wallet->cs_wallet);
- wallet->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
+ AddKey(*wallet, coinbaseKey);
wallet->ScanForWalletTransactions(chainActive.Genesis());
}
@@ -635,7 +638,7 @@ public:
BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup)
{
std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
- LOCK(wallet->cs_wallet);
+ LOCK2(cs_main, wallet->cs_wallet);
// Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
// address.
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index c152b9d697..d1d2060b0c 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -30,6 +30,7 @@
#include "util.h"
#include "ui_interface.h"
#include "utilmoneystr.h"
+#include "wallet/fees.h"
#include <assert.h>
@@ -494,63 +495,6 @@ void CWallet::Flush(bool shutdown)
dbw->Flush(shutdown);
}
-bool CWallet::Verify()
-{
- if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
- return true;
-
- uiInterface.InitMessage(_("Verifying wallet(s)..."));
-
- // Keep track of each wallet absolute path to detect duplicates.
- std::set<fs::path> wallet_paths;
-
- for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
- if (boost::filesystem::path(walletFile).filename() != walletFile) {
- return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile));
- }
-
- if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
- return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile));
- }
-
- fs::path wallet_path = fs::absolute(walletFile, GetDataDir());
-
- if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) {
- return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile));
- }
-
- if (!wallet_paths.insert(wallet_path).second) {
- return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
- }
-
- std::string strError;
- if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
- return InitError(strError);
- }
-
- if (GetBoolArg("-salvagewallet", false)) {
- // Recover readable keypairs:
- CWallet dummyWallet;
- std::string backup_filename;
- if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
- return false;
- }
- }
-
- std::string strWarning;
- bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
- if (!strWarning.empty()) {
- InitWarning(strWarning);
- }
- if (!dbV) {
- InitError(strError);
- return false;
- }
- }
-
- return true;
-}
-
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
@@ -623,8 +567,9 @@ void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
void CWallet::AddToSpends(const uint256& wtxid)
{
- assert(mapWallet.count(wtxid));
- CWalletTx& thisTx = mapWallet[wtxid];
+ auto it = mapWallet.find(wtxid);
+ assert(it != mapWallet.end());
+ CWalletTx& thisTx = it->second;
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
@@ -739,13 +684,13 @@ DBErrors CWallet::ReorderTransactions()
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
- txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
+ txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
}
std::list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit("", acentries);
for (CAccountingEntry& entry : acentries)
{
- txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
+ txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
}
nOrderPosNext = 0;
@@ -754,7 +699,7 @@ DBErrors CWallet::ReorderTransactions()
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
- int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
+ int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
@@ -939,7 +884,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&walletdb);
- wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
+ wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
}
@@ -986,7 +931,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
- std::string strCmd = GetArg("-walletnotify", "");
+ std::string strCmd = gArgs.GetArg("-walletnotify", "");
if ( !strCmd.empty())
{
@@ -1004,11 +949,12 @@ bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this);
- wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
+ wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
AddToSpends(hash);
for (const CTxIn& txin : wtx.tx->vin) {
- if (mapWallet.count(txin.prevout.hash)) {
- CWalletTx& prevtx = mapWallet[txin.prevout.hash];
+ auto it = mapWallet.find(txin.prevout.hash);
+ if (it != mapWallet.end()) {
+ CWalletTx& prevtx = it->second;
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
MarkConflicted(prevtx.hashBlock, wtx.GetHash());
}
@@ -1107,8 +1053,9 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
- assert(mapWallet.count(hashTx));
- CWalletTx& origtx = mapWallet[hashTx];
+ auto it = mapWallet.find(hashTx);
+ assert(it != mapWallet.end());
+ CWalletTx& origtx = it->second;
if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
return false;
}
@@ -1119,8 +1066,9 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
- assert(mapWallet.count(now));
- CWalletTx& wtx = mapWallet[now];
+ auto it = mapWallet.find(now);
+ assert(it != mapWallet.end());
+ CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
@@ -1145,8 +1093,10 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin)
{
- if (mapWallet.count(txin.prevout.hash))
- mapWallet[txin.prevout.hash].MarkDirty();
+ auto it = mapWallet.find(txin.prevout.hash);
+ if (it != mapWallet.end()) {
+ it->second.MarkDirty();
+ }
}
}
}
@@ -1184,8 +1134,9 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
- assert(mapWallet.count(now));
- CWalletTx& wtx = mapWallet[now];
+ auto it = mapWallet.find(now);
+ assert(it != mapWallet.end());
+ CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
@@ -1204,10 +1155,11 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
- for (const CTxIn& txin : wtx.tx->vin)
- {
- if (mapWallet.count(txin.prevout.hash))
- mapWallet[txin.prevout.hash].MarkDirty();
+ for (const CTxIn& txin : wtx.tx->vin) {
+ auto it = mapWallet.find(txin.prevout.hash);
+ if (it != mapWallet.end()) {
+ it->second.MarkDirty();
+ }
}
}
}
@@ -1222,10 +1174,11 @@ void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pin
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
- for (const CTxIn& txin : tx.vin)
- {
- if (mapWallet.count(txin.prevout.hash))
- mapWallet[txin.prevout.hash].MarkDirty();
+ for (const CTxIn& txin : tx.vin) {
+ auto it = mapWallet.find(txin.prevout.hash);
+ if (it != mapWallet.end()) {
+ it->second.MarkDirty();
+ }
}
}
@@ -1794,7 +1747,7 @@ CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
{
- if (pwallet == 0)
+ if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
@@ -1838,7 +1791,7 @@ CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
{
- if (pwallet == 0)
+ if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
@@ -2501,8 +2454,8 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
++it;
}
- size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
- bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
+ size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
+ bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
bool res = nTargetValue <= nValueFromPresetInputs ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
@@ -2571,7 +2524,7 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
if (nChangePosInOut != -1) {
tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
- // we dont have the normal Create/Commit cycle, and dont want to risk reusing change,
+ // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
// so just remove the key from the keypool here.
reservekey.KeepKey();
}
@@ -2599,17 +2552,6 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
return true;
}
-static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
-{
- unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
- CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
- // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
- discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
- // Discard rate must be at least dustRelayFee
- discard_rate = std::max(discard_rate, ::dustRelayFee);
- return discard_rate;
-}
-
bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
{
@@ -2670,6 +2612,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
FeeCalculation feeCalc;
+ CAmount nFeeNeeded;
unsigned int nBytes;
{
std::set<CInputCoin> setCoins;
@@ -2831,7 +2774,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
vin.scriptWitness.SetNull();
}
- CAmount nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
+ nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
@@ -2852,13 +2795,15 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
// new inputs. We now know we only need the smaller fee
// (because of reduced tx size) and so we should add a
// change output. Only try this once.
- CAmount fee_needed_for_change = GetMinimumFee(change_prototype_size, coin_control, ::mempool, ::feeEstimator, nullptr);
- CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
- CAmount max_excess_fee = fee_needed_for_change + minimum_value_for_change;
- if (nFeeRet > nFeeNeeded + max_excess_fee && nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
- pick_new_inputs = false;
- nFeeRet = nFeeNeeded + fee_needed_for_change;
- continue;
+ if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
+ unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
+ CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
+ CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
+ if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
+ pick_new_inputs = false;
+ nFeeRet = fee_needed_with_change;
+ continue;
+ }
}
// If we have change output already, just increase it
@@ -2937,15 +2882,15 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
}
}
- if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
+ if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
// Lastly, ensure this tx will pass the mempool's chain limits
LockPoints lp;
CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
CTxMemPool::setEntries setAncestors;
- size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
- size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
- size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
- size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
+ size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
+ size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
+ size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
+ size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
strFailReason = _("Transaction has too long of a mempool chain");
@@ -2953,8 +2898,8 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
}
}
- LogPrintf("Fee Calculation: Fee:%d Bytes:%u Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
- nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
+ LogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
+ nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
feeCalc.est.pass.start, feeCalc.est.pass.end,
100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
@@ -3026,85 +2971,21 @@ bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwa
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
- wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
+ wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
return true;
}
-CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
-{
- return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
-}
-
-CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
-{
- /* User control of how to calculate fee uses the following parameter precedence:
- 1. coin_control.m_feerate
- 2. coin_control.m_confirm_target
- 3. payTxFee (user-set global variable)
- 4. nTxConfirmTarget (user-set global variable)
- The first parameter that is set is used.
- */
- CAmount fee_needed;
- if (coin_control.m_feerate) { // 1.
- fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
- if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
- // Allow to override automatic min/max check over coin control instance
- if (coin_control.fOverrideFeeRate) return fee_needed;
- }
- else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
- fee_needed = ::payTxFee.GetFee(nTxBytes);
- if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
- }
- else { // 2. or 4.
- // We will use smart fee estimation
- unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
- // By default estimates are economical iff we are signaling opt-in-RBF
- bool conservative_estimate = !coin_control.signalRbf;
- // Allow to override the default fee estimate mode over the CoinControl instance
- if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
- else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
-
- fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
- if (fee_needed == 0) {
- // if we don't have enough data for estimateSmartFee, then use fallbackFee
- fee_needed = fallbackFee.GetFee(nTxBytes);
- if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
- }
- // Obey mempool min fee when using smart fee estimation
- CAmount min_mempool_fee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
- if (fee_needed < min_mempool_fee) {
- fee_needed = min_mempool_fee;
- if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
- }
- }
-
- // prevent user from paying a fee below minRelayTxFee or minTxFee
- CAmount required_fee = GetRequiredFee(nTxBytes);
- if (required_fee > fee_needed) {
- fee_needed = required_fee;
- if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
- }
- // But always obey the maximum
- if (fee_needed > maxTxFee) {
- fee_needed = maxTxFee;
- if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
- }
- return fee_needed;
-}
-
-
-
-
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
+ LOCK2(cs_main, cs_wallet);
+
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
- LOCK(cs_wallet);
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
@@ -3114,9 +2995,11 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
}
}
+ // This wallet is in its first run if all of these are empty
+ fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
+
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
- fFirstRunRet = !vchDefaultKey.IsValid();
uiInterface.LoadWallet(this);
@@ -3126,7 +3009,6 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{
AssertLockHeld(cs_wallet); // mapWallet
- vchDefaultKey = CPubKey();
DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
for (uint256 hash : vHashOut)
mapWallet.erase(hash);
@@ -3155,7 +3037,6 @@ DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
- vchDefaultKey = CPubKey();
DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE)
{
@@ -3231,14 +3112,6 @@ const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
return DEFAULT_ACCOUNT_NAME;
}
-bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
-{
- if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
- return false;
- vchDefaultKey = vchPubKey;
- return true;
-}
-
/**
* Mark old keypool keys as used,
* and generate all new keys
@@ -3307,7 +3180,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
if (kpSize > 0)
nTargetSize = kpSize;
else
- nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
+ nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
// count amount of available keys (internal, external)
// make sure the keypool of external and internal keys fits the user selected target (-keypool)
@@ -3659,15 +3532,11 @@ void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
}
walletdb.ErasePool(index);
+ LogPrintf("keypool index %d removed\n", index);
it = setKeyPool->erase(it);
}
}
-bool CWallet::HasUnusedKeys(int min_keys) const
-{
- return setExternalKeyPool.size() >= min_keys && (setInternalKeyPool.size() >= min_keys || !CanSupportFeature(FEATURE_HD_SPLIT));
-}
-
void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
{
std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
@@ -3888,64 +3757,21 @@ std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
return values;
}
-std::string CWallet::GetWalletHelpString(bool showDebug)
-{
- std::string strUsage = HelpMessageGroup(_("Wallet options:"));
- strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
- strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
- strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
- CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
- strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
- "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target"),
- CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
- strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
- CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
- strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
- CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
- strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
- strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
- strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
- strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
- strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
- strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
- strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
- strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
- strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
- strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
- strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
- " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
-
- if (showDebug)
- {
- strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
-
- strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
- strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
- strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
- strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
- }
-
- return strUsage;
-}
-
CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
{
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
- if (GetBoolArg("-zapwallettxes", false)) {
+ if (gArgs.GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
- CWallet *tempWallet = new CWallet(std::move(dbw));
+ std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
-
- delete tempWallet;
- tempWallet = nullptr;
}
uiInterface.InitMessage(_("Loading wallet..."));
@@ -3982,9 +3808,9 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
}
}
- if (GetBoolArg("-upgradewallet", fFirstRun))
+ if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
{
- int nMaxVersion = GetArg("-upgradewallet", 0);
+ int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
@@ -4004,7 +3830,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
if (fFirstRun)
{
// Create new keyUser and set as default key
- if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
+ if (gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
// ensure this wallet.dat can only be opened by clients supporting HD with chain split
walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
@@ -4014,19 +3840,17 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
if (!walletInstance->SetHDMasterKey(masterPubKey))
throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
}
- CPubKey newDefaultKey;
- if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
- walletInstance->SetDefaultKey(newDefaultKey);
- if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
- InitError(_("Cannot write default address") += "\n");
- return nullptr;
- }
+
+ // Top up the keypool
+ if (!walletInstance->TopUpKeyPool()) {
+ InitError(_("Unable to generate initial keys") += "\n");
+ return NULL;
}
walletInstance->SetBestChain(chainActive.GetLocator());
}
- else if (IsArgSet("-usehd")) {
- bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
+ else if (gArgs.IsArgSet("-usehd")) {
+ bool useHD = gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
if (walletInstance->IsHDEnabled() && !useHD) {
InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
return nullptr;
@@ -4045,7 +3869,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
walletInstance->TopUpKeyPool();
CBlockIndex *pindexRescan = chainActive.Genesis();
- if (!GetBoolArg("-rescan", false))
+ if (!gArgs.GetBoolArg("-rescan", false))
{
CWalletDB walletdb(*walletInstance->dbw);
CBlockLocator locator;
@@ -4085,7 +3909,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
walletInstance->dbw->IncrementUpdateCounter();
// Restore wallet transaction metadata after -zapwallettxes=1
- if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
+ if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
{
CWalletDB walletdb(*walletInstance->dbw);
@@ -4109,7 +3933,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
}
}
}
- walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
+ walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
{
LOCK(walletInstance->cs_wallet);
@@ -4121,24 +3945,6 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
return walletInstance;
}
-bool CWallet::InitLoadWallet()
-{
- if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
- LogPrintf("Wallet disabled!\n");
- return true;
- }
-
- for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
- CWallet * const pwallet = CreateWalletFromFile(walletFile);
- if (!pwallet) {
- return false;
- }
- vpwallets.push_back(pwallet);
- }
-
- return true;
-}
-
std::atomic<bool> CWallet::fFlushScheduled(false);
void CWallet::postInitProcess(CScheduler& scheduler)
@@ -4153,126 +3959,6 @@ void CWallet::postInitProcess(CScheduler& scheduler)
}
}
-bool CWallet::ParameterInteraction()
-{
- SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
- const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
-
- if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
- return true;
-
- if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
- LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
- }
-
- if (GetBoolArg("-salvagewallet", false)) {
- if (is_multiwallet) {
- return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
- }
- // Rewrite just private keys: rescan to find transactions
- if (SoftSetBoolArg("-rescan", true)) {
- LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
- }
- }
-
- int zapwallettxes = GetArg("-zapwallettxes", 0);
- // -zapwallettxes implies dropping the mempool on startup
- if (zapwallettxes != 0 && SoftSetBoolArg("-persistmempool", false)) {
- LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
- }
-
- // -zapwallettxes implies a rescan
- if (zapwallettxes != 0) {
- if (is_multiwallet) {
- return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
- }
- if (SoftSetBoolArg("-rescan", true)) {
- LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
- }
- }
-
- if (is_multiwallet) {
- if (GetBoolArg("-upgradewallet", false)) {
- return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
- }
- }
-
- if (GetBoolArg("-sysperms", false))
- return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
- if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
- return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
-
- if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
- InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
- _("The wallet will avoid paying less than the minimum relay fee."));
-
- if (IsArgSet("-mintxfee"))
- {
- CAmount n = 0;
- if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
- return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
- if (n > HIGH_TX_FEE_PER_KB)
- InitWarning(AmountHighWarn("-mintxfee") + " " +
- _("This is the minimum transaction fee you pay on every transaction."));
- CWallet::minTxFee = CFeeRate(n);
- }
- if (IsArgSet("-fallbackfee"))
- {
- CAmount nFeePerK = 0;
- if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
- return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
- if (nFeePerK > HIGH_TX_FEE_PER_KB)
- InitWarning(AmountHighWarn("-fallbackfee") + " " +
- _("This is the transaction fee you may pay when fee estimates are not available."));
- CWallet::fallbackFee = CFeeRate(nFeePerK);
- }
- if (IsArgSet("-discardfee"))
- {
- CAmount nFeePerK = 0;
- if (!ParseMoney(GetArg("-discardfee", ""), nFeePerK))
- return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), GetArg("-discardfee", "")));
- if (nFeePerK > HIGH_TX_FEE_PER_KB)
- InitWarning(AmountHighWarn("-discardfee") + " " +
- _("This is the transaction fee you may discard if change is smaller than dust at this level"));
- CWallet::m_discard_rate = CFeeRate(nFeePerK);
- }
- if (IsArgSet("-paytxfee"))
- {
- CAmount nFeePerK = 0;
- if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
- return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
- if (nFeePerK > HIGH_TX_FEE_PER_KB)
- InitWarning(AmountHighWarn("-paytxfee") + " " +
- _("This is the transaction fee you will pay if you send a transaction."));
-
- payTxFee = CFeeRate(nFeePerK, 1000);
- if (payTxFee < ::minRelayTxFee)
- {
- return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
- GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
- }
- }
- if (IsArgSet("-maxtxfee"))
- {
- CAmount nMaxFee = 0;
- if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
- return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
- if (nMaxFee > HIGH_MAX_TX_FEE)
- InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
- maxTxFee = nMaxFee;
- if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
- {
- return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
- GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
- }
- }
- nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
- bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
- fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
-
- return true;
-}
-
bool CWallet::BackupWallet(const std::string& strDest)
{
return dbw->Backup(strDest);
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index f97a99d82a..73ad3bdeca 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -208,7 +208,7 @@ public:
Init();
}
- CMerkleTx(CTransactionRef arg)
+ explicit CMerkleTx(CTransactionRef arg)
{
SetTx(std::move(arg));
Init();
@@ -548,7 +548,7 @@ public:
//! todo: add something to note what created it (user, getnewaddress, change)
//! maybe should have a map<string, string> property map
- CWalletKey(int64_t nExpires=0);
+ explicit CWalletKey(int64_t nExpires=0);
ADD_SERIALIZE_METHODS;
@@ -651,7 +651,7 @@ private:
* A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
* and provides the ability to create new transactions.
*/
-class CWallet : public CCryptoKeyStore, public CValidationInterface
+class CWallet final : public CCryptoKeyStore, public CValidationInterface
{
private:
static std::atomic<bool> fFlushScheduled;
@@ -765,7 +765,7 @@ public:
}
// Create wallet with passed-in database handle
- CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
+ explicit CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
{
SetNull();
}
@@ -807,8 +807,6 @@ public:
std::map<CTxDestination, CAddressBookData> mapAddressBook;
- CPubKey vchDefaultKey;
-
std::set<COutPoint> setLockedCoins;
const CWalletTx* GetWalletTx(const uint256& hash) const;
@@ -960,16 +958,6 @@ public:
static CFeeRate minTxFee;
static CFeeRate fallbackFee;
static CFeeRate m_discard_rate;
- /**
- * Estimate the minimum fee considering user set parameters
- * and the required fee
- */
- static CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc);
- /**
- * Return the minimum required fee taking into account the
- * floating relay fee and user set minimum transaction fee
- */
- static CAmount GetRequiredFee(unsigned int nTxBytes);
bool NewKeyPool();
size_t KeypoolCountExternalKeys();
@@ -984,8 +972,6 @@ public:
*/
void MarkReserveKeysAsUsed(int64_t keypool_id);
const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
- /** Does the wallet have at least min_keys in the keypool? */
- bool HasUnusedKeys(int min_keys) const;
std::set< std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
@@ -1040,8 +1026,6 @@ public:
return setInternalKeyPool.size() + setExternalKeyPool.size();
}
- bool SetDefaultKey(const CPubKey &vchPubKey);
-
//! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = nullptr, bool fExplicit = false);
@@ -1060,11 +1044,6 @@ public:
//! Flush wallet (bitdb flush)
void Flush(bool shutdown=false);
- //! Responsible for reading and validating the -wallet arguments and verifying the wallet database.
- // This function will perform salvage on the wallet if requested, as long as only one wallet is
- // being loaded (CWallet::ParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet).
- static bool Verify();
-
/**
* Address book entry changed.
* @note called with lock cs_wallet held.
@@ -1101,12 +1080,8 @@ public:
/** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
- /* Returns the wallets help message */
- static std::string GetWalletHelpString(bool showDebug);
-
/* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
static CWallet* CreateWalletFromFile(const std::string walletFile);
- static bool InitLoadWallet();
/**
* Wallet post-init setup
@@ -1114,9 +1089,6 @@ public:
*/
void postInitProcess(CScheduler& scheduler);
- /* Wallets parameter interaction */
- static bool ParameterInteraction();
-
bool BackupWallet(const std::string& strDest);
/* Set the HD chain model (chain child index counters) */
@@ -1137,7 +1109,7 @@ public:
};
/** A key allocated from the key pool. */
-class CReserveKey : public CReserveScript
+class CReserveKey final : public CReserveScript
{
protected:
CWallet* pwallet;
@@ -1145,7 +1117,7 @@ protected:
CPubKey vchPubKey;
bool fInternal;
public:
- CReserveKey(CWallet* pwalletIn)
+ explicit CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
index c8dc526264..12da3cce64 100644
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -130,11 +130,6 @@ bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
return WriteIC(std::string("orderposnext"), nOrderPosNext);
}
-bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey)
-{
- return WriteIC(std::string("defaultkey"), vchPubKey);
-}
-
bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return batch.Read(std::make_pair(std::string("pool"), nPool), keypool);
@@ -452,7 +447,14 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
}
else if (strType == "defaultkey")
{
- ssValue >> pwallet->vchDefaultKey;
+ // We don't want or need the default key, but if there is one set,
+ // we want to make sure that it is valid so that we can detect corruption
+ CPubKey vchPubKey;
+ ssValue >> vchPubKey;
+ if (!vchPubKey.IsValid()) {
+ strErr = "Error reading wallet database: Default Key corrupt";
+ return false;
+ }
}
else if (strType == "pool")
{
@@ -522,7 +524,6 @@ bool CWalletDB::IsKeyType(const std::string& strType)
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
- pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
@@ -565,7 +566,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
- if (IsKeyType(strType))
+ if (IsKeyType(strType) || strType == "defaultkey")
result = DB_CORRUPT;
else
{
@@ -573,7 +574,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
- SoftSetBoolArg("-rescan", true);
+ gArgs.SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
@@ -621,7 +622,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
pwallet->laccentries.clear();
ListAccountCreditDebit("*", pwallet->laccentries);
for (CAccountingEntry& entry : pwallet->laccentries) {
- pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry)));
+ pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair(nullptr, &entry)));
}
return result;
@@ -751,7 +752,7 @@ void MaybeCompactWalletDB()
if (fOneThread.exchange(true)) {
return;
}
- if (!GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET)) {
+ if (!gArgs.GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET)) {
return;
}
diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h
index d78f143ebd..4f8ea185d5 100644
--- a/src/wallet/walletdb.h
+++ b/src/wallet/walletdb.h
@@ -105,7 +105,7 @@ public:
{
SetNull();
}
- CKeyMetadata(int64_t nCreateTime_)
+ explicit CKeyMetadata(int64_t nCreateTime_)
{
SetNull();
nCreateTime = nCreateTime_;
@@ -162,7 +162,7 @@ private:
}
public:
- CWalletDB(CWalletDBWrapper& dbw, const char* pszMode = "r+", bool _fFlushOnClose = true) :
+ explicit CWalletDB(CWalletDBWrapper& dbw, const char* pszMode = "r+", bool _fFlushOnClose = true) :
batch(dbw, pszMode, _fFlushOnClose),
m_dbw(dbw)
{
@@ -191,8 +191,6 @@ public:
bool WriteOrderPosNext(int64_t nOrderPosNext);
- bool WriteDefaultKey(const CPubKey& vchPubKey);
-
bool ReadPool(int64_t nPool, CKeyPool& keypool);
bool WritePool(int64_t nPool, const CKeyPool& keypool);
bool ErasePool(int64_t nPool);
diff --git a/src/warnings.cpp b/src/warnings.cpp
index 75ccfeb116..d4e33b701a 100644
--- a/src/warnings.cpp
+++ b/src/warnings.cpp
@@ -51,7 +51,7 @@ std::string GetWarnings(const std::string& strFor)
strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
}
- if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
+ if (gArgs.GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
strStatusBar = strRPC = strGUI = "testsafemode enabled";
// Misc warnings like out of disk space and clock is wrong
diff --git a/src/zmq/zmqabstractnotifier.h b/src/zmq/zmqabstractnotifier.h
index 77cf5141e2..7828822149 100644
--- a/src/zmq/zmqabstractnotifier.h
+++ b/src/zmq/zmqabstractnotifier.h
@@ -15,7 +15,7 @@ typedef CZMQAbstractNotifier* (*CZMQNotifierFactory)();
class CZMQAbstractNotifier
{
public:
- CZMQAbstractNotifier() : psocket(0) { }
+ CZMQAbstractNotifier() : psocket(nullptr) { }
virtual ~CZMQAbstractNotifier();
template <typename T>
diff --git a/src/zmq/zmqnotificationinterface.cpp b/src/zmq/zmqnotificationinterface.cpp
index b637f26fb2..9909395d84 100644
--- a/src/zmq/zmqnotificationinterface.cpp
+++ b/src/zmq/zmqnotificationinterface.cpp
@@ -43,10 +43,10 @@ CZMQNotificationInterface* CZMQNotificationInterface::Create()
for (std::map<std::string, CZMQNotifierFactory>::const_iterator i=factories.begin(); i!=factories.end(); ++i)
{
std::string arg("-zmq" + i->first);
- if (IsArgSet(arg))
+ if (gArgs.IsArgSet(arg))
{
CZMQNotifierFactory factory = i->second;
- std::string address = GetArg(arg, "");
+ std::string address = gArgs.GetArg(arg, "");
CZMQAbstractNotifier *notifier = factory();
notifier->SetType(i->first);
notifier->SetAddress(address);
@@ -120,7 +120,7 @@ void CZMQNotificationInterface::Shutdown()
}
zmq_ctx_destroy(pcontext);
- pcontext = 0;
+ pcontext = nullptr;
}
}
diff --git a/src/zmq/zmqnotificationinterface.h b/src/zmq/zmqnotificationinterface.h
index eec6f7bc64..cb92216fa4 100644
--- a/src/zmq/zmqnotificationinterface.h
+++ b/src/zmq/zmqnotificationinterface.h
@@ -13,7 +13,7 @@
class CBlockIndex;
class CZMQAbstractNotifier;
-class CZMQNotificationInterface : public CValidationInterface
+class CZMQNotificationInterface final : public CValidationInterface
{
public:
virtual ~CZMQNotificationInterface();
diff --git a/src/zmq/zmqpublishnotifier.cpp b/src/zmq/zmqpublishnotifier.cpp
index 700c39f66e..ab54e2bb8b 100644
--- a/src/zmq/zmqpublishnotifier.cpp
+++ b/src/zmq/zmqpublishnotifier.cpp
@@ -126,7 +126,7 @@ void CZMQAbstractPublishNotifier::Shutdown()
zmq_close(psocket);
}
- psocket = 0;
+ psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
@@ -136,7 +136,7 @@ bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* d
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
- int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), (void*)0);
+ int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
diff --git a/test/functional/README.md b/test/functional/README.md
index 44efda33d3..2558bd017d 100644
--- a/test/functional/README.md
+++ b/test/functional/README.md
@@ -24,8 +24,8 @@ don't have test cases for.
- Use a module-level docstring to describe what the test is testing, and how it
is testing it.
- When subclassing the BitcoinTestFramwork, place overrides for the
- `__init__()`, and `setup_xxxx()` methods at the top of the subclass, then
- locally-defined helper methods, then the `run_test()` method.
+ `set_test_params()`, `add_options()` and `setup_xxxx()` methods at the top of
+ the subclass, then locally-defined helper methods, then the `run_test()` method.
#### General test-writing advice
@@ -36,7 +36,7 @@ don't have test cases for.
- Avoid stop-starting the nodes multiple times during the test if possible. A
stop-start takes several seconds, so doing it several times blows up the
runtime of the test.
-- Set the `self.setup_clean_chain` variable in `__init__()` to control whether
+- Set the `self.setup_clean_chain` variable in `set_test_params()` to control whether
or not to use the cached data directories. The cached data directories
contain a 200-block pre-mined blockchain and wallets for four nodes. Each node
has 25 mature blocks (25x50=1250 BTC) in its wallet.
diff --git a/test/functional/abandonconflict.py b/test/functional/abandonconflict.py
index c87c02492d..e8dbc86469 100755
--- a/test/functional/abandonconflict.py
+++ b/test/functional/abandonconflict.py
@@ -14,10 +14,8 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class AbandonConflictTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
self.extra_args = [["-minrelaytxfee=0.00001"], []]
def run_test(self):
@@ -74,7 +72,7 @@ class AbandonConflictTest(BitcoinTestFramework):
# Restart the node with a higher min relay fee so the parent tx is no longer in mempool
# TODO: redo with eviction
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-minrelaytxfee=0.0001"])
+ self.start_node(0, extra_args=["-minrelaytxfee=0.0001"])
# Verify txs no longer in either node's mempool
assert_equal(len(self.nodes[0].getrawmempool()), 0)
@@ -101,7 +99,7 @@ class AbandonConflictTest(BitcoinTestFramework):
# Verify that even with a low min relay fee, the tx is not reaccepted from wallet on startup once abandoned
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-minrelaytxfee=0.00001"])
+ self.start_node(0, extra_args=["-minrelaytxfee=0.00001"])
assert_equal(len(self.nodes[0].getrawmempool()), 0)
assert_equal(self.nodes[0].getbalance(), balance)
@@ -121,7 +119,7 @@ class AbandonConflictTest(BitcoinTestFramework):
# Remove using high relay fee again
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-minrelaytxfee=0.0001"])
+ self.start_node(0, extra_args=["-minrelaytxfee=0.0001"])
assert_equal(len(self.nodes[0].getrawmempool()), 0)
newbalance = self.nodes[0].getbalance()
assert_equal(newbalance, balance - Decimal("24.9996"))
diff --git a/test/functional/assumevalid.py b/test/functional/assumevalid.py
index 9d17faac51..beaf8c7055 100755
--- a/test/functional/assumevalid.py
+++ b/test/functional/assumevalid.py
@@ -54,16 +54,16 @@ class BaseNode(NodeConnCB):
self.send_message(headers_message)
class AssumeValidTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
def setup_network(self):
+ self.add_nodes(3)
# Start node0. We don't start the other nodes yet since
# we need to pre-mine a block with an invalid transaction
# signature so we can pass in the block hash as assumevalid.
- self.nodes = [self.start_node(0, self.options.tmpdir)]
+ self.start_node(0)
def send_blocks_until_disconnected(self, node):
"""Keep sending blocks to the node until we're disconnected."""
@@ -162,15 +162,13 @@ class AssumeValidTest(BitcoinTestFramework):
height += 1
# Start node1 and node2 with assumevalid so they accept a block with a bad signature.
- self.nodes.append(self.start_node(1, self.options.tmpdir,
- ["-assumevalid=" + hex(block102.sha256)]))
+ self.start_node(1, extra_args=["-assumevalid=" + hex(block102.sha256)])
node1 = BaseNode() # connects to node1
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], node1))
node1.add_connection(connections[1])
node1.wait_for_verack()
- self.nodes.append(self.start_node(2, self.options.tmpdir,
- ["-assumevalid=" + hex(block102.sha256)]))
+ self.start_node(2, extra_args=["-assumevalid=" + hex(block102.sha256)])
node2 = BaseNode() # connects to node2
connections.append(NodeConn('127.0.0.1', p2p_port(2), self.nodes[2], node2))
node2.add_connection(connections[2])
diff --git a/test/functional/bip65-cltv-p2p.py b/test/functional/bip65-cltv-p2p.py
index 7e5e4cf682..2cd6df6e37 100755
--- a/test/functional/bip65-cltv-p2p.py
+++ b/test/functional/bip65-cltv-p2p.py
@@ -60,9 +60,7 @@ def create_transaction(node, coinbase, to_address, amount):
return tx
class BIP65Test(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-promiscuousmempoolflags=1', '-whitelist=127.0.0.1']]
self.setup_clean_chain = True
@@ -109,7 +107,7 @@ class BIP65Test(BitcoinTestFramework):
node0.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
- assert wait_until(lambda: "reject" in node0.last_message.keys())
+ wait_until(lambda: "reject" in node0.last_message.keys(), lock=mininode_lock)
with mininode_lock:
assert_equal(node0.last_message["reject"].code, REJECT_OBSOLETE)
assert_equal(node0.last_message["reject"].reason, b'bad-version(0x00000003)')
@@ -138,7 +136,7 @@ class BIP65Test(BitcoinTestFramework):
node0.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
- assert wait_until (lambda: "reject" in node0.last_message.keys())
+ wait_until(lambda: "reject" in node0.last_message.keys(), lock=mininode_lock)
with mininode_lock:
assert node0.last_message["reject"].code in [REJECT_INVALID, REJECT_NONSTANDARD]
assert_equal(node0.last_message["reject"].data, block.sha256)
diff --git a/test/functional/bip68-112-113-p2p.py b/test/functional/bip68-112-113-p2p.py
index 5a322e8c0e..7e6a4f4408 100755
--- a/test/functional/bip68-112-113-p2p.py
+++ b/test/functional/bip68-112-113-p2p.py
@@ -92,9 +92,9 @@ def all_rlt_txs(txarray):
return txs
class BIP68_112_113Test(ComparisonTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
+ self.setup_clean_chain = True
self.extra_args = [['-whitelist=127.0.0.1', '-blockversion=4']]
def run_test(self):
diff --git a/test/functional/bip68-sequence.py b/test/functional/bip68-sequence.py
index 87a50692f6..3818287209 100755
--- a/test/functional/bip68-sequence.py
+++ b/test/functional/bip68-sequence.py
@@ -17,10 +17,8 @@ SEQUENCE_LOCKTIME_MASK = 0x0000ffff
NOT_FINAL_ERROR = "64: non-BIP68-final"
class BIP68Test(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
self.extra_args = [[], ["-acceptnonstdtxn=0"]]
def run_test(self):
@@ -387,7 +385,7 @@ class BIP68Test(BitcoinTestFramework):
tx = FromHex(CTransaction(), rawtxfund)
tx.nVersion = 2
tx_signed = self.nodes[1].signrawtransaction(ToHex(tx))["hex"]
- tx_id = self.nodes[1].sendrawtransaction(tx_signed)
+ self.nodes[1].sendrawtransaction(tx_signed)
if __name__ == '__main__':
BIP68Test().main()
diff --git a/test/functional/bip9-softforks.py b/test/functional/bip9-softforks.py
index f00232c9ff..904789301a 100755
--- a/test/functional/bip9-softforks.py
+++ b/test/functional/bip9-softforks.py
@@ -28,11 +28,10 @@ from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP
class BIP9SoftForksTest(ComparisonTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-whitelist=127.0.0.1']]
+ self.setup_clean_chain = True
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
@@ -241,6 +240,7 @@ class BIP9SoftForksTest(ComparisonTestFramework):
# Restart all
self.test.clear_all_connections()
self.stop_nodes()
+ self.nodes = []
shutil.rmtree(self.options.tmpdir + "/node0")
self.setup_chain()
self.setup_network()
diff --git a/test/functional/bipdersig-p2p.py b/test/functional/bipdersig-p2p.py
index 38a9009544..c620d3e155 100755
--- a/test/functional/bipdersig-p2p.py
+++ b/test/functional/bipdersig-p2p.py
@@ -48,9 +48,7 @@ def create_transaction(node, coinbase, to_address, amount):
return tx
class BIP66Test(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-promiscuousmempoolflags=1', '-whitelist=127.0.0.1']]
self.setup_clean_chain = True
@@ -98,7 +96,7 @@ class BIP66Test(BitcoinTestFramework):
node0.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
- assert wait_until(lambda: "reject" in node0.last_message.keys())
+ wait_until(lambda: "reject" in node0.last_message.keys(), lock=mininode_lock)
with mininode_lock:
assert_equal(node0.last_message["reject"].code, REJECT_OBSOLETE)
assert_equal(node0.last_message["reject"].reason, b'bad-version(0x00000002)')
@@ -128,7 +126,7 @@ class BIP66Test(BitcoinTestFramework):
node0.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
- assert wait_until (lambda: "reject" in node0.last_message.keys())
+ wait_until(lambda: "reject" in node0.last_message.keys(), lock=mininode_lock)
with mininode_lock:
# We can receive different reject messages depending on whether
# bitcoind is running with multiple script check threads. If script
diff --git a/test/functional/bitcoin_cli.py b/test/functional/bitcoin_cli.py
new file mode 100755
index 0000000000..7acfede3f7
--- /dev/null
+++ b/test/functional/bitcoin_cli.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+# Copyright (c) 2017 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test bitcoin-cli"""
+from test_framework.test_framework import BitcoinTestFramework
+from test_framework.util import assert_equal
+
+class TestBitcoinCli(BitcoinTestFramework):
+
+ def set_test_params(self):
+ self.setup_clean_chain = True
+ self.num_nodes = 1
+
+ def run_test(self):
+ """Main test logic"""
+
+ self.log.info("Compare responses from getinfo RPC and `bitcoin-cli getinfo`")
+ cli_get_info = self.nodes[0].cli.getinfo()
+ rpc_get_info = self.nodes[0].getinfo()
+
+ assert_equal(cli_get_info, rpc_get_info)
+
+if __name__ == '__main__':
+ TestBitcoinCli().main()
diff --git a/test/functional/blockchain.py b/test/functional/blockchain.py
index a7034e6bcd..5d04de9940 100755
--- a/test/functional/blockchain.py
+++ b/test/functional/blockchain.py
@@ -30,12 +30,8 @@ from test_framework.util import (
assert_is_hash_string,
)
-
class BlockchainTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = False
+ def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-stopatheight=207']]
@@ -139,14 +135,14 @@ class BlockchainTest(BitcoinTestFramework):
self.nodes[0].generate(6)
assert_equal(self.nodes[0].getblockcount(), 206)
self.log.debug('Node should not stop at this height')
- assert_raises(subprocess.TimeoutExpired, lambda: self.bitcoind_processes[0].wait(timeout=3))
+ assert_raises(subprocess.TimeoutExpired, lambda: self.nodes[0].process.wait(timeout=3))
try:
self.nodes[0].generate(1)
except (ConnectionError, http.client.BadStatusLine):
pass # The node already shut down before response
self.log.debug('Node should stop at this height...')
- self.bitcoind_processes[0].wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
- self.nodes[0] = self.start_node(0, self.options.tmpdir)
+ self.nodes[0].process.wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
+ self.start_node(0)
assert_equal(self.nodes[0].getblockcount(), 207)
diff --git a/test/functional/bumpfee.py b/test/functional/bumpfee.py
index 9237f09240..dde87d5bd1 100755
--- a/test/functional/bumpfee.py
+++ b/test/functional/bumpfee.py
@@ -30,26 +30,21 @@ WALLET_PASSPHRASE_TIMEOUT = 3600
class BumpFeeTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
+ self.extra_args = [["-prematurewitness", "-walletprematurewitness", "-walletrbf={}".format(i)]
+ for i in range(self.num_nodes)]
- def setup_network(self, split=False):
- extra_args = [["-prematurewitness", "-walletprematurewitness", "-walletrbf={}".format(i)]
- for i in range(self.num_nodes)]
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
-
+ def run_test(self):
# Encrypt wallet for test_locked_wallet_fails test
- self.nodes[1].encryptwallet(WALLET_PASSPHRASE)
- self.bitcoind_processes[1].wait()
- self.nodes[1] = self.start_node(1, self.options.tmpdir, extra_args[1])
+ self.nodes[1].node_encrypt_wallet(WALLET_PASSPHRASE)
+ self.start_node(1)
self.nodes[1].walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
connect_nodes_bi(self.nodes, 0, 1)
self.sync_all()
- def run_test(self):
peer_node, rbf_node = self.nodes
rbf_node_address = rbf_node.getnewaddress()
@@ -90,7 +85,7 @@ def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address):
bumped_tx = rbf_node.bumpfee(rbfid)
assert_equal(bumped_tx["errors"], [])
assert bumped_tx["fee"] - abs(rbftx["fee"]) > 0
- # check that bumped_tx propogates, original tx was evicted and has a wallet conflict
+ # check that bumped_tx propagates, original tx was evicted and has a wallet conflict
sync_mempools((rbf_node, peer_node))
assert bumped_tx["txid"] in rbf_node.getrawmempool()
assert bumped_tx["txid"] in peer_node.getrawmempool()
@@ -168,7 +163,7 @@ def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address)
parent_id = spend_one_input(rbf_node, rbf_node_address)
tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.00020000})
tx = rbf_node.signrawtransaction(tx)
- txid = rbf_node.sendrawtransaction(tx["hex"])
+ rbf_node.sendrawtransaction(tx["hex"])
assert_raises_jsonrpc(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id)
diff --git a/test/functional/create_cache.py b/test/functional/create_cache.py
index 39c4c0f47e..7d4d1a529b 100755
--- a/test/functional/create_cache.py
+++ b/test/functional/create_cache.py
@@ -12,13 +12,10 @@ tests are being run in parallel.
from test_framework.test_framework import BitcoinTestFramework
class CreateCache(BitcoinTestFramework):
+ # Test network and test nodes are not required:
- def __init__(self):
- super().__init__()
-
- # Test network and test nodes are not required:
+ def set_test_params(self):
self.num_nodes = 0
- self.nodes = []
def setup_network(self):
pass
diff --git a/test/functional/dbcrash.py b/test/functional/dbcrash.py
index 8339305f5e..71424f641b 100755
--- a/test/functional/dbcrash.py
+++ b/test/functional/dbcrash.py
@@ -43,8 +43,7 @@ except AttributeError:
pass
class ChainstateWriteCrashTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 4
self.setup_clean_chain = False
@@ -64,7 +63,9 @@ class ChainstateWriteCrashTest(BitcoinTestFramework):
self.extra_args = [self.node0_args, self.node1_args, self.node2_args, self.node3_args]
def setup_network(self):
- self.setup_nodes()
+ # Need a bit of extra time for the nodes to start up for this test
+ self.add_nodes(self.num_nodes, timewait=90)
+ self.start_nodes()
# Leave them unconnected, we'll use submitblock directly in this test
def restart_node(self, node_index, expected_tip):
@@ -74,10 +75,10 @@ class ChainstateWriteCrashTest(BitcoinTestFramework):
after 60 seconds. Returns the utxo hash of the given node."""
time_start = time.time()
- while time.time() - time_start < 60:
+ while time.time() - time_start < 120:
try:
# Any of these RPC calls could throw due to node crash
- self.nodes[node_index] = self.start_node(node_index, self.options.tmpdir, self.extra_args[node_index])
+ self.start_node(node_index)
self.nodes[node_index].waitforblock(expected_tip)
utxo_hash = self.nodes[node_index].gettxoutsetinfo()['hash_serialized_2']
return utxo_hash
diff --git a/test/functional/decodescript.py b/test/functional/decodescript.py
index 21a9f1223f..6611da8831 100755
--- a/test/functional/decodescript.py
+++ b/test/functional/decodescript.py
@@ -10,9 +10,7 @@ from test_framework.mininode import *
from io import BytesIO
class DecodeScriptTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
diff --git a/test/functional/disablewallet.py b/test/functional/disablewallet.py
index d344513414..c1d37963bc 100755
--- a/test/functional/disablewallet.py
+++ b/test/functional/disablewallet.py
@@ -11,11 +11,8 @@
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
-
class DisableWalletTest (BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-disablewallet"]]
diff --git a/test/functional/disconnect_ban.py b/test/functional/disconnect_ban.py
index 89b68aeb25..a6445b9b35 100755
--- a/test/functional/disconnect_ban.py
+++ b/test/functional/disconnect_ban.py
@@ -5,18 +5,17 @@
"""Test node disconnect and ban behavior"""
import time
-from test_framework.mininode import wait_until
from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import (assert_equal,
- assert_raises_jsonrpc,
- connect_nodes_bi)
+from test_framework.util import (
+ assert_equal,
+ assert_raises_jsonrpc,
+ connect_nodes_bi,
+ wait_until,
+)
class DisconnectBanTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
def run_test(self):
self.log.info("Test setban and listbanned RPCs")
@@ -24,7 +23,7 @@ class DisconnectBanTest(BitcoinTestFramework):
self.log.info("setban: successfully ban single IP address")
assert_equal(len(self.nodes[1].getpeerinfo()), 2) # node1 should have 2 connections to node0 at this point
self.nodes[1].setban("127.0.0.1", "add")
- assert wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeout=10)
+ wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeout=10)
assert_equal(len(self.nodes[1].getpeerinfo()), 0) # all nodes must be disconnected at this point
assert_equal(len(self.nodes[1].listbanned()), 1)
@@ -66,8 +65,8 @@ class DisconnectBanTest(BitcoinTestFramework):
assert_equal(len(self.nodes[1].listbanned()), 3)
self.stop_node(1)
+ self.start_node(1)
- self.nodes[1] = self.start_node(1, self.options.tmpdir)
listAfterShutdown = self.nodes[1].listbanned()
assert_equal("127.0.0.0/24", listAfterShutdown[0]['address'])
assert_equal("127.0.0.0/32", listAfterShutdown[1]['address'])
@@ -90,7 +89,7 @@ class DisconnectBanTest(BitcoinTestFramework):
self.log.info("disconnectnode: successfully disconnect node by address")
address1 = self.nodes[0].getpeerinfo()[0]['addr']
self.nodes[0].disconnectnode(address=address1)
- assert wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10)
+ wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10)
assert not [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1]
self.log.info("disconnectnode: successfully reconnect node")
@@ -101,7 +100,7 @@ class DisconnectBanTest(BitcoinTestFramework):
self.log.info("disconnectnode: successfully disconnect node by node id")
id1 = self.nodes[0].getpeerinfo()[0]['id']
self.nodes[0].disconnectnode(nodeid=id1)
- assert wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10)
+ wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10)
assert not [node for node in self.nodes[0].getpeerinfo() if node['id'] == id1]
if __name__ == '__main__':
diff --git a/test/functional/example_test.py b/test/functional/example_test.py
index 7709524f23..87d73ad14a 100755
--- a/test/functional/example_test.py
+++ b/test/functional/example_test.py
@@ -23,13 +23,13 @@ from test_framework.mininode import (
mininode_lock,
msg_block,
msg_getdata,
- wait_until,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
connect_nodes,
p2p_port,
+ wait_until,
)
# NodeConnCB is a class containing callbacks to be executed when a P2P
@@ -73,21 +73,19 @@ def custom_function():
class ExampleTest(BitcoinTestFramework):
# Each functional test is a subclass of the BitcoinTestFramework class.
- # Override the __init__(), add_options(), setup_chain(), setup_network()
+ # Override the set_test_params(), add_options(), setup_chain(), setup_network()
# and setup_nodes() methods to customize the test setup as required.
- def __init__(self):
- """Initialize the test
+ def set_test_params(self):
+ """Override test parameters for your individual test.
- Call super().__init__() first, and then override any test parameters
- for your individual test."""
- super().__init__()
+ This method must be overridden and num_nodes must be exlicitly set."""
self.setup_clean_chain = True
self.num_nodes = 3
# Use self.extra_args to change command-line arguments for the nodes
self.extra_args = [[], ["-logips"], []]
- # self.log.info("I've finished __init__") # Oops! Can't run self.log before run_test()
+ # self.log.info("I've finished set_test_params") # Oops! Can't run self.log before run_test()
# Use add_options() to add specific command-line options for your test.
# In practice this is not used very much, since the tests are mostly written
@@ -200,7 +198,7 @@ class ExampleTest(BitcoinTestFramework):
node2.add_connection(connections[1])
node2.wait_for_verack()
- self.log.info("Wait for node2 reach current tip. Test that it has propogated all the blocks to us")
+ self.log.info("Wait for node2 reach current tip. Test that it has propagated all the blocks to us")
getdata_request = msg_getdata()
for block in blocks:
@@ -209,7 +207,7 @@ class ExampleTest(BitcoinTestFramework):
# wait_until() will loop until a predicate condition is met. Use it to test properties of the
# NodeConnCB objects.
- assert wait_until(lambda: sorted(blocks) == sorted(list(node2.block_receive_map.keys())), timeout=5)
+ wait_until(lambda: sorted(blocks) == sorted(list(node2.block_receive_map.keys())), timeout=5, lock=mininode_lock)
self.log.info("Check that each block was received only once")
# The network thread uses a global lock on data access to the NodeConn objects when sending and receiving
diff --git a/test/functional/forknotify.py b/test/functional/forknotify.py
index 3bcf0a6795..afcad1f9cc 100755
--- a/test/functional/forknotify.py
+++ b/test/functional/forknotify.py
@@ -7,28 +7,18 @@ import os
import time
from test_framework.test_framework import BitcoinTestFramework
-from test_framework.util import *
class ForkNotifyTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
def setup_network(self):
- self.nodes = []
self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt")
with open(self.alert_filename, 'w', encoding='utf8'):
pass # Just open then close to create zero-length file
- self.nodes.append(self.start_node(0, self.options.tmpdir,
- ["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""]))
- # Node1 mines block.version=211 blocks
- self.nodes.append(self.start_node(1, self.options.tmpdir,
- ["-blockversion=211"]))
- connect_nodes(self.nodes[1], 0)
-
- self.sync_all()
+ self.extra_args = [["-blockversion=2", "-alertnotify=echo %s >> \"" + self.alert_filename + "\""],
+ ["-blockversion=211"]]
+ super().setup_network()
def run_test(self):
# Mine 51 up-version blocks
diff --git a/test/functional/fundrawtransaction.py b/test/functional/fundrawtransaction.py
index e52e773918..75a0dc5f9d 100755
--- a/test/functional/fundrawtransaction.py
+++ b/test/functional/fundrawtransaction.py
@@ -14,13 +14,10 @@ def get_unspent(listunspent, amount):
return utx
raise AssertionError('Could not find unspent with amount={}'.format(amount))
-
class RawTransactionsTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = True
+ def set_test_params(self):
self.num_nodes = 4
+ self.setup_clean_chain = True
def setup_network(self, split=False):
self.setup_nodes()
@@ -312,7 +309,6 @@ class RawTransactionsTest(BitcoinTestFramework):
##############################################
# test a fundrawtransaction with invalid vin #
##############################################
- listunspent = self.nodes[2].listunspent()
inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin!
outputs = { self.nodes[0].getnewaddress() : 1.0}
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
@@ -449,12 +445,11 @@ class RawTransactionsTest(BitcoinTestFramework):
############################################################
# locked wallet test
self.stop_node(0)
+ self.nodes[1].node_encrypt_wallet("test")
self.stop_node(2)
self.stop_node(3)
- self.nodes[1].encryptwallet("test")
- self.bitcoind_processes[1].wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir)
+ self.start_nodes()
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
diff --git a/test/functional/getblocktemplate_longpoll.py b/test/functional/getblocktemplate_longpoll.py
index bbe1dda5f7..89768bd2fb 100755
--- a/test/functional/getblocktemplate_longpoll.py
+++ b/test/functional/getblocktemplate_longpoll.py
@@ -17,16 +17,14 @@ class LongpollThread(threading.Thread):
self.longpollid = templat['longpollid']
# create a new connection to the node, we can't use the same
# connection from two threads
- self.node = get_rpc_proxy(node.url, 1, timeout=600)
+ self.node = get_rpc_proxy(node.url, 1, timeout=600, coveragedir=node.coverage_dir)
def run(self):
self.node.getblocktemplate({'longpollid':self.longpollid})
class GetBlockTemplateLPTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
- self.num_nodes = 4
- self.setup_clean_chain = False
+ def set_test_params(self):
+ self.num_nodes = 2
def run_test(self):
self.log.info("Warning: this test will take about 70 seconds in the best case. Be patient.")
diff --git a/test/functional/getchaintips.py b/test/functional/getchaintips.py
index 15f96c565f..21b67bfc64 100755
--- a/test/functional/getchaintips.py
+++ b/test/functional/getchaintips.py
@@ -14,13 +14,10 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class GetChainTipsTest (BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 4
- self.setup_clean_chain = False
def run_test (self):
-
tips = self.nodes[0].getchaintips ()
assert_equal (len (tips), 1)
assert_equal (tips[0]['branchlen'], 0)
diff --git a/test/functional/httpbasics.py b/test/functional/httpbasics.py
index 4b32e8d9ca..c7682cb49d 100755
--- a/test/functional/httpbasics.py
+++ b/test/functional/httpbasics.py
@@ -11,10 +11,8 @@ import http.client
import urllib.parse
class HTTPBasicsTest (BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 3
- self.setup_clean_chain = False
def setup_network(self):
self.setup_nodes()
diff --git a/test/functional/import-rescan.py b/test/functional/import-rescan.py
index 4fc5078217..cb5b65c682 100755
--- a/test/functional/import-rescan.py
+++ b/test/functional/import-rescan.py
@@ -111,8 +111,7 @@ TIMESTAMP_WINDOW = 2 * 60 * 60
class ImportRescanTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2 + len(IMPORT_NODES)
def setup_network(self):
@@ -121,7 +120,8 @@ class ImportRescanTest(BitcoinTestFramework):
if import_node.prune:
extra_args[i] += ["-prune=1"]
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
+ self.add_nodes(self.num_nodes, extra_args)
+ self.start_nodes()
for i in range(1, self.num_nodes):
connect_nodes(self.nodes[i], 0)
@@ -161,7 +161,6 @@ class ImportRescanTest(BitcoinTestFramework):
variant.check()
# Create new transactions sending to each address.
- fee = self.nodes[0].getnetworkinfo()["relayfee"]
for i, variant in enumerate(IMPORT_VARIANTS):
variant.sent_amount = 10 - (2 * i + 1) / 8.0
variant.sent_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.sent_amount)
diff --git a/test/functional/importmulti.py b/test/functional/importmulti.py
index e83e85de13..32f555c79b 100755
--- a/test/functional/importmulti.py
+++ b/test/functional/importmulti.py
@@ -7,8 +7,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class ImportMultiTest (BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
@@ -21,16 +20,7 @@ class ImportMultiTest (BitcoinTestFramework):
self.nodes[1].generate(1)
timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']
- # keyword definition
- PRIV_KEY = 'privkey'
- PUB_KEY = 'pubkey'
- ADDRESS_KEY = 'address'
- SCRIPT_KEY = 'script'
-
-
node0_address1 = self.nodes[0].validateaddress(self.nodes[0].getnewaddress())
- node0_address2 = self.nodes[0].validateaddress(self.nodes[0].getnewaddress())
- node0_address3 = self.nodes[0].validateaddress(self.nodes[0].getnewaddress())
#Check only one address
assert_equal(node0_address1['ismine'], True)
@@ -230,7 +220,6 @@ class ImportMultiTest (BitcoinTestFramework):
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")
result = self.nodes[1].importmulti([{
@@ -258,7 +247,6 @@ class ImportMultiTest (BitcoinTestFramework):
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")
result = self.nodes[1].importmulti([{
@@ -286,7 +274,6 @@ class ImportMultiTest (BitcoinTestFramework):
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")
result = self.nodes[1].importmulti([{
@@ -314,7 +301,6 @@ class ImportMultiTest (BitcoinTestFramework):
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")
result = self.nodes[1].importmulti([{
@@ -429,7 +415,7 @@ class ImportMultiTest (BitcoinTestFramework):
# restart nodes to check for proper serialization/deserialization of watch only address
self.stop_nodes()
- self.nodes = self.start_nodes(2, self.options.tmpdir)
+ self.start_nodes()
address_assert = self.nodes[1].validateaddress(watchonly_address)
assert_equal(address_assert['iswatchonly'], True)
assert_equal(address_assert['ismine'], False)
diff --git a/test/functional/importprunedfunds.py b/test/functional/importprunedfunds.py
index 94753fe431..cb70010668 100755
--- a/test/functional/importprunedfunds.py
+++ b/test/functional/importprunedfunds.py
@@ -6,11 +6,8 @@
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
-
class ImportPrunedFundsTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
@@ -24,7 +21,6 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
address1 = self.nodes[0].getnewaddress()
# pubkey
address2 = self.nodes[0].getnewaddress()
- address2_pubkey = self.nodes[0].validateaddress(address2)['pubkey'] # Using pubkey
# privkey
address3 = self.nodes[0].getnewaddress()
address3_privkey = self.nodes[0].dumpprivkey(address3) # Using privkey
@@ -77,13 +73,13 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
#Import with affiliated address with no rescan
self.nodes[1].importaddress(address2, "add2", False)
- result2 = self.nodes[1].importprunedfunds(rawtxn2, proof2)
+ self.nodes[1].importprunedfunds(rawtxn2, proof2)
balance2 = self.nodes[1].getbalance("add2", 0, True)
assert_equal(balance2, Decimal('0.05'))
#Import with private key with no rescan
self.nodes[1].importprivkey(address3_privkey, "add3", False)
- result3 = self.nodes[1].importprunedfunds(rawtxn3, proof3)
+ self.nodes[1].importprunedfunds(rawtxn3, proof3)
balance3 = self.nodes[1].getbalance("add3", 0, False)
assert_equal(balance3, Decimal('0.025'))
balance3 = self.nodes[1].getbalance("*", 0, True)
diff --git a/test/functional/invalidateblock.py b/test/functional/invalidateblock.py
index c499d57b90..dd3daf1e07 100755
--- a/test/functional/invalidateblock.py
+++ b/test/functional/invalidateblock.py
@@ -8,9 +8,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class InvalidateTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
diff --git a/test/functional/invalidblockrequest.py b/test/functional/invalidblockrequest.py
index eabc0db8df..9f44b44927 100755
--- a/test/functional/invalidblockrequest.py
+++ b/test/functional/invalidblockrequest.py
@@ -23,9 +23,9 @@ class InvalidBlockRequestTest(ComparisonTestFramework):
''' Can either run this test as 1 node with expected answers, or two and compare them.
Change the "outcome" variable from each TestInstance object to only do the comparison. '''
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
+ self.setup_clean_chain = True
def run_test(self):
test = TestManager(self, self.options.tmpdir)
diff --git a/test/functional/invalidtxrequest.py b/test/functional/invalidtxrequest.py
index a9ac231f09..a22bd8f8cd 100755
--- a/test/functional/invalidtxrequest.py
+++ b/test/functional/invalidtxrequest.py
@@ -19,9 +19,9 @@ class InvalidTxRequestTest(ComparisonTestFramework):
''' Can either run this test as 1 node with expected answers, or two and compare them.
Change the "outcome" variable from each TestInstance object to only do the comparison. '''
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
+ self.setup_clean_chain = True
def run_test(self):
test = TestManager(self, self.options.tmpdir)
diff --git a/test/functional/keypool-topup.py b/test/functional/keypool-topup.py
index 0e0c0ea74b..b87433a9c5 100755
--- a/test/functional/keypool-topup.py
+++ b/test/functional/keypool-topup.py
@@ -20,8 +20,7 @@ from test_framework.util import (
)
class KeypoolRestoreTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [['-usehd=0'], ['-usehd=1', '-keypool=100', '-keypoolmin=20']]
@@ -35,7 +34,7 @@ class KeypoolRestoreTest(BitcoinTestFramework):
self.stop_node(1)
shutil.copyfile(self.tmpdir + "/node1/regtest/wallet.dat", self.tmpdir + "/wallet.bak")
- self.nodes[1] = self.start_node(1, self.tmpdir, self.extra_args[1])
+ self.start_node(1, self.extra_args[1])
connect_nodes_bi(self.nodes, 0, 1)
self.log.info("Generate keys for wallet")
@@ -61,7 +60,7 @@ class KeypoolRestoreTest(BitcoinTestFramework):
self.log.info("Verify keypool is restored and balance is correct")
- self.nodes[1] = self.start_node(1, self.tmpdir, self.extra_args[1])
+ self.start_node(1, self.extra_args[1])
connect_nodes_bi(self.nodes, 0, 1)
self.sync_all()
@@ -69,7 +68,7 @@ class KeypoolRestoreTest(BitcoinTestFramework):
assert_equal(self.nodes[1].listtransactions()[0]['category'], "receive")
# Check that we have marked all keys up to the used keypool key as used
- assert_equal(self.nodes[1].validateaddress(self.nodes[1].getnewaddress())['hdkeypath'], "m/0'/0'/111'")
+ assert_equal(self.nodes[1].validateaddress(self.nodes[1].getnewaddress())['hdkeypath'], "m/0'/0'/110'")
if __name__ == '__main__':
KeypoolRestoreTest().main()
diff --git a/test/functional/keypool.py b/test/functional/keypool.py
index e8be559918..b823ca63bb 100755
--- a/test/functional/keypool.py
+++ b/test/functional/keypool.py
@@ -8,6 +8,8 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class KeyPoolTest(BitcoinTestFramework):
+ def set_test_params(self):
+ self.num_nodes = 1
def run_test(self):
nodes = self.nodes
@@ -17,10 +19,9 @@ class KeyPoolTest(BitcoinTestFramework):
assert(addr_before_encrypting_data['hdmasterkeyid'] == wallet_info_old['hdmasterkeyid'])
# Encrypt wallet and wait to terminate
- nodes[0].encryptwallet('test')
- self.bitcoind_processes[0].wait()
+ nodes[0].node_encrypt_wallet('test')
# Restart node 0
- nodes[0] = self.start_node(0, self.options.tmpdir)
+ self.start_node(0)
# Keep creating keys
addr = nodes[0].getnewaddress()
addr_data = nodes[0].validateaddress(addr)
@@ -79,10 +80,5 @@ class KeyPoolTest(BitcoinTestFramework):
assert_equal(wi['keypoolsize_hd_internal'], 100)
assert_equal(wi['keypoolsize'], 100)
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = False
- self.num_nodes = 1
-
if __name__ == '__main__':
KeyPoolTest().main()
diff --git a/test/functional/listsinceblock.py b/test/functional/listsinceblock.py
index ce2d556ef0..6f428388ec 100755
--- a/test/functional/listsinceblock.py
+++ b/test/functional/listsinceblock.py
@@ -8,11 +8,9 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class ListSinceBlockTest (BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = True
+ def set_test_params(self):
self.num_nodes = 4
+ self.setup_clean_chain = True
def run_test(self):
self.nodes[2].generate(101)
diff --git a/test/functional/listtransactions.py b/test/functional/listtransactions.py
index f75a8e29cc..e4522cc3b5 100755
--- a/test/functional/listtransactions.py
+++ b/test/functional/listtransactions.py
@@ -16,15 +16,9 @@ def txFromHex(hexstring):
return tx
class ListTransactionsTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
- self.num_nodes = 4
- self.setup_clean_chain = False
-
- def setup_nodes(self):
- #This test requires mocktime
+ def set_test_params(self):
+ self.num_nodes = 2
self.enable_mocktime()
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir)
def run_test(self):
# Simple send, 0 to 1:
diff --git a/test/functional/maxuploadtarget.py b/test/functional/maxuploadtarget.py
index 66e5bd29e6..1f402798e7 100755
--- a/test/functional/maxuploadtarget.py
+++ b/test/functional/maxuploadtarget.py
@@ -31,8 +31,7 @@ class TestNode(NodeConnCB):
class MaxUploadTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-maxuploadtarget=800", "-blockmaxsize=999000"]]
@@ -147,7 +146,7 @@ class MaxUploadTest(BitcoinTestFramework):
#stop and start node 0 with 1MB maxuploadtarget, whitelist 127.0.0.1
self.log.info("Restarting nodes with -whitelist=127.0.0.1")
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-whitelist=127.0.0.1", "-maxuploadtarget=1", "-blockmaxsize=999000"])
+ self.start_node(0, ["-whitelist=127.0.0.1", "-maxuploadtarget=1", "-blockmaxsize=999000"])
#recreate/reconnect a test node
test_nodes = [TestNode()]
diff --git a/test/functional/mempool_limit.py b/test/functional/mempool_limit.py
index 2777291dd0..e24dc5a464 100755
--- a/test/functional/mempool_limit.py
+++ b/test/functional/mempool_limit.py
@@ -8,9 +8,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class MempoolLimitTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-maxmempool=5", "-spendzeroconfchange=0"]]
diff --git a/test/functional/mempool_packages.py b/test/functional/mempool_packages.py
index e225493816..2b09889661 100755
--- a/test/functional/mempool_packages.py
+++ b/test/functional/mempool_packages.py
@@ -12,10 +12,8 @@ MAX_ANCESTORS = 25
MAX_DESCENDANTS = 25
class MempoolPackagesTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
self.extra_args = [["-maxorphantx=1000"], ["-maxorphantx=1000", "-limitancestorcount=5"]]
# Build a transaction that spends parent_txid:vout
@@ -213,7 +211,7 @@ class MempoolPackagesTest(BitcoinTestFramework):
value = send_value
# Create tx1
- (tx1_id, tx1_value) = self.chain_transaction(self.nodes[0], tx0_id, 0, value, fee, 1)
+ tx1_id, _ = self.chain_transaction(self.nodes[0], tx0_id, 0, value, fee, 1)
# Create tx2-7
vout = 1
diff --git a/test/functional/mempool_persist.py b/test/functional/mempool_persist.py
index e0889fd5e9..01f65b1373 100755
--- a/test/functional/mempool_persist.py
+++ b/test/functional/mempool_persist.py
@@ -32,17 +32,12 @@ Test is as follows:
"""
import time
-from test_framework.mininode import wait_until
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class MempoolPersistTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- # We need 3 nodes for this test. Node1 does not have a persistent mempool.
+ def set_test_params(self):
self.num_nodes = 3
- self.setup_clean_chain = False
self.extra_args = [[], ["-persistmempool=0"], []]
def run_test(self):
@@ -64,27 +59,24 @@ class MempoolPersistTest(BitcoinTestFramework):
self.log.debug("Stop-start node0 and node1. Verify that node0 has the transactions in its mempool and node1 does not.")
self.stop_nodes()
- self.nodes = []
- self.nodes.append(self.start_node(0, self.options.tmpdir))
- self.nodes.append(self.start_node(1, self.options.tmpdir))
+ self.start_node(0)
+ self.start_node(1)
# Give bitcoind a second to reload the mempool
time.sleep(1)
- assert wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)
+ wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)
assert_equal(len(self.nodes[1].getrawmempool()), 0)
self.log.debug("Stop-start node0 with -persistmempool=0. Verify that it doesn't load its mempool.dat file.")
self.stop_nodes()
- self.nodes = []
- self.nodes.append(self.start_node(0, self.options.tmpdir, ["-persistmempool=0"]))
+ self.start_node(0, extra_args=["-persistmempool=0"])
# Give bitcoind a second to reload the mempool
time.sleep(1)
assert_equal(len(self.nodes[0].getrawmempool()), 0)
self.log.debug("Stop-start node0. Verify that it has the transactions in its mempool.")
self.stop_nodes()
- self.nodes = []
- self.nodes.append(self.start_node(0, self.options.tmpdir))
- assert wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)
+ self.start_node(0)
+ wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)
if __name__ == '__main__':
MempoolPersistTest().main()
diff --git a/test/functional/mempool_reorg.py b/test/functional/mempool_reorg.py
index 937bf4bab5..7dfddd3230 100755
--- a/test/functional/mempool_reorg.py
+++ b/test/functional/mempool_reorg.py
@@ -13,10 +13,8 @@ from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
self.extra_args = [["-checkmempool"]] * 2
alert_filename = None # Set by setup_network
diff --git a/test/functional/mempool_resurrect_test.py b/test/functional/mempool_resurrect_test.py
index a2f6228df9..1263c9306b 100755
--- a/test/functional/mempool_resurrect_test.py
+++ b/test/functional/mempool_resurrect_test.py
@@ -9,12 +9,8 @@ from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
- self.setup_clean_chain = False
- # Just need one node for this test
self.extra_args = [["-checkmempool"]]
def run_test(self):
diff --git a/test/functional/mempool_spendcoinbase.py b/test/functional/mempool_spendcoinbase.py
index 277ea45ad5..58ccd3e373 100755
--- a/test/functional/mempool_spendcoinbase.py
+++ b/test/functional/mempool_spendcoinbase.py
@@ -17,11 +17,8 @@ from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolSpendCoinbaseTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
- self.setup_clean_chain = False
self.extra_args = [["-checkmempool"]]
def run_test(self):
diff --git a/test/functional/merkle_blocks.py b/test/functional/merkle_blocks.py
index bcc65c8408..a58334b2a5 100755
--- a/test/functional/merkle_blocks.py
+++ b/test/functional/merkle_blocks.py
@@ -8,11 +8,9 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class MerkleBlockTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = True
+ def set_test_params(self):
self.num_nodes = 4
+ self.setup_clean_chain = True
# Nodes 0/1 are "wallet" nodes, Nodes 2/3 are used for testing
self.extra_args = [[], [], [], ["-txindex"]]
diff --git a/test/functional/mining.py b/test/functional/mining.py
index dbd4e29eca..93f9838896 100755
--- a/test/functional/mining.py
+++ b/test/functional/mining.py
@@ -4,16 +4,18 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mining RPCs
+- getmininginfo
- getblocktemplate proposal mode
- submitblock"""
-from binascii import b2a_hex
import copy
+from binascii import b2a_hex
+from decimal import Decimal
from test_framework.blocktools import create_coinbase
-from test_framework.test_framework import BitcoinTestFramework
from test_framework.mininode import CBlock
-from test_framework.util import *
+from test_framework.test_framework import BitcoinTestFramework
+from test_framework.util import assert_equal, assert_raises_jsonrpc
def b2x(b):
return b2a_hex(b).decode('ascii')
@@ -25,14 +27,24 @@ def assert_template(node, block, expect, rehash=True):
assert_equal(rsp, expect)
class MiningTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = False
def run_test(self):
node = self.nodes[0]
+
+ self.log.info('getmininginfo')
+ mining_info = node.getmininginfo()
+ assert_equal(mining_info['blocks'], 200)
+ assert_equal(mining_info['chain'], 'regtest')
+ assert_equal(mining_info['currentblocksize'], 0)
+ assert_equal(mining_info['currentblocktx'], 0)
+ assert_equal(mining_info['currentblockweight'], 0)
+ assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10'))
+ assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
+ assert_equal(mining_info['pooledtx'], 0)
+
# Mine a block to leave initial block download
node.generate(1)
tmpl = node.getblocktemplate()
diff --git a/test/functional/multi_rpc.py b/test/functional/multi_rpc.py
index a30e15ace9..a2b346f274 100755
--- a/test/functional/multi_rpc.py
+++ b/test/functional/multi_rpc.py
@@ -12,10 +12,7 @@ import http.client
import urllib.parse
class HTTPBasicsTest (BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = False
+ def set_test_params(self):
self.num_nodes = 2
def setup_chain(self):
diff --git a/test/functional/multiwallet.py b/test/functional/multiwallet.py
index 5679f40503..e5453e9aad 100755
--- a/test/functional/multiwallet.py
+++ b/test/functional/multiwallet.py
@@ -12,9 +12,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_jsonrpc
class MultiWalletTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [['-wallet=w1', '-wallet=w2', '-wallet=w3']]
@@ -23,23 +21,27 @@ class MultiWalletTest(BitcoinTestFramework):
self.stop_node(0)
# should not initialize if there are duplicate wallets
- self.assert_start_raises_init_error(0, self.options.tmpdir, ['-wallet=w1', '-wallet=w1'], 'Error loading wallet w1. Duplicate -wallet filename specified.')
+ self.assert_start_raises_init_error(0, ['-wallet=w1', '-wallet=w1'], 'Error loading wallet w1. Duplicate -wallet filename specified.')
# should not initialize if wallet file is a directory
os.mkdir(os.path.join(self.options.tmpdir, 'node0', 'regtest', 'w11'))
- self.assert_start_raises_init_error(0, self.options.tmpdir, ['-wallet=w11'], 'Error loading wallet w11. -wallet filename must be a regular file.')
+ self.assert_start_raises_init_error(0, ['-wallet=w11'], 'Error loading wallet w11. -wallet filename must be a regular file.')
# should not initialize if wallet file is a symlink
os.symlink(os.path.join(self.options.tmpdir, 'node0', 'regtest', 'w1'), os.path.join(self.options.tmpdir, 'node0', 'regtest', 'w12'))
- self.assert_start_raises_init_error(0, self.options.tmpdir, ['-wallet=w12'], 'Error loading wallet w12. -wallet filename must be a regular file.')
+ self.assert_start_raises_init_error(0, ['-wallet=w12'], 'Error loading wallet w12. -wallet filename must be a regular file.')
+
+ self.start_node(0, self.extra_args[0])
- self.nodes[0] = self.start_node(0, self.options.tmpdir, self.extra_args[0])
+ w1 = self.nodes[0].get_wallet_rpc("w1")
+ w2 = self.nodes[0].get_wallet_rpc("w2")
+ w3 = self.nodes[0].get_wallet_rpc("w3")
+ wallet_bad = self.nodes[0].get_wallet_rpc("bad")
- w1 = self.nodes[0] / "wallet/w1"
w1.generate(1)
# accessing invalid wallet fails
- assert_raises_jsonrpc(-18, "Requested wallet does not exist or is not loaded", (self.nodes[0] / "wallet/bad").getwalletinfo)
+ assert_raises_jsonrpc(-18, "Requested wallet does not exist or is not loaded", wallet_bad.getwalletinfo)
# accessing wallet RPC without using wallet endpoint fails
assert_raises_jsonrpc(-19, "Wallet file not specified", self.nodes[0].getwalletinfo)
@@ -50,14 +52,12 @@ class MultiWalletTest(BitcoinTestFramework):
w1_name = w1_info['walletname']
assert_equal(w1_name, "w1")
- # check w1 wallet balance
- w2 = self.nodes[0] / "wallet/w2"
+ # check w2 wallet balance
w2_info = w2.getwalletinfo()
assert_equal(w2_info['immature_balance'], 0)
w2_name = w2_info['walletname']
assert_equal(w2_name, "w2")
- w3 = self.nodes[0] / "wallet/w3"
w3_name = w3.getwalletinfo()['walletname']
assert_equal(w3_name, "w3")
diff --git a/test/functional/net.py b/test/functional/net.py
index 3ba3764cf9..830aeb45b4 100755
--- a/test/functional/net.py
+++ b/test/functional/net.py
@@ -17,10 +17,8 @@ from test_framework.util import (
p2p_port,
)
-
class NetTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
@@ -85,7 +83,7 @@ class NetTest(BitcoinTestFramework):
added_nodes = self.nodes[0].getaddednodeinfo(ip_port)
assert_equal(len(added_nodes), 1)
assert_equal(added_nodes[0]['addednode'], ip_port)
- # check that a non-existant node returns an error
+ # check that a non-existent node returns an error
assert_raises_jsonrpc(-24, "Node has not been added",
self.nodes[0].getaddednodeinfo, '1.1.1.1')
diff --git a/test/functional/nulldummy.py b/test/functional/nulldummy.py
index 9717add272..60d0d876df 100755
--- a/test/functional/nulldummy.py
+++ b/test/functional/nulldummy.py
@@ -37,8 +37,7 @@ def trueDummy(tx):
class NULLDUMMYTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.extra_args = [['-whitelist=127.0.0.1', '-walletprematurewitness']]
diff --git a/test/functional/p2p-acceptblock.py b/test/functional/p2p-acceptblock.py
index 322cb767db..293bc05539 100755
--- a/test/functional/p2p-acceptblock.py
+++ b/test/functional/p2p-acceptblock.py
@@ -60,8 +60,7 @@ class AcceptBlockTest(BitcoinTestFramework):
default=os.getenv("BITCOIND", "bitcoind"),
help="bitcoind binary to test")
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [[], ["-whitelist=127.0.0.1"]]
diff --git a/test/functional/p2p-compactblocks.py b/test/functional/p2p-compactblocks.py
index ff76e49fba..94513d3f43 100755
--- a/test/functional/p2p-compactblocks.py
+++ b/test/functional/p2p-compactblocks.py
@@ -70,7 +70,7 @@ class TestNode(NodeConnCB):
def request_headers_and_sync(self, locator, hashstop=0):
self.clear_block_announcement()
self.get_headers(locator, hashstop)
- assert wait_until(self.received_block_announcement, timeout=30)
+ wait_until(self.received_block_announcement, timeout=30, lock=mininode_lock)
self.clear_block_announcement()
# Block until a block announcement for a particular block hash is
@@ -78,7 +78,7 @@ class TestNode(NodeConnCB):
def wait_for_block_announcement(self, block_hash, timeout=30):
def received_hash():
return (block_hash in self.announced_blockhashes)
- return wait_until(received_hash, timeout=timeout)
+ wait_until(received_hash, timeout=timeout, lock=mininode_lock)
def send_await_disconnect(self, message, timeout=30):
"""Sends a message to the node and wait for disconnect.
@@ -86,15 +86,10 @@ class TestNode(NodeConnCB):
This is used when we want to send a message into the node that we expect
will get us disconnected, eg an invalid block."""
self.send_message(message)
- success = wait_until(lambda: not self.connected, timeout=timeout)
- if not success:
- logger.error("send_await_disconnect failed!")
- raise AssertionError("send_await_disconnect failed!")
- return success
+ wait_until(lambda: not self.connected, timeout=timeout, lock=mininode_lock)
class CompactBlocksTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
# Node0 = pre-segwit, node1 = segwit-aware
self.num_nodes = 2
@@ -150,9 +145,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Make sure we get a SENDCMPCT message from our peer
def received_sendcmpct():
return (len(test_node.last_sendcmpct) > 0)
- got_message = wait_until(received_sendcmpct, timeout=30)
- assert(received_sendcmpct())
- assert(got_message)
+ wait_until(received_sendcmpct, timeout=30, lock=mininode_lock)
with mininode_lock:
# Check that the first version received is the preferred one
assert_equal(test_node.last_sendcmpct[0].version, preferred_version)
@@ -167,7 +160,6 @@ class CompactBlocksTest(BitcoinTestFramework):
block_hash = int(node.generate(1)[0], 16)
peer.wait_for_block_announcement(block_hash, timeout=30)
assert(peer.block_announced)
- assert(got_message)
with mininode_lock:
assert predicate(peer), (
@@ -282,7 +274,7 @@ class CompactBlocksTest(BitcoinTestFramework):
# Wait until we've seen the block announcement for the resulting tip
tip = int(node.getbestblockhash(), 16)
- assert(test_node.wait_for_block_announcement(tip))
+ test_node.wait_for_block_announcement(tip)
# Make sure we will receive a fast-announce compact block
self.request_cb_announcements(test_node, node, version)
@@ -293,12 +285,12 @@ class CompactBlocksTest(BitcoinTestFramework):
# Store the raw block in our internal format.
block = FromHex(CBlock(), node.getblock("%02x" % block_hash, False))
- [tx.calc_sha256() for tx in block.vtx]
+ for tx in block.vtx:
+ tx.calc_sha256()
block.rehash()
# Wait until the block was announced (via compact blocks)
- wait_until(test_node.received_block_announcement, timeout=30)
- assert(test_node.received_block_announcement())
+ wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
# Now fetch and check the compact block
header_and_shortids = None
@@ -314,8 +306,7 @@ class CompactBlocksTest(BitcoinTestFramework):
inv = CInv(4, block_hash) # 4 == "CompactBlock"
test_node.send_message(msg_getdata([inv]))
- wait_until(test_node.received_block_announcement, timeout=30)
- assert(test_node.received_block_announcement())
+ wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
# Now fetch and check the compact block
header_and_shortids = None
@@ -386,13 +377,11 @@ class CompactBlocksTest(BitcoinTestFramework):
if announce == "inv":
test_node.send_message(msg_inv([CInv(2, block.sha256)]))
- success = wait_until(lambda: "getheaders" in test_node.last_message, timeout=30)
- assert(success)
+ wait_until(lambda: "getheaders" in test_node.last_message, timeout=30, lock=mininode_lock)
test_node.send_header_for_blocks([block])
else:
test_node.send_header_for_blocks([block])
- success = wait_until(lambda: "getdata" in test_node.last_message, timeout=30)
- assert(success)
+ wait_until(lambda: "getdata" in test_node.last_message, timeout=30, lock=mininode_lock)
assert_equal(len(test_node.last_message["getdata"].inv), 1)
assert_equal(test_node.last_message["getdata"].inv[0].type, 4)
assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
@@ -571,8 +560,7 @@ class CompactBlocksTest(BitcoinTestFramework):
assert_equal(int(node.getbestblockhash(), 16), block.hashPrevBlock)
# We should receive a getdata request
- success = wait_until(lambda: "getdata" in test_node.last_message, timeout=10)
- assert(success)
+ wait_until(lambda: "getdata" in test_node.last_message, timeout=10, lock=mininode_lock)
assert_equal(len(test_node.last_message["getdata"].inv), 1)
assert(test_node.last_message["getdata"].inv[0].type == 2 or test_node.last_message["getdata"].inv[0].type == 2|MSG_WITNESS_FLAG)
assert_equal(test_node.last_message["getdata"].inv[0].hash, block.sha256)
@@ -599,8 +587,7 @@ class CompactBlocksTest(BitcoinTestFramework):
num_to_request = random.randint(1, len(block.vtx))
msg.block_txn_request.from_absolute(sorted(random.sample(range(len(block.vtx)), num_to_request)))
test_node.send_message(msg)
- success = wait_until(lambda: "blocktxn" in test_node.last_message, timeout=10)
- assert(success)
+ wait_until(lambda: "blocktxn" in test_node.last_message, timeout=10, lock=mininode_lock)
[tx.calc_sha256() for tx in block.vtx]
with mininode_lock:
@@ -639,22 +626,20 @@ class CompactBlocksTest(BitcoinTestFramework):
for i in range(MAX_CMPCTBLOCK_DEPTH + 1):
test_node.clear_block_announcement()
new_blocks.append(node.generate(1)[0])
- wait_until(test_node.received_block_announcement, timeout=30)
+ wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
test_node.clear_block_announcement()
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
- success = wait_until(lambda: "cmpctblock" in test_node.last_message, timeout=30)
- assert(success)
+ wait_until(lambda: "cmpctblock" in test_node.last_message, timeout=30, lock=mininode_lock)
test_node.clear_block_announcement()
node.generate(1)
- wait_until(test_node.received_block_announcement, timeout=30)
+ wait_until(test_node.received_block_announcement, timeout=30, lock=mininode_lock)
test_node.clear_block_announcement()
with mininode_lock:
test_node.last_message.pop("block", None)
test_node.send_message(msg_getdata([CInv(4, int(new_blocks[0], 16))]))
- success = wait_until(lambda: "block" in test_node.last_message, timeout=30)
- assert(success)
+ wait_until(lambda: "block" in test_node.last_message, timeout=30, lock=mininode_lock)
with mininode_lock:
test_node.last_message["block"].block.calc_sha256()
assert_equal(test_node.last_message["block"].block.sha256, int(new_blocks[0], 16))
@@ -705,7 +690,7 @@ class CompactBlocksTest(BitcoinTestFramework):
node.submitblock(ToHex(block))
for l in listeners:
- wait_until(lambda: l.received_block_announcement(), timeout=30)
+ wait_until(lambda: l.received_block_announcement(), timeout=30, lock=mininode_lock)
with mininode_lock:
for l in listeners:
assert "cmpctblock" in l.last_message
diff --git a/test/functional/p2p-feefilter.py b/test/functional/p2p-feefilter.py
index dbccb633a5..8c92365ced 100755
--- a/test/functional/p2p-feefilter.py
+++ b/test/functional/p2p-feefilter.py
@@ -37,11 +37,8 @@ class TestNode(NodeConnCB):
self.txinvs = []
class FeeFilterTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
- self.setup_clean_chain = False
def run_test(self):
node1 = self.nodes[1]
diff --git a/test/functional/p2p-fullblocktest.py b/test/functional/p2p-fullblocktest.py
index e7fe7372c8..1d969fc7c1 100755
--- a/test/functional/p2p-fullblocktest.py
+++ b/test/functional/p2p-fullblocktest.py
@@ -49,12 +49,11 @@ class CBrokenBlock(CBlock):
return r
class FullBlockTest(ComparisonTestFramework):
-
# Can either run this test as 1 node with expected answers, or two and compare them.
# Change the "outcome" variable from each TestInstance object to only do the comparison.
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
+ self.setup_clean_chain = True
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(b"horsebattery")
@@ -397,7 +396,7 @@ class FullBlockTest(ComparisonTestFramework):
yield rejected(RejectResult(16, b'bad-cb-length'))
# Extend the b26 chain to make sure bitcoind isn't accepting b26
- b27 = block(27, spend=out[7])
+ block(27, spend=out[7])
yield rejected(False)
# Now try a too-large-coinbase script
@@ -409,7 +408,7 @@ class FullBlockTest(ComparisonTestFramework):
yield rejected(RejectResult(16, b'bad-cb-length'))
# Extend the b28 chain to make sure bitcoind isn't accepting b28
- b29 = block(29, spend=out[7])
+ block(29, spend=out[7])
yield rejected(False)
# b30 has a max-sized coinbase scriptSig.
@@ -581,7 +580,7 @@ class FullBlockTest(ComparisonTestFramework):
# same as b40, but one less sigop
tip(39)
- b41 = block(41, spend=None)
+ block(41, spend=None)
update_block(41, b40.vtx[1:-1])
b41_sigops_to_fill = b40_sigops_to_fill - 1
tx = CTransaction()
@@ -927,7 +926,7 @@ class FullBlockTest(ComparisonTestFramework):
# -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
#
tip(64)
- b65 = block(65)
+ block(65)
tx1 = create_and_sign_tx(out[19].tx, out[19].n, out[19].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 0)
update_block(65, [tx1, tx2])
@@ -939,7 +938,7 @@ class FullBlockTest(ComparisonTestFramework):
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
# \-> b66 (20)
tip(65)
- b66 = block(66)
+ block(66)
tx1 = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 1)
update_block(66, [tx2, tx1])
@@ -952,7 +951,7 @@ class FullBlockTest(ComparisonTestFramework):
#
#
tip(65)
- b67 = block(67)
+ block(67)
tx1 = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 1)
tx3 = create_and_sign_tx(tx1, 0, 2)
@@ -972,7 +971,7 @@ class FullBlockTest(ComparisonTestFramework):
# this succeeds
#
tip(65)
- b68 = block(68, additional_coinbase_value=10)
+ block(68, additional_coinbase_value=10)
tx = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue-9)
update_block(68, [tx])
yield rejected(RejectResult(16, b'bad-cb-amount'))
@@ -1175,7 +1174,7 @@ class FullBlockTest(ComparisonTestFramework):
#
# -> b81 (26) -> b82 (27) -> b83 (28)
#
- b83 = block(83)
+ block(83)
op_codes = [OP_IF, OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF]
script = CScript(op_codes)
tx1 = create_and_sign_tx(out[28].tx, out[28].n, out[28].tx.vout[0].nValue, script)
@@ -1195,7 +1194,7 @@ class FullBlockTest(ComparisonTestFramework):
# \-> b85 (29) -> b86 (30) \-> b89a (32)
#
#
- b84 = block(84)
+ block(84)
tx1 = create_tx(out[29].tx, out[29].n, 0, CScript([OP_RETURN]))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
diff --git a/test/functional/p2p-leaktests.py b/test/functional/p2p-leaktests.py
index 5611c876ae..f27086c97e 100755
--- a/test/functional/p2p-leaktests.py
+++ b/test/functional/p2p-leaktests.py
@@ -92,8 +92,7 @@ class CNodeNoVerackIdle(CLazyNode):
conn.send_message(msg_getaddr())
class P2PLeakTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-banscore='+str(banscore)]]
@@ -119,11 +118,11 @@ class P2PLeakTest(BitcoinTestFramework):
NetworkThread().start() # Start up network handling in another thread
- assert wait_until(lambda: no_version_bannode.ever_connected, timeout=10)
- assert wait_until(lambda: no_version_idlenode.ever_connected, timeout=10)
- assert wait_until(lambda: no_verack_idlenode.version_received, timeout=10)
- assert wait_until(lambda: unsupported_service_bit5_node.ever_connected, timeout=10)
- assert wait_until(lambda: unsupported_service_bit7_node.ever_connected, timeout=10)
+ wait_until(lambda: no_version_bannode.ever_connected, timeout=10, lock=mininode_lock)
+ wait_until(lambda: no_version_idlenode.ever_connected, timeout=10, lock=mininode_lock)
+ wait_until(lambda: no_verack_idlenode.version_received, timeout=10, lock=mininode_lock)
+ wait_until(lambda: unsupported_service_bit5_node.ever_connected, timeout=10, lock=mininode_lock)
+ wait_until(lambda: unsupported_service_bit7_node.ever_connected, timeout=10, lock=mininode_lock)
# Mine a block and make sure that it's not sent to the connected nodes
self.nodes[0].generate(1)
@@ -158,8 +157,8 @@ class P2PLeakTest(BitcoinTestFramework):
allowed_service_bit5_node.add_connection(connections[5])
allowed_service_bit7_node.add_connection(connections[6])
- assert wait_until(lambda: allowed_service_bit5_node.message_count["verack"], timeout=10)
- assert wait_until(lambda: allowed_service_bit7_node.message_count["verack"], timeout=10)
+ wait_until(lambda: allowed_service_bit5_node.message_count["verack"], timeout=10, lock=mininode_lock)
+ wait_until(lambda: allowed_service_bit7_node.message_count["verack"], timeout=10, lock=mininode_lock)
if __name__ == '__main__':
P2PLeakTest().main()
diff --git a/test/functional/p2p-mempool.py b/test/functional/p2p-mempool.py
index 34ef249eea..40fcde2605 100755
--- a/test/functional/p2p-mempool.py
+++ b/test/functional/p2p-mempool.py
@@ -13,9 +13,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class P2PMempoolTests(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-peerbloomfilters=0"]]
diff --git a/test/functional/p2p-segwit.py b/test/functional/p2p-segwit.py
index 63dfbb8ae6..943bc2c6d2 100755
--- a/test/functional/p2p-segwit.py
+++ b/test/functional/p2p-segwit.py
@@ -17,7 +17,6 @@ from binascii import hexlify
# The versionbit bit used to signal activation of SegWit
VB_WITNESS_BIT = 1
VB_PERIOD = 144
-VB_ACTIVATION_THRESHOLD = 108
VB_TOP_BITS = 0x20000000
MAX_SIGOP_COST = 80000
@@ -33,8 +32,8 @@ def get_virtual_size(witness_block):
return vsize
class TestNode(NodeConnCB):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
+ self.num_nodes = 3
self.getdataset = set()
def on_getdata(self, conn, message):
@@ -109,9 +108,7 @@ def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key):
class SegWitTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [["-whitelist=127.0.0.1"], ["-whitelist=127.0.0.1", "-acceptnonstdtxn=0"], ["-whitelist=127.0.0.1", "-vbparams=segwit:0:0"]]
@@ -1496,7 +1493,7 @@ class SegWitTest(BitcoinTestFramework):
# Restart with the new binary
self.stop_node(node_id)
- self.nodes[node_id] = self.start_node(node_id, self.options.tmpdir)
+ self.start_node(node_id, extra_args=[])
connect_nodes(self.nodes[0], node_id)
sync_blocks(self.nodes)
diff --git a/test/functional/p2p-timeouts.py b/test/functional/p2p-timeouts.py
index c3b29c215b..51d4769efc 100755
--- a/test/functional/p2p-timeouts.py
+++ b/test/functional/p2p-timeouts.py
@@ -33,8 +33,7 @@ class TestNode(NodeConnCB):
pass
class TimeoutsTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
diff --git a/test/functional/p2p-versionbits-warning.py b/test/functional/p2p-versionbits-warning.py
index df7e8ce5c1..5dfac6dd10 100755
--- a/test/functional/p2p-versionbits-warning.py
+++ b/test/functional/p2p-versionbits-warning.py
@@ -28,8 +28,7 @@ class TestNode(NodeConnCB):
pass
class VersionBitsWarningTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
@@ -112,7 +111,7 @@ class VersionBitsWarningTest(BitcoinTestFramework):
# Empty out the alert file
with open(self.alert_filename, 'w', encoding='utf8') as _:
pass
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, self.extra_args)
+ self.start_nodes()
# Connecting one block should be enough to generate an error.
self.nodes[0].generate(1)
@@ -123,7 +122,7 @@ class VersionBitsWarningTest(BitcoinTestFramework):
self.test_versionbits_in_alert_file()
# Test framework expects the node to still be running...
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, self.extra_args)
+ self.start_nodes()
if __name__ == '__main__':
VersionBitsWarningTest().main()
diff --git a/test/functional/preciousblock.py b/test/functional/preciousblock.py
index 04b41e76ba..1466f901c0 100755
--- a/test/functional/preciousblock.py
+++ b/test/functional/preciousblock.py
@@ -35,8 +35,7 @@ def node_sync_via_rpc(nodes):
unidirectional_node_sync_via_rpc(node_src, node_dest)
class PreciousTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
@@ -47,16 +46,16 @@ class PreciousTest(BitcoinTestFramework):
self.log.info("Ensure submitblock can in principle reorg to a competing chain")
self.nodes[0].generate(1)
assert_equal(self.nodes[0].getblockcount(), 1)
- (hashY, hashZ) = self.nodes[1].generate(2)
+ hashZ = self.nodes[1].generate(2)[-1]
assert_equal(self.nodes[1].getblockcount(), 2)
node_sync_via_rpc(self.nodes[0:3])
assert_equal(self.nodes[0].getbestblockhash(), hashZ)
self.log.info("Mine blocks A-B-C on Node 0")
- (hashA, hashB, hashC) = self.nodes[0].generate(3)
+ hashC = self.nodes[0].generate(3)[-1]
assert_equal(self.nodes[0].getblockcount(), 5)
self.log.info("Mine competing blocks E-F-G on Node 1")
- (hashE, hashF, hashG) = self.nodes[1].generate(3)
+ hashG = self.nodes[1].generate(3)[-1]
assert_equal(self.nodes[1].getblockcount(), 5)
assert(hashC != hashG)
self.log.info("Connect nodes and check no reorg occurs")
diff --git a/test/functional/prioritise_transaction.py b/test/functional/prioritise_transaction.py
index 4fc03d2547..7ad368acd4 100755
--- a/test/functional/prioritise_transaction.py
+++ b/test/functional/prioritise_transaction.py
@@ -9,9 +9,7 @@ from test_framework.util import *
from test_framework.mininode import COIN, MAX_BLOCK_BASE_SIZE
class PrioritiseTransactionTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [["-printpriority=1"], ["-printpriority=1"]]
diff --git a/test/functional/proxy_test.py b/test/functional/proxy_test.py
index ae6f843ddc..81b99d1bf4 100755
--- a/test/functional/proxy_test.py
+++ b/test/functional/proxy_test.py
@@ -41,12 +41,9 @@ from test_framework.netutil import test_ipv6_local
RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports
-
class ProxyTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 4
- self.setup_clean_chain = False
def setup_nodes(self):
self.have_ipv6 = test_ipv6_local()
@@ -89,7 +86,8 @@ class ProxyTest(BitcoinTestFramework):
]
if self.have_ipv6:
args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion']
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args=args)
+ self.add_nodes(self.num_nodes, extra_args=args)
+ self.start_nodes()
def node_test(self, node, proxies, auth, test_onion=True):
rv = []
diff --git a/test/functional/pruning.py b/test/functional/pruning.py
index 0af91e0658..f53fe82881 100755
--- a/test/functional/pruning.py
+++ b/test/functional/pruning.py
@@ -26,9 +26,7 @@ def calc_usage(blockdir):
return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f)) / (1024. * 1024.)
class PruneTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 6
@@ -56,6 +54,10 @@ class PruneTest(BitcoinTestFramework):
connect_nodes(self.nodes[0], 4)
sync_blocks(self.nodes[0:5])
+ def setup_nodes(self):
+ self.add_nodes(self.num_nodes, self.extra_args, timewait=900)
+ self.start_nodes()
+
def create_big_chain(self):
# Start by creating some coinbases we can spend later
self.nodes[1].generate(200)
@@ -98,7 +100,7 @@ class PruneTest(BitcoinTestFramework):
# Node 2 stays connected, so it hears about the stale blocks and then reorg's when node0 reconnects
# Stopping node 0 also clears its mempool, so it doesn't have node1's transactions to accidentally mine
self.stop_node(0)
- self.nodes[0]=self.start_node(0, self.options.tmpdir, self.full_node_default_args, timewait=900)
+ self.start_node(0, extra_args=self.full_node_default_args)
# Mine 24 blocks in node 1
for i in range(24):
if j == 0:
@@ -126,7 +128,7 @@ class PruneTest(BitcoinTestFramework):
# Reboot node 1 to clear its mempool (hopefully make the invalidate faster)
# Lower the block max size so we don't keep mining all our big mempool transactions (from disconnected blocks)
self.stop_node(1)
- self.nodes[1] = self.start_node(1, self.options.tmpdir, ["-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"], timewait=900)
+ self.start_node(1, extra_args=["-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"])
height = self.nodes[1].getblockcount()
self.log.info("Current block height: %d" % height)
@@ -136,7 +138,7 @@ class PruneTest(BitcoinTestFramework):
self.log.info("Invalidating block %s at height %d" % (badhash,invalidheight))
self.nodes[1].invalidateblock(badhash)
- # We've now switched to our previously mined-24 block fork on node 1, but thats not what we want
+ # We've now switched to our previously mined-24 block fork on node 1, but that's not what we want
# So invalidate that fork as well, until we're on the same chain as node 0/2 (but at an ancestor 288 blocks ago)
mainchainhash = self.nodes[0].getblockhash(invalidheight - 1)
curhash = self.nodes[1].getblockhash(invalidheight - 1)
@@ -149,7 +151,7 @@ class PruneTest(BitcoinTestFramework):
# Reboot node1 to clear those giant tx's from mempool
self.stop_node(1)
- self.nodes[1] = self.start_node(1, self.options.tmpdir, ["-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"], timewait=900)
+ self.start_node(1, extra_args=["-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"])
self.log.info("Generating new longer chain of 300 more blocks")
self.nodes[1].generate(300)
@@ -199,7 +201,7 @@ class PruneTest(BitcoinTestFramework):
goalbesthash = self.mainchainhash2
# As of 0.10 the current block download logic is not able to reorg to the original chain created in
- # create_chain_with_stale_blocks because it doesn't know of any peer thats on that chain from which to
+ # create_chain_with_stale_blocks because it doesn't know of any peer that's on that chain from which to
# redownload its missing blocks.
# Invalidate the reorg_test chain in node 0 as well, it can successfully switch to the original chain
# because it has all the block data.
@@ -227,13 +229,15 @@ class PruneTest(BitcoinTestFramework):
def manual_test(self, node_number, use_timestamp):
# at this point, node has 995 blocks and has not yet run in prune mode
- node = self.nodes[node_number] = self.start_node(node_number, self.options.tmpdir, timewait=900)
+ self.start_node(node_number)
+ node = self.nodes[node_number]
assert_equal(node.getblockcount(), 995)
assert_raises_jsonrpc(-1, "not in prune mode", node.pruneblockchain, 500)
- self.stop_node(node_number)
# now re-start in manual pruning mode
- node = self.nodes[node_number] = self.start_node(node_number, self.options.tmpdir, ["-prune=1"], timewait=900)
+ self.stop_node(node_number)
+ self.start_node(node_number, extra_args=["-prune=1"])
+ node = self.nodes[node_number]
assert_equal(node.getblockcount(), 995)
def height(index):
@@ -307,7 +311,7 @@ class PruneTest(BitcoinTestFramework):
# stop node, start back up with auto-prune at 550MB, make sure still runs
self.stop_node(node_number)
- self.nodes[node_number] = self.start_node(node_number, self.options.tmpdir, ["-prune=550"], timewait=900)
+ self.start_node(node_number, extra_args=["-prune=550"])
self.log.info("Success")
@@ -315,7 +319,7 @@ class PruneTest(BitcoinTestFramework):
# check that the pruning node's wallet is still in good shape
self.log.info("Stop and start pruning node to trigger wallet rescan")
self.stop_node(2)
- self.nodes[2] = self.start_node(2, self.options.tmpdir, ["-prune=550"])
+ self.start_node(2, extra_args=["-prune=550"])
self.log.info("Success")
# check that wallet loads successfully when restarting a pruned node after IBD.
@@ -325,7 +329,7 @@ class PruneTest(BitcoinTestFramework):
nds = [self.nodes[0], self.nodes[5]]
sync_blocks(nds, wait=5, timeout=300)
self.stop_node(5) #stop and start to trigger rescan
- self.nodes[5] = self.start_node(5, self.options.tmpdir, ["-prune=550"])
+ self.start_node(5, extra_args=["-prune=550"])
self.log.info("Success")
def run_test(self):
diff --git a/test/functional/rawtransactions.py b/test/functional/rawtransactions.py
index 6272fc69b7..d7255daa0a 100755
--- a/test/functional/rawtransactions.py
+++ b/test/functional/rawtransactions.py
@@ -2,7 +2,7 @@
# 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.
-"""Test the rawtranscation RPCs.
+"""Test the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
@@ -17,9 +17,7 @@ from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
@@ -63,7 +61,6 @@ class RawTransactionsTest(BitcoinTestFramework):
addr2Obj = self.nodes[2].validateaddress(addr2)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
- mSigObjValid = self.nodes[2].validateaddress(mSigObj)
#use balance deltas instead of absolute values
bal = self.nodes[2].getbalance()
@@ -87,7 +84,6 @@ class RawTransactionsTest(BitcoinTestFramework):
addr3Obj = self.nodes[2].validateaddress(addr3)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])
- mSigObjValid = self.nodes[2].validateaddress(mSigObj)
txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
decTx = self.nodes[0].gettransaction(txId)
diff --git a/test/functional/receivedby.py b/test/functional/receivedby.py
index 19d99c9c9e..db6fc86b82 100755
--- a/test/functional/receivedby.py
+++ b/test/functional/receivedby.py
@@ -23,16 +23,9 @@ def get_sub_array_from_array(object_array, to_match):
return []
class ReceivedByTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.num_nodes = 4
- self.setup_clean_chain = False
-
- def setup_nodes(self):
- #This test requires mocktime
+ def set_test_params(self):
+ self.num_nodes = 2
self.enable_mocktime()
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir)
def run_test(self):
'''
diff --git a/test/functional/reindex.py b/test/functional/reindex.py
index b446baa04d..1f684a1afe 100755
--- a/test/functional/reindex.py
+++ b/test/functional/reindex.py
@@ -15,8 +15,7 @@ import time
class ReindexTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
@@ -25,7 +24,7 @@ class ReindexTest(BitcoinTestFramework):
blockcount = self.nodes[0].getblockcount()
self.stop_nodes()
extra_args = [["-reindex-chainstate" if justchainstate else "-reindex", "-checkblockindex=1"]]
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
+ self.start_nodes(extra_args)
while self.nodes[0].getblockcount() < blockcount:
time.sleep(0.1)
assert_equal(self.nodes[0].getblockcount(), blockcount)
diff --git a/test/functional/replace-by-fee.py b/test/functional/replace-by-fee.py
index bc67654987..1d6494fe41 100755
--- a/test/functional/replace-by-fee.py
+++ b/test/functional/replace-by-fee.py
@@ -61,10 +61,8 @@ def make_utxo(node, amount, confirmed=True, scriptPubKey=CScript([1])):
class ReplaceByFeeTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 1
- self.setup_clean_chain = False
self.extra_args= [["-maxorphantx=1000",
"-whitelist=127.0.0.1",
"-limitancestorcount=50",
@@ -270,7 +268,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]
tx1a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1a_hex = txToHex(tx1a)
- tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, True)
+ self.nodes[0].sendrawtransaction(tx1a_hex, True)
# Higher fee, but the fee per KB is much lower, so the replacement is
# rejected.
@@ -331,7 +329,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx1.vin = [CTxIn(confirmed_utxo)]
tx1.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx1_hex = txToHex(tx1)
- tx1_txid = self.nodes[0].sendrawtransaction(tx1_hex, True)
+ self.nodes[0].sendrawtransaction(tx1_hex, True)
tx2 = CTransaction()
tx2.vin = [CTxIn(confirmed_utxo), CTxIn(unconfirmed_utxo)]
@@ -499,7 +497,7 @@ class ReplaceByFeeTest(BitcoinTestFramework):
tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0)]
tx2a.vout = [CTxOut(1*COIN, CScript([b'a']))]
tx2a_hex = txToHex(tx2a)
- tx2a_txid = self.nodes[0].sendrawtransaction(tx2a_hex, True)
+ self.nodes[0].sendrawtransaction(tx2a_hex, True)
# Lower fee, but we'll prioritise it
tx2b = CTransaction()
diff --git a/test/functional/resendwallettransactions.py b/test/functional/resendwallettransactions.py
index 5059aa106e..d6ba591391 100755
--- a/test/functional/resendwallettransactions.py
+++ b/test/functional/resendwallettransactions.py
@@ -8,11 +8,9 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_jsonrpc
class ResendWalletTransactionsTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.extra_args = [['--walletbroadcast=false']]
+ def set_test_params(self):
self.num_nodes = 1
+ self.extra_args = [['--walletbroadcast=false']]
def run_test(self):
# Should raise RPC_WALLET_ERROR (-4) if walletbroadcast is disabled.
@@ -20,7 +18,7 @@ class ResendWalletTransactionsTest(BitcoinTestFramework):
# Should return an empty array if there aren't unconfirmed wallet transactions.
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir)
+ self.start_node(0, extra_args=[])
assert_equal(self.nodes[0].resendwallettransactions(), [])
# Should return an array with the unconfirmed wallet transaction.
diff --git a/test/functional/rest.py b/test/functional/rest.py
index a69dbb5013..437111a4d7 100755
--- a/test/functional/rest.py
+++ b/test/functional/rest.py
@@ -43,8 +43,7 @@ def http_post_call(host, port, path, requestdata = '', response_object = 0):
class RESTTest (BitcoinTestFramework):
FORMAT_SEPARATOR = "."
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
diff --git a/test/functional/rpcbind_test.py b/test/functional/rpcbind_test.py
index 951685aa76..0cf64beebd 100755
--- a/test/functional/rpcbind_test.py
+++ b/test/functional/rpcbind_test.py
@@ -11,19 +11,13 @@ from test_framework.test_framework import BitcoinTestFramework, SkipTest
from test_framework.util import *
from test_framework.netutil import *
-
class RPCBindTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def setup_network(self):
- pass
-
- def setup_nodes(self):
- pass
+ self.add_nodes(self.num_nodes, None)
def run_bind_test(self, allow_ips, connect_to, addresses, expected):
'''
@@ -31,13 +25,15 @@ class RPCBindTest(BitcoinTestFramework):
then try to connect, and check if the set of bound addresses
matches the expected set.
'''
+ self.log.info("Bind test for %s" % str(addresses))
expected = [(addr_to_hex(addr), port) for (addr, port) in expected]
base_args = ['-disablewallet', '-nolisten']
if allow_ips:
base_args += ['-rpcallowip=' + x for x in allow_ips]
binds = ['-rpcbind='+addr for addr in addresses]
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, [base_args + binds], connect_to)
- pid = self.bitcoind_processes[0].pid
+ self.nodes[0].rpchost = connect_to
+ self.start_node(0, base_args + binds)
+ pid = self.nodes[0].process.pid
assert_equal(set(get_bind_addrs(pid)), set(expected))
self.stop_nodes()
@@ -46,10 +42,12 @@ class RPCBindTest(BitcoinTestFramework):
Start a node with rpcallow IP, and request getnetworkinfo
at a non-localhost IP.
'''
+ self.log.info("Allow IP test for %s:%d" % (rpchost, rpcport))
base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, [base_args])
+ self.nodes[0].rpchost = None
+ self.start_nodes([base_args])
# connect to node through non-loopback interface
- node = get_rpc_proxy(rpc_url(get_datadir_path(self.options.tmpdir, 0), 0, "%s:%d" % (rpchost, rpcport)), 0)
+ node = get_rpc_proxy(rpc_url(get_datadir_path(self.options.tmpdir, 0), 0, "%s:%d" % (rpchost, rpcport)), 0, coveragedir=self.options.coveragedir)
node.getnetworkinfo()
self.stop_nodes()
diff --git a/test/functional/rpcnamedargs.py b/test/functional/rpcnamedargs.py
index 3b286000a1..da61cc66e6 100755
--- a/test/functional/rpcnamedargs.py
+++ b/test/functional/rpcnamedargs.py
@@ -10,15 +10,8 @@ from test_framework.util import (
assert_raises_jsonrpc,
)
-
class NamedArgumentTest(BitcoinTestFramework):
- """
- Test named arguments on RPC calls.
- """
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = False
+ def set_test_params(self):
self.num_nodes = 1
def run_test(self):
diff --git a/test/functional/segwit.py b/test/functional/segwit.py
index 51eaa34a54..609c592ed3 100755
--- a/test/functional/segwit.py
+++ b/test/functional/segwit.py
@@ -12,7 +12,6 @@ from test_framework.script import CScript, OP_HASH160, OP_CHECKSIG, OP_0, hash16
from io import BytesIO
NODE_0 = 0
-NODE_1 = 1
NODE_2 = 2
WIT_V0 = 0
WIT_V1 = 1
@@ -75,9 +74,7 @@ def find_unspent(node, min_value):
return utxo
class SegWitTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [["-walletprematurewitness", "-rpcserialversion=0"],
diff --git a/test/functional/sendheaders.py b/test/functional/sendheaders.py
index e47e07fb86..fe577dc20a 100755
--- a/test/functional/sendheaders.py
+++ b/test/functional/sendheaders.py
@@ -128,7 +128,7 @@ class TestNode(NodeConnCB):
expect_headers = headers if headers != None else []
expect_inv = inv if inv != None else []
test_function = lambda: self.block_announced
- assert(wait_until(test_function, timeout=60))
+ wait_until(test_function, timeout=60, lock=mininode_lock)
with mininode_lock:
self.block_announced = False
@@ -155,12 +155,12 @@ class TestNode(NodeConnCB):
return
test_function = lambda: "getdata" in self.last_message and [x.hash for x in self.last_message["getdata"].inv] == hash_list
- assert(wait_until(test_function, timeout=timeout))
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
return
def wait_for_block_announcement(self, block_hash, timeout=60):
test_function = lambda: self.last_blockhash_announced == block_hash
- assert(wait_until(test_function, timeout=timeout))
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
return
def send_header_for_blocks(self, new_blocks):
@@ -174,8 +174,7 @@ class TestNode(NodeConnCB):
self.send_message(getblocks_message)
class SendHeadersTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
diff --git a/test/functional/signmessages.py b/test/functional/signmessages.py
index 42f6a9daaf..52ba6a5ad7 100755
--- a/test/functional/signmessages.py
+++ b/test/functional/signmessages.py
@@ -5,31 +5,34 @@
"""Test RPC commands for signing and verifying messages."""
from test_framework.test_framework import BitcoinTestFramework
+from test_framework.util import assert_equal
class SignMessagesTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
message = 'This is just a test message'
- # Test the signing with a privkey
- privKey = 'cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N'
+ self.log.info('test signing with priv_key')
+ priv_key = 'cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N'
address = 'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB'
- signature = self.nodes[0].signmessagewithprivkey(privKey, message)
-
- # Verify the message
+ expected_signature = 'INbVnW4e6PeRmsv2Qgu8NuopvrVjkcxob+sX8OcZG0SALhWybUjzMLPdAsXI46YZGb0KQTRii+wWIQzRpG/U+S0='
+ signature = self.nodes[0].signmessagewithprivkey(priv_key, message)
+ assert_equal(expected_signature, signature)
assert(self.nodes[0].verifymessage(address, signature, message))
- # Test the signing with an address with wallet
+ self.log.info('test signing with an address with wallet')
address = self.nodes[0].getnewaddress()
signature = self.nodes[0].signmessage(address, message)
-
- # Verify the message
assert(self.nodes[0].verifymessage(address, signature, message))
+ self.log.info('test verifying with another address should not work')
+ other_address = self.nodes[0].getnewaddress()
+ other_signature = self.nodes[0].signmessage(other_address, message)
+ assert(not self.nodes[0].verifymessage(other_address, signature, message))
+ assert(not self.nodes[0].verifymessage(address, other_signature, message))
+
if __name__ == '__main__':
SignMessagesTest().main()
diff --git a/test/functional/signrawtransactions.py b/test/functional/signrawtransactions.py
index 415727268a..b47ef93955 100755
--- a/test/functional/signrawtransactions.py
+++ b/test/functional/signrawtransactions.py
@@ -9,8 +9,7 @@ from test_framework.util import *
class SignRawTransactionsTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
diff --git a/test/functional/smartfees.py b/test/functional/smartfees.py
index bc42a319df..76632fc578 100755
--- a/test/functional/smartfees.py
+++ b/test/functional/smartfees.py
@@ -141,11 +141,8 @@ def check_estimates(node, fees_seen, max_invalid, print_estimates = True):
class EstimateFeeTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 3
- self.setup_clean_chain = False
def setup_network(self):
"""
@@ -153,57 +150,16 @@ class EstimateFeeTest(BitcoinTestFramework):
But first we need to use one node to create a lot of outputs
which we will use to generate our transactions.
"""
- self.nodes = []
+ self.add_nodes(3, extra_args=[["-maxorphantx=1000", "-whitelist=127.0.0.1"],
+ ["-blockmaxsize=17000", "-maxorphantx=1000"],
+ ["-blockmaxsize=8000", "-maxorphantx=1000"]])
# Use node0 to mine blocks for input splitting
- self.nodes.append(self.start_node(0, self.options.tmpdir, ["-maxorphantx=1000",
- "-whitelist=127.0.0.1"]))
-
- self.log.info("This test is time consuming, please be patient")
- self.log.info("Splitting inputs so we can generate tx's")
- self.txouts = []
- self.txouts2 = []
- # Split a coinbase into two transaction puzzle outputs
- split_inputs(self.nodes[0], self.nodes[0].listunspent(0), self.txouts, True)
-
- # Mine
- while (len(self.nodes[0].getrawmempool()) > 0):
- self.nodes[0].generate(1)
-
- # Repeatedly split those 2 outputs, doubling twice for each rep
- # Use txouts to monitor the available utxo, since these won't be tracked in wallet
- reps = 0
- while (reps < 5):
- #Double txouts to txouts2
- while (len(self.txouts)>0):
- split_inputs(self.nodes[0], self.txouts, self.txouts2)
- while (len(self.nodes[0].getrawmempool()) > 0):
- self.nodes[0].generate(1)
- #Double txouts2 to txouts
- while (len(self.txouts2)>0):
- split_inputs(self.nodes[0], self.txouts2, self.txouts)
- while (len(self.nodes[0].getrawmempool()) > 0):
- self.nodes[0].generate(1)
- reps += 1
- self.log.info("Finished splitting")
-
- # Now we can connect the other nodes, didn't want to connect them earlier
- # so the estimates would not be affected by the splitting transactions
# Node1 mines small blocks but that are bigger than the expected transaction rate.
# NOTE: the CreateNewBlock code starts counting block size at 1,000 bytes,
# (17k is room enough for 110 or so transactions)
- self.nodes.append(self.start_node(1, self.options.tmpdir,
- ["-blockmaxsize=17000", "-maxorphantx=1000"]))
- connect_nodes(self.nodes[1], 0)
-
# Node2 is a stingy miner, that
# produces too small blocks (room for only 55 or so transactions)
- node2args = ["-blockmaxsize=8000", "-maxorphantx=1000"]
- self.nodes.append(self.start_node(2, self.options.tmpdir, node2args))
- connect_nodes(self.nodes[0], 2)
- connect_nodes(self.nodes[2], 1)
-
- self.sync_all()
def transact_and_mine(self, numblocks, mining_node):
min_fee = Decimal("0.00001")
@@ -232,9 +188,51 @@ class EstimateFeeTest(BitcoinTestFramework):
self.memutxo = newmem
def run_test(self):
+ self.log.info("This test is time consuming, please be patient")
+ self.log.info("Splitting inputs so we can generate tx's")
+
# Make log handler available to helper functions
global log
log = self.log
+
+ # Start node0
+ self.start_node(0)
+ self.txouts = []
+ self.txouts2 = []
+ # Split a coinbase into two transaction puzzle outputs
+ split_inputs(self.nodes[0], self.nodes[0].listunspent(0), self.txouts, True)
+
+ # Mine
+ while (len(self.nodes[0].getrawmempool()) > 0):
+ self.nodes[0].generate(1)
+
+ # Repeatedly split those 2 outputs, doubling twice for each rep
+ # Use txouts to monitor the available utxo, since these won't be tracked in wallet
+ reps = 0
+ while (reps < 5):
+ #Double txouts to txouts2
+ while (len(self.txouts)>0):
+ split_inputs(self.nodes[0], self.txouts, self.txouts2)
+ while (len(self.nodes[0].getrawmempool()) > 0):
+ self.nodes[0].generate(1)
+ #Double txouts2 to txouts
+ while (len(self.txouts2)>0):
+ split_inputs(self.nodes[0], self.txouts2, self.txouts)
+ while (len(self.nodes[0].getrawmempool()) > 0):
+ self.nodes[0].generate(1)
+ reps += 1
+ self.log.info("Finished splitting")
+
+ # Now we can connect the other nodes, didn't want to connect them earlier
+ # so the estimates would not be affected by the splitting transactions
+ self.start_node(1)
+ self.start_node(2)
+ connect_nodes(self.nodes[1], 0)
+ connect_nodes(self.nodes[0], 2)
+ connect_nodes(self.nodes[2], 1)
+
+ self.sync_all()
+
self.fees_per_kb = []
self.memutxo = []
self.confutxo = self.txouts # Start with the set of confirmed txouts after splitting
diff --git a/test/functional/test_framework/address.py b/test/functional/test_framework/address.py
index 96bebe1ea1..180dac197e 100644
--- a/test/functional/test_framework/address.py
+++ b/test/functional/test_framework/address.py
@@ -44,16 +44,6 @@ def script_to_p2sh(script, main = False):
script = check_script(script)
return scripthash_to_p2sh(hash160(script), main)
-def key_to_p2sh_p2wpkh(key, main = False):
- key = check_key(key)
- p2shscript = CScript([OP_0, hash160(key)])
- return script_to_p2sh(p2shscript, main)
-
-def script_to_p2sh_p2wsh(script, main = False):
- script = check_script(script)
- p2shscript = CScript([OP_0, sha256(script)])
- return script_to_p2sh(p2shscript, main)
-
def check_key(key):
if (type(key) is str):
key = hex_str_to_bytes(key) # Assuming this is hex string
diff --git a/test/functional/test_framework/bignum.py b/test/functional/test_framework/bignum.py
index 024611da6e..db5ccd62c2 100644
--- a/test/functional/test_framework/bignum.py
+++ b/test/functional/test_framework/bignum.py
@@ -26,12 +26,6 @@ def bn2bin(v):
i -= 1
return s
-def bin2bn(s):
- l = 0
- for ch in s:
- l = (l << 8) | ch
- return l
-
def bn2mpi(v):
have_ext = False
if v.bit_length() > 0:
@@ -54,30 +48,6 @@ def bn2mpi(v):
v_bin[0] |= 0x80
return s + ext + v_bin
-def mpi2bn(s):
- if len(s) < 4:
- return None
- s_size = bytes(s[:4])
- v_len = struct.unpack(b">I", s_size)[0]
- if len(s) != (v_len + 4):
- return None
- if v_len == 0:
- return 0
-
- v_str = bytearray(s[4:])
- neg = False
- i = v_str[0]
- if i & 0x80:
- neg = True
- i &= ~0x80
- v_str[0] = i
-
- v = bin2bn(v_str)
-
- if neg:
- return -v
- return v
-
# bitcoin-specific little endian format, with implicit size
def mpi2vch(s):
r = s[4:] # strip size
@@ -86,12 +56,3 @@ def mpi2vch(s):
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
-
-def vch2mpi(s):
- r = struct.pack(b">I", len(s)) # size
- r += s[::-1] # reverse string, converting LE->BE
- return r
-
-def vch2bn(s):
- return mpi2bn(vch2mpi(s))
-
diff --git a/test/functional/test_framework/blockstore.py b/test/functional/test_framework/blockstore.py
index 4cfd682bb5..4b2170a03f 100644
--- a/test/functional/test_framework/blockstore.py
+++ b/test/functional/test_framework/blockstore.py
@@ -143,16 +143,6 @@ class TxStore(object):
return None
return value
- def get_transaction(self, txhash):
- ret = None
- serialized_tx = self.get(txhash)
- if serialized_tx is not None:
- f = BytesIO(serialized_tx)
- ret = CTransaction()
- ret.deserialize(f)
- ret.calc_sha256()
- return ret
-
def add_transaction(self, tx):
tx.calc_sha256()
try:
diff --git a/test/functional/test_framework/comptool.py b/test/functional/test_framework/comptool.py
index 9f062865a3..bfbc0c3b03 100755
--- a/test/functional/test_framework/comptool.py
+++ b/test/functional/test_framework/comptool.py
@@ -19,7 +19,7 @@ TestNode behaves as follows:
from .mininode import *
from .blockstore import BlockStore, TxStore
-from .util import p2p_port
+from .util import p2p_port, wait_until
import logging
@@ -189,7 +189,7 @@ class TestManager(object):
def wait_for_disconnections(self):
def disconnected():
return all(node.closed for node in self.test_nodes)
- return wait_until(disconnected, timeout=10)
+ wait_until(disconnected, timeout=10, lock=mininode_lock)
def wait_for_verack(self):
return all(node.wait_for_verack() for node in self.test_nodes)
@@ -197,7 +197,7 @@ class TestManager(object):
def wait_for_pings(self, counter):
def received_pongs():
return all(node.received_ping_response(counter) for node in self.test_nodes)
- return wait_until(received_pongs)
+ wait_until(received_pongs, lock=mininode_lock)
# sync_blocks: Wait for all connections to request the blockhash given
# then send get_headers to find out the tip of each node, and synchronize
@@ -210,8 +210,7 @@ class TestManager(object):
)
# --> error if not requested
- if not wait_until(blocks_requested, attempts=20*num_blocks):
- raise AssertionError("Not all nodes requested block")
+ wait_until(blocks_requested, attempts=20*num_blocks, lock=mininode_lock)
# Send getheaders message
[ c.cb.send_getheaders() for c in self.connections ]
@@ -231,8 +230,7 @@ class TestManager(object):
)
# --> error if not requested
- if not wait_until(transaction_requested, attempts=20*num_events):
- raise AssertionError("Not all nodes requested transaction")
+ wait_until(transaction_requested, attempts=20*num_events, lock=mininode_lock)
# Get the mempool
[ c.cb.send_mempool() for c in self.connections ]
diff --git a/test/functional/test_framework/mininode.py b/test/functional/test_framework/mininode.py
index a4d85501e7..2607b9b07c 100755
--- a/test/functional/test_framework/mininode.py
+++ b/test/functional/test_framework/mininode.py
@@ -35,7 +35,7 @@ import time
from threading import RLock, Thread
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, bytes_to_hex_str, wait_until
BIP0031_VERSION = 60000
MY_VERSION = 70014 # past bip-31 for ping/pong
@@ -48,8 +48,8 @@ MAX_BLOCK_BASE_SIZE = 1000000
COIN = 100000000 # 1 btc in satoshis
NODE_NETWORK = (1 << 0)
-NODE_GETUTXO = (1 << 1)
-NODE_BLOOM = (1 << 2)
+# NODE_GETUTXO = (1 << 1)
+# NODE_BLOOM = (1 << 2)
NODE_WITNESS = (1 << 3)
NODE_UNSUPPORTED_SERVICE_BIT_5 = (1 << 5)
NODE_UNSUPPORTED_SERVICE_BIT_7 = (1 << 7)
@@ -1358,23 +1358,6 @@ class msg_reject(object):
return "msg_reject: %s %d %s [%064x]" \
% (self.message, self.code, self.reason, self.data)
-# Helper function
-def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf')):
- if attempts == float('inf') and timeout == float('inf'):
- timeout = 60
- attempt = 0
- elapsed = 0
-
- while attempt < attempts and elapsed < timeout:
- with mininode_lock:
- if predicate():
- return True
- attempt += 1
- elapsed += 0.05
- time.sleep(0.05)
-
- return False
-
class msg_feefilter(object):
command = b"feefilter"
@@ -1496,9 +1479,6 @@ class NodeConnCB(object):
# before acquiring the global lock and delivering the next message.
self.deliver_sleep_time = None
- # Remember the services our peer has advertised
- self.peer_services = None
-
# Message receiving methods
def deliver(self, conn, message):
@@ -1523,10 +1503,6 @@ class NodeConnCB(object):
print("ERROR delivering %s (%s)" % (repr(message),
sys.exc_info()[0]))
- def set_deliver_sleep_time(self, value):
- with mininode_lock:
- self.deliver_sleep_time = value
-
def get_deliver_sleep_time(self):
with mininode_lock:
return self.deliver_sleep_time
@@ -1591,21 +1567,21 @@ class NodeConnCB(object):
def wait_for_disconnect(self, timeout=60):
test_function = lambda: not self.connected
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
# Message receiving helper methods
def wait_for_block(self, blockhash, timeout=60):
test_function = lambda: self.last_message.get("block") and self.last_message["block"].block.rehash() == blockhash
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
def wait_for_getdata(self, timeout=60):
test_function = lambda: self.last_message.get("getdata")
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
def wait_for_getheaders(self, timeout=60):
test_function = lambda: self.last_message.get("getheaders")
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
def wait_for_inv(self, expected_inv, timeout=60):
"""Waits for an INV message and checks that the first inv object in the message was as expected."""
@@ -1614,11 +1590,11 @@ class NodeConnCB(object):
test_function = lambda: self.last_message.get("inv") and \
self.last_message["inv"].inv[0].type == expected_inv[0].type and \
self.last_message["inv"].inv[0].hash == expected_inv[0].hash
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
def wait_for_verack(self, timeout=60):
test_function = lambda: self.message_count["verack"]
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
# Message sending helper functions
@@ -1636,7 +1612,7 @@ class NodeConnCB(object):
def sync_with_ping(self, timeout=60):
self.send_message(msg_ping(nonce=self.ping_counter))
test_function = lambda: self.last_message.get("pong") and self.last_message["pong"].nonce == self.ping_counter
- assert wait_until(test_function, timeout=timeout)
+ wait_until(test_function, timeout=timeout, lock=mininode_lock)
self.ping_counter += 1
return True
diff --git a/test/functional/test_framework/netutil.py b/test/functional/test_framework/netutil.py
index 45d8e22d22..e5d415788f 100644
--- a/test/functional/test_framework/netutil.py
+++ b/test/functional/test_framework/netutil.py
@@ -15,17 +15,17 @@ import array
import os
from binascii import unhexlify, hexlify
-STATE_ESTABLISHED = '01'
-STATE_SYN_SENT = '02'
-STATE_SYN_RECV = '03'
-STATE_FIN_WAIT1 = '04'
-STATE_FIN_WAIT2 = '05'
-STATE_TIME_WAIT = '06'
-STATE_CLOSE = '07'
-STATE_CLOSE_WAIT = '08'
-STATE_LAST_ACK = '09'
+# STATE_ESTABLISHED = '01'
+# STATE_SYN_SENT = '02'
+# STATE_SYN_RECV = '03'
+# STATE_FIN_WAIT1 = '04'
+# STATE_FIN_WAIT2 = '05'
+# STATE_TIME_WAIT = '06'
+# STATE_CLOSE = '07'
+# STATE_CLOSE_WAIT = '08'
+# STATE_LAST_ACK = '09'
STATE_LISTEN = '0A'
-STATE_CLOSING = '0B'
+# STATE_CLOSING = '0B'
def get_socket_inodes(pid):
'''
diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py
index 3d9572788e..8f5339a02a 100644
--- a/test/functional/test_framework/script.py
+++ b/test/functional/test_framework/script.py
@@ -23,9 +23,7 @@ import struct
from .bignum import bn2vch
-MAX_SCRIPT_SIZE = 10000
MAX_SCRIPT_ELEMENT_SIZE = 520
-MAX_SCRIPT_OPCODES = 201
OPCODE_NAMES = {}
@@ -242,131 +240,6 @@ OP_PUBKEY = CScriptOp(0xfe)
OP_INVALIDOPCODE = CScriptOp(0xff)
-VALID_OPCODES = {
- OP_1NEGATE,
- OP_RESERVED,
- OP_1,
- OP_2,
- OP_3,
- OP_4,
- OP_5,
- OP_6,
- OP_7,
- OP_8,
- OP_9,
- OP_10,
- OP_11,
- OP_12,
- OP_13,
- OP_14,
- OP_15,
- OP_16,
-
- OP_NOP,
- OP_VER,
- OP_IF,
- OP_NOTIF,
- OP_VERIF,
- OP_VERNOTIF,
- OP_ELSE,
- OP_ENDIF,
- OP_VERIFY,
- OP_RETURN,
-
- OP_TOALTSTACK,
- OP_FROMALTSTACK,
- OP_2DROP,
- OP_2DUP,
- OP_3DUP,
- OP_2OVER,
- OP_2ROT,
- OP_2SWAP,
- OP_IFDUP,
- OP_DEPTH,
- OP_DROP,
- OP_DUP,
- OP_NIP,
- OP_OVER,
- OP_PICK,
- OP_ROLL,
- OP_ROT,
- OP_SWAP,
- OP_TUCK,
-
- OP_CAT,
- OP_SUBSTR,
- OP_LEFT,
- OP_RIGHT,
- OP_SIZE,
-
- OP_INVERT,
- OP_AND,
- OP_OR,
- OP_XOR,
- OP_EQUAL,
- OP_EQUALVERIFY,
- OP_RESERVED1,
- OP_RESERVED2,
-
- OP_1ADD,
- OP_1SUB,
- OP_2MUL,
- OP_2DIV,
- OP_NEGATE,
- OP_ABS,
- OP_NOT,
- OP_0NOTEQUAL,
-
- OP_ADD,
- OP_SUB,
- OP_MUL,
- OP_DIV,
- OP_MOD,
- OP_LSHIFT,
- OP_RSHIFT,
-
- OP_BOOLAND,
- OP_BOOLOR,
- OP_NUMEQUAL,
- OP_NUMEQUALVERIFY,
- OP_NUMNOTEQUAL,
- OP_LESSTHAN,
- OP_GREATERTHAN,
- OP_LESSTHANOREQUAL,
- OP_GREATERTHANOREQUAL,
- OP_MIN,
- OP_MAX,
-
- OP_WITHIN,
-
- OP_RIPEMD160,
- OP_SHA1,
- OP_SHA256,
- OP_HASH160,
- OP_HASH256,
- OP_CODESEPARATOR,
- OP_CHECKSIG,
- OP_CHECKSIGVERIFY,
- OP_CHECKMULTISIG,
- OP_CHECKMULTISIGVERIFY,
-
- OP_NOP1,
- OP_CHECKLOCKTIMEVERIFY,
- OP_CHECKSEQUENCEVERIFY,
- OP_NOP4,
- OP_NOP5,
- OP_NOP6,
- OP_NOP7,
- OP_NOP8,
- OP_NOP9,
- OP_NOP10,
-
- OP_SMALLINTEGER,
- OP_PUBKEYS,
- OP_PUBKEYHASH,
- OP_PUBKEY,
-}
-
OPCODE_NAMES.update({
OP_0 : 'OP_0',
OP_PUSHDATA1 : 'OP_PUSHDATA1',
@@ -486,124 +359,6 @@ OPCODE_NAMES.update({
OP_INVALIDOPCODE : 'OP_INVALIDOPCODE',
})
-OPCODES_BY_NAME = {
- 'OP_0' : OP_0,
- 'OP_PUSHDATA1' : OP_PUSHDATA1,
- 'OP_PUSHDATA2' : OP_PUSHDATA2,
- 'OP_PUSHDATA4' : OP_PUSHDATA4,
- 'OP_1NEGATE' : OP_1NEGATE,
- 'OP_RESERVED' : OP_RESERVED,
- 'OP_1' : OP_1,
- 'OP_2' : OP_2,
- 'OP_3' : OP_3,
- 'OP_4' : OP_4,
- 'OP_5' : OP_5,
- 'OP_6' : OP_6,
- 'OP_7' : OP_7,
- 'OP_8' : OP_8,
- 'OP_9' : OP_9,
- 'OP_10' : OP_10,
- 'OP_11' : OP_11,
- 'OP_12' : OP_12,
- 'OP_13' : OP_13,
- 'OP_14' : OP_14,
- 'OP_15' : OP_15,
- 'OP_16' : OP_16,
- 'OP_NOP' : OP_NOP,
- 'OP_VER' : OP_VER,
- 'OP_IF' : OP_IF,
- 'OP_NOTIF' : OP_NOTIF,
- 'OP_VERIF' : OP_VERIF,
- 'OP_VERNOTIF' : OP_VERNOTIF,
- 'OP_ELSE' : OP_ELSE,
- 'OP_ENDIF' : OP_ENDIF,
- 'OP_VERIFY' : OP_VERIFY,
- 'OP_RETURN' : OP_RETURN,
- 'OP_TOALTSTACK' : OP_TOALTSTACK,
- 'OP_FROMALTSTACK' : OP_FROMALTSTACK,
- 'OP_2DROP' : OP_2DROP,
- 'OP_2DUP' : OP_2DUP,
- 'OP_3DUP' : OP_3DUP,
- 'OP_2OVER' : OP_2OVER,
- 'OP_2ROT' : OP_2ROT,
- 'OP_2SWAP' : OP_2SWAP,
- 'OP_IFDUP' : OP_IFDUP,
- 'OP_DEPTH' : OP_DEPTH,
- 'OP_DROP' : OP_DROP,
- 'OP_DUP' : OP_DUP,
- 'OP_NIP' : OP_NIP,
- 'OP_OVER' : OP_OVER,
- 'OP_PICK' : OP_PICK,
- 'OP_ROLL' : OP_ROLL,
- 'OP_ROT' : OP_ROT,
- 'OP_SWAP' : OP_SWAP,
- 'OP_TUCK' : OP_TUCK,
- 'OP_CAT' : OP_CAT,
- 'OP_SUBSTR' : OP_SUBSTR,
- 'OP_LEFT' : OP_LEFT,
- 'OP_RIGHT' : OP_RIGHT,
- 'OP_SIZE' : OP_SIZE,
- 'OP_INVERT' : OP_INVERT,
- 'OP_AND' : OP_AND,
- 'OP_OR' : OP_OR,
- 'OP_XOR' : OP_XOR,
- 'OP_EQUAL' : OP_EQUAL,
- 'OP_EQUALVERIFY' : OP_EQUALVERIFY,
- 'OP_RESERVED1' : OP_RESERVED1,
- 'OP_RESERVED2' : OP_RESERVED2,
- 'OP_1ADD' : OP_1ADD,
- 'OP_1SUB' : OP_1SUB,
- 'OP_2MUL' : OP_2MUL,
- 'OP_2DIV' : OP_2DIV,
- 'OP_NEGATE' : OP_NEGATE,
- 'OP_ABS' : OP_ABS,
- 'OP_NOT' : OP_NOT,
- 'OP_0NOTEQUAL' : OP_0NOTEQUAL,
- 'OP_ADD' : OP_ADD,
- 'OP_SUB' : OP_SUB,
- 'OP_MUL' : OP_MUL,
- 'OP_DIV' : OP_DIV,
- 'OP_MOD' : OP_MOD,
- 'OP_LSHIFT' : OP_LSHIFT,
- 'OP_RSHIFT' : OP_RSHIFT,
- 'OP_BOOLAND' : OP_BOOLAND,
- 'OP_BOOLOR' : OP_BOOLOR,
- 'OP_NUMEQUAL' : OP_NUMEQUAL,
- 'OP_NUMEQUALVERIFY' : OP_NUMEQUALVERIFY,
- 'OP_NUMNOTEQUAL' : OP_NUMNOTEQUAL,
- 'OP_LESSTHAN' : OP_LESSTHAN,
- 'OP_GREATERTHAN' : OP_GREATERTHAN,
- 'OP_LESSTHANOREQUAL' : OP_LESSTHANOREQUAL,
- 'OP_GREATERTHANOREQUAL' : OP_GREATERTHANOREQUAL,
- 'OP_MIN' : OP_MIN,
- 'OP_MAX' : OP_MAX,
- 'OP_WITHIN' : OP_WITHIN,
- 'OP_RIPEMD160' : OP_RIPEMD160,
- 'OP_SHA1' : OP_SHA1,
- 'OP_SHA256' : OP_SHA256,
- 'OP_HASH160' : OP_HASH160,
- 'OP_HASH256' : OP_HASH256,
- 'OP_CODESEPARATOR' : OP_CODESEPARATOR,
- 'OP_CHECKSIG' : OP_CHECKSIG,
- 'OP_CHECKSIGVERIFY' : OP_CHECKSIGVERIFY,
- 'OP_CHECKMULTISIG' : OP_CHECKMULTISIG,
- 'OP_CHECKMULTISIGVERIFY' : OP_CHECKMULTISIGVERIFY,
- 'OP_NOP1' : OP_NOP1,
- 'OP_CHECKLOCKTIMEVERIFY' : OP_CHECKLOCKTIMEVERIFY,
- 'OP_CHECKSEQUENCEVERIFY' : OP_CHECKSEQUENCEVERIFY,
- 'OP_NOP4' : OP_NOP4,
- 'OP_NOP5' : OP_NOP5,
- 'OP_NOP6' : OP_NOP6,
- 'OP_NOP7' : OP_NOP7,
- 'OP_NOP8' : OP_NOP8,
- 'OP_NOP9' : OP_NOP9,
- 'OP_NOP10' : OP_NOP10,
- 'OP_SMALLINTEGER' : OP_SMALLINTEGER,
- 'OP_PUBKEYS' : OP_PUBKEYS,
- 'OP_PUBKEYHASH' : OP_PUBKEYHASH,
- 'OP_PUBKEY' : OP_PUBKEY,
-}
-
class CScriptInvalidError(Exception):
"""Base class for CScript exceptions"""
pass
diff --git a/test/functional/test_framework/socks5.py b/test/functional/test_framework/socks5.py
index a08b03ed24..0070844168 100644
--- a/test/functional/test_framework/socks5.py
+++ b/test/functional/test_framework/socks5.py
@@ -91,7 +91,7 @@ class Socks5Connection(object):
self.conn.sendall(bytearray([0x01, 0x00]))
# Read connect request
- (ver,cmd,rsv,atyp) = recvall(self.conn, 4)
+ ver, cmd, _, atyp = recvall(self.conn, 4)
if ver != 0x05:
raise IOError('Invalid socks version %i in connect request' % ver)
if cmd != Command.CONNECT:
diff --git a/test/functional/test_framework/test_framework.py b/test/functional/test_framework/test_framework.py
index e562d11938..103651f175 100755
--- a/test/functional/test_framework/test_framework.py
+++ b/test/functional/test_framework/test_framework.py
@@ -5,15 +5,12 @@
"""Base class for RPC testing."""
from collections import deque
-import errno
from enum import Enum
-import http.client
import logging
import optparse
import os
import pdb
import shutil
-import subprocess
import sys
import tempfile
import time
@@ -21,6 +18,7 @@ import traceback
from .authproxy import JSONRPCException
from . import coverage
+from .test_node import TestNode
from .util import (
MAX_NODES,
PortSeed,
@@ -28,12 +26,9 @@ from .util import (
check_json_precision,
connect_nodes_bi,
disconnect_nodes,
- get_rpc_proxy,
initialize_datadir,
- get_datadir_path,
log_filename,
p2p_port,
- rpc_url,
set_node_times,
sync_blocks,
sync_mempools,
@@ -53,58 +48,30 @@ BITCOIND_PROC_WAIT_TIMEOUT = 60
class BitcoinTestFramework(object):
"""Base class for a bitcoin test script.
- Individual bitcoin test scripts should subclass this class and override the following methods:
+ Individual bitcoin test scripts should subclass this class and override the set_test_params() and run_test() methods.
+
+ Individual tests can also override the following methods to customize the test setup:
- - __init__()
- add_options()
- setup_chain()
- setup_network()
- - run_test()
+ - setup_nodes()
- The main() method should not be overridden.
+ The __init__() and main() methods should not be overridden.
This class also contains various public and private helper methods."""
- # Methods to override in subclass test scripts.
def __init__(self):
- self.num_nodes = 4
+ """Sets test framework defaults. Do not override this method. Instead, override the set_test_params() method"""
self.setup_clean_chain = False
self.nodes = []
- self.bitcoind_processes = {}
self.mocktime = 0
+ self.set_test_params()
- def add_options(self, parser):
- pass
-
- def setup_chain(self):
- self.log.info("Initializing test directory " + self.options.tmpdir)
- if self.setup_clean_chain:
- self._initialize_chain_clean(self.options.tmpdir, self.num_nodes)
- else:
- self._initialize_chain(self.options.tmpdir, self.num_nodes, self.options.cachedir)
-
- def setup_network(self):
- self.setup_nodes()
-
- # Connect the nodes as a "chain". This allows us
- # to split the network between nodes 1 and 2 to get
- # two halves that can work on competing chains.
- for i in range(self.num_nodes - 1):
- connect_nodes_bi(self.nodes, i, i + 1)
- self.sync_all()
-
- def setup_nodes(self):
- extra_args = None
- if hasattr(self, "extra_args"):
- extra_args = self.extra_args
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
-
- def run_test(self):
- raise NotImplementedError
-
- # Main function. This should not be overridden by the subclass test scripts.
+ assert hasattr(self, "num_nodes"), "Test must set self.num_nodes in set_test_params()"
def main(self):
+ """Main function. This should not be overridden by the subclass test scripts."""
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
@@ -208,77 +175,117 @@ class BitcoinTestFramework(object):
logging.shutdown()
sys.exit(TEST_EXIT_FAILED)
- # Public helper methods. These can be accessed by the subclass test scripts.
+ # Methods to override in subclass test scripts.
+ def set_test_params(self):
+ """Tests must this method to change default values for number of nodes, topology, etc"""
+ raise NotImplementedError
- def start_node(self, i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None, stderr=None):
- """Start a bitcoind and return RPC connection to it"""
+ def add_options(self, parser):
+ """Override this method to add command-line options to the test"""
+ pass
- datadir = os.path.join(dirname, "node" + str(i))
- if binary is None:
- binary = os.getenv("BITCOIND", "bitcoind")
- args = [binary, "-datadir=" + datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-logtimemicros", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", "-mocktime=" + str(self.mocktime), "-uacomment=testnode%d" % i]
- if extra_args is not None:
- args.extend(extra_args)
- self.bitcoind_processes[i] = subprocess.Popen(args, stderr=stderr)
- self.log.debug("initialize_chain: bitcoind started, waiting for RPC to come up")
- self._wait_for_bitcoind_start(self.bitcoind_processes[i], datadir, i, rpchost)
- self.log.debug("initialize_chain: RPC successfully started")
- proxy = get_rpc_proxy(rpc_url(datadir, i, rpchost), i, timeout=timewait)
+ def setup_chain(self):
+ """Override this method to customize blockchain setup"""
+ self.log.info("Initializing test directory " + self.options.tmpdir)
+ if self.setup_clean_chain:
+ self._initialize_chain_clean()
+ else:
+ self._initialize_chain()
- if self.options.coveragedir:
- coverage.write_all_rpc_commands(self.options.coveragedir, proxy)
+ def setup_network(self):
+ """Override this method to customize test network topology"""
+ self.setup_nodes()
- return proxy
+ # Connect the nodes as a "chain". This allows us
+ # to split the network between nodes 1 and 2 to get
+ # two halves that can work on competing chains.
+ for i in range(self.num_nodes - 1):
+ connect_nodes_bi(self.nodes, i, i + 1)
+ self.sync_all()
- def start_nodes(self, num_nodes, dirname, extra_args=None, rpchost=None, timewait=None, binary=None):
- """Start multiple bitcoinds, return RPC connections to them"""
+ def setup_nodes(self):
+ """Override this method to customize test node setup"""
+ extra_args = None
+ if hasattr(self, "extra_args"):
+ extra_args = self.extra_args
+ self.add_nodes(self.num_nodes, extra_args)
+ self.start_nodes()
+
+ def run_test(self):
+ """Tests must override this method to define test logic"""
+ raise NotImplementedError
+
+ # Public helper methods. These can be accessed by the subclass test scripts.
+
+ def add_nodes(self, num_nodes, extra_args=None, rpchost=None, timewait=None, binary=None):
+ """Instantiate TestNode objects"""
if extra_args is None:
- extra_args = [None] * num_nodes
+ extra_args = [[]] * num_nodes
if binary is None:
binary = [None] * num_nodes
assert_equal(len(extra_args), num_nodes)
assert_equal(len(binary), num_nodes)
- rpcs = []
+ for i in range(num_nodes):
+ self.nodes.append(TestNode(i, self.options.tmpdir, extra_args[i], rpchost, timewait=timewait, binary=binary[i], stderr=None, mocktime=self.mocktime, coverage_dir=self.options.coveragedir))
+
+ def start_node(self, i, extra_args=None, stderr=None):
+ """Start a bitcoind"""
+
+ node = self.nodes[i]
+
+ node.start(extra_args, stderr)
+ node.wait_for_rpc_connection()
+
+ if self.options.coveragedir is not None:
+ coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)
+
+ def start_nodes(self, extra_args=None):
+ """Start multiple bitcoinds"""
+
+ if extra_args is None:
+ extra_args = [None] * self.num_nodes
+ assert_equal(len(extra_args), self.num_nodes)
try:
- for i in range(num_nodes):
- rpcs.append(self.start_node(i, dirname, extra_args[i], rpchost, timewait=timewait, binary=binary[i]))
+ for i, node in enumerate(self.nodes):
+ node.start(extra_args[i])
+ for node in self.nodes:
+ node.wait_for_rpc_connection()
except:
# If one node failed to start, stop the others
- # TODO: abusing self.nodes in this way is a little hacky.
- # Eventually we should do a better job of tracking nodes
- self.nodes.extend(rpcs)
self.stop_nodes()
- self.nodes = []
raise
- return rpcs
+
+ if self.options.coveragedir is not None:
+ for node in self.nodes:
+ coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)
def stop_node(self, i):
"""Stop a bitcoind test node"""
-
- self.log.debug("Stopping node %d" % i)
- try:
- self.nodes[i].stop()
- except http.client.CannotSendRequest as e:
- self.log.exception("Unable to stop node")
- return_code = self.bitcoind_processes[i].wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
- del self.bitcoind_processes[i]
- assert_equal(return_code, 0)
+ self.nodes[i].stop_node()
+ while not self.nodes[i].is_node_stopped():
+ time.sleep(0.1)
def stop_nodes(self):
"""Stop multiple bitcoind test nodes"""
+ for node in self.nodes:
+ # Issue RPC to stop nodes
+ node.stop_node()
- for i in range(len(self.nodes)):
- self.stop_node(i)
- assert not self.bitcoind_processes.values() # All connections must be gone now
+ for node in self.nodes:
+ # Wait for nodes to stop
+ while not node.is_node_stopped():
+ time.sleep(0.1)
- def assert_start_raises_init_error(self, i, dirname, extra_args=None, expected_msg=None):
+ def assert_start_raises_init_error(self, i, extra_args=None, expected_msg=None):
with tempfile.SpooledTemporaryFile(max_size=2**16) as log_stderr:
try:
- self.start_node(i, dirname, extra_args, stderr=log_stderr)
+ self.start_node(i, extra_args, stderr=log_stderr)
self.stop_node(i)
except Exception as e:
assert 'bitcoind exited' in str(e) # node must have shutdown
+ self.nodes[i].running = False
+ self.nodes[i].process = None
if expected_msg is not None:
log_stderr.seek(0)
stderr = log_stderr.read().decode('utf-8')
@@ -292,7 +299,7 @@ class BitcoinTestFramework(object):
raise AssertionError(assert_msg)
def wait_for_node_exit(self, i, timeout):
- self.bitcoind_processes[i].wait(timeout)
+ self.nodes[i].process.wait(timeout)
def split_network(self):
"""
@@ -362,16 +369,16 @@ class BitcoinTestFramework(object):
rpc_handler.setLevel(logging.DEBUG)
rpc_logger.addHandler(rpc_handler)
- def _initialize_chain(self, test_dir, num_nodes, cachedir):
+ def _initialize_chain(self):
"""Initialize a pre-mined blockchain for use by the test.
Create a cache of a 200-block-long chain (with wallet) for MAX_NODES
Afterward, create num_nodes copies from the cache."""
- assert num_nodes <= MAX_NODES
+ assert self.num_nodes <= MAX_NODES
create_cache = False
for i in range(MAX_NODES):
- if not os.path.isdir(os.path.join(cachedir, 'node' + str(i))):
+ if not os.path.isdir(os.path.join(self.options.cachedir, 'node' + str(i))):
create_cache = True
break
@@ -380,27 +387,22 @@ class BitcoinTestFramework(object):
# find and delete old cache directories if any exist
for i in range(MAX_NODES):
- if os.path.isdir(os.path.join(cachedir, "node" + str(i))):
- shutil.rmtree(os.path.join(cachedir, "node" + str(i)))
+ if os.path.isdir(os.path.join(self.options.cachedir, "node" + str(i))):
+ shutil.rmtree(os.path.join(self.options.cachedir, "node" + str(i)))
# Create cache directories, run bitcoinds:
for i in range(MAX_NODES):
- datadir = initialize_datadir(cachedir, i)
+ datadir = initialize_datadir(self.options.cachedir, i)
args = [os.getenv("BITCOIND", "bitcoind"), "-server", "-keypool=1", "-datadir=" + datadir, "-discover=0"]
if i > 0:
args.append("-connect=127.0.0.1:" + str(p2p_port(0)))
- self.bitcoind_processes[i] = subprocess.Popen(args)
- self.log.debug("initialize_chain: bitcoind started, waiting for RPC to come up")
- self._wait_for_bitcoind_start(self.bitcoind_processes[i], datadir, i)
- self.log.debug("initialize_chain: RPC successfully started")
+ self.nodes.append(TestNode(i, self.options.cachedir, extra_args=[], rpchost=None, timewait=None, binary=None, stderr=None, mocktime=self.mocktime, coverage_dir=None))
+ self.nodes[i].args = args
+ self.start_node(i)
- self.nodes = []
- for i in range(MAX_NODES):
- try:
- self.nodes.append(get_rpc_proxy(rpc_url(get_datadir_path(cachedir, i), i), i))
- except:
- self.log.exception("Error connecting to node %d" % i)
- sys.exit(1)
+ # Wait for RPC connections to be ready
+ for node in self.nodes:
+ node.wait_for_rpc_connection()
# Create a 200-block-long chain; each of the 4 first nodes
# gets 25 mature blocks and 25 immature.
@@ -425,48 +427,24 @@ class BitcoinTestFramework(object):
self.nodes = []
self.disable_mocktime()
for i in range(MAX_NODES):
- os.remove(log_filename(cachedir, i, "debug.log"))
- os.remove(log_filename(cachedir, i, "db.log"))
- os.remove(log_filename(cachedir, i, "peers.dat"))
- os.remove(log_filename(cachedir, i, "fee_estimates.dat"))
-
- for i in range(num_nodes):
- from_dir = os.path.join(cachedir, "node" + str(i))
- to_dir = os.path.join(test_dir, "node" + str(i))
+ os.remove(log_filename(self.options.cachedir, i, "debug.log"))
+ os.remove(log_filename(self.options.cachedir, i, "db.log"))
+ os.remove(log_filename(self.options.cachedir, i, "peers.dat"))
+ os.remove(log_filename(self.options.cachedir, i, "fee_estimates.dat"))
+
+ for i in range(self.num_nodes):
+ from_dir = os.path.join(self.options.cachedir, "node" + str(i))
+ to_dir = os.path.join(self.options.tmpdir, "node" + str(i))
shutil.copytree(from_dir, to_dir)
- initialize_datadir(test_dir, i) # Overwrite port/rpcport in bitcoin.conf
+ initialize_datadir(self.options.tmpdir, i) # Overwrite port/rpcport in bitcoin.conf
- def _initialize_chain_clean(self, test_dir, num_nodes):
+ def _initialize_chain_clean(self):
"""Initialize empty blockchain for use by the test.
Create an empty blockchain and num_nodes wallets.
Useful if a test case wants complete control over initialization."""
- for i in range(num_nodes):
- initialize_datadir(test_dir, i)
-
- def _wait_for_bitcoind_start(self, process, datadir, i, rpchost=None):
- """Wait for bitcoind to start.
-
- This means that RPC is accessible and fully initialized.
- Raise an exception if bitcoind exits during initialization."""
- while True:
- if process.poll() is not None:
- raise Exception('bitcoind exited with status %i during initialization' % process.returncode)
- try:
- # Check if .cookie file to be created
- rpc = get_rpc_proxy(rpc_url(datadir, i, rpchost), i, coveragedir=self.options.coveragedir)
- rpc.getblockcount()
- break # break out of loop on success
- except IOError as e:
- if e.errno != errno.ECONNREFUSED: # Port not yet open?
- raise # unknown IO error
- except JSONRPCException as e: # Initialization phase
- if e.error['code'] != -28: # RPC in warmup?
- raise # unknown JSON RPC exception
- except ValueError as e: # cookie file not found and no rpcuser or rpcassword. bitcoind still starting
- if "No RPC credentials" not in str(e):
- raise
- time.sleep(0.25)
+ for i in range(self.num_nodes):
+ initialize_datadir(self.options.tmpdir, i)
class ComparisonTestFramework(BitcoinTestFramework):
"""Test framework for doing p2p comparison testing
@@ -476,8 +454,7 @@ class ComparisonTestFramework(BitcoinTestFramework):
- 2 binaries: 1 test binary, 1 ref binary
- n>2 binaries: 1 test binary, n-1 ref binaries"""
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
@@ -490,13 +467,13 @@ class ComparisonTestFramework(BitcoinTestFramework):
help="bitcoind binary to use for reference nodes (if any)")
def setup_network(self):
- extra_args = [['-whitelist=127.0.0.1']]*self.num_nodes
+ extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes
if hasattr(self, "extra_args"):
extra_args = self.extra_args
- self.nodes = self.start_nodes(
- self.num_nodes, self.options.tmpdir, extra_args,
- binary=[self.options.testbinary] +
- [self.options.refbinary] * (self.num_nodes - 1))
+ self.add_nodes(self.num_nodes, extra_args,
+ binary=[self.options.testbinary] +
+ [self.options.refbinary] * (self.num_nodes - 1))
+ self.start_nodes()
class SkipTest(Exception):
"""This exception is raised to skip a test"""
diff --git a/test/functional/test_framework/test_node.py b/test/functional/test_framework/test_node.py
new file mode 100755
index 0000000000..efb3ac9d16
--- /dev/null
+++ b/test/functional/test_framework/test_node.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+# Copyright (c) 2017 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Class for bitcoind node under test"""
+
+import decimal
+import errno
+import http.client
+import json
+import logging
+import os
+import subprocess
+import time
+
+from .util import (
+ assert_equal,
+ get_rpc_proxy,
+ rpc_url,
+)
+from .authproxy import JSONRPCException
+
+class TestNode():
+ """A class for representing a bitcoind node under test.
+
+ This class contains:
+
+ - state about the node (whether it's running, etc)
+ - a Python subprocess.Popen object representing the running process
+ - an RPC connection to the node
+
+ To make things easier for the test writer, a bit of magic is happening under the covers.
+ Any unrecognised messages will be dispatched to the RPC connection."""
+
+ def __init__(self, i, dirname, extra_args, rpchost, timewait, binary, stderr, mocktime, coverage_dir):
+ self.index = i
+ self.datadir = os.path.join(dirname, "node" + str(i))
+ self.rpchost = rpchost
+ if timewait:
+ self.rpc_timeout = timewait
+ else:
+ # Wait for up to 60 seconds for the RPC server to respond
+ self.rpc_timeout = 60
+ if binary is None:
+ self.binary = os.getenv("BITCOIND", "bitcoind")
+ else:
+ self.binary = binary
+ self.stderr = stderr
+ self.coverage_dir = coverage_dir
+ # Most callers will just need to add extra args to the standard list below. For those callers that need more flexibity, they can just set the args property directly.
+ self.extra_args = extra_args
+ self.args = [self.binary, "-datadir=" + self.datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-logtimemicros", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", "-mocktime=" + str(mocktime), "-uacomment=testnode%d" % i]
+
+ self.cli = TestNodeCLI(os.getenv("BITCOINCLI", "bitcoin-cli"), self.datadir)
+
+ self.running = False
+ self.process = None
+ self.rpc_connected = False
+ self.rpc = None
+ self.url = None
+ self.log = logging.getLogger('TestFramework.node%d' % i)
+
+ def __getattr__(self, *args, **kwargs):
+ """Dispatches any unrecognised messages to the RPC connection."""
+ assert self.rpc_connected and self.rpc is not None, "Error: no RPC connection"
+ return self.rpc.__getattr__(*args, **kwargs)
+
+ def start(self, extra_args=None, stderr=None):
+ """Start the node."""
+ if extra_args is None:
+ extra_args = self.extra_args
+ if stderr is None:
+ stderr = self.stderr
+ self.process = subprocess.Popen(self.args + extra_args, stderr=stderr)
+ self.running = True
+ self.log.debug("bitcoind started, waiting for RPC to come up")
+
+ def wait_for_rpc_connection(self):
+ """Sets up an RPC connection to the bitcoind process. Returns False if unable to connect."""
+ # Poll at a rate of four times per second
+ poll_per_s = 4
+ for _ in range(poll_per_s * self.rpc_timeout):
+ assert self.process.poll() is None, "bitcoind exited with status %i during initialization" % self.process.returncode
+ try:
+ self.rpc = get_rpc_proxy(rpc_url(self.datadir, self.index, self.rpchost), self.index, timeout=self.rpc_timeout, coveragedir=self.coverage_dir)
+ self.rpc.getblockcount()
+ # If the call to getblockcount() succeeds then the RPC connection is up
+ self.rpc_connected = True
+ self.url = self.rpc.url
+ self.log.debug("RPC successfully started")
+ return
+ except IOError as e:
+ if e.errno != errno.ECONNREFUSED: # Port not yet open?
+ raise # unknown IO error
+ except JSONRPCException as e: # Initialization phase
+ if e.error['code'] != -28: # RPC in warmup?
+ raise # unknown JSON RPC exception
+ except ValueError as e: # cookie file not found and no rpcuser or rpcassword. bitcoind still starting
+ if "No RPC credentials" not in str(e):
+ raise
+ time.sleep(1.0 / poll_per_s)
+ raise AssertionError("Unable to connect to bitcoind")
+
+ def get_wallet_rpc(self, wallet_name):
+ assert self.rpc_connected
+ assert self.rpc
+ wallet_path = "wallet/%s" % wallet_name
+ return self.rpc / wallet_path
+
+ def stop_node(self):
+ """Stop the node."""
+ if not self.running:
+ return
+ self.log.debug("Stopping node")
+ try:
+ self.stop()
+ except http.client.CannotSendRequest:
+ self.log.exception("Unable to stop node.")
+
+ def is_node_stopped(self):
+ """Checks whether the node has stopped.
+
+ Returns True if the node has stopped. False otherwise.
+ This method is responsible for freeing resources (self.process)."""
+ if not self.running:
+ return True
+ return_code = self.process.poll()
+ if return_code is not None:
+ # process has stopped. Assert that it didn't return an error code.
+ assert_equal(return_code, 0)
+ self.running = False
+ self.process = None
+ self.log.debug("Node stopped")
+ return True
+ return False
+
+ def node_encrypt_wallet(self, passphrase):
+ """"Encrypts the wallet.
+
+ This causes bitcoind to shutdown, so this method takes
+ care of cleaning up resources."""
+ self.encryptwallet(passphrase)
+ while not self.is_node_stopped():
+ time.sleep(0.1)
+ self.rpc = None
+ self.rpc_connected = False
+
+class TestNodeCLI():
+ """Interface to bitcoin-cli for an individual node"""
+
+ def __init__(self, binary, datadir):
+ self.binary = binary
+ self.datadir = datadir
+
+ def __getattr__(self, command):
+ def dispatcher(*args, **kwargs):
+ return self.send_cli(command, *args, **kwargs)
+ return dispatcher
+
+ def send_cli(self, command, *args, **kwargs):
+ """Run bitcoin-cli command. Deserializes returned string as python object."""
+
+ pos_args = [str(arg) for arg in args]
+ named_args = [str(key) + "=" + str(value) for (key, value) in kwargs.items()]
+ assert not (pos_args and named_args), "Cannot use positional arguments and named arguments in the same bitcoin-cli call"
+ p_args = [self.binary, "-datadir=" + self.datadir]
+ if named_args:
+ p_args += ["-named"]
+ p_args += [command] + pos_args + named_args
+ cli_output = subprocess.check_output(p_args, universal_newlines=True)
+ return json.loads(cli_output, parse_float=decimal.Decimal)
diff --git a/test/functional/test_framework/util.py b/test/functional/test_framework/util.py
index acca72aa86..a14cda07d0 100644
--- a/test/functional/test_framework/util.py
+++ b/test/functional/test_framework/util.py
@@ -157,6 +157,28 @@ def str_to_b64str(string):
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
+def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf'), lock=None):
+ if attempts == float('inf') and timeout == float('inf'):
+ timeout = 60
+ attempt = 0
+ timeout += time.time()
+
+ while attempt < attempts and time.time() < timeout:
+ if lock:
+ with lock:
+ if predicate():
+ return
+ else:
+ if predicate():
+ return
+ attempt += 1
+ time.sleep(0.05)
+
+ # Print the cause of the timeout
+ assert_greater_than(attempts, attempt)
+ assert_greater_than(timeout, time.time())
+ raise RuntimeError('Unreachable')
+
# RPC/P2P connection constants and functions
############################################
@@ -204,7 +226,7 @@ def rpc_port(n):
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
def rpc_url(datadir, i, rpchost=None):
- rpc_u, rpc_p = get_auth_cookie(datadir, i)
+ rpc_u, rpc_p = get_auth_cookie(datadir)
host = '127.0.0.1'
port = rpc_port(i)
if rpchost:
@@ -232,7 +254,7 @@ def initialize_datadir(dirname, n):
def get_datadir_path(dirname, n):
return os.path.join(dirname, "node" + str(n))
-def get_auth_cookie(datadir, n):
+def get_auth_cookie(datadir):
user = None
password = None
if os.path.isfile(os.path.join(datadir, "bitcoin.conf")):
diff --git a/test/functional/test_runner.py b/test/functional/test_runner.py
index 93f180555d..59c236ce15 100755
--- a/test/functional/test_runner.py
+++ b/test/functional/test_runner.py
@@ -81,6 +81,7 @@ BASE_SCRIPTS= [
# vv Tests less than 30s vv
'keypool-topup.py',
'zmq_test.py',
+ 'bitcoin_cli.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
@@ -170,7 +171,7 @@ def main():
Help text and arguments for individual test script:''',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
- parser.add_argument('--exclude', '-x', help='specify a comma-seperated-list of scripts to exclude.')
+ parser.add_argument('--exclude', '-x', help='specify a comma-separated-list of scripts to exclude.')
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
parser.add_argument('--force', '-f', action='store_true', help='run tests even on platforms where they are disabled by default (e.g. windows).')
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
@@ -279,6 +280,7 @@ def run_tests(test_list, src_dir, build_dir, exeext, tmpdir, jobs=1, enable_cove
#Set env vars
if "BITCOIND" not in os.environ:
os.environ["BITCOIND"] = build_dir + '/src/bitcoind' + exeext
+ os.environ["BITCOINCLI"] = build_dir + '/src/bitcoin-cli' + exeext
tests_dir = src_dir + '/test/functional/'
@@ -352,7 +354,7 @@ def print_results(test_results, max_len_name, runtime):
class TestHandler:
"""
- Trigger the testscrips passed in via the list.
+ Trigger the test scripts passed in via the list.
"""
def __init__(self, num_tests_parallel, tests_dir, tmpdir, test_list=None, flags=None):
diff --git a/test/functional/txn_clone.py b/test/functional/txn_clone.py
index 9b81af96cf..740bb2d4c5 100755
--- a/test/functional/txn_clone.py
+++ b/test/functional/txn_clone.py
@@ -8,11 +8,8 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class TxnMallTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 4
- self.setup_clean_chain = False
def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
diff --git a/test/functional/txn_doublespend.py b/test/functional/txn_doublespend.py
index 1bd3b3271c..69629ef951 100755
--- a/test/functional/txn_doublespend.py
+++ b/test/functional/txn_doublespend.py
@@ -8,11 +8,8 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class TxnMallTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 4
- self.setup_clean_chain = False
def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
diff --git a/test/functional/uptime.py b/test/functional/uptime.py
index b20d6f5cb6..78236b2393 100755
--- a/test/functional/uptime.py
+++ b/test/functional/uptime.py
@@ -13,9 +13,7 @@ from test_framework.test_framework import BitcoinTestFramework
class UptimeTest(BitcoinTestFramework):
- def __init__(self):
- super().__init__()
-
+ def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
diff --git a/test/functional/wallet-accounts.py b/test/functional/wallet-accounts.py
index 158aa9ae89..40726d2a76 100755
--- a/test/functional/wallet-accounts.py
+++ b/test/functional/wallet-accounts.py
@@ -17,9 +17,7 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class WalletAccountsTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [[]]
diff --git a/test/functional/wallet-dump.py b/test/functional/wallet-dump.py
index 569cc46e6c..e4757c8c03 100755
--- a/test/functional/wallet-dump.py
+++ b/test/functional/wallet-dump.py
@@ -56,10 +56,7 @@ def read_dump(file_name, addrs, hd_master_addr_old):
class WalletDumpTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = False
+ def set_test_params(self):
self.num_nodes = 1
self.extra_args = [["-keypool=90"]]
@@ -68,7 +65,8 @@ class WalletDumpTest(BitcoinTestFramework):
# longer than the default 30 seconds due to an expensive
# CWallet::TopUpKeyPool call, and the encryptwallet RPC made later in
# the test often takes even longer.
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, self.extra_args, timewait=60)
+ self.add_nodes(self.num_nodes, self.extra_args, timewait=60)
+ self.start_nodes()
def run_test (self):
tmpdir = self.options.tmpdir
@@ -94,15 +92,14 @@ class WalletDumpTest(BitcoinTestFramework):
assert_equal(found_addr_rsv, 90*2) # 90 keys plus 100% internal keys
#encrypt wallet, restart, unlock and dump
- self.nodes[0].encryptwallet('test')
- self.bitcoind_processes[0].wait()
- self.nodes[0] = self.start_node(0, self.options.tmpdir, self.extra_args[0])
+ self.nodes[0].node_encrypt_wallet('test')
+ self.start_node(0)
self.nodes[0].walletpassphrase('test', 10)
# Should be a no-op:
self.nodes[0].keypoolrefill()
self.nodes[0].dumpwallet(tmpdir + "/node0/wallet.encrypted.dump")
- found_addr, found_addr_chg, found_addr_rsv, hd_master_addr_enc = \
+ found_addr, found_addr_chg, found_addr_rsv, _ = \
read_dump(tmpdir + "/node0/wallet.encrypted.dump", addrs, hd_master_addr_unenc)
assert_equal(found_addr, test_addr_count)
assert_equal(found_addr_chg, 90*2 + 50) # old reserve keys are marked as change now
diff --git a/test/functional/wallet-encryption.py b/test/functional/wallet-encryption.py
index ba72918fe1..f63bb2ea5e 100755
--- a/test/functional/wallet-encryption.py
+++ b/test/functional/wallet-encryption.py
@@ -13,9 +13,7 @@ from test_framework.util import (
)
class WalletEncryptionTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
@@ -30,9 +28,8 @@ class WalletEncryptionTest(BitcoinTestFramework):
assert_equal(len(privkey), 52)
# Encrypt the wallet
- self.nodes[0].encryptwallet(passphrase)
- self.bitcoind_processes[0].wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
- self.nodes[0] = self.start_node(0, self.options.tmpdir)
+ self.nodes[0].node_encrypt_wallet(passphrase)
+ self.start_node(0)
# Test that the wallet is encrypted
assert_raises_jsonrpc(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
diff --git a/test/functional/wallet-hd.py b/test/functional/wallet-hd.py
index 821575ed19..a6b96b7455 100755
--- a/test/functional/wallet-hd.py
+++ b/test/functional/wallet-hd.py
@@ -11,11 +11,8 @@ from test_framework.util import (
)
import shutil
-
class WalletHDTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [['-usehd=0'], ['-usehd=1', '-keypool=0']]
@@ -25,8 +22,8 @@ class WalletHDTest(BitcoinTestFramework):
# Make sure can't switch off usehd after wallet creation
self.stop_node(1)
- self.assert_start_raises_init_error(1, self.options.tmpdir, ['-usehd=0'], 'already existing HD wallet')
- self.nodes[1] = self.start_node(1, self.options.tmpdir, self.extra_args[1])
+ self.assert_start_raises_init_error(1, ['-usehd=0'], 'already existing HD wallet')
+ self.start_node(1)
connect_nodes_bi(self.nodes, 0, 1)
# Make sure we use hd, keep masterkeyid
@@ -42,7 +39,7 @@ class WalletHDTest(BitcoinTestFramework):
non_hd_add = self.nodes[0].getnewaddress()
self.nodes[1].importprivkey(self.nodes[0].dumpprivkey(non_hd_add))
- # This should be enough to keep the master key and the non-HD key
+ # This should be enough to keep the master key and the non-HD key
self.nodes[1].backupwallet(tmpdir + "/hd.bak")
#self.nodes[1].dumpwallet(tmpdir + "/hd.dump")
@@ -54,7 +51,7 @@ class WalletHDTest(BitcoinTestFramework):
for i in range(num_hd_adds):
hd_add = self.nodes[1].getnewaddress()
hd_info = self.nodes[1].validateaddress(hd_add)
- assert_equal(hd_info["hdkeypath"], "m/0'/0'/"+str(i+1)+"'")
+ assert_equal(hd_info["hdkeypath"], "m/0'/0'/"+str(i)+"'")
assert_equal(hd_info["hdmasterkeyid"], masterkeyid)
self.nodes[0].sendtoaddress(hd_add, 1)
self.nodes[0].generate(1)
@@ -76,14 +73,14 @@ class WalletHDTest(BitcoinTestFramework):
shutil.rmtree(tmpdir + "/node1/regtest/blocks")
shutil.rmtree(tmpdir + "/node1/regtest/chainstate")
shutil.copyfile(tmpdir + "/hd.bak", tmpdir + "/node1/regtest/wallet.dat")
- self.nodes[1] = self.start_node(1, self.options.tmpdir, self.extra_args[1])
+ self.start_node(1)
# Assert that derivation is deterministic
hd_add_2 = None
for _ in range(num_hd_adds):
hd_add_2 = self.nodes[1].getnewaddress()
hd_info_2 = self.nodes[1].validateaddress(hd_add_2)
- assert_equal(hd_info_2["hdkeypath"], "m/0'/0'/"+str(_+1)+"'")
+ assert_equal(hd_info_2["hdkeypath"], "m/0'/0'/"+str(_)+"'")
assert_equal(hd_info_2["hdmasterkeyid"], masterkeyid)
assert_equal(hd_add, hd_add_2)
connect_nodes_bi(self.nodes, 0, 1)
@@ -91,7 +88,7 @@ class WalletHDTest(BitcoinTestFramework):
# Needs rescan
self.stop_node(1)
- self.nodes[1] = self.start_node(1, self.options.tmpdir, self.extra_args[1] + ['-rescan'])
+ self.start_node(1, extra_args=self.extra_args[1] + ['-rescan'])
assert_equal(self.nodes[1].getbalance(), num_hd_adds + 1)
# send a tx and make sure its using the internal chain for the changeoutput
@@ -101,7 +98,7 @@ class WalletHDTest(BitcoinTestFramework):
for out in outs:
if out['value'] != 1:
keypath = self.nodes[1].validateaddress(out['scriptPubKey']['addresses'][0])['hdkeypath']
-
+
assert_equal(keypath[0:7], "m/0'/1'")
if __name__ == '__main__':
diff --git a/test/functional/wallet.py b/test/functional/wallet.py
index 3e3e8fcddb..27089e8845 100755
--- a/test/functional/wallet.py
+++ b/test/functional/wallet.py
@@ -7,28 +7,28 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class WalletTest(BitcoinTestFramework):
-
- def check_fee_amount(self, curr_balance, balance_with_fee, fee_per_byte, tx_size):
- """Return curr_balance after asserting the fee was in range"""
- fee = balance_with_fee - curr_balance
- assert_fee_amount(fee, tx_size, fee_per_byte * 1000)
- return curr_balance
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = True
+ def set_test_params(self):
self.num_nodes = 4
+ self.setup_clean_chain = True
self.extra_args = [['-usehd={:d}'.format(i%2==0)] for i in range(4)]
def setup_network(self):
- self.nodes = self.start_nodes(3, self.options.tmpdir, self.extra_args[:3])
+ self.add_nodes(4, self.extra_args)
+ self.start_node(0)
+ self.start_node(1)
+ self.start_node(2)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
- def run_test(self):
+ def check_fee_amount(self, curr_balance, balance_with_fee, fee_per_byte, tx_size):
+ """Return curr_balance after asserting the fee was in range"""
+ fee = balance_with_fee - curr_balance
+ assert_fee_amount(fee, tx_size, fee_per_byte * 1000)
+ return curr_balance
+ def run_test(self):
# Check that there's no UTXO on none of the nodes
assert_equal(len(self.nodes[0].listunspent()), 0)
assert_equal(len(self.nodes[1].listunspent()), 0)
@@ -42,9 +42,9 @@ class WalletTest(BitcoinTestFramework):
assert_equal(walletinfo['immature_balance'], 50)
assert_equal(walletinfo['balance'], 0)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
self.nodes[1].generate(101)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
assert_equal(self.nodes[0].getbalance(), 50)
assert_equal(self.nodes[1].getbalance(), 50)
@@ -56,6 +56,15 @@ class WalletTest(BitcoinTestFramework):
assert_equal(len(self.nodes[1].listunspent()), 1)
assert_equal(len(self.nodes[2].listunspent()), 0)
+ self.log.info("test gettxout")
+ confirmed_txid, confirmed_index = utxos[0]["txid"], utxos[0]["vout"]
+ # First, outputs that are unspent both in the chain and in the
+ # mempool should appear with or without include_mempool
+ txout = self.nodes[0].gettxout(txid=confirmed_txid, n=confirmed_index, include_mempool=False)
+ assert_equal(txout['value'], 50)
+ txout = self.nodes[0].gettxout(txid=confirmed_txid, n=confirmed_index, include_mempool=True)
+ assert_equal(txout['value'], 50)
+
# Send 21 BTC from 0 to 2 using sendtoaddress call.
# Locked memory should use at least 32 bytes to sign each transaction
self.log.info("test getmemoryinfo")
@@ -65,10 +74,9 @@ class WalletTest(BitcoinTestFramework):
memory_after = self.nodes[0].getmemoryinfo()
assert(memory_before['locked']['used'] + 64 <= memory_after['locked']['used'])
- self.log.info("test gettxout")
+ self.log.info("test gettxout (second part)")
# utxo spent in mempool should be visible if you exclude mempool
# but invisible if you include mempool
- confirmed_txid, confirmed_index = utxos[0]["txid"], utxos[0]["vout"]
txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index, False)
assert_equal(txout['value'], 50)
txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index, True)
@@ -88,7 +96,7 @@ class WalletTest(BitcoinTestFramework):
# Have node0 mine a block, thus it will collect its own fee.
self.nodes[0].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
# Exercise locking of unspent outputs
unspent_0 = self.nodes[2].listunspent()[0]
@@ -101,7 +109,7 @@ class WalletTest(BitcoinTestFramework):
# Have node1 generate 100 blocks (so node0 can recover the fee)
self.nodes[1].generate(100)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
# node0 should end up with 100 btc in block rewards plus fees, but
# minus the 21 plus fees sent to node2
@@ -130,7 +138,7 @@ class WalletTest(BitcoinTestFramework):
# Have node1 mine a block to confirm transactions:
self.nodes[1].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
assert_equal(self.nodes[0].getbalance(), 0)
assert_equal(self.nodes[2].getbalance(), 94)
@@ -142,14 +150,14 @@ class WalletTest(BitcoinTestFramework):
self.nodes[2].settxfee(fee_per_byte * 1000)
txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
self.nodes[2].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), Decimal('84'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
assert_equal(self.nodes[0].getbalance(), Decimal('10'))
# Send 10 BTC with subtract fee from amount
txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
self.nodes[2].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
node_2_bal -= Decimal('10')
assert_equal(self.nodes[2].getbalance(), node_2_bal)
node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), Decimal('20'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
@@ -157,7 +165,7 @@ class WalletTest(BitcoinTestFramework):
# Sendmany 10 BTC
txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [])
self.nodes[2].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
node_0_bal += Decimal('10')
node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), node_2_bal - Decimal('10'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
assert_equal(self.nodes[0].getbalance(), node_0_bal)
@@ -165,7 +173,7 @@ class WalletTest(BitcoinTestFramework):
# Sendmany 10 BTC with subtract fee from amount
txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [address])
self.nodes[2].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
node_2_bal -= Decimal('10')
assert_equal(self.nodes[2].getbalance(), node_2_bal)
node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), node_0_bal + Decimal('10'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
@@ -176,9 +184,9 @@ class WalletTest(BitcoinTestFramework):
# EXPECT: nodes[3] should have those transactions in its mempool.
txid1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1)
txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
- sync_mempools(self.nodes)
+ sync_mempools(self.nodes[0:2])
- self.nodes.append(self.start_node(3, self.options.tmpdir, self.extra_args[3]))
+ self.start_node(3)
connect_nodes_bi(self.nodes, 0, 3)
sync_blocks(self.nodes)
@@ -206,7 +214,7 @@ class WalletTest(BitcoinTestFramework):
signedRawTx = self.nodes[1].signrawtransaction(rawTx)
decRawTx = self.nodes[1].decoderawtransaction(signedRawTx['hex'])
zeroValueTxid= decRawTx['txid']
- sendResp = self.nodes[1].sendrawtransaction(signedRawTx['hex'])
+ self.nodes[1].sendrawtransaction(signedRawTx['hex'])
self.sync_all()
self.nodes[1].generate(1) #mine a block
@@ -222,22 +230,24 @@ class WalletTest(BitcoinTestFramework):
#do some -walletbroadcast tests
self.stop_nodes()
- self.nodes = self.start_nodes(3, self.options.tmpdir, [["-walletbroadcast=0"],["-walletbroadcast=0"],["-walletbroadcast=0"]])
+ self.start_node(0, ["-walletbroadcast=0"])
+ self.start_node(1, ["-walletbroadcast=0"])
+ self.start_node(2, ["-walletbroadcast=0"])
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
txIdNotBroadcasted = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)
txObjNotBroadcasted = self.nodes[0].gettransaction(txIdNotBroadcasted)
self.nodes[1].generate(1) #mine a block, tx should not be in there
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
assert_equal(self.nodes[2].getbalance(), node_2_bal) #should not be changed because tx was not broadcasted
#now broadcast from another node, mine a block, sync, and check the balance
self.nodes[1].sendrawtransaction(txObjNotBroadcasted['hex'])
self.nodes[1].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
node_2_bal += 2
txObjNotBroadcasted = self.nodes[0].gettransaction(txIdNotBroadcasted)
assert_equal(self.nodes[2].getbalance(), node_2_bal)
@@ -247,14 +257,16 @@ class WalletTest(BitcoinTestFramework):
#restart the nodes with -walletbroadcast=1
self.stop_nodes()
- self.nodes = self.start_nodes(3, self.options.tmpdir)
+ self.start_node(0)
+ self.start_node(1)
+ self.start_node(2)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
- sync_blocks(self.nodes)
+ sync_blocks(self.nodes[0:3])
self.nodes[0].generate(1)
- sync_blocks(self.nodes)
+ sync_blocks(self.nodes[0:3])
node_2_bal += 2
#tx should be added to balance because after restarting the nodes tx should be broadcastet
@@ -285,7 +297,7 @@ class WalletTest(BitcoinTestFramework):
address_to_import = self.nodes[2].getnewaddress()
txid = self.nodes[0].sendtoaddress(address_to_import, 1)
self.nodes[0].generate(1)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
# 2. Import address from node2 to node1
self.nodes[1].importaddress(address_to_import)
@@ -311,15 +323,15 @@ class WalletTest(BitcoinTestFramework):
cbAddr = self.nodes[1].getnewaddress()
blkHash = self.nodes[0].generatetoaddress(1, cbAddr)[0]
cbTxId = self.nodes[0].getblock(blkHash)['tx'][0]
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
# Check that the txid and balance is found by node1
self.nodes[1].gettransaction(cbTxId)
# check if wallet or blockchain maintenance changes the balance
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
blocks = self.nodes[0].generate(2)
- self.sync_all()
+ self.sync_all([self.nodes[0:3]])
balance_nodes = [self.nodes[i].getbalance() for i in range(3)]
block_count = self.nodes[0].getblockcount()
@@ -350,7 +362,9 @@ class WalletTest(BitcoinTestFramework):
self.log.info("check " + m)
self.stop_nodes()
# set lower ancestor limit for later
- self.nodes = self.start_nodes(3, self.options.tmpdir, [[m, "-limitancestorcount="+str(chainlimit)]] * 3)
+ self.start_node(0, [m, "-limitancestorcount="+str(chainlimit)])
+ self.start_node(1, [m, "-limitancestorcount="+str(chainlimit)])
+ self.start_node(2, [m, "-limitancestorcount="+str(chainlimit)])
while m == '-reindex' and [block_count] * 3 != [self.nodes[i].getblockcount() for i in range(3)]:
# reindex will leave rpc warm up "early"; Wait for it to finish
time.sleep(0.1)
@@ -398,7 +412,7 @@ class WalletTest(BitcoinTestFramework):
# Try with walletrejectlongchains
# Double chain limit but require combining inputs, so we pass SelectCoinsMinConf
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-walletrejectlongchains", "-limitancestorcount="+str(2*chainlimit)])
+ self.start_node(0, extra_args=["-walletrejectlongchains", "-limitancestorcount="+str(2*chainlimit)])
# wait for loadmempool
timeout = 10
diff --git a/test/functional/walletbackup.py b/test/functional/walletbackup.py
index ff51cba4b3..15ea26afa1 100755
--- a/test/functional/walletbackup.py
+++ b/test/functional/walletbackup.py
@@ -37,11 +37,9 @@ from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class WalletBackupTest(BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
- self.setup_clean_chain = True
+ def set_test_params(self):
self.num_nodes = 4
+ self.setup_clean_chain = True
# nodes 1, 2,3 are spenders, let's give them a keypool=100
self.extra_args = [["-keypool=100"], ["-keypool=100"], ["-keypool=100"], []]
@@ -78,9 +76,9 @@ class WalletBackupTest(BitcoinTestFramework):
# As above, this mirrors the original bash test.
def start_three(self):
- self.nodes[0] = self.start_node(0, self.options.tmpdir)
- self.nodes[1] = self.start_node(1, self.options.tmpdir)
- self.nodes[2] = self.start_node(2, self.options.tmpdir)
+ self.start_node(0)
+ self.start_node(1)
+ self.start_node(2)
connect_nodes(self.nodes[0], 3)
connect_nodes(self.nodes[1], 3)
connect_nodes(self.nodes[2], 3)
diff --git a/test/functional/zapwallettxes.py b/test/functional/zapwallettxes.py
index af867d7a52..c001517a6d 100755
--- a/test/functional/zapwallettxes.py
+++ b/test/functional/zapwallettxes.py
@@ -20,9 +20,7 @@ from test_framework.util import (assert_equal,
)
class ZapWalletTXesTest (BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
@@ -48,7 +46,7 @@ class ZapWalletTXesTest (BitcoinTestFramework):
# Stop-start node0. Both confirmed and unconfirmed transactions remain in the wallet.
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir)
+ self.start_node(0)
assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1)
assert_equal(self.nodes[0].gettransaction(txid2)['txid'], txid2)
@@ -56,7 +54,7 @@ class ZapWalletTXesTest (BitcoinTestFramework):
# Stop node0 and restart with zapwallettxes and persistmempool. The unconfirmed
# transaction is zapped from the wallet, but is re-added when the mempool is reloaded.
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-persistmempool=1", "-zapwallettxes=2"])
+ self.start_node(0, ["-persistmempool=1", "-zapwallettxes=2"])
assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1)
assert_equal(self.nodes[0].gettransaction(txid2)['txid'], txid2)
@@ -64,7 +62,7 @@ class ZapWalletTXesTest (BitcoinTestFramework):
# Stop node0 and restart with zapwallettxes, but not persistmempool.
# The unconfirmed transaction is zapped and is no longer in the wallet.
self.stop_node(0)
- self.nodes[0] = self.start_node(0, self.options.tmpdir, ["-zapwallettxes=2"])
+ self.start_node(0, ["-zapwallettxes=2"])
# tx1 is still be available because it was confirmed
assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1)
diff --git a/test/functional/zmq_test.py b/test/functional/zmq_test.py
index 26c946d215..3f2668ee87 100755
--- a/test/functional/zmq_test.py
+++ b/test/functional/zmq_test.py
@@ -13,9 +13,7 @@ from test_framework.util import (assert_equal,
)
class ZMQTest (BitcoinTestFramework):
-
- def __init__(self):
- super().__init__()
+ def set_test_params(self):
self.num_nodes = 2
def setup_nodes(self):
@@ -41,8 +39,9 @@ class ZMQTest (BitcoinTestFramework):
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashtx")
ip_address = "tcp://127.0.0.1:28332"
self.zmqSubSocket.connect(ip_address)
- extra_args = [['-zmqpubhashtx=%s' % ip_address, '-zmqpubhashblock=%s' % ip_address], []]
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
+ self.extra_args = [['-zmqpubhashtx=%s' % ip_address, '-zmqpubhashblock=%s' % ip_address], []]
+ self.add_nodes(self.num_nodes, self.extra_args)
+ self.start_nodes()
def run_test(self):
try: