diff options
84 files changed, 620 insertions, 632 deletions
diff --git a/configure.ac b/configure.ac index c422914a26..b38e480f27 100644 --- a/configure.ac +++ b/configure.ac @@ -1373,6 +1373,7 @@ echo " with test = $use_tests" echo " with bench = $use_bench" echo " with upnp = $use_upnp" echo " use asm = $use_asm" +echo " sanitizers = $use_sanitizers" echo " debug enabled = $enable_debug" echo " gprof enabled = $enable_gprof" echo " werror = $enable_werror" diff --git a/contrib/devtools/lint-logs.sh b/contrib/devtools/lint-logs.sh new file mode 100755 index 0000000000..3bb54359a8 --- /dev/null +++ b/contrib/devtools/lint-logs.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# +# Copyright (c) 2018 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# +# Check that all logs are terminated with '\n' +# +# Some logs are continued over multiple lines. They should be explicitly +# commented with \* Continued *\ +# +# There are some instances of LogPrintf() in comments. Those can be +# ignored + + +UNTERMINATED_LOGS=$(git grep "LogPrintf(" -- "*.cpp" | \ + grep -v '\\n"' | \ + grep -v "/\* Continued \*/" | \ + grep -v "LogPrintf()") +if [[ ${UNTERMINATED_LOGS} != "" ]]; then + echo "All calls to LogPrintf() should be terminated with \\n" + echo + echo "${UNTERMINATED_LOGS}" + exit 1 +fi diff --git a/contrib/devtools/lint-tests.sh b/contrib/devtools/lint-tests.sh index dd1a3ebdc4..ffc0660551 100755 --- a/contrib/devtools/lint-tests.sh +++ b/contrib/devtools/lint-tests.sh @@ -4,7 +4,9 @@ # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # -# Check the test suite naming convention +# Check the test suite naming conventions + +EXIT_CODE=0 NAMING_INCONSISTENCIES=$(git grep -E '^BOOST_FIXTURE_TEST_SUITE\(' -- \ "src/test/**.cpp" "src/wallet/test/**.cpp" | \ @@ -15,5 +17,18 @@ if [[ ${NAMING_INCONSISTENCIES} != "" ]]; then echo "that convention:" echo echo "${NAMING_INCONSISTENCIES}" - exit 1 + EXIT_CODE=1 fi + +TEST_SUITE_NAME_COLLISSIONS=$(git grep -E '^BOOST_FIXTURE_TEST_SUITE\(' -- \ + "src/test/**.cpp" "src/wallet/test/**.cpp" | cut -f2 -d'(' | cut -f1 -d, | \ + sort | uniq -d) +if [[ ${TEST_SUITE_NAME_COLLISSIONS} != "" ]]; then + echo "Test suite names must be unique. The following test suite names" + echo "appear to be used more than once:" + echo + echo "${TEST_SUITE_NAME_COLLISSIONS}" + EXIT_CODE=1 +fi + +exit ${EXIT_CODE} diff --git a/contrib/verify-commits/verify-commits.sh b/contrib/verify-commits/verify-commits.sh index 532b97a438..6415eea4d5 100755 --- a/contrib/verify-commits/verify-commits.sh +++ b/contrib/verify-commits/verify-commits.sh @@ -35,6 +35,8 @@ NO_SHA1=1 PREV_COMMIT="" INITIAL_COMMIT="${CURRENT_COMMIT}" +BRANCH="$(git rev-parse --abbrev-ref HEAD)" + while true; do if [ "$CURRENT_COMMIT" = $VERIFIED_ROOT ]; then echo "There is a valid path from \"$INITIAL_COMMIT\" to $VERIFIED_ROOT where all commits are signed!" @@ -123,9 +125,29 @@ while true; do fi PARENTS=$(git show -s --format=format:%P "$CURRENT_COMMIT") - for PARENT in $PARENTS; do - PREV_COMMIT="$CURRENT_COMMIT" - CURRENT_COMMIT="$PARENT" - break - done + PARENT1=${PARENTS%% *} + PARENT2="" + if [ "x$PARENT1" != "x$PARENTS" ]; then + PARENTX=${PARENTS#* } + PARENT2=${PARENTX%% *} + if [ "x$PARENT2" != "x$PARENTX" ]; then + echo "Commit $CURRENT_COMMIT is an octopus merge" > /dev/stderr + exit 1 + fi + fi + if [ "x$PARENT2" != "x" ]; then + CURRENT_TREE="$(git show --format="%T" "$CURRENT_COMMIT")" + git checkout --force --quiet "$PARENT1" + git merge --no-ff --quiet "$PARENT2" >/dev/null + RECREATED_TREE="$(git show --format="%T" HEAD)" + if [ "$CURRENT_TREE" != "$RECREATED_TREE" ]; then + echo "Merge commit $CURRENT_COMMIT is not clean" > /dev/stderr + git diff "$CURRENT_COMMIT" + git checkout --force --quiet "$BRANCH" + exit 1 + fi + git checkout --force --quiet "$BRANCH" + fi + PREV_COMMIT="$CURRENT_COMMIT" + CURRENT_COMMIT="$PARENT1" done diff --git a/doc/build-osx.md b/doc/build-osx.md index f19e4f0b8d..e52a770ced 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 miniupnpc openssl pkg-config protobuf python qt libevent + brew install automake berkeley-db4 libtool boost miniupnpc openssl pkg-config protobuf python qt libevent qrencode See [dependencies.md](dependencies.md) for a complete overview. diff --git a/doc/developer-notes.md b/doc/developer-notes.md index b00cceb987..980eed44f3 100644 --- a/doc/developer-notes.md +++ b/doc/developer-notes.md @@ -72,7 +72,8 @@ code. - Class names, function names and method names are UpperCamelCase (PascalCase). Do not prefix class names with `C`. - Test suite naming convention: The Boost test suite in file - `src/test/foo_tests.cpp` should be named `foo_tests`. + `src/test/foo_tests.cpp` should be named `foo_tests`. Test suite names + must be unique. - **Miscellaneous** - `++i` is preferred over `i++`. @@ -450,12 +451,21 @@ C++ data structures - Vector bounds checking is only enabled in debug mode. Do not rely on it -- Make sure that constructors initialize all fields. If this is skipped for a - good reason (i.e., optimization on the critical path), add an explicit - comment about this +- Initialize all non-static class members where they are defined. + If this is skipped for a good reason (i.e., optimization on the critical + path), add an explicit comment about this - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized values. Also, static analyzers balk about this. + Initializing the members in the declaration makes it easy to + spot uninitialized ones. + +```cpp +class A +{ + uint32_t m_count{0}; +} +``` - By default, declare single-argument constructors `explicit`. @@ -474,18 +484,6 @@ C++ data structures - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those that are not language lawyers -- Initialize all non-static class members where they are defined - - - *Rationale*: Initializing the members in the declaration makes it easy to spot uninitialized ones, - and avoids accidentally reading uninitialized memory - -```cpp -class A -{ - uint32_t m_count{0}; -} -``` - Strings and formatting ------------------------ @@ -626,7 +624,7 @@ GUI holds: try to not directly access core data structures from Views. - Avoid adding slow or blocking code in the GUI thread. In particular do not - add new `interface::Node` and `interface::Wallet` method calls, even if they + add new `interfaces::Node` and `interfaces::Wallet` method calls, even if they may be fast now, in case they are changed to lock or communicate across processes in the future. diff --git a/doc/release-notes.md b/doc/release-notes.md index 48ee364c18..0a72f3fe4a 100644 --- a/doc/release-notes.md +++ b/doc/release-notes.md @@ -74,6 +74,7 @@ RPC changes add `label` fields to returned JSON objects that previously only had `account` fields. - `sendmany` now shuffles outputs to improve privacy, so any previously expected behavior with regards to output ordering can no longer be relied upon. +- The new RPC `testmempoolaccept` can be used to test acceptance of a transaction to the mempool without adding it. External wallet files --------------------- diff --git a/src/Makefile.am b/src/Makefile.am index 605c932120..f82248fbed 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -105,9 +105,9 @@ BITCOIN_CORE_H = \ httpserver.h \ indirectmap.h \ init.h \ - interface/handler.h \ - interface/node.h \ - interface/wallet.h \ + interfaces/handler.h \ + interfaces/node.h \ + interfaces/wallet.h \ key.h \ key_io.h \ keystore.h \ @@ -172,7 +172,6 @@ BITCOIN_CORE_H = \ wallet/db.h \ wallet/feebumper.h \ wallet/fees.h \ - wallet/init.h \ wallet/rpcwallet.h \ wallet/wallet.h \ wallet/walletdb.h \ @@ -249,7 +248,7 @@ endif libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_wallet_a_SOURCES = \ - interface/wallet.cpp \ + interfaces/wallet.cpp \ wallet/crypter.cpp \ wallet/db.cpp \ wallet/feebumper.cpp \ @@ -362,8 +361,8 @@ libbitcoin_util_a_SOURCES = \ compat/glibcxx_sanity.cpp \ compat/strnlen.cpp \ fs.cpp \ - interface/handler.cpp \ - interface/node.cpp \ + interfaces/handler.cpp \ + interfaces/node.cpp \ random.cpp \ rpc/protocol.cpp \ rpc/util.cpp \ diff --git a/src/Makefile.test.include b/src/Makefile.test.include index 4d0819ab79..76da140b84 100644 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -94,7 +94,7 @@ BITCOIN_TESTS += \ wallet/test/wallet_test_fixture.h \ wallet/test/accounting_tests.cpp \ wallet/test/wallet_tests.cpp \ - wallet/test/crypto_tests.cpp \ + wallet/test/wallet_crypto_tests.cpp \ wallet/test/coinselector_tests.cpp endif diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index 8d08f413ac..4aa811b86b 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -18,9 +18,6 @@ #include <httpserver.h> #include <httprpc.h> #include <utilstrencodings.h> -#if ENABLE_WALLET -#include <wallet/init.h> -#endif #include <walletinitinterface.h> #include <boost/thread.hpp> @@ -63,12 +60,6 @@ bool AppInit(int argc, char* argv[]) { bool fRet = false; -#if ENABLE_WALLET - g_wallet_init_interface.reset(new WalletInit); -#else - g_wallet_init_interface.reset(new DummyWalletInit); -#endif - // // Parameters // diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp index ca446c92fe..e401b5fb1b 100644 --- a/src/dbwrapper.cpp +++ b/src/dbwrapper.cpp @@ -63,7 +63,7 @@ public: assert(p <= limit); base[std::min(bufsize - 1, (int)(p - base))] = '\0'; - LogPrintf("leveldb: %s", base); + LogPrintf("leveldb: %s", base); /* Continued */ if (base != buffer) { delete[] base; } diff --git a/src/init.cpp b/src/init.cpp index 4bb2bc2c3e..9684b0c702 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -72,7 +72,25 @@ static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false; std::unique_ptr<CConnman> g_connman; std::unique_ptr<PeerLogicValidation> peerLogic; -std::unique_ptr<WalletInitInterface> g_wallet_init_interface; + +#if !(ENABLE_WALLET) +class DummyWalletInit : public WalletInitInterface { +public: + + std::string GetHelpString(bool showDebug) override {return std::string{};} + bool ParameterInteraction() override {return true;} + void RegisterRPC(CRPCTable &) override {} + bool Verify() override {return true;} + bool Open() override {return true;} + void Start(CScheduler& scheduler) override {} + void Flush() override {} + void Stop() override {} + void Close() override {} +}; + +static DummyWalletInit g_dummy_wallet_init; +WalletInitInterface* const g_wallet_init_interface = &g_dummy_wallet_init; +#endif #if ENABLE_ZMQ static CZMQNotificationInterface* pzmqNotificationInterface = nullptr; @@ -266,7 +284,6 @@ void Shutdown() GetMainSignals().UnregisterBackgroundSignalScheduler(); GetMainSignals().UnregisterWithMempoolSignals(mempool); g_wallet_init_interface->Close(); - g_wallet_init_interface.reset(); globalVerifyHandle.reset(); ECC_Stop(); LogPrintf("%s: done\n", __func__); @@ -615,6 +632,7 @@ void ThreadImport(std::vector<fs::path> vImportFiles) { const CChainParams& chainparams = Params(); RenameThread("bitcoin-loadblk"); + ScheduleBatchPriority(); { CImportingNow imp; @@ -1215,7 +1233,7 @@ bool AppInitMain() // Warn about relative -datadir path. if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) { - LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " + LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */ "current working directory '%s'. This is fragile, because if bitcoin is started in the future " "from a different location, it will be unable to locate the current data files. There could " "also be data loss if bitcoin is started while in a temporary directory.\n", diff --git a/src/init.h b/src/init.h index c93a210154..829c110112 100644 --- a/src/init.h +++ b/src/init.h @@ -13,7 +13,7 @@ class CScheduler; class CWallet; class WalletInitInterface; -extern std::unique_ptr<WalletInitInterface> g_wallet_init_interface; +extern WalletInitInterface* const g_wallet_init_interface; namespace boost { diff --git a/src/interface/README.md b/src/interfaces/README.md index e93b91d23c..e93b91d23c 100644 --- a/src/interface/README.md +++ b/src/interfaces/README.md diff --git a/src/interface/handler.cpp b/src/interfaces/handler.cpp index 4b27f374f4..1443fe9f18 100644 --- a/src/interface/handler.cpp +++ b/src/interfaces/handler.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include <interface/handler.h> +#include <interfaces/handler.h> #include <util.h> @@ -10,7 +10,7 @@ #include <memory> #include <utility> -namespace interface { +namespace interfaces { namespace { class HandlerImpl : public Handler @@ -30,4 +30,4 @@ std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection) return MakeUnique<HandlerImpl>(std::move(connection)); } -} // namespace interface +} // namespace interfaces diff --git a/src/interface/handler.h b/src/interfaces/handler.h index a76334bfbf..c4c674cac5 100644 --- a/src/interface/handler.h +++ b/src/interfaces/handler.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_INTERFACE_HANDLER_H -#define BITCOIN_INTERFACE_HANDLER_H +#ifndef BITCOIN_INTERFACES_HANDLER_H +#define BITCOIN_INTERFACES_HANDLER_H #include <memory> @@ -13,7 +13,7 @@ class connection; } // namespace signals2 } // namespace boost -namespace interface { +namespace interfaces { //! Generic interface for managing an event handler or callback function //! registered with another interface. Has a single disconnect method to cancel @@ -30,6 +30,6 @@ public: //! Return handler wrapping a boost signal connection. std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection); -} // namespace interface +} // namespace interfaces -#endif // BITCOIN_INTERFACE_HANDLER_H +#endif // BITCOIN_INTERFACES_HANDLER_H diff --git a/src/interface/node.cpp b/src/interfaces/node.cpp index f04da4e176..919748f942 100644 --- a/src/interface/node.cpp +++ b/src/interfaces/node.cpp @@ -2,15 +2,15 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include <interface/node.h> +#include <interfaces/node.h> #include <addrdb.h> #include <amount.h> #include <chain.h> #include <chainparams.h> #include <init.h> -#include <interface/handler.h> -#include <interface/wallet.h> +#include <interfaces/handler.h> +#include <interfaces/wallet.h> #include <net.h> #include <net_processing.h> #include <netaddress.h> @@ -43,7 +43,7 @@ #include <boost/thread/thread.hpp> #include <univalue.h> -namespace interface { +namespace interfaces { namespace { class NodeImpl : public Node @@ -305,4 +305,4 @@ class NodeImpl : public Node std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); } -} // namespace interface +} // namespace interfaces diff --git a/src/interface/node.h b/src/interfaces/node.h index 6ae7f9e46c..f375af2f19 100644 --- a/src/interface/node.h +++ b/src/interfaces/node.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_INTERFACE_NODE_H -#define BITCOIN_INTERFACE_NODE_H +#ifndef BITCOIN_INTERFACES_NODE_H +#define BITCOIN_INTERFACES_NODE_H #include <addrdb.h> // For banmap_t #include <amount.h> // For CAmount @@ -29,7 +29,7 @@ class proxyType; enum class FeeReason; struct CNodeStateStats; -namespace interface { +namespace interfaces { class Handler; class Wallet; @@ -254,6 +254,6 @@ public: //! Return implementation of Node interface. std::unique_ptr<Node> MakeNode(); -} // namespace interface +} // namespace interfaces -#endif // BITCOIN_INTERFACE_NODE_H +#endif // BITCOIN_INTERFACES_NODE_H diff --git a/src/interface/wallet.cpp b/src/interfaces/wallet.cpp index a6bce7d3de..0244fe70f5 100644 --- a/src/interface/wallet.cpp +++ b/src/interfaces/wallet.cpp @@ -2,12 +2,12 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include <interface/wallet.h> +#include <interfaces/wallet.h> #include <amount.h> #include <chain.h> #include <consensus/validation.h> -#include <interface/handler.h> +#include <interfaces/handler.h> #include <net.h> #include <policy/policy.h> #include <primitives/transaction.h> @@ -24,7 +24,7 @@ #include <memory> -namespace interface { +namespace interfaces { namespace { class PendingWalletTxImpl : public PendingWalletTx @@ -283,7 +283,7 @@ public: return result; } bool tryGetTxStatus(const uint256& txid, - interface::WalletTxStatus& tx_status, + interfaces::WalletTxStatus& tx_status, int& num_blocks, int64_t& adjusted_time) override { @@ -438,4 +438,4 @@ public: std::unique_ptr<Wallet> MakeWallet(CWallet& wallet) { return MakeUnique<WalletImpl>(wallet); } -} // namespace interface +} // namespace interfaces diff --git a/src/interface/wallet.h b/src/interfaces/wallet.h index b66ed63398..3e27242c2c 100644 --- a/src/interface/wallet.h +++ b/src/interfaces/wallet.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_INTERFACE_WALLET_H -#define BITCOIN_INTERFACE_WALLET_H +#ifndef BITCOIN_INTERFACES_WALLET_H +#define BITCOIN_INTERFACES_WALLET_H #include <amount.h> // For CAmount #include <pubkey.h> // For CTxDestination (CKeyID and CScriptID) @@ -27,7 +27,7 @@ class CWallet; enum class OutputType; struct CRecipient; -namespace interface { +namespace interfaces { class Handler; class PendingWalletTx; @@ -347,6 +347,6 @@ struct WalletTxOut //! in builds where ENABLE_WALLET is false. std::unique_ptr<Wallet> MakeWallet(CWallet& wallet); -} // namespace interface +} // namespace interfaces -#endif // BITCOIN_INTERFACE_WALLET_H +#endif // BITCOIN_INTERFACES_WALLET_H diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp index a9408895d9..1e3acd75c0 100644 --- a/src/qt/addresstablemodel.cpp +++ b/src/qt/addresstablemodel.cpp @@ -7,7 +7,7 @@ #include <qt/guiutil.h> #include <qt/walletmodel.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <key_io.h> #include <wallet/wallet.h> @@ -74,7 +74,7 @@ public: AddressTablePriv(AddressTableModel *_parent): parent(_parent) {} - void refreshAddressTable(interface::Wallet& wallet) + void refreshAddressTable(interfaces::Wallet& wallet) { cachedAddressTable.clear(); { diff --git a/src/qt/addresstablemodel.h b/src/qt/addresstablemodel.h index 954f0f593e..d7aeda9d8e 100644 --- a/src/qt/addresstablemodel.h +++ b/src/qt/addresstablemodel.h @@ -13,7 +13,7 @@ enum class OutputType; class AddressTablePriv; class WalletModel; -namespace interface { +namespace interfaces { class Wallet; } diff --git a/src/qt/bantablemodel.cpp b/src/qt/bantablemodel.cpp index cbd67d70ab..26cb03c2c7 100644 --- a/src/qt/bantablemodel.cpp +++ b/src/qt/bantablemodel.cpp @@ -8,7 +8,7 @@ #include <qt/guiconstants.h> #include <qt/guiutil.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <sync.h> #include <utiltime.h> @@ -46,7 +46,7 @@ public: Qt::SortOrder sortOrder; /** Pull a full list of banned nodes from CNode into our cache */ - void refreshBanlist(interface::Node& node) + void refreshBanlist(interfaces::Node& node) { banmap_t banMap; node.getBanned(banMap); @@ -82,7 +82,7 @@ public: } }; -BanTableModel::BanTableModel(interface::Node& node, ClientModel *parent) : +BanTableModel::BanTableModel(interfaces::Node& node, ClientModel *parent) : QAbstractTableModel(parent), m_node(node), clientModel(parent) diff --git a/src/qt/bantablemodel.h b/src/qt/bantablemodel.h index 4c171e6fbe..d6c8dbf6dd 100644 --- a/src/qt/bantablemodel.h +++ b/src/qt/bantablemodel.h @@ -15,7 +15,7 @@ class ClientModel; class BanTablePriv; -namespace interface { +namespace interfaces { class Node; } @@ -45,7 +45,7 @@ class BanTableModel : public QAbstractTableModel Q_OBJECT public: - explicit BanTableModel(interface::Node& node, ClientModel *parent = 0); + explicit BanTableModel(interfaces::Node& node, ClientModel *parent = 0); ~BanTableModel(); void startAutoRefresh(); void stopAutoRefresh(); @@ -71,7 +71,7 @@ public Q_SLOTS: void refresh(); private: - interface::Node& m_node; + interfaces::Node& m_node; ClientModel *clientModel; QStringList columns; std::unique_ptr<BanTablePriv> priv; diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp index a663b61109..599c3c0985 100644 --- a/src/qt/bitcoin.cpp +++ b/src/qt/bitcoin.cpp @@ -27,17 +27,14 @@ #endif #include <init.h> -#include <interface/handler.h> -#include <interface/node.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <rpc/server.h> #include <ui_interface.h> #include <uint256.h> #include <util.h> #include <warnings.h> -#ifdef ENABLE_WALLET -#include <wallet/init.h> -#endif #include <walletinitinterface.h> #include <memory> @@ -182,7 +179,7 @@ class BitcoinCore: public QObject { Q_OBJECT public: - explicit BitcoinCore(interface::Node& node); + explicit BitcoinCore(interfaces::Node& node); public Q_SLOTS: void initialize(); @@ -197,7 +194,7 @@ private: /// Pass fatal exception message to UI thread void handleRunawayException(const std::exception *e); - interface::Node& m_node; + interfaces::Node& m_node; }; /** Main Bitcoin application object */ @@ -205,7 +202,7 @@ class BitcoinApplication: public QApplication { Q_OBJECT public: - explicit BitcoinApplication(interface::Node& node, int &argc, char **argv); + explicit BitcoinApplication(interfaces::Node& node, int &argc, char **argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET @@ -246,7 +243,7 @@ Q_SIGNALS: private: QThread *coreThread; - interface::Node& m_node; + interfaces::Node& m_node; OptionsModel *optionsModel; ClientModel *clientModel; BitcoinGUI *window; @@ -264,7 +261,7 @@ private: #include <qt/bitcoin.moc> -BitcoinCore::BitcoinCore(interface::Node& node) : +BitcoinCore::BitcoinCore(interfaces::Node& node) : QObject(), m_node(node) { } @@ -304,7 +301,7 @@ void BitcoinCore::shutdown() } } -BitcoinApplication::BitcoinApplication(interface::Node& node, int &argc, char **argv): +BitcoinApplication::BitcoinApplication(interfaces::Node& node, int &argc, char **argv): QApplication(argc, argv), coreThread(0), m_node(node), @@ -535,7 +532,7 @@ int main(int argc, char *argv[]) { SetupEnvironment(); - std::unique_ptr<interface::Node> node = interface::MakeNode(); + std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: @@ -660,11 +657,6 @@ int main(int argc, char *argv[]) // Start up the payment server early, too, so impatient users that click on // bitcoin: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); - - // Hook up the wallet init interface - g_wallet_init_interface.reset(new WalletInit); -#else - g_wallet_init_interface.reset(new DummyWalletInit); #endif /// 9. Main GUI initialization @@ -687,7 +679,7 @@ int main(int argc, char *argv[]) app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false)); // Subscribe to global signals from core - std::unique_ptr<interface::Handler> handler = node->handleInitMessage(InitMessage); + std::unique_ptr<interfaces::Handler> handler = node->handleInitMessage(InitMessage); if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index 63a2a200b2..bfa8844a09 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -30,8 +30,8 @@ #include <chainparams.h> #include <init.h> -#include <interface/handler.h> -#include <interface/node.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <ui_interface.h> #include <util.h> @@ -74,7 +74,7 @@ const std::string BitcoinGUI::DEFAULT_UIPLATFORM = #endif ; -BitcoinGUI::BitcoinGUI(interface::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) : +BitcoinGUI::BitcoinGUI(interfaces::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) : QMainWindow(parent), enableWallet(false), m_node(node), diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index 3a4b25d804..e59c71cd4f 100644 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -33,7 +33,7 @@ class WalletModel; class HelpMessageDialog; class ModalOverlay; -namespace interface { +namespace interfaces { class Handler; class Node; } @@ -56,7 +56,7 @@ class BitcoinGUI : public QMainWindow public: static const std::string DEFAULT_UIPLATFORM; - explicit BitcoinGUI(interface::Node& node, const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = 0); + explicit BitcoinGUI(interfaces::Node& node, const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = 0); ~BitcoinGUI(); /** Set the client model. @@ -83,9 +83,9 @@ protected: bool eventFilter(QObject *object, QEvent *event); private: - interface::Node& m_node; - std::unique_ptr<interface::Handler> m_handler_message_box; - std::unique_ptr<interface::Handler> m_handler_question; + interfaces::Node& m_node; + std::unique_ptr<interfaces::Handler> m_handler_message_box; + std::unique_ptr<interfaces::Handler> m_handler_question; ClientModel *clientModel; WalletFrame *walletFrame; diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp index 1dbfc815b6..37fd06ccc9 100644 --- a/src/qt/clientmodel.cpp +++ b/src/qt/clientmodel.cpp @@ -13,8 +13,8 @@ #include <chainparams.h> #include <checkpoints.h> #include <clientversion.h> -#include <interface/handler.h> -#include <interface/node.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <validation.h> #include <net.h> #include <txmempool.h> @@ -32,7 +32,7 @@ class CBlockIndex; static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; -ClientModel::ClientModel(interface::Node& node, OptionsModel *_optionsModel, QObject *parent) : +ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) : QObject(parent), m_node(node), optionsModel(_optionsModel), diff --git a/src/qt/clientmodel.h b/src/qt/clientmodel.h index 9faa10b87e..a609222f7d 100644 --- a/src/qt/clientmodel.h +++ b/src/qt/clientmodel.h @@ -17,7 +17,7 @@ class PeerTableModel; class CBlockIndex; -namespace interface { +namespace interfaces { class Handler; class Node; } @@ -46,10 +46,10 @@ class ClientModel : public QObject Q_OBJECT public: - explicit ClientModel(interface::Node& node, OptionsModel *optionsModel, QObject *parent = 0); + explicit ClientModel(interfaces::Node& node, OptionsModel *optionsModel, QObject *parent = 0); ~ClientModel(); - interface::Node& node() const { return m_node; } + interfaces::Node& node() const { return m_node; } OptionsModel *getOptionsModel(); PeerTableModel *getPeerTableModel(); BanTableModel *getBanTableModel(); @@ -75,14 +75,14 @@ public: mutable std::atomic<int64_t> cachedBestHeaderTime; private: - interface::Node& m_node; - std::unique_ptr<interface::Handler> m_handler_show_progress; - std::unique_ptr<interface::Handler> m_handler_notify_num_connections_changed; - std::unique_ptr<interface::Handler> m_handler_notify_network_active_changed; - std::unique_ptr<interface::Handler> m_handler_notify_alert_changed; - std::unique_ptr<interface::Handler> m_handler_banned_list_changed; - std::unique_ptr<interface::Handler> m_handler_notify_block_tip; - std::unique_ptr<interface::Handler> m_handler_notify_header_tip; + interfaces::Node& m_node; + std::unique_ptr<interfaces::Handler> m_handler_show_progress; + std::unique_ptr<interfaces::Handler> m_handler_notify_num_connections_changed; + std::unique_ptr<interfaces::Handler> m_handler_notify_network_active_changed; + std::unique_ptr<interfaces::Handler> m_handler_notify_alert_changed; + std::unique_ptr<interfaces::Handler> m_handler_banned_list_changed; + std::unique_ptr<interfaces::Handler> m_handler_notify_block_tip; + std::unique_ptr<interfaces::Handler> m_handler_notify_header_tip; OptionsModel *optionsModel; PeerTableModel *peerTableModel; BanTableModel *banTableModel; diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index 2081d6ca08..601a77fc85 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -14,7 +14,7 @@ #include <qt/walletmodel.h> #include <wallet/coincontrol.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <key_io.h> #include <policy/fees.h> #include <policy/policy.h> @@ -648,7 +648,7 @@ void CoinControlDialog::updateView() int nChildren = 0; for (const auto& outpair : coins.second) { const COutPoint& output = std::get<0>(outpair); - const interface::WalletTxOut& out = std::get<1>(outpair); + const interfaces::WalletTxOut& out = std::get<1>(outpair); nSum += out.txout.nValue; nChildren++; diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp index 5bf1b5cf59..563f930dec 100644 --- a/src/qt/guiutil.cpp +++ b/src/qt/guiutil.cpp @@ -13,7 +13,7 @@ #include <chainparams.h> #include <primitives/transaction.h> #include <key_io.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <policy/policy.h> #include <protocol.h> #include <script/script.h> @@ -232,7 +232,7 @@ QString formatBitcoinURI(const SendCoinsRecipient &info) return ret; } -bool isDust(interface::Node& node, const QString& address, const CAmount& amount) +bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount) { CTxDestination dest = DecodeDestination(address.toStdString()); CScript script = GetScriptForDestination(dest); diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h index 40037edb9d..4a26964098 100644 --- a/src/qt/guiutil.h +++ b/src/qt/guiutil.h @@ -20,7 +20,7 @@ class QValidatedLineEdit; class SendCoinsRecipient; -namespace interface +namespace interfaces { class Node; } @@ -54,7 +54,7 @@ namespace GUIUtil QString formatBitcoinURI(const SendCoinsRecipient &info); // Returns true if given address+amount meets "dust" definition - bool isDust(interface::Node& node, const QString& address, const CAmount& amount); + bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount); // HTML escaping for rich text controls QString HtmlEscape(const QString& str, bool fMultiLine=false); diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp index 4eb7482018..8c00ca0363 100644 --- a/src/qt/intro.cpp +++ b/src/qt/intro.cpp @@ -12,7 +12,7 @@ #include <qt/guiutil.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <util.h> #include <QFileDialog> @@ -187,7 +187,7 @@ QString Intro::getDefaultDataDirectory() return GUIUtil::boostPathToQString(GetDefaultDataDir()); } -bool Intro::pickDataDirectory(interface::Node& node) +bool Intro::pickDataDirectory(interfaces::Node& node) { QSettings settings; /* If data directory provided on command line, no need to look at settings diff --git a/src/qt/intro.h b/src/qt/intro.h index 07d2025bb6..b0937aedcb 100644 --- a/src/qt/intro.h +++ b/src/qt/intro.h @@ -13,7 +13,7 @@ static const bool DEFAULT_CHOOSE_DATADIR = false; class FreespaceChecker; -namespace interface { +namespace interfaces { class Node; } @@ -45,7 +45,7 @@ public: * @note do NOT call global GetDataDir() before calling this function, this * will cause the wrong path to be cached. */ - static bool pickDataDirectory(interface::Node& node); + static bool pickDataDirectory(interfaces::Node& node); /** * Determine default data directory for operating system. diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp index 438e9e70f1..c0ddb89b40 100644 --- a/src/qt/optionsdialog.cpp +++ b/src/qt/optionsdialog.cpp @@ -13,7 +13,7 @@ #include <qt/guiutil.h> #include <qt/optionsmodel.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <validation.h> // for DEFAULT_SCRIPTCHECK_THREADS and MAX_SCRIPTCHECK_THREADS #include <netbase.h> #include <txdb.h> // for -dbcache defaults diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index d8197b6ec6..30c8124c58 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -11,7 +11,7 @@ #include <qt/bitcoinunits.h> #include <qt/guiutil.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <validation.h> // For DEFAULT_SCRIPTCHECK_THREADS #include <net.h> #include <netbase.h> @@ -24,7 +24,7 @@ const char *DEFAULT_GUI_PROXY_HOST = "127.0.0.1"; -OptionsModel::OptionsModel(interface::Node& node, QObject *parent, bool resetSettings) : +OptionsModel::OptionsModel(interfaces::Node& node, QObject *parent, bool resetSettings) : QAbstractListModel(parent), m_node(node) { Init(resetSettings); diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h index 96c6b8fa45..fc1d119a71 100644 --- a/src/qt/optionsmodel.h +++ b/src/qt/optionsmodel.h @@ -9,7 +9,7 @@ #include <QAbstractListModel> -namespace interface { +namespace interfaces { class Node; } @@ -31,7 +31,7 @@ class OptionsModel : public QAbstractListModel Q_OBJECT public: - explicit OptionsModel(interface::Node& node, QObject *parent = 0, bool resetSettings = false); + explicit OptionsModel(interfaces::Node& node, QObject *parent = 0, bool resetSettings = false); enum OptionID { StartAtStartup, // bool @@ -79,10 +79,10 @@ public: void setRestartRequired(bool fRequired); bool isRestartRequired() const; - interface::Node& node() const { return m_node; } + interfaces::Node& node() const { return m_node; } private: - interface::Node& m_node; + interfaces::Node& m_node; /* Qt-only settings */ bool fHideTrayIcon; bool fMinimizeToTray; diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index 76d0220648..8e8788dad3 100644 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -21,7 +21,7 @@ #define DECORATION_SIZE 54 #define NUM_ITEMS 5 -Q_DECLARE_METATYPE(interface::WalletBalances) +Q_DECLARE_METATYPE(interfaces::WalletBalances) class TxViewDelegate : public QAbstractItemDelegate { @@ -157,7 +157,7 @@ OverviewPage::~OverviewPage() delete ui; } -void OverviewPage::setBalance(const interface::WalletBalances& balances) +void OverviewPage::setBalance(const interfaces::WalletBalances& balances) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); m_balances = balances; @@ -224,10 +224,10 @@ void OverviewPage::setWalletModel(WalletModel *model) ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet - interface::Wallet& wallet = model->wallet(); - interface::WalletBalances balances = wallet.getBalances(); + interfaces::Wallet& wallet = model->wallet(); + interfaces::WalletBalances balances = wallet.getBalances(); setBalance(balances); - connect(model, SIGNAL(balanceChanged(interface::WalletBalances)), this, SLOT(setBalance(interface::WalletBalances))); + connect(model, SIGNAL(balanceChanged(interfaces::WalletBalances)), this, SLOT(setBalance(interfaces::WalletBalances))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); diff --git a/src/qt/overviewpage.h b/src/qt/overviewpage.h index 36333536e5..d519eca43a 100644 --- a/src/qt/overviewpage.h +++ b/src/qt/overviewpage.h @@ -5,7 +5,7 @@ #ifndef BITCOIN_QT_OVERVIEWPAGE_H #define BITCOIN_QT_OVERVIEWPAGE_H -#include <interface/wallet.h> +#include <interfaces/wallet.h> #include <QWidget> #include <memory> @@ -38,7 +38,7 @@ public: void showOutOfSyncWarning(bool fShow); public Q_SLOTS: - void setBalance(const interface::WalletBalances& balances); + void setBalance(const interfaces::WalletBalances& balances); Q_SIGNALS: void transactionClicked(const QModelIndex &index); @@ -48,7 +48,7 @@ private: Ui::OverviewPage *ui; ClientModel *clientModel; WalletModel *walletModel; - interface::WalletBalances m_balances; + interfaces::WalletBalances m_balances; TxViewDelegate *txdelegate; std::unique_ptr<TransactionFilterProxy> filter; diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp index 926a699754..70cdb3361c 100644 --- a/src/qt/paymentserver.cpp +++ b/src/qt/paymentserver.cpp @@ -9,7 +9,7 @@ #include <qt/optionsmodel.h> #include <chainparams.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <policy/policy.h> #include <key_io.h> #include <ui_interface.h> @@ -201,7 +201,7 @@ void PaymentServer::LoadRootCAs(X509_STORE* _store) // Warning: ipcSendCommandLine() is called early in init, // so don't use "Q_EMIT message()", but "QMessageBox::"! // -void PaymentServer::ipcParseCommandLine(interface::Node& node, int argc, char* argv[]) +void PaymentServer::ipcParseCommandLine(interfaces::Node& node, int argc, char* argv[]) { for (int i = 1; i < argc; i++) { @@ -760,7 +760,7 @@ void PaymentServer::handlePaymentACK(const QString& paymentACKMsg) Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL); } -bool PaymentServer::verifyNetwork(interface::Node& node, const payments::PaymentDetails& requestDetails) +bool PaymentServer::verifyNetwork(interfaces::Node& node, const payments::PaymentDetails& requestDetails) { bool fVerified = requestDetails.network() == node.getNetwork(); if (!fVerified) { diff --git a/src/qt/paymentserver.h b/src/qt/paymentserver.h index e139899e22..511fc5bd6e 100644 --- a/src/qt/paymentserver.h +++ b/src/qt/paymentserver.h @@ -60,7 +60,7 @@ class PaymentServer : public QObject public: // Parse URIs on command line // Returns false on error - static void ipcParseCommandLine(interface::Node& node, int argc, char *argv[]); + static void ipcParseCommandLine(interfaces::Node& node, int argc, char *argv[]); // Returns true if there were URIs on the command line // which were successfully sent to an already-running @@ -87,7 +87,7 @@ public: void setOptionsModel(OptionsModel *optionsModel); // Verify that the payment request network matches the client network - static bool verifyNetwork(interface::Node& node, const payments::PaymentDetails& requestDetails); + static bool verifyNetwork(interfaces::Node& node, const payments::PaymentDetails& requestDetails); // Verify if the payment request is expired static bool verifyExpired(const payments::PaymentDetails& requestDetails); // Verify the payment request size is valid as per BIP70 diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp index f33db8e761..7e318e3035 100644 --- a/src/qt/peertablemodel.cpp +++ b/src/qt/peertablemodel.cpp @@ -8,7 +8,7 @@ #include <qt/guiconstants.h> #include <qt/guiutil.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <validation.h> // for cs_main #include <sync.h> @@ -57,12 +57,12 @@ public: std::map<NodeId, int> mapNodeRows; /** Pull a full list of peers from vNodes into our cache */ - void refreshPeers(interface::Node& node) + void refreshPeers(interfaces::Node& node) { { cachedNodeStats.clear(); - interface::Node::NodesStats nodes_stats; + interfaces::Node::NodesStats nodes_stats; node.getNodesStats(nodes_stats); #if QT_VERSION >= 0x040700 cachedNodeStats.reserve(nodes_stats.size()); @@ -102,7 +102,7 @@ public: } }; -PeerTableModel::PeerTableModel(interface::Node& node, ClientModel *parent) : +PeerTableModel::PeerTableModel(interfaces::Node& node, ClientModel *parent) : QAbstractTableModel(parent), m_node(node), clientModel(parent), diff --git a/src/qt/peertablemodel.h b/src/qt/peertablemodel.h index c53462c57c..69c9744c8f 100644 --- a/src/qt/peertablemodel.h +++ b/src/qt/peertablemodel.h @@ -16,7 +16,7 @@ class ClientModel; class PeerTablePriv; -namespace interface { +namespace interfaces { class Node; } @@ -51,7 +51,7 @@ class PeerTableModel : public QAbstractTableModel Q_OBJECT public: - explicit PeerTableModel(interface::Node& node, ClientModel *parent = 0); + explicit PeerTableModel(interfaces::Node& node, ClientModel *parent = 0); ~PeerTableModel(); const CNodeCombinedStats *getNodeStats(int idx); int getRowByNodeId(NodeId nodeid); @@ -82,7 +82,7 @@ public Q_SLOTS: void refresh(); private: - interface::Node& m_node; + interfaces::Node& m_node; ClientModel *clientModel; QStringList columns; std::unique_ptr<PeerTablePriv> priv; diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp index 745055b944..5122bab36f 100644 --- a/src/qt/rpcconsole.cpp +++ b/src/qt/rpcconsole.cpp @@ -14,7 +14,7 @@ #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <chainparams.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <netbase.h> #include <rpc/server.h> #include <rpc/client.h> @@ -85,7 +85,7 @@ class RPCExecutor : public QObject { Q_OBJECT public: - RPCExecutor(interface::Node& node) : m_node(node) {} + RPCExecutor(interfaces::Node& node) : m_node(node) {} public Q_SLOTS: void request(const QString &command, const QString &walletID); @@ -94,7 +94,7 @@ Q_SIGNALS: void reply(int category, const QString &command); private: - interface::Node& m_node; + interfaces::Node& m_node; }; /** Class for handling RPC timers @@ -153,7 +153,7 @@ public: * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data */ -bool RPCConsole::RPCParseCommandLine(interface::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const std::string *walletID) +bool RPCConsole::RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const std::string *walletID) { std::vector< std::vector<std::string> > stack; stack.push_back(std::vector<std::string>()); @@ -451,7 +451,7 @@ void RPCExecutor::request(const QString &command, const QString &walletID) } } -RPCConsole::RPCConsole(interface::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) : +RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) : QWidget(parent), m_node(node), ui(new Ui::RPCConsole), @@ -575,7 +575,7 @@ void RPCConsole::setClientModel(ClientModel *model) setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); - interface::Node& node = clientModel->node(); + interfaces::Node& node = clientModel->node(); setNumBlocks(node.getNumBlocks(), QDateTime::fromTime_t(node.getLastBlockTime()), node.getVerificationProgress(), false); connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool))); diff --git a/src/qt/rpcconsole.h b/src/qt/rpcconsole.h index 8381301759..a9a60d09f1 100644 --- a/src/qt/rpcconsole.h +++ b/src/qt/rpcconsole.h @@ -19,7 +19,7 @@ class PlatformStyle; class RPCTimerInterface; class WalletModel; -namespace interface { +namespace interfaces { class Node; } @@ -38,11 +38,11 @@ class RPCConsole: public QWidget Q_OBJECT public: - explicit RPCConsole(interface::Node& node, const PlatformStyle *platformStyle, QWidget *parent); + explicit RPCConsole(interfaces::Node& node, const PlatformStyle *platformStyle, QWidget *parent); ~RPCConsole(); - static bool RPCParseCommandLine(interface::Node* node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr); - static bool RPCExecuteCommandLine(interface::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr) { + static bool RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr); + static bool RPCExecuteCommandLine(interfaces::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr) { return RPCParseCommandLine(&node, strResult, strCommand, true, pstrFilteredOut, walletID); } @@ -144,7 +144,7 @@ private: }; - interface::Node& m_node; + interfaces::Node& m_node; Ui::RPCConsole *ui; ClientModel *clientModel; QStringList history; diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp index b4c1471a4f..0874a0ada4 100644 --- a/src/qt/sendcoinsdialog.cpp +++ b/src/qt/sendcoinsdialog.cpp @@ -15,7 +15,7 @@ #include <qt/sendcoinsentry.h> #include <chainparams.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <key_io.h> #include <wallet/coincontrol.h> #include <ui_interface.h> @@ -149,9 +149,9 @@ void SendCoinsDialog::setModel(WalletModel *_model) } } - interface::WalletBalances balances = _model->wallet().getBalances(); + interfaces::WalletBalances balances = _model->wallet().getBalances(); setBalance(balances); - connect(_model, SIGNAL(balanceChanged(interface::WalletBalances)), this, SLOT(setBalance(interface::WalletBalances))); + connect(_model, SIGNAL(balanceChanged(interfaces::WalletBalances)), this, SLOT(setBalance(interfaces::WalletBalances))); connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); @@ -515,7 +515,7 @@ bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv) return true; } -void SendCoinsDialog::setBalance(const interface::WalletBalances& balances) +void SendCoinsDialog::setBalance(const interfaces::WalletBalances& balances) { if(model && model->getOptionsModel()) { diff --git a/src/qt/sendcoinsdialog.h b/src/qt/sendcoinsdialog.h index 43757e3186..40a1d10c2b 100644 --- a/src/qt/sendcoinsdialog.h +++ b/src/qt/sendcoinsdialog.h @@ -51,7 +51,7 @@ public Q_SLOTS: void accept(); SendCoinsEntry *addEntry(); void updateTabsAndLabels(); - void setBalance(const interface::WalletBalances& balances); + void setBalance(const interfaces::WalletBalances& balances); Q_SIGNALS: void coinsSent(const uint256& txid); diff --git a/src/qt/sendcoinsentry.cpp b/src/qt/sendcoinsentry.cpp index 6a961d83ea..977425f7e3 100644 --- a/src/qt/sendcoinsentry.cpp +++ b/src/qt/sendcoinsentry.cpp @@ -127,7 +127,7 @@ void SendCoinsEntry::useAvailableBalanceClicked() Q_EMIT useAvailableBalance(this); } -bool SendCoinsEntry::validate(interface::Node& node) +bool SendCoinsEntry::validate(interfaces::Node& node) { if (!model) return false; diff --git a/src/qt/sendcoinsentry.h b/src/qt/sendcoinsentry.h index 715f4cfde5..76f96c61e0 100644 --- a/src/qt/sendcoinsentry.h +++ b/src/qt/sendcoinsentry.h @@ -30,7 +30,7 @@ public: ~SendCoinsEntry(); void setModel(WalletModel *model); - bool validate(interface::Node& node); + bool validate(interfaces::Node& node); SendCoinsRecipient getValue(); /** Return whether the entry is still empty and unedited */ diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp index 2475a82ef9..4d972b431c 100644 --- a/src/qt/splashscreen.cpp +++ b/src/qt/splashscreen.cpp @@ -12,9 +12,9 @@ #include <clientversion.h> #include <init.h> -#include <interface/handler.h> -#include <interface/node.h> -#include <interface/wallet.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> +#include <interfaces/wallet.h> #include <util.h> #include <ui_interface.h> #include <version.h> @@ -25,7 +25,7 @@ #include <QPainter> #include <QRadialGradient> -SplashScreen::SplashScreen(interface::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) : +SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0), m_node(node) { // set reference point, paddings @@ -177,7 +177,7 @@ static void ShowProgress(SplashScreen *splash, const std::string &title, int nPr strprintf("\n%d", nProgress) + "%"); } #ifdef ENABLE_WALLET -void SplashScreen::ConnectWallet(std::unique_ptr<interface::Wallet> wallet) +void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet) { m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2, false))); m_connected_wallets.emplace_back(std::move(wallet)); @@ -190,7 +190,7 @@ void SplashScreen::subscribeToCoreSignals() m_handler_init_message = m_node.handleInitMessage(boost::bind(InitMessage, this, _1)); m_handler_show_progress = m_node.handleShowProgress(boost::bind(ShowProgress, this, _1, _2, _3)); #ifdef ENABLE_WALLET - m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interface::Wallet> wallet) { ConnectWallet(std::move(wallet)); }); + m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { ConnectWallet(std::move(wallet)); }); #endif } diff --git a/src/qt/splashscreen.h b/src/qt/splashscreen.h index 419f36f641..9ef19675d8 100644 --- a/src/qt/splashscreen.h +++ b/src/qt/splashscreen.h @@ -12,7 +12,7 @@ class NetworkStyle; -namespace interface { +namespace interfaces { class Handler; class Node; class Wallet; @@ -29,7 +29,7 @@ class SplashScreen : public QWidget Q_OBJECT public: - explicit SplashScreen(interface::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle); + explicit SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle); ~SplashScreen(); protected: @@ -52,19 +52,19 @@ private: /** Disconnect core signals to splash screen */ void unsubscribeFromCoreSignals(); /** Connect wallet signals to splash screen */ - void ConnectWallet(std::unique_ptr<interface::Wallet> wallet); + void ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet); QPixmap pixmap; QString curMessage; QColor curColor; int curAlignment; - interface::Node& m_node; - std::unique_ptr<interface::Handler> m_handler_init_message; - std::unique_ptr<interface::Handler> m_handler_show_progress; - std::unique_ptr<interface::Handler> m_handler_load_wallet; - std::list<std::unique_ptr<interface::Wallet>> m_connected_wallets; - std::list<std::unique_ptr<interface::Handler>> m_connected_wallet_handlers; + interfaces::Node& m_node; + std::unique_ptr<interfaces::Handler> m_handler_init_message; + std::unique_ptr<interfaces::Handler> m_handler_show_progress; + std::unique_ptr<interfaces::Handler> m_handler_load_wallet; + std::list<std::unique_ptr<interfaces::Wallet>> m_connected_wallets; + std::list<std::unique_ptr<interfaces::Handler>> m_connected_wallet_handlers; }; #endif // BITCOIN_QT_SPLASHSCREEN_H diff --git a/src/qt/test/paymentservertests.cpp b/src/qt/test/paymentservertests.cpp index 46e9d4d0a4..83484b5ce7 100644 --- a/src/qt/test/paymentservertests.cpp +++ b/src/qt/test/paymentservertests.cpp @@ -9,7 +9,7 @@ #include <amount.h> #include <chainparams.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <random.h> #include <script/script.h> #include <script/standard.h> @@ -67,7 +67,7 @@ static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsig void PaymentServerTests::paymentServerTests() { SelectParams(CBaseChainParams::MAIN); - auto node = interface::MakeNode(); + auto node = interfaces::MakeNode(); OptionsModel optionsModel(*node); PaymentServer* server = new PaymentServer(nullptr, false); X509_STORE* caStore = X509_STORE_new(); diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp index 467107dc4c..974e7831c4 100644 --- a/src/qt/test/rpcnestedtests.cpp +++ b/src/qt/test/rpcnestedtests.cpp @@ -7,7 +7,7 @@ #include <chainparams.h> #include <consensus/validation.h> #include <fs.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <validation.h> #include <rpc/register.h> #include <rpc/server.h> @@ -46,7 +46,7 @@ void RPCNestedTests::rpcNestedTests() std::string result; std::string result2; std::string filtered; - auto node = interface::MakeNode(); + auto node = interfaces::MakeNode(); RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path QVERIFY(result=="main"); QVERIFY(filtered == "getblockchaininfo()[chain]"); diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp index b60c5b979f..fb86cf5ec9 100644 --- a/src/qt/test/wallettests.cpp +++ b/src/qt/test/wallettests.cpp @@ -1,6 +1,6 @@ #include <qt/test/wallettests.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <qt/bitcoinamountfield.h> #include <qt/callback.h> #include <qt/optionsmodel.h> @@ -178,7 +178,7 @@ void TestGUI() std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); SendCoinsDialog sendCoinsDialog(platformStyle.get()); TransactionView transactionView(platformStyle.get()); - auto node = interface::MakeNode(); + auto node = interfaces::MakeNode(); OptionsModel optionsModel(*node); vpwallets.insert(vpwallets.begin(), &wallet); WalletModel walletModel(std::move(node->getWallets()[0]), *node, platformStyle.get(), &optionsModel); diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp index ff378ed1bf..5a3b645f65 100644 --- a/src/qt/trafficgraphwidget.cpp +++ b/src/qt/trafficgraphwidget.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include <interface/node.h> +#include <interfaces/node.h> #include <qt/trafficgraphwidget.h> #include <qt/clientmodel.h> diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp index 409835592f..f316c3ca45 100644 --- a/src/qt/transactiondesc.cpp +++ b/src/qt/transactiondesc.cpp @@ -10,7 +10,7 @@ #include <qt/transactionrecord.h> #include <consensus/consensus.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <key_io.h> #include <validation.h> #include <script/script.h> @@ -23,7 +23,7 @@ #include <stdint.h> #include <string> -QString TransactionDesc::FormatTxStatus(const interface::WalletTx& wtx, const interface::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime) +QString TransactionDesc::FormatTxStatus(const interfaces::WalletTx& wtx, const interfaces::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime) { if (!status.is_final) { @@ -48,14 +48,14 @@ QString TransactionDesc::FormatTxStatus(const interface::WalletTx& wtx, const in } } -QString TransactionDesc::toHTML(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit) +QString TransactionDesc::toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit) { int numBlocks; int64_t adjustedTime; - interface::WalletTxStatus status; - interface::WalletOrderForm orderForm; + interfaces::WalletTxStatus status; + interfaces::WalletOrderForm orderForm; bool inMempool; - interface::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime); + interfaces::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime); QString strHTML; diff --git a/src/qt/transactiondesc.h b/src/qt/transactiondesc.h index ea9ab28ee3..cb8453cb81 100644 --- a/src/qt/transactiondesc.h +++ b/src/qt/transactiondesc.h @@ -10,7 +10,7 @@ class TransactionRecord; -namespace interface { +namespace interfaces { class Node; class Wallet; struct WalletTx; @@ -24,12 +24,12 @@ class TransactionDesc: public QObject Q_OBJECT public: - static QString toHTML(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit); + static QString toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit); private: TransactionDesc() {} - static QString FormatTxStatus(const interface::WalletTx& wtx, const interface::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime); + static QString FormatTxStatus(const interfaces::WalletTx& wtx, const interfaces::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime); }; #endif // BITCOIN_QT_TRANSACTIONDESC_H diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp index 60ab2d57d7..b6ed66ad96 100644 --- a/src/qt/transactionrecord.cpp +++ b/src/qt/transactionrecord.cpp @@ -5,7 +5,7 @@ #include <qt/transactionrecord.h> #include <consensus/consensus.h> -#include <interface/wallet.h> +#include <interfaces/wallet.h> #include <key_io.h> #include <timedata.h> #include <validation.h> @@ -25,7 +25,7 @@ bool TransactionRecord::showTransaction() /* * Decompose CWallet transaction to model transaction records. */ -QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interface::WalletTx& wtx) +QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interfaces::WalletTx& wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.time; @@ -158,7 +158,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interface return parts; } -void TransactionRecord::updateStatus(const interface::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime) +void TransactionRecord::updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime) { // Determine transaction status diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h index c653584b52..62961434ed 100644 --- a/src/qt/transactionrecord.h +++ b/src/qt/transactionrecord.h @@ -11,7 +11,7 @@ #include <QList> #include <QString> -namespace interface { +namespace interfaces { class Node; class Wallet; struct WalletTx; @@ -111,7 +111,7 @@ public: /** Decompose CWallet transaction to model transaction records. */ static bool showTransaction(); - static QList<TransactionRecord> decomposeTransaction(const interface::WalletTx& wtx); + static QList<TransactionRecord> decomposeTransaction(const interfaces::WalletTx& wtx); /** @name Immutable transaction attributes @{*/ @@ -140,7 +140,7 @@ public: /** Update status from core wallet tx. */ - void updateStatus(const interface::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime); + void updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime); /** Return whether a status update is needed. */ diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp index 2148ff1728..46169a91d1 100644 --- a/src/qt/transactiontablemodel.cpp +++ b/src/qt/transactiontablemodel.cpp @@ -14,8 +14,8 @@ #include <qt/walletmodel.h> #include <core_io.h> -#include <interface/handler.h> -#include <interface/node.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <validation.h> #include <sync.h> #include <uint256.h> @@ -73,7 +73,7 @@ public: /* Query entire wallet anew from core. */ - void refreshWallet(interface::Wallet& wallet) + void refreshWallet(interfaces::Wallet& wallet) { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); @@ -91,7 +91,7 @@ public: Call with transaction that was added, removed or changed. */ - void updateWallet(interface::Wallet& wallet, const uint256 &hash, int status, bool showTransaction) + void updateWallet(interfaces::Wallet& wallet, const uint256 &hash, int status, bool showTransaction) { qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status); @@ -127,7 +127,7 @@ public: if(showTransaction) { // Find transaction in wallet - interface::WalletTx wtx = wallet.getWalletTx(hash); + interfaces::WalletTx wtx = wallet.getWalletTx(hash); if(!wtx.tx) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet"; @@ -176,7 +176,7 @@ public: return cachedWallet.size(); } - TransactionRecord *index(interface::Wallet& wallet, int idx) + TransactionRecord *index(interfaces::Wallet& wallet, int idx) { if(idx >= 0 && idx < cachedWallet.size()) { @@ -189,7 +189,7 @@ public: // If a status update is needed (blocks came in since last check), // update the status of this transaction from the wallet. Otherwise, // simply re-use the cached status. - interface::WalletTxStatus wtx; + interfaces::WalletTxStatus wtx; int numBlocks; int64_t adjustedTime; if (wallet.tryGetTxStatus(rec->hash, wtx, numBlocks, adjustedTime) && rec->statusUpdateNeeded(numBlocks)) { @@ -200,12 +200,12 @@ public: return 0; } - QString describe(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit) + QString describe(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit) { return TransactionDesc::toHTML(node, wallet, rec, unit); } - QString getTxHex(interface::Wallet& wallet, TransactionRecord *rec) + QString getTxHex(interfaces::Wallet& wallet, TransactionRecord *rec) { auto tx = wallet.getTx(rec->hash); if (tx) { diff --git a/src/qt/transactiontablemodel.h b/src/qt/transactiontablemodel.h index 57566db638..8b029be5f5 100644 --- a/src/qt/transactiontablemodel.h +++ b/src/qt/transactiontablemodel.h @@ -12,7 +12,7 @@ #include <memory> -namespace interface { +namespace interfaces { class Handler; } @@ -85,8 +85,8 @@ public: private: WalletModel *walletModel; - std::unique_ptr<interface::Handler> m_handler_transaction_changed; - std::unique_ptr<interface::Handler> m_handler_show_progress; + std::unique_ptr<interfaces::Handler> m_handler_transaction_changed; + std::unique_ptr<interfaces::Handler> m_handler_show_progress; QStringList columns; TransactionTablePriv *priv; bool fProcessingQueuedTransactions; diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp index 6114ea0de1..d5b98486ae 100644 --- a/src/qt/utilitydialog.cpp +++ b/src/qt/utilitydialog.cpp @@ -19,7 +19,7 @@ #include <clientversion.h> #include <init.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <util.h> #include <stdio.h> @@ -32,7 +32,7 @@ #include <QVBoxLayout> /** "Help message" or "About" dialog box */ -HelpMessageDialog::HelpMessageDialog(interface::Node& node, QWidget *parent, bool about) : +HelpMessageDialog::HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about) : QDialog(parent), ui(new Ui::HelpMessageDialog) { diff --git a/src/qt/utilitydialog.h b/src/qt/utilitydialog.h index e6ad7be5d0..f5c8af4362 100644 --- a/src/qt/utilitydialog.h +++ b/src/qt/utilitydialog.h @@ -10,7 +10,7 @@ class BitcoinGUI; -namespace interface { +namespace interfaces { class Node; } @@ -24,7 +24,7 @@ class HelpMessageDialog : public QDialog Q_OBJECT public: - explicit HelpMessageDialog(interface::Node& node, QWidget *parent, bool about); + explicit HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about); ~HelpMessageDialog(); void printToConsole(); diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index d9db437dc5..00b98901c0 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -12,8 +12,8 @@ #include <qt/sendcoinsdialog.h> #include <qt/transactiontablemodel.h> -#include <interface/handler.h> -#include <interface/node.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <key_io.h> #include <ui_interface.h> #include <util.h> // for GetBoolArg @@ -28,7 +28,7 @@ #include <QTimer> -WalletModel::WalletModel(std::unique_ptr<interface::Wallet> wallet, interface::Node& node, const PlatformStyle *platformStyle, OptionsModel *_optionsModel, QObject *parent) : +WalletModel::WalletModel(std::unique_ptr<interfaces::Wallet> wallet, interfaces::Node& node, const PlatformStyle *platformStyle, OptionsModel *_optionsModel, QObject *parent) : QObject(parent), m_wallet(std::move(wallet)), m_node(node), optionsModel(_optionsModel), addressTableModel(0), transactionTableModel(0), recentRequestsTableModel(0), @@ -70,7 +70,7 @@ void WalletModel::pollBalanceChanged() // avoids the GUI from getting stuck on periodical polls if the core is // holding the locks for a longer time - for example, during a wallet // rescan. - interface::WalletBalances new_balances; + interfaces::WalletBalances new_balances; int numBlocks = -1; if (!m_wallet->tryGetBalances(new_balances, numBlocks)) { return; @@ -89,7 +89,7 @@ void WalletModel::pollBalanceChanged() } } -void WalletModel::checkBalanceChanged(const interface::WalletBalances& new_balances) +void WalletModel::checkBalanceChanged(const interfaces::WalletBalances& new_balances) { if(new_balances.balanceChanged(m_cached_balances)) { m_cached_balances = new_balances; diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index bc409b10ee..e5ed5b4e82 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -13,7 +13,7 @@ #include <qt/paymentrequestplus.h> #include <qt/walletmodeltransaction.h> -#include <interface/wallet.h> +#include <interfaces/wallet.h> #include <support/allocators/secure.h> #include <map> @@ -37,9 +37,9 @@ class COutput; class CPubKey; class uint256; -namespace interface { +namespace interfaces { class Node; -} // namespace interface +} // namespace interfaces QT_BEGIN_NAMESPACE class QTimer; @@ -111,7 +111,7 @@ class WalletModel : public QObject Q_OBJECT public: - explicit WalletModel(std::unique_ptr<interface::Wallet> wallet, interface::Node& node, const PlatformStyle *platformStyle, OptionsModel *optionsModel, QObject *parent = 0); + explicit WalletModel(std::unique_ptr<interfaces::Wallet> wallet, interfaces::Node& node, const PlatformStyle *platformStyle, OptionsModel *optionsModel, QObject *parent = 0); ~WalletModel(); enum StatusCode // Returned by sendCoins @@ -198,20 +198,20 @@ public: static bool isWalletEnabled(); - interface::Node& node() const { return m_node; } - interface::Wallet& wallet() const { return *m_wallet; } + interfaces::Node& node() const { return m_node; } + interfaces::Wallet& wallet() const { return *m_wallet; } QString getWalletName() const; bool isMultiwallet(); private: - std::unique_ptr<interface::Wallet> m_wallet; - std::unique_ptr<interface::Handler> m_handler_status_changed; - std::unique_ptr<interface::Handler> m_handler_address_book_changed; - std::unique_ptr<interface::Handler> m_handler_transaction_changed; - std::unique_ptr<interface::Handler> m_handler_show_progress; - std::unique_ptr<interface::Handler> m_handler_watch_only_changed; - interface::Node& m_node; + std::unique_ptr<interfaces::Wallet> m_wallet; + std::unique_ptr<interfaces::Handler> m_handler_status_changed; + std::unique_ptr<interfaces::Handler> m_handler_address_book_changed; + std::unique_ptr<interfaces::Handler> m_handler_transaction_changed; + std::unique_ptr<interfaces::Handler> m_handler_show_progress; + std::unique_ptr<interfaces::Handler> m_handler_watch_only_changed; + interfaces::Node& m_node; bool fHaveWatchOnly; bool fForceCheckBalanceChanged; @@ -225,7 +225,7 @@ private: RecentRequestsTableModel *recentRequestsTableModel; // Cache some values to be able to detect changes - interface::WalletBalances m_cached_balances; + interfaces::WalletBalances m_cached_balances; EncryptionStatus cachedEncryptionStatus; int cachedNumBlocks; @@ -233,11 +233,11 @@ private: void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); - void checkBalanceChanged(const interface::WalletBalances& new_balances); + void checkBalanceChanged(const interfaces::WalletBalances& new_balances); Q_SIGNALS: // Signal that balance in wallet changed - void balanceChanged(const interface::WalletBalances& balances); + void balanceChanged(const interfaces::WalletBalances& balances); // Encryption status of wallet changed void encryptionStatusChanged(); diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp index 21bdfe3818..d5187d6634 100644 --- a/src/qt/walletmodeltransaction.cpp +++ b/src/qt/walletmodeltransaction.cpp @@ -4,7 +4,7 @@ #include <qt/walletmodeltransaction.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <policy/policy.h> WalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient> &_recipients) : @@ -18,7 +18,7 @@ QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const return recipients; } -std::unique_ptr<interface::PendingWalletTx>& WalletModelTransaction::getWtx() +std::unique_ptr<interfaces::PendingWalletTx>& WalletModelTransaction::getWtx() { return wtx; } diff --git a/src/qt/walletmodeltransaction.h b/src/qt/walletmodeltransaction.h index 32fd0d2110..9f91326109 100644 --- a/src/qt/walletmodeltransaction.h +++ b/src/qt/walletmodeltransaction.h @@ -13,7 +13,7 @@ class SendCoinsRecipient; -namespace interface { +namespace interfaces { class Node; class PendingWalletTx; } @@ -26,7 +26,7 @@ public: QList<SendCoinsRecipient> getRecipients() const; - std::unique_ptr<interface::PendingWalletTx>& getWtx(); + std::unique_ptr<interfaces::PendingWalletTx>& getWtx(); unsigned int getTransactionSize(); void setTransactionFee(const CAmount& newFee); @@ -38,7 +38,7 @@ public: private: QList<SendCoinsRecipient> recipients; - std::unique_ptr<interface::PendingWalletTx> wtx; + std::unique_ptr<interfaces::PendingWalletTx> wtx; CAmount fee; }; diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp index 1505557244..8b9b85c8c9 100644 --- a/src/qt/walletview.cpp +++ b/src/qt/walletview.cpp @@ -19,7 +19,7 @@ #include <qt/transactionview.h> #include <qt/walletmodel.h> -#include <interface/node.h> +#include <interfaces/node.h> #include <ui_interface.h> #include <QAction> diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 9d7aa58894..f0493de3bd 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -1198,7 +1198,7 @@ UniValue testmempoolaccept(const JSONRPCRequest& request) { LOCK(cs_main); test_accept_res = AcceptToMemoryPool(mempool, state, std::move(tx), &missing_inputs, - nullptr /* plTxnReplaced */, false /* bypass_limits */, max_raw_tx_fee, /* test_accpet */ true); + nullptr /* plTxnReplaced */, false /* bypass_limits */, max_raw_tx_fee, /* test_accept */ true); } result_0.pushKV("allowed", test_accept_res); if (!test_accept_res) { diff --git a/src/sync.cpp b/src/sync.cpp index fdf7c44e4c..6f21d498ee 100644 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -81,20 +81,20 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, LogPrintf("Previous lock order was:\n"); for (const std::pair<void*, CLockLocation> & i : s2) { if (i.first == mismatch.first) { - LogPrintf(" (1)"); + LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { - LogPrintf(" (2)"); + LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); for (const std::pair<void*, CLockLocation> & i : s1) { if (i.first == mismatch.first) { - LogPrintf(" (1)"); + LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { - LogPrintf(" (2)"); + LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } diff --git a/src/txdb.cpp b/src/txdb.cpp index 8550a7e889..45ce94ae42 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -370,7 +370,7 @@ bool CCoinsViewDB::Upgrade() { int64_t count = 0; LogPrintf("Upgrading utxo-set database...\n"); - LogPrintf("[0%%]..."); + LogPrintf("[0%%]..."); /* Continued */ uiInterface.ShowProgress(_("Upgrading UTXO database"), 0, true); size_t batch_size = 1 << 24; CDBBatch batch(db); @@ -389,7 +389,7 @@ bool CCoinsViewDB::Upgrade() { uiInterface.ShowProgress(_("Upgrading UTXO database"), percentageDone, true); if (reportDone < percentageDone/10) { // report max. every 10% step - LogPrintf("[%d%%]...", percentageDone); + LogPrintf("[%d%%]...", percentageDone); /* Continued */ reportDone = percentageDone/10; } } diff --git a/src/util.cpp b/src/util.cpp index 78df33e888..393cc413d6 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -31,6 +31,7 @@ #include <algorithm> #include <fcntl.h> +#include <sched.h> #include <sys/resource.h> #include <sys/stat.h> @@ -1059,3 +1060,17 @@ fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific) { return fs::absolute(path, GetDataDir(net_specific)); } + +int ScheduleBatchPriority(void) +{ +#ifdef SCHED_BATCH + const static sched_param param{.sched_priority = 0}; + if (int ret = pthread_setschedparam(0, SCHED_BATCH, ¶m)) { + LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(errno)); + return ret; + } + return 0; +#else + return 1; +#endif +} diff --git a/src/util.h b/src/util.h index bfd3184ac2..3952461e48 100644 --- a/src/util.h +++ b/src/util.h @@ -389,4 +389,13 @@ std::unique_ptr<T> MakeUnique(Args&&... args) return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } +/** + * On platforms that support it, tell the kernel the calling thread is + * CPU-intensive and non-interactive. See SCHED_BATCH in sched(7) for details. + * + * @return The return value of sched_setschedule(), or 1 on systems without + * sched_setchedule(). + */ +int ScheduleBatchPriority(void); + #endif // BITCOIN_UTIL_H diff --git a/src/validation.cpp b/src/validation.cpp index df8729e382..4a6c4066fc 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -507,7 +507,7 @@ void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool f // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool // were somehow broken and returning the wrong scriptPubKeys -static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool, +static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool, unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) { AssertLockHeld(cs_main); @@ -917,8 +917,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool // invalid blocks (using TestBlockValidity), however allowing such // transactions into the mempool can be exploited as a DoS attack. unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus()); - if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) - { + if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) { // If we're using promiscuousmempoolflags, we may hit this normally // Check if current block has some flags that scriptVerifyFlags // does not before printing an ominous warning @@ -1794,8 +1793,15 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl // is enforced in ContextualCheckBlockHeader(); we wouldn't want to // re-enforce that rule here (at least until we make it impossible for // GetAdjustedTime() to go backward). - if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck)) + if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck)) { + if (state.CorruptionPossible()) { + // We don't write down blocks to disk if they may have been + // corrupted, so this should be impossible unless we're having hardware + // problems. + return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down"); + } return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state)); + } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash(); @@ -2231,13 +2237,13 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar DoWarning(strWarning); } } - LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__, + LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__, /* Continued */ pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion, log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx, FormatISO8601DateTime(pindexNew->GetBlockTime()), GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); if (!warningMessages.empty()) - LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", ")); + LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", ")); /* Continued */ LogPrintf("\n"); } @@ -3903,14 +3909,14 @@ bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nGoodTransactions = 0; CValidationState state; int reportDone = 0; - LogPrintf("[0%%]..."); + LogPrintf("[0%%]..."); /* Continued */ for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))); if (reportDone < percentageDone/10) { // report every 10% step - LogPrintf("[%d%%]...", percentageDone); + LogPrintf("[%d%%]...", percentageDone); /* Continued */ reportDone = percentageDone/10; } uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false); diff --git a/src/wallet/crypter.h b/src/wallet/crypter.h index fdeb4cfee0..4c0c8ff5ec 100644 --- a/src/wallet/crypter.h +++ b/src/wallet/crypter.h @@ -67,7 +67,7 @@ public: typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial; -namespace crypto_tests +namespace wallet_crypto_tests { class TestCrypter; } @@ -75,7 +75,7 @@ namespace crypto_tests /** Encryption/decryption context with key information */ class CCrypter { -friend class crypto_tests::TestCrypter; // for test access to chKey/chIV +friend class wallet_crypto_tests::TestCrypter; // for test access to chKey/chIV private: std::vector<unsigned char, secure_allocator<unsigned char>> vchKey; std::vector<unsigned char, secure_allocator<unsigned char>> vchIV; diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp index 3d7bb674f0..c860eede05 100644 --- a/src/wallet/init.cpp +++ b/src/wallet/init.cpp @@ -3,17 +3,53 @@ // 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 <chainparams.h> +#include <init.h> #include <net.h> #include <util.h> #include <utilmoneystr.h> #include <validation.h> +#include <walletinitinterface.h> #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> +class WalletInit : public WalletInitInterface { +public: + + //! Return the wallets help message. + std::string GetHelpString(bool showDebug) override; + + //! Wallets parameter interaction + bool ParameterInteraction() override; + + //! Register wallet RPCs. + void RegisterRPC(CRPCTable &tableRPC) override; + + //! 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 (WalletParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet). + bool Verify() override; + + //! Load wallet databases. + bool Open() override; + + //! Complete startup of wallets. + void Start(CScheduler& scheduler) override; + + //! Flush all wallets in preparation for shutdown. + void Flush() override; + + //! Stop all wallets. Wallets will be flushed first. + void Stop() override; + + //! Close all wallets. + void Close() override; +}; + +static WalletInit g_wallet_init; +WalletInitInterface* const g_wallet_init_interface = &g_wallet_init; + std::string WalletInit::GetHelpString(bool showDebug) { std::string strUsage = HelpMessageGroup(_("Wallet options:")); diff --git a/src/wallet/init.h b/src/wallet/init.h deleted file mode 100644 index f8be90d3e3..0000000000 --- a/src/wallet/init.h +++ /dev/null @@ -1,48 +0,0 @@ -// 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 <walletinitinterface.h> -#include <string> - -class CRPCTable; -class CScheduler; - -class WalletInit : public WalletInitInterface { -public: - - //! Return the wallets help message. - std::string GetHelpString(bool showDebug) override; - - //! Wallets parameter interaction - bool ParameterInteraction() override; - - //! Register wallet RPCs. - void RegisterRPC(CRPCTable &tableRPC) override; - - //! 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 (WalletParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet). - bool Verify() override; - - //! Load wallet databases. - bool Open() override; - - //! Complete startup of wallets. - void Start(CScheduler& scheduler) override; - - //! Flush all wallets in preparation for shutdown. - void Flush() override; - - //! Stop all wallets. Wallets will be flushed first. - void Stop() override; - - //! Close all wallets. - void Close() override; -}; - -#endif // BITCOIN_WALLET_INIT_H diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 3f88c62c61..a3594aa692 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -6,7 +6,6 @@ #include <key_io.h> #include <rpc/safemode.h> #include <rpc/server.h> -#include <wallet/init.h> #include <validation.h> #include <script/script.h> #include <script/standard.h> diff --git a/src/wallet/test/crypto_tests.cpp b/src/wallet/test/wallet_crypto_tests.cpp index d8c0cdf0f9..e04c0af1dd 100644 --- a/src/wallet/test/crypto_tests.cpp +++ b/src/wallet/test/wallet_crypto_tests.cpp @@ -10,7 +10,7 @@ #include <boost/test/unit_test.hpp> -BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup) +BOOST_FIXTURE_TEST_SUITE(wallet_crypto_tests, BasicTestingSetup) class TestCrypter { diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index dbc1760c80..894dfb035c 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -12,7 +12,6 @@ #include <consensus/consensus.h> #include <consensus/validation.h> #include <fs.h> -#include <wallet/init.h> #include <key.h> #include <key_io.h> #include <keystore.h> @@ -3076,7 +3075,7 @@ bool CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::ve wtxNew.fTimeReceivedIsTxTime = true; wtxNew.fFromMe = true; - LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString()); + LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString()); /* Continued */ { // Take key pair from key pool so it won't be used again reservekey.KeepKey(); diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 898c32c708..22a0ac2924 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -661,22 +661,22 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface { private: static std::atomic<bool> fFlushScheduled; - std::atomic<bool> fAbortRescan; - std::atomic<bool> fScanningWallet; //controlled by WalletRescanReserver + std::atomic<bool> fAbortRescan{false}; + std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver std::mutex mutexScanning; friend class WalletRescanReserver; - CWalletDB *pwalletdbEncryption; + CWalletDB *pwalletdbEncryption = nullptr; //! the current wallet version: clients below this version are not able to load the wallet - int nWalletVersion; + int nWalletVersion = FEATURE_BASE; //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded - int nWalletMaxVersion; + int nWalletMaxVersion = FEATURE_BASE; - int64_t nNextResend; - int64_t nLastResend; - bool fBroadcastTransactions; + int64_t nNextResend = 0; + int64_t nLastResend = 0; + bool fBroadcastTransactions = false; /** * Used to keep track of spent outpoints, and @@ -705,10 +705,10 @@ private: std::set<int64_t> setInternalKeyPool; std::set<int64_t> setExternalKeyPool; - int64_t m_max_keypool_index; + int64_t m_max_keypool_index = 0; std::map<CKeyID, int64_t> m_pool_key_to_index; - int64_t nTimeFirstKey; + int64_t nTimeFirstKey = 0; /** * Private version of AddWatchOnly method which does not accept a @@ -741,7 +741,7 @@ private: * * Protected by cs_main (see BlockUntilSyncedToCurrentChain) */ - const CBlockIndex* m_last_block_processed; + const CBlockIndex* m_last_block_processed = nullptr; public: /* @@ -780,12 +780,11 @@ public: typedef std::map<unsigned int, CMasterKey> MasterKeyMap; MasterKeyMap mapMasterKeys; - unsigned int nMasterKeyMaxID; + unsigned int nMasterKeyMaxID = 0; /** Construct wallet with specified name and database implementation. */ CWallet(std::string name, std::unique_ptr<CWalletDBWrapper> dbw) : m_name(std::move(name)), dbw(std::move(dbw)) { - SetNull(); } ~CWallet() @@ -794,24 +793,6 @@ public: pwalletdbEncryption = nullptr; } - void SetNull() - { - nWalletVersion = FEATURE_BASE; - nWalletMaxVersion = FEATURE_BASE; - nMasterKeyMaxID = 0; - pwalletdbEncryption = nullptr; - nOrderPosNext = 0; - nAccountingEntryNumber = 0; - nNextResend = 0; - nLastResend = 0; - m_max_keypool_index = 0; - nTimeFirstKey = 0; - fBroadcastTransactions = false; - nRelockTime = 0; - fAbortRescan = false; - fScanningWallet = false; - } - std::map<uint256, CWalletTx> mapWallet; std::list<CAccountingEntry> laccentries; @@ -819,8 +800,8 @@ public: typedef std::multimap<int64_t, TxPair > TxItems; TxItems wtxOrdered; - int64_t nOrderPosNext; - uint64_t nAccountingEntryNumber; + int64_t nOrderPosNext = 0; + uint64_t nAccountingEntryNumber = 0; std::map<uint256, int> mapRequestCount; std::map<CTxDestination, CAddressBookData> mapAddressBook; @@ -913,7 +894,7 @@ public: bool LoadWatchOnly(const CScript &dest); //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock(). - int64_t nRelockTime; + int64_t nRelockTime = 0; bool Unlock(const SecureString& strWalletPassphrase); bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase); diff --git a/src/walletinitinterface.h b/src/walletinitinterface.h index a7b52685dd..c7eee37ce5 100644 --- a/src/walletinitinterface.h +++ b/src/walletinitinterface.h @@ -34,18 +34,4 @@ public: virtual ~WalletInitInterface() {} }; -class DummyWalletInit : public WalletInitInterface { -public: - - std::string GetHelpString(bool showDebug) override {return std::string{};} - bool ParameterInteraction() override {return true;} - void RegisterRPC(CRPCTable &) override {} - bool Verify() override {return true;} - bool Open() override {return true;} - void Start(CScheduler& scheduler) override {} - void Flush() override {} - void Stop() override {} - void Close() override {} -}; - #endif // BITCOIN_WALLETINITINTERFACE_H diff --git a/test/functional/interface_rest.py b/test/functional/interface_rest.py index 6f585f6825..2ee33aa869 100755 --- a/test/functional/interface_rest.py +++ b/test/functional/interface_rest.py @@ -4,351 +4,297 @@ # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the REST API.""" -from test_framework.test_framework import BitcoinTestFramework -from test_framework.util import * -from struct import * +import binascii +from decimal import Decimal +from enum import Enum from io import BytesIO -from codecs import encode +import json +from struct import pack, unpack import http.client import urllib.parse -def deser_uint256(f): - r = 0 - for i in range(8): - t = unpack(b"<I", f.read(4))[0] - r += t << (i * 32) - return r - -#allows simple http get calls -def http_get_call(host, port, path, response_object = 0): - conn = http.client.HTTPConnection(host, port) - conn.request('GET', path) - - if response_object: - return conn.getresponse() - - return conn.getresponse().read().decode('utf-8') - -#allows simple http post calls with a request body -def http_post_call(host, port, path, requestdata = '', response_object = 0): - conn = http.client.HTTPConnection(host, port) - conn.request('POST', path, requestdata) - - if response_object: - return conn.getresponse() - - return conn.getresponse().read() +from test_framework.test_framework import BitcoinTestFramework +from test_framework.util import ( + assert_equal, + assert_greater_than, + assert_greater_than_or_equal, + hex_str_to_bytes, +) + +class ReqType(Enum): + JSON = 1 + BIN = 2 + HEX = 3 + +class RetType(Enum): + OBJ = 1 + BYTES = 2 + JSON = 3 + +def filter_output_indices_by_value(vouts, value): + for vout in vouts: + if vout['value'] == value: + yield vout['n'] class RESTTest (BitcoinTestFramework): - FORMAT_SEPARATOR = "." - def set_test_params(self): self.setup_clean_chain = True - self.num_nodes = 3 - self.extra_args = [["-rest"]] * self.num_nodes - - def setup_network(self, split=False): - super().setup_network() - connect_nodes_bi(self.nodes, 0, 2) + self.num_nodes = 2 + self.extra_args = [["-rest"], []] + + def test_rest_request(self, uri, http_method='GET', req_type=ReqType.JSON, body='', status=200, ret_type=RetType.JSON): + rest_uri = '/rest' + uri + if req_type == ReqType.JSON: + rest_uri += '.json' + elif req_type == ReqType.BIN: + rest_uri += '.bin' + elif req_type == ReqType.HEX: + rest_uri += '.hex' + + conn = http.client.HTTPConnection(self.url.hostname, self.url.port) + self.log.debug('%s %s %s', http_method, rest_uri, body) + if http_method == 'GET': + conn.request('GET', rest_uri) + elif http_method == 'POST': + conn.request('POST', rest_uri, body) + resp = conn.getresponse() + + assert_equal(resp.status, status) + + if ret_type == RetType.OBJ: + return resp + elif ret_type == RetType.BYTES: + return resp.read() + elif ret_type == RetType.JSON: + return json.loads(resp.read().decode('utf-8'), parse_float=Decimal) def run_test(self): - url = urllib.parse.urlparse(self.nodes[0].url) - self.log.info("Mining blocks...") + self.url = urllib.parse.urlparse(self.nodes[0].url) + self.log.info("Mine blocks and send Bitcoin to node 1") + + # Random address so node1's balance doesn't increase + not_related_address = "2MxqoHEdNQTyYeX1mHcbrrpzgojbosTpCvJ" self.nodes[0].generate(1) self.sync_all() - self.nodes[2].generate(100) + self.nodes[1].generatetoaddress(100, not_related_address) self.sync_all() assert_equal(self.nodes[0].getbalance(), 50) txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1) self.sync_all() - self.nodes[2].generate(1) + self.nodes[1].generatetoaddress(1, not_related_address) self.sync_all() bb_hash = self.nodes[0].getbestblockhash() - assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) #balance now should be 0.1 on node 1 + assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) - # load the latest 0.1 tx over the REST API - json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json") - json_obj = json.loads(json_string) - vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then) + self.log.info("Load the transaction using the /tx URI") + + json_obj = self.test_rest_request("/tx/{}".format(txid)) + spent = (json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout']) # get the vin to later check for utxo (should be spent by then) # get n of 0.1 outpoint - n = 0 - for vout in json_obj['vout']: - if vout['value'] == 0.1: - n = vout['n'] + n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1')) + spending = (txid, n) + self.log.info("Query an unspent TXO using the /getutxos URI") - ####################################### - # GETUTXOS: query an unspent outpoint # - ####################################### - json_request = '/'+txid+'-'+str(n) - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) + json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spending)) - #check chainTip response + # Check chainTip response assert_equal(json_obj['chaintipHash'], bb_hash) - #make sure there is one utxo + # Make sure there is one utxo assert_equal(len(json_obj['utxos']), 1) - assert_equal(json_obj['utxos'][0]['value'], 0.1) + assert_equal(json_obj['utxos'][0]['value'], Decimal('0.1')) + self.log.info("Query a spent TXO using the /getutxos URI") - ################################################# - # GETUTXOS: now query an already spent outpoint # - ################################################# - json_request = '/'+vintx+'-0' - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) + json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spent)) - #check chainTip response + # Check chainTip response assert_equal(json_obj['chaintipHash'], bb_hash) - #make sure there is no utxo in the response because this oupoint has been spent + # Make sure there is no utxo in the response because this outpoint has been spent assert_equal(len(json_obj['utxos']), 0) - #check bitmap + # Check bitmap assert_equal(json_obj['bitmap'], "0") + self.log.info("Query two TXOs using the /getutxos URI") + + json_obj = self.test_rest_request("/getutxos/{}-{}/{}-{}".format(*(spending + spent))) - ################################################## - # GETUTXOS: now check both with the same request # - ################################################## - json_request = '/'+txid+'-'+str(n)+'/'+vintx+'-0' - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) assert_equal(len(json_obj['utxos']), 1) assert_equal(json_obj['bitmap'], "10") - #test binary response - bb_hash = self.nodes[0].getbestblockhash() - - binaryRequest = b'\x01\x02' - binaryRequest += hex_str_to_bytes(txid) - binaryRequest += pack("i", n) - binaryRequest += hex_str_to_bytes(vintx) - binaryRequest += pack("i", 0) + self.log.info("Query the TXOs using the /getutxos URI with a binary response") - bin_response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', binaryRequest) - output = BytesIO() - output.write(bin_response) - output.seek(0) - chainHeight = unpack("i", output.read(4))[0] - hashFromBinResponse = hex(deser_uint256(output))[2:].zfill(64) + bin_request = b'\x01\x02' + for txid, n in [spending, spent]: + bin_request += hex_str_to_bytes(txid) + bin_request += pack("i", n) - assert_equal(bb_hash, hashFromBinResponse) #check if getutxo's chaintip during calculation was fine - assert_equal(chainHeight, 102) #chain height must be 102 + bin_response = self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body=bin_request, ret_type=RetType.BYTES) + output = BytesIO(bin_response) + chain_height, = unpack("i", output.read(4)) + response_hash = binascii.hexlify(output.read(32)[::-1]).decode('ascii') + assert_equal(bb_hash, response_hash) # check if getutxo's chaintip during calculation was fine + assert_equal(chain_height, 102) # chain height must be 102 - ############################ - # GETUTXOS: mempool checks # - ############################ + self.log.info("Test the /getutxos URI with and without /checkmempool") + # Create a transaction, check that it's found with /checkmempool, but + # not found without. Then confirm the transaction and check that it's + # found with or without /checkmempool. # do a tx and don't sync txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1) - json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json") - json_obj = json.loads(json_string) + json_obj = self.test_rest_request("/tx/{}".format(txid)) # get the spent output to later check for utxo (should be spent by then) - spent = '{}-{}'.format(json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout']) + spent = (json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout']) # get n of 0.1 outpoint - n = 0 - for vout in json_obj['vout']: - if vout['value'] == 0.1: - n = vout['n'] - spending = '{}-{}'.format(txid, n) - - json_request = '/'+spending - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - assert_equal(len(json_obj['utxos']), 0) #there should be no outpoint because it has just added to the mempool - - json_request = '/checkmempool/'+spending - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it has just added to the mempool - - json_request = '/'+spent - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because its spending tx is not confirmed - - json_request = '/checkmempool/'+spent - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - assert_equal(len(json_obj['utxos']), 0) #there should be no outpoint because it has just spent (by mempool tx) + n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1')) + spending = (txid, n) + + json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spending)) + assert_equal(len(json_obj['utxos']), 0) + + json_obj = self.test_rest_request("/getutxos/checkmempool/{}-{}".format(*spending)) + assert_equal(len(json_obj['utxos']), 1) + + json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spent)) + assert_equal(len(json_obj['utxos']), 1) + + json_obj = self.test_rest_request("/getutxos/checkmempool/{}-{}".format(*spent)) + assert_equal(len(json_obj['utxos']), 0) self.nodes[0].generate(1) self.sync_all() - json_request = '/'+spending - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it was mined - - json_request = '/checkmempool/'+spending - json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it was mined - - #do some invalid requests - json_request = '{"checkmempool' - response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True) - assert_equal(response.status, 400) #must be a 400 because we send an invalid json request - - json_request = '{"checkmempool' - response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True) - assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request - - response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True) - assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request - - #test limits - json_request = '/checkmempool/' - for x in range(0, 20): - json_request += txid+'-'+str(n)+'/' - json_request = json_request.rstrip("/") - response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True) - assert_equal(response.status, 400) #must be a 400 because we exceeding the limits - - json_request = '/checkmempool/' - for x in range(0, 15): - json_request += txid+'-'+str(n)+'/' - json_request = json_request.rstrip("/") - response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True) - assert_equal(response.status, 200) #must be a 200 because we are within the limits - - self.nodes[0].generate(1) #generate block to not affect upcoming tests + json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spending)) + assert_equal(len(json_obj['utxos']), 1) + + json_obj = self.test_rest_request("/getutxos/checkmempool/{}-{}".format(*spending)) + assert_equal(len(json_obj['utxos']), 1) + + # Do some invalid requests + self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.JSON, body='{"checkmempool', status=400, ret_type=RetType.OBJ) + self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body='{"checkmempool', status=400, ret_type=RetType.OBJ) + self.test_rest_request("/getutxos/checkmempool", http_method='POST', req_type=ReqType.JSON, status=400, ret_type=RetType.OBJ) + + # Test limits + long_uri = '/'.join(["{}-{}".format(txid, n) for n in range(20)]) + self.test_rest_request("/getutxos/checkmempool/{}".format(long_uri), http_method='POST', status=400, ret_type=RetType.OBJ) + + long_uri = '/'.join(['{}-{}'.format(txid, n) for n in range(15)]) + self.test_rest_request("/getutxos/checkmempool/{}".format(long_uri), http_method='POST', status=200) + + self.nodes[0].generate(1) # generate block to not affect upcoming tests self.sync_all() - ################ - # /rest/block/ # - ################ + self.log.info("Test the /block and /headers URIs") + bb_hash = self.nodes[0].getbestblockhash() - # check binary format - response = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True) - assert_equal(response.status, 200) + # Check binary format + response = self.test_rest_request("/block/{}".format(bb_hash), req_type=ReqType.BIN, ret_type=RetType.OBJ) assert_greater_than(int(response.getheader('content-length')), 80) - response_str = response.read() + response_bytes = response.read() - # compare with block header - response_header = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True) - assert_equal(response_header.status, 200) + # Compare with block header + response_header = self.test_rest_request("/headers/1/{}".format(bb_hash), req_type=ReqType.BIN, ret_type=RetType.OBJ) assert_equal(int(response_header.getheader('content-length')), 80) - response_header_str = response_header.read() - assert_equal(response_str[0:80], response_header_str) + response_header_bytes = response_header.read() + assert_equal(response_bytes[:80], response_header_bytes) - # check block hex format - response_hex = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True) - assert_equal(response_hex.status, 200) + # Check block hex format + response_hex = self.test_rest_request("/block/{}".format(bb_hash), req_type=ReqType.HEX, ret_type=RetType.OBJ) assert_greater_than(int(response_hex.getheader('content-length')), 160) - response_hex_str = response_hex.read() - assert_equal(encode(response_str, "hex_codec")[0:160], response_hex_str[0:160]) + response_hex_bytes = response_hex.read().strip(b'\n') + assert_equal(binascii.hexlify(response_bytes), response_hex_bytes) - # compare with hex block header - response_header_hex = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True) - assert_equal(response_header_hex.status, 200) + # Compare with hex block header + response_header_hex = self.test_rest_request("/headers/1/{}".format(bb_hash), req_type=ReqType.HEX, ret_type=RetType.OBJ) assert_greater_than(int(response_header_hex.getheader('content-length')), 160) - response_header_hex_str = response_header_hex.read() - assert_equal(response_hex_str[0:160], response_header_hex_str[0:160]) - assert_equal(encode(response_header_str, "hex_codec")[0:160], response_header_hex_str[0:160]) + response_header_hex_bytes = response_header_hex.read(160) + assert_equal(binascii.hexlify(response_bytes[:80]), response_header_hex_bytes) - # check json format - block_json_string = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+'json') - block_json_obj = json.loads(block_json_string) + # Check json format + block_json_obj = self.test_rest_request("/block/{}".format(bb_hash)) assert_equal(block_json_obj['hash'], bb_hash) - # compare with json block header - response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"json", True) - assert_equal(response_header_json.status, 200) - response_header_json_str = response_header_json.read().decode('utf-8') - json_obj = json.loads(response_header_json_str, parse_float=Decimal) - assert_equal(len(json_obj), 1) #ensure that there is one header in the json response - assert_equal(json_obj[0]['hash'], bb_hash) #request/response hash should be the same + # Compare with json block header + json_obj = self.test_rest_request("/headers/1/{}".format(bb_hash)) + assert_equal(len(json_obj), 1) # ensure that there is one header in the json response + assert_equal(json_obj[0]['hash'], bb_hash) # request/response hash should be the same - #compare with normal RPC block response + # Compare with normal RPC block response rpc_block_json = self.nodes[0].getblock(bb_hash) - assert_equal(json_obj[0]['hash'], rpc_block_json['hash']) - assert_equal(json_obj[0]['confirmations'], rpc_block_json['confirmations']) - assert_equal(json_obj[0]['height'], rpc_block_json['height']) - assert_equal(json_obj[0]['version'], rpc_block_json['version']) - assert_equal(json_obj[0]['merkleroot'], rpc_block_json['merkleroot']) - assert_equal(json_obj[0]['time'], rpc_block_json['time']) - assert_equal(json_obj[0]['nonce'], rpc_block_json['nonce']) - assert_equal(json_obj[0]['bits'], rpc_block_json['bits']) - assert_equal(json_obj[0]['difficulty'], rpc_block_json['difficulty']) - assert_equal(json_obj[0]['chainwork'], rpc_block_json['chainwork']) - assert_equal(json_obj[0]['previousblockhash'], rpc_block_json['previousblockhash']) - - #see if we can get 5 headers in one response + for key in ['hash', 'confirmations', 'height', 'version', 'merkleroot', 'time', 'nonce', 'bits', 'difficulty', 'chainwork', 'previousblockhash']: + assert_equal(json_obj[0][key], rpc_block_json[key]) + + # See if we can get 5 headers in one response self.nodes[1].generate(5) self.sync_all() - response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/5/'+bb_hash+self.FORMAT_SEPARATOR+"json", True) - assert_equal(response_header_json.status, 200) - response_header_json_str = response_header_json.read().decode('utf-8') - json_obj = json.loads(response_header_json_str) - assert_equal(len(json_obj), 5) #now we should have 5 header objects + json_obj = self.test_rest_request("/headers/5/{}".format(bb_hash)) + assert_equal(len(json_obj), 5) # now we should have 5 header objects + + self.log.info("Test the /tx URI") - # do tx test tx_hash = block_json_obj['tx'][0]['txid'] - json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"json") - json_obj = json.loads(json_string) + json_obj = self.test_rest_request("/tx/{}".format(tx_hash)) assert_equal(json_obj['txid'], tx_hash) - # check hex format response - hex_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"hex", True) - assert_equal(hex_string.status, 200) - assert_greater_than(int(response.getheader('content-length')), 10) + # Check hex format response + hex_response = self.test_rest_request("/tx/{}".format(tx_hash), req_type=ReqType.HEX, ret_type=RetType.OBJ) + assert_greater_than_or_equal(int(hex_response.getheader('content-length')), + json_obj['size']*2) + self.log.info("Test tx inclusion in the /mempool and /block URIs") - # check block tx details - # let's make 3 tx and mine them on node 1 + # Make 3 tx and mine them on node 1 txs = [] - txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)) - txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)) - txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)) + txs.append(self.nodes[0].sendtoaddress(not_related_address, 11)) + txs.append(self.nodes[0].sendtoaddress(not_related_address, 11)) + txs.append(self.nodes[0].sendtoaddress(not_related_address, 11)) self.sync_all() - # check that there are exactly 3 transactions in the TX memory pool before generating the block - json_string = http_get_call(url.hostname, url.port, '/rest/mempool/info'+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) + # Check that there are exactly 3 transactions in the TX memory pool before generating the block + json_obj = self.test_rest_request("/mempool/info") assert_equal(json_obj['size'], 3) # the size of the memory pool should be greater than 3x ~100 bytes assert_greater_than(json_obj['bytes'], 300) - # check that there are our submitted transactions in the TX memory pool - json_string = http_get_call(url.hostname, url.port, '/rest/mempool/contents'+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) + # Check that there are our submitted transactions in the TX memory pool + json_obj = self.test_rest_request("/mempool/contents") for i, tx in enumerate(txs): - assert_equal(tx in json_obj, True) - assert_equal(json_obj[tx]['spentby'], txs[i+1:i+2]) - assert_equal(json_obj[tx]['depends'], txs[i-1:i]) + assert tx in json_obj + assert_equal(json_obj[tx]['spentby'], txs[i + 1:i + 2]) + assert_equal(json_obj[tx]['depends'], txs[i - 1:i]) - # now mine the transactions + # Now mine the transactions newblockhash = self.nodes[1].generate(1) self.sync_all() - #check if the 3 tx show up in the new block - json_string = http_get_call(url.hostname, url.port, '/rest/block/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) - for tx in json_obj['tx']: - if not 'coinbase' in tx['vin'][0]: #exclude coinbase - assert_equal(tx['txid'] in txs, True) + # Check if the 3 tx show up in the new block + json_obj = self.test_rest_request("/block/{}".format(newblockhash[0])) + non_coinbase_txs = {tx['txid'] for tx in json_obj['tx'] + if 'coinbase' not in tx['vin'][0]} + assert_equal(non_coinbase_txs, set(txs)) - #check the same but without tx details - json_string = http_get_call(url.hostname, url.port, '/rest/block/notxdetails/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json') - json_obj = json.loads(json_string) + # Check the same but without tx details + json_obj = self.test_rest_request("/block/notxdetails/{}".format(newblockhash[0])) for tx in txs: - assert_equal(tx in json_obj['tx'], True) + assert tx in json_obj['tx'] + + self.log.info("Test the /chaininfo URI") - #test rest bestblock bb_hash = self.nodes[0].getbestblockhash() - json_string = http_get_call(url.hostname, url.port, '/rest/chaininfo.json') - json_obj = json.loads(json_string) + json_obj = self.test_rest_request("/chaininfo") assert_equal(json_obj['bestblockhash'], bb_hash) if __name__ == '__main__': - RESTTest ().main () + RESTTest().main() diff --git a/test/functional/p2p_sendheaders.py b/test/functional/p2p_sendheaders.py index 8869aeaaea..4c7d5e65c5 100755 --- a/test/functional/p2p_sendheaders.py +++ b/test/functional/p2p_sendheaders.py @@ -411,21 +411,18 @@ class SendHeadersTest(BitcoinTestFramework): inv_node.check_last_announcement(inv=[tip], headers=[]) test_node.check_last_announcement(inv=[tip], headers=[]) if i == 0: - # Just get the data -- shouldn't cause headers announcements to resume + self.log.debug("Just get the data -- shouldn't cause headers announcements to resume") test_node.send_get_data([tip]) test_node.wait_for_block(tip) elif i == 1: - # Send a getheaders message that shouldn't trigger headers announcements - # to resume (best header sent will be too old) + self.log.debug("Send a getheaders message that shouldn't trigger headers announcements to resume (best header sent will be too old)") test_node.send_get_headers(locator=[fork_point], hashstop=new_block_hashes[1]) test_node.send_get_data([tip]) test_node.wait_for_block(tip) elif i == 2: test_node.send_get_data([tip]) test_node.wait_for_block(tip) - # This time, try sending either a getheaders to trigger resumption - # of headers announcements, or mine a new block and inv it, also - # triggering resumption of headers announcements. + self.log.debug("This time, try sending either a getheaders to trigger resumption of headers announcements, or mine a new block and inv it, also triggering resumption of headers announcements.") if j == 0: test_node.send_get_headers(locator=[tip], hashstop=0) test_node.sync_with_ping() |