diff options
Diffstat (limited to 'src')
114 files changed, 2720 insertions, 1331 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index 72e5cdb95d..1bbb92bf42 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -7,6 +7,7 @@ DIST_SUBDIRS = secp256k1 univalue AM_LDFLAGS = $(PTHREAD_CFLAGS) $(LIBTOOL_LDFLAGS) $(HARDENED_LDFLAGS) $(GPROF_LDFLAGS) $(SANITIZER_LDFLAGS) AM_CXXFLAGS = $(HARDENED_CXXFLAGS) $(ERROR_CXXFLAGS) $(GPROF_CXXFLAGS) $(SANITIZER_CXXFLAGS) AM_CPPFLAGS = $(HARDENED_CPPFLAGS) +AM_LIBTOOLFLAGS = --preserve-dup-deps EXTRA_LIBRARIES = if EMBEDDED_UNIVALUE @@ -104,6 +105,9 @@ BITCOIN_CORE_H = \ httpserver.h \ indirectmap.h \ init.h \ + interfaces/handler.h \ + interfaces/node.h \ + interfaces/wallet.h \ key.h \ key_io.h \ keystore.h \ @@ -168,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 \ @@ -245,6 +248,7 @@ endif libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) libbitcoin_wallet_a_SOURCES = \ + interfaces/wallet.cpp \ wallet/crypter.cpp \ wallet/db.cpp \ wallet/feebumper.cpp \ @@ -312,6 +316,7 @@ libbitcoin_consensus_a_SOURCES = \ script/script_error.cpp \ script/script_error.h \ serialize.h \ + span.h \ tinyformat.h \ uint256.cpp \ uint256.h \ @@ -357,6 +362,8 @@ libbitcoin_util_a_SOURCES = \ compat/glibcxx_sanity.cpp \ compat/strnlen.cpp \ fs.cpp \ + interfaces/handler.cpp \ + interfaces/node.cpp \ random.cpp \ rpc/protocol.cpp \ rpc/util.cpp \ diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include index 0bdde06772..38eb12ce0d 100644 --- a/src/Makefile.qt.include +++ b/src/Makefile.qt.include @@ -402,7 +402,7 @@ if TARGET_WINDOWS endif qt_bitcoin_qt_LDADD = qt/libbitcoinqt.a $(LIBBITCOIN_SERVER) if ENABLE_WALLET -qt_bitcoin_qt_LDADD += $(LIBBITCOIN_WALLET) +qt_bitcoin_qt_LDADD += $(LIBBITCOIN_UTIL) $(LIBBITCOIN_WALLET) endif if ENABLE_ZMQ qt_bitcoin_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS) @@ -411,7 +411,7 @@ qt_bitcoin_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(BOOST_LIBS) $(QT_LIBS) $(QT_DBUS_LIBS) $(QR_LIBS) $(PROTOBUF_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(LIBSECP256K1) \ $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) qt_bitcoin_qt_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(QT_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) -qt_bitcoin_qt_LIBTOOLFLAGS = --tag CXX +qt_bitcoin_qt_LIBTOOLFLAGS = $(AM_LIBTOOLFLAGS) --tag CXX #locale/foo.ts -> locale/foo.qm QT_QM=$(QT_TS:.ts=.qm) diff --git a/src/Makefile.qttest.include b/src/Makefile.qttest.include index ea2ed17472..1279152198 100644 --- a/src/Makefile.qttest.include +++ b/src/Makefile.qttest.include @@ -52,7 +52,7 @@ nodist_qt_test_test_bitcoin_qt_SOURCES = $(TEST_QT_MOC_CPP) qt_test_test_bitcoin_qt_LDADD = $(LIBBITCOINQT) $(LIBBITCOIN_SERVER) if ENABLE_WALLET -qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_WALLET) +qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_UTIL) $(LIBBITCOIN_WALLET) endif if ENABLE_ZMQ qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS) 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/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index 263520ee4e..26a9231308 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -15,6 +15,7 @@ #include <util.h> #include <utilstrencodings.h> +#include <memory> #include <stdio.h> #include <event2/buffer.h> @@ -113,7 +114,7 @@ static int AppInitRPC(int argc, char* argv[]) } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) try { - SelectBaseParams(ChainNameFromCommandLine()); + SelectBaseParams(gArgs.GetChainName()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp index 76a6f94899..deb8212a8f 100644 --- a/src/bitcoin-tx.cpp +++ b/src/bitcoin-tx.cpp @@ -22,6 +22,7 @@ #include <utilmoneystr.h> #include <utilstrencodings.h> +#include <memory> #include <stdio.h> #include <boost/algorithm/string.hpp> @@ -43,7 +44,7 @@ static int AppInitRawTx(int argc, char* argv[]) // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { - SelectParams(ChainNameFromCommandLine()); + SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index 58518d611f..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 // @@ -111,7 +102,7 @@ bool AppInit(int argc, char* argv[]) } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { - SelectParams(ChainNameFromCommandLine()); + SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 6067503b0b..adf8e6ae5b 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -11,6 +11,7 @@ #include <utilstrencodings.h> #include <assert.h> +#include <memory> #include <chainparamsseeds.h> diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp index a04258fd40..c51a3fc960 100644 --- a/src/chainparamsbase.cpp +++ b/src/chainparamsbase.cpp @@ -9,6 +9,7 @@ #include <util.h> #include <assert.h> +#include <memory> const std::string CBaseChainParams::MAIN = "main"; const std::string CBaseChainParams::TESTNET = "test"; @@ -48,17 +49,3 @@ void SelectBaseParams(const std::string& chain) { globalChainBaseParams = CreateBaseChainParams(chain); } - -std::string ChainNameFromCommandLine() -{ - bool fRegTest = gArgs.GetBoolArg("-regtest", false); - bool fTestNet = gArgs.GetBoolArg("-testnet", false); - - if (fTestNet && fRegTest) - throw std::runtime_error("Invalid combination of -regtest and -testnet."); - if (fRegTest) - return CBaseChainParams::REGTEST; - if (fTestNet) - return CBaseChainParams::TESTNET; - return CBaseChainParams::MAIN; -} diff --git a/src/chainparamsbase.h b/src/chainparamsbase.h index 2cb860380e..5b11f36770 100644 --- a/src/chainparamsbase.h +++ b/src/chainparamsbase.h @@ -54,10 +54,4 @@ const CBaseChainParams& BaseParams(); /** Sets the params returned by Params() to those for the given network. */ void SelectBaseParams(const std::string& chain); -/** - * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. - * @return CBaseChainParams::MAX_NETWORK_TYPES if an invalid combination is given. CBaseChainParams::MAIN by default. - */ -std::string ChainNameFromCommandLine(); - #endif // BITCOIN_CHAINPARAMSBASE_H diff --git a/src/compressor.h b/src/compressor.h index 561c8e66d0..6bd68529d4 100644 --- a/src/compressor.h +++ b/src/compressor.h @@ -9,6 +9,7 @@ #include <primitives/transaction.h> #include <script/script.h> #include <serialize.h> +#include <span.h> class CKeyID; class CPubKey; @@ -51,12 +52,12 @@ public: void Serialize(Stream &s) const { std::vector<unsigned char> compr; if (CompressScript(script, compr)) { - s << CFlatData(compr); + s << MakeSpan(compr); return; } unsigned int nSize = script.size() + nSpecialScripts; s << VARINT(nSize); - s << CFlatData(script); + s << MakeSpan(script); } template<typename Stream> @@ -65,7 +66,7 @@ public: s >> VARINT(nSize); if (nSize < nSpecialScripts) { std::vector<unsigned char> vch(GetSpecialScriptSize(nSize), 0x00); - s >> CFlatData(vch); + s >> MakeSpan(vch); DecompressScript(script, nSize, vch); return; } @@ -76,7 +77,7 @@ public: s.ignore(nSize); } else { script.resize(nSize); - s >> CFlatData(script); + s >> MakeSpan(script); } } }; diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp index 752f985bc0..e401b5fb1b 100644 --- a/src/dbwrapper.cpp +++ b/src/dbwrapper.cpp @@ -4,6 +4,7 @@ #include <dbwrapper.h> +#include <memory> #include <random.h> #include <leveldb/cache.h> @@ -62,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/httprpc.cpp b/src/httprpc.cpp index 0a70619ba6..de2437943e 100644 --- a/src/httprpc.cpp +++ b/src/httprpc.cpp @@ -17,6 +17,8 @@ #include <crypto/hmac_sha256.h> #include <stdio.h> +#include <memory> + #include <boost/algorithm/string.hpp> // boost::trim /** WWW-Authenticate to present with 401 Unauthorized response */ diff --git a/src/httpserver.cpp b/src/httpserver.cpp index 36db530c82..b8b338dfbc 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -13,6 +13,7 @@ #include <sync.h> #include <ui_interface.h> +#include <memory> #include <stdio.h> #include <stdlib.h> #include <string.h> diff --git a/src/init.cpp b/src/init.cpp index f6f522da66..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; @@ -668,7 +686,7 @@ void ThreadImport(std::vector<fs::path> vImportFiles) // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ActivateBestChain(state, chainparams)) { - LogPrintf("Failed to connect best block"); + LogPrintf("Failed to connect best block\n"); StartShutdown(); return; } @@ -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/interfaces/README.md b/src/interfaces/README.md new file mode 100644 index 0000000000..e93b91d23c --- /dev/null +++ b/src/interfaces/README.md @@ -0,0 +1,17 @@ +# Internal c++ interfaces + +The following interfaces are defined here: + +* [`Chain`](chain.h) — used by wallet to access blockchain and mempool state. Added in [#10973](https://github.com/bitcoin/bitcoin/pull/10973). + +* [`Chain::Client`](chain.h) — used by node to start & stop `Chain` clients. Added in [#10973](https://github.com/bitcoin/bitcoin/pull/10973). + +* [`Node`](node.h) — used by GUI to start & stop bitcoin node. Added in [#10244](https://github.com/bitcoin/bitcoin/pull/10244). + +* [`Wallet`](wallet.h) — used by GUI to access wallets. Added in [#10244](https://github.com/bitcoin/bitcoin/pull/10244). + +* [`Handler`](handler.h) — returned by `handleEvent` methods on interfaces above and used to manage lifetimes of event handlers. + +* [`Init`](init.h) — used by multiprocess code to access interfaces above on startup. Added in [#10102](https://github.com/bitcoin/bitcoin/pull/10102). + +The interfaces above define boundaries between major components of bitcoin code (node, wallet, and gui), making it possible for them to run in different processes, and be tested, developed, and understood independently. These interfaces are not currently designed to be stable or to be used externally. diff --git a/src/interfaces/handler.cpp b/src/interfaces/handler.cpp new file mode 100644 index 0000000000..1443fe9f18 --- /dev/null +++ b/src/interfaces/handler.cpp @@ -0,0 +1,33 @@ +// 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. + +#include <interfaces/handler.h> + +#include <util.h> + +#include <boost/signals2/connection.hpp> +#include <memory> +#include <utility> + +namespace interfaces { +namespace { + +class HandlerImpl : public Handler +{ +public: + HandlerImpl(boost::signals2::connection connection) : m_connection(std::move(connection)) {} + + void disconnect() override { m_connection.disconnect(); } + + boost::signals2::scoped_connection m_connection; +}; + +} // namespace + +std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection) +{ + return MakeUnique<HandlerImpl>(std::move(connection)); +} + +} // namespace interfaces diff --git a/src/interfaces/handler.h b/src/interfaces/handler.h new file mode 100644 index 0000000000..c4c674cac5 --- /dev/null +++ b/src/interfaces/handler.h @@ -0,0 +1,35 @@ +// 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. + +#ifndef BITCOIN_INTERFACES_HANDLER_H +#define BITCOIN_INTERFACES_HANDLER_H + +#include <memory> + +namespace boost { +namespace signals2 { +class connection; +} // namespace signals2 +} // namespace boost + +namespace interfaces { + +//! Generic interface for managing an event handler or callback function +//! registered with another interface. Has a single disconnect method to cancel +//! the registration and prevent any future notifications. +class Handler +{ +public: + virtual ~Handler() {} + + //! Disconnect the handler. + virtual void disconnect() = 0; +}; + +//! Return handler wrapping a boost signal connection. +std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection); + +} // namespace interfaces + +#endif // BITCOIN_INTERFACES_HANDLER_H diff --git a/src/interfaces/node.cpp b/src/interfaces/node.cpp new file mode 100644 index 0000000000..919748f942 --- /dev/null +++ b/src/interfaces/node.cpp @@ -0,0 +1,308 @@ +// 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. + +#include <interfaces/node.h> + +#include <addrdb.h> +#include <amount.h> +#include <chain.h> +#include <chainparams.h> +#include <init.h> +#include <interfaces/handler.h> +#include <interfaces/wallet.h> +#include <net.h> +#include <net_processing.h> +#include <netaddress.h> +#include <netbase.h> +#include <policy/feerate.h> +#include <policy/fees.h> +#include <policy/policy.h> +#include <primitives/block.h> +#include <rpc/server.h> +#include <scheduler.h> +#include <sync.h> +#include <txmempool.h> +#include <ui_interface.h> +#include <util.h> +#include <validation.h> +#include <warnings.h> + +#if defined(HAVE_CONFIG_H) +#include <config/bitcoin-config.h> +#endif +#ifdef ENABLE_WALLET +#include <wallet/fees.h> +#include <wallet/wallet.h> +#define CHECK_WALLET(x) x +#else +#define CHECK_WALLET(x) throw std::logic_error("Wallet function called in non-wallet build.") +#endif + +#include <atomic> +#include <boost/thread/thread.hpp> +#include <univalue.h> + +namespace interfaces { +namespace { + +class NodeImpl : public Node +{ + void parseParameters(int argc, const char* const argv[]) override + { + gArgs.ParseParameters(argc, argv); + } + void readConfigFile(const std::string& conf_path) override { gArgs.ReadConfigFile(conf_path); } + bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); } + bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); } + void selectParams(const std::string& network) override { SelectParams(network); } + std::string getNetwork() override { return Params().NetworkIDString(); } + void initLogging() override { InitLogging(); } + void initParameterInteraction() override { InitParameterInteraction(); } + std::string getWarnings(const std::string& type) override { return GetWarnings(type); } + uint32_t getLogCategories() override { return ::logCategories; } + bool baseInitialize() override + { + return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() && + AppInitLockDataDirectory(); + } + bool appInitMain() override { return AppInitMain(); } + void appShutdown() override + { + Interrupt(); + Shutdown(); + } + void startShutdown() override { StartShutdown(); } + bool shutdownRequested() override { return ShutdownRequested(); } + void mapPort(bool use_upnp) override + { + if (use_upnp) { + StartMapPort(); + } else { + InterruptMapPort(); + StopMapPort(); + } + } + std::string helpMessage(HelpMessageMode mode) override { return HelpMessage(mode); } + bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); } + size_t getNodeCount(CConnman::NumConnections flags) override + { + return g_connman ? g_connman->GetNodeCount(flags) : 0; + } + bool getNodesStats(NodesStats& stats) override + { + stats.clear(); + + if (g_connman) { + std::vector<CNodeStats> stats_temp; + g_connman->GetNodeStats(stats_temp); + + stats.reserve(stats_temp.size()); + for (auto& node_stats_temp : stats_temp) { + stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats()); + } + + // Try to retrieve the CNodeStateStats for each node. + TRY_LOCK(::cs_main, lockMain); + if (lockMain) { + for (auto& node_stats : stats) { + std::get<1>(node_stats) = + GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats)); + } + } + return true; + } + return false; + } + bool getBanned(banmap_t& banmap) override + { + if (g_connman) { + g_connman->GetBanned(banmap); + return true; + } + return false; + } + bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override + { + if (g_connman) { + g_connman->Ban(net_addr, reason, ban_time_offset); + return true; + } + return false; + } + bool unban(const CSubNet& ip) override + { + if (g_connman) { + g_connman->Unban(ip); + return true; + } + return false; + } + bool disconnect(NodeId id) override + { + if (g_connman) { + return g_connman->DisconnectNode(id); + } + return false; + } + int64_t getTotalBytesRecv() override { return g_connman ? g_connman->GetTotalBytesRecv() : 0; } + int64_t getTotalBytesSent() override { return g_connman ? g_connman->GetTotalBytesSent() : 0; } + size_t getMempoolSize() override { return ::mempool.size(); } + size_t getMempoolDynamicUsage() override { return ::mempool.DynamicMemoryUsage(); } + bool getHeaderTip(int& height, int64_t& block_time) override + { + LOCK(::cs_main); + if (::pindexBestHeader) { + height = ::pindexBestHeader->nHeight; + block_time = ::pindexBestHeader->GetBlockTime(); + return true; + } + return false; + } + int getNumBlocks() override + { + LOCK(::cs_main); + return ::chainActive.Height(); + } + int64_t getLastBlockTime() override + { + LOCK(::cs_main); + if (::chainActive.Tip()) { + return ::chainActive.Tip()->GetBlockTime(); + } + return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network + } + double getVerificationProgress() override + { + const CBlockIndex* tip; + { + LOCK(::cs_main); + tip = ::chainActive.Tip(); + } + return GuessVerificationProgress(Params().TxData(), tip); + } + bool isInitialBlockDownload() override { return IsInitialBlockDownload(); } + bool getReindex() override { return ::fReindex; } + bool getImporting() override { return ::fImporting; } + void setNetworkActive(bool active) override + { + if (g_connman) { + g_connman->SetNetworkActive(active); + } + } + bool getNetworkActive() override { return g_connman && g_connman->GetNetworkActive(); } + unsigned int getTxConfirmTarget() override { CHECK_WALLET(return ::nTxConfirmTarget); } + CAmount getRequiredFee(unsigned int tx_bytes) override { CHECK_WALLET(return GetRequiredFee(tx_bytes)); } + CAmount getMinimumFee(unsigned int tx_bytes, + const CCoinControl& coin_control, + int* returned_target, + FeeReason* reason) override + { + FeeCalculation fee_calc; + CAmount result; + CHECK_WALLET(result = GetMinimumFee(tx_bytes, coin_control, ::mempool, ::feeEstimator, &fee_calc)); + if (returned_target) *returned_target = fee_calc.returnedTarget; + if (reason) *reason = fee_calc.reason; + return result; + } + CAmount getMaxTxFee() override { return ::maxTxFee; } + CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override + { + FeeCalculation fee_calc; + CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative); + if (returned_target) { + *returned_target = fee_calc.returnedTarget; + } + return result; + } + CFeeRate getDustRelayFee() override { return ::dustRelayFee; } + CFeeRate getFallbackFee() override { CHECK_WALLET(return CWallet::fallbackFee); } + CFeeRate getPayTxFee() override { CHECK_WALLET(return ::payTxFee); } + void setPayTxFee(CFeeRate rate) override { CHECK_WALLET(::payTxFee = rate); } + UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override + { + JSONRPCRequest req; + req.params = params; + req.strMethod = command; + req.URI = uri; + return ::tableRPC.execute(req); + } + std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); } + void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); } + void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); } + bool getUnspentOutput(const COutPoint& output, Coin& coin) override + { + LOCK(::cs_main); + return ::pcoinsTip->GetCoin(output, coin); + } + std::vector<std::unique_ptr<Wallet>> getWallets() override + { +#ifdef ENABLE_WALLET + std::vector<std::unique_ptr<Wallet>> wallets; + for (CWalletRef wallet : ::vpwallets) { + wallets.emplace_back(MakeWallet(*wallet)); + } + return wallets; +#else + throw std::logic_error("Node::getWallets() called in non-wallet build."); +#endif + } + std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override + { + return MakeHandler(::uiInterface.InitMessage.connect(fn)); + } + std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override + { + return MakeHandler(::uiInterface.ThreadSafeMessageBox.connect(fn)); + } + std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override + { + return MakeHandler(::uiInterface.ThreadSafeQuestion.connect(fn)); + } + std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override + { + return MakeHandler(::uiInterface.ShowProgress.connect(fn)); + } + std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override + { + CHECK_WALLET( + return MakeHandler(::uiInterface.LoadWallet.connect([fn](CWallet* wallet) { fn(MakeWallet(*wallet)); }))); + } + std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override + { + return MakeHandler(::uiInterface.NotifyNumConnectionsChanged.connect(fn)); + } + std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override + { + return MakeHandler(::uiInterface.NotifyNetworkActiveChanged.connect(fn)); + } + std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override + { + return MakeHandler(::uiInterface.NotifyAlertChanged.connect(fn)); + } + std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override + { + return MakeHandler(::uiInterface.BannedListChanged.connect(fn)); + } + std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override + { + return MakeHandler(::uiInterface.NotifyBlockTip.connect([fn](bool initial_download, const CBlockIndex* block) { + fn(initial_download, block->nHeight, block->GetBlockTime(), + GuessVerificationProgress(Params().TxData(), block)); + })); + } + std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override + { + return MakeHandler( + ::uiInterface.NotifyHeaderTip.connect([fn](bool initial_download, const CBlockIndex* block) { + fn(initial_download, block->nHeight, block->GetBlockTime(), + GuessVerificationProgress(Params().TxData(), block)); + })); + } +}; + +} // namespace + +std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); } + +} // namespace interfaces diff --git a/src/interfaces/node.h b/src/interfaces/node.h new file mode 100644 index 0000000000..f375af2f19 --- /dev/null +++ b/src/interfaces/node.h @@ -0,0 +1,259 @@ +// 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. + +#ifndef BITCOIN_INTERFACES_NODE_H +#define BITCOIN_INTERFACES_NODE_H + +#include <addrdb.h> // For banmap_t +#include <amount.h> // For CAmount +#include <init.h> // For HelpMessageMode +#include <net.h> // For CConnman::NumConnections +#include <netaddress.h> // For Network + +#include <functional> +#include <memory> +#include <stddef.h> +#include <stdint.h> +#include <string> +#include <tuple> +#include <vector> + +class CCoinControl; +class CFeeRate; +class CNodeStats; +class Coin; +class RPCTimerInterface; +class UniValue; +class proxyType; +enum class FeeReason; +struct CNodeStateStats; + +namespace interfaces { + +class Handler; +class Wallet; + +//! Top-level interface for a bitcoin node (bitcoind process). +class Node +{ +public: + virtual ~Node() {} + + //! Set command line arguments. + virtual void parseParameters(int argc, const char* const argv[]) = 0; + + //! Set a command line argument if it doesn't already have a value + virtual bool softSetArg(const std::string& arg, const std::string& value) = 0; + + //! Set a command line boolean argument if it doesn't already have a value + virtual bool softSetBoolArg(const std::string& arg, bool value) = 0; + + //! Load settings from configuration file. + virtual void readConfigFile(const std::string& conf_path) = 0; + + //! Choose network parameters. + virtual void selectParams(const std::string& network) = 0; + + //! Get network name. + virtual std::string getNetwork() = 0; + + //! Init logging. + virtual void initLogging() = 0; + + //! Init parameter interaction. + virtual void initParameterInteraction() = 0; + + //! Get warnings. + virtual std::string getWarnings(const std::string& type) = 0; + + // Get log flags. + virtual uint32_t getLogCategories() = 0; + + //! Initialize app dependencies. + virtual bool baseInitialize() = 0; + + //! Start node. + virtual bool appInitMain() = 0; + + //! Stop node. + virtual void appShutdown() = 0; + + //! Start shutdown. + virtual void startShutdown() = 0; + + //! Return whether shutdown was requested. + virtual bool shutdownRequested() = 0; + + //! Get help message string. + virtual std::string helpMessage(HelpMessageMode mode) = 0; + + //! Map port. + virtual void mapPort(bool use_upnp) = 0; + + //! Get proxy. + virtual bool getProxy(Network net, proxyType& proxy_info) = 0; + + //! Get number of connections. + virtual size_t getNodeCount(CConnman::NumConnections flags) = 0; + + //! Get stats for connected nodes. + using NodesStats = std::vector<std::tuple<CNodeStats, bool, CNodeStateStats>>; + virtual bool getNodesStats(NodesStats& stats) = 0; + + //! Get ban map entries. + virtual bool getBanned(banmap_t& banmap) = 0; + + //! Ban node. + virtual bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) = 0; + + //! Unban node. + virtual bool unban(const CSubNet& ip) = 0; + + //! Disconnect node. + virtual bool disconnect(NodeId id) = 0; + + //! Get total bytes recv. + virtual int64_t getTotalBytesRecv() = 0; + + //! Get total bytes sent. + virtual int64_t getTotalBytesSent() = 0; + + //! Get mempool size. + virtual size_t getMempoolSize() = 0; + + //! Get mempool dynamic usage. + virtual size_t getMempoolDynamicUsage() = 0; + + //! Get header tip height and time. + virtual bool getHeaderTip(int& height, int64_t& block_time) = 0; + + //! Get num blocks. + virtual int getNumBlocks() = 0; + + //! Get last block time. + virtual int64_t getLastBlockTime() = 0; + + //! Get verification progress. + virtual double getVerificationProgress() = 0; + + //! Is initial block download. + virtual bool isInitialBlockDownload() = 0; + + //! Get reindex. + virtual bool getReindex() = 0; + + //! Get importing. + virtual bool getImporting() = 0; + + //! Set network active. + virtual void setNetworkActive(bool active) = 0; + + //! Get network active. + virtual bool getNetworkActive() = 0; + + //! Get tx confirm target. + virtual unsigned int getTxConfirmTarget() = 0; + + //! Get required fee. + virtual CAmount getRequiredFee(unsigned int tx_bytes) = 0; + + //! Get minimum fee. + virtual CAmount getMinimumFee(unsigned int tx_bytes, + const CCoinControl& coin_control, + int* returned_target, + FeeReason* reason) = 0; + + //! Get max tx fee. + virtual CAmount getMaxTxFee() = 0; + + //! Estimate smart fee. + virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) = 0; + + //! Get dust relay fee. + virtual CFeeRate getDustRelayFee() = 0; + + //! Get fallback fee. + virtual CFeeRate getFallbackFee() = 0; + + //! Get pay tx fee. + virtual CFeeRate getPayTxFee() = 0; + + //! Set pay tx fee. + virtual void setPayTxFee(CFeeRate rate) = 0; + + //! Execute rpc command. + virtual UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) = 0; + + //! List rpc commands. + virtual std::vector<std::string> listRpcCommands() = 0; + + //! Set RPC timer interface if unset. + virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) = 0; + + //! Unset RPC timer interface. + virtual void rpcUnsetTimerInterface(RPCTimerInterface* iface) = 0; + + //! Get unspent outputs associated with a transaction. + virtual bool getUnspentOutput(const COutPoint& output, Coin& coin) = 0; + + //! Return interfaces for accessing wallets (if any). + virtual std::vector<std::unique_ptr<Wallet>> getWallets() = 0; + + //! Register handler for init messages. + using InitMessageFn = std::function<void(const std::string& message)>; + virtual std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) = 0; + + //! Register handler for message box messages. + using MessageBoxFn = + std::function<bool(const std::string& message, const std::string& caption, unsigned int style)>; + virtual std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) = 0; + + //! Register handler for question messages. + using QuestionFn = std::function<bool(const std::string& message, + const std::string& non_interactive_message, + const std::string& caption, + unsigned int style)>; + virtual std::unique_ptr<Handler> handleQuestion(QuestionFn fn) = 0; + + //! Register handler for progress messages. + using ShowProgressFn = std::function<void(const std::string& title, int progress, bool resume_possible)>; + virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0; + + //! Register handler for load wallet messages. + using LoadWalletFn = std::function<void(std::unique_ptr<Wallet> wallet)>; + virtual std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) = 0; + + //! Register handler for number of connections changed messages. + using NotifyNumConnectionsChangedFn = std::function<void(int new_num_connections)>; + virtual std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) = 0; + + //! Register handler for network active messages. + using NotifyNetworkActiveChangedFn = std::function<void(bool network_active)>; + virtual std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) = 0; + + //! Register handler for notify alert messages. + using NotifyAlertChangedFn = std::function<void()>; + virtual std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) = 0; + + //! Register handler for ban list messages. + using BannedListChangedFn = std::function<void()>; + virtual std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) = 0; + + //! Register handler for block tip messages. + using NotifyBlockTipFn = + std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>; + virtual std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) = 0; + + //! Register handler for header tip messages. + using NotifyHeaderTipFn = + std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>; + virtual std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) = 0; +}; + +//! Return implementation of Node interface. +std::unique_ptr<Node> MakeNode(); + +} // namespace interfaces + +#endif // BITCOIN_INTERFACES_NODE_H diff --git a/src/interfaces/wallet.cpp b/src/interfaces/wallet.cpp new file mode 100644 index 0000000000..0244fe70f5 --- /dev/null +++ b/src/interfaces/wallet.cpp @@ -0,0 +1,441 @@ +// 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. + +#include <interfaces/wallet.h> + +#include <amount.h> +#include <chain.h> +#include <consensus/validation.h> +#include <interfaces/handler.h> +#include <net.h> +#include <policy/policy.h> +#include <primitives/transaction.h> +#include <script/ismine.h> +#include <script/standard.h> +#include <support/allocators/secure.h> +#include <sync.h> +#include <timedata.h> +#include <ui_interface.h> +#include <uint256.h> +#include <validation.h> +#include <wallet/feebumper.h> +#include <wallet/wallet.h> + +#include <memory> + +namespace interfaces { +namespace { + +class PendingWalletTxImpl : public PendingWalletTx +{ +public: + PendingWalletTxImpl(CWallet& wallet) : m_wallet(wallet), m_key(&wallet) {} + + const CTransaction& get() override { return *m_tx; } + + int64_t getVirtualSize() override { return GetVirtualTransactionSize(*m_tx); } + + bool commit(WalletValueMap value_map, + WalletOrderForm order_form, + std::string from_account, + std::string& reject_reason) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + CValidationState state; + if (!m_wallet.CommitTransaction(m_tx, std::move(value_map), std::move(order_form), std::move(from_account), m_key, g_connman.get(), state)) { + reject_reason = state.GetRejectReason(); + return false; + } + return true; + } + + CTransactionRef m_tx; + CWallet& m_wallet; + CReserveKey m_key; +}; + +//! Construct wallet tx struct. +WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx) +{ + WalletTx result; + result.tx = wtx.tx; + result.txin_is_mine.reserve(wtx.tx->vin.size()); + for (const auto& txin : wtx.tx->vin) { + result.txin_is_mine.emplace_back(wallet.IsMine(txin)); + } + result.txout_is_mine.reserve(wtx.tx->vout.size()); + result.txout_address.reserve(wtx.tx->vout.size()); + result.txout_address_is_mine.reserve(wtx.tx->vout.size()); + for (const auto& txout : wtx.tx->vout) { + result.txout_is_mine.emplace_back(wallet.IsMine(txout)); + result.txout_address.emplace_back(); + result.txout_address_is_mine.emplace_back(ExtractDestination(txout.scriptPubKey, result.txout_address.back()) ? + IsMine(wallet, result.txout_address.back()) : + ISMINE_NO); + } + result.credit = wtx.GetCredit(ISMINE_ALL); + result.debit = wtx.GetDebit(ISMINE_ALL); + result.change = wtx.GetChange(); + result.time = wtx.GetTxTime(); + result.value_map = wtx.mapValue; + result.is_coinbase = wtx.IsCoinBase(); + return result; +} + +//! Construct wallet tx status struct. +WalletTxStatus MakeWalletTxStatus(const CWalletTx& wtx) +{ + WalletTxStatus result; + auto mi = ::mapBlockIndex.find(wtx.hashBlock); + CBlockIndex* block = mi != ::mapBlockIndex.end() ? mi->second : nullptr; + result.block_height = (block ? block->nHeight : std::numeric_limits<int>::max()), + result.blocks_to_maturity = wtx.GetBlocksToMaturity(); + result.depth_in_main_chain = wtx.GetDepthInMainChain(); + result.request_count = wtx.GetRequestCount(); + result.time_received = wtx.nTimeReceived; + result.lock_time = wtx.tx->nLockTime; + result.is_final = CheckFinalTx(*wtx.tx); + result.is_trusted = wtx.IsTrusted(); + result.is_abandoned = wtx.isAbandoned(); + result.is_coinbase = wtx.IsCoinBase(); + result.is_in_main_chain = wtx.IsInMainChain(); + return result; +} + +//! Construct wallet TxOut struct. +WalletTxOut MakeWalletTxOut(CWallet& wallet, const CWalletTx& wtx, int n, int depth) +{ + WalletTxOut result; + result.txout = wtx.tx->vout[n]; + result.time = wtx.GetTxTime(); + result.depth_in_main_chain = depth; + result.is_spent = wallet.IsSpent(wtx.GetHash(), n); + return result; +} + +class WalletImpl : public Wallet +{ +public: + WalletImpl(CWallet& wallet) : m_wallet(wallet) {} + + bool encryptWallet(const SecureString& wallet_passphrase) override + { + return m_wallet.EncryptWallet(wallet_passphrase); + } + bool isCrypted() override { return m_wallet.IsCrypted(); } + bool lock() override { return m_wallet.Lock(); } + bool unlock(const SecureString& wallet_passphrase) override { return m_wallet.Unlock(wallet_passphrase); } + bool isLocked() override { return m_wallet.IsLocked(); } + bool changeWalletPassphrase(const SecureString& old_wallet_passphrase, + const SecureString& new_wallet_passphrase) override + { + return m_wallet.ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase); + } + bool backupWallet(const std::string& filename) override { return m_wallet.BackupWallet(filename); } + std::string getWalletName() override { return m_wallet.GetName(); } + bool getKeyFromPool(bool internal, CPubKey& pub_key) override + { + return m_wallet.GetKeyFromPool(pub_key, internal); + } + bool getPubKey(const CKeyID& address, CPubKey& pub_key) override { return m_wallet.GetPubKey(address, pub_key); } + bool getPrivKey(const CKeyID& address, CKey& key) override { return m_wallet.GetKey(address, key); } + bool isSpendable(const CTxDestination& dest) override { return IsMine(m_wallet, dest) & ISMINE_SPENDABLE; } + bool haveWatchOnly() override { return m_wallet.HaveWatchOnly(); }; + bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) override + { + return m_wallet.SetAddressBook(dest, name, purpose); + } + bool delAddressBook(const CTxDestination& dest) override + { + return m_wallet.DelAddressBook(dest); + } + bool getAddress(const CTxDestination& dest, std::string* name, isminetype* is_mine) override + { + LOCK(m_wallet.cs_wallet); + auto it = m_wallet.mapAddressBook.find(dest); + if (it == m_wallet.mapAddressBook.end()) { + return false; + } + if (name) { + *name = it->second.name; + } + if (is_mine) { + *is_mine = IsMine(m_wallet, dest); + } + return true; + } + std::vector<WalletAddress> getAddresses() override + { + LOCK(m_wallet.cs_wallet); + std::vector<WalletAddress> result; + for (const auto& item : m_wallet.mapAddressBook) { + result.emplace_back(item.first, IsMine(m_wallet, item.first), item.second.name, item.second.purpose); + } + return result; + } + void learnRelatedScripts(const CPubKey& key, OutputType type) override { m_wallet.LearnRelatedScripts(key, type); } + bool addDestData(const CTxDestination& dest, const std::string& key, const std::string& value) override + { + LOCK(m_wallet.cs_wallet); + return m_wallet.AddDestData(dest, key, value); + } + bool eraseDestData(const CTxDestination& dest, const std::string& key) override + { + LOCK(m_wallet.cs_wallet); + return m_wallet.EraseDestData(dest, key); + } + std::vector<std::string> getDestValues(const std::string& prefix) override + { + return m_wallet.GetDestValues(prefix); + } + void lockCoin(const COutPoint& output) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.LockCoin(output); + } + void unlockCoin(const COutPoint& output) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.UnlockCoin(output); + } + bool isLockedCoin(const COutPoint& output) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.IsLockedCoin(output.hash, output.n); + } + void listLockedCoins(std::vector<COutPoint>& outputs) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.ListLockedCoins(outputs); + } + std::unique_ptr<PendingWalletTx> createTransaction(const std::vector<CRecipient>& recipients, + const CCoinControl& coin_control, + bool sign, + int& change_pos, + CAmount& fee, + std::string& fail_reason) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + auto pending = MakeUnique<PendingWalletTxImpl>(m_wallet); + if (!m_wallet.CreateTransaction(recipients, pending->m_tx, pending->m_key, fee, change_pos, + fail_reason, coin_control, sign)) { + return {}; + } + return std::move(pending); + } + bool transactionCanBeAbandoned(const uint256& txid) override { return m_wallet.TransactionCanBeAbandoned(txid); } + bool abandonTransaction(const uint256& txid) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.AbandonTransaction(txid); + } + bool transactionCanBeBumped(const uint256& txid) override + { + return feebumper::TransactionCanBeBumped(&m_wallet, txid); + } + bool createBumpTransaction(const uint256& txid, + const CCoinControl& coin_control, + CAmount total_fee, + std::vector<std::string>& errors, + CAmount& old_fee, + CAmount& new_fee, + CMutableTransaction& mtx) override + { + return feebumper::CreateTransaction(&m_wallet, txid, coin_control, total_fee, errors, old_fee, new_fee, mtx) == + feebumper::Result::OK; + } + bool signBumpTransaction(CMutableTransaction& mtx) override { return feebumper::SignTransaction(&m_wallet, mtx); } + bool commitBumpTransaction(const uint256& txid, + CMutableTransaction&& mtx, + std::vector<std::string>& errors, + uint256& bumped_txid) override + { + return feebumper::CommitTransaction(&m_wallet, txid, std::move(mtx), errors, bumped_txid) == + feebumper::Result::OK; + } + CTransactionRef getTx(const uint256& txid) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + auto mi = m_wallet.mapWallet.find(txid); + if (mi != m_wallet.mapWallet.end()) { + return mi->second.tx; + } + return {}; + } + WalletTx getWalletTx(const uint256& txid) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + auto mi = m_wallet.mapWallet.find(txid); + if (mi != m_wallet.mapWallet.end()) { + return MakeWalletTx(m_wallet, mi->second); + } + return {}; + } + std::vector<WalletTx> getWalletTxs() override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + std::vector<WalletTx> result; + result.reserve(m_wallet.mapWallet.size()); + for (const auto& entry : m_wallet.mapWallet) { + result.emplace_back(MakeWalletTx(m_wallet, entry.second)); + } + return result; + } + bool tryGetTxStatus(const uint256& txid, + interfaces::WalletTxStatus& tx_status, + int& num_blocks, + int64_t& adjusted_time) override + { + TRY_LOCK(::cs_main, locked_chain); + if (!locked_chain) { + return false; + } + TRY_LOCK(m_wallet.cs_wallet, locked_wallet); + if (!locked_wallet) { + return false; + } + auto mi = m_wallet.mapWallet.find(txid); + if (mi == m_wallet.mapWallet.end()) { + return false; + } + num_blocks = ::chainActive.Height(); + adjusted_time = GetAdjustedTime(); + tx_status = MakeWalletTxStatus(mi->second); + return true; + } + WalletTx getWalletTxDetails(const uint256& txid, + WalletTxStatus& tx_status, + WalletOrderForm& order_form, + bool& in_mempool, + int& num_blocks, + int64_t& adjusted_time) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + auto mi = m_wallet.mapWallet.find(txid); + if (mi != m_wallet.mapWallet.end()) { + num_blocks = ::chainActive.Height(); + adjusted_time = GetAdjustedTime(); + in_mempool = mi->second.InMempool(); + order_form = mi->second.vOrderForm; + tx_status = MakeWalletTxStatus(mi->second); + return MakeWalletTx(m_wallet, mi->second); + } + return {}; + } + WalletBalances getBalances() override + { + WalletBalances result; + result.balance = m_wallet.GetBalance(); + result.unconfirmed_balance = m_wallet.GetUnconfirmedBalance(); + result.immature_balance = m_wallet.GetImmatureBalance(); + result.have_watch_only = m_wallet.HaveWatchOnly(); + if (result.have_watch_only) { + result.watch_only_balance = m_wallet.GetWatchOnlyBalance(); + result.unconfirmed_watch_only_balance = m_wallet.GetUnconfirmedWatchOnlyBalance(); + result.immature_watch_only_balance = m_wallet.GetImmatureWatchOnlyBalance(); + } + return result; + } + bool tryGetBalances(WalletBalances& balances, int& num_blocks) override + { + TRY_LOCK(cs_main, locked_chain); + if (!locked_chain) return false; + TRY_LOCK(m_wallet.cs_wallet, locked_wallet); + if (!locked_wallet) { + return false; + } + balances = getBalances(); + num_blocks = ::chainActive.Height(); + return true; + } + CAmount getBalance() override { return m_wallet.GetBalance(); } + CAmount getAvailableBalance(const CCoinControl& coin_control) override + { + return m_wallet.GetAvailableBalance(&coin_control); + } + isminetype txinIsMine(const CTxIn& txin) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.IsMine(txin); + } + isminetype txoutIsMine(const CTxOut& txout) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.IsMine(txout); + } + CAmount getDebit(const CTxIn& txin, isminefilter filter) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.GetDebit(txin, filter); + } + CAmount getCredit(const CTxOut& txout, isminefilter filter) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.GetCredit(txout, filter); + } + CoinsList listCoins() override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + CoinsList result; + for (const auto& entry : m_wallet.ListCoins()) { + auto& group = result[entry.first]; + for (const auto& coin : entry.second) { + group.emplace_back( + COutPoint(coin.tx->GetHash(), coin.i), MakeWalletTxOut(m_wallet, *coin.tx, coin.i, coin.nDepth)); + } + } + return result; + } + std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + std::vector<WalletTxOut> result; + result.reserve(outputs.size()); + for (const auto& output : outputs) { + result.emplace_back(); + auto it = m_wallet.mapWallet.find(output.hash); + if (it != m_wallet.mapWallet.end()) { + int depth = it->second.GetDepthInMainChain(); + if (depth >= 0) { + result.back() = MakeWalletTxOut(m_wallet, it->second, output.n, depth); + } + } + } + return result; + } + bool hdEnabled() override { return m_wallet.IsHDEnabled(); } + OutputType getDefaultAddressType() override { return m_wallet.m_default_address_type; } + OutputType getDefaultChangeType() override { return m_wallet.m_default_change_type; } + std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override + { + return MakeHandler(m_wallet.ShowProgress.connect(fn)); + } + std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyStatusChanged.connect([fn](CCryptoKeyStore*) { fn(); })); + } + std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyAddressBookChanged.connect( + [fn](CWallet*, const CTxDestination& address, const std::string& label, bool is_mine, + const std::string& purpose, ChangeType status) { fn(address, label, is_mine, purpose, status); })); + } + std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyTransactionChanged.connect( + [fn, this](CWallet*, const uint256& txid, ChangeType status) { fn(txid, status); })); + } + std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyWatchonlyChanged.connect(fn)); + } + + CWallet& m_wallet; +}; + +} // namespace + +std::unique_ptr<Wallet> MakeWallet(CWallet& wallet) { return MakeUnique<WalletImpl>(wallet); } + +} // namespace interfaces diff --git a/src/interfaces/wallet.h b/src/interfaces/wallet.h new file mode 100644 index 0000000000..3e27242c2c --- /dev/null +++ b/src/interfaces/wallet.h @@ -0,0 +1,352 @@ +// 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. + +#ifndef BITCOIN_INTERFACES_WALLET_H +#define BITCOIN_INTERFACES_WALLET_H + +#include <amount.h> // For CAmount +#include <pubkey.h> // For CTxDestination (CKeyID and CScriptID) +#include <script/ismine.h> // For isminefilter, isminetype +#include <script/standard.h> // For CTxDestination +#include <support/allocators/secure.h> // For SecureString +#include <ui_interface.h> // For ChangeType + +#include <functional> +#include <map> +#include <memory> +#include <stdint.h> +#include <string> +#include <tuple> +#include <utility> +#include <vector> + +class CCoinControl; +class CKey; +class CWallet; +enum class OutputType; +struct CRecipient; + +namespace interfaces { + +class Handler; +class PendingWalletTx; +struct WalletAddress; +struct WalletBalances; +struct WalletTx; +struct WalletTxOut; +struct WalletTxStatus; + +using WalletOrderForm = std::vector<std::pair<std::string, std::string>>; +using WalletValueMap = std::map<std::string, std::string>; + +//! Interface for accessing a wallet. +class Wallet +{ +public: + virtual ~Wallet() {} + + //! Encrypt wallet. + virtual bool encryptWallet(const SecureString& wallet_passphrase) = 0; + + //! Return whether wallet is encrypted. + virtual bool isCrypted() = 0; + + //! Lock wallet. + virtual bool lock() = 0; + + //! Unlock wallet. + virtual bool unlock(const SecureString& wallet_passphrase) = 0; + + //! Return whether wallet is locked. + virtual bool isLocked() = 0; + + //! Change wallet passphrase. + virtual bool changeWalletPassphrase(const SecureString& old_wallet_passphrase, + const SecureString& new_wallet_passphrase) = 0; + + //! Back up wallet. + virtual bool backupWallet(const std::string& filename) = 0; + + //! Get wallet name. + virtual std::string getWalletName() = 0; + + // Get key from pool. + virtual bool getKeyFromPool(bool internal, CPubKey& pub_key) = 0; + + //! Get public key. + virtual bool getPubKey(const CKeyID& address, CPubKey& pub_key) = 0; + + //! Get private key. + virtual bool getPrivKey(const CKeyID& address, CKey& key) = 0; + + //! Return whether wallet has private key. + virtual bool isSpendable(const CTxDestination& dest) = 0; + + //! Return whether wallet has watch only keys. + virtual bool haveWatchOnly() = 0; + + //! Add or update address. + virtual bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) = 0; + + // Remove address. + virtual bool delAddressBook(const CTxDestination& dest) = 0; + + //! Look up address in wallet, return whether exists. + virtual bool getAddress(const CTxDestination& dest, + std::string* name = nullptr, + isminetype* is_mine = nullptr) = 0; + + //! Get wallet address list. + virtual std::vector<WalletAddress> getAddresses() = 0; + + //! Add scripts to key store so old so software versions opening the wallet + //! database can detect payments to newer address types. + virtual void learnRelatedScripts(const CPubKey& key, OutputType type) = 0; + + //! Add dest data. + virtual bool addDestData(const CTxDestination& dest, const std::string& key, const std::string& value) = 0; + + //! Erase dest data. + virtual bool eraseDestData(const CTxDestination& dest, const std::string& key) = 0; + + //! Get dest values with prefix. + virtual std::vector<std::string> getDestValues(const std::string& prefix) = 0; + + //! Lock coin. + virtual void lockCoin(const COutPoint& output) = 0; + + //! Unlock coin. + virtual void unlockCoin(const COutPoint& output) = 0; + + //! Return whether coin is locked. + virtual bool isLockedCoin(const COutPoint& output) = 0; + + //! List locked coins. + virtual void listLockedCoins(std::vector<COutPoint>& outputs) = 0; + + //! Create transaction. + virtual std::unique_ptr<PendingWalletTx> createTransaction(const std::vector<CRecipient>& recipients, + const CCoinControl& coin_control, + bool sign, + int& change_pos, + CAmount& fee, + std::string& fail_reason) = 0; + + //! Return whether transaction can be abandoned. + virtual bool transactionCanBeAbandoned(const uint256& txid) = 0; + + //! Abandon transaction. + virtual bool abandonTransaction(const uint256& txid) = 0; + + //! Return whether transaction can be bumped. + virtual bool transactionCanBeBumped(const uint256& txid) = 0; + + //! Create bump transaction. + virtual bool createBumpTransaction(const uint256& txid, + const CCoinControl& coin_control, + CAmount total_fee, + std::vector<std::string>& errors, + CAmount& old_fee, + CAmount& new_fee, + CMutableTransaction& mtx) = 0; + + //! Sign bump transaction. + virtual bool signBumpTransaction(CMutableTransaction& mtx) = 0; + + //! Commit bump transaction. + virtual bool commitBumpTransaction(const uint256& txid, + CMutableTransaction&& mtx, + std::vector<std::string>& errors, + uint256& bumped_txid) = 0; + + //! Get a transaction. + virtual CTransactionRef getTx(const uint256& txid) = 0; + + //! Get transaction information. + virtual WalletTx getWalletTx(const uint256& txid) = 0; + + //! Get list of all wallet transactions. + virtual std::vector<WalletTx> getWalletTxs() = 0; + + //! Try to get updated status for a particular transaction, if possible without blocking. + virtual bool tryGetTxStatus(const uint256& txid, + WalletTxStatus& tx_status, + int& num_blocks, + int64_t& adjusted_time) = 0; + + //! Get transaction details. + virtual WalletTx getWalletTxDetails(const uint256& txid, + WalletTxStatus& tx_status, + WalletOrderForm& order_form, + bool& in_mempool, + int& num_blocks, + int64_t& adjusted_time) = 0; + + //! Get balances. + virtual WalletBalances getBalances() = 0; + + //! Get balances if possible without blocking. + virtual bool tryGetBalances(WalletBalances& balances, int& num_blocks) = 0; + + //! Get balance. + virtual CAmount getBalance() = 0; + + //! Get available balance. + virtual CAmount getAvailableBalance(const CCoinControl& coin_control) = 0; + + //! Return whether transaction input belongs to wallet. + virtual isminetype txinIsMine(const CTxIn& txin) = 0; + + //! Return whether transaction output belongs to wallet. + virtual isminetype txoutIsMine(const CTxOut& txout) = 0; + + //! Return debit amount if transaction input belongs to wallet. + virtual CAmount getDebit(const CTxIn& txin, isminefilter filter) = 0; + + //! Return credit amount if transaction input belongs to wallet. + virtual CAmount getCredit(const CTxOut& txout, isminefilter filter) = 0; + + //! Return AvailableCoins + LockedCoins grouped by wallet address. + //! (put change in one group with wallet address) + using CoinsList = std::map<CTxDestination, std::vector<std::tuple<COutPoint, WalletTxOut>>>; + virtual CoinsList listCoins() = 0; + + //! Return wallet transaction output information. + virtual std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) = 0; + + // Return whether HD enabled. + virtual bool hdEnabled() = 0; + + // Get default address type. + virtual OutputType getDefaultAddressType() = 0; + + // Get default change type. + virtual OutputType getDefaultChangeType() = 0; + + //! Register handler for show progress messages. + using ShowProgressFn = std::function<void(const std::string& title, int progress)>; + virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0; + + //! Register handler for status changed messages. + using StatusChangedFn = std::function<void()>; + virtual std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) = 0; + + //! Register handler for address book changed messages. + using AddressBookChangedFn = std::function<void(const CTxDestination& address, + const std::string& label, + bool is_mine, + const std::string& purpose, + ChangeType status)>; + virtual std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) = 0; + + //! Register handler for transaction changed messages. + using TransactionChangedFn = std::function<void(const uint256& txid, ChangeType status)>; + virtual std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) = 0; + + //! Register handler for watchonly changed messages. + using WatchOnlyChangedFn = std::function<void(bool have_watch_only)>; + virtual std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) = 0; +}; + +//! Tracking object returned by CreateTransaction and passed to CommitTransaction. +class PendingWalletTx +{ +public: + virtual ~PendingWalletTx() {} + + //! Get transaction data. + virtual const CTransaction& get() = 0; + + //! Get virtual transaction size. + virtual int64_t getVirtualSize() = 0; + + //! Send pending transaction and commit to wallet. + virtual bool commit(WalletValueMap value_map, + WalletOrderForm order_form, + std::string from_account, + std::string& reject_reason) = 0; +}; + +//! Information about one wallet address. +struct WalletAddress +{ + CTxDestination dest; + isminetype is_mine; + std::string name; + std::string purpose; + + WalletAddress(CTxDestination dest, isminetype is_mine, std::string name, std::string purpose) + : dest(std::move(dest)), is_mine(is_mine), name(std::move(name)), purpose(std::move(purpose)) + { + } +}; + +//! Collection of wallet balances. +struct WalletBalances +{ + CAmount balance = 0; + CAmount unconfirmed_balance = 0; + CAmount immature_balance = 0; + bool have_watch_only = false; + CAmount watch_only_balance = 0; + CAmount unconfirmed_watch_only_balance = 0; + CAmount immature_watch_only_balance = 0; + + bool balanceChanged(const WalletBalances& prev) const + { + return balance != prev.balance || unconfirmed_balance != prev.unconfirmed_balance || + immature_balance != prev.immature_balance || watch_only_balance != prev.watch_only_balance || + unconfirmed_watch_only_balance != prev.unconfirmed_watch_only_balance || + immature_watch_only_balance != prev.immature_watch_only_balance; + } +}; + +// Wallet transaction information. +struct WalletTx +{ + CTransactionRef tx; + std::vector<isminetype> txin_is_mine; + std::vector<isminetype> txout_is_mine; + std::vector<CTxDestination> txout_address; + std::vector<isminetype> txout_address_is_mine; + CAmount credit; + CAmount debit; + CAmount change; + int64_t time; + std::map<std::string, std::string> value_map; + bool is_coinbase; +}; + +//! Updated transaction status. +struct WalletTxStatus +{ + int block_height; + int blocks_to_maturity; + int depth_in_main_chain; + int request_count; + unsigned int time_received; + uint32_t lock_time; + bool is_final; + bool is_trusted; + bool is_abandoned; + bool is_coinbase; + bool is_in_main_chain; +}; + +//! Wallet transaction output. +struct WalletTxOut +{ + CTxOut txout; + int64_t time; + int depth_in_main_chain = -1; + bool is_spent = false; +}; + +//! Return implementation of Wallet interface. This function will be undefined +//! in builds where ENABLE_WALLET is false. +std::unique_ptr<Wallet> MakeWallet(CWallet& wallet); + +} // namespace interfaces + +#endif // BITCOIN_INTERFACES_WALLET_H diff --git a/src/memusage.h b/src/memusage.h index fea7ecdf9f..0b92e53b48 100644 --- a/src/memusage.h +++ b/src/memusage.h @@ -10,6 +10,7 @@ #include <stdlib.h> #include <map> +#include <memory> #include <set> #include <vector> #include <unordered_map> diff --git a/src/miner.cpp b/src/miner.cpp index 0660df928c..d2be393538 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -27,6 +27,7 @@ #include <validationinterface.h> #include <algorithm> +#include <memory> #include <queue> #include <utility> diff --git a/src/net.cpp b/src/net.cpp index 342dfbaeb9..f45592ab83 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -20,6 +20,7 @@ #include <ui_interface.h> #include <utilstrencodings.h> +#include <memory> #ifdef WIN32 #include <string.h> #else diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 61e6ae7448..dbdae705de 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -30,6 +30,8 @@ #include <utilmoneystr.h> #include <utilstrencodings.h> +#include <memory> + #if defined(NDEBUG) # error "Bitcoin cannot be compiled without assertions." #endif diff --git a/src/net_processing.h b/src/net_processing.h index 11543129cf..195d0d2033 100644 --- a/src/net_processing.h +++ b/src/net_processing.h @@ -86,9 +86,9 @@ private: }; struct CNodeStateStats { - int nMisbehavior; - int nSyncHeight; - int nCommonHeight; + int nMisbehavior = 0; + int nSyncHeight = -1; + int nCommonHeight = -1; std::vector<int> vHeightInFlight; }; diff --git a/src/netaddress.h b/src/netaddress.h index ad6b55eb58..b3d1407f72 100644 --- a/src/netaddress.h +++ b/src/netaddress.h @@ -11,6 +11,7 @@ #include <compat.h> #include <serialize.h> +#include <span.h> #include <stdint.h> #include <string> @@ -167,10 +168,13 @@ class CService : public CNetAddr template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(ip); + + // TODO: introduce native support for BE serialization in serialize.h unsigned short portN = htons(port); - READWRITE(FLATDATA(portN)); - if (ser_action.ForRead()) + READWRITE(Span<unsigned char>((unsigned char*)&portN, 2)); + if (ser_action.ForRead()) { port = ntohs(portN); + } } }; diff --git a/src/policy/fees.h b/src/policy/fees.h index afb4746def..8c34bee237 100644 --- a/src/policy/fees.h +++ b/src/policy/fees.h @@ -12,6 +12,7 @@ #include <sync.h> #include <map> +#include <memory> #include <string> #include <vector> diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp index 801334483a..1e3acd75c0 100644 --- a/src/qt/addresstablemodel.cpp +++ b/src/qt/addresstablemodel.cpp @@ -7,6 +7,7 @@ #include <qt/guiutil.h> #include <qt/walletmodel.h> +#include <interfaces/node.h> #include <key_io.h> #include <wallet/wallet.h> @@ -67,28 +68,23 @@ static AddressTableEntry::Type translateTransactionType(const QString &strPurpos class AddressTablePriv { public: - CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; - AddressTablePriv(CWallet *_wallet, AddressTableModel *_parent): - wallet(_wallet), parent(_parent) {} + AddressTablePriv(AddressTableModel *_parent): + parent(_parent) {} - void refreshAddressTable() + void refreshAddressTable(interfaces::Wallet& wallet) { cachedAddressTable.clear(); { - LOCK(wallet->cs_wallet); - for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook) + for (const auto& address : wallet.getAddresses()) { - const CTxDestination& address = item.first; - bool fMine = IsMine(*wallet, address); AddressTableEntry::Type addressType = translateTransactionType( - QString::fromStdString(item.second.purpose), fMine); - const std::string& strName = item.second.name; + QString::fromStdString(address.purpose), address.is_mine); cachedAddressTable.append(AddressTableEntry(addressType, - QString::fromStdString(strName), - QString::fromStdString(EncodeDestination(address)))); + QString::fromStdString(address.name), + QString::fromStdString(EncodeDestination(address.dest)))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order @@ -162,12 +158,12 @@ public: } }; -AddressTableModel::AddressTableModel(CWallet *_wallet, WalletModel *parent) : - QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0) +AddressTableModel::AddressTableModel(WalletModel *parent) : + QAbstractTableModel(parent),walletModel(parent),priv(0) { columns << tr("Label") << tr("Address"); - priv = new AddressTablePriv(wallet, this); - priv->refreshAddressTable(); + priv = new AddressTablePriv(this); + priv->refreshAddressTable(parent->wallet()); } AddressTableModel::~AddressTableModel() @@ -244,7 +240,6 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, if(role == Qt::EditRole) { - LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = DecodeDestination(rec->address.toStdString()); if(index.column() == Label) { @@ -254,7 +249,7 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, editStatus = NO_CHANGES; return false; } - wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); + walletModel->wallet().setAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = DecodeDestination(value.toString().toStdString()); // Refuse to set invalid address, set error status and return false @@ -271,7 +266,7 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) - else if(wallet->mapAddressBook.count(newAddress)) + if (walletModel->wallet().getAddress(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; @@ -280,9 +275,9 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, else if(rec->type == AddressTableEntry::Sending) { // Remove old entry - wallet->DelAddressBook(curAddress); + walletModel->wallet().delAddressBook(curAddress); // Add new entry with new address - wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); + walletModel->wallet().setAddressBook(newAddress, value.toString().toStdString(), strPurpose); } } return true; @@ -356,8 +351,7 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con } // Check for duplicate addresses { - LOCK(wallet->cs_wallet); - if(wallet->mapAddressBook.count(DecodeDestination(strAddress))) + if(walletModel->wallet().getAddress(DecodeDestination(strAddress))) { editStatus = DUPLICATE_ADDRESS; return QString(); @@ -368,7 +362,7 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con { // Generate a new address to associate with given label CPubKey newKey; - if(!wallet->GetKeyFromPool(newKey)) + if(!walletModel->wallet().getKeyFromPool(false /* internal */, newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) @@ -377,13 +371,13 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con editStatus = WALLET_UNLOCK_FAILURE; return QString(); } - if(!wallet->GetKeyFromPool(newKey)) + if(!walletModel->wallet().getKeyFromPool(false /* internal */, newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } - wallet->LearnRelatedScripts(newKey, address_type); + walletModel->wallet().learnRelatedScripts(newKey, address_type); strAddress = EncodeDestination(GetDestinationForKey(newKey, address_type)); } else @@ -392,7 +386,7 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con } // Add entry - wallet->SetAddressBook(DecodeDestination(strAddress), strLabel, + walletModel->wallet().setAddressBook(DecodeDestination(strAddress), strLabel, (type == Send ? "send" : "receive")); return QString::fromStdString(strAddress); } @@ -407,7 +401,7 @@ bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent // Also refuse to remove receiving addresses. return false; } - wallet->DelAddressBook(DecodeDestination(rec->address.toStdString())); + walletModel->wallet().delAddressBook(DecodeDestination(rec->address.toStdString())); return true; } @@ -416,12 +410,11 @@ bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent QString AddressTableModel::labelForAddress(const QString &address) const { { - LOCK(wallet->cs_wallet); CTxDestination destination = DecodeDestination(address.toStdString()); - std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(destination); - if (mi != wallet->mapAddressBook.end()) + std::string name; + if (walletModel->wallet().getAddress(destination, &name)) { - return QString::fromStdString(mi->second.name); + return QString::fromStdString(name); } } return QString(); @@ -441,7 +434,7 @@ int AddressTableModel::lookupAddress(const QString &address) const } } -OutputType AddressTableModel::GetDefaultAddressType() const { return wallet->m_default_address_type; }; +OutputType AddressTableModel::GetDefaultAddressType() const { return walletModel->wallet().getDefaultAddressType(); }; void AddressTableModel::emitDataChanged(int idx) { diff --git a/src/qt/addresstablemodel.h b/src/qt/addresstablemodel.h index ed7a4e6f43..d7aeda9d8e 100644 --- a/src/qt/addresstablemodel.h +++ b/src/qt/addresstablemodel.h @@ -13,7 +13,9 @@ enum class OutputType; class AddressTablePriv; class WalletModel; -class CWallet; +namespace interfaces { +class Wallet; +} /** Qt model of the address book in the core. This allows views to access and modify the address book. @@ -23,7 +25,7 @@ class AddressTableModel : public QAbstractTableModel Q_OBJECT public: - explicit AddressTableModel(CWallet *wallet, WalletModel *parent = 0); + explicit AddressTableModel(WalletModel *parent = 0); ~AddressTableModel(); enum ColumnIndex { @@ -80,7 +82,6 @@ public: private: WalletModel *walletModel; - CWallet *wallet; AddressTablePriv *priv; QStringList columns; EditStatus editStatus; diff --git a/src/qt/bantablemodel.cpp b/src/qt/bantablemodel.cpp index c89c90e118..26cb03c2c7 100644 --- a/src/qt/bantablemodel.cpp +++ b/src/qt/bantablemodel.cpp @@ -8,6 +8,7 @@ #include <qt/guiconstants.h> #include <qt/guiutil.h> +#include <interfaces/node.h> #include <sync.h> #include <utiltime.h> @@ -45,11 +46,10 @@ public: Qt::SortOrder sortOrder; /** Pull a full list of banned nodes from CNode into our cache */ - void refreshBanlist() + void refreshBanlist(interfaces::Node& node) { banmap_t banMap; - if(g_connman) - g_connman->GetBanned(banMap); + node.getBanned(banMap); cachedBanlist.clear(); #if QT_VERSION >= 0x040700 @@ -82,8 +82,9 @@ public: } }; -BanTableModel::BanTableModel(ClientModel *parent) : +BanTableModel::BanTableModel(interfaces::Node& node, ClientModel *parent) : QAbstractTableModel(parent), + m_node(node), clientModel(parent) { columns << tr("IP/Netmask") << tr("Banned Until"); @@ -168,7 +169,7 @@ QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent) void BanTableModel::refresh() { Q_EMIT layoutAboutToBeChanged(); - priv->refreshBanlist(); + priv->refreshBanlist(m_node); Q_EMIT layoutChanged(); } diff --git a/src/qt/bantablemodel.h b/src/qt/bantablemodel.h index a54f8793d0..d6c8dbf6dd 100644 --- a/src/qt/bantablemodel.h +++ b/src/qt/bantablemodel.h @@ -7,12 +7,18 @@ #include <net.h> +#include <memory> + #include <QAbstractTableModel> #include <QStringList> class ClientModel; class BanTablePriv; +namespace interfaces { + class Node; +} + struct CCombinedBan { CSubNet subnet; CBanEntry banEntry; @@ -39,7 +45,7 @@ class BanTableModel : public QAbstractTableModel Q_OBJECT public: - explicit BanTableModel(ClientModel *parent = 0); + explicit BanTableModel(interfaces::Node& node, ClientModel *parent = 0); ~BanTableModel(); void startAutoRefresh(); void stopAutoRefresh(); @@ -65,6 +71,7 @@ public Q_SLOTS: void refresh(); private: + 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 140e56123f..599c3c0985 100644 --- a/src/qt/bitcoin.cpp +++ b/src/qt/bitcoin.cpp @@ -27,18 +27,17 @@ #endif #include <init.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> -#include <wallet/wallet.h> -#endif #include <walletinitinterface.h> +#include <memory> #include <stdint.h> #include <boost/thread.hpp> @@ -180,11 +179,7 @@ class BitcoinCore: public QObject { Q_OBJECT public: - explicit BitcoinCore(); - /** Basic initialization, before starting initialization/shutdown thread. - * Return true on success. - */ - static bool baseInitialize(); + explicit BitcoinCore(interfaces::Node& node); public Q_SLOTS: void initialize(); @@ -196,9 +191,10 @@ Q_SIGNALS: void runawayException(const QString &message); private: - /// Pass fatal exception message to UI thread void handleRunawayException(const std::exception *e); + + interfaces::Node& m_node; }; /** Main Bitcoin application object */ @@ -206,7 +202,7 @@ class BitcoinApplication: public QApplication { Q_OBJECT public: - explicit BitcoinApplication(int &argc, char **argv); + explicit BitcoinApplication(interfaces::Node& node, int &argc, char **argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET @@ -247,6 +243,7 @@ Q_SIGNALS: private: QThread *coreThread; + interfaces::Node& m_node; OptionsModel *optionsModel; ClientModel *clientModel; BitcoinGUI *window; @@ -264,36 +261,15 @@ private: #include <qt/bitcoin.moc> -BitcoinCore::BitcoinCore(): - QObject() +BitcoinCore::BitcoinCore(interfaces::Node& node) : + QObject(), m_node(node) { } void BitcoinCore::handleRunawayException(const std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); - Q_EMIT runawayException(QString::fromStdString(GetWarnings("gui"))); -} - -bool BitcoinCore::baseInitialize() -{ - if (!AppInitBasicSetup()) - { - return false; - } - if (!AppInitParameterInteraction()) - { - return false; - } - if (!AppInitSanityChecks()) - { - return false; - } - if (!AppInitLockDataDirectory()) - { - return false; - } - return true; + Q_EMIT runawayException(QString::fromStdString(m_node.getWarnings("gui"))); } void BitcoinCore::initialize() @@ -301,7 +277,7 @@ void BitcoinCore::initialize() try { qDebug() << __func__ << ": Running initialization in thread"; - bool rv = AppInitMain(); + bool rv = m_node.appInitMain(); Q_EMIT initializeResult(rv); } catch (const std::exception& e) { handleRunawayException(&e); @@ -315,8 +291,7 @@ void BitcoinCore::shutdown() try { qDebug() << __func__ << ": Running Shutdown in thread"; - Interrupt(); - Shutdown(); + m_node.appShutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(); } catch (const std::exception& e) { @@ -326,9 +301,10 @@ void BitcoinCore::shutdown() } } -BitcoinApplication::BitcoinApplication(int &argc, char **argv): +BitcoinApplication::BitcoinApplication(interfaces::Node& node, int &argc, char **argv): QApplication(argc, argv), coreThread(0), + m_node(node), optionsModel(0), clientModel(0), window(0), @@ -383,12 +359,12 @@ void BitcoinApplication::createPaymentServer() void BitcoinApplication::createOptionsModel(bool resetSettings) { - optionsModel = new OptionsModel(nullptr, resetSettings); + optionsModel = new OptionsModel(m_node, nullptr, resetSettings); } void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) { - window = new BitcoinGUI(platformStyle, networkStyle, 0); + window = new BitcoinGUI(m_node, platformStyle, networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown())); @@ -396,7 +372,7 @@ void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle) { - SplashScreen *splash = new SplashScreen(0, networkStyle); + SplashScreen *splash = new SplashScreen(m_node, 0, networkStyle); // We don't hold a direct pointer to the splash screen after creation, but the splash // screen will take care of deleting itself when slotFinish happens. splash->show(); @@ -409,7 +385,7 @@ void BitcoinApplication::startThread() if(coreThread) return; coreThread = new QThread(this); - BitcoinCore *executor = new BitcoinCore(); + BitcoinCore *executor = new BitcoinCore(m_node); executor->moveToThread(coreThread); /* communication to and from thread */ @@ -427,8 +403,8 @@ void BitcoinApplication::startThread() void BitcoinApplication::parameterSetup() { - InitLogging(); - InitParameterInteraction(); + m_node.initLogging(); + m_node.initParameterInteraction(); } void BitcoinApplication::requestInitialize() @@ -461,7 +437,7 @@ void BitcoinApplication::requestShutdown() delete clientModel; clientModel = 0; - StartShutdown(); + m_node.startShutdown(); // Request shutdown from core thread Q_EMIT requestedShutdown(); @@ -481,13 +457,14 @@ void BitcoinApplication::initializeResult(bool success) paymentServer->setOptionsModel(optionsModel); #endif - clientModel = new ClientModel(optionsModel); + clientModel = new ClientModel(m_node, optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET bool fFirstWallet = true; - for (CWalletRef pwallet : vpwallets) { - WalletModel * const walletModel = new WalletModel(platformStyle, pwallet, optionsModel); + auto wallets = m_node.getWallets(); + for (auto& wallet : wallets) { + WalletModel * const walletModel = new WalletModel(std::move(wallet), m_node, platformStyle, optionsModel); window->addWallet(walletModel); if (fFirstWallet) { @@ -495,8 +472,8 @@ void BitcoinApplication::initializeResult(bool success) fFirstWallet = false; } - connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)), - paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray))); + connect(walletModel, SIGNAL(coinsSent(WalletModel*,SendCoinsRecipient,QByteArray)), + paymentServer, SLOT(fetchPaymentACK(WalletModel*,const SendCoinsRecipient&,QByteArray))); m_wallet_models.push_back(walletModel); } @@ -555,9 +532,11 @@ int main(int argc, char *argv[]) { SetupEnvironment(); + std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(); + /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: - gArgs.ParseParameters(argc, argv); + node->parseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory @@ -571,7 +550,7 @@ int main(int argc, char *argv[]) Q_INIT_RESOURCE(bitcoin); Q_INIT_RESOURCE(bitcoin_locale); - BitcoinApplication app(argc, argv); + BitcoinApplication app(*node, argc, argv); #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); @@ -614,14 +593,14 @@ int main(int argc, char *argv[]) // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { - HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version")); + HelpMessageDialog help(*node, nullptr, gArgs.IsArgSet("-version")); help.showOrPrint(); return EXIT_SUCCESS; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory - if (!Intro::pickDataDirectory()) + if (!Intro::pickDataDirectory(*node)) return EXIT_SUCCESS; /// 6. Determine availability of data and blocks directory and parse bitcoin.conf @@ -633,7 +612,7 @@ int main(int argc, char *argv[]) return EXIT_FAILURE; } try { - gArgs.ReadConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)); + node->readConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)); } catch (const std::exception& e) { QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); @@ -648,14 +627,14 @@ int main(int argc, char *argv[]) // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { - SelectParams(ChainNameFromCommandLine()); + node->selectParams(gArgs.GetChainName()); } catch(std::exception &e) { QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QObject::tr("Error: %1").arg(e.what())); return EXIT_FAILURE; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() - PaymentServer::ipcParseCommandLine(argc, argv); + PaymentServer::ipcParseCommandLine(*node, argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); @@ -678,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 @@ -705,7 +679,7 @@ int main(int argc, char *argv[]) app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false)); // Subscribe to global signals from core - uiInterface.InitMessage.connect(InitMessage); + std::unique_ptr<interfaces::Handler> handler = node->handleInitMessage(InitMessage); if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); @@ -717,7 +691,7 @@ int main(int argc, char *argv[]) // Perform base initialization before spinning up initialization/shutdown thread // This is acceptable because this function only contains steps that are quick to execute, // so the GUI thread won't be held up. - if (BitcoinCore::baseInitialize()) { + if (node->baseInitialize()) { app.requestInitialize(); #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(QObject::tr(PACKAGE_NAME)), (HWND)app.getMainWinId()); @@ -732,10 +706,10 @@ int main(int argc, char *argv[]) } } catch (const std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); - app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); + app.handleRunawayException(QString::fromStdString(node->getWarnings("gui"))); } catch (...) { PrintExceptionContinue(nullptr, "Runaway exception"); - app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); + app.handleRunawayException(QString::fromStdString(node->getWarnings("gui"))); } return rv; } diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index e4207fce99..bfa8844a09 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -30,6 +30,8 @@ #include <chainparams.h> #include <init.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <ui_interface.h> #include <util.h> @@ -72,9 +74,10 @@ const std::string BitcoinGUI::DEFAULT_UIPLATFORM = #endif ; -BitcoinGUI::BitcoinGUI(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), clientModel(0), walletFrame(0), unitDisplayControl(0), @@ -149,8 +152,8 @@ BitcoinGUI::BitcoinGUI(const PlatformStyle *_platformStyle, const NetworkStyle * setUnifiedTitleAndToolBarOnMac(true); #endif - rpcConsole = new RPCConsole(_platformStyle, 0); - helpMessageDialog = new HelpMessageDialog(this, false); + rpcConsole = new RPCConsole(node, _platformStyle, 0); + helpMessageDialog = new HelpMessageDialog(node, this, false); #ifdef ENABLE_WALLET if(enableWallet) { @@ -490,7 +493,7 @@ void BitcoinGUI::setClientModel(ClientModel *_clientModel) connect(_clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool))); modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime())); - setNumBlocks(_clientModel->getNumBlocks(), _clientModel->getLastBlockDate(), _clientModel->getVerificationProgress(nullptr), false); + setNumBlocks(m_node.getNumBlocks(), QDateTime::fromTime_t(m_node.getLastBlockTime()), m_node.getVerificationProgress(), false); connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool))); // Receive and report messages from client model @@ -665,7 +668,7 @@ void BitcoinGUI::aboutClicked() if(!clientModel) return; - HelpMessageDialog dlg(this, true); + HelpMessageDialog dlg(m_node, this, true); dlg.exec(); } @@ -748,7 +751,7 @@ void BitcoinGUI::updateNetworkState() QString tooltip; - if (clientModel->getNetworkActive()) { + if (m_node.getNetworkActive()) { tooltip = tr("%n active connection(s) to Bitcoin network", "", count) + QString(".<br>") + tr("Click to disable network activity."); } else { tooltip = tr("Network activity disabled.") + QString("<br>") + tr("Click to enable network activity again."); @@ -1007,7 +1010,7 @@ void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmoun // On new transaction, make an info balloon QString msg = tr("Date: %1\n").arg(date) + tr("Amount: %1\n").arg(BitcoinUnits::formatWithUnit(unit, amount, true)); - if (WalletModel::isMultiwallet() && !walletName.isEmpty()) { + if (m_node.getWallets().size() > 1 && !walletName.isEmpty()) { msg += tr("Wallet: %1\n").arg(walletName); } msg += tr("Type: %1\n").arg(type); @@ -1113,7 +1116,7 @@ void BitcoinGUI::updateWalletStatus() } WalletModel * const walletModel = walletView->getWalletModel(); setEncryptionStatus(walletModel->getEncryptionStatus()); - setHDStatus(walletModel->hdEnabled()); + setHDStatus(walletModel->wallet().hdEnabled()); } #endif // ENABLE_WALLET @@ -1149,7 +1152,7 @@ void BitcoinGUI::toggleHidden() void BitcoinGUI::detectShutdown() { - if (ShutdownRequested()) + if (m_node.shutdownRequested()) { if(rpcConsole) rpcConsole->hide(); @@ -1214,22 +1217,20 @@ static bool ThreadSafeMessageBox(BitcoinGUI *gui, const std::string& message, co void BitcoinGUI::subscribeToCoreSignals() { // Connect signals to client - uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); - uiInterface.ThreadSafeQuestion.connect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4)); + m_handler_message_box = m_node.handleMessageBox(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); + m_handler_question = m_node.handleQuestion(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4)); } void BitcoinGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client - uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); - uiInterface.ThreadSafeQuestion.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4)); + m_handler_message_box->disconnect(); + m_handler_question->disconnect(); } void BitcoinGUI::toggleNetworkActive() { - if (clientModel) { - clientModel->setNetworkActive(!clientModel->getNetworkActive()); - } + m_node.setNetworkActive(!m_node.getNetworkActive()); } UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) : diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index b9e92f2d5b..e59c71cd4f 100644 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -18,6 +18,8 @@ #include <QPoint> #include <QSystemTrayIcon> +#include <memory> + class ClientModel; class NetworkStyle; class Notificator; @@ -31,6 +33,11 @@ class WalletModel; class HelpMessageDialog; class ModalOverlay; +namespace interfaces { +class Handler; +class Node; +} + QT_BEGIN_NAMESPACE class QAction; class QComboBox; @@ -49,7 +56,7 @@ class BitcoinGUI : public QMainWindow public: static const std::string DEFAULT_UIPLATFORM; - explicit BitcoinGUI(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. @@ -76,6 +83,9 @@ protected: bool eventFilter(QObject *object, QEvent *event); private: + 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 40661d9ec3..37fd06ccc9 100644 --- a/src/qt/clientmodel.cpp +++ b/src/qt/clientmodel.cpp @@ -13,6 +13,8 @@ #include <chainparams.h> #include <checkpoints.h> #include <clientversion.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <validation.h> #include <net.h> #include <txmempool.h> @@ -30,8 +32,9 @@ class CBlockIndex; static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; -ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : +ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) : QObject(parent), + m_node(node), optionsModel(_optionsModel), peerTableModel(0), banTableModel(0), @@ -39,8 +42,8 @@ ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; - peerTableModel = new PeerTableModel(this); - banTableModel = new BanTableModel(this); + peerTableModel = new PeerTableModel(m_node, this); + banTableModel = new BanTableModel(m_node, this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); @@ -64,15 +67,7 @@ int ClientModel::getNumConnections(unsigned int flags) const else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; - if(g_connman) - return g_connman->GetNodeCount(connections); - return 0; -} - -int ClientModel::getNumBlocks() const -{ - LOCK(cs_main); - return chainActive.Height(); + return m_node.getNodeCount(connections); } int ClientModel::getHeaderTipHeight() const @@ -80,10 +75,11 @@ int ClientModel::getHeaderTipHeight() const if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update - LOCK(cs_main); - if (pindexBestHeader) { - cachedBestHeaderHeight = pindexBestHeader->nHeight; - cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); + int height; + int64_t blockTime; + if (m_node.getHeaderTip(height, blockTime)) { + cachedBestHeaderHeight = height; + cachedBestHeaderTime = blockTime; } } return cachedBestHeaderHeight; @@ -92,66 +88,22 @@ int ClientModel::getHeaderTipHeight() const int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { - LOCK(cs_main); - if (pindexBestHeader) { - cachedBestHeaderHeight = pindexBestHeader->nHeight; - cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); + int height; + int64_t blockTime; + if (m_node.getHeaderTip(height, blockTime)) { + cachedBestHeaderHeight = height; + cachedBestHeaderTime = blockTime; } } return cachedBestHeaderTime; } -quint64 ClientModel::getTotalBytesRecv() const -{ - if(!g_connman) - return 0; - return g_connman->GetTotalBytesRecv(); -} - -quint64 ClientModel::getTotalBytesSent() const -{ - if(!g_connman) - return 0; - return g_connman->GetTotalBytesSent(); -} - -QDateTime ClientModel::getLastBlockDate() const -{ - LOCK(cs_main); - - if (chainActive.Tip()) - return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); - - return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network -} - -long ClientModel::getMempoolSize() const -{ - return mempool.size(); -} - -size_t ClientModel::getMempoolDynamicUsage() const -{ - return mempool.DynamicMemoryUsage(); -} - -double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const -{ - CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); - LOCK(cs_main); - if (!tip) - { - tip = chainActive.Tip(); - } - return GuessVerificationProgress(Params().TxData(), tip); -} - void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock - Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); - Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); + Q_EMIT mempoolSizeChanged(m_node.getMempoolSize(), m_node.getMempoolDynamicUsage()); + Q_EMIT bytesChanged(m_node.getTotalBytesRecv(), m_node.getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) @@ -169,16 +121,11 @@ void ClientModel::updateAlert() Q_EMIT alertsChanged(getStatusBarWarnings()); } -bool ClientModel::inInitialBlockDownload() const -{ - return IsInitialBlockDownload(); -} - enum BlockSource ClientModel::getBlockSource() const { - if (fReindex) + if (m_node.getReindex()) return BlockSource::REINDEX; - else if (fImporting) + else if (m_node.getImporting()) return BlockSource::DISK; else if (getNumConnections() > 0) return BlockSource::NETWORK; @@ -186,24 +133,9 @@ enum BlockSource ClientModel::getBlockSource() const return BlockSource::NONE; } -void ClientModel::setNetworkActive(bool active) -{ - if (g_connman) { - g_connman->SetNetworkActive(active); - } -} - -bool ClientModel::getNetworkActive() const -{ - if (g_connman) { - return g_connman->GetNetworkActive(); - } - return false; -} - QString ClientModel::getStatusBarWarnings() const { - return QString::fromStdString(GetWarnings("gui")); + return QString::fromStdString(m_node.getWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() @@ -285,7 +217,7 @@ static void BannedListChanged(ClientModel *clientmodel) QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } -static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) +static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, int height, int64_t blockTime, double verificationProgress, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update @@ -298,16 +230,16 @@ static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CB if (fHeader) { // cache best headers time and height to reduce future cs_main locks - clientmodel->cachedBestHeaderHeight = pIndex->nHeight; - clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); + clientmodel->cachedBestHeaderHeight = height; + clientmodel->cachedBestHeaderTime = blockTime; } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass an async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, - Q_ARG(int, pIndex->nHeight), - Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), - Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), + Q_ARG(int, height), + Q_ARG(QDateTime, QDateTime::fromTime_t(blockTime)), + Q_ARG(double, verificationProgress), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } @@ -316,23 +248,23 @@ static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CB void ClientModel::subscribeToCoreSignals() { // Connect signals to client - uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); - uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); - uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1)); - uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this)); - uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); - uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); - uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); + m_handler_show_progress = m_node.handleShowProgress(boost::bind(ShowProgress, this, _1, _2)); + m_handler_notify_num_connections_changed = m_node.handleNotifyNumConnectionsChanged(boost::bind(NotifyNumConnectionsChanged, this, _1)); + m_handler_notify_network_active_changed = m_node.handleNotifyNetworkActiveChanged(boost::bind(NotifyNetworkActiveChanged, this, _1)); + m_handler_notify_alert_changed = m_node.handleNotifyAlertChanged(boost::bind(NotifyAlertChanged, this)); + m_handler_banned_list_changed = m_node.handleBannedListChanged(boost::bind(BannedListChanged, this)); + m_handler_notify_block_tip = m_node.handleNotifyBlockTip(boost::bind(BlockTipChanged, this, _1, _2, _3, _4, false)); + m_handler_notify_header_tip = m_node.handleNotifyHeaderTip(boost::bind(BlockTipChanged, this, _1, _2, _3, _4, true)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client - uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); - uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); - uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1)); - uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this)); - uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); - uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false)); - uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true)); + m_handler_show_progress->disconnect(); + m_handler_notify_num_connections_changed->disconnect(); + m_handler_notify_network_active_changed->disconnect(); + m_handler_notify_alert_changed->disconnect(); + m_handler_banned_list_changed->disconnect(); + m_handler_notify_block_tip->disconnect(); + m_handler_notify_header_tip->disconnect(); } diff --git a/src/qt/clientmodel.h b/src/qt/clientmodel.h index 1118bc31b3..a609222f7d 100644 --- a/src/qt/clientmodel.h +++ b/src/qt/clientmodel.h @@ -9,6 +9,7 @@ #include <QDateTime> #include <atomic> +#include <memory> class BanTableModel; class OptionsModel; @@ -16,6 +17,11 @@ class PeerTableModel; class CBlockIndex; +namespace interfaces { +class Handler; +class Node; +} + QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE @@ -40,37 +46,21 @@ class ClientModel : public QObject Q_OBJECT public: - explicit ClientModel(OptionsModel *optionsModel, QObject *parent = 0); + explicit ClientModel(interfaces::Node& node, OptionsModel *optionsModel, QObject *parent = 0); ~ClientModel(); + interfaces::Node& node() const { return m_node; } OptionsModel *getOptionsModel(); PeerTableModel *getPeerTableModel(); BanTableModel *getBanTableModel(); //! Return number of connections, default is in- and outbound (total) int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const; - int getNumBlocks() const; int getHeaderTipHeight() const; int64_t getHeaderTipTime() const; - //! Return number of transactions in the mempool - long getMempoolSize() const; - //! Return the dynamic memory usage of the mempool - size_t getMempoolDynamicUsage() const; - - quint64 getTotalBytesRecv() const; - quint64 getTotalBytesSent() const; - - double getVerificationProgress(const CBlockIndex *tip) const; - QDateTime getLastBlockDate() const; - - //! Return true if core is doing initial block download - bool inInitialBlockDownload() const; + //! Returns enum BlockSource of the current importing/syncing state enum BlockSource getBlockSource() const; - //! Return true if network activity in core is enabled - bool getNetworkActive() const; - //! Toggle network activity state in core - void setNetworkActive(bool active); //! Return warnings to be displayed in status bar QString getStatusBarWarnings() const; @@ -85,6 +75,14 @@ public: mutable std::atomic<int64_t> cachedBestHeaderTime; private: + 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 a45e9f85c1..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 <init.h> +#include <interfaces/node.h> #include <key_io.h> #include <policy/fees.h> #include <policy/policy.h> @@ -209,7 +209,7 @@ void CoinControlDialog::showMenu(const QPoint &point) if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means it is a child node, so it is not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); - if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) + if (model->wallet().isLockedCoin(COutPoint(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))) { lockAction->setEnabled(false); unlockAction->setEnabled(true); @@ -269,7 +269,7 @@ void CoinControlDialog::lockCoin() contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); - model->lockCoin(outpt); + model->wallet().lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); updateLabelLocked(); @@ -279,7 +279,7 @@ void CoinControlDialog::lockCoin() void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); - model->unlockCoin(outpt); + model->wallet().unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); @@ -405,7 +405,7 @@ void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) void CoinControlDialog::updateLabelLocked() { std::vector<COutPoint> vOutpts; - model->listLockedCoins(vOutpts); + model->wallet().listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); @@ -431,7 +431,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { CTxOut txout(amount, static_cast<CScript>(std::vector<unsigned char>(24, 0))); txDummy.vout.push_back(txout); - fDust |= IsDust(txout, ::dustRelayFee); + fDust |= IsDust(txout, model->node().getDustRelayFee()); } } @@ -445,16 +445,16 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) bool fWitness = false; std::vector<COutPoint> vCoinControl; - std::vector<COutput> vOutputs; coinControl()->ListSelected(vCoinControl); - model->getOutputs(vCoinControl, vOutputs); - for (const COutput& out : vOutputs) { + size_t i = 0; + for (const auto& out : model->wallet().getCoins(vCoinControl)) { + if (out.depth_in_main_chain < 0) continue; + // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer - uint256 txhash = out.tx->GetHash(); - COutPoint outpt(txhash, out.i); - if (model->isSpent(outpt)) + const COutPoint& outpt = vCoinControl[i++]; + if (out.is_spent) { coinControl()->UnSelect(outpt); continue; @@ -464,22 +464,22 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) nQuantity++; // Amount - nAmount += out.tx->tx->vout[out.i].nValue; + nAmount += out.txout.nValue; // Bytes CTxDestination address; int witnessversion = 0; std::vector<unsigned char> witnessprogram; - if (out.tx->tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) + if (out.txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4); fWitness = true; } - else if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address)) + else if(ExtractDestination(out.txout.scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&address); - if (keyid && model->getPubKey(*keyid, pubkey)) + if (keyid && model->wallet().getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); } @@ -509,7 +509,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) nBytes -= 34; // Fee - nPayFee = GetMinimumFee(nBytes, *coinControl(), ::mempool, ::feeEstimator, nullptr /* FeeCalculation */); + nPayFee = model->node().getMinimumFee(nBytes, *coinControl(), nullptr /* returned_target */, nullptr /* reason */); if (nPayAmount > 0) { @@ -521,7 +521,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) if (nChange > 0 && nChange < MIN_CHANGE) { CTxOut txout(nChange, static_cast<CScript>(std::vector<unsigned char>(24, 0))); - if (IsDust(txout, ::dustRelayFee)) + if (IsDust(txout, model->node().getDustRelayFee())) { nPayFee += nChange; nChange = 0; @@ -621,13 +621,10 @@ void CoinControlDialog::updateView() int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); - std::map<QString, std::vector<COutput> > mapCoins; - model->listCoins(mapCoins); - - for (const std::pair<QString, std::vector<COutput>>& coins : mapCoins) { + for (const auto& coins : model->wallet().listCoins()) { CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); - QString sWalletAddress = coins.first; + QString sWalletAddress = QString::fromStdString(EncodeDestination(coins.first)); QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); @@ -649,8 +646,10 @@ void CoinControlDialog::updateView() CAmount nSum = 0; int nChildren = 0; - for (const COutput& out : coins.second) { - nSum += out.tx->tx->vout[out.i].nValue; + for (const auto& outpair : coins.second) { + const COutPoint& output = std::get<0>(outpair); + const interfaces::WalletTxOut& out = std::get<1>(outpair); + nSum += out.txout.nValue; nChildren++; CCoinControlWidgetItem *itemOutput; @@ -662,7 +661,7 @@ void CoinControlDialog::updateView() // address CTxDestination outputAddress; QString sAddress = ""; - if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, outputAddress)) + if(ExtractDestination(out.txout.scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(EncodeDestination(outputAddress)); @@ -687,35 +686,33 @@ void CoinControlDialog::updateView() } // amount - itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue)); - itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->tx->vout[out.i].nValue)); // padding so that sorting works correctly + itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.txout.nValue)); + itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.txout.nValue)); // padding so that sorting works correctly // date - itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); - itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime())); + itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.time)); + itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.time)); // confirmations - itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth)); - itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth)); + itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.depth_in_main_chain)); + itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.depth_in_main_chain)); // transaction hash - uint256 txhash = out.tx->GetHash(); - itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); + itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(output.hash.GetHex())); // vout index - itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); + itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(output.n)); // disable locked coins - if (model->isLockedCoin(txhash, out.i)) + if (model->wallet().isLockedCoin(output)) { - COutPoint outpt(txhash, out.i); - coinControl()->UnSelect(outpt); // just to be sure + coinControl()->UnSelect(output); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); } // set checkbox - if (coinControl()->IsSelected(COutPoint(txhash, out.i))) + if (coinControl()->IsSelected(output)) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp index 7b653a99da..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 <init.h> +#include <interfaces/node.h> #include <policy/policy.h> #include <protocol.h> #include <script/script.h> @@ -232,12 +232,12 @@ QString formatBitcoinURI(const SendCoinsRecipient &info) return ret; } -bool isDust(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); CTxOut txOut(amount, script); - return IsDust(txOut, ::dustRelayFee); + return IsDust(txOut, node.getDustRelayFee()); } QString HtmlEscape(const QString& str, bool fMultiLine) @@ -599,7 +599,7 @@ TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* t #ifdef WIN32 fs::path static StartupShortcutPath() { - std::string chain = ChainNameFromCommandLine(); + std::string chain = gArgs.GetChainName(); if (chain == CBaseChainParams::MAIN) return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk"; if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4" @@ -697,7 +697,7 @@ fs::path static GetAutostartDir() fs::path static GetAutostartFilePath() { - std::string chain = ChainNameFromCommandLine(); + std::string chain = gArgs.GetChainName(); if (chain == CBaseChainParams::MAIN) return GetAutostartDir() / "bitcoin.desktop"; return GetAutostartDir() / strprintf("bitcoin-%s.lnk", chain); @@ -739,7 +739,7 @@ bool SetStartOnSystemStartup(bool fAutoStart) fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; - std::string chain = ChainNameFromCommandLine(); + std::string chain = gArgs.GetChainName(); // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h index bbbeaf2c43..4a26964098 100644 --- a/src/qt/guiutil.h +++ b/src/qt/guiutil.h @@ -20,6 +20,11 @@ class QValidatedLineEdit; class SendCoinsRecipient; +namespace interfaces +{ + class Node; +} + QT_BEGIN_NAMESPACE class QAbstractItemView; class QDateTime; @@ -49,7 +54,7 @@ namespace GUIUtil QString formatBitcoinURI(const SendCoinsRecipient &info); // Returns true if given address+amount meets "dust" definition - bool isDust(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 e69f196238..8c00ca0363 100644 --- a/src/qt/intro.cpp +++ b/src/qt/intro.cpp @@ -12,6 +12,7 @@ #include <qt/guiutil.h> +#include <interfaces/node.h> #include <util.h> #include <QFileDialog> @@ -186,7 +187,7 @@ QString Intro::getDefaultDataDirectory() return GUIUtil::boostPathToQString(GetDefaultDataDir()); } -bool Intro::pickDataDirectory() +bool Intro::pickDataDirectory(interfaces::Node& node) { QSettings settings; /* If data directory provided on command line, no need to look at settings @@ -233,8 +234,9 @@ bool Intro::pickDataDirectory() * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ - if(dataDir != getDefaultDataDirectory()) - gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting + if(dataDir != getDefaultDataDirectory()) { + node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting + } return true; } diff --git a/src/qt/intro.h b/src/qt/intro.h index 5b428b379c..b0937aedcb 100644 --- a/src/qt/intro.h +++ b/src/qt/intro.h @@ -13,6 +13,10 @@ static const bool DEFAULT_CHOOSE_DATADIR = false; class FreespaceChecker; +namespace interfaces { + class Node; +} + namespace Ui { class Intro; } @@ -41,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(); + 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 5bef473c63..c0ddb89b40 100644 --- a/src/qt/optionsdialog.cpp +++ b/src/qt/optionsdialog.cpp @@ -13,6 +13,7 @@ #include <qt/guiutil.h> #include <qt/optionsmodel.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 @@ -313,17 +314,17 @@ void OptionsDialog::updateDefaultProxyNets() std::string strProxy; QString strDefaultProxyGUI; - GetProxy(NET_IPV4, proxy); + model->node().getProxy(NET_IPV4, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv4->setChecked(true) : ui->proxyReachIPv4->setChecked(false); - GetProxy(NET_IPV6, proxy); + model->node().getProxy(NET_IPV6, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv6->setChecked(true) : ui->proxyReachIPv6->setChecked(false); - GetProxy(NET_TOR, proxy); + model->node().getProxy(NET_TOR, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachTor->setChecked(true) : ui->proxyReachTor->setChecked(false); diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index 909be1c264..30c8124c58 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -11,26 +11,21 @@ #include <qt/bitcoinunits.h> #include <qt/guiutil.h> -#include <init.h> +#include <interfaces/node.h> #include <validation.h> // For DEFAULT_SCRIPTCHECK_THREADS #include <net.h> #include <netbase.h> #include <txdb.h> // for -dbcache defaults #include <qt/intro.h> -#ifdef ENABLE_WALLET -#include <wallet/wallet.h> -#include <wallet/walletdb.h> -#endif - #include <QNetworkProxy> #include <QSettings> #include <QStringList> const char *DEFAULT_GUI_PROXY_HOST = "127.0.0.1"; -OptionsModel::OptionsModel(QObject *parent, bool resetSettings) : - QAbstractListModel(parent) +OptionsModel::OptionsModel(interfaces::Node& node, QObject *parent, bool resetSettings) : + QAbstractListModel(parent), m_node(node) { Init(resetSettings); } @@ -93,12 +88,12 @@ void OptionsModel::Init(bool resetSettings) // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); - if (!gArgs.SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) + if (!m_node.softSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); - if (!gArgs.SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) + if (!m_node.softSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); if (!settings.contains("strDataDir")) @@ -108,19 +103,19 @@ void OptionsModel::Init(bool resetSettings) #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); - if (!gArgs.SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) + if (!m_node.softSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); - if (!gArgs.SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) + if (!m_node.softSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); - if (!gArgs.SoftSetBoolArg("-listen", settings.value("fListen").toBool())) + if (!m_node.softSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) @@ -128,7 +123,7 @@ void OptionsModel::Init(bool resetSettings) if (!settings.contains("addrProxy")) settings.setValue("addrProxy", QString("%1:%2").arg(DEFAULT_GUI_PROXY_HOST, DEFAULT_GUI_PROXY_PORT)); // Only try to set -proxy, if user has enabled fUseProxy - if (settings.value("fUseProxy").toBool() && !gArgs.SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) + if (settings.value("fUseProxy").toBool() && !m_node.softSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !gArgs.GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); @@ -138,7 +133,7 @@ void OptionsModel::Init(bool resetSettings) if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", QString("%1:%2").arg(DEFAULT_GUI_PROXY_HOST, DEFAULT_GUI_PROXY_PORT)); // Only try to set -onion, if user has enabled fUseSeparateProxyTor - if (settings.value("fUseSeparateProxyTor").toBool() && !gArgs.SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) + if (settings.value("fUseSeparateProxyTor").toBool() && !m_node.softSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !gArgs.GetArg("-onion", "").empty()) addOverriddenOption("-onion"); @@ -146,7 +141,7 @@ void OptionsModel::Init(bool resetSettings) // Display if (!settings.contains("language")) settings.setValue("language", ""); - if (!gArgs.SoftSetArg("-lang", settings.value("language").toString().toStdString())) + if (!m_node.softSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); @@ -315,12 +310,7 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); - if (value.toBool()) { - StartMapPort(); - } else { - InterruptMapPort(); - StopMapPort(); - } + m_node.mapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); @@ -453,7 +443,7 @@ bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const // Directly query current base proxy, because // GUI settings can be overridden with -proxy. proxyType curProxy; - if (GetProxy(NET_IPV4, curProxy)) { + if (m_node.getProxy(NET_IPV4, curProxy)) { proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName(QString::fromStdString(curProxy.proxy.ToStringIP())); proxy.setPort(curProxy.proxy.GetPort()); diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h index 3f50541eb4..fc1d119a71 100644 --- a/src/qt/optionsmodel.h +++ b/src/qt/optionsmodel.h @@ -9,6 +9,10 @@ #include <QAbstractListModel> +namespace interfaces { +class Node; +} + QT_BEGIN_NAMESPACE class QNetworkProxy; QT_END_NAMESPACE @@ -27,7 +31,7 @@ class OptionsModel : public QAbstractListModel Q_OBJECT public: - explicit OptionsModel(QObject *parent = 0, bool resetSettings = false); + explicit OptionsModel(interfaces::Node& node, QObject *parent = 0, bool resetSettings = false); enum OptionID { StartAtStartup, // bool @@ -75,7 +79,10 @@ public: void setRestartRequired(bool fRequired); bool isRestartRequired() const; + interfaces::Node& node() const { return m_node; } + private: + interfaces::Node& m_node; /* Qt-only settings */ bool fHideTrayIcon; bool fMinimizeToTray; diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index d1c9f17961..8e8788dad3 100644 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -21,6 +21,8 @@ #define DECORATION_SIZE 54 #define NUM_ITEMS 5 +Q_DECLARE_METATYPE(interfaces::WalletBalances) + class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT @@ -113,16 +115,12 @@ OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) ui(new Ui::OverviewPage), clientModel(0), walletModel(0), - currentBalance(-1), - currentUnconfirmedBalance(-1), - currentImmatureBalance(-1), - currentWatchOnlyBalance(-1), - currentWatchUnconfBalance(-1), - currentWatchImmatureBalance(-1), txdelegate(new TxViewDelegate(platformStyle, this)) { ui->setupUi(this); + m_balances.balance = -1; + // use a SingleColorIcon for the "out of sync warning" icon QIcon icon = platformStyle->SingleColorIcon(":/icons/warning"); icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503) @@ -159,28 +157,23 @@ OverviewPage::~OverviewPage() delete ui; } -void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) +void OverviewPage::setBalance(const interfaces::WalletBalances& balances) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); - currentBalance = balance; - currentUnconfirmedBalance = unconfirmedBalance; - currentImmatureBalance = immatureBalance; - currentWatchOnlyBalance = watchOnlyBalance; - currentWatchUnconfBalance = watchUnconfBalance; - currentWatchImmatureBalance = watchImmatureBalance; - ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways)); - ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance, false, BitcoinUnits::separatorAlways)); - ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance, false, BitcoinUnits::separatorAlways)); - ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance, false, BitcoinUnits::separatorAlways)); - ui->labelWatchAvailable->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance, false, BitcoinUnits::separatorAlways)); - ui->labelWatchPending->setText(BitcoinUnits::formatWithUnit(unit, watchUnconfBalance, false, BitcoinUnits::separatorAlways)); - ui->labelWatchImmature->setText(BitcoinUnits::formatWithUnit(unit, watchImmatureBalance, false, BitcoinUnits::separatorAlways)); - ui->labelWatchTotal->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways)); + m_balances = balances; + ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balances.balance, false, BitcoinUnits::separatorAlways)); + ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, balances.unconfirmed_balance, false, BitcoinUnits::separatorAlways)); + ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, balances.immature_balance, false, BitcoinUnits::separatorAlways)); + ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, false, BitcoinUnits::separatorAlways)); + ui->labelWatchAvailable->setText(BitcoinUnits::formatWithUnit(unit, balances.watch_only_balance, false, BitcoinUnits::separatorAlways)); + ui->labelWatchPending->setText(BitcoinUnits::formatWithUnit(unit, balances.unconfirmed_watch_only_balance, false, BitcoinUnits::separatorAlways)); + ui->labelWatchImmature->setText(BitcoinUnits::formatWithUnit(unit, balances.immature_watch_only_balance, false, BitcoinUnits::separatorAlways)); + ui->labelWatchTotal->setText(BitcoinUnits::formatWithUnit(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, false, BitcoinUnits::separatorAlways)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users - bool showImmature = immatureBalance != 0; - bool showWatchOnlyImmature = watchImmatureBalance != 0; + bool showImmature = balances.immature_balance != 0; + bool showWatchOnlyImmature = balances.immature_watch_only_balance != 0; // for symmetry reasons also show immature label when the watch-only one is shown ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature); @@ -231,13 +224,14 @@ void OverviewPage::setWalletModel(WalletModel *model) ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet - setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), - model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); - connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); + interfaces::Wallet& wallet = model->wallet(); + interfaces::WalletBalances balances = wallet.getBalances(); + setBalance(balances); + connect(model, SIGNAL(balanceChanged(interfaces::WalletBalances)), this, SLOT(setBalance(interfaces::WalletBalances))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); - updateWatchOnlyLabels(model->haveWatchOnly()); + updateWatchOnlyLabels(wallet.haveWatchOnly()); connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool))); } @@ -249,9 +243,9 @@ void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { - if(currentBalance != -1) - setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, - currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); + if (m_balances.balance != -1) { + setBalance(m_balances); + } // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); diff --git a/src/qt/overviewpage.h b/src/qt/overviewpage.h index 0ce9f98c8c..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 <amount.h> +#include <interfaces/wallet.h> #include <QWidget> #include <memory> @@ -38,8 +38,7 @@ public: void showOutOfSyncWarning(bool fShow); public Q_SLOTS: - void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, - const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance); + void setBalance(const interfaces::WalletBalances& balances); Q_SIGNALS: void transactionClicked(const QModelIndex &index); @@ -49,12 +48,7 @@ private: Ui::OverviewPage *ui; ClientModel *clientModel; WalletModel *walletModel; - CAmount currentBalance; - CAmount currentUnconfirmedBalance; - CAmount currentImmatureBalance; - CAmount currentWatchOnlyBalance; - CAmount currentWatchUnconfBalance; - CAmount currentWatchImmatureBalance; + interfaces::WalletBalances m_balances; TxViewDelegate *txdelegate; std::unique_ptr<TransactionFilterProxy> filter; diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp index 65ef250440..70cdb3361c 100644 --- a/src/qt/paymentserver.cpp +++ b/src/qt/paymentserver.cpp @@ -9,6 +9,7 @@ #include <qt/optionsmodel.h> #include <chainparams.h> +#include <interfaces/node.h> #include <policy/policy.h> #include <key_io.h> #include <ui_interface.h> @@ -16,6 +17,7 @@ #include <wallet/wallet.h> #include <cstdlib> +#include <memory> #include <openssl/x509_vfy.h> @@ -199,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(int argc, char* argv[]) +void PaymentServer::ipcParseCommandLine(interfaces::Node& node, int argc, char* argv[]) { for (int i = 1; i < argc; i++) { @@ -221,11 +223,11 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[]) auto tempChainParams = CreateChainParams(CBaseChainParams::MAIN); if (IsValidDestinationString(r.address.toStdString(), *tempChainParams)) { - SelectParams(CBaseChainParams::MAIN); + node.selectParams(CBaseChainParams::MAIN); } else { tempChainParams = CreateChainParams(CBaseChainParams::TESTNET); if (IsValidDestinationString(r.address.toStdString(), *tempChainParams)) { - SelectParams(CBaseChainParams::TESTNET); + node.selectParams(CBaseChainParams::TESTNET); } } } @@ -239,11 +241,11 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[]) { if (request.getDetails().network() == "main") { - SelectParams(CBaseChainParams::MAIN); + node.selectParams(CBaseChainParams::MAIN); } else if (request.getDetails().network() == "test") { - SelectParams(CBaseChainParams::TESTNET); + node.selectParams(CBaseChainParams::TESTNET); } } } @@ -526,7 +528,7 @@ bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, Sen if (request.IsInitialized()) { // Payment request network matches client network? - if (!verifyNetwork(request.getDetails())) { + if (!verifyNetwork(optionsModel->node(), request.getDetails())) { Q_EMIT message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."), CClientUIInterface::MSG_ERROR); @@ -583,7 +585,7 @@ bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, Sen // Extract and check amounts CTxOut txOut(sendingTo.second, sendingTo.first); - if (IsDust(txOut, ::dustRelayFee)) { + if (IsDust(txOut, optionsModel->node().getDustRelayFee())) { Q_EMIT message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).") .arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)), CClientUIInterface::MSG_ERROR); @@ -621,7 +623,7 @@ void PaymentServer::fetchRequest(const QUrl& url) netManager->get(netRequest); } -void PaymentServer::fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction) +void PaymentServer::fetchPaymentACK(WalletModel* walletModel, const SendCoinsRecipient& recipient, QByteArray transaction) { const payments::PaymentDetails& details = recipient.paymentRequest.getDetails(); if (!details.has_payment_url()) @@ -640,17 +642,17 @@ void PaymentServer::fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& r // Create a new refund address, or re-use: CPubKey newKey; - if (wallet->GetKeyFromPool(newKey)) { + if (walletModel->wallet().getKeyFromPool(false /* internal */, newKey)) { // BIP70 requests encode the scriptPubKey directly, so we are not restricted to address // types supported by the receiver. As a result, we choose the address format we also // use for change. Despite an actual payment and not change, this is a close match: // it's the output type we use subject to privacy issues, but not restricted by what // other software supports. - const OutputType change_type = wallet->m_default_change_type != OutputType::NONE ? wallet->m_default_change_type : wallet->m_default_address_type; - wallet->LearnRelatedScripts(newKey, change_type); + const OutputType change_type = walletModel->wallet().getDefaultChangeType() != OutputType::NONE ? walletModel->wallet().getDefaultChangeType() : walletModel->wallet().getDefaultAddressType(); + walletModel->wallet().learnRelatedScripts(newKey, change_type); CTxDestination dest = GetDestinationForKey(newKey, change_type); std::string label = tr("Refund from %1").arg(recipient.authenticatedMerchant).toStdString(); - wallet->SetAddressBook(dest, label, "refund"); + walletModel->wallet().setAddressBook(dest, label, "refund"); CScript s = GetScriptForDestination(dest); payments::Output* refund_to = payment.add_refund_to(); @@ -758,14 +760,14 @@ void PaymentServer::handlePaymentACK(const QString& paymentACKMsg) Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL); } -bool PaymentServer::verifyNetwork(const payments::PaymentDetails& requestDetails) +bool PaymentServer::verifyNetwork(interfaces::Node& node, const payments::PaymentDetails& requestDetails) { - bool fVerified = requestDetails.network() == Params().NetworkIDString(); + bool fVerified = requestDetails.network() == node.getNetwork(); if (!fVerified) { qWarning() << QString("PaymentServer::%1: Payment request network \"%2\" doesn't match client network \"%3\".") .arg(__func__) .arg(QString::fromStdString(requestDetails.network())) - .arg(QString::fromStdString(Params().NetworkIDString())); + .arg(QString::fromStdString(node.getNetwork())); } return fVerified; } diff --git a/src/qt/paymentserver.h b/src/qt/paymentserver.h index e262fc6bf7..511fc5bd6e 100644 --- a/src/qt/paymentserver.h +++ b/src/qt/paymentserver.h @@ -40,8 +40,6 @@ class OptionsModel; -class CWallet; - QT_BEGIN_NAMESPACE class QApplication; class QByteArray; @@ -62,7 +60,7 @@ class PaymentServer : public QObject public: // Parse URIs on command line // Returns false on error - static void ipcParseCommandLine(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 @@ -89,7 +87,7 @@ public: void setOptionsModel(OptionsModel *optionsModel); // Verify that the payment request network matches the client network - static bool verifyNetwork(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 @@ -113,7 +111,7 @@ public Q_SLOTS: void uiReady(); // Submit Payment message to a merchant, get back PaymentACK: - void fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction); + void fetchPaymentACK(WalletModel* walletModel, const SendCoinsRecipient& recipient, QByteArray transaction); // Handle an incoming URI, URI with local file scheme or file void handleURIOrFile(const QString& s); diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp index 0a57dcfca3..7e318e3035 100644 --- a/src/qt/peertablemodel.cpp +++ b/src/qt/peertablemodel.cpp @@ -8,6 +8,7 @@ #include <qt/guiconstants.h> #include <qt/guiutil.h> +#include <interfaces/node.h> #include <validation.h> // for cs_main #include <sync.h> @@ -56,38 +57,26 @@ public: std::map<NodeId, int> mapNodeRows; /** Pull a full list of peers from vNodes into our cache */ - void refreshPeers() + void refreshPeers(interfaces::Node& node) { { cachedNodeStats.clear(); - std::vector<CNodeStats> vstats; - if(g_connman) - g_connman->GetNodeStats(vstats); + + interfaces::Node::NodesStats nodes_stats; + node.getNodesStats(nodes_stats); #if QT_VERSION >= 0x040700 - cachedNodeStats.reserve(vstats.size()); + cachedNodeStats.reserve(nodes_stats.size()); #endif - for (const CNodeStats& nodestats : vstats) + for (auto& node_stats : nodes_stats) { CNodeCombinedStats stats; - stats.nodeStateStats.nMisbehavior = 0; - stats.nodeStateStats.nSyncHeight = -1; - stats.nodeStateStats.nCommonHeight = -1; - stats.fNodeStateStatsAvailable = false; - stats.nodeStats = nodestats; + stats.nodeStats = std::get<0>(node_stats); + stats.fNodeStateStatsAvailable = std::get<1>(node_stats); + stats.nodeStateStats = std::get<2>(node_stats); cachedNodeStats.append(stats); } } - // Try to retrieve the CNodeStateStats for each node. - { - TRY_LOCK(cs_main, lockMain); - if (lockMain) - { - for (CNodeCombinedStats &stats : cachedNodeStats) - stats.fNodeStateStatsAvailable = GetNodeStateStats(stats.nodeStats.nodeid, stats.nodeStateStats); - } - } - if (sortColumn >= 0) // sort cacheNodeStats (use stable sort to prevent rows jumping around unnecessarily) qStableSort(cachedNodeStats.begin(), cachedNodeStats.end(), NodeLessThan(sortColumn, sortOrder)); @@ -113,8 +102,9 @@ public: } }; -PeerTableModel::PeerTableModel(ClientModel *parent) : +PeerTableModel::PeerTableModel(interfaces::Node& node, ClientModel *parent) : QAbstractTableModel(parent), + m_node(node), clientModel(parent), timer(0) { @@ -235,7 +225,7 @@ const CNodeCombinedStats *PeerTableModel::getNodeStats(int idx) void PeerTableModel::refresh() { Q_EMIT layoutAboutToBeChanged(); - priv->refreshPeers(); + priv->refreshPeers(m_node); Q_EMIT layoutChanged(); } diff --git a/src/qt/peertablemodel.h b/src/qt/peertablemodel.h index e3c9c6e5a3..69c9744c8f 100644 --- a/src/qt/peertablemodel.h +++ b/src/qt/peertablemodel.h @@ -8,12 +8,18 @@ #include <net_processing.h> // For CNodeStateStats #include <net.h> +#include <memory> + #include <QAbstractTableModel> #include <QStringList> class ClientModel; class PeerTablePriv; +namespace interfaces { +class Node; +} + QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE @@ -45,7 +51,7 @@ class PeerTableModel : public QAbstractTableModel Q_OBJECT public: - explicit PeerTableModel(ClientModel *parent = 0); + explicit PeerTableModel(interfaces::Node& node, ClientModel *parent = 0); ~PeerTableModel(); const CNodeCombinedStats *getNodeStats(int idx); int getRowByNodeId(NodeId nodeid); @@ -76,6 +82,7 @@ public Q_SLOTS: void refresh(); private: + interfaces::Node& m_node; ClientModel *clientModel; QStringList columns; std::unique_ptr<PeerTablePriv> priv; diff --git a/src/qt/receivecoinsdialog.cpp b/src/qt/receivecoinsdialog.cpp index c8b6366db0..70e11f0296 100644 --- a/src/qt/receivecoinsdialog.cpp +++ b/src/qt/receivecoinsdialog.cpp @@ -95,13 +95,13 @@ void ReceiveCoinsDialog::setModel(WalletModel *_model) columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this); // configure bech32 checkbox, disable if launched with legacy as default: - if (model->getDefaultAddressType() == OutputType::BECH32) { + if (model->wallet().getDefaultAddressType() == OutputType::BECH32) { ui->useBech32->setCheckState(Qt::Checked); } else { ui->useBech32->setCheckState(Qt::Unchecked); } - ui->useBech32->setVisible(model->getDefaultAddressType() != OutputType::LEGACY); + ui->useBech32->setVisible(model->wallet().getDefaultAddressType() != OutputType::LEGACY); } } @@ -144,7 +144,7 @@ void ReceiveCoinsDialog::on_receiveButton_clicked() QString address; QString label = ui->reqLabel->text(); /* Generate new receiving address */ - OutputType address_type = model->getDefaultAddressType(); + OutputType address_type = model->wallet().getDefaultAddressType(); if (address_type != OutputType::LEGACY) { address_type = ui->useBech32->isChecked() ? OutputType::BECH32 : OutputType::P2SH_SEGWIT; } diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp index f045053c3b..1c910926d4 100644 --- a/src/qt/recentrequeststablemodel.cpp +++ b/src/qt/recentrequeststablemodel.cpp @@ -12,10 +12,9 @@ #include <streams.h> -RecentRequestsTableModel::RecentRequestsTableModel(CWallet *wallet, WalletModel *parent) : +RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) : QAbstractTableModel(parent), walletModel(parent) { - Q_UNUSED(wallet); nReceiveRequestsMaxId = 0; // Load entries from wallet diff --git a/src/qt/recentrequeststablemodel.h b/src/qt/recentrequeststablemodel.h index ebad98cee8..80c7834a19 100644 --- a/src/qt/recentrequeststablemodel.h +++ b/src/qt/recentrequeststablemodel.h @@ -11,8 +11,6 @@ #include <QStringList> #include <QDateTime> -class CWallet; - class RecentRequestEntry { public: @@ -60,7 +58,7 @@ class RecentRequestsTableModel: public QAbstractTableModel Q_OBJECT public: - explicit RecentRequestsTableModel(CWallet *wallet, WalletModel *parent); + explicit RecentRequestsTableModel(WalletModel *parent); ~RecentRequestsTableModel(); enum ColumnIndex { diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp index c41e19f6f5..5122bab36f 100644 --- a/src/qt/rpcconsole.cpp +++ b/src/qt/rpcconsole.cpp @@ -14,6 +14,7 @@ #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <chainparams.h> +#include <interfaces/node.h> #include <netbase.h> #include <rpc/server.h> #include <rpc/client.h> @@ -83,12 +84,17 @@ const QStringList historyFilter = QStringList() class RPCExecutor : public QObject { Q_OBJECT +public: + RPCExecutor(interfaces::Node& node) : m_node(node) {} public Q_SLOTS: void request(const QString &command, const QString &walletID); Q_SIGNALS: void reply(int category, const QString &command); + +private: + interfaces::Node& m_node; }; /** Class for handling RPC timers @@ -140,13 +146,14 @@ public: * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * + * @param[in] node optional node to execute command on * @param[out] result stringified Result from the executed command(chain) * @param[in] strCommand Command line to split * @param[in] fExecute set true if you want the command to be executed * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data */ -bool RPCConsole::RPCParseCommandLine(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>()); @@ -300,16 +307,17 @@ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string & if (fExecute) { // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. - JSONRPCRequest req; - req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); - req.strMethod = stack.back()[0]; + UniValue params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); + std::string method = stack.back()[0]; + std::string uri; #ifdef ENABLE_WALLET if (walletID && !walletID->empty()) { QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(*walletID)); - req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length()); + uri = "/wallet/"+std::string(encodedName.constData(), encodedName.length()); } #endif - lastResult = tableRPC.execute(req); + assert(node); + lastResult = node->executeRpc(method, params, uri); } state = STATE_COMMAND_EXECUTED; @@ -416,7 +424,7 @@ void RPCExecutor::request(const QString &command, const QString &walletID) return; } std::string wallet_id = walletID.toStdString(); - if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand, nullptr, &wallet_id)) + if(!RPCConsole::RPCExecuteCommandLine(m_node, result, executableCommand, nullptr, &wallet_id)) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; @@ -443,8 +451,9 @@ void RPCExecutor::request(const QString &command, const QString &walletID) } } -RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) : +RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) : QWidget(parent), + m_node(node), ui(new Ui::RPCConsole), clientModel(0), historyPtr(0), @@ -493,7 +502,7 @@ RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) : rpcTimerInterface = new QtRPCTimerInterface(); // avoid accidentally overwriting an existing, non QTThread // based timer interface - RPCSetTimerInterfaceIfUnset(rpcTimerInterface); + m_node.rpcSetTimerInterfaceIfUnset(rpcTimerInterface); setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS); @@ -508,7 +517,7 @@ RPCConsole::~RPCConsole() { QSettings settings; settings.setValue("RPCConsoleWindowGeometry", saveGeometry()); - RPCUnsetTimerInterface(rpcTimerInterface); + m_node.rpcUnsetTimerInterface(rpcTimerInterface); delete rpcTimerInterface; delete ui; } @@ -566,13 +575,14 @@ void RPCConsole::setClientModel(ClientModel *model) setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); - setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false); + 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))); updateNetworkState(); connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool))); - updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent()); + updateTrafficStats(node.getTotalBytesRecv(), node.getTotalBytesSent()); connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64))); connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t))); @@ -667,7 +677,7 @@ void RPCConsole::setClientModel(ClientModel *model) //Setup autocomplete and attach it QStringList wordList; - std::vector<std::string> commandList = tableRPC.listCommands(); + std::vector<std::string> commandList = m_node.listRpcCommands(); for (size_t i = 0; i < commandList.size(); ++i) { wordList << commandList[i].c_str(); @@ -835,7 +845,7 @@ void RPCConsole::updateNetworkState() connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / "; connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")"; - if(!clientModel->getNetworkActive()) { + if(!clientModel->node().getNetworkActive()) { connections += " (" + tr("Network activity disabled") + ")"; } @@ -882,7 +892,7 @@ void RPCConsole::on_lineEdit_returnPressed() std::string strFilteredCmd; try { std::string dummy; - if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) { + if (!RPCParseCommandLine(nullptr, dummy, cmd.toStdString(), false, &strFilteredCmd)) { // Failed to parse command, so we cannot even filter it for the history throw std::runtime_error("Invalid command line"); } @@ -955,7 +965,7 @@ void RPCConsole::browseHistory(int offset) void RPCConsole::startExecutor() { - RPCExecutor *executor = new RPCExecutor(); + RPCExecutor *executor = new RPCExecutor(m_node); executor->moveToThread(&thread); // Replies from executor object must go to this object @@ -1181,9 +1191,6 @@ void RPCConsole::showBanTableContextMenu(const QPoint& point) void RPCConsole::disconnectSelectedNode() { - if(!g_connman) - return; - // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) @@ -1191,14 +1198,14 @@ void RPCConsole::disconnectSelectedNode() // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Find the node, disconnect it and clear the selected node - if(g_connman->DisconnectNode(id)) + if(m_node.disconnect(id)) clearSelectedNode(); } } void RPCConsole::banSelectedNode(int bantime) { - if (!clientModel || !g_connman) + if (!clientModel) return; // Get selected peer addresses @@ -1216,7 +1223,7 @@ void RPCConsole::banSelectedNode(int bantime) // Find possible nodes, ban it and clear the selected node const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); if(stats) { - g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime); + m_node.ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime); } } clearSelectedNode(); @@ -1237,9 +1244,8 @@ void RPCConsole::unbanSelectedNode() CSubNet possibleSubnet; LookupSubNet(strNode.toStdString().c_str(), possibleSubnet); - if (possibleSubnet.IsValid() && g_connman) + if (possibleSubnet.IsValid() && m_node.unban(possibleSubnet)) { - g_connman->Unban(possibleSubnet); clientModel->getBanTableModel()->refresh(); } } diff --git a/src/qt/rpcconsole.h b/src/qt/rpcconsole.h index c97260b2c3..a9a60d09f1 100644 --- a/src/qt/rpcconsole.h +++ b/src/qt/rpcconsole.h @@ -19,6 +19,10 @@ class PlatformStyle; class RPCTimerInterface; class WalletModel; +namespace interfaces { + class Node; +} + namespace Ui { class RPCConsole; } @@ -34,12 +38,12 @@ class RPCConsole: public QWidget Q_OBJECT public: - explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent); + explicit RPCConsole(interfaces::Node& node, const PlatformStyle *platformStyle, QWidget *parent); ~RPCConsole(); - static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr); - static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr) { - return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut, walletID); + 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); } void setClientModel(ClientModel *model); @@ -140,6 +144,7 @@ private: }; + interfaces::Node& m_node; Ui::RPCConsole *ui; ClientModel *clientModel; QStringList history; diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp index 8a52aadbb0..0874a0ada4 100644 --- a/src/qt/sendcoinsdialog.cpp +++ b/src/qt/sendcoinsdialog.cpp @@ -15,9 +15,9 @@ #include <qt/sendcoinsentry.h> #include <chainparams.h> +#include <interfaces/node.h> #include <key_io.h> #include <wallet/coincontrol.h> -#include <validation.h> // mempool and minRelayTxFee #include <ui_interface.h> #include <txmempool.h> #include <policy/fees.h> @@ -149,9 +149,9 @@ void SendCoinsDialog::setModel(WalletModel *_model) } } - setBalance(_model->getBalance(), _model->getUnconfirmedBalance(), _model->getImmatureBalance(), - _model->getWatchBalance(), _model->getWatchUnconfirmedBalance(), _model->getWatchImmatureBalance()); - connect(_model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); + interfaces::WalletBalances balances = _model->wallet().getBalances(); + setBalance(balances); + connect(_model, SIGNAL(balanceChanged(interfaces::WalletBalances)), this, SLOT(setBalance(interfaces::WalletBalances))); connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); @@ -175,7 +175,7 @@ void SendCoinsDialog::setModel(WalletModel *_model) connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(updateSmartFeeLabel())); connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); - ui->customFee->setSingleStep(GetRequiredFee(1000)); + ui->customFee->setSingleStep(model->node().getRequiredFee(1000)); updateFeeSectionControls(); updateMinFeeLabel(); updateSmartFeeLabel(); @@ -193,7 +193,7 @@ void SendCoinsDialog::setModel(WalletModel *_model) settings.remove("nSmartFeeSliderPosition"); } if (settings.value("nConfTarget").toInt() == 0) - ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->getDefaultConfirmTarget())); + ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->node().getTxConfirmTarget())); else ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(settings.value("nConfTarget").toInt())); } @@ -224,7 +224,7 @@ void SendCoinsDialog::on_sendButton_clicked() SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { - if(entry->validate()) + if(entry->validate(model->node())) { recipients.append(entry->getValue()); } @@ -372,7 +372,7 @@ void SendCoinsDialog::on_sendButton_clicked() accept(); CoinControlDialog::coinControl()->UnSelectAll(); coinControlUpdateLabels(); - Q_EMIT coinsSent(currentTransaction.getTransaction()->GetHash()); + Q_EMIT coinsSent(currentTransaction.getWtx()->get().GetHash()); } fNewRecipientAllowed = true; } @@ -515,24 +515,17 @@ bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv) return true; } -void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, - const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance) +void SendCoinsDialog::setBalance(const interfaces::WalletBalances& balances) { - Q_UNUSED(unconfirmedBalance); - Q_UNUSED(immatureBalance); - Q_UNUSED(watchBalance); - Q_UNUSED(watchUnconfirmedBalance); - Q_UNUSED(watchImmatureBalance); - if(model && model->getOptionsModel()) { - ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance)); + ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balances.balance)); } } void SendCoinsDialog::updateDisplayUnit() { - setBalance(model->getBalance(), 0, 0, 0, 0, 0); + setBalance(model->wallet().getBalances()); ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); updateMinFeeLabel(); updateSmartFeeLabel(); @@ -573,7 +566,7 @@ void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::AbsurdFee: - msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), maxTxFee)); + msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->node().getMaxTxFee())); break; case WalletModel::PaymentRequestExpired: msgParams.first = tr("Payment request expired."); @@ -618,7 +611,7 @@ void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry) } // Calculate available amount to send. - CAmount amount = model->getBalance(&coin_control); + CAmount amount = model->wallet().getAvailableBalance(coin_control); for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* e = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (e && !e->isHidden() && e != entry) { @@ -636,7 +629,7 @@ void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry) void SendCoinsDialog::setMinimumFee() { - ui->customFee->setValue(GetRequiredFee(1000)); + ui->customFee->setValue(model->node().getRequiredFee(1000)); } void SendCoinsDialog::updateFeeSectionControls() @@ -668,7 +661,7 @@ void SendCoinsDialog::updateMinFeeLabel() { if (model && model->getOptionsModel()) ui->checkBoxMinimumFee->setText(tr("Pay only the required fee of %1").arg( - BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), GetRequiredFee(1000)) + "/kB") + BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->node().getRequiredFee(1000)) + "/kB") ); } @@ -692,12 +685,13 @@ void SendCoinsDialog::updateSmartFeeLabel() CCoinControl coin_control; updateCoinControlState(coin_control); coin_control.m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels - FeeCalculation feeCalc; - CFeeRate feeRate = CFeeRate(GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc)); + int returned_target; + FeeReason reason; + CFeeRate feeRate = CFeeRate(model->node().getMinimumFee(1000, coin_control, &returned_target, &reason)); ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); - if (feeCalc.reason == FeeReason::FALLBACK) { + if (reason == FeeReason::FALLBACK) { ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...) ui->labelFeeEstimation->setText(""); ui->fallbackFeeWarningLabel->setVisible(true); @@ -709,7 +703,7 @@ void SendCoinsDialog::updateSmartFeeLabel() else { ui->labelSmartFee2->hide(); - ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", feeCalc.returnedTarget)); + ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", returned_target)); ui->fallbackFeeWarningLabel->setVisible(false); } @@ -814,7 +808,7 @@ void SendCoinsDialog::coinControlChangeEdited(const QString& text) } else // Valid address { - if (!model->IsSpendable(dest)) { + if (!model->wallet().isSpendable(dest)) { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); // confirmation dialog diff --git a/src/qt/sendcoinsdialog.h b/src/qt/sendcoinsdialog.h index 48885bbcad..40a1d10c2b 100644 --- a/src/qt/sendcoinsdialog.h +++ b/src/qt/sendcoinsdialog.h @@ -51,8 +51,7 @@ public Q_SLOTS: void accept(); SendCoinsEntry *addEntry(); void updateTabsAndLabels(); - void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, - const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance); + 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 b7decbb69b..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() +bool SendCoinsEntry::validate(interfaces::Node& node) { if (!model) return false; @@ -158,7 +158,7 @@ bool SendCoinsEntry::validate() } // Reject dust outputs: - if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) { + if (retval && GUIUtil::isDust(node, ui->payTo->text(), ui->payAmount->value())) { ui->payAmount->setValid(false); retval = false; } diff --git a/src/qt/sendcoinsentry.h b/src/qt/sendcoinsentry.h index a9fdd5938c..76f96c61e0 100644 --- a/src/qt/sendcoinsentry.h +++ b/src/qt/sendcoinsentry.h @@ -30,7 +30,7 @@ public: ~SendCoinsEntry(); void setModel(WalletModel *model); - bool validate(); + bool validate(interfaces::Node& node); SendCoinsRecipient getValue(); /** Return whether the entry is still empty and unedited */ diff --git a/src/qt/signverifymessagedialog.cpp b/src/qt/signverifymessagedialog.cpp index 8dade8df79..94a3ad7987 100644 --- a/src/qt/signverifymessagedialog.cpp +++ b/src/qt/signverifymessagedialog.cpp @@ -140,7 +140,7 @@ void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() } CKey key; - if (!model->getPrivKey(*keyID, key)) + if (!model->wallet().getPrivKey(*keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp index 66e9dd0465..4d972b431c 100644 --- a/src/qt/splashscreen.cpp +++ b/src/qt/splashscreen.cpp @@ -12,22 +12,21 @@ #include <clientversion.h> #include <init.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> +#include <interfaces/wallet.h> #include <util.h> #include <ui_interface.h> #include <version.h> -#ifdef ENABLE_WALLET -#include <wallet/wallet.h> -#endif - #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> #include <QRadialGradient> -SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : - QWidget(0, f), curAlignment(0) +SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) : + QWidget(0, f), curAlignment(0), m_node(node) { // set reference point, paddings int paddingRight = 50; @@ -143,7 +142,7 @@ bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) { if (ev->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev); if(keyEvent->text()[0] == 'q') { - StartShutdown(); + m_node.startShutdown(); } } return QObject::eventFilter(obj, ev); @@ -177,35 +176,34 @@ static void ShowProgress(SplashScreen *splash, const std::string &title, int nPr : _("press q to shutdown")) + strprintf("\n%d", nProgress) + "%"); } - #ifdef ENABLE_WALLET -void SplashScreen::ConnectWallet(CWallet* wallet) +void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet) { - wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2, false)); - connectedWallets.push_back(wallet); + m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2, false))); + m_connected_wallets.emplace_back(std::move(wallet)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client - uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); - uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2, _3)); + 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 - uiInterface.LoadWallet.connect(boost::bind(&SplashScreen::ConnectWallet, this, _1)); + m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { ConnectWallet(std::move(wallet)); }); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client - uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); - uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2, _3)); -#ifdef ENABLE_WALLET - for (CWallet* const & pwallet : connectedWallets) { - pwallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2, false)); + m_handler_init_message->disconnect(); + m_handler_show_progress->disconnect(); + for (auto& handler : m_connected_wallet_handlers) { + handler->disconnect(); } -#endif + m_connected_wallet_handlers.clear(); + m_connected_wallets.clear(); } void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color) @@ -227,6 +225,6 @@ void SplashScreen::paintEvent(QPaintEvent *event) void SplashScreen::closeEvent(QCloseEvent *event) { - StartShutdown(); // allows an "emergency" shutdown during startup + m_node.startShutdown(); // allows an "emergency" shutdown during startup event->ignore(); } diff --git a/src/qt/splashscreen.h b/src/qt/splashscreen.h index e1568e406b..9ef19675d8 100644 --- a/src/qt/splashscreen.h +++ b/src/qt/splashscreen.h @@ -8,9 +8,16 @@ #include <functional> #include <QSplashScreen> -class CWallet; +#include <memory> + class NetworkStyle; +namespace interfaces { +class Handler; +class Node; +class Wallet; +}; + /** Class for the splashscreen with information of the running client. * * @note this is intentionally not a QSplashScreen. Bitcoin Core initialization @@ -22,7 +29,7 @@ class SplashScreen : public QWidget Q_OBJECT public: - explicit SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle); + explicit SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle); ~SplashScreen(); protected: @@ -45,14 +52,19 @@ private: /** Disconnect core signals to splash screen */ void unsubscribeFromCoreSignals(); /** Connect wallet signals to splash screen */ - void ConnectWallet(CWallet*); + void ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet); QPixmap pixmap; QString curMessage; QColor curColor; int curAlignment; - QList<CWallet*> connectedWallets; + 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 29ef4b4c9e..83484b5ce7 100644 --- a/src/qt/test/paymentservertests.cpp +++ b/src/qt/test/paymentservertests.cpp @@ -9,6 +9,7 @@ #include <amount.h> #include <chainparams.h> +#include <interfaces/node.h> #include <random.h> #include <script/script.h> #include <script/standard.h> @@ -66,7 +67,8 @@ static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsig void PaymentServerTests::paymentServerTests() { SelectParams(CBaseChainParams::MAIN); - OptionsModel optionsModel; + auto node = interfaces::MakeNode(); + OptionsModel optionsModel(*node); PaymentServer* server = new PaymentServer(nullptr, false); X509_STORE* caStore = X509_STORE_new(); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64)); @@ -145,7 +147,7 @@ void PaymentServerTests::paymentServerTests() // Ensure the request is initialized, because network "main" is default, even for // uninitialized payment requests and that will fail our test here. QVERIFY(r.paymentRequest.IsInitialized()); - QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false); + QCOMPARE(PaymentServer::verifyNetwork(*node, r.paymentRequest.getDetails()), false); // Expired payment request (expires is set to 1 = 1970-01-01 00:00:01): data = DecodeBase64(paymentrequest2_cert2_BASE64); diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp index 9d0e0b97d1..974e7831c4 100644 --- a/src/qt/test/rpcnestedtests.cpp +++ b/src/qt/test/rpcnestedtests.cpp @@ -7,6 +7,7 @@ #include <chainparams.h> #include <consensus/validation.h> #include <fs.h> +#include <interfaces/node.h> #include <validation.h> #include <rpc/register.h> #include <rpc/server.h> @@ -45,89 +46,90 @@ void RPCNestedTests::rpcNestedTests() std::string result; std::string result2; std::string filtered; - RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path + auto node = interfaces::MakeNode(); + RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path QVERIFY(result=="main"); QVERIFY(filtered == "getblockchaininfo()[chain]"); - RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting - RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)"); + RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting + RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)"); - RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter + RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter - RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo"); + RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo"); QVERIFY(result.substr(0,1) == "{"); - RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()"); + RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()"); QVERIFY(result.substr(0,1) == "{"); - RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated + RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated QVERIFY(result.substr(0,1) == "{"); - (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key + (RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key QVERIFY(result == "null"); - (RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed - (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed + (RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed + (RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed QVERIFY(result == result2); - (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed + (RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed QVERIFY(result == result2); - RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered); + RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered); QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"); QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]"); - RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered); QVERIFY(filtered == "importprivkey(…)"); - RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); - RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); - RPCConsole::RPCParseCommandLine(result, "signrawtransactionwithkey(abc)", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered); QVERIFY(filtered == "signrawtransactionwithkey(…)"); - RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered); QVERIFY(filtered == "walletpassphrase(…)"); - RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered); QVERIFY(filtered == "walletpassphrasechange(…)"); - RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered); QVERIFY(filtered == "help(encryptwallet(…))"); - RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); - RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); - RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered); + RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest"); QVERIFY(result == "[]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''"); QVERIFY(result == "[\"\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\""); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\""); QVERIFY(result == "[\"\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc"); QVERIFY(result == "[\"\",\"abc\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc"); QVERIFY(result == "[\"abc\",\"\",\"abc\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc"); QVERIFY(result == "[\"abc\",\"abc\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc"); QVERIFY(result == "[\"abc\",\"abc\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )"); QVERIFY(result == "[\"abc\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )"); QVERIFY(result == "[\"abc\"]"); - RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )"); + RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )"); QVERIFY(result == "[\"abc\",\"cba\"]"); #if QT_VERSION >= 0x050300 // do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3) - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax - (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments - (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using , - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using , - QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using , + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax + (RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments + (RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using , + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using , + QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using , #endif } diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp index c9898e52ca..fb86cf5ec9 100644 --- a/src/qt/test/wallettests.cpp +++ b/src/qt/test/wallettests.cpp @@ -1,5 +1,6 @@ #include <qt/test/wallettests.h> +#include <interfaces/node.h> #include <qt/bitcoinamountfield.h> #include <qt/callback.h> #include <qt/optionsmodel.h> @@ -19,6 +20,8 @@ #include <qt/recentrequeststablemodel.h> #include <qt/receiverequestdialog.h> +#include <memory> + #include <QAbstractButton> #include <QAction> #include <QApplication> @@ -175,8 +178,11 @@ void TestGUI() std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); SendCoinsDialog sendCoinsDialog(platformStyle.get()); TransactionView transactionView(platformStyle.get()); - OptionsModel optionsModel; - WalletModel walletModel(platformStyle.get(), &wallet, &optionsModel); + auto node = interfaces::MakeNode(); + OptionsModel optionsModel(*node); + vpwallets.insert(vpwallets.begin(), &wallet); + WalletModel walletModel(std::move(node->getWallets()[0]), *node, platformStyle.get(), &optionsModel); + vpwallets.erase(vpwallets.begin()); sendCoinsDialog.setModel(&walletModel); transactionView.setModel(&walletModel); @@ -201,7 +207,7 @@ void TestGUI() QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance"); QString balanceText = balanceLabel->text(); int unit = walletModel.getOptionsModel()->getDisplayUnit(); - CAmount balance = walletModel.getBalance(); + CAmount balance = walletModel.wallet().getBalance(); QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways); QCOMPARE(balanceText, balanceComparison); diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp index f869799462..5a3b645f65 100644 --- a/src/qt/trafficgraphwidget.cpp +++ b/src/qt/trafficgraphwidget.cpp @@ -2,6 +2,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include <interfaces/node.h> #include <qt/trafficgraphwidget.h> #include <qt/clientmodel.h> @@ -35,8 +36,8 @@ void TrafficGraphWidget::setClientModel(ClientModel *model) { clientModel = model; if(model) { - nLastBytesIn = model->getTotalBytesRecv(); - nLastBytesOut = model->getTotalBytesSent(); + nLastBytesIn = model->node().getTotalBytesRecv(); + nLastBytesOut = model->node().getTotalBytesSent(); } } @@ -123,8 +124,8 @@ void TrafficGraphWidget::updateRates() { if(!clientModel) return; - quint64 bytesIn = clientModel->getTotalBytesRecv(), - bytesOut = clientModel->getTotalBytesSent(); + quint64 bytesIn = clientModel->node().getTotalBytesRecv(), + bytesOut = clientModel->node().getTotalBytesSent(); float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval(); float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval(); vSamplesIn.push_front(inRate); @@ -169,8 +170,8 @@ void TrafficGraphWidget::clear() fMax = 0.0f; if(clientModel) { - nLastBytesIn = clientModel->getTotalBytesRecv(); - nLastBytesOut = clientModel->getTotalBytesSent(); + nLastBytesIn = clientModel->node().getTotalBytesRecv(); + nLastBytesOut = clientModel->node().getTotalBytesSent(); } timer->start(); } diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp index ec5a66bc9f..f316c3ca45 100644 --- a/src/qt/transactiondesc.cpp +++ b/src/qt/transactiondesc.cpp @@ -10,6 +10,7 @@ #include <qt/transactionrecord.h> #include <consensus/consensus.h> +#include <interfaces/node.h> #include <key_io.h> #include <validation.h> #include <script/script.h> @@ -22,25 +23,24 @@ #include <stdint.h> #include <string> -QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) +QString TransactionDesc::FormatTxStatus(const interfaces::WalletTx& wtx, const interfaces::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime) { - AssertLockHeld(cs_main); - if (!CheckFinalTx(*wtx.tx)) + if (!status.is_final) { if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD) - return tr("Open for %n more block(s)", "", wtx.tx->nLockTime - chainActive.Height()); + return tr("Open for %n more block(s)", "", wtx.tx->nLockTime - numBlocks); else return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime)); } else { - int nDepth = wtx.GetDepthInMainChain(); + int nDepth = status.depth_in_main_chain; if (nDepth < 0) return tr("conflicted with a transaction with %1 confirmations").arg(-nDepth); - else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) + else if (adjustedTime - status.time_received > 2 * 60 && status.request_count == 0) return tr("%1/offline").arg(nDepth); else if (nDepth == 0) - return tr("0/unconfirmed, %1").arg((wtx.InMempool() ? tr("in memory pool") : tr("not in memory pool"))) + (wtx.isAbandoned() ? ", "+tr("abandoned") : ""); + return tr("0/unconfirmed, %1").arg((inMempool ? tr("in memory pool") : tr("not in memory pool"))) + (status.is_abandoned ? ", "+tr("abandoned") : ""); else if (nDepth < 6) return tr("%1/unconfirmed").arg(nDepth); else @@ -48,21 +48,27 @@ QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) } } -QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit) +QString TransactionDesc::toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit) { + int numBlocks; + int64_t adjustedTime; + interfaces::WalletTxStatus status; + interfaces::WalletOrderForm orderForm; + bool inMempool; + interfaces::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime); + QString strHTML; - LOCK2(cs_main, wallet->cs_wallet); strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; - int64_t nTime = wtx.GetTxTime(); - CAmount nCredit = wtx.GetCredit(ISMINE_ALL); - CAmount nDebit = wtx.GetDebit(ISMINE_ALL); + int64_t nTime = wtx.time; + CAmount nCredit = wtx.credit; + CAmount nDebit = wtx.debit; CAmount nNet = nCredit - nDebit; - strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx); - int nRequests = wtx.GetRequestCount(); + strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx, status, inMempool, numBlocks, adjustedTime); + int nRequests = status.request_count; if (nRequests != -1) { if (nRequests == 0) @@ -77,14 +83,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // // From // - if (wtx.IsCoinBase()) + if (wtx.is_coinbase) { strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>"; } - else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty()) + else if (wtx.value_map.count("from") && !wtx.value_map["from"].empty()) { // Online transaction - strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>"; + strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.value_map["from"]) + "<br>"; } else { @@ -94,14 +100,16 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // Credit CTxDestination address = DecodeDestination(rec->address); if (IsValidDestination(address)) { - if (wallet->mapAddressBook.count(address)) + std::string name; + isminetype ismine; + if (wallet.getAddress(address, &name, &ismine)) { strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>"; strHTML += "<b>" + tr("To") + ":</b> "; strHTML += GUIUtil::HtmlEscape(rec->address); - QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only"); - if (!wallet->mapAddressBook[address].name.empty()) - strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")"; + QString addressOwned = ismine == ISMINE_SPENDABLE ? tr("own address") : tr("watch-only"); + if (!name.empty()) + strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(name) + ")"; else strHTML += " (" + addressOwned + ")"; strHTML += "<br>"; @@ -113,31 +121,32 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // // To // - if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty()) + if (wtx.value_map.count("to") && !wtx.value_map["to"].empty()) { // Online transaction - std::string strAddress = wtx.mapValue["to"]; + std::string strAddress = wtx.value_map["to"]; strHTML += "<b>" + tr("To") + ":</b> "; CTxDestination dest = DecodeDestination(strAddress); - if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty()) - strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " "; + std::string name; + if (wallet.getAddress(dest, &name) && !name.empty()) + strHTML += GUIUtil::HtmlEscape(name) + " "; strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>"; } // // Amount // - if (wtx.IsCoinBase() && nCredit == 0) + if (wtx.is_coinbase && nCredit == 0) { // // Coinbase // CAmount nUnmatured = 0; for (const CTxOut& txout : wtx.tx->vout) - nUnmatured += wallet->GetCredit(txout, ISMINE_ALL); + nUnmatured += wallet.getCredit(txout, ISMINE_ALL); strHTML += "<b>" + tr("Credit") + ":</b> "; - if (wtx.IsInMainChain()) - strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")"; + if (status.is_in_main_chain) + strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", status.blocks_to_maturity) + ")"; else strHTML += "(" + tr("not accepted") + ")"; strHTML += "<br>"; @@ -152,16 +161,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco else { isminetype fAllFromMe = ISMINE_SPENDABLE; - for (const CTxIn& txin : wtx.tx->vin) + for (isminetype mine : wtx.txin_is_mine) { - isminetype mine = wallet->IsMine(txin); if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; - for (const CTxOut& txout : wtx.tx->vout) + for (isminetype mine : wtx.txout_is_mine) { - isminetype mine = wallet->IsMine(txout); if(fAllToMe > mine) fAllToMe = mine; } @@ -173,22 +180,24 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // // Debit // + auto mine = wtx.txout_is_mine.begin(); for (const CTxOut& txout : wtx.tx->vout) { // Ignore change - isminetype toSelf = wallet->IsMine(txout); + isminetype toSelf = *(mine++); if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE)) continue; - if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty()) + if (!wtx.value_map.count("to") || wtx.value_map["to"].empty()) { // Offline transaction CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { strHTML += "<b>" + tr("To") + ":</b> "; - if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) - strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; + std::string name; + if (wallet.getAddress(address, &name) && !name.empty()) + strHTML += GUIUtil::HtmlEscape(name) + " "; strHTML += GUIUtil::HtmlEscape(EncodeDestination(address)); if(toSelf == ISMINE_SPENDABLE) strHTML += " (own address)"; @@ -206,7 +215,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco if (fAllToMe) { // Payment to self - CAmount nChange = wtx.GetChange(); + CAmount nChange = wtx.change; CAmount nValue = nCredit - nChange; strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>"; strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>"; @@ -221,12 +230,18 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // // Mixed debit transaction // - for (const CTxIn& txin : wtx.tx->vin) - if (wallet->IsMine(txin)) - strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; - for (const CTxOut& txout : wtx.tx->vout) - if (wallet->IsMine(txout)) - strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; + auto mine = wtx.txin_is_mine.begin(); + for (const CTxIn& txin : wtx.tx->vin) { + if (*(mine++)) { + strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet.getDebit(txin, ISMINE_ALL)) + "<br>"; + } + } + mine = wtx.txout_is_mine.begin(); + for (const CTxOut& txout : wtx.tx->vout) { + if (*(mine++)) { + strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet.getCredit(txout, ISMINE_ALL)) + "<br>"; + } + } } } @@ -235,10 +250,10 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // // Message // - if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty()) - strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>"; - if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty()) - strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>"; + if (wtx.value_map.count("message") && !wtx.value_map["message"].empty()) + strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.value_map["message"], true) + "<br>"; + if (wtx.value_map.count("comment") && !wtx.value_map["comment"].empty()) + strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.value_map["comment"], true) + "<br>"; strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxHash() + "<br>"; strHTML += "<b>" + tr("Transaction total size") + ":</b> " + QString::number(wtx.tx->GetTotalSize()) + " bytes<br>"; @@ -246,14 +261,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>"; // Message from normal bitcoin:URI (bitcoin:123...?message=example) - for (const std::pair<std::string, std::string>& r : wtx.vOrderForm) + for (const std::pair<std::string, std::string>& r : orderForm) if (r.first == "Message") strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>"; // // PaymentRequest info: // - for (const std::pair<std::string, std::string>& r : wtx.vOrderForm) + for (const std::pair<std::string, std::string>& r : orderForm) { if (r.first == "PaymentRequest") { @@ -265,7 +280,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco } } - if (wtx.IsCoinBase()) + if (wtx.is_coinbase) { quint32 numBlocksToMaturity = COINBASE_MATURITY + 1; strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>"; @@ -274,15 +289,15 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco // // Debug view // - if (logCategories != BCLog::NONE) + if (node.getLogCategories() != BCLog::NONE) { strHTML += "<hr><br>" + tr("Debug information") + "<br><br>"; for (const CTxIn& txin : wtx.tx->vin) - if(wallet->IsMine(txin)) - strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; + if(wallet.txinIsMine(txin)) + strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet.getDebit(txin, ISMINE_ALL)) + "<br>"; for (const CTxOut& txout : wtx.tx->vout) - if(wallet->IsMine(txout)) - strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; + if(wallet.txoutIsMine(txout)) + strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet.getCredit(txout, ISMINE_ALL)) + "<br>"; strHTML += "<br><b>" + tr("Transaction") + ":</b><br>"; strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true); @@ -295,7 +310,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco COutPoint prevout = txin.prevout; Coin prev; - if(pcoinsTip->GetCoin(prevout, prev)) + if(node.getUnspentOutput(prevout, prev)) { { strHTML += "<li>"; @@ -303,13 +318,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco CTxDestination address; if (ExtractDestination(vout.scriptPubKey, address)) { - if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) - strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; + std::string name; + if (wallet.getAddress(address, &name) && !name.empty()) + strHTML += GUIUtil::HtmlEscape(name) + " "; strHTML += QString::fromStdString(EncodeDestination(address)); } strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue); - strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>"; - strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>"; + strHTML = strHTML + " IsMine=" + (wallet.txoutIsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>"; + strHTML = strHTML + " IsWatchOnly=" + (wallet.txoutIsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>"; } } } diff --git a/src/qt/transactiondesc.h b/src/qt/transactiondesc.h index 01b90b130f..cb8453cb81 100644 --- a/src/qt/transactiondesc.h +++ b/src/qt/transactiondesc.h @@ -10,8 +10,12 @@ class TransactionRecord; -class CWallet; -class CWalletTx; +namespace interfaces { +class Node; +class Wallet; +struct WalletTx; +struct WalletTxStatus; +} /** Provide a human-readable extended HTML description of a transaction. */ @@ -20,12 +24,12 @@ class TransactionDesc: public QObject Q_OBJECT public: - static QString toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit); + static QString toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit); private: TransactionDesc() {} - static QString FormatTxStatus(const CWalletTx& wtx); + 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 cc30cf747d..b6ed66ad96 100644 --- a/src/qt/transactionrecord.cpp +++ b/src/qt/transactionrecord.cpp @@ -5,17 +5,17 @@ #include <qt/transactionrecord.h> #include <consensus/consensus.h> +#include <interfaces/wallet.h> #include <key_io.h> -#include <validation.h> #include <timedata.h> -#include <wallet/wallet.h> +#include <validation.h> #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ -bool TransactionRecord::showTransaction(const CWalletTx &wtx) +bool TransactionRecord::showTransaction() { // There are currently no cases where we hide transactions, but // we may want to use this in the future for things like RBF. @@ -25,17 +25,17 @@ bool TransactionRecord::showTransaction(const CWalletTx &wtx) /* * Decompose CWallet transaction to model transaction records. */ -QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) +QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interfaces::WalletTx& wtx) { QList<TransactionRecord> parts; - int64_t nTime = wtx.GetTxTime(); - CAmount nCredit = wtx.GetCredit(ISMINE_ALL); - CAmount nDebit = wtx.GetDebit(ISMINE_ALL); + int64_t nTime = wtx.time; + CAmount nCredit = wtx.credit; + CAmount nDebit = wtx.debit; CAmount nNet = nCredit - nDebit; - uint256 hash = wtx.GetHash(); - std::map<std::string, std::string> mapValue = wtx.mapValue; + uint256 hash = wtx.tx->GetHash(); + std::map<std::string, std::string> mapValue = wtx.value_map; - if (nNet > 0 || wtx.IsCoinBase()) + if (nNet > 0 || wtx.is_coinbase) { // // Credit @@ -43,7 +43,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * for(unsigned int i = 0; i < wtx.tx->vout.size(); i++) { const CTxOut& txout = wtx.tx->vout[i]; - isminetype mine = wallet->IsMine(txout); + isminetype mine = wtx.txout_is_mine[i]; if(mine) { TransactionRecord sub(hash, nTime); @@ -51,11 +51,11 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * sub.idx = i; // vout index sub.credit = txout.nValue; sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; - if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) + if (wtx.txout_address_is_mine[i]) { // Received by Bitcoin Address sub.type = TransactionRecord::RecvWithAddress; - sub.address = EncodeDestination(address); + sub.address = EncodeDestination(wtx.txout_address[i]); } else { @@ -63,7 +63,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } - if (wtx.IsCoinBase()) + if (wtx.is_coinbase) { // Generated sub.type = TransactionRecord::Generated; @@ -77,17 +77,15 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * { bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; - for (const CTxIn& txin : wtx.tx->vin) + for (isminetype mine : wtx.txin_is_mine) { - isminetype mine = wallet->IsMine(txin); if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; - for (const CTxOut& txout : wtx.tx->vout) + for (isminetype mine : wtx.txout_is_mine) { - isminetype mine = wallet->IsMine(txout); if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllToMe > mine) fAllToMe = mine; } @@ -95,7 +93,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * if (fAllFromMe && fAllToMe) { // Payment to self - CAmount nChange = wtx.GetChange(); + CAmount nChange = wtx.change; parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange), nCredit - nChange)); @@ -115,19 +113,18 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * sub.idx = nOut; sub.involvesWatchAddress = involvesWatchAddress; - if(wallet->IsMine(txout)) + if(wtx.txout_is_mine[nOut]) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } - CTxDestination address; - if (ExtractDestination(txout.scriptPubKey, address)) + if (!boost::get<CNoDestination>(&wtx.txout_address[nOut])) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; - sub.address = EncodeDestination(address); + sub.address = EncodeDestination(wtx.txout_address[nOut]); } else { @@ -161,50 +158,46 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet * return parts; } -void TransactionRecord::updateStatus(const CWalletTx &wtx) +void TransactionRecord::updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime) { - AssertLockHeld(cs_main); // Determine transaction status - // Find the block the tx is in - const CBlockIndex* pindex = LookupBlockIndex(wtx.hashBlock); - // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", - (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), - (wtx.IsCoinBase() ? 1 : 0), - wtx.nTimeReceived, + wtx.block_height, + wtx.is_coinbase ? 1 : 0, + wtx.time_received, idx); - status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0); - status.depth = wtx.GetDepthInMainChain(); - status.cur_num_blocks = chainActive.Height(); + status.countsForBalance = wtx.is_trusted && !(wtx.blocks_to_maturity > 0); + status.depth = wtx.depth_in_main_chain; + status.cur_num_blocks = numBlocks; - if (!CheckFinalTx(*wtx.tx)) + if (!wtx.is_final) { - if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD) + if (wtx.lock_time < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; - status.open_for = wtx.tx->nLockTime - chainActive.Height(); + status.open_for = wtx.lock_time - numBlocks; } else { status.status = TransactionStatus::OpenUntilDate; - status.open_for = wtx.tx->nLockTime; + status.open_for = wtx.lock_time; } } // For generated transactions, determine maturity else if(type == TransactionRecord::Generated) { - if (wtx.GetBlocksToMaturity() > 0) + if (wtx.blocks_to_maturity > 0) { status.status = TransactionStatus::Immature; - if (wtx.IsInMainChain()) + if (wtx.is_in_main_chain) { - status.matures_in = wtx.GetBlocksToMaturity(); + status.matures_in = wtx.blocks_to_maturity; // Check if the block was requested by anyone - if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) + if (adjustedTime - wtx.time_received > 2 * 60 && wtx.request_count == 0) status.status = TransactionStatus::MaturesWarning; } else @@ -223,14 +216,14 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx) { status.status = TransactionStatus::Conflicted; } - else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) + else if (adjustedTime - wtx.time_received > 2 * 60 && wtx.request_count == 0) { status.status = TransactionStatus::Offline; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; - if (wtx.isAbandoned()) + if (wtx.is_abandoned) status.status = TransactionStatus::Abandoned; } else if (status.depth < RecommendedNumConfirmations) @@ -245,10 +238,9 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx) status.needsUpdate = false; } -bool TransactionRecord::statusUpdateNeeded() const +bool TransactionRecord::statusUpdateNeeded(int numBlocks) const { - AssertLockHeld(cs_main); - return status.cur_num_blocks != chainActive.Height() || status.needsUpdate; + return status.cur_num_blocks != numBlocks || status.needsUpdate; } QString TransactionRecord::getTxHash() const diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h index 5321d05d15..62961434ed 100644 --- a/src/qt/transactionrecord.h +++ b/src/qt/transactionrecord.h @@ -11,8 +11,12 @@ #include <QList> #include <QString> -class CWallet; -class CWalletTx; +namespace interfaces { +class Node; +class Wallet; +struct WalletTx; +struct WalletTxStatus; +} /** UI model for transaction status. The transaction status is the part of a transaction that will change over time. */ @@ -106,8 +110,8 @@ public: /** Decompose CWallet transaction to model transaction records. */ - static bool showTransaction(const CWalletTx &wtx); - static QList<TransactionRecord> decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx); + static bool showTransaction(); + static QList<TransactionRecord> decomposeTransaction(const interfaces::WalletTx& wtx); /** @name Immutable transaction attributes @{*/ @@ -136,11 +140,11 @@ public: /** Update status from core wallet tx. */ - void updateStatus(const CWalletTx &wtx); + void updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime); /** Return whether a status update is needed. */ - bool statusUpdateNeeded() const; + bool statusUpdateNeeded(int numBlocks) const; }; #endif // BITCOIN_QT_TRANSACTIONRECORD_H diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp index 84800125fe..46169a91d1 100644 --- a/src/qt/transactiontablemodel.cpp +++ b/src/qt/transactiontablemodel.cpp @@ -14,11 +14,12 @@ #include <qt/walletmodel.h> #include <core_io.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <validation.h> #include <sync.h> #include <uint256.h> #include <util.h> -#include <wallet/wallet.h> #include <QColor> #include <QDateTime> @@ -57,13 +58,11 @@ struct TxLessThan class TransactionTablePriv { public: - TransactionTablePriv(CWallet *_wallet, TransactionTableModel *_parent) : - wallet(_wallet), + TransactionTablePriv(TransactionTableModel *_parent) : parent(_parent) { } - CWallet *wallet; TransactionTableModel *parent; /* Local cache of wallet. @@ -74,16 +73,15 @@ public: /* Query entire wallet anew from core. */ - void refreshWallet() + void refreshWallet(interfaces::Wallet& wallet) { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); { - LOCK2(cs_main, wallet->cs_wallet); - for (const auto& entry : wallet->mapWallet) - { - if (TransactionRecord::showTransaction(entry.second)) - cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, entry.second)); + for (const auto& wtx : wallet.getWalletTxs()) { + if (TransactionRecord::showTransaction()) { + cachedWallet.append(TransactionRecord::decomposeTransaction(wtx)); + } } } } @@ -93,7 +91,7 @@ public: Call with transaction that was added, removed or changed. */ - void updateWallet(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); @@ -128,17 +126,16 @@ public: } if(showTransaction) { - LOCK2(cs_main, wallet->cs_wallet); // Find transaction in wallet - std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); - if(mi == wallet->mapWallet.end()) + interfaces::WalletTx wtx = wallet.getWalletTx(hash); + if(!wtx.tx) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet"; break; } // Added -- insert at the right position QList<TransactionRecord> toInsert = - TransactionRecord::decomposeTransaction(wallet, mi->second); + TransactionRecord::decomposeTransaction(wtx); if(!toInsert.isEmpty()) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); @@ -179,7 +176,7 @@ public: return cachedWallet.size(); } - TransactionRecord *index(int idx) + TransactionRecord *index(interfaces::Wallet& wallet, int idx) { if(idx >= 0 && idx < cachedWallet.size()) { @@ -192,61 +189,42 @@ 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. - TRY_LOCK(cs_main, lockMain); - if(lockMain) - { - TRY_LOCK(wallet->cs_wallet, lockWallet); - if(lockWallet && rec->statusUpdateNeeded()) - { - std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); - - if(mi != wallet->mapWallet.end()) - { - rec->updateStatus(mi->second); - } - } + interfaces::WalletTxStatus wtx; + int numBlocks; + int64_t adjustedTime; + if (wallet.tryGetTxStatus(rec->hash, wtx, numBlocks, adjustedTime) && rec->statusUpdateNeeded(numBlocks)) { + rec->updateStatus(wtx, numBlocks, adjustedTime); } return rec; } return 0; } - QString describe(TransactionRecord *rec, int unit) + QString describe(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit) { - { - LOCK2(cs_main, wallet->cs_wallet); - std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); - if(mi != wallet->mapWallet.end()) - { - return TransactionDesc::toHTML(wallet, mi->second, rec, unit); - } - } - return QString(); + return TransactionDesc::toHTML(node, wallet, rec, unit); } - QString getTxHex(TransactionRecord *rec) + QString getTxHex(interfaces::Wallet& wallet, TransactionRecord *rec) { - LOCK2(cs_main, wallet->cs_wallet); - std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); - if(mi != wallet->mapWallet.end()) - { - std::string strHex = EncodeHexTx(*mi->second.tx); + auto tx = wallet.getTx(rec->hash); + if (tx) { + std::string strHex = EncodeHexTx(*tx); return QString::fromStdString(strHex); } return QString(); } }; -TransactionTableModel::TransactionTableModel(const PlatformStyle *_platformStyle, CWallet* _wallet, WalletModel *parent): +TransactionTableModel::TransactionTableModel(const PlatformStyle *_platformStyle, WalletModel *parent): QAbstractTableModel(parent), - wallet(_wallet), walletModel(parent), - priv(new TransactionTablePriv(_wallet, this)), + priv(new TransactionTablePriv(this)), fProcessingQueuedTransactions(false), platformStyle(_platformStyle) { columns << QString() << QString() << tr("Date") << tr("Type") << tr("Label") << BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); - priv->refreshWallet(); + priv->refreshWallet(walletModel->wallet()); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); @@ -271,7 +249,7 @@ void TransactionTableModel::updateTransaction(const QString &hash, int status, b uint256 updated; updated.SetHex(hash.toStdString()); - priv->updateWallet(updated, status, showTransaction); + priv->updateWallet(walletModel->wallet(), updated, status, showTransaction); } void TransactionTableModel::updateConfirmations() @@ -608,7 +586,7 @@ QVariant TransactionTableModel::data(const QModelIndex &index, int role) const case WatchonlyDecorationRole: return txWatchonlyDecoration(rec); case LongDescriptionRole: - return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit()); + return priv->describe(walletModel->node(), walletModel->wallet(), rec, walletModel->getOptionsModel()->getDisplayUnit()); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: @@ -618,7 +596,7 @@ QVariant TransactionTableModel::data(const QModelIndex &index, int role) const case TxHashRole: return rec->getTxHash(); case TxHexRole: - return priv->getTxHex(rec); + return priv->getTxHex(walletModel->wallet(), rec); case TxPlainTextRole: { QString details; @@ -694,10 +672,10 @@ QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientat QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); - TransactionRecord *data = priv->index(row); + TransactionRecord *data = priv->index(walletModel->wallet(), row); if(data) { - return createIndex(row, column, priv->index(row)); + return createIndex(row, column, priv->index(walletModel->wallet(), row)); } return QModelIndex(); } @@ -735,13 +713,11 @@ private: static bool fQueueNotifications = false; static std::vector< TransactionNotification > vQueueNotifications; -static void NotifyTransactionChanged(TransactionTableModel *ttm, CWallet *wallet, const uint256 &hash, ChangeType status) +static void NotifyTransactionChanged(TransactionTableModel *ttm, const uint256 &hash, ChangeType status) { // Find transaction in wallet - std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); // Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread) - bool inWallet = mi != wallet->mapWallet.end(); - bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second)); + bool showTransaction = TransactionRecord::showTransaction(); TransactionNotification notification(hash, status, showTransaction); @@ -777,13 +753,13 @@ static void ShowProgress(TransactionTableModel *ttm, const std::string &title, i void TransactionTableModel::subscribeToCoreSignals() { // Connect signals to wallet - wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); - wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); + m_handler_transaction_changed = walletModel->wallet().handleTransactionChanged(boost::bind(NotifyTransactionChanged, this, _1, _2)); + m_handler_show_progress = walletModel->wallet().handleShowProgress(boost::bind(ShowProgress, this, _1, _2)); } void TransactionTableModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet - wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); - wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); + m_handler_transaction_changed->disconnect(); + m_handler_show_progress->disconnect(); } diff --git a/src/qt/transactiontablemodel.h b/src/qt/transactiontablemodel.h index 781874d160..8b029be5f5 100644 --- a/src/qt/transactiontablemodel.h +++ b/src/qt/transactiontablemodel.h @@ -10,13 +10,17 @@ #include <QAbstractTableModel> #include <QStringList> +#include <memory> + +namespace interfaces { +class Handler; +} + class PlatformStyle; class TransactionRecord; class TransactionTablePriv; class WalletModel; -class CWallet; - /** UI model for the transaction table of a wallet. */ class TransactionTableModel : public QAbstractTableModel @@ -24,7 +28,7 @@ class TransactionTableModel : public QAbstractTableModel Q_OBJECT public: - explicit TransactionTableModel(const PlatformStyle *platformStyle, CWallet* wallet, WalletModel *parent = 0); + explicit TransactionTableModel(const PlatformStyle *platformStyle, WalletModel *parent = 0); ~TransactionTableModel(); enum ColumnIndex { @@ -80,8 +84,9 @@ public: bool processingQueuedTransactions() const { return fProcessingQueuedTransactions; } private: - CWallet* wallet; WalletModel *walletModel; + 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/transactionview.cpp b/src/qt/transactionview.cpp index 26391452da..aa6444245a 100644 --- a/src/qt/transactionview.cpp +++ b/src/qt/transactionview.cpp @@ -254,7 +254,7 @@ void TransactionView::setModel(WalletModel *_model) } // show/hide column Watch-only - updateWatchOnlyColumn(_model->haveWatchOnly()); + updateWatchOnlyColumn(_model->wallet().haveWatchOnly()); // Watch-only signal connect(_model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyColumn(bool))); @@ -364,7 +364,7 @@ void TransactionView::exportClicked() // name, column, role writer.setModel(transactionProxyModel); writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole); - if (model->haveWatchOnly()) + if (model->wallet().haveWatchOnly()) writer.addColumn(tr("Watch-only"), TransactionTableModel::Watchonly); writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole); writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole); @@ -393,8 +393,8 @@ void TransactionView::contextualMenu(const QPoint &point) // check if transaction can be abandoned, disable context menu action in case it doesn't uint256 hash; hash.SetHex(selection.at(0).data(TransactionTableModel::TxHashRole).toString().toStdString()); - abandonAction->setEnabled(model->transactionCanBeAbandoned(hash)); - bumpFeeAction->setEnabled(model->transactionCanBeBumped(hash)); + abandonAction->setEnabled(model->wallet().transactionCanBeAbandoned(hash)); + bumpFeeAction->setEnabled(model->wallet().transactionCanBeBumped(hash)); if(index.isValid()) { @@ -414,7 +414,7 @@ void TransactionView::abandonTx() hash.SetHex(hashQStr.toStdString()); // Abandon the wallet transaction over the walletModel - model->abandonTransaction(hash); + model->wallet().abandonTransaction(hash); // Update the table model->getTransactionTableModel()->updateTransaction(hashQStr, CT_UPDATED, false); diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp index c19e6aae78..d5b98486ae 100644 --- a/src/qt/utilitydialog.cpp +++ b/src/qt/utilitydialog.cpp @@ -19,6 +19,7 @@ #include <clientversion.h> #include <init.h> +#include <interfaces/node.h> #include <util.h> #include <stdio.h> @@ -31,7 +32,7 @@ #include <QVBoxLayout> /** "Help message" or "About" dialog box */ -HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : +HelpMessageDialog::HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about) : QDialog(parent), ui(new Ui::HelpMessageDialog) { @@ -77,7 +78,7 @@ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : cursor.insertText(header); cursor.insertBlock(); - std::string strUsage = HelpMessage(HelpMessageMode::BITCOIN_QT); + std::string strUsage = node.helpMessage(HelpMessageMode::BITCOIN_QT); const bool showDebug = gArgs.GetBoolArg("-help-debug", false); strUsage += HelpMessageGroup(tr("UI Options:").toStdString()); if (showDebug) { diff --git a/src/qt/utilitydialog.h b/src/qt/utilitydialog.h index d43d9a82c0..f5c8af4362 100644 --- a/src/qt/utilitydialog.h +++ b/src/qt/utilitydialog.h @@ -10,6 +10,10 @@ class BitcoinGUI; +namespace interfaces { + class Node; +} + namespace Ui { class HelpMessageDialog; } @@ -20,7 +24,7 @@ class HelpMessageDialog : public QDialog Q_OBJECT public: - explicit HelpMessageDialog(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 795302be58..00b98901c0 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -5,29 +5,20 @@ #include <qt/walletmodel.h> #include <qt/addresstablemodel.h> -#include <consensus/validation.h> #include <qt/guiconstants.h> -#include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/paymentserver.h> #include <qt/recentrequeststablemodel.h> #include <qt/sendcoinsdialog.h> #include <qt/transactiontablemodel.h> -#include <chain.h> +#include <interfaces/handler.h> +#include <interfaces/node.h> #include <key_io.h> -#include <keystore.h> -#include <validation.h> -#include <net.h> // for g_connman -#include <policy/fees.h> -#include <policy/rbf.h> -#include <sync.h> #include <ui_interface.h> #include <util.h> // for GetBoolArg #include <wallet/coincontrol.h> -#include <wallet/feebumper.h> #include <wallet/wallet.h> -#include <wallet/walletdb.h> // for BackupWallet #include <stdint.h> @@ -37,21 +28,19 @@ #include <QTimer> -WalletModel::WalletModel(const PlatformStyle *platformStyle, CWallet *_wallet, OptionsModel *_optionsModel, QObject *parent) : - QObject(parent), wallet(_wallet), optionsModel(_optionsModel), addressTableModel(0), +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), - cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), - cachedWatchOnlyBalance{0}, cachedWatchUnconfBalance{0}, cachedWatchImmatureBalance{0}, cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { - fHaveWatchOnly = wallet->HaveWatchOnly(); + fHaveWatchOnly = m_wallet->haveWatchOnly(); fForceCheckBalanceChanged = false; - addressTableModel = new AddressTableModel(wallet, this); - transactionTableModel = new TransactionTableModel(platformStyle, wallet, this); - recentRequestsTableModel = new RecentRequestsTableModel(wallet, this); + addressTableModel = new AddressTableModel(this); + transactionTableModel = new TransactionTableModel(platformStyle, this); + recentRequestsTableModel = new RecentRequestsTableModel(this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); @@ -66,46 +55,6 @@ WalletModel::~WalletModel() unsubscribeFromCoreSignals(); } -CAmount WalletModel::getBalance(const CCoinControl *coinControl) const -{ - if (coinControl) - { - return wallet->GetAvailableBalance(coinControl); - } - - return wallet->GetBalance(); -} - -CAmount WalletModel::getUnconfirmedBalance() const -{ - return wallet->GetUnconfirmedBalance(); -} - -CAmount WalletModel::getImmatureBalance() const -{ - return wallet->GetImmatureBalance(); -} - -bool WalletModel::haveWatchOnly() const -{ - return fHaveWatchOnly; -} - -CAmount WalletModel::getWatchBalance() const -{ - return wallet->GetWatchOnlyBalance(); -} - -CAmount WalletModel::getWatchUnconfirmedBalance() const -{ - return wallet->GetUnconfirmedWatchOnlyBalance(); -} - -CAmount WalletModel::getWatchImmatureBalance() const -{ - return wallet->GetImmatureWatchOnlyBalance(); -} - void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); @@ -117,55 +66,34 @@ void WalletModel::updateStatus() void WalletModel::pollBalanceChanged() { - // Get required locks upfront. This 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. - TRY_LOCK(cs_main, lockMain); - if(!lockMain) - return; - TRY_LOCK(wallet->cs_wallet, lockWallet); - if(!lockWallet) + // Try to get balances and return early if locks can't be acquired. This + // 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. + interfaces::WalletBalances new_balances; + int numBlocks = -1; + if (!m_wallet->tryGetBalances(new_balances, numBlocks)) { return; + } - if(fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks) + if(fForceCheckBalanceChanged || m_node.getNumBlocks() != cachedNumBlocks) { fForceCheckBalanceChanged = false; // Balance and number of transactions might have changed - cachedNumBlocks = chainActive.Height(); + cachedNumBlocks = m_node.getNumBlocks(); - checkBalanceChanged(); + checkBalanceChanged(new_balances); if(transactionTableModel) transactionTableModel->updateConfirmations(); } } -void WalletModel::checkBalanceChanged() +void WalletModel::checkBalanceChanged(const interfaces::WalletBalances& new_balances) { - CAmount newBalance = getBalance(); - CAmount newUnconfirmedBalance = getUnconfirmedBalance(); - CAmount newImmatureBalance = getImmatureBalance(); - CAmount newWatchOnlyBalance = 0; - CAmount newWatchUnconfBalance = 0; - CAmount newWatchImmatureBalance = 0; - if (haveWatchOnly()) - { - newWatchOnlyBalance = getWatchBalance(); - newWatchUnconfBalance = getWatchUnconfirmedBalance(); - newWatchImmatureBalance = getWatchImmatureBalance(); - } - - if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || - cachedWatchOnlyBalance != newWatchOnlyBalance || cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance) - { - cachedBalance = newBalance; - cachedUnconfirmedBalance = newUnconfirmedBalance; - cachedImmatureBalance = newImmatureBalance; - cachedWatchOnlyBalance = newWatchOnlyBalance; - cachedWatchUnconfBalance = newWatchUnconfBalance; - cachedWatchImmatureBalance = newWatchImmatureBalance; - Q_EMIT balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance, - newWatchOnlyBalance, newWatchUnconfBalance, newWatchImmatureBalance); + if(new_balances.balanceChanged(m_cached_balances)) { + m_cached_balances = new_balances; + Q_EMIT balanceChanged(new_balances); } } @@ -260,7 +188,7 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact return DuplicateAddress; } - CAmount nBalance = getBalance(&coinControl); + CAmount nBalance = m_wallet->getAvailableBalance(coinControl); if(total > nBalance) { @@ -268,22 +196,17 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact } { - LOCK2(cs_main, wallet->cs_wallet); - - transaction.newPossibleKeyChange(wallet); - CAmount nFeeRequired = 0; int nChangePosRet = -1; std::string strFailReason; - CTransactionRef& newTx = transaction.getTransaction(); - CReserveKey *keyChange = transaction.getPossibleKeyChange(); - bool fCreated = wallet->CreateTransaction(vecSend, newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl); + auto& newTx = transaction.getWtx(); + newTx = m_wallet->createTransaction(vecSend, coinControl, true /* sign */, nChangePosRet, nFeeRequired, strFailReason); transaction.setTransactionFee(nFeeRequired); - if (fSubtractFeeFromAmount && fCreated) + if (fSubtractFeeFromAmount && newTx) transaction.reassignAmounts(nChangePosRet); - if(!fCreated) + if(!newTx) { if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance) { @@ -297,7 +220,7 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact // reject absurdly high fee. (This can never happen because the // wallet caps the fee at maxTxFee. This merely serves as a // belt-and-suspenders check) - if (nFeeRequired > maxTxFee) + if (nFeeRequired > m_node.getMaxTxFee()) return AbsurdFee; } @@ -309,8 +232,6 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran QByteArray transaction_array; /* store serialized transaction */ { - LOCK2(cs_main, wallet->cs_wallet); - std::vector<std::pair<std::string, std::string>> vOrderForm; for (const SendCoinsRecipient &rcp : transaction.getRecipients()) { @@ -330,14 +251,13 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran vOrderForm.emplace_back("Message", rcp.message.toStdString()); } - CTransactionRef& newTx = transaction.getTransaction(); - CReserveKey *keyChange = transaction.getPossibleKeyChange(); - CValidationState state; - if (!wallet->CommitTransaction(newTx, {} /* mapValue */, std::move(vOrderForm), {} /* fromAccount */, *keyChange, g_connman.get(), state)) - return SendCoinsReturn(TransactionCommitFailed, QString::fromStdString(state.GetRejectReason())); + auto& newTx = transaction.getWtx(); + std::string rejectReason; + if (!newTx->commit({} /* mapValue */, std::move(vOrderForm), {} /* fromAccount */, rejectReason)) + return SendCoinsReturn(TransactionCommitFailed, QString::fromStdString(rejectReason)); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); - ssTx << newTx; + ssTx << newTx->get(); transaction_array.append(&(ssTx[0]), ssTx.size()); } @@ -352,24 +272,22 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran CTxDestination dest = DecodeDestination(strAddress); std::string strLabel = rcp.label.toStdString(); { - LOCK(wallet->cs_wallet); - - std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest); - // Check if we have a new address or an updated label - if (mi == wallet->mapAddressBook.end()) + std::string name; + if (!m_wallet->getAddress(dest, &name)) { - wallet->SetAddressBook(dest, strLabel, "send"); + m_wallet->setAddressBook(dest, strLabel, "send"); } - else if (mi->second.name != strLabel) + else if (name != strLabel) { - wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose + m_wallet->setAddressBook(dest, strLabel, ""); // "" means don't change purpose } } } - Q_EMIT coinsSent(wallet, rcp, transaction_array); + Q_EMIT coinsSent(this, rcp, transaction_array); } - checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits + + checkBalanceChanged(m_wallet->getBalances()); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits return SendCoinsReturn(OK); } @@ -396,11 +314,11 @@ RecentRequestsTableModel *WalletModel::getRecentRequestsTableModel() WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { - if(!wallet->IsCrypted()) + if(!m_wallet->isCrypted()) { return Unencrypted; } - else if(wallet->IsLocked()) + else if(m_wallet->isLocked()) { return Locked; } @@ -415,7 +333,7 @@ bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphr if(encrypted) { // Encrypt - return wallet->EncryptWallet(passphrase); + return m_wallet->encryptWallet(passphrase); } else { @@ -429,39 +347,29 @@ bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) if(locked) { // Lock - return wallet->Lock(); + return m_wallet->lock(); } else { // Unlock - return wallet->Unlock(passPhrase); + return m_wallet->unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { - bool retval; - { - LOCK(wallet->cs_wallet); - wallet->Lock(); // Make sure wallet is locked before attempting pass change - retval = wallet->ChangeWalletPassphrase(oldPass, newPass); - } - return retval; -} - -bool WalletModel::backupWallet(const QString &filename) -{ - return wallet->BackupWallet(filename.toLocal8Bit().data()); + m_wallet->lock(); // Make sure wallet is locked before attempting pass change + return m_wallet->changeWalletPassphrase(oldPass, newPass); } // Handlers for core signals -static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) +static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel) { qDebug() << "NotifyKeyStoreStatusChanged"; QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } -static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, +static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status) { @@ -478,9 +386,8 @@ static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, Q_ARG(int, status)); } -static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) +static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status) { - Q_UNUSED(wallet); Q_UNUSED(hash); Q_UNUSED(status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection); @@ -503,21 +410,21 @@ static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet - wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); - wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); - wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); - wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); - wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1)); + m_handler_status_changed = m_wallet->handleStatusChanged(boost::bind(&NotifyKeyStoreStatusChanged, this)); + m_handler_address_book_changed = m_wallet->handleAddressBookChanged(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); + m_handler_transaction_changed = m_wallet->handleTransactionChanged(boost::bind(NotifyTransactionChanged, this, _1, _2)); + m_handler_show_progress = m_wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2)); + m_handler_watch_only_changed = m_wallet->handleWatchOnlyChanged(boost::bind(NotifyWatchonlyChanged, this, _1)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet - wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); - wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); - wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); - wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); - wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1)); + m_handler_status_changed->disconnect(); + m_handler_address_book_changed->disconnect(); + m_handler_transaction_changed->disconnect(); + m_handler_show_progress->disconnect(); + m_handler_watch_only_changed->disconnect(); } // WalletModel::UnlockContext implementation @@ -557,80 +464,9 @@ void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) rhs.relock = false; } -bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const -{ - return wallet->GetPubKey(address, vchPubKeyOut); -} - -bool WalletModel::IsSpendable(const CTxDestination& dest) const -{ - return IsMine(*wallet, dest) & ISMINE_SPENDABLE; -} - -bool WalletModel::getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const -{ - return wallet->GetKey(address, vchPrivKeyOut); -} - -// returns a list of COutputs from COutPoints -void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) -{ - LOCK2(cs_main, wallet->cs_wallet); - for (const COutPoint& outpoint : vOutpoints) - { - auto it = wallet->mapWallet.find(outpoint.hash); - if (it == wallet->mapWallet.end()) continue; - int nDepth = it->second.GetDepthInMainChain(); - if (nDepth < 0) continue; - COutput out(&it->second, outpoint.n, nDepth, true /* spendable */, true /* solvable */, true /* safe */); - vOutputs.push_back(out); - } -} - -bool WalletModel::isSpent(const COutPoint& outpoint) const -{ - LOCK2(cs_main, wallet->cs_wallet); - return wallet->IsSpent(outpoint.hash, outpoint.n); -} - -// AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) -void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const -{ - for (auto& group : wallet->ListCoins()) { - auto& resultGroup = mapCoins[QString::fromStdString(EncodeDestination(group.first))]; - for (auto& coin : group.second) { - resultGroup.emplace_back(std::move(coin)); - } - } -} - -bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const -{ - LOCK2(cs_main, wallet->cs_wallet); - return wallet->IsLockedCoin(hash, n); -} - -void WalletModel::lockCoin(COutPoint& output) -{ - LOCK2(cs_main, wallet->cs_wallet); - wallet->LockCoin(output); -} - -void WalletModel::unlockCoin(COutPoint& output) -{ - LOCK2(cs_main, wallet->cs_wallet); - wallet->UnlockCoin(output); -} - -void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) -{ - LOCK2(cs_main, wallet->cs_wallet); - wallet->ListLockedCoins(vOutpts); -} - void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests) { - vReceiveRequests = wallet->GetDestValues("rr"); // receive request + vReceiveRequests = m_wallet->getDestValues("rr"); // receive request } bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest) @@ -641,27 +477,10 @@ bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t ss << nId; std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata - LOCK(wallet->cs_wallet); if (sRequest.empty()) - return wallet->EraseDestData(dest, key); + return m_wallet->eraseDestData(dest, key); else - return wallet->AddDestData(dest, key, sRequest); -} - -bool WalletModel::transactionCanBeAbandoned(uint256 hash) const -{ - return wallet->TransactionCanBeAbandoned(hash); -} - -bool WalletModel::abandonTransaction(uint256 hash) const -{ - LOCK2(cs_main, wallet->cs_wallet); - return wallet->AbandonTransaction(hash); -} - -bool WalletModel::transactionCanBeBumped(uint256 hash) const -{ - return feebumper::TransactionCanBeBumped(wallet, hash); + return m_wallet->addDestData(dest, key, sRequest); } bool WalletModel::bumpFee(uint256 hash) @@ -672,7 +491,7 @@ bool WalletModel::bumpFee(uint256 hash) CAmount old_fee; CAmount new_fee; CMutableTransaction mtx; - if (feebumper::CreateTransaction(wallet, hash, coin_control, 0 /* totalFee */, errors, old_fee, new_fee, mtx) != feebumper::Result::OK) { + if (!m_wallet->createBumpTransaction(hash, coin_control, 0 /* totalFee */, errors, old_fee, new_fee, mtx)) { QMessageBox::critical(0, tr("Fee bump error"), tr("Increasing transaction fee failed") + "<br />(" + (errors.size() ? QString::fromStdString(errors[0]) : "") +")"); return false; @@ -711,13 +530,13 @@ bool WalletModel::bumpFee(uint256 hash) } // sign bumped transaction - if (!feebumper::SignTransaction(wallet, mtx)) { + if (!m_wallet->signBumpTransaction(mtx)) { QMessageBox::critical(0, tr("Fee bump error"), tr("Can't sign transaction.")); return false; } // commit the bumped transaction uint256 txid; - if (feebumper::CommitTransaction(wallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) { + if(!m_wallet->commitBumpTransaction(hash, std::move(mtx), errors, txid)) { QMessageBox::critical(0, tr("Fee bump error"), tr("Could not commit transaction") + "<br />(" + QString::fromStdString(errors[0])+")"); return false; @@ -730,28 +549,12 @@ bool WalletModel::isWalletEnabled() return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET); } -bool WalletModel::hdEnabled() const -{ - return wallet->IsHDEnabled(); -} - -OutputType WalletModel::getDefaultAddressType() const -{ - return wallet->m_default_address_type; -} - -int WalletModel::getDefaultConfirmTarget() const -{ - return nTxConfirmTarget; -} - QString WalletModel::getWalletName() const { - LOCK(wallet->cs_wallet); - return QString::fromStdString(wallet->GetName()); + return QString::fromStdString(m_wallet->getWalletName()); } bool WalletModel::isMultiwallet() { - return gArgs.GetArgs("-wallet").size() > 1; + return m_node.getWallets().size() > 1; } diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index ff4b38a804..e5ed5b4e82 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -13,6 +13,7 @@ #include <qt/paymentrequestplus.h> #include <qt/walletmodeltransaction.h> +#include <interfaces/wallet.h> #include <support/allocators/secure.h> #include <map> @@ -34,9 +35,12 @@ class CKeyID; class COutPoint; class COutput; class CPubKey; -class CWallet; class uint256; +namespace interfaces { +class Node; +} // namespace interfaces + QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE @@ -107,7 +111,7 @@ class WalletModel : public QObject Q_OBJECT public: - explicit WalletModel(const PlatformStyle *platformStyle, CWallet *wallet, 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 @@ -136,15 +140,6 @@ public: TransactionTableModel *getTransactionTableModel(); RecentRequestsTableModel *getRecentRequestsTableModel(); - CWallet *getWallet() const { return wallet; }; - - CAmount getBalance(const CCoinControl *coinControl = nullptr) const; - CAmount getUnconfirmedBalance() const; - CAmount getImmatureBalance() const; - bool haveWatchOnly() const; - CAmount getWatchBalance() const; - CAmount getWatchUnconfirmedBalance() const; - CAmount getWatchImmatureBalance() const; EncryptionStatus getEncryptionStatus() const; // Check address for validity @@ -173,8 +168,6 @@ public: // Passphrase only needed when unlocking bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString()); bool changePassphrase(const SecureString &oldPass, const SecureString &newPass); - // Wallet backup - bool backupWallet(const QString &filename); // RAI object for unlocking wallet, returned by requestUnlock() class UnlockContext @@ -198,40 +191,28 @@ public: UnlockContext requestUnlock(); - bool getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; - bool IsSpendable(const CTxDestination& dest) const; - bool getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const; - void getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs); - bool isSpent(const COutPoint& outpoint) const; - void listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const; - - bool isLockedCoin(uint256 hash, unsigned int n) const; - void lockCoin(COutPoint& output); - void unlockCoin(COutPoint& output); - void listLockedCoins(std::vector<COutPoint>& vOutpts); - void loadReceiveRequests(std::vector<std::string>& vReceiveRequests); bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest); - bool transactionCanBeAbandoned(uint256 hash) const; - bool abandonTransaction(uint256 hash) const; - - bool transactionCanBeBumped(uint256 hash) const; bool bumpFee(uint256 hash); static bool isWalletEnabled(); - bool hdEnabled() const; - - OutputType getDefaultAddressType() const; - - int getDefaultConfirmTarget() const; + interfaces::Node& node() const { return m_node; } + interfaces::Wallet& wallet() const { return *m_wallet; } QString getWalletName() const; - static bool isMultiwallet(); + bool isMultiwallet(); private: - CWallet *wallet; + 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; @@ -244,12 +225,7 @@ private: RecentRequestsTableModel *recentRequestsTableModel; // Cache some values to be able to detect changes - CAmount cachedBalance; - CAmount cachedUnconfirmedBalance; - CAmount cachedImmatureBalance; - CAmount cachedWatchOnlyBalance; - CAmount cachedWatchUnconfBalance; - CAmount cachedWatchImmatureBalance; + interfaces::WalletBalances m_cached_balances; EncryptionStatus cachedEncryptionStatus; int cachedNumBlocks; @@ -257,12 +233,11 @@ private: void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); - void checkBalanceChanged(); + void checkBalanceChanged(const interfaces::WalletBalances& new_balances); Q_SIGNALS: // Signal that balance in wallet changed - void balanceChanged(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, - const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance); + void balanceChanged(const interfaces::WalletBalances& balances); // Encryption status of wallet changed void encryptionStatusChanged(); @@ -276,7 +251,7 @@ Q_SIGNALS: void message(const QString &title, const QString &message, unsigned int style); // Coins sent: from wallet, to recipient, in (serialized) transaction: - void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction); + void coinsSent(WalletModel* wallet, SendCoinsRecipient recipient, QByteArray transaction); // Show progress dialog e.g. for rescan void showProgress(const QString &title, int nProgress); diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp index 4df8a5687e..d5187d6634 100644 --- a/src/qt/walletmodeltransaction.cpp +++ b/src/qt/walletmodeltransaction.cpp @@ -4,12 +4,11 @@ #include <qt/walletmodeltransaction.h> +#include <interfaces/node.h> #include <policy/policy.h> -#include <wallet/wallet.h> WalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient> &_recipients) : recipients(_recipients), - walletTransaction(0), fee(0) { } @@ -19,14 +18,14 @@ QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const return recipients; } -CTransactionRef& WalletModelTransaction::getTransaction() +std::unique_ptr<interfaces::PendingWalletTx>& WalletModelTransaction::getWtx() { - return walletTransaction; + return wtx; } unsigned int WalletModelTransaction::getTransactionSize() { - return (!walletTransaction ? 0 : ::GetVirtualTransactionSize(*walletTransaction)); + return wtx ? wtx->getVirtualSize() : 0; } CAmount WalletModelTransaction::getTransactionFee() const @@ -41,6 +40,7 @@ void WalletModelTransaction::setTransactionFee(const CAmount& newFee) void WalletModelTransaction::reassignAmounts(int nChangePosRet) { + const CTransaction* walletTransaction = &wtx->get(); int i = 0; for (QList<SendCoinsRecipient>::iterator it = recipients.begin(); it != recipients.end(); ++it) { @@ -80,13 +80,3 @@ CAmount WalletModelTransaction::getTotalTransactionAmount() const } return totalTransactionAmount; } - -void WalletModelTransaction::newPossibleKeyChange(CWallet *wallet) -{ - keyChange.reset(new CReserveKey(wallet)); -} - -CReserveKey *WalletModelTransaction::getPossibleKeyChange() -{ - return keyChange.get(); -} diff --git a/src/qt/walletmodeltransaction.h b/src/qt/walletmodeltransaction.h index 931e960d18..9f91326109 100644 --- a/src/qt/walletmodeltransaction.h +++ b/src/qt/walletmodeltransaction.h @@ -7,13 +7,16 @@ #include <qt/walletmodel.h> +#include <memory> + #include <QObject> class SendCoinsRecipient; -class CReserveKey; -class CWallet; -class CWalletTx; +namespace interfaces { +class Node; +class PendingWalletTx; +} /** Data model for a walletmodel transaction. */ class WalletModelTransaction @@ -23,7 +26,7 @@ public: QList<SendCoinsRecipient> getRecipients() const; - CTransactionRef& getTransaction(); + std::unique_ptr<interfaces::PendingWalletTx>& getWtx(); unsigned int getTransactionSize(); void setTransactionFee(const CAmount& newFee); @@ -31,15 +34,11 @@ public: CAmount getTotalTransactionAmount() const; - void newPossibleKeyChange(CWallet *wallet); - CReserveKey *getPossibleKeyChange(); - void reassignAmounts(int nChangePosRet); // needed for the subtract-fee-from-amount feature private: QList<SendCoinsRecipient> recipients; - CTransactionRef walletTransaction; - std::unique_ptr<CReserveKey> keyChange; + std::unique_ptr<interfaces::PendingWalletTx> wtx; CAmount fee; }; diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp index cc4300a7a1..8b9b85c8c9 100644 --- a/src/qt/walletview.cpp +++ b/src/qt/walletview.cpp @@ -19,6 +19,7 @@ #include <qt/transactionview.h> #include <qt/walletmodel.h> +#include <interfaces/node.h> #include <ui_interface.h> #include <QAction> @@ -158,7 +159,7 @@ void WalletView::setWalletModel(WalletModel *_walletModel) void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress - if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) + if (!walletModel || !clientModel || clientModel->node().isInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); @@ -257,7 +258,7 @@ void WalletView::backupWallet() if (filename.isEmpty()) return; - if (!walletModel->backupWallet(filename)) { + if (!walletModel->wallet().backupWallet(filename.toLocal8Bit().data())) { Q_EMIT message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 31cbec4c86..06c68ea27c 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -33,6 +33,7 @@ #include <boost/thread/thread.hpp> // boost::thread::interrupt +#include <memory> #include <mutex> #include <condition_variable> 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/serialize.h b/src/serialize.h index 247e915298..e90b041cc2 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -22,6 +22,7 @@ #include <vector> #include <prevector.h> +#include <span.h> static const unsigned int MAX_SIZE = 0x02000000; @@ -41,7 +42,7 @@ constexpr deserialize_type deserialize {}; /** * Used to bypass the rule against non-const reference to temporary - * where it makes sense with wrappers such as CFlatData or CTxDB + * where it makes sense with wrappers. */ template<typename T> inline T& REF(const T& val) @@ -185,6 +186,8 @@ template<typename Stream> inline void Serialize(Stream& s, float a ) { ser_wri template<typename Stream> inline void Serialize(Stream& s, double a ) { ser_writedata64(s, ser_double_to_uint64(a)); } template<typename Stream, int N> inline void Serialize(Stream& s, const char (&a)[N]) { s.write(a, N); } template<typename Stream, int N> inline void Serialize(Stream& s, const unsigned char (&a)[N]) { s.write(CharCast(a), N); } +template<typename Stream> inline void Serialize(Stream& s, const Span<const unsigned char>& span) { s.write(CharCast(span.data()), span.size()); } +template<typename Stream> inline void Serialize(Stream& s, const Span<unsigned char>& span) { s.write(CharCast(span.data()), span.size()); } template<typename Stream> inline void Unserialize(Stream& s, char& a ) { a = ser_readdata8(s); } // TODO Get rid of bare char template<typename Stream> inline void Unserialize(Stream& s, int8_t& a ) { a = ser_readdata8(s); } @@ -199,6 +202,7 @@ template<typename Stream> inline void Unserialize(Stream& s, float& a ) { a = template<typename Stream> inline void Unserialize(Stream& s, double& a ) { a = ser_uint64_to_double(ser_readdata64(s)); } template<typename Stream, int N> inline void Unserialize(Stream& s, char (&a)[N]) { s.read(a, N); } template<typename Stream, int N> inline void Unserialize(Stream& s, unsigned char (&a)[N]) { s.read(CharCast(a), N); } +template<typename Stream> inline void Unserialize(Stream& s, Span<unsigned char>& span) { s.read(CharCast(span.data()), span.size()); } template<typename Stream> inline void Serialize(Stream& s, bool a) { char f=a; ser_writedata8(s, f); } template<typename Stream> inline void Unserialize(Stream& s, bool& a) { char f=ser_readdata8(s); a=f; } @@ -384,51 +388,10 @@ I ReadVarInt(Stream& is) } } -#define FLATDATA(obj) CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)) #define VARINT(obj, ...) WrapVarInt<__VA_ARGS__>(REF(obj)) #define COMPACTSIZE(obj) CCompactSize(REF(obj)) #define LIMITED_STRING(obj,n) LimitedString< n >(REF(obj)) -/** - * Wrapper for serializing arrays and POD. - */ -class CFlatData -{ -protected: - char* pbegin; - char* pend; -public: - CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { } - template <class T, class TAl> - explicit CFlatData(std::vector<T,TAl> &v) - { - pbegin = (char*)v.data(); - pend = (char*)(v.data() + v.size()); - } - template <unsigned int N, typename T, typename S, typename D> - explicit CFlatData(prevector<N, T, S, D> &v) - { - pbegin = (char*)v.data(); - pend = (char*)(v.data() + v.size()); - } - char* begin() { return pbegin; } - const char* begin() const { return pbegin; } - char* end() { return pend; } - const char* end() const { return pend; } - - template<typename Stream> - void Serialize(Stream& s) const - { - s.write(pbegin, pend - pbegin); - } - - template<typename Stream> - void Unserialize(Stream& s) - { - s.read(pbegin, pend - pbegin); - } -}; - template<VarIntMode Mode, typename I> class CVarInt { diff --git a/src/span.h b/src/span.h new file mode 100644 index 0000000000..707fc21918 --- /dev/null +++ b/src/span.h @@ -0,0 +1,40 @@ +// 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. + +#ifndef BITCOIN_SPAN_H +#define BITCOIN_SPAN_H + +#include <type_traits> +#include <cstddef> + +/** A Span is an object that can refer to a contiguous sequence of objects. + * + * It implements a subset of C++20's std::span. + */ +template<typename C> +class Span +{ + C* m_data; + std::ptrdiff_t m_size; + +public: + constexpr Span() noexcept : m_data(nullptr), m_size(0) {} + constexpr Span(C* data, std::ptrdiff_t size) noexcept : m_data(data), m_size(size) {} + + constexpr C* data() const noexcept { return m_data; } + constexpr std::ptrdiff_t size() const noexcept { return m_size; } +}; + +/** Create a span to a container exposing data() and size(). + * + * This correctly deals with constness: the returned Span's element type will be + * whatever data() returns a pointer to. If either the passed container is const, + * or its element type is const, the resulting span will have a const element type. + * + * std::span will have a constructor that implements this functionality directly. + */ +template<typename V> +constexpr Span<typename std::remove_pointer<decltype(std::declval<V>().data())>::type> MakeSpan(V& v) { return Span<typename std::remove_pointer<decltype(std::declval<V>().data())>::type>(v.data(), v.size()); } + +#endif diff --git a/src/support/lockedpool.cpp b/src/support/lockedpool.cpp index f10fd07c63..51c337ed2f 100644 --- a/src/support/lockedpool.cpp +++ b/src/support/lockedpool.cpp @@ -27,6 +27,7 @@ #endif #include <algorithm> +#include <memory> LockedPoolManager* LockedPoolManager::_instance = nullptr; std::once_flag LockedPoolManager::init_flag; diff --git a/src/sync.cpp b/src/sync.cpp index bf3d131e4e..6f21d498ee 100644 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -4,6 +4,7 @@ #include <sync.h> +#include <memory> #include <set> #include <util.h> #include <utilstrencodings.h> @@ -80,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/test/allocator_tests.cpp b/src/test/allocator_tests.cpp index c177f0bf00..24cd88c7a7 100644 --- a/src/test/allocator_tests.cpp +++ b/src/test/allocator_tests.cpp @@ -7,6 +7,8 @@ #include <support/allocators/secure.h> #include <test/test_bitcoin.h> +#include <memory> + #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup) diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp index 6694401a29..35f0463e3e 100644 --- a/src/test/dbwrapper_tests.cpp +++ b/src/test/dbwrapper_tests.cpp @@ -7,6 +7,8 @@ #include <random.h> #include <test/test_bitcoin.h> +#include <memory> + #include <boost/test/unit_test.hpp> // Test if a string consists entirely of null characters diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp index 6552613c04..436ae696d1 100644 --- a/src/test/net_tests.cpp +++ b/src/test/net_tests.cpp @@ -13,6 +13,8 @@ #include <chainparams.h> #include <util.h> +#include <memory> + class CAddrManSerializationMock : public CAddrMan { public: diff --git a/src/test/test_bitcoin.h b/src/test/test_bitcoin.h index 944835cccf..8136da3aa9 100644 --- a/src/test/test_bitcoin.h +++ b/src/test/test_bitcoin.h @@ -14,6 +14,8 @@ #include <txdb.h> #include <txmempool.h> +#include <memory> + #include <boost/thread.hpp> extern uint256 insecure_rand_seed; diff --git a/src/test/test_bitcoin_fuzzy.cpp b/src/test/test_bitcoin_fuzzy.cpp index aaba2095e0..69e9804c2f 100644 --- a/src/test/test_bitcoin_fuzzy.cpp +++ b/src/test/test_bitcoin_fuzzy.cpp @@ -25,6 +25,7 @@ #include <unistd.h> #include <algorithm> +#include <memory> #include <vector> enum TEST_ID { diff --git a/src/test/test_bitcoin_main.cpp b/src/test/test_bitcoin_main.cpp index 64408e9c5b..e48c685b6b 100644 --- a/src/test/test_bitcoin_main.cpp +++ b/src/test/test_bitcoin_main.cpp @@ -6,6 +6,8 @@ #include <net.h> +#include <memory> + #include <boost/test/unit_test.hpp> std::unique_ptr<CConnman> g_connman; diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 4b44bbadac..b4af3617f1 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -190,6 +190,11 @@ struct TestArgsManager : public ArgsManager std::map<std::string, std::string>& GetMapArgs() { return mapArgs; } const std::map<std::string, std::vector<std::string> >& GetMapMultiArgs() { return mapMultiArgs; } const std::unordered_set<std::string>& GetNegatedArgs() { return m_negated_args; } + void ReadConfigString(const std::string str_config) + { + std::istringstream stream(str_config); + ReadConfigStream(stream); + } }; BOOST_AUTO_TEST_CASE(util_ParseParameters) @@ -253,16 +258,154 @@ BOOST_AUTO_TEST_CASE(util_GetBoolArgEdgeCases) { // Test some awful edge cases that hopefully no user will ever exercise. TestArgsManager testArgs; + + // Params test const char *argv_test[] = {"ignored", "-nofoo", "-foo", "-nobar=0"}; testArgs.ParseParameters(4, (char**)argv_test); // This was passed twice, second one overrides the negative setting. BOOST_CHECK(!testArgs.IsArgNegated("-foo")); - BOOST_CHECK(testArgs.GetBoolArg("-foo", false) == true); + BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == ""); + + // A double negative is a positive. + BOOST_CHECK(testArgs.IsArgNegated("-bar")); + BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1"); + + // Config test + const char *conf_test = "nofoo=1\nfoo=1\nnobar=0\n"; + testArgs.ParseParameters(1, (char**)argv_test); + testArgs.ReadConfigString(conf_test); + + // This was passed twice, second one overrides the negative setting, + // but not the value. + BOOST_CHECK(!testArgs.IsArgNegated("-foo")); + BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "0"); // A double negative is a positive. BOOST_CHECK(testArgs.IsArgNegated("-bar")); - BOOST_CHECK(testArgs.GetBoolArg("-bar", false) == true); + BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1"); + + // Combined test + const char *combo_test_args[] = {"ignored", "-nofoo", "-bar"}; + const char *combo_test_conf = "foo=1\nnobar=1\n"; + testArgs.ParseParameters(3, (char**)combo_test_args); + testArgs.ReadConfigString(combo_test_conf); + + // Command line overrides, but doesn't erase old setting + BOOST_CHECK(!testArgs.IsArgNegated("-foo")); + BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "0"); + BOOST_CHECK(testArgs.GetArgs("-foo").size() == 2 + && testArgs.GetArgs("-foo").front() == "0" + && testArgs.GetArgs("-foo").back() == "1"); + + // Command line overrides, but doesn't erase old setting + BOOST_CHECK(testArgs.IsArgNegated("-bar")); + BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == ""); + BOOST_CHECK(testArgs.GetArgs("-bar").size() == 2 + && testArgs.GetArgs("-bar").front() == "" + && testArgs.GetArgs("-bar").back() == "0"); +} + +BOOST_AUTO_TEST_CASE(util_ReadConfigStream) +{ + const char *str_config = + "a=\n" + "b=1\n" + "ccc=argument\n" + "ccc=multiple\n" + "d=e\n" + "nofff=1\n" + "noggg=0\n" + "h=1\n" + "noh=1\n" + "noi=1\n" + "i=1\n"; + + TestArgsManager test_args; + + test_args.ReadConfigString(str_config); + // expectation: a, b, ccc, d, fff, ggg, h, i end up in map + + BOOST_CHECK(test_args.GetMapArgs().size() == 8); + BOOST_CHECK(test_args.GetMapMultiArgs().size() == 8); + + BOOST_CHECK(test_args.GetMapArgs().count("-a") + && test_args.GetMapArgs().count("-b") + && test_args.GetMapArgs().count("-ccc") + && test_args.GetMapArgs().count("-d") + && test_args.GetMapArgs().count("-fff") + && test_args.GetMapArgs().count("-ggg") + && test_args.GetMapArgs().count("-h") + && test_args.GetMapArgs().count("-i") + ); + + BOOST_CHECK(test_args.IsArgSet("-a") + && test_args.IsArgSet("-b") + && test_args.IsArgSet("-ccc") + && test_args.IsArgSet("-d") + && test_args.IsArgSet("-fff") + && test_args.IsArgSet("-ggg") + && test_args.IsArgSet("-h") + && test_args.IsArgSet("-i") + && !test_args.IsArgSet("-zzz") + ); + + BOOST_CHECK(test_args.GetArg("-a", "xxx") == "" + && test_args.GetArg("-b", "xxx") == "1" + && test_args.GetArg("-ccc", "xxx") == "argument" + && test_args.GetArg("-d", "xxx") == "e" + && test_args.GetArg("-fff", "xxx") == "0" + && test_args.GetArg("-ggg", "xxx") == "1" + && test_args.GetArg("-h", "xxx") == "1" // 1st value takes precedence + && test_args.GetArg("-i", "xxx") == "0" // 1st value takes precedence + && test_args.GetArg("-zzz", "xxx") == "xxx" + ); + + for (bool def : {false, true}) { + BOOST_CHECK(test_args.GetBoolArg("-a", def) + && test_args.GetBoolArg("-b", def) + && !test_args.GetBoolArg("-ccc", def) + && !test_args.GetBoolArg("-d", def) + && !test_args.GetBoolArg("-fff", def) + && test_args.GetBoolArg("-ggg", def) + && test_args.GetBoolArg("-h", def) + && !test_args.GetBoolArg("-i", def) + && test_args.GetBoolArg("-zzz", def) == def + ); + } + + BOOST_CHECK(test_args.GetArgs("-a").size() == 1 + && test_args.GetArgs("-a").front() == ""); + BOOST_CHECK(test_args.GetArgs("-b").size() == 1 + && test_args.GetArgs("-b").front() == "1"); + BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2 + && test_args.GetArgs("-ccc").front() == "argument" + && test_args.GetArgs("-ccc").back() == "multiple"); + BOOST_CHECK(test_args.GetArgs("-fff").size() == 1 + && test_args.GetArgs("-fff").front() == "0"); + BOOST_CHECK(test_args.GetArgs("-nofff").size() == 0); + BOOST_CHECK(test_args.GetArgs("-ggg").size() == 1 + && test_args.GetArgs("-ggg").front() == "1"); + BOOST_CHECK(test_args.GetArgs("-noggg").size() == 0); + BOOST_CHECK(test_args.GetArgs("-h").size() == 2 + && test_args.GetArgs("-h").front() == "1" + && test_args.GetArgs("-h").back() == "0"); + BOOST_CHECK(test_args.GetArgs("-noh").size() == 0); + BOOST_CHECK(test_args.GetArgs("-i").size() == 2 + && test_args.GetArgs("-i").front() == "0" + && test_args.GetArgs("-i").back() == "1"); + BOOST_CHECK(test_args.GetArgs("-noi").size() == 0); + BOOST_CHECK(test_args.GetArgs("-zzz").size() == 0); + + BOOST_CHECK(!test_args.IsArgNegated("-a")); + BOOST_CHECK(!test_args.IsArgNegated("-b")); + BOOST_CHECK(!test_args.IsArgNegated("-ccc")); + BOOST_CHECK(!test_args.IsArgNegated("-d")); + BOOST_CHECK(test_args.IsArgNegated("-fff")); + BOOST_CHECK(test_args.IsArgNegated("-ggg")); // IsArgNegated==true when noggg=0 + BOOST_CHECK(test_args.IsArgNegated("-h")); // last setting takes precedence + BOOST_CHECK(!test_args.IsArgNegated("-i")); // last setting takes precedence + BOOST_CHECK(!test_args.IsArgNegated("-zzz")); } BOOST_AUTO_TEST_CASE(util_GetArg) @@ -290,6 +433,54 @@ BOOST_AUTO_TEST_CASE(util_GetArg) BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest4", false), true); } +BOOST_AUTO_TEST_CASE(util_GetChainName) +{ + TestArgsManager test_args; + + const char* argv_testnet[] = {"cmd", "-testnet"}; + const char* argv_regtest[] = {"cmd", "-regtest"}; + const char* argv_test_no_reg[] = {"cmd", "-testnet", "-noregtest"}; + const char* argv_both[] = {"cmd", "-testnet", "-regtest"}; + + // equivalent to "-testnet" + const char* testnetconf = "testnet=1\nregtest=0\n"; + + test_args.ParseParameters(0, (char**)argv_testnet); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "main"); + + test_args.ParseParameters(2, (char**)argv_testnet); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); + + test_args.ParseParameters(2, (char**)argv_regtest); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "regtest"); + + test_args.ParseParameters(3, (char**)argv_test_no_reg); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); + + test_args.ParseParameters(3, (char**)argv_both); + BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); + + test_args.ParseParameters(0, (char**)argv_testnet); + test_args.ReadConfigString(testnetconf); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); + + test_args.ParseParameters(2, (char**)argv_testnet); + test_args.ReadConfigString(testnetconf); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); + + test_args.ParseParameters(2, (char**)argv_regtest); + test_args.ReadConfigString(testnetconf); + BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); + + test_args.ParseParameters(3, (char**)argv_test_no_reg); + test_args.ReadConfigString(testnetconf); + BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); + + test_args.ParseParameters(3, (char**)argv_both); + test_args.ReadConfigString(testnetconf); + BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); +} + BOOST_AUTO_TEST_CASE(util_FormatMoney) { BOOST_CHECK_EQUAL(FormatMoney(0), "0.00"); 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/txdb.h b/src/txdb.h index 2fc69e563b..ad76b3257d 100644 --- a/src/txdb.h +++ b/src/txdb.h @@ -11,6 +11,7 @@ #include <chain.h> #include <map> +#include <memory> #include <string> #include <utility> #include <vector> diff --git a/src/util.cpp b/src/util.cpp index 46054f5025..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> @@ -735,28 +736,34 @@ fs::path GetConfigFile(const std::string& confPath) return AbsPathForConfigVal(fs::path(confPath), false); } -void ArgsManager::ReadConfigFile(const std::string& confPath) +void ArgsManager::ReadConfigStream(std::istream& stream) { - fs::ifstream streamConfig(GetConfigFile(confPath)); - if (!streamConfig.good()) - return; // No bitcoin.conf file is OK + LOCK(cs_args); + + std::set<std::string> setOptions; + setOptions.insert("*"); + for (boost::program_options::detail::config_file_iterator it(stream, setOptions), end; it != end; ++it) { - LOCK(cs_args); - std::set<std::string> setOptions; - setOptions.insert("*"); + // Don't overwrite existing settings so command line settings override bitcoin.conf + std::string strKey = std::string("-") + it->string_key; + std::string strValue = it->value[0]; + InterpretNegatedOption(strKey, strValue); + if (mapArgs.count(strKey) == 0) + mapArgs[strKey] = strValue; + mapMultiArgs[strKey].push_back(strValue); + } +} - for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) - { - // Don't overwrite existing settings so command line settings override bitcoin.conf - std::string strKey = std::string("-") + it->string_key; - std::string strValue = it->value[0]; - InterpretNegatedOption(strKey, strValue); - if (mapArgs.count(strKey) == 0) - mapArgs[strKey] = strValue; - mapMultiArgs[strKey].push_back(strValue); - } +void ArgsManager::ReadConfigFile(const std::string& confPath) +{ + fs::ifstream stream(GetConfigFile(confPath)); + + // ok to not have a config file + if (stream.good()) { + ReadConfigStream(stream); } + // If datadir is changed in .conf file: ClearDatadirCache(); if (!fs::is_directory(GetDataDir(false))) { @@ -764,6 +771,20 @@ void ArgsManager::ReadConfigFile(const std::string& confPath) } } +std::string ArgsManager::GetChainName() const +{ + bool fRegTest = GetBoolArg("-regtest", false); + bool fTestNet = GetBoolArg("-testnet", false); + + if (fTestNet && fRegTest) + throw std::runtime_error("Invalid combination of -regtest and -testnet."); + if (fRegTest) + return CBaseChainParams::REGTEST; + if (fTestNet) + return CBaseChainParams::TESTNET; + return CBaseChainParams::MAIN; +} + #ifndef WIN32 fs::path GetPidFile() { @@ -1039,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 17881ff3b6..3952461e48 100644 --- a/src/util.h +++ b/src/util.h @@ -23,6 +23,7 @@ #include <atomic> #include <exception> #include <map> +#include <memory> #include <stdint.h> #include <string> #include <unordered_set> @@ -227,6 +228,8 @@ protected: std::map<std::string, std::vector<std::string>> mapMultiArgs; std::unordered_set<std::string> m_negated_args; + void ReadConfigStream(std::istream& stream); + public: void ParseParameters(int argc, const char*const argv[]); void ReadConfigFile(const std::string& confPath); @@ -305,6 +308,12 @@ public: // been set. Also called directly in testing. void ForceSetArg(const std::string& strArg, const std::string& strValue); + /** + * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. + * @return CBaseChainParams::MAIN by default; raises runtime error if an invalid combination is given. + */ + std::string GetChainName() const; + private: // Munge -nofoo into -foo=0 and track the value as negated. @@ -380,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/validation.h b/src/validation.h index 95c31bf0fc..dad6858b1e 100644 --- a/src/validation.h +++ b/src/validation.h @@ -22,6 +22,7 @@ #include <algorithm> #include <exception> #include <map> +#include <memory> #include <set> #include <stdint.h> #include <string> 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/db.h b/src/wallet/db.h index 65bb8cc253..49a9f3f082 100644 --- a/src/wallet/db.h +++ b/src/wallet/db.h @@ -16,6 +16,7 @@ #include <atomic> #include <map> +#include <memory> #include <string> #include <vector> 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/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index c34b166a41..29760a7092 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -37,6 +37,8 @@ #include <univalue.h> +#include <functional> + static const std::string WALLET_ENDPOINT_BASE = "/wallet/"; CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request) @@ -2349,8 +2351,7 @@ UniValue walletpassphrase(const JSONRPCRequest& request) "This is needed prior to performing transactions related to private keys such as sending bitcoins\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The wallet passphrase\n" - "2. timeout (numeric, required) The time to keep the decryption key in seconds. Limited to at most 1073741824 (2^30) seconds.\n" - " Any value greater than 1073741824 seconds will be set to 1073741824 seconds.\n" + "2. timeout (numeric, required) The time to keep the decryption key in seconds; capped at 100000000 (~3 years).\n" "\nNote:\n" "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n" "time that overrides the old one.\n" @@ -2383,9 +2384,10 @@ UniValue walletpassphrase(const JSONRPCRequest& request) if (nSleepTime < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Timeout cannot be negative."); } - // Clamp timeout to 2^30 seconds - if (nSleepTime > (int64_t)1 << 30) { - nSleepTime = (int64_t)1 << 30; + // Clamp timeout + constexpr int64_t MAX_SLEEP_TIME = 100000000; // larger values trigger a macos/libevent bug? + if (nSleepTime > MAX_SLEEP_TIME) { + nSleepTime = MAX_SLEEP_TIME; } if (strWalletPass.length() > 0) @@ -2402,7 +2404,7 @@ UniValue walletpassphrase(const JSONRPCRequest& request) pwallet->TopUpKeyPool(); pwallet->nRelockTime = GetTime() + nSleepTime; - RPCRunLater(strprintf("lockwallet(%s)", pwallet->GetName()), boost::bind(LockWallet, pwallet), nSleepTime); + RPCRunLater(strprintf("lockwallet(%s)", pwallet->GetName()), std::bind(LockWallet, pwallet), nSleepTime); return NullUniValue; } 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/test/wallet_test_fixture.h b/src/wallet/test/wallet_test_fixture.h index 23575391c4..b328b3543b 100644 --- a/src/wallet/test/wallet_test_fixture.h +++ b/src/wallet/test/wallet_test_fixture.h @@ -9,6 +9,8 @@ #include <wallet/wallet.h> +#include <memory> + /** Testing setup and teardown for wallet. */ struct WalletTestingSetup: public TestingSetup { diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index 808f8b8838..e93e0f1966 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -4,6 +4,7 @@ #include <wallet/wallet.h> +#include <memory> #include <set> #include <stdint.h> #include <utility> diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index c9843599d6..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> @@ -878,7 +877,7 @@ bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash) bool success = true; if (!walletdb.WriteTx(wtx)) { - LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString()); + LogPrintf("%s: Updating walletdb tx %s failed\n", __func__, wtx.GetHash().ToString()); success = false; } @@ -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 3ef5bfbb65..22a0ac2924 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -24,6 +24,7 @@ #include <algorithm> #include <atomic> #include <map> +#include <memory> #include <set> #include <stdexcept> #include <stdint.h> @@ -660,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 @@ -704,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 @@ -740,7 +741,7 @@ private: * * Protected by cs_main (see BlockUntilSyncedToCurrentChain) */ - const CBlockIndex* m_last_block_processed; + const CBlockIndex* m_last_block_processed = nullptr; public: /* @@ -779,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() @@ -793,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; @@ -818,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; @@ -912,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 |