aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Makefile.am14
-rw-r--r--src/Makefile.test.include2
-rw-r--r--src/arith_uint256.cpp8
-rw-r--r--src/bench/coin_selection.cpp2
-rw-r--r--src/bitcoin-cli.cpp2
-rw-r--r--src/bitcoin-tx.cpp2
-rw-r--r--src/bitcoind.cpp11
-rw-r--r--src/chainparams.cpp1
-rw-r--r--src/chainparamsbase.cpp15
-rw-r--r--src/chainparamsbase.h6
-rw-r--r--src/compressor.h9
-rw-r--r--src/cuckoocache.h16
-rw-r--r--src/dbwrapper.cpp2
-rw-r--r--src/init.cpp25
-rw-r--r--src/init.h2
-rw-r--r--src/interfaces/README.md (renamed from src/interface/README.md)0
-rw-r--r--src/interfaces/handler.cpp (renamed from src/interface/handler.cpp)7
-rw-r--r--src/interfaces/handler.h (renamed from src/interface/handler.h)10
-rw-r--r--src/interfaces/node.cpp (renamed from src/interface/node.cpp)10
-rw-r--r--src/interfaces/node.h (renamed from src/interface/node.h)10
-rw-r--r--src/interfaces/wallet.cpp (renamed from src/interface/wallet.cpp)12
-rw-r--r--src/interfaces/wallet.h (renamed from src/interface/wallet.h)10
-rw-r--r--src/miner.cpp1
-rw-r--r--src/net.cpp1
-rw-r--r--src/netaddress.h8
-rw-r--r--src/qt/README.md10
-rw-r--r--src/qt/addresstablemodel.cpp4
-rw-r--r--src/qt/addresstablemodel.h2
-rw-r--r--src/qt/bantablemodel.cpp6
-rw-r--r--src/qt/bantablemodel.h6
-rw-r--r--src/qt/bitcoin.cpp30
-rw-r--r--src/qt/bitcoingui.cpp6
-rw-r--r--src/qt/bitcoingui.h10
-rw-r--r--src/qt/clientmodel.cpp6
-rw-r--r--src/qt/clientmodel.h22
-rw-r--r--src/qt/coincontroldialog.cpp4
-rw-r--r--src/qt/guiutil.cpp10
-rw-r--r--src/qt/guiutil.h4
-rw-r--r--src/qt/intro.cpp4
-rw-r--r--src/qt/intro.h4
-rw-r--r--src/qt/optionsdialog.cpp2
-rw-r--r--src/qt/optionsmodel.cpp4
-rw-r--r--src/qt/optionsmodel.h8
-rw-r--r--src/qt/overviewpage.cpp10
-rw-r--r--src/qt/overviewpage.h6
-rw-r--r--src/qt/paymentrequestplus.cpp1
-rw-r--r--src/qt/paymentserver.cpp6
-rw-r--r--src/qt/paymentserver.h4
-rw-r--r--src/qt/peertablemodel.cpp8
-rw-r--r--src/qt/peertablemodel.h6
-rw-r--r--src/qt/rpcconsole.cpp12
-rw-r--r--src/qt/rpcconsole.h10
-rw-r--r--src/qt/sendcoinsdialog.cpp8
-rw-r--r--src/qt/sendcoinsdialog.h2
-rw-r--r--src/qt/sendcoinsentry.cpp2
-rw-r--r--src/qt/sendcoinsentry.h2
-rw-r--r--src/qt/splashscreen.cpp12
-rw-r--r--src/qt/splashscreen.h18
-rw-r--r--src/qt/test/paymentservertests.cpp4
-rw-r--r--src/qt/test/rpcnestedtests.cpp4
-rw-r--r--src/qt/test/wallettests.cpp6
-rw-r--r--src/qt/trafficgraphwidget.cpp2
-rw-r--r--src/qt/transactiondesc.cpp12
-rw-r--r--src/qt/transactiondesc.h6
-rw-r--r--src/qt/transactionrecord.cpp6
-rw-r--r--src/qt/transactionrecord.h6
-rw-r--r--src/qt/transactiontablemodel.cpp18
-rw-r--r--src/qt/transactiontablemodel.h6
-rw-r--r--src/qt/utilitydialog.cpp4
-rw-r--r--src/qt/utilitydialog.h4
-rw-r--r--src/qt/walletmodel.cpp10
-rw-r--r--src/qt/walletmodel.h32
-rw-r--r--src/qt/walletmodeltransaction.cpp4
-rw-r--r--src/qt/walletmodeltransaction.h6
-rw-r--r--src/qt/walletview.cpp2
-rw-r--r--src/random.cpp1
-rw-r--r--src/rpc/mining.cpp1
-rw-r--r--src/rpc/rawtransaction.cpp2
-rw-r--r--src/serialize.h47
-rw-r--r--src/span.h40
-rw-r--r--src/support/lockedpool.cpp1
-rw-r--r--src/sync.cpp8
-rw-r--r--src/test/test_bitcoin.cpp2
-rw-r--r--src/test/uint256_tests.cpp13
-rw-r--r--src/test/util_tests.cpp197
-rw-r--r--src/txdb.cpp4
-rw-r--r--src/util.cpp69
-rw-r--r--src/util.h17
-rw-r--r--src/validation.cpp22
-rw-r--r--src/wallet/crypter.h4
-rw-r--r--src/wallet/db.cpp145
-rw-r--r--src/wallet/db.h50
-rw-r--r--src/wallet/init.cpp48
-rw-r--r--src/wallet/init.h48
-rw-r--r--src/wallet/rpcdump.cpp1
-rw-r--r--src/wallet/rpcwallet.cpp14
-rw-r--r--src/wallet/test/coinselector_tests.cpp2
-rw-r--r--src/wallet/test/wallet_crypto_tests.cpp (renamed from src/wallet/test/crypto_tests.cpp)2
-rw-r--r--src/wallet/test/wallet_test_fixture.cpp3
-rw-r--r--src/wallet/test/wallet_tests.cpp14
-rw-r--r--src/wallet/wallet.cpp249
-rw-r--r--src/wallet/wallet.h73
-rw-r--r--src/wallet/walletdb.cpp134
-rw-r--r--src/wallet/walletdb.h44
-rw-r--r--src/walletinitinterface.h14
105 files changed, 1013 insertions, 823 deletions
diff --git a/src/Makefile.am b/src/Makefile.am
index 605c932120..1bbb92bf42 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -105,9 +105,9 @@ BITCOIN_CORE_H = \
httpserver.h \
indirectmap.h \
init.h \
- interface/handler.h \
- interface/node.h \
- interface/wallet.h \
+ interfaces/handler.h \
+ interfaces/node.h \
+ interfaces/wallet.h \
key.h \
key_io.h \
keystore.h \
@@ -172,7 +172,6 @@ BITCOIN_CORE_H = \
wallet/db.h \
wallet/feebumper.h \
wallet/fees.h \
- wallet/init.h \
wallet/rpcwallet.h \
wallet/wallet.h \
wallet/walletdb.h \
@@ -249,7 +248,7 @@ endif
libbitcoin_wallet_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_wallet_a_SOURCES = \
- interface/wallet.cpp \
+ interfaces/wallet.cpp \
wallet/crypter.cpp \
wallet/db.cpp \
wallet/feebumper.cpp \
@@ -317,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 \
@@ -362,8 +362,8 @@ libbitcoin_util_a_SOURCES = \
compat/glibcxx_sanity.cpp \
compat/strnlen.cpp \
fs.cpp \
- interface/handler.cpp \
- interface/node.cpp \
+ interfaces/handler.cpp \
+ interfaces/node.cpp \
random.cpp \
rpc/protocol.cpp \
rpc/util.cpp \
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index a645c3b734..c4f18bb371 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -93,7 +93,7 @@ if ENABLE_WALLET
BITCOIN_TESTS += \
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
BITCOIN_TEST_SUITE += \
diff --git a/src/arith_uint256.cpp b/src/arith_uint256.cpp
index 65de632306..c7ddb17eb0 100644
--- a/src/arith_uint256.cpp
+++ b/src/arith_uint256.cpp
@@ -69,16 +69,16 @@ base_uint<BITS>& base_uint<BITS>::operator*=(uint32_t b32)
template <unsigned int BITS>
base_uint<BITS>& base_uint<BITS>::operator*=(const base_uint& b)
{
- base_uint<BITS> a = *this;
- *this = 0;
+ base_uint<BITS> a;
for (int j = 0; j < WIDTH; j++) {
uint64_t carry = 0;
for (int i = 0; i + j < WIDTH; i++) {
- uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i];
- pn[i + j] = n & 0xffffffff;
+ uint64_t n = carry + a.pn[i + j] + (uint64_t)pn[j] * b.pn[i];
+ a.pn[i + j] = n & 0xffffffff;
carry = n >> 32;
}
}
+ *this = a;
return *this;
}
diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp
index 4b2a0e72fe..64ec056c4d 100644
--- a/src/bench/coin_selection.cpp
+++ b/src/bench/coin_selection.cpp
@@ -33,7 +33,7 @@ static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<CO
// (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484)
static void CoinSelection(benchmark::State& state)
{
- const CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ const CWallet wallet("dummy", WalletDatabase::CreateDummy());
std::vector<COutput> vCoins;
LOCK(wallet.cs_wallet);
diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
index 618b0d16bc..26a9231308 100644
--- a/src/bitcoin-cli.cpp
+++ b/src/bitcoin-cli.cpp
@@ -114,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 65f8177daf..deb8212a8f 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -44,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 adf8e6ae5b..6067503b0b 100644
--- a/src/chainparams.cpp
+++ b/src/chainparams.cpp
@@ -11,7 +11,6 @@
#include <utilstrencodings.h>
#include <assert.h>
-#include <memory>
#include <chainparamsseeds.h>
diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp
index 726616e650..e840a2ed30 100644
--- a/src/chainparamsbase.cpp
+++ b/src/chainparamsbase.cpp
@@ -9,7 +9,6 @@
#include <util.h>
#include <assert.h>
-#include <memory>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
@@ -49,17 +48,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/cuckoocache.h b/src/cuckoocache.h
index d1de712024..15f6873961 100644
--- a/src/cuckoocache.h
+++ b/src/cuckoocache.h
@@ -242,14 +242,14 @@ private:
*/
inline std::array<uint32_t, 8> compute_hashes(const Element& e) const
{
- return {{(uint32_t)((hash_function.template operator()<0>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<1>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<2>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<3>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<4>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<5>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<6>(e) * (uint64_t)size) >> 32),
- (uint32_t)((hash_function.template operator()<7>(e) * (uint64_t)size) >> 32)}};
+ return {{(uint32_t)(((uint64_t)hash_function.template operator()<0>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<1>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<2>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<3>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<4>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<5>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<6>(e) * (uint64_t)size) >> 32),
+ (uint32_t)(((uint64_t)hash_function.template operator()<7>(e) * (uint64_t)size) >> 32)}};
}
/* end
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index ca446c92fe..e401b5fb1b 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -63,7 +63,7 @@ public:
assert(p <= limit);
base[std::min(bufsize - 1, (int)(p - base))] = '\0';
- LogPrintf("leveldb: %s", base);
+ LogPrintf("leveldb: %s", base); /* Continued */
if (base != buffer) {
delete[] base;
}
diff --git a/src/init.cpp b/src/init.cpp
index 4bb2bc2c3e..9edd93000f 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -47,7 +47,6 @@
#include <walletinitinterface.h>
#include <stdint.h>
#include <stdio.h>
-#include <memory>
#ifndef WIN32
#include <signal.h>
@@ -72,7 +71,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 {LogPrintf("No wallet support compiled in!\n"); 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 +283,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 +631,7 @@ void ThreadImport(std::vector<fs::path> vImportFiles)
{
const CChainParams& chainparams = Params();
RenameThread("bitcoin-loadblk");
+ ScheduleBatchPriority();
{
CImportingNow imp;
@@ -1215,7 +1232,7 @@ bool AppInitMain()
// Warn about relative -datadir path.
if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) {
- LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the "
+ LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
"current working directory '%s'. This is fragile, because if bitcoin is started in the future "
"from a different location, it will be unable to locate the current data files. There could "
"also be data loss if bitcoin is started while in a temporary directory.\n",
diff --git a/src/init.h b/src/init.h
index c93a210154..829c110112 100644
--- a/src/init.h
+++ b/src/init.h
@@ -13,7 +13,7 @@ class CScheduler;
class CWallet;
class WalletInitInterface;
-extern std::unique_ptr<WalletInitInterface> g_wallet_init_interface;
+extern WalletInitInterface* const g_wallet_init_interface;
namespace boost
{
diff --git a/src/interface/README.md b/src/interfaces/README.md
index e93b91d23c..e93b91d23c 100644
--- a/src/interface/README.md
+++ b/src/interfaces/README.md
diff --git a/src/interface/handler.cpp b/src/interfaces/handler.cpp
index 4b27f374f4..8e45faa2a5 100644
--- a/src/interface/handler.cpp
+++ b/src/interfaces/handler.cpp
@@ -2,15 +2,14 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <interface/handler.h>
+#include <interfaces/handler.h>
#include <util.h>
#include <boost/signals2/connection.hpp>
-#include <memory>
#include <utility>
-namespace interface {
+namespace interfaces {
namespace {
class HandlerImpl : public Handler
@@ -30,4 +29,4 @@ std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection)
return MakeUnique<HandlerImpl>(std::move(connection));
}
-} // namespace interface
+} // namespace interfaces
diff --git a/src/interface/handler.h b/src/interfaces/handler.h
index a76334bfbf..c4c674cac5 100644
--- a/src/interface/handler.h
+++ b/src/interfaces/handler.h
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_INTERFACE_HANDLER_H
-#define BITCOIN_INTERFACE_HANDLER_H
+#ifndef BITCOIN_INTERFACES_HANDLER_H
+#define BITCOIN_INTERFACES_HANDLER_H
#include <memory>
@@ -13,7 +13,7 @@ class connection;
} // namespace signals2
} // namespace boost
-namespace interface {
+namespace interfaces {
//! Generic interface for managing an event handler or callback function
//! registered with another interface. Has a single disconnect method to cancel
@@ -30,6 +30,6 @@ public:
//! Return handler wrapping a boost signal connection.
std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection);
-} // namespace interface
+} // namespace interfaces
-#endif // BITCOIN_INTERFACE_HANDLER_H
+#endif // BITCOIN_INTERFACES_HANDLER_H
diff --git a/src/interface/node.cpp b/src/interfaces/node.cpp
index f04da4e176..919748f942 100644
--- a/src/interface/node.cpp
+++ b/src/interfaces/node.cpp
@@ -2,15 +2,15 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <addrdb.h>
#include <amount.h>
#include <chain.h>
#include <chainparams.h>
#include <init.h>
-#include <interface/handler.h>
-#include <interface/wallet.h>
+#include <interfaces/handler.h>
+#include <interfaces/wallet.h>
#include <net.h>
#include <net_processing.h>
#include <netaddress.h>
@@ -43,7 +43,7 @@
#include <boost/thread/thread.hpp>
#include <univalue.h>
-namespace interface {
+namespace interfaces {
namespace {
class NodeImpl : public Node
@@ -305,4 +305,4 @@ class NodeImpl : public Node
std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
-} // namespace interface
+} // namespace interfaces
diff --git a/src/interface/node.h b/src/interfaces/node.h
index 6ae7f9e46c..f375af2f19 100644
--- a/src/interface/node.h
+++ b/src/interfaces/node.h
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_INTERFACE_NODE_H
-#define BITCOIN_INTERFACE_NODE_H
+#ifndef BITCOIN_INTERFACES_NODE_H
+#define BITCOIN_INTERFACES_NODE_H
#include <addrdb.h> // For banmap_t
#include <amount.h> // For CAmount
@@ -29,7 +29,7 @@ class proxyType;
enum class FeeReason;
struct CNodeStateStats;
-namespace interface {
+namespace interfaces {
class Handler;
class Wallet;
@@ -254,6 +254,6 @@ public:
//! Return implementation of Node interface.
std::unique_ptr<Node> MakeNode();
-} // namespace interface
+} // namespace interfaces
-#endif // BITCOIN_INTERFACE_NODE_H
+#endif // BITCOIN_INTERFACES_NODE_H
diff --git a/src/interface/wallet.cpp b/src/interfaces/wallet.cpp
index a6bce7d3de..21543552db 100644
--- a/src/interface/wallet.cpp
+++ b/src/interfaces/wallet.cpp
@@ -2,12 +2,12 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <interface/wallet.h>
+#include <interfaces/wallet.h>
#include <amount.h>
#include <chain.h>
#include <consensus/validation.h>
-#include <interface/handler.h>
+#include <interfaces/handler.h>
#include <net.h>
#include <policy/policy.h>
#include <primitives/transaction.h>
@@ -22,9 +22,7 @@
#include <wallet/feebumper.h>
#include <wallet/wallet.h>
-#include <memory>
-
-namespace interface {
+namespace interfaces {
namespace {
class PendingWalletTxImpl : public PendingWalletTx
@@ -283,7 +281,7 @@ public:
return result;
}
bool tryGetTxStatus(const uint256& txid,
- interface::WalletTxStatus& tx_status,
+ interfaces::WalletTxStatus& tx_status,
int& num_blocks,
int64_t& adjusted_time) override
{
@@ -438,4 +436,4 @@ public:
std::unique_ptr<Wallet> MakeWallet(CWallet& wallet) { return MakeUnique<WalletImpl>(wallet); }
-} // namespace interface
+} // namespace interfaces
diff --git a/src/interface/wallet.h b/src/interfaces/wallet.h
index b66ed63398..3e27242c2c 100644
--- a/src/interface/wallet.h
+++ b/src/interfaces/wallet.h
@@ -2,8 +2,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_INTERFACE_WALLET_H
-#define BITCOIN_INTERFACE_WALLET_H
+#ifndef BITCOIN_INTERFACES_WALLET_H
+#define BITCOIN_INTERFACES_WALLET_H
#include <amount.h> // For CAmount
#include <pubkey.h> // For CTxDestination (CKeyID and CScriptID)
@@ -27,7 +27,7 @@ class CWallet;
enum class OutputType;
struct CRecipient;
-namespace interface {
+namespace interfaces {
class Handler;
class PendingWalletTx;
@@ -347,6 +347,6 @@ struct WalletTxOut
//! in builds where ENABLE_WALLET is false.
std::unique_ptr<Wallet> MakeWallet(CWallet& wallet);
-} // namespace interface
+} // namespace interfaces
-#endif // BITCOIN_INTERFACE_WALLET_H
+#endif // BITCOIN_INTERFACES_WALLET_H
diff --git a/src/miner.cpp b/src/miner.cpp
index d2be393538..0660df928c 100644
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -27,7 +27,6 @@
#include <validationinterface.h>
#include <algorithm>
-#include <memory>
#include <queue>
#include <utility>
diff --git a/src/net.cpp b/src/net.cpp
index f45592ab83..342dfbaeb9 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -20,7 +20,6 @@
#include <ui_interface.h>
#include <utilstrencodings.h>
-#include <memory>
#ifdef WIN32
#include <string.h>
#else
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/qt/README.md b/src/qt/README.md
index 7ffea98170..7c23ccadcc 100644
--- a/src/qt/README.md
+++ b/src/qt/README.md
@@ -1,6 +1,6 @@
-This directory contains the BitcoinQT graphical user interface (GUI). It uses the cross platform framework [QT](https://www1.qt.io/developers/).
+This directory contains the BitcoinQT graphical user interface (GUI). It uses the cross-platform framework [Qt](https://www1.qt.io/developers/).
-The current precise version for QT 5 is specified in [qt.mk](/depends/packages/qt.mk). QT 4 is also supported (see [#8263](https://github.com/bitcoin/bitcoin/issues/8263)).
+The current precise version for Qt 5 is specified in [qt.mk](/depends/packages/qt.mk). Qt 4 is also supported (see [#8263](https://github.com/bitcoin/bitcoin/issues/8263)).
## Compile and run
@@ -36,7 +36,7 @@ Represents the main window of the Bitcoin UI.
### \*model.(h/cpp)
-The model. When it has a corresponding controller, it generally inherits from [QAbstractTableModel](http://doc.qt.io/qt-5/qabstracttablemodel.html). Models that are used by controllers as helpers inherit from other QT classes like [QValidator](http://doc.qt.io/qt-5/qvalidator.html).
+The model. When it has a corresponding controller, it generally inherits from [QAbstractTableModel](http://doc.qt.io/qt-5/qabstracttablemodel.html). Models that are used by controllers as helpers inherit from other Qt classes like [QValidator](http://doc.qt.io/qt-5/qvalidator.html).
ClientModel is used by the main application `bitcoingui` and several models like `peertablemodel`.
@@ -69,7 +69,7 @@ Represents the view to a single wallet.
## Contribute
-See [CONTRIBUTING.md](/CONTRIBUTING.md) for general guidelines. Specifically for QT:
+See [CONTRIBUTING.md](/CONTRIBUTING.md) for general guidelines. Specifically for Qt:
* don't change `local/bitcoin_en.ts`; this happens [automatically](/doc/translation_process.md#writing-code-with-translations)
@@ -83,7 +83,7 @@ Uncheck everything except Qt Creator during the installation process.
Instructions for OSX:
-1. Make sure you installed everything through Homebrew mentioned in the [OSX build instructions](/docs/build-osx.md)
+1. Make sure you installed everything through Homebrew mentioned in the [OSX build instructions](/doc/build-osx.md)
2. Use `./configure` with the `--enable-debug` flag
3. In Qt Creator do "New Project" -> Import Project -> Import Existing Project
4. Enter "bitcoin-qt" as project name, enter src/qt as location
diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp
index a9408895d9..1e3acd75c0 100644
--- a/src/qt/addresstablemodel.cpp
+++ b/src/qt/addresstablemodel.cpp
@@ -7,7 +7,7 @@
#include <qt/guiutil.h>
#include <qt/walletmodel.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <key_io.h>
#include <wallet/wallet.h>
@@ -74,7 +74,7 @@ public:
AddressTablePriv(AddressTableModel *_parent):
parent(_parent) {}
- void refreshAddressTable(interface::Wallet& wallet)
+ void refreshAddressTable(interfaces::Wallet& wallet)
{
cachedAddressTable.clear();
{
diff --git a/src/qt/addresstablemodel.h b/src/qt/addresstablemodel.h
index 954f0f593e..d7aeda9d8e 100644
--- a/src/qt/addresstablemodel.h
+++ b/src/qt/addresstablemodel.h
@@ -13,7 +13,7 @@ enum class OutputType;
class AddressTablePriv;
class WalletModel;
-namespace interface {
+namespace interfaces {
class Wallet;
}
diff --git a/src/qt/bantablemodel.cpp b/src/qt/bantablemodel.cpp
index cbd67d70ab..26cb03c2c7 100644
--- a/src/qt/bantablemodel.cpp
+++ b/src/qt/bantablemodel.cpp
@@ -8,7 +8,7 @@
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <sync.h>
#include <utiltime.h>
@@ -46,7 +46,7 @@ public:
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
- void refreshBanlist(interface::Node& node)
+ void refreshBanlist(interfaces::Node& node)
{
banmap_t banMap;
node.getBanned(banMap);
@@ -82,7 +82,7 @@ public:
}
};
-BanTableModel::BanTableModel(interface::Node& node, ClientModel *parent) :
+BanTableModel::BanTableModel(interfaces::Node& node, ClientModel *parent) :
QAbstractTableModel(parent),
m_node(node),
clientModel(parent)
diff --git a/src/qt/bantablemodel.h b/src/qt/bantablemodel.h
index 4c171e6fbe..d6c8dbf6dd 100644
--- a/src/qt/bantablemodel.h
+++ b/src/qt/bantablemodel.h
@@ -15,7 +15,7 @@
class ClientModel;
class BanTablePriv;
-namespace interface {
+namespace interfaces {
class Node;
}
@@ -45,7 +45,7 @@ class BanTableModel : public QAbstractTableModel
Q_OBJECT
public:
- explicit BanTableModel(interface::Node& node, ClientModel *parent = 0);
+ explicit BanTableModel(interfaces::Node& node, ClientModel *parent = 0);
~BanTableModel();
void startAutoRefresh();
void stopAutoRefresh();
@@ -71,7 +71,7 @@ public Q_SLOTS:
void refresh();
private:
- interface::Node& m_node;
+ interfaces::Node& m_node;
ClientModel *clientModel;
QStringList columns;
std::unique_ptr<BanTablePriv> priv;
diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp
index 30d0acb7ef..599c3c0985 100644
--- a/src/qt/bitcoin.cpp
+++ b/src/qt/bitcoin.cpp
@@ -27,17 +27,14 @@
#endif
#include <init.h>
-#include <interface/handler.h>
-#include <interface/node.h>
+#include <interfaces/handler.h>
+#include <interfaces/node.h>
#include <rpc/server.h>
#include <ui_interface.h>
#include <uint256.h>
#include <util.h>
#include <warnings.h>
-#ifdef ENABLE_WALLET
-#include <wallet/init.h>
-#endif
#include <walletinitinterface.h>
#include <memory>
@@ -182,7 +179,7 @@ class BitcoinCore: public QObject
{
Q_OBJECT
public:
- explicit BitcoinCore(interface::Node& node);
+ explicit BitcoinCore(interfaces::Node& node);
public Q_SLOTS:
void initialize();
@@ -197,7 +194,7 @@ private:
/// Pass fatal exception message to UI thread
void handleRunawayException(const std::exception *e);
- interface::Node& m_node;
+ interfaces::Node& m_node;
};
/** Main Bitcoin application object */
@@ -205,7 +202,7 @@ class BitcoinApplication: public QApplication
{
Q_OBJECT
public:
- explicit BitcoinApplication(interface::Node& node, int &argc, char **argv);
+ explicit BitcoinApplication(interfaces::Node& node, int &argc, char **argv);
~BitcoinApplication();
#ifdef ENABLE_WALLET
@@ -246,7 +243,7 @@ Q_SIGNALS:
private:
QThread *coreThread;
- interface::Node& m_node;
+ interfaces::Node& m_node;
OptionsModel *optionsModel;
ClientModel *clientModel;
BitcoinGUI *window;
@@ -264,7 +261,7 @@ private:
#include <qt/bitcoin.moc>
-BitcoinCore::BitcoinCore(interface::Node& node) :
+BitcoinCore::BitcoinCore(interfaces::Node& node) :
QObject(), m_node(node)
{
}
@@ -304,7 +301,7 @@ void BitcoinCore::shutdown()
}
}
-BitcoinApplication::BitcoinApplication(interface::Node& node, int &argc, char **argv):
+BitcoinApplication::BitcoinApplication(interfaces::Node& node, int &argc, char **argv):
QApplication(argc, argv),
coreThread(0),
m_node(node),
@@ -535,7 +532,7 @@ int main(int argc, char *argv[])
{
SetupEnvironment();
- std::unique_ptr<interface::Node> node = interface::MakeNode();
+ std::unique_ptr<interfaces::Node> node = interfaces::MakeNode();
/// 1. Parse command-line options. These take precedence over anything else.
// Command-line options take precedence:
@@ -630,7 +627,7 @@ int main(int argc, char *argv[])
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
- node->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;
@@ -660,11 +657,6 @@ int main(int argc, char *argv[])
// Start up the payment server early, too, so impatient users that click on
// bitcoin: links repeatedly have their payment requests routed to this process:
app.createPaymentServer();
-
- // Hook up the wallet init interface
- g_wallet_init_interface.reset(new WalletInit);
-#else
- g_wallet_init_interface.reset(new DummyWalletInit);
#endif
/// 9. Main GUI initialization
@@ -687,7 +679,7 @@ int main(int argc, char *argv[])
app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
// Subscribe to global signals from core
- std::unique_ptr<interface::Handler> handler = node->handleInitMessage(InitMessage);
+ std::unique_ptr<interfaces::Handler> handler = node->handleInitMessage(InitMessage);
if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());
diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp
index 63a2a200b2..bfa8844a09 100644
--- a/src/qt/bitcoingui.cpp
+++ b/src/qt/bitcoingui.cpp
@@ -30,8 +30,8 @@
#include <chainparams.h>
#include <init.h>
-#include <interface/handler.h>
-#include <interface/node.h>
+#include <interfaces/handler.h>
+#include <interfaces/node.h>
#include <ui_interface.h>
#include <util.h>
@@ -74,7 +74,7 @@ const std::string BitcoinGUI::DEFAULT_UIPLATFORM =
#endif
;
-BitcoinGUI::BitcoinGUI(interface::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
+BitcoinGUI::BitcoinGUI(interfaces::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
QMainWindow(parent),
enableWallet(false),
m_node(node),
diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h
index 3a4b25d804..e59c71cd4f 100644
--- a/src/qt/bitcoingui.h
+++ b/src/qt/bitcoingui.h
@@ -33,7 +33,7 @@ class WalletModel;
class HelpMessageDialog;
class ModalOverlay;
-namespace interface {
+namespace interfaces {
class Handler;
class Node;
}
@@ -56,7 +56,7 @@ class BitcoinGUI : public QMainWindow
public:
static const std::string DEFAULT_UIPLATFORM;
- explicit BitcoinGUI(interface::Node& node, const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = 0);
+ explicit BitcoinGUI(interfaces::Node& node, const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = 0);
~BitcoinGUI();
/** Set the client model.
@@ -83,9 +83,9 @@ protected:
bool eventFilter(QObject *object, QEvent *event);
private:
- interface::Node& m_node;
- std::unique_ptr<interface::Handler> m_handler_message_box;
- std::unique_ptr<interface::Handler> m_handler_question;
+ interfaces::Node& m_node;
+ std::unique_ptr<interfaces::Handler> m_handler_message_box;
+ std::unique_ptr<interfaces::Handler> m_handler_question;
ClientModel *clientModel;
WalletFrame *walletFrame;
diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp
index 1dbfc815b6..37fd06ccc9 100644
--- a/src/qt/clientmodel.cpp
+++ b/src/qt/clientmodel.cpp
@@ -13,8 +13,8 @@
#include <chainparams.h>
#include <checkpoints.h>
#include <clientversion.h>
-#include <interface/handler.h>
-#include <interface/node.h>
+#include <interfaces/handler.h>
+#include <interfaces/node.h>
#include <validation.h>
#include <net.h>
#include <txmempool.h>
@@ -32,7 +32,7 @@ class CBlockIndex;
static int64_t nLastHeaderTipUpdateNotification = 0;
static int64_t nLastBlockTipUpdateNotification = 0;
-ClientModel::ClientModel(interface::Node& node, OptionsModel *_optionsModel, QObject *parent) :
+ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) :
QObject(parent),
m_node(node),
optionsModel(_optionsModel),
diff --git a/src/qt/clientmodel.h b/src/qt/clientmodel.h
index 9faa10b87e..a609222f7d 100644
--- a/src/qt/clientmodel.h
+++ b/src/qt/clientmodel.h
@@ -17,7 +17,7 @@ class PeerTableModel;
class CBlockIndex;
-namespace interface {
+namespace interfaces {
class Handler;
class Node;
}
@@ -46,10 +46,10 @@ class ClientModel : public QObject
Q_OBJECT
public:
- explicit ClientModel(interface::Node& node, OptionsModel *optionsModel, QObject *parent = 0);
+ explicit ClientModel(interfaces::Node& node, OptionsModel *optionsModel, QObject *parent = 0);
~ClientModel();
- interface::Node& node() const { return m_node; }
+ interfaces::Node& node() const { return m_node; }
OptionsModel *getOptionsModel();
PeerTableModel *getPeerTableModel();
BanTableModel *getBanTableModel();
@@ -75,14 +75,14 @@ public:
mutable std::atomic<int64_t> cachedBestHeaderTime;
private:
- interface::Node& m_node;
- std::unique_ptr<interface::Handler> m_handler_show_progress;
- std::unique_ptr<interface::Handler> m_handler_notify_num_connections_changed;
- std::unique_ptr<interface::Handler> m_handler_notify_network_active_changed;
- std::unique_ptr<interface::Handler> m_handler_notify_alert_changed;
- std::unique_ptr<interface::Handler> m_handler_banned_list_changed;
- std::unique_ptr<interface::Handler> m_handler_notify_block_tip;
- std::unique_ptr<interface::Handler> m_handler_notify_header_tip;
+ interfaces::Node& m_node;
+ std::unique_ptr<interfaces::Handler> m_handler_show_progress;
+ std::unique_ptr<interfaces::Handler> m_handler_notify_num_connections_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_notify_network_active_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_notify_alert_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_banned_list_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_notify_block_tip;
+ std::unique_ptr<interfaces::Handler> m_handler_notify_header_tip;
OptionsModel *optionsModel;
PeerTableModel *peerTableModel;
BanTableModel *banTableModel;
diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp
index 2081d6ca08..601a77fc85 100644
--- a/src/qt/coincontroldialog.cpp
+++ b/src/qt/coincontroldialog.cpp
@@ -14,7 +14,7 @@
#include <qt/walletmodel.h>
#include <wallet/coincontrol.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <key_io.h>
#include <policy/fees.h>
#include <policy/policy.h>
@@ -648,7 +648,7 @@ void CoinControlDialog::updateView()
int nChildren = 0;
for (const auto& outpair : coins.second) {
const COutPoint& output = std::get<0>(outpair);
- const interface::WalletTxOut& out = std::get<1>(outpair);
+ const interfaces::WalletTxOut& out = std::get<1>(outpair);
nSum += out.txout.nValue;
nChildren++;
diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp
index 3501f97908..563f930dec 100644
--- a/src/qt/guiutil.cpp
+++ b/src/qt/guiutil.cpp
@@ -13,7 +13,7 @@
#include <chainparams.h>
#include <primitives/transaction.h>
#include <key_io.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <policy/policy.h>
#include <protocol.h>
#include <script/script.h>
@@ -232,7 +232,7 @@ QString formatBitcoinURI(const SendCoinsRecipient &info)
return ret;
}
-bool isDust(interface::Node& node, const QString& address, const CAmount& amount)
+bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount)
{
CTxDestination dest = DecodeDestination(address.toStdString());
CScript script = GetScriptForDestination(dest);
@@ -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 40037edb9d..4a26964098 100644
--- a/src/qt/guiutil.h
+++ b/src/qt/guiutil.h
@@ -20,7 +20,7 @@
class QValidatedLineEdit;
class SendCoinsRecipient;
-namespace interface
+namespace interfaces
{
class Node;
}
@@ -54,7 +54,7 @@ namespace GUIUtil
QString formatBitcoinURI(const SendCoinsRecipient &info);
// Returns true if given address+amount meets "dust" definition
- bool isDust(interface::Node& node, const QString& address, const CAmount& amount);
+ bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount);
// HTML escaping for rich text controls
QString HtmlEscape(const QString& str, bool fMultiLine=false);
diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp
index 4eb7482018..8c00ca0363 100644
--- a/src/qt/intro.cpp
+++ b/src/qt/intro.cpp
@@ -12,7 +12,7 @@
#include <qt/guiutil.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <util.h>
#include <QFileDialog>
@@ -187,7 +187,7 @@ QString Intro::getDefaultDataDirectory()
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
-bool Intro::pickDataDirectory(interface::Node& node)
+bool Intro::pickDataDirectory(interfaces::Node& node)
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
diff --git a/src/qt/intro.h b/src/qt/intro.h
index 07d2025bb6..b0937aedcb 100644
--- a/src/qt/intro.h
+++ b/src/qt/intro.h
@@ -13,7 +13,7 @@ static const bool DEFAULT_CHOOSE_DATADIR = false;
class FreespaceChecker;
-namespace interface {
+namespace interfaces {
class Node;
}
@@ -45,7 +45,7 @@ public:
* @note do NOT call global GetDataDir() before calling this function, this
* will cause the wrong path to be cached.
*/
- static bool pickDataDirectory(interface::Node& node);
+ static bool pickDataDirectory(interfaces::Node& node);
/**
* Determine default data directory for operating system.
diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp
index 438e9e70f1..c0ddb89b40 100644
--- a/src/qt/optionsdialog.cpp
+++ b/src/qt/optionsdialog.cpp
@@ -13,7 +13,7 @@
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <validation.h> // for DEFAULT_SCRIPTCHECK_THREADS and MAX_SCRIPTCHECK_THREADS
#include <netbase.h>
#include <txdb.h> // for -dbcache defaults
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index d8197b6ec6..30c8124c58 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -11,7 +11,7 @@
#include <qt/bitcoinunits.h>
#include <qt/guiutil.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <validation.h> // For DEFAULT_SCRIPTCHECK_THREADS
#include <net.h>
#include <netbase.h>
@@ -24,7 +24,7 @@
const char *DEFAULT_GUI_PROXY_HOST = "127.0.0.1";
-OptionsModel::OptionsModel(interface::Node& node, QObject *parent, bool resetSettings) :
+OptionsModel::OptionsModel(interfaces::Node& node, QObject *parent, bool resetSettings) :
QAbstractListModel(parent), m_node(node)
{
Init(resetSettings);
diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h
index 96c6b8fa45..fc1d119a71 100644
--- a/src/qt/optionsmodel.h
+++ b/src/qt/optionsmodel.h
@@ -9,7 +9,7 @@
#include <QAbstractListModel>
-namespace interface {
+namespace interfaces {
class Node;
}
@@ -31,7 +31,7 @@ class OptionsModel : public QAbstractListModel
Q_OBJECT
public:
- explicit OptionsModel(interface::Node& node, QObject *parent = 0, bool resetSettings = false);
+ explicit OptionsModel(interfaces::Node& node, QObject *parent = 0, bool resetSettings = false);
enum OptionID {
StartAtStartup, // bool
@@ -79,10 +79,10 @@ public:
void setRestartRequired(bool fRequired);
bool isRestartRequired() const;
- interface::Node& node() const { return m_node; }
+ interfaces::Node& node() const { return m_node; }
private:
- interface::Node& m_node;
+ interfaces::Node& m_node;
/* Qt-only settings */
bool fHideTrayIcon;
bool fMinimizeToTray;
diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp
index 76d0220648..8e8788dad3 100644
--- a/src/qt/overviewpage.cpp
+++ b/src/qt/overviewpage.cpp
@@ -21,7 +21,7 @@
#define DECORATION_SIZE 54
#define NUM_ITEMS 5
-Q_DECLARE_METATYPE(interface::WalletBalances)
+Q_DECLARE_METATYPE(interfaces::WalletBalances)
class TxViewDelegate : public QAbstractItemDelegate
{
@@ -157,7 +157,7 @@ OverviewPage::~OverviewPage()
delete ui;
}
-void OverviewPage::setBalance(const interface::WalletBalances& balances)
+void OverviewPage::setBalance(const interfaces::WalletBalances& balances)
{
int unit = walletModel->getOptionsModel()->getDisplayUnit();
m_balances = balances;
@@ -224,10 +224,10 @@ void OverviewPage::setWalletModel(WalletModel *model)
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
- interface::Wallet& wallet = model->wallet();
- interface::WalletBalances balances = wallet.getBalances();
+ interfaces::Wallet& wallet = model->wallet();
+ interfaces::WalletBalances balances = wallet.getBalances();
setBalance(balances);
- connect(model, SIGNAL(balanceChanged(interface::WalletBalances)), this, SLOT(setBalance(interface::WalletBalances)));
+ connect(model, SIGNAL(balanceChanged(interfaces::WalletBalances)), this, SLOT(setBalance(interfaces::WalletBalances)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
diff --git a/src/qt/overviewpage.h b/src/qt/overviewpage.h
index 36333536e5..d519eca43a 100644
--- a/src/qt/overviewpage.h
+++ b/src/qt/overviewpage.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_OVERVIEWPAGE_H
#define BITCOIN_QT_OVERVIEWPAGE_H
-#include <interface/wallet.h>
+#include <interfaces/wallet.h>
#include <QWidget>
#include <memory>
@@ -38,7 +38,7 @@ public:
void showOutOfSyncWarning(bool fShow);
public Q_SLOTS:
- void setBalance(const interface::WalletBalances& balances);
+ void setBalance(const interfaces::WalletBalances& balances);
Q_SIGNALS:
void transactionClicked(const QModelIndex &index);
@@ -48,7 +48,7 @@ private:
Ui::OverviewPage *ui;
ClientModel *clientModel;
WalletModel *walletModel;
- interface::WalletBalances m_balances;
+ interfaces::WalletBalances m_balances;
TxViewDelegate *txdelegate;
std::unique_ptr<TransactionFilterProxy> filter;
diff --git a/src/qt/paymentrequestplus.cpp b/src/qt/paymentrequestplus.cpp
index 357e98a53c..b0ef475b35 100644
--- a/src/qt/paymentrequestplus.cpp
+++ b/src/qt/paymentrequestplus.cpp
@@ -9,7 +9,6 @@
#include <qt/paymentrequestplus.h>
-#include <script/script.h>
#include <util.h>
#include <stdexcept>
diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp
index 926a699754..70cdb3361c 100644
--- a/src/qt/paymentserver.cpp
+++ b/src/qt/paymentserver.cpp
@@ -9,7 +9,7 @@
#include <qt/optionsmodel.h>
#include <chainparams.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <policy/policy.h>
#include <key_io.h>
#include <ui_interface.h>
@@ -201,7 +201,7 @@ void PaymentServer::LoadRootCAs(X509_STORE* _store)
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "Q_EMIT message()", but "QMessageBox::"!
//
-void PaymentServer::ipcParseCommandLine(interface::Node& node, int argc, char* argv[])
+void PaymentServer::ipcParseCommandLine(interfaces::Node& node, int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
@@ -760,7 +760,7 @@ void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
-bool PaymentServer::verifyNetwork(interface::Node& node, const payments::PaymentDetails& requestDetails)
+bool PaymentServer::verifyNetwork(interfaces::Node& node, const payments::PaymentDetails& requestDetails)
{
bool fVerified = requestDetails.network() == node.getNetwork();
if (!fVerified) {
diff --git a/src/qt/paymentserver.h b/src/qt/paymentserver.h
index e139899e22..511fc5bd6e 100644
--- a/src/qt/paymentserver.h
+++ b/src/qt/paymentserver.h
@@ -60,7 +60,7 @@ class PaymentServer : public QObject
public:
// Parse URIs on command line
// Returns false on error
- static void ipcParseCommandLine(interface::Node& node, int argc, char *argv[]);
+ static void ipcParseCommandLine(interfaces::Node& node, int argc, char *argv[]);
// Returns true if there were URIs on the command line
// which were successfully sent to an already-running
@@ -87,7 +87,7 @@ public:
void setOptionsModel(OptionsModel *optionsModel);
// Verify that the payment request network matches the client network
- static bool verifyNetwork(interface::Node& node, const payments::PaymentDetails& requestDetails);
+ static bool verifyNetwork(interfaces::Node& node, const payments::PaymentDetails& requestDetails);
// Verify if the payment request is expired
static bool verifyExpired(const payments::PaymentDetails& requestDetails);
// Verify the payment request size is valid as per BIP70
diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp
index f33db8e761..7e318e3035 100644
--- a/src/qt/peertablemodel.cpp
+++ b/src/qt/peertablemodel.cpp
@@ -8,7 +8,7 @@
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <validation.h> // for cs_main
#include <sync.h>
@@ -57,12 +57,12 @@ public:
std::map<NodeId, int> mapNodeRows;
/** Pull a full list of peers from vNodes into our cache */
- void refreshPeers(interface::Node& node)
+ void refreshPeers(interfaces::Node& node)
{
{
cachedNodeStats.clear();
- interface::Node::NodesStats nodes_stats;
+ interfaces::Node::NodesStats nodes_stats;
node.getNodesStats(nodes_stats);
#if QT_VERSION >= 0x040700
cachedNodeStats.reserve(nodes_stats.size());
@@ -102,7 +102,7 @@ public:
}
};
-PeerTableModel::PeerTableModel(interface::Node& node, ClientModel *parent) :
+PeerTableModel::PeerTableModel(interfaces::Node& node, ClientModel *parent) :
QAbstractTableModel(parent),
m_node(node),
clientModel(parent),
diff --git a/src/qt/peertablemodel.h b/src/qt/peertablemodel.h
index c53462c57c..69c9744c8f 100644
--- a/src/qt/peertablemodel.h
+++ b/src/qt/peertablemodel.h
@@ -16,7 +16,7 @@
class ClientModel;
class PeerTablePriv;
-namespace interface {
+namespace interfaces {
class Node;
}
@@ -51,7 +51,7 @@ class PeerTableModel : public QAbstractTableModel
Q_OBJECT
public:
- explicit PeerTableModel(interface::Node& node, ClientModel *parent = 0);
+ explicit PeerTableModel(interfaces::Node& node, ClientModel *parent = 0);
~PeerTableModel();
const CNodeCombinedStats *getNodeStats(int idx);
int getRowByNodeId(NodeId nodeid);
@@ -82,7 +82,7 @@ public Q_SLOTS:
void refresh();
private:
- interface::Node& m_node;
+ interfaces::Node& m_node;
ClientModel *clientModel;
QStringList columns;
std::unique_ptr<PeerTablePriv> priv;
diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp
index 745055b944..5122bab36f 100644
--- a/src/qt/rpcconsole.cpp
+++ b/src/qt/rpcconsole.cpp
@@ -14,7 +14,7 @@
#include <qt/platformstyle.h>
#include <qt/walletmodel.h>
#include <chainparams.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <netbase.h>
#include <rpc/server.h>
#include <rpc/client.h>
@@ -85,7 +85,7 @@ class RPCExecutor : public QObject
{
Q_OBJECT
public:
- RPCExecutor(interface::Node& node) : m_node(node) {}
+ RPCExecutor(interfaces::Node& node) : m_node(node) {}
public Q_SLOTS:
void request(const QString &command, const QString &walletID);
@@ -94,7 +94,7 @@ Q_SIGNALS:
void reply(int category, const QString &command);
private:
- interface::Node& m_node;
+ interfaces::Node& m_node;
};
/** Class for handling RPC timers
@@ -153,7 +153,7 @@ public:
* @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
*/
-bool RPCConsole::RPCParseCommandLine(interface::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const std::string *walletID)
+bool RPCConsole::RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const std::string *walletID)
{
std::vector< std::vector<std::string> > stack;
stack.push_back(std::vector<std::string>());
@@ -451,7 +451,7 @@ void RPCExecutor::request(const QString &command, const QString &walletID)
}
}
-RPCConsole::RPCConsole(interface::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) :
+RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) :
QWidget(parent),
m_node(node),
ui(new Ui::RPCConsole),
@@ -575,7 +575,7 @@ void RPCConsole::setClientModel(ClientModel *model)
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
- interface::Node& node = clientModel->node();
+ interfaces::Node& node = clientModel->node();
setNumBlocks(node.getNumBlocks(), QDateTime::fromTime_t(node.getLastBlockTime()), node.getVerificationProgress(), false);
connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
diff --git a/src/qt/rpcconsole.h b/src/qt/rpcconsole.h
index 8381301759..a9a60d09f1 100644
--- a/src/qt/rpcconsole.h
+++ b/src/qt/rpcconsole.h
@@ -19,7 +19,7 @@ class PlatformStyle;
class RPCTimerInterface;
class WalletModel;
-namespace interface {
+namespace interfaces {
class Node;
}
@@ -38,11 +38,11 @@ class RPCConsole: public QWidget
Q_OBJECT
public:
- explicit RPCConsole(interface::Node& node, const PlatformStyle *platformStyle, QWidget *parent);
+ explicit RPCConsole(interfaces::Node& node, const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole();
- static bool RPCParseCommandLine(interface::Node* node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr);
- static bool RPCExecuteCommandLine(interface::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr) {
+ static bool RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr);
+ static bool RPCExecuteCommandLine(interfaces::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const std::string *walletID = nullptr) {
return RPCParseCommandLine(&node, strResult, strCommand, true, pstrFilteredOut, walletID);
}
@@ -144,7 +144,7 @@ private:
};
- interface::Node& m_node;
+ interfaces::Node& m_node;
Ui::RPCConsole *ui;
ClientModel *clientModel;
QStringList history;
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index b4c1471a4f..0874a0ada4 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -15,7 +15,7 @@
#include <qt/sendcoinsentry.h>
#include <chainparams.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <key_io.h>
#include <wallet/coincontrol.h>
#include <ui_interface.h>
@@ -149,9 +149,9 @@ void SendCoinsDialog::setModel(WalletModel *_model)
}
}
- interface::WalletBalances balances = _model->wallet().getBalances();
+ interfaces::WalletBalances balances = _model->wallet().getBalances();
setBalance(balances);
- connect(_model, SIGNAL(balanceChanged(interface::WalletBalances)), this, SLOT(setBalance(interface::WalletBalances)));
+ connect(_model, SIGNAL(balanceChanged(interfaces::WalletBalances)), this, SLOT(setBalance(interfaces::WalletBalances)));
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
@@ -515,7 +515,7 @@ bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
return true;
}
-void SendCoinsDialog::setBalance(const interface::WalletBalances& balances)
+void SendCoinsDialog::setBalance(const interfaces::WalletBalances& balances)
{
if(model && model->getOptionsModel())
{
diff --git a/src/qt/sendcoinsdialog.h b/src/qt/sendcoinsdialog.h
index 43757e3186..40a1d10c2b 100644
--- a/src/qt/sendcoinsdialog.h
+++ b/src/qt/sendcoinsdialog.h
@@ -51,7 +51,7 @@ public Q_SLOTS:
void accept();
SendCoinsEntry *addEntry();
void updateTabsAndLabels();
- void setBalance(const interface::WalletBalances& balances);
+ void setBalance(const interfaces::WalletBalances& balances);
Q_SIGNALS:
void coinsSent(const uint256& txid);
diff --git a/src/qt/sendcoinsentry.cpp b/src/qt/sendcoinsentry.cpp
index 6a961d83ea..977425f7e3 100644
--- a/src/qt/sendcoinsentry.cpp
+++ b/src/qt/sendcoinsentry.cpp
@@ -127,7 +127,7 @@ void SendCoinsEntry::useAvailableBalanceClicked()
Q_EMIT useAvailableBalance(this);
}
-bool SendCoinsEntry::validate(interface::Node& node)
+bool SendCoinsEntry::validate(interfaces::Node& node)
{
if (!model)
return false;
diff --git a/src/qt/sendcoinsentry.h b/src/qt/sendcoinsentry.h
index 715f4cfde5..76f96c61e0 100644
--- a/src/qt/sendcoinsentry.h
+++ b/src/qt/sendcoinsentry.h
@@ -30,7 +30,7 @@ public:
~SendCoinsEntry();
void setModel(WalletModel *model);
- bool validate(interface::Node& node);
+ bool validate(interfaces::Node& node);
SendCoinsRecipient getValue();
/** Return whether the entry is still empty and unedited */
diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp
index 2475a82ef9..4d972b431c 100644
--- a/src/qt/splashscreen.cpp
+++ b/src/qt/splashscreen.cpp
@@ -12,9 +12,9 @@
#include <clientversion.h>
#include <init.h>
-#include <interface/handler.h>
-#include <interface/node.h>
-#include <interface/wallet.h>
+#include <interfaces/handler.h>
+#include <interfaces/node.h>
+#include <interfaces/wallet.h>
#include <util.h>
#include <ui_interface.h>
#include <version.h>
@@ -25,7 +25,7 @@
#include <QPainter>
#include <QRadialGradient>
-SplashScreen::SplashScreen(interface::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) :
+SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) :
QWidget(0, f), curAlignment(0), m_node(node)
{
// set reference point, paddings
@@ -177,7 +177,7 @@ static void ShowProgress(SplashScreen *splash, const std::string &title, int nPr
strprintf("\n%d", nProgress) + "%");
}
#ifdef ENABLE_WALLET
-void SplashScreen::ConnectWallet(std::unique_ptr<interface::Wallet> wallet)
+void SplashScreen::ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet)
{
m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2, false)));
m_connected_wallets.emplace_back(std::move(wallet));
@@ -190,7 +190,7 @@ void SplashScreen::subscribeToCoreSignals()
m_handler_init_message = m_node.handleInitMessage(boost::bind(InitMessage, this, _1));
m_handler_show_progress = m_node.handleShowProgress(boost::bind(ShowProgress, this, _1, _2, _3));
#ifdef ENABLE_WALLET
- m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interface::Wallet> wallet) { ConnectWallet(std::move(wallet)); });
+ m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { ConnectWallet(std::move(wallet)); });
#endif
}
diff --git a/src/qt/splashscreen.h b/src/qt/splashscreen.h
index 419f36f641..9ef19675d8 100644
--- a/src/qt/splashscreen.h
+++ b/src/qt/splashscreen.h
@@ -12,7 +12,7 @@
class NetworkStyle;
-namespace interface {
+namespace interfaces {
class Handler;
class Node;
class Wallet;
@@ -29,7 +29,7 @@ class SplashScreen : public QWidget
Q_OBJECT
public:
- explicit SplashScreen(interface::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle);
+ explicit SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle);
~SplashScreen();
protected:
@@ -52,19 +52,19 @@ private:
/** Disconnect core signals to splash screen */
void unsubscribeFromCoreSignals();
/** Connect wallet signals to splash screen */
- void ConnectWallet(std::unique_ptr<interface::Wallet> wallet);
+ void ConnectWallet(std::unique_ptr<interfaces::Wallet> wallet);
QPixmap pixmap;
QString curMessage;
QColor curColor;
int curAlignment;
- interface::Node& m_node;
- std::unique_ptr<interface::Handler> m_handler_init_message;
- std::unique_ptr<interface::Handler> m_handler_show_progress;
- std::unique_ptr<interface::Handler> m_handler_load_wallet;
- std::list<std::unique_ptr<interface::Wallet>> m_connected_wallets;
- std::list<std::unique_ptr<interface::Handler>> m_connected_wallet_handlers;
+ interfaces::Node& m_node;
+ std::unique_ptr<interfaces::Handler> m_handler_init_message;
+ std::unique_ptr<interfaces::Handler> m_handler_show_progress;
+ std::unique_ptr<interfaces::Handler> m_handler_load_wallet;
+ std::list<std::unique_ptr<interfaces::Wallet>> m_connected_wallets;
+ std::list<std::unique_ptr<interfaces::Handler>> m_connected_wallet_handlers;
};
#endif // BITCOIN_QT_SPLASHSCREEN_H
diff --git a/src/qt/test/paymentservertests.cpp b/src/qt/test/paymentservertests.cpp
index 46e9d4d0a4..83484b5ce7 100644
--- a/src/qt/test/paymentservertests.cpp
+++ b/src/qt/test/paymentservertests.cpp
@@ -9,7 +9,7 @@
#include <amount.h>
#include <chainparams.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <random.h>
#include <script/script.h>
#include <script/standard.h>
@@ -67,7 +67,7 @@ static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsig
void PaymentServerTests::paymentServerTests()
{
SelectParams(CBaseChainParams::MAIN);
- auto node = interface::MakeNode();
+ auto node = interfaces::MakeNode();
OptionsModel optionsModel(*node);
PaymentServer* server = new PaymentServer(nullptr, false);
X509_STORE* caStore = X509_STORE_new();
diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp
index 467107dc4c..974e7831c4 100644
--- a/src/qt/test/rpcnestedtests.cpp
+++ b/src/qt/test/rpcnestedtests.cpp
@@ -7,7 +7,7 @@
#include <chainparams.h>
#include <consensus/validation.h>
#include <fs.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <validation.h>
#include <rpc/register.h>
#include <rpc/server.h>
@@ -46,7 +46,7 @@ void RPCNestedTests::rpcNestedTests()
std::string result;
std::string result2;
std::string filtered;
- auto node = interface::MakeNode();
+ auto node = interfaces::MakeNode();
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp
index b60c5b979f..dcc834c352 100644
--- a/src/qt/test/wallettests.cpp
+++ b/src/qt/test/wallettests.cpp
@@ -1,6 +1,6 @@
#include <qt/test/wallettests.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <qt/bitcoinamountfield.h>
#include <qt/callback.h>
#include <qt/optionsmodel.h>
@@ -158,7 +158,7 @@ void TestGUI()
for (int i = 0; i < 5; ++i) {
test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey()));
}
- CWallet wallet("mock", CWalletDBWrapper::CreateMock());
+ CWallet wallet("mock", WalletDatabase::CreateMock());
bool firstRun;
wallet.LoadWallet(firstRun);
{
@@ -178,7 +178,7 @@ void TestGUI()
std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
SendCoinsDialog sendCoinsDialog(platformStyle.get());
TransactionView transactionView(platformStyle.get());
- auto node = interface::MakeNode();
+ auto node = interfaces::MakeNode();
OptionsModel optionsModel(*node);
vpwallets.insert(vpwallets.begin(), &wallet);
WalletModel walletModel(std::move(node->getWallets()[0]), *node, platformStyle.get(), &optionsModel);
diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp
index ff378ed1bf..5a3b645f65 100644
--- a/src/qt/trafficgraphwidget.cpp
+++ b/src/qt/trafficgraphwidget.cpp
@@ -2,7 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <qt/trafficgraphwidget.h>
#include <qt/clientmodel.h>
diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp
index 409835592f..f316c3ca45 100644
--- a/src/qt/transactiondesc.cpp
+++ b/src/qt/transactiondesc.cpp
@@ -10,7 +10,7 @@
#include <qt/transactionrecord.h>
#include <consensus/consensus.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <key_io.h>
#include <validation.h>
#include <script/script.h>
@@ -23,7 +23,7 @@
#include <stdint.h>
#include <string>
-QString TransactionDesc::FormatTxStatus(const interface::WalletTx& wtx, const interface::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime)
+QString TransactionDesc::FormatTxStatus(const interfaces::WalletTx& wtx, const interfaces::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime)
{
if (!status.is_final)
{
@@ -48,14 +48,14 @@ QString TransactionDesc::FormatTxStatus(const interface::WalletTx& wtx, const in
}
}
-QString TransactionDesc::toHTML(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit)
+QString TransactionDesc::toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit)
{
int numBlocks;
int64_t adjustedTime;
- interface::WalletTxStatus status;
- interface::WalletOrderForm orderForm;
+ interfaces::WalletTxStatus status;
+ interfaces::WalletOrderForm orderForm;
bool inMempool;
- interface::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime);
+ interfaces::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime);
QString strHTML;
diff --git a/src/qt/transactiondesc.h b/src/qt/transactiondesc.h
index ea9ab28ee3..cb8453cb81 100644
--- a/src/qt/transactiondesc.h
+++ b/src/qt/transactiondesc.h
@@ -10,7 +10,7 @@
class TransactionRecord;
-namespace interface {
+namespace interfaces {
class Node;
class Wallet;
struct WalletTx;
@@ -24,12 +24,12 @@ class TransactionDesc: public QObject
Q_OBJECT
public:
- static QString toHTML(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit);
+ static QString toHTML(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit);
private:
TransactionDesc() {}
- static QString FormatTxStatus(const interface::WalletTx& wtx, const interface::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime);
+ static QString FormatTxStatus(const interfaces::WalletTx& wtx, const interfaces::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime);
};
#endif // BITCOIN_QT_TRANSACTIONDESC_H
diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp
index 60ab2d57d7..b6ed66ad96 100644
--- a/src/qt/transactionrecord.cpp
+++ b/src/qt/transactionrecord.cpp
@@ -5,7 +5,7 @@
#include <qt/transactionrecord.h>
#include <consensus/consensus.h>
-#include <interface/wallet.h>
+#include <interfaces/wallet.h>
#include <key_io.h>
#include <timedata.h>
#include <validation.h>
@@ -25,7 +25,7 @@ bool TransactionRecord::showTransaction()
/*
* Decompose CWallet transaction to model transaction records.
*/
-QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interface::WalletTx& wtx)
+QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interfaces::WalletTx& wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.time;
@@ -158,7 +158,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interface
return parts;
}
-void TransactionRecord::updateStatus(const interface::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime)
+void TransactionRecord::updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime)
{
// Determine transaction status
diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h
index c653584b52..62961434ed 100644
--- a/src/qt/transactionrecord.h
+++ b/src/qt/transactionrecord.h
@@ -11,7 +11,7 @@
#include <QList>
#include <QString>
-namespace interface {
+namespace interfaces {
class Node;
class Wallet;
struct WalletTx;
@@ -111,7 +111,7 @@ public:
/** Decompose CWallet transaction to model transaction records.
*/
static bool showTransaction();
- static QList<TransactionRecord> decomposeTransaction(const interface::WalletTx& wtx);
+ static QList<TransactionRecord> decomposeTransaction(const interfaces::WalletTx& wtx);
/** @name Immutable transaction attributes
@{*/
@@ -140,7 +140,7 @@ public:
/** Update status from core wallet tx.
*/
- void updateStatus(const interface::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime);
+ void updateStatus(const interfaces::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime);
/** Return whether a status update is needed.
*/
diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp
index 2148ff1728..46169a91d1 100644
--- a/src/qt/transactiontablemodel.cpp
+++ b/src/qt/transactiontablemodel.cpp
@@ -14,8 +14,8 @@
#include <qt/walletmodel.h>
#include <core_io.h>
-#include <interface/handler.h>
-#include <interface/node.h>
+#include <interfaces/handler.h>
+#include <interfaces/node.h>
#include <validation.h>
#include <sync.h>
#include <uint256.h>
@@ -73,7 +73,7 @@ public:
/* Query entire wallet anew from core.
*/
- void refreshWallet(interface::Wallet& wallet)
+ void refreshWallet(interfaces::Wallet& wallet)
{
qDebug() << "TransactionTablePriv::refreshWallet";
cachedWallet.clear();
@@ -91,7 +91,7 @@ public:
Call with transaction that was added, removed or changed.
*/
- void updateWallet(interface::Wallet& wallet, const uint256 &hash, int status, bool showTransaction)
+ void updateWallet(interfaces::Wallet& wallet, const uint256 &hash, int status, bool showTransaction)
{
qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);
@@ -127,7 +127,7 @@ public:
if(showTransaction)
{
// Find transaction in wallet
- interface::WalletTx wtx = wallet.getWalletTx(hash);
+ interfaces::WalletTx wtx = wallet.getWalletTx(hash);
if(!wtx.tx)
{
qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet";
@@ -176,7 +176,7 @@ public:
return cachedWallet.size();
}
- TransactionRecord *index(interface::Wallet& wallet, int idx)
+ TransactionRecord *index(interfaces::Wallet& wallet, int idx)
{
if(idx >= 0 && idx < cachedWallet.size())
{
@@ -189,7 +189,7 @@ public:
// If a status update is needed (blocks came in since last check),
// update the status of this transaction from the wallet. Otherwise,
// simply re-use the cached status.
- interface::WalletTxStatus wtx;
+ interfaces::WalletTxStatus wtx;
int numBlocks;
int64_t adjustedTime;
if (wallet.tryGetTxStatus(rec->hash, wtx, numBlocks, adjustedTime) && rec->statusUpdateNeeded(numBlocks)) {
@@ -200,12 +200,12 @@ public:
return 0;
}
- QString describe(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit)
+ QString describe(interfaces::Node& node, interfaces::Wallet& wallet, TransactionRecord *rec, int unit)
{
return TransactionDesc::toHTML(node, wallet, rec, unit);
}
- QString getTxHex(interface::Wallet& wallet, TransactionRecord *rec)
+ QString getTxHex(interfaces::Wallet& wallet, TransactionRecord *rec)
{
auto tx = wallet.getTx(rec->hash);
if (tx) {
diff --git a/src/qt/transactiontablemodel.h b/src/qt/transactiontablemodel.h
index 57566db638..8b029be5f5 100644
--- a/src/qt/transactiontablemodel.h
+++ b/src/qt/transactiontablemodel.h
@@ -12,7 +12,7 @@
#include <memory>
-namespace interface {
+namespace interfaces {
class Handler;
}
@@ -85,8 +85,8 @@ public:
private:
WalletModel *walletModel;
- std::unique_ptr<interface::Handler> m_handler_transaction_changed;
- std::unique_ptr<interface::Handler> m_handler_show_progress;
+ std::unique_ptr<interfaces::Handler> m_handler_transaction_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_show_progress;
QStringList columns;
TransactionTablePriv *priv;
bool fProcessingQueuedTransactions;
diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp
index 6114ea0de1..d5b98486ae 100644
--- a/src/qt/utilitydialog.cpp
+++ b/src/qt/utilitydialog.cpp
@@ -19,7 +19,7 @@
#include <clientversion.h>
#include <init.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <util.h>
#include <stdio.h>
@@ -32,7 +32,7 @@
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
-HelpMessageDialog::HelpMessageDialog(interface::Node& node, QWidget *parent, bool about) :
+HelpMessageDialog::HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
diff --git a/src/qt/utilitydialog.h b/src/qt/utilitydialog.h
index e6ad7be5d0..f5c8af4362 100644
--- a/src/qt/utilitydialog.h
+++ b/src/qt/utilitydialog.h
@@ -10,7 +10,7 @@
class BitcoinGUI;
-namespace interface {
+namespace interfaces {
class Node;
}
@@ -24,7 +24,7 @@ class HelpMessageDialog : public QDialog
Q_OBJECT
public:
- explicit HelpMessageDialog(interface::Node& node, QWidget *parent, bool about);
+ explicit HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about);
~HelpMessageDialog();
void printToConsole();
diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp
index d9db437dc5..00b98901c0 100644
--- a/src/qt/walletmodel.cpp
+++ b/src/qt/walletmodel.cpp
@@ -12,8 +12,8 @@
#include <qt/sendcoinsdialog.h>
#include <qt/transactiontablemodel.h>
-#include <interface/handler.h>
-#include <interface/node.h>
+#include <interfaces/handler.h>
+#include <interfaces/node.h>
#include <key_io.h>
#include <ui_interface.h>
#include <util.h> // for GetBoolArg
@@ -28,7 +28,7 @@
#include <QTimer>
-WalletModel::WalletModel(std::unique_ptr<interface::Wallet> wallet, interface::Node& node, const PlatformStyle *platformStyle, OptionsModel *_optionsModel, QObject *parent) :
+WalletModel::WalletModel(std::unique_ptr<interfaces::Wallet> wallet, interfaces::Node& node, const PlatformStyle *platformStyle, OptionsModel *_optionsModel, QObject *parent) :
QObject(parent), m_wallet(std::move(wallet)), m_node(node), optionsModel(_optionsModel), addressTableModel(0),
transactionTableModel(0),
recentRequestsTableModel(0),
@@ -70,7 +70,7 @@ void WalletModel::pollBalanceChanged()
// avoids the GUI from getting stuck on periodical polls if the core is
// holding the locks for a longer time - for example, during a wallet
// rescan.
- interface::WalletBalances new_balances;
+ interfaces::WalletBalances new_balances;
int numBlocks = -1;
if (!m_wallet->tryGetBalances(new_balances, numBlocks)) {
return;
@@ -89,7 +89,7 @@ void WalletModel::pollBalanceChanged()
}
}
-void WalletModel::checkBalanceChanged(const interface::WalletBalances& new_balances)
+void WalletModel::checkBalanceChanged(const interfaces::WalletBalances& new_balances)
{
if(new_balances.balanceChanged(m_cached_balances)) {
m_cached_balances = new_balances;
diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h
index bc409b10ee..e5ed5b4e82 100644
--- a/src/qt/walletmodel.h
+++ b/src/qt/walletmodel.h
@@ -13,7 +13,7 @@
#include <qt/paymentrequestplus.h>
#include <qt/walletmodeltransaction.h>
-#include <interface/wallet.h>
+#include <interfaces/wallet.h>
#include <support/allocators/secure.h>
#include <map>
@@ -37,9 +37,9 @@ class COutput;
class CPubKey;
class uint256;
-namespace interface {
+namespace interfaces {
class Node;
-} // namespace interface
+} // namespace interfaces
QT_BEGIN_NAMESPACE
class QTimer;
@@ -111,7 +111,7 @@ class WalletModel : public QObject
Q_OBJECT
public:
- explicit WalletModel(std::unique_ptr<interface::Wallet> wallet, interface::Node& node, const PlatformStyle *platformStyle, OptionsModel *optionsModel, QObject *parent = 0);
+ explicit WalletModel(std::unique_ptr<interfaces::Wallet> wallet, interfaces::Node& node, const PlatformStyle *platformStyle, OptionsModel *optionsModel, QObject *parent = 0);
~WalletModel();
enum StatusCode // Returned by sendCoins
@@ -198,20 +198,20 @@ public:
static bool isWalletEnabled();
- interface::Node& node() const { return m_node; }
- interface::Wallet& wallet() const { return *m_wallet; }
+ interfaces::Node& node() const { return m_node; }
+ interfaces::Wallet& wallet() const { return *m_wallet; }
QString getWalletName() const;
bool isMultiwallet();
private:
- std::unique_ptr<interface::Wallet> m_wallet;
- std::unique_ptr<interface::Handler> m_handler_status_changed;
- std::unique_ptr<interface::Handler> m_handler_address_book_changed;
- std::unique_ptr<interface::Handler> m_handler_transaction_changed;
- std::unique_ptr<interface::Handler> m_handler_show_progress;
- std::unique_ptr<interface::Handler> m_handler_watch_only_changed;
- interface::Node& m_node;
+ std::unique_ptr<interfaces::Wallet> m_wallet;
+ std::unique_ptr<interfaces::Handler> m_handler_status_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_address_book_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_transaction_changed;
+ std::unique_ptr<interfaces::Handler> m_handler_show_progress;
+ std::unique_ptr<interfaces::Handler> m_handler_watch_only_changed;
+ interfaces::Node& m_node;
bool fHaveWatchOnly;
bool fForceCheckBalanceChanged;
@@ -225,7 +225,7 @@ private:
RecentRequestsTableModel *recentRequestsTableModel;
// Cache some values to be able to detect changes
- interface::WalletBalances m_cached_balances;
+ interfaces::WalletBalances m_cached_balances;
EncryptionStatus cachedEncryptionStatus;
int cachedNumBlocks;
@@ -233,11 +233,11 @@ private:
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
- void checkBalanceChanged(const interface::WalletBalances& new_balances);
+ void checkBalanceChanged(const interfaces::WalletBalances& new_balances);
Q_SIGNALS:
// Signal that balance in wallet changed
- void balanceChanged(const interface::WalletBalances& balances);
+ void balanceChanged(const interfaces::WalletBalances& balances);
// Encryption status of wallet changed
void encryptionStatusChanged();
diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp
index 21bdfe3818..d5187d6634 100644
--- a/src/qt/walletmodeltransaction.cpp
+++ b/src/qt/walletmodeltransaction.cpp
@@ -4,7 +4,7 @@
#include <qt/walletmodeltransaction.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <policy/policy.h>
WalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient> &_recipients) :
@@ -18,7 +18,7 @@ QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const
return recipients;
}
-std::unique_ptr<interface::PendingWalletTx>& WalletModelTransaction::getWtx()
+std::unique_ptr<interfaces::PendingWalletTx>& WalletModelTransaction::getWtx()
{
return wtx;
}
diff --git a/src/qt/walletmodeltransaction.h b/src/qt/walletmodeltransaction.h
index 32fd0d2110..9f91326109 100644
--- a/src/qt/walletmodeltransaction.h
+++ b/src/qt/walletmodeltransaction.h
@@ -13,7 +13,7 @@
class SendCoinsRecipient;
-namespace interface {
+namespace interfaces {
class Node;
class PendingWalletTx;
}
@@ -26,7 +26,7 @@ public:
QList<SendCoinsRecipient> getRecipients() const;
- std::unique_ptr<interface::PendingWalletTx>& getWtx();
+ std::unique_ptr<interfaces::PendingWalletTx>& getWtx();
unsigned int getTransactionSize();
void setTransactionFee(const CAmount& newFee);
@@ -38,7 +38,7 @@ public:
private:
QList<SendCoinsRecipient> recipients;
- std::unique_ptr<interface::PendingWalletTx> wtx;
+ std::unique_ptr<interfaces::PendingWalletTx> wtx;
CAmount fee;
};
diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp
index 1505557244..8b9b85c8c9 100644
--- a/src/qt/walletview.cpp
+++ b/src/qt/walletview.cpp
@@ -19,7 +19,7 @@
#include <qt/transactionview.h>
#include <qt/walletmodel.h>
-#include <interface/node.h>
+#include <interfaces/node.h>
#include <ui_interface.h>
#include <QAction>
diff --git a/src/random.cpp b/src/random.cpp
index a845526d8a..b004dcac39 100644
--- a/src/random.cpp
+++ b/src/random.cpp
@@ -15,7 +15,6 @@
#include <utilstrencodings.h> // for GetTime()
#include <stdlib.h>
-#include <limits>
#include <chrono>
#include <thread>
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index 06882c0dfd..75bc983200 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -235,6 +235,7 @@ UniValue prioritisetransaction(const JSONRPCRequest& request)
"2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n"
" DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n"
"3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
+ " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
" The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
" considers the transaction as it would have paid a higher (or lower) fee.\n"
"\nResult:\n"
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 51c337ed2f..f10fd07c63 100644
--- a/src/support/lockedpool.cpp
+++ b/src/support/lockedpool.cpp
@@ -27,7 +27,6 @@
#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 fdf7c44e4c..6f21d498ee 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -81,20 +81,20 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch,
LogPrintf("Previous lock order was:\n");
for (const std::pair<void*, CLockLocation> & i : s2) {
if (i.first == mismatch.first) {
- LogPrintf(" (1)");
+ LogPrintf(" (1)"); /* Continued */
}
if (i.first == mismatch.second) {
- LogPrintf(" (2)");
+ LogPrintf(" (2)"); /* Continued */
}
LogPrintf(" %s\n", i.second.ToString());
}
LogPrintf("Current lock order is:\n");
for (const std::pair<void*, CLockLocation> & i : s1) {
if (i.first == mismatch.first) {
- LogPrintf(" (1)");
+ LogPrintf(" (1)"); /* Continued */
}
if (i.first == mismatch.second) {
- LogPrintf(" (2)");
+ LogPrintf(" (2)"); /* Continued */
}
LogPrintf(" %s\n", i.second.ToString());
}
diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp
index ec068f6d6c..ff20d4b3d7 100644
--- a/src/test/test_bitcoin.cpp
+++ b/src/test/test_bitcoin.cpp
@@ -17,8 +17,6 @@
#include <rpc/register.h>
#include <script/sigcache.h>
-#include <memory>
-
void CConnmanTest::AddNode(CNode& node)
{
LOCK(g_connman->cs_vNodes);
diff --git a/src/test/uint256_tests.cpp b/src/test/uint256_tests.cpp
index ad5478e829..20ed29f59b 100644
--- a/src/test/uint256_tests.cpp
+++ b/src/test/uint256_tests.cpp
@@ -266,4 +266,17 @@ BOOST_AUTO_TEST_CASE( conversion )
BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex());
}
+BOOST_AUTO_TEST_CASE( operator_with_self )
+{
+ arith_uint256 v = UintToArith256(uint256S("02"));
+ v *= v;
+ BOOST_CHECK(v == UintToArith256(uint256S("04")));
+ v /= v;
+ BOOST_CHECK(v == UintToArith256(uint256S("01")));
+ v += v;
+ BOOST_CHECK(v == UintToArith256(uint256S("02")));
+ v -= v;
+ BOOST_CHECK(v == UintToArith256(uint256S("0")));
+}
+
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp
index 4b44bbadac..d41c43a795 100644
--- a/src/test/util_tests.cpp
+++ b/src/test/util_tests.cpp
@@ -62,7 +62,7 @@ BOOST_AUTO_TEST_CASE(util_ParseHex)
result = ParseHex("12 34 56 78");
BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
- // Leading space must be supported (used in CDBEnv::Salvage)
+ // Leading space must be supported (used in BerkeleyEnvironment::Salvage)
result = ParseHex(" 89 34 56 78");
BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
@@ -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/util.cpp b/src/util.cpp
index 46054f5025..f55c9c8c34 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{0};
+ if (int ret = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param)) {
+ 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 7114c0accd..3952461e48 100644
--- a/src/util.h
+++ b/src/util.h
@@ -228,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);
@@ -306,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.
@@ -381,4 +389,13 @@ std::unique_ptr<T> MakeUnique(Args&&... args)
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
+/**
+ * On platforms that support it, tell the kernel the calling thread is
+ * CPU-intensive and non-interactive. See SCHED_BATCH in sched(7) for details.
+ *
+ * @return The return value of sched_setschedule(), or 1 on systems without
+ * sched_setchedule().
+ */
+int ScheduleBatchPriority(void);
+
#endif // BITCOIN_UTIL_H
diff --git a/src/validation.cpp b/src/validation.cpp
index df8729e382..4a6c4066fc 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -507,7 +507,7 @@ void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool f
// Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
// were somehow broken and returning the wrong scriptPubKeys
-static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
+static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool,
unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
AssertLockHeld(cs_main);
@@ -917,8 +917,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// invalid blocks (using TestBlockValidity), however allowing such
// transactions into the mempool can be exploited as a DoS attack.
unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
- if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
- {
+ if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) {
// If we're using promiscuousmempoolflags, we may hit this normally
// Check if current block has some flags that scriptVerifyFlags
// does not before printing an ominous warning
@@ -1794,8 +1793,15 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
// is enforced in ContextualCheckBlockHeader(); we wouldn't want to
// re-enforce that rule here (at least until we make it impossible for
// GetAdjustedTime() to go backward).
- if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
+ if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck)) {
+ if (state.CorruptionPossible()) {
+ // We don't write down blocks to disk if they may have been
+ // corrupted, so this should be impossible unless we're having hardware
+ // problems.
+ return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
+ }
return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
+ }
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
@@ -2231,13 +2237,13 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar
DoWarning(strWarning);
}
}
- LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
+ LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__, /* Continued */
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
FormatISO8601DateTime(pindexNew->GetBlockTime()),
GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
if (!warningMessages.empty())
- LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
+ LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", ")); /* Continued */
LogPrintf("\n");
}
@@ -3903,14 +3909,14 @@ bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview,
int nGoodTransactions = 0;
CValidationState state;
int reportDone = 0;
- LogPrintf("[0%%]...");
+ LogPrintf("[0%%]..."); /* Continued */
for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
{
boost::this_thread::interruption_point();
int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
if (reportDone < percentageDone/10) {
// report every 10% step
- LogPrintf("[%d%%]...", percentageDone);
+ LogPrintf("[%d%%]...", percentageDone); /* Continued */
reportDone = percentageDone/10;
}
uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
diff --git a/src/wallet/crypter.h b/src/wallet/crypter.h
index fdeb4cfee0..4c0c8ff5ec 100644
--- a/src/wallet/crypter.h
+++ b/src/wallet/crypter.h
@@ -67,7 +67,7 @@ public:
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
-namespace crypto_tests
+namespace wallet_crypto_tests
{
class TestCrypter;
}
@@ -75,7 +75,7 @@ namespace crypto_tests
/** Encryption/decryption context with key information */
class CCrypter
{
-friend class crypto_tests::TestCrypter; // for test access to chKey/chIV
+friend class wallet_crypto_tests::TestCrypter; // for test access to chKey/chIV
private:
std::vector<unsigned char, secure_allocator<unsigned char>> vchKey;
std::vector<unsigned char, secure_allocator<unsigned char>> vchIV;
diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp
index 553cae4d02..10a06e4b9a 100644
--- a/src/wallet/db.cpp
+++ b/src/wallet/db.cpp
@@ -8,7 +8,6 @@
#include <addrman.h>
#include <hash.h>
#include <protocol.h>
-#include <util.h>
#include <utilstrencodings.h>
#include <wallet/walletutil.h>
@@ -30,14 +29,14 @@ namespace {
//! (https://docs.oracle.com/cd/E17275_01/html/programmer_reference/program_copy.html),
//! so bitcoin should never create different databases with the same fileid, but
//! this error can be triggered if users manually copy database files.
-void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db)
+void CheckUniqueFileid(const BerkeleyEnvironment& env, const std::string& filename, Db& db)
{
if (env.IsMock()) return;
u_int8_t fileid[DB_FILE_ID_LEN];
int ret = db.get_mpf()->get_fileid(fileid);
if (ret != 0) {
- throw std::runtime_error(strprintf("CDB: Can't open database %s (get_fileid failed with %d)", filename, ret));
+ throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (get_fileid failed with %d)", filename, ret));
}
for (const auto& item : env.mapDb) {
@@ -46,7 +45,7 @@ void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db)
memcmp(fileid, item_fileid, sizeof(fileid)) == 0) {
const char* item_filename = nullptr;
item.second->get_dbname(&item_filename, nullptr);
- throw std::runtime_error(strprintf("CDB: Can't open database %s (duplicates fileid %s from %s)", filename,
+ throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (duplicates fileid %s from %s)", filename,
HexStr(std::begin(item_fileid), std::end(item_fileid)),
item_filename ? item_filename : "(unknown database)"));
}
@@ -54,10 +53,10 @@ void CheckUniqueFileid(const CDBEnv& env, const std::string& filename, Db& db)
}
CCriticalSection cs_db;
-std::map<std::string, CDBEnv> g_dbenvs; //!< Map from directory name to open db environment.
+std::map<std::string, BerkeleyEnvironment> g_dbenvs; //!< Map from directory name to open db environment.
} // namespace
-CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename)
+BerkeleyEnvironment* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename)
{
fs::path env_directory;
if (fs::is_regular_file(wallet_path)) {
@@ -73,7 +72,7 @@ CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename
database_filename = "wallet.dat";
}
LOCK(cs_db);
- // Note: An ununsed temporary CDBEnv object may be created inside the
+ // Note: An ununsed temporary BerkeleyEnvironment object may be created inside the
// emplace function if the key already exists. This is a little inefficient,
// but not a big concern since the map will be changed in the future to hold
// pointers instead of objects, anyway.
@@ -81,10 +80,10 @@ CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename
}
//
-// CDB
+// BerkeleyBatch
//
-void CDBEnv::Close()
+void BerkeleyEnvironment::Close()
{
if (!fDbEnvInit)
return;
@@ -103,29 +102,29 @@ void CDBEnv::Close()
int ret = dbenv->close(0);
if (ret != 0)
- LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
+ LogPrintf("BerkeleyEnvironment::EnvShutdown: Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb)
DbEnv((u_int32_t)0).remove(strPath.c_str(), 0);
}
-void CDBEnv::Reset()
+void BerkeleyEnvironment::Reset()
{
dbenv.reset(new DbEnv(DB_CXX_NO_EXCEPTIONS));
fDbEnvInit = false;
fMockDb = false;
}
-CDBEnv::CDBEnv(const fs::path& dir_path) : strPath(dir_path.string())
+BerkeleyEnvironment::BerkeleyEnvironment(const fs::path& dir_path) : strPath(dir_path.string())
{
Reset();
}
-CDBEnv::~CDBEnv()
+BerkeleyEnvironment::~BerkeleyEnvironment()
{
Close();
}
-bool CDBEnv::Open(bool retry)
+bool BerkeleyEnvironment::Open(bool retry)
{
if (fDbEnvInit)
return true;
@@ -142,7 +141,7 @@ bool CDBEnv::Open(bool retry)
fs::path pathLogDir = pathIn / "database";
TryCreateDirectories(pathLogDir);
fs::path pathErrorFile = pathIn / "db.log";
- LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
+ LogPrintf("BerkeleyEnvironment::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB))
@@ -170,7 +169,7 @@ bool CDBEnv::Open(bool retry)
S_IRUSR | S_IWUSR);
if (ret != 0) {
dbenv->close(0);
- LogPrintf("CDBEnv::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
+ LogPrintf("BerkeleyEnvironment::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
if (retry) {
// try moving the database env out of the way
fs::path pathDatabaseBak = pathIn / strprintf("database.%d.bak", GetTime());
@@ -195,14 +194,14 @@ bool CDBEnv::Open(bool retry)
return true;
}
-void CDBEnv::MakeMock()
+void BerkeleyEnvironment::MakeMock()
{
if (fDbEnvInit)
- throw std::runtime_error("CDBEnv::MakeMock: Already initialized");
+ throw std::runtime_error("BerkeleyEnvironment::MakeMock: Already initialized");
boost::this_thread::interruption_point();
- LogPrint(BCLog::DB, "CDBEnv::MakeMock\n");
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::MakeMock\n");
dbenv->set_cachesize(1, 0, 1);
dbenv->set_lg_bsize(10485760 * 4);
@@ -221,13 +220,13 @@ void CDBEnv::MakeMock()
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
- throw std::runtime_error(strprintf("CDBEnv::MakeMock: Error %d opening database environment.", ret));
+ throw std::runtime_error(strprintf("BerkeleyEnvironment::MakeMock: Error %d opening database environment.", ret));
fDbEnvInit = true;
fMockDb = true;
}
-CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename)
+BerkeleyEnvironment::VerifyResult BerkeleyEnvironment::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
@@ -244,10 +243,10 @@ CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type
return (fRecovered ? VerifyResult::RECOVER_OK : VerifyResult::RECOVER_FAIL);
}
-bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename)
+bool BerkeleyBatch::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename)
{
std::string filename;
- CDBEnv* env = GetWalletEnv(file_path, filename);
+ BerkeleyEnvironment* env = GetWalletEnv(file_path, filename);
// Recovery procedure:
// move wallet file to walletfilename.timestamp.bak
@@ -269,7 +268,7 @@ bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recove
return false;
}
- std::vector<CDBEnv::KeyValPair> salvagedData;
+ std::vector<BerkeleyEnvironment::KeyValPair> salvagedData;
bool fSuccess = env->Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
@@ -292,7 +291,7 @@ bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recove
}
DbTxn* ptxn = env->TxnBegin();
- for (CDBEnv::KeyValPair& row : salvagedData)
+ for (BerkeleyEnvironment::KeyValPair& row : salvagedData)
{
if (recoverKVcallback)
{
@@ -313,10 +312,10 @@ bool CDB::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recove
return fSuccess;
}
-bool CDB::VerifyEnvironment(const fs::path& file_path, std::string& errorStr)
+bool BerkeleyBatch::VerifyEnvironment(const fs::path& file_path, std::string& errorStr)
{
std::string walletFile;
- CDBEnv* env = GetWalletEnv(file_path, walletFile);
+ BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile);
fs::path walletDir = env->Directory();
LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
@@ -337,17 +336,17 @@ bool CDB::VerifyEnvironment(const fs::path& file_path, std::string& errorStr)
return true;
}
-bool CDB::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, CDBEnv::recoverFunc_type recoverFunc)
+bool BerkeleyBatch::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, BerkeleyEnvironment::recoverFunc_type recoverFunc)
{
std::string walletFile;
- CDBEnv* env = GetWalletEnv(file_path, walletFile);
+ BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile);
fs::path walletDir = env->Directory();
if (fs::exists(walletDir / walletFile))
{
std::string backup_filename;
- CDBEnv::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename);
- if (r == CDBEnv::VerifyResult::RECOVER_OK)
+ BerkeleyEnvironment::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename);
+ if (r == BerkeleyEnvironment::VerifyResult::RECOVER_OK)
{
warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!"
" Original %s saved as %s in %s; if"
@@ -355,7 +354,7 @@ bool CDB::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr,
" restore from a backup."),
walletFile, backup_filename, walletDir);
}
- if (r == CDBEnv::VerifyResult::RECOVER_FAIL)
+ if (r == BerkeleyEnvironment::VerifyResult::RECOVER_FAIL)
{
errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile);
return false;
@@ -370,7 +369,7 @@ static const char *HEADER_END = "HEADER=END";
/* End of key/value data */
static const char *DATA_END = "DATA=END";
-bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<CDBEnv::KeyValPair>& vResult)
+bool BerkeleyEnvironment::Salvage(const std::string& strFile, bool fAggressive, std::vector<BerkeleyEnvironment::KeyValPair>& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
@@ -384,14 +383,14 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
Db db(dbenv.get(), 0);
int result = db.verify(strFile.c_str(), nullptr, &strDump, flags);
if (result == DB_VERIFY_BAD) {
- LogPrintf("CDBEnv::Salvage: Database salvage found errors, all data may not be recoverable.\n");
+ LogPrintf("BerkeleyEnvironment::Salvage: Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) {
- LogPrintf("CDBEnv::Salvage: Rerun with aggressive mode to ignore errors and continue.\n");
+ LogPrintf("BerkeleyEnvironment::Salvage: Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
- LogPrintf("CDBEnv::Salvage: Database salvage failed with result %d.\n", result);
+ LogPrintf("BerkeleyEnvironment::Salvage: Database salvage failed with result %d.\n", result);
return false;
}
@@ -415,7 +414,7 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
break;
getline(strDump, valueHex);
if (valueHex == DATA_END) {
- LogPrintf("CDBEnv::Salvage: WARNING: Number of keys in data does not match number of values.\n");
+ LogPrintf("BerkeleyEnvironment::Salvage: WARNING: Number of keys in data does not match number of values.\n");
break;
}
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
@@ -423,7 +422,7 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
}
if (keyHex != DATA_END) {
- LogPrintf("CDBEnv::Salvage: WARNING: Unexpected end of file while reading salvage output.\n");
+ LogPrintf("BerkeleyEnvironment::Salvage: WARNING: Unexpected end of file while reading salvage output.\n");
return false;
}
@@ -431,7 +430,7 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
}
-void CDBEnv::CheckpointLSN(const std::string& strFile)
+void BerkeleyEnvironment::CheckpointLSN(const std::string& strFile)
{
dbenv->txn_checkpoint(0, 0, 0);
if (fMockDb)
@@ -440,15 +439,15 @@ void CDBEnv::CheckpointLSN(const std::string& strFile)
}
-CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
+BerkeleyBatch::BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
{
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
fFlushOnClose = fFlushOnCloseIn;
- env = dbw.env;
- if (dbw.IsDummy()) {
+ env = database.env;
+ if (database.IsDummy()) {
return;
}
- const std::string &strFilename = dbw.strFile;
+ const std::string &strFilename = database.strFile;
bool fCreate = strchr(pszMode, 'c') != nullptr;
unsigned int nFlags = DB_THREAD;
@@ -458,7 +457,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
{
LOCK(cs_db);
if (!env->Open(false /* retry */))
- throw std::runtime_error("CDB: Failed to open database environment.");
+ throw std::runtime_error("BerkeleyBatch: Failed to open database environment.");
pdb = env->mapDb[strFilename];
if (pdb == nullptr) {
@@ -470,7 +469,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
DbMpoolFile* mpf = pdb_temp->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0) {
- throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFilename));
+ throw std::runtime_error(strprintf("BerkeleyBatch: Failed to configure for no temp file backing for database %s", strFilename));
}
}
@@ -482,7 +481,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
0);
if (ret != 0) {
- throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename));
+ throw std::runtime_error(strprintf("BerkeleyBatch: Error %d, can't open database %s", ret, strFilename));
}
// Call CheckUniqueFileid on the containing BDB environment to
@@ -519,7 +518,7 @@ CDB::CDB(CWalletDBWrapper& dbw, const char* pszMode, bool fFlushOnCloseIn) : pdb
}
}
-void CDB::Flush()
+void BerkeleyBatch::Flush()
{
if (activeTxn)
return;
@@ -532,12 +531,12 @@ void CDB::Flush()
env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
}
-void CWalletDBWrapper::IncrementUpdateCounter()
+void BerkeleyDatabase::IncrementUpdateCounter()
{
++nUpdateCounter;
}
-void CDB::Close()
+void BerkeleyBatch::Close()
{
if (!pdb)
return;
@@ -555,7 +554,7 @@ void CDB::Close()
}
}
-void CDBEnv::CloseDb(const std::string& strFile)
+void BerkeleyEnvironment::CloseDb(const std::string& strFile)
{
{
LOCK(cs_db);
@@ -569,13 +568,13 @@ void CDBEnv::CloseDb(const std::string& strFile)
}
}
-bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
+bool BerkeleyBatch::Rewrite(BerkeleyDatabase& database, const char* pszSkip)
{
- if (dbw.IsDummy()) {
+ if (database.IsDummy()) {
return true;
}
- CDBEnv *env = dbw.env;
- const std::string& strFile = dbw.strFile;
+ BerkeleyEnvironment *env = database.env;
+ const std::string& strFile = database.strFile;
while (true) {
{
LOCK(cs_db);
@@ -586,10 +585,10 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
env->mapFileUseCount.erase(strFile);
bool fSuccess = true;
- LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile);
+ LogPrintf("BerkeleyBatch::Rewrite: Rewriting %s...\n", strFile);
std::string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
- CDB db(dbw, "r");
+ BerkeleyBatch db(database, "r");
std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
@@ -599,7 +598,7 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
DB_CREATE, // Flags
0);
if (ret > 0) {
- LogPrintf("CDB::Rewrite: Can't create database file %s\n", strFileRes);
+ LogPrintf("BerkeleyBatch::Rewrite: Can't create database file %s\n", strFileRes);
fSuccess = false;
}
@@ -649,7 +648,7 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
fSuccess = false;
}
if (!fSuccess)
- LogPrintf("CDB::Rewrite: Failed to rewrite database file %s\n", strFileRes);
+ LogPrintf("BerkeleyBatch::Rewrite: Failed to rewrite database file %s\n", strFileRes);
return fSuccess;
}
}
@@ -658,11 +657,11 @@ bool CDB::Rewrite(CWalletDBWrapper& dbw, const char* pszSkip)
}
-void CDBEnv::Flush(bool fShutdown)
+void BerkeleyEnvironment::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file on all files that are not in use
- LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
if (!fDbEnvInit)
return;
{
@@ -671,21 +670,21 @@ void CDBEnv::Flush(bool fShutdown)
while (mi != mapFileUseCount.end()) {
std::string strFile = (*mi).first;
int nRefCount = (*mi).second;
- LogPrint(BCLog::DB, "CDBEnv::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount);
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) {
// Move log data to the dat file
CloseDb(strFile);
- LogPrint(BCLog::DB, "CDBEnv::Flush: %s checkpoint\n", strFile);
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s checkpoint\n", strFile);
dbenv->txn_checkpoint(0, 0, 0);
- LogPrint(BCLog::DB, "CDBEnv::Flush: %s detach\n", strFile);
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s detach\n", strFile);
if (!fMockDb)
dbenv->lsn_reset(strFile.c_str(), 0);
- LogPrint(BCLog::DB, "CDBEnv::Flush: %s closed\n", strFile);
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s closed\n", strFile);
mapFileUseCount.erase(mi++);
} else
mi++;
}
- LogPrint(BCLog::DB, "CDBEnv::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
+ LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
if (fShutdown) {
char** listp;
if (mapFileUseCount.empty()) {
@@ -698,14 +697,14 @@ void CDBEnv::Flush(bool fShutdown)
}
}
-bool CDB::PeriodicFlush(CWalletDBWrapper& dbw)
+bool BerkeleyBatch::PeriodicFlush(BerkeleyDatabase& database)
{
- if (dbw.IsDummy()) {
+ if (database.IsDummy()) {
return true;
}
bool ret = false;
- CDBEnv *env = dbw.env;
- const std::string& strFile = dbw.strFile;
+ BerkeleyEnvironment *env = database.env;
+ const std::string& strFile = database.strFile;
TRY_LOCK(cs_db, lockDb);
if (lockDb)
{
@@ -741,12 +740,12 @@ bool CDB::PeriodicFlush(CWalletDBWrapper& dbw)
return ret;
}
-bool CWalletDBWrapper::Rewrite(const char* pszSkip)
+bool BerkeleyDatabase::Rewrite(const char* pszSkip)
{
- return CDB::Rewrite(*this, pszSkip);
+ return BerkeleyBatch::Rewrite(*this, pszSkip);
}
-bool CWalletDBWrapper::Backup(const std::string& strDest)
+bool BerkeleyDatabase::Backup(const std::string& strDest)
{
if (IsDummy()) {
return false;
@@ -787,7 +786,7 @@ bool CWalletDBWrapper::Backup(const std::string& strDest)
}
}
-void CWalletDBWrapper::Flush(bool shutdown)
+void BerkeleyDatabase::Flush(bool shutdown)
{
if (!IsDummy()) {
env->Flush(shutdown);
diff --git a/src/wallet/db.h b/src/wallet/db.h
index 49a9f3f082..5e61280f7a 100644
--- a/src/wallet/db.h
+++ b/src/wallet/db.h
@@ -25,7 +25,7 @@
static const unsigned int DEFAULT_WALLET_DBLOGSIZE = 100;
static const bool DEFAULT_WALLET_PRIVDB = true;
-class CDBEnv
+class BerkeleyEnvironment
{
private:
bool fDbEnvInit;
@@ -39,8 +39,8 @@ public:
std::map<std::string, int> mapFileUseCount;
std::map<std::string, Db*> mapDb;
- CDBEnv(const fs::path& env_directory);
- ~CDBEnv();
+ BerkeleyEnvironment(const fs::path& env_directory);
+ ~BerkeleyEnvironment();
void Reset();
void MakeMock();
@@ -86,23 +86,23 @@ public:
}
};
-/** Get CDBEnv and database filename given a wallet path. */
-CDBEnv* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename);
+/** Get BerkeleyEnvironment and database filename given a wallet path. */
+BerkeleyEnvironment* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename);
/** An instance of this class represents one database.
* For BerkeleyDB this is just a (env, strFile) tuple.
**/
-class CWalletDBWrapper
+class BerkeleyDatabase
{
- friend class CDB;
+ friend class BerkeleyBatch;
public:
/** Create dummy DB handle */
- CWalletDBWrapper() : nUpdateCounter(0), nLastSeen(0), nLastFlushed(0), nLastWalletUpdate(0), env(nullptr)
+ BerkeleyDatabase() : nUpdateCounter(0), nLastSeen(0), nLastFlushed(0), nLastWalletUpdate(0), env(nullptr)
{
}
/** Create DB handle to real database */
- CWalletDBWrapper(const fs::path& wallet_path, bool mock = false) :
+ BerkeleyDatabase(const fs::path& wallet_path, bool mock = false) :
nUpdateCounter(0), nLastSeen(0), nLastFlushed(0), nLastWalletUpdate(0)
{
env = GetWalletEnv(wallet_path, strFile);
@@ -114,21 +114,21 @@ public:
}
/** Return object for accessing database at specified path. */
- static std::unique_ptr<CWalletDBWrapper> Create(const fs::path& path)
+ static std::unique_ptr<BerkeleyDatabase> Create(const fs::path& path)
{
- return MakeUnique<CWalletDBWrapper>(path);
+ return MakeUnique<BerkeleyDatabase>(path);
}
/** Return object for accessing dummy database with no read/write capabilities. */
- static std::unique_ptr<CWalletDBWrapper> CreateDummy()
+ static std::unique_ptr<BerkeleyDatabase> CreateDummy()
{
- return MakeUnique<CWalletDBWrapper>();
+ return MakeUnique<BerkeleyDatabase>();
}
/** Return object for accessing temporary in-memory database. */
- static std::unique_ptr<CWalletDBWrapper> CreateMock()
+ static std::unique_ptr<BerkeleyDatabase> CreateMock()
{
- return MakeUnique<CWalletDBWrapper>("", true /* mock */);
+ return MakeUnique<BerkeleyDatabase>("", true /* mock */);
}
/** Rewrite the entire database on disk, with the exception of key pszSkip if non-zero
@@ -152,7 +152,7 @@ public:
private:
/** BerkeleyDB specific */
- CDBEnv *env;
+ BerkeleyEnvironment *env;
std::string strFile;
/** Return whether this database handle is a dummy for testing.
@@ -164,7 +164,7 @@ private:
/** RAII class that provides access to a Berkeley database */
-class CDB
+class BerkeleyBatch
{
protected:
Db* pdb;
@@ -172,14 +172,14 @@ protected:
DbTxn* activeTxn;
bool fReadOnly;
bool fFlushOnClose;
- CDBEnv *env;
+ BerkeleyEnvironment *env;
public:
- explicit CDB(CWalletDBWrapper& dbw, const char* pszMode = "r+", bool fFlushOnCloseIn=true);
- ~CDB() { Close(); }
+ explicit BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode = "r+", bool fFlushOnCloseIn=true);
+ ~BerkeleyBatch() { Close(); }
- CDB(const CDB&) = delete;
- CDB& operator=(const CDB&) = delete;
+ BerkeleyBatch(const BerkeleyBatch&) = delete;
+ BerkeleyBatch& operator=(const BerkeleyBatch&) = delete;
void Flush();
void Close();
@@ -187,11 +187,11 @@ public:
/* flush the wallet passively (TRY_LOCK)
ideal to be called periodically */
- static bool PeriodicFlush(CWalletDBWrapper& dbw);
+ static bool PeriodicFlush(BerkeleyDatabase& database);
/* verifies the database environment */
static bool VerifyEnvironment(const fs::path& file_path, std::string& errorStr);
/* verifies the database file */
- static bool VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, CDBEnv::recoverFunc_type recoverFunc);
+ static bool VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, BerkeleyEnvironment::recoverFunc_type recoverFunc);
public:
template <typename K, typename T>
@@ -387,7 +387,7 @@ public:
return Write(std::string("version"), nVersion);
}
- bool static Rewrite(CWalletDBWrapper& dbw, const char* pszSkip = nullptr);
+ bool static Rewrite(BerkeleyDatabase& database, const char* pszSkip = nullptr);
};
#endif // BITCOIN_WALLET_DB_H
diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp
index 3d7bb674f0..b6f4a0e1e1 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:"));
@@ -241,21 +277,21 @@ bool WalletInit::Verify()
}
std::string strError;
- if (!CWalletDB::VerifyEnvironment(wallet_path, strError)) {
+ if (!WalletBatch::VerifyEnvironment(wallet_path, strError)) {
return InitError(strError);
}
if (gArgs.GetBoolArg("-salvagewallet", false)) {
// Recover readable keypairs:
- CWallet dummyWallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet dummyWallet("dummy", WalletDatabase::CreateDummy());
std::string backup_filename;
- if (!CWalletDB::Recover(wallet_path, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
+ if (!WalletBatch::Recover(wallet_path, (void *)&dummyWallet, WalletBatch::RecoverKeysOnlyFilter, backup_filename)) {
return false;
}
}
std::string strWarning;
- bool dbV = CWalletDB::VerifyDatabaseFile(wallet_path, strWarning, strError);
+ bool dbV = WalletBatch::VerifyDatabaseFile(wallet_path, strWarning, strError);
if (!strWarning.empty()) {
InitWarning(strWarning);
}
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/coinselector_tests.cpp b/src/wallet/test/coinselector_tests.cpp
index 184a8a3f1f..ac47d4448a 100644
--- a/src/wallet/test/coinselector_tests.cpp
+++ b/src/wallet/test/coinselector_tests.cpp
@@ -28,7 +28,7 @@ std::vector<std::unique_ptr<CWalletTx>> wtxn;
typedef std::set<CInputCoin> CoinSet;
static std::vector<COutput> vCoins;
-static CWallet testWallet("dummy", CWalletDBWrapper::CreateDummy());
+static CWallet testWallet("dummy", WalletDatabase::CreateDummy());
static CAmount balance = 0;
CoinEligibilityFilter filter_standard(1, 6, 0);
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.cpp b/src/wallet/test/wallet_test_fixture.cpp
index 5c550742c8..6129e337ce 100644
--- a/src/wallet/test/wallet_test_fixture.cpp
+++ b/src/wallet/test/wallet_test_fixture.cpp
@@ -6,10 +6,9 @@
#include <rpc/server.h>
#include <wallet/db.h>
-#include <wallet/wallet.h>
WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
- TestingSetup(chainName), m_wallet("mock", CWalletDBWrapper::CreateMock())
+ TestingSetup(chainName), m_wallet("mock", WalletDatabase::CreateMock())
{
bool fFirstRun;
m_wallet.LoadWallet(fFirstRun);
diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp
index e93e0f1966..727c6caf96 100644
--- a/src/wallet/test/wallet_tests.cpp
+++ b/src/wallet/test/wallet_tests.cpp
@@ -46,7 +46,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
// Verify ScanForWalletTransactions picks up transactions in both the old
// and new block files.
{
- CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet wallet("dummy", WalletDatabase::CreateDummy());
AddKey(wallet, coinbaseKey);
WalletRescanReserver reserver(&wallet);
reserver.reserve();
@@ -61,7 +61,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
// Verify ScanForWalletTransactions only picks transactions in the new block
// file.
{
- CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet wallet("dummy", WalletDatabase::CreateDummy());
AddKey(wallet, coinbaseKey);
WalletRescanReserver reserver(&wallet);
reserver.reserve();
@@ -73,7 +73,7 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
// before the missing block, and success for a key whose creation time is
// after.
{
- CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet wallet("dummy", WalletDatabase::CreateDummy());
vpwallets.insert(vpwallets.begin(), &wallet);
UniValue keys;
keys.setArray();
@@ -132,7 +132,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
// Import key into wallet and call dumpwallet to create backup file.
{
- CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet wallet("dummy", WalletDatabase::CreateDummy());
LOCK(wallet.cs_wallet);
wallet.mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
@@ -147,7 +147,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
// Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
// were scanned, and no prior blocks were scanned.
{
- CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet wallet("dummy", WalletDatabase::CreateDummy());
JSONRPCRequest request;
request.params.setArray();
@@ -177,7 +177,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
// debit functions.
BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
{
- CWallet wallet("dummy", CWalletDBWrapper::CreateDummy());
+ CWallet wallet("dummy", WalletDatabase::CreateDummy());
CWalletTx wtx(&wallet, MakeTransactionRef(coinbaseTxns.back()));
LOCK2(cs_main, wallet.cs_wallet);
wtx.hashBlock = chainActive.Tip()->GetBlockHash();
@@ -270,7 +270,7 @@ public:
ListCoinsTestingSetup()
{
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
- wallet = MakeUnique<CWallet>("mock", CWalletDBWrapper::CreateMock());
+ wallet = MakeUnique<CWallet>("mock", WalletDatabase::CreateMock());
bool firstRun;
wallet->LoadWallet(firstRun);
AddKey(*wallet, coinbaseKey);
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index dbc1760c80..4308b6d0e8 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -8,11 +8,9 @@
#include <checkpoints.h>
#include <chain.h>
#include <wallet/coincontrol.h>
-#include <wallet/coinselection.h>
#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>
@@ -27,7 +25,6 @@
#include <scheduler.h>
#include <timedata.h>
#include <txmempool.h>
-#include <util.h>
#include <utilmoneystr.h>
#include <wallet/fees.h>
@@ -132,7 +129,7 @@ const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
return &(it->second);
}
-CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
+CPubKey CWallet::GenerateNewKey(WalletBatch &batch, bool internal)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
@@ -145,7 +142,7 @@ CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
// use HD key derivation if HD was enabled during wallet creation
if (IsHDEnabled()) {
- DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
+ DeriveNewChildKey(batch, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
} else {
secret.MakeNewKey(fCompressed);
}
@@ -161,13 +158,13 @@ CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
mapKeyMetadata[pubkey.GetID()] = metadata;
UpdateTimeFirstKey(nCreationTime);
- if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
+ if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
throw std::runtime_error(std::string(__func__) + ": AddKey failed");
}
return pubkey;
}
-void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
+void CWallet::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, bool internal)
{
// for now we use a fixed keypath scheme of m/0'/0'/k
CKey key; //master key seed (256bit)
@@ -209,26 +206,26 @@ void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKe
secret = childKey.key;
metadata.hdMasterKeyID = hdChain.masterKeyID;
// update the chain model in the database
- if (!walletdb.WriteHDChain(hdChain))
+ if (!batch.WriteHDChain(hdChain))
throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
}
-bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
+bool CWallet::AddKeyPubKeyWithDB(WalletBatch &batch, const CKey& secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
// CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
// which is overridden below. To avoid flushes, the database handle is
// tunneled through to it.
- bool needsDB = !pwalletdbEncryption;
+ bool needsDB = !encrypted_batch;
if (needsDB) {
- pwalletdbEncryption = &walletdb;
+ encrypted_batch = &batch;
}
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
- if (needsDB) pwalletdbEncryption = nullptr;
+ if (needsDB) encrypted_batch = nullptr;
return false;
}
- if (needsDB) pwalletdbEncryption = nullptr;
+ if (needsDB) encrypted_batch = nullptr;
// check if we need to remove from watch-only
CScript script;
@@ -242,7 +239,7 @@ bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const
}
if (!IsCrypted()) {
- return walletdb.WriteKey(pubkey,
+ return batch.WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
@@ -251,8 +248,8 @@ bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
- CWalletDB walletdb(*dbw);
- return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
+ WalletBatch batch(*database);
+ return CWallet::AddKeyPubKeyWithDB(batch, secret, pubkey);
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
@@ -262,12 +259,12 @@ bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
return false;
{
LOCK(cs_wallet);
- if (pwalletdbEncryption)
- return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
+ if (encrypted_batch)
+ return encrypted_batch->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
- return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
+ return WalletBatch(*database).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
@@ -314,7 +311,7 @@ bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
- return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
+ return WalletBatch(*database).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
@@ -340,7 +337,7 @@ bool CWallet::AddWatchOnly(const CScript& dest)
const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
UpdateTimeFirstKey(meta.nCreateTime);
NotifyWatchonlyChanged(true);
- return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
+ return WalletBatch(*database).WriteWatchOnly(dest, meta);
}
bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
@@ -356,7 +353,7 @@ bool CWallet::RemoveWatchOnly(const CScript &dest)
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
- if (!CWalletDB(*dbw).EraseWatchOnly(dest))
+ if (!WalletBatch(*database).EraseWatchOnly(dest))
return false;
return true;
@@ -422,7 +419,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase,
return false;
if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
- CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
+ WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
@@ -435,11 +432,11 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase,
void CWallet::SetBestChain(const CBlockLocator& loc)
{
- CWalletDB walletdb(*dbw);
- walletdb.WriteBestBlock(loc);
+ WalletBatch batch(*database);
+ batch.WriteBestBlock(loc);
}
-bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
+bool CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
@@ -455,11 +452,11 @@ bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn,
nWalletMaxVersion = nVersion;
{
- CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
+ WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database);
if (nWalletVersion > 40000)
- pwalletdb->WriteMinVersion(nWalletVersion);
- if (!pwalletdbIn)
- delete pwalletdb;
+ batch->WriteMinVersion(nWalletVersion);
+ if (!batch_in)
+ delete batch;
}
return true;
@@ -509,7 +506,7 @@ bool CWallet::HasWalletSpend(const uint256& txid) const
void CWallet::Flush(bool shutdown)
{
- dbw->Flush(shutdown);
+ database->Flush(shutdown);
}
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
@@ -632,36 +629,36 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
- assert(!pwalletdbEncryption);
- pwalletdbEncryption = new CWalletDB(*dbw);
- if (!pwalletdbEncryption->TxnBegin()) {
- delete pwalletdbEncryption;
- pwalletdbEncryption = nullptr;
+ assert(!encrypted_batch);
+ encrypted_batch = new WalletBatch(*database);
+ if (!encrypted_batch->TxnBegin()) {
+ delete encrypted_batch;
+ encrypted_batch = nullptr;
return false;
}
- pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
+ encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
if (!EncryptKeys(_vMasterKey))
{
- pwalletdbEncryption->TxnAbort();
- delete pwalletdbEncryption;
+ encrypted_batch->TxnAbort();
+ delete encrypted_batch;
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
- SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
+ SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true);
- if (!pwalletdbEncryption->TxnCommit()) {
- delete pwalletdbEncryption;
+ if (!encrypted_batch->TxnCommit()) {
+ delete encrypted_batch;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
- delete pwalletdbEncryption;
- pwalletdbEncryption = nullptr;
+ delete encrypted_batch;
+ encrypted_batch = nullptr;
Lock();
Unlock(strWalletPassphrase);
@@ -678,7 +675,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
- dbw->Rewrite();
+ database->Rewrite();
}
NotifyStatusChanged(this);
@@ -689,7 +686,7 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
DBErrors CWallet::ReorderTransactions()
{
LOCK(cs_wallet);
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
@@ -705,7 +702,7 @@ DBErrors CWallet::ReorderTransactions()
txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
}
std::list<CAccountingEntry> acentries;
- walletdb.ListAccountCreditDebit("", acentries);
+ batch.ListAccountCreditDebit("", acentries);
for (CAccountingEntry& entry : acentries)
{
txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
@@ -726,11 +723,11 @@ DBErrors CWallet::ReorderTransactions()
if (pwtx)
{
- if (!walletdb.WriteTx(*pwtx))
+ if (!batch.WriteTx(*pwtx))
return DBErrors::LOAD_FAIL;
}
else
- if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
+ if (!batch.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DBErrors::LOAD_FAIL;
}
else
@@ -750,60 +747,60 @@ DBErrors CWallet::ReorderTransactions()
// Since we're changing the order, write it back
if (pwtx)
{
- if (!walletdb.WriteTx(*pwtx))
+ if (!batch.WriteTx(*pwtx))
return DBErrors::LOAD_FAIL;
}
else
- if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
+ if (!batch.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DBErrors::LOAD_FAIL;
}
}
- walletdb.WriteOrderPosNext(nOrderPosNext);
+ batch.WriteOrderPosNext(nOrderPosNext);
return DBErrors::LOAD_OK;
}
-int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
+int64_t CWallet::IncOrderPosNext(WalletBatch *batch)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
- if (pwalletdb) {
- pwalletdb->WriteOrderPosNext(nOrderPosNext);
+ if (batch) {
+ batch->WriteOrderPosNext(nOrderPosNext);
} else {
- CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
+ WalletBatch(*database).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
{
- CWalletDB walletdb(*dbw);
- if (!walletdb.TxnBegin())
+ WalletBatch batch(*database);
+ if (!batch.TxnBegin())
return false;
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
- debit.nOrderPos = IncOrderPosNext(&walletdb);
+ debit.nOrderPos = IncOrderPosNext(&batch);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
- AddAccountingEntry(debit, &walletdb);
+ AddAccountingEntry(debit, &batch);
// Credit
CAccountingEntry credit;
- credit.nOrderPos = IncOrderPosNext(&walletdb);
+ credit.nOrderPos = IncOrderPosNext(&batch);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
- AddAccountingEntry(credit, &walletdb);
+ AddAccountingEntry(credit, &batch);
- if (!walletdb.TxnCommit())
+ if (!batch.TxnCommit())
return false;
return true;
@@ -811,10 +808,10 @@ bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmoun
bool CWallet::GetLabelDestination(CTxDestination &dest, const std::string& label, bool bForceNew)
{
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
CAccount account;
- walletdb.ReadAccount(label, account);
+ batch.ReadAccount(label, account);
if (!bForceNew) {
if (!account.vchPubKey.IsValid())
@@ -841,7 +838,7 @@ bool CWallet::GetLabelDestination(CTxDestination &dest, const std::string& label
LearnRelatedScripts(account.vchPubKey, m_default_address_type);
dest = GetDestinationForKey(account.vchPubKey, m_default_address_type);
SetAddressBook(dest, label, "receive");
- walletdb.WriteAccount(label, account);
+ batch.WriteAccount(label, account);
} else {
dest = GetDestinationForKey(account.vchPubKey, m_default_address_type);
}
@@ -874,11 +871,11 @@ bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
wtx.mapValue["replaced_by_txid"] = newHash.ToString();
- CWalletDB walletdb(*dbw, "r+");
+ WalletBatch batch(*database, "r+");
bool success = true;
- if (!walletdb.WriteTx(wtx)) {
- LogPrintf("%s: Updating walletdb tx %s failed\n", __func__, wtx.GetHash().ToString());
+ if (!batch.WriteTx(wtx)) {
+ LogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
success = false;
}
@@ -891,7 +888,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{
LOCK(cs_wallet);
- CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
+ WalletBatch batch(*database, "r+", fFlushOnClose);
uint256 hash = wtxIn.GetHash();
@@ -903,7 +900,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
- wtx.nOrderPos = IncOrderPosNext(&walletdb);
+ wtx.nOrderPos = IncOrderPosNext(&batch);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
@@ -950,7 +947,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
// Write to disk
if (fInsertedNew || fUpdated)
- if (!walletdb.WriteTx(wtx))
+ if (!batch.WriteTx(wtx))
return false;
// Break debit/credit balance caches:
@@ -1075,7 +1072,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
- CWalletDB walletdb(*dbw, "r+");
+ WalletBatch batch(*database, "r+");
std::set<uint256> todo;
std::set<uint256> done;
@@ -1107,7 +1104,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
wtx.nIndex = -1;
wtx.setAbandoned();
wtx.MarkDirty();
- walletdb.WriteTx(wtx);
+ batch.WriteTx(wtx);
NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
@@ -1149,7 +1146,7 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
return;
// Do not flush the wallet here for performance reasons
- CWalletDB walletdb(*dbw, "r+", false);
+ WalletBatch batch(*database, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
@@ -1170,7 +1167,7 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
wtx.nIndex = -1;
wtx.hashBlock = hashBlock;
wtx.MarkDirty();
- walletdb.WriteTx(wtx);
+ batch.WriteTx(wtx);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
@@ -1474,7 +1471,7 @@ bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
{
LOCK(cs_wallet);
- if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
+ if (!memonly && !WalletBatch(*database).WriteHDChain(chain))
throw std::runtime_error(std::string(__func__) + ": writing chain failed");
hdChain = chain;
@@ -2232,7 +2229,7 @@ CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, cons
}
if (account) {
- balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
+ balance += WalletBatch(*database).GetAccountCreditDebit(*account);
}
return balance;
@@ -3076,7 +3073,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();
@@ -3116,20 +3113,20 @@ bool CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::ve
}
void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
- CWalletDB walletdb(*dbw);
- return walletdb.ListAccountCreditDebit(strAccount, entries);
+ WalletBatch batch(*database);
+ return batch.ListAccountCreditDebit(strAccount, entries);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
{
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
- return AddAccountingEntry(acentry, &walletdb);
+ return AddAccountingEntry(acentry, &batch);
}
-bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
+bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, WalletBatch *batch)
{
- if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
+ if (!batch->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
return false;
}
@@ -3145,10 +3142,10 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
LOCK2(cs_main, cs_wallet);
fFirstRunRet = false;
- DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
+ DBErrors nLoadWalletRet = WalletBatch(*database,"cr+").LoadWallet(this);
if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{
- if (dbw->Rewrite("\x04pool"))
+ if (database->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
@@ -3173,13 +3170,13 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{
AssertLockHeld(cs_wallet); // mapWallet
- DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
+ DBErrors nZapSelectTxRet = WalletBatch(*database,"cr+").ZapSelectTx(vHashIn, vHashOut);
for (uint256 hash : vHashOut)
mapWallet.erase(hash);
if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
{
- if (dbw->Rewrite("\x04pool"))
+ if (database->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
@@ -3201,10 +3198,10 @@ DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
- DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
+ DBErrors nZapWalletTxRet = WalletBatch(*database,"cr+").ZapWalletTx(vWtx);
if (nZapWalletTxRet == DBErrors::NEED_REWRITE)
{
- if (dbw->Rewrite("\x04pool"))
+ if (database->Rewrite("\x04pool"))
{
LOCK(cs_wallet);
setInternalKeyPool.clear();
@@ -3236,9 +3233,9 @@ bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& s
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
- if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
+ if (!strPurpose.empty() && !WalletBatch(*database).WritePurpose(EncodeDestination(address), strPurpose))
return false;
- return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
+ return WalletBatch(*database).WriteName(EncodeDestination(address), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
@@ -3250,15 +3247,15 @@ bool CWallet::DelAddressBook(const CTxDestination& address)
std::string strAddress = EncodeDestination(address);
for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
{
- CWalletDB(*dbw).EraseDestData(strAddress, item.first);
+ WalletBatch(*database).EraseDestData(strAddress, item.first);
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
- CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
- return CWalletDB(*dbw).EraseName(EncodeDestination(address));
+ WalletBatch(*database).ErasePurpose(EncodeDestination(address));
+ return WalletBatch(*database).EraseName(EncodeDestination(address));
}
const std::string& CWallet::GetLabelName(const CScript& scriptPubKey) const
@@ -3284,15 +3281,15 @@ bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
for (int64_t nIndex : setInternalKeyPool) {
- walletdb.ErasePool(nIndex);
+ batch.ErasePool(nIndex);
}
setInternalKeyPool.clear();
for (int64_t nIndex : setExternalKeyPool) {
- walletdb.ErasePool(nIndex);
+ batch.ErasePool(nIndex);
}
setExternalKeyPool.clear();
@@ -3357,7 +3354,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
missingInternal = 0;
}
bool internal = false;
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
for (int64_t i = missingInternal + missingExternal; i--;)
{
if (i < missingInternal) {
@@ -3367,8 +3364,8 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
int64_t index = ++m_max_keypool_index;
- CPubKey pubkey(GenerateNewKey(walletdb, internal));
- if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
+ CPubKey pubkey(GenerateNewKey(batch, internal));
+ if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
}
@@ -3403,12 +3400,12 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRe
if(setKeyPool.empty())
return;
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
auto it = setKeyPool.begin();
nIndex = *it;
setKeyPool.erase(it);
- if (!walletdb.ReadPool(nIndex, keypool)) {
+ if (!batch.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read failed");
}
if (!HaveKey(keypool.vchPubKey.GetID())) {
@@ -3427,8 +3424,8 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRe
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
- CWalletDB walletdb(*dbw);
- walletdb.ErasePool(nIndex);
+ WalletBatch batch(*database);
+ batch.ErasePool(nIndex);
LogPrintf("keypool keep %d\n", nIndex);
}
@@ -3457,8 +3454,8 @@ bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
if (nIndex == -1)
{
if (IsLocked()) return false;
- CWalletDB walletdb(*dbw);
- result = GenerateNewKey(walletdb, internal);
+ WalletBatch batch(*database);
+ result = GenerateNewKey(batch, internal);
return true;
}
KeepKey(nIndex);
@@ -3467,14 +3464,14 @@ bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
return true;
}
-static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
+static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
if (setKeyPool.empty()) {
return GetTime();
}
CKeyPool keypool;
int64_t nIndex = *(setKeyPool.begin());
- if (!walletdb.ReadPool(nIndex, keypool)) {
+ if (!batch.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
}
assert(keypool.vchPubKey.IsValid());
@@ -3485,12 +3482,12 @@ int64_t CWallet::GetOldestKeyPoolTime()
{
LOCK(cs_wallet);
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
// load oldest key from keypool, get time and return
- int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
+ int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
- oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
+ oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
}
return oldestKey;
@@ -3686,17 +3683,17 @@ void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
auto it = setKeyPool->begin();
- CWalletDB walletdb(*dbw);
+ WalletBatch batch(*database);
while (it != std::end(*setKeyPool)) {
const int64_t& index = *(it);
if (index > keypool_id) break; // set*KeyPool is ordered
CKeyPool keypool;
- if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
+ if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
}
LearnAllRelatedScripts(keypool.vchPubKey);
- walletdb.ErasePool(index);
+ batch.ErasePool(index);
LogPrintf("keypool index %d removed\n", index);
it = setKeyPool->erase(it);
}
@@ -3873,14 +3870,14 @@ bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, co
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
- return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
+ return WalletBatch(*database).WriteDestData(EncodeDestination(dest), key, value);
}
bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
- return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
+ return WalletBatch(*database).EraseDestData(EncodeDestination(dest), key);
}
bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
@@ -3929,7 +3926,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
if (gArgs.GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
- std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(name, CWalletDBWrapper::Create(path));
+ std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(name, WalletDatabase::Create(path));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DBErrors::LOAD_OK) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
@@ -3941,7 +3938,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
int64_t nStart = GetTimeMillis();
bool fFirstRun = true;
- CWallet *walletInstance = new CWallet(name, CWalletDBWrapper::Create(path));
+ CWallet *walletInstance = new CWallet(name, WalletDatabase::Create(path));
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
if (nLoadWalletRet != DBErrors::LOAD_OK)
{
@@ -4046,9 +4043,9 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
CBlockIndex *pindexRescan = chainActive.Genesis();
if (!gArgs.GetBoolArg("-rescan", false))
{
- CWalletDB walletdb(*walletInstance->dbw);
+ WalletBatch batch(*walletInstance->database);
CBlockLocator locator;
- if (walletdb.ReadBestBlock(locator))
+ if (batch.ReadBestBlock(locator))
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
}
@@ -4092,12 +4089,12 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
}
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
walletInstance->SetBestChain(chainActive.GetLocator());
- walletInstance->dbw->IncrementUpdateCounter();
+ walletInstance->database->IncrementUpdateCounter();
// Restore wallet transaction metadata after -zapwallettxes=1
if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
{
- CWalletDB walletdb(*walletInstance->dbw);
+ WalletBatch batch(*walletInstance->database);
for (const CWalletTx& wtxOld : vWtx)
{
@@ -4114,7 +4111,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
- walletdb.WriteTx(*copyTo);
+ batch.WriteTx(*copyTo);
}
}
}
@@ -4147,7 +4144,7 @@ void CWallet::postInitProcess(CScheduler& scheduler)
bool CWallet::BackupWallet(const std::string& strDest)
{
- return dbw->Backup(strDest);
+ return database->Backup(strDest);
}
CKeyPool::CKeyPool()
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index 898c32c708..170e60d485 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -661,22 +661,22 @@ class CWallet final : public CCryptoKeyStore, public CValidationInterface
{
private:
static std::atomic<bool> fFlushScheduled;
- std::atomic<bool> fAbortRescan;
- std::atomic<bool> fScanningWallet; //controlled by WalletRescanReserver
+ std::atomic<bool> fAbortRescan{false};
+ std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
std::mutex mutexScanning;
friend class WalletRescanReserver;
- CWalletDB *pwalletdbEncryption;
+ WalletBatch *encrypted_batch = 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
@@ -701,14 +701,14 @@ private:
CHDChain hdChain;
/* HD derive new child key (on internal or external chain) */
- void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal = false);
+ void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, bool internal = false);
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
@@ -729,7 +729,7 @@ private:
std::string m_name;
/** Internal database handle. */
- std::unique_ptr<CWalletDBWrapper> dbw;
+ std::unique_ptr<WalletDatabase> database;
/**
* The following is used to keep track of how far behind the wallet is
@@ -741,7 +741,7 @@ private:
*
* Protected by cs_main (see BlockUntilSyncedToCurrentChain)
*/
- const CBlockIndex* m_last_block_processed;
+ const CBlockIndex* m_last_block_processed = nullptr;
public:
/*
@@ -753,9 +753,9 @@ public:
/** Get database handle used by this wallet. Ideally this function would
* not be necessary.
*/
- CWalletDBWrapper& GetDBHandle()
+ WalletDatabase& GetDBHandle()
{
- return *dbw;
+ return *database;
}
/**
@@ -780,36 +780,17 @@ 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))
+ CWallet(std::string name, std::unique_ptr<WalletDatabase> database) : m_name(std::move(name)), database(std::move(database))
{
- SetNull();
}
~CWallet()
{
- delete pwalletdbEncryption;
- 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;
+ delete encrypted_batch;
+ encrypted_batch = nullptr;
}
std::map<uint256, CWalletTx> mapWallet;
@@ -819,8 +800,8 @@ public:
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems wtxOrdered;
- int64_t nOrderPosNext;
- uint64_t nAccountingEntryNumber;
+ int64_t nOrderPosNext = 0;
+ uint64_t nAccountingEntryNumber = 0;
std::map<uint256, int> mapRequestCount;
std::map<CTxDestination, CAddressBookData> mapAddressBook;
@@ -875,10 +856,10 @@ public:
* keystore implementation
* Generate a new key
*/
- CPubKey GenerateNewKey(CWalletDB& walletdb, bool internal = false);
+ CPubKey GenerateNewKey(WalletBatch& batch, bool internal = false);
//! Adds a key to the store, and saves it to disk.
bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
- bool AddKeyPubKeyWithDB(CWalletDB &walletdb,const CKey& key, const CPubKey &pubkey);
+ bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey);
//! Adds a key to the store, without saving it to disk (used by LoadWallet)
bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
//! Load metadata (used by LoadWallet)
@@ -913,7 +894,7 @@ public:
bool LoadWatchOnly(const CScript &dest);
//! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
- int64_t nRelockTime;
+ int64_t nRelockTime = 0;
bool Unlock(const SecureString& strWalletPassphrase);
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
@@ -926,7 +907,7 @@ public:
* Increment the next transaction order id
* @return next transaction order id
*/
- int64_t IncOrderPosNext(CWalletDB *pwalletdb = nullptr);
+ int64_t IncOrderPosNext(WalletBatch *batch = nullptr);
DBErrors ReorderTransactions();
bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
bool GetLabelDestination(CTxDestination &dest, const std::string& label, bool bForceNew = false);
@@ -974,7 +955,7 @@ public:
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
bool AddAccountingEntry(const CAccountingEntry&);
- bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
+ bool AddAccountingEntry(const CAccountingEntry&, WalletBatch *batch);
bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts) const
{
std::vector<CTxOut> v_txouts(txouts.size());
@@ -1058,7 +1039,7 @@ public:
}
//! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
- bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = nullptr, bool fExplicit = false);
+ bool SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false);
//! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
bool SetMaxVersion(int nVersion);
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
index 77cdfe7dd0..57261bb922 100644
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -21,42 +21,42 @@
#include <boost/thread.hpp>
//
-// CWalletDB
+// WalletBatch
//
-bool CWalletDB::WriteName(const std::string& strAddress, const std::string& strName)
+bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
{
return WriteIC(std::make_pair(std::string("name"), strAddress), strName);
}
-bool CWalletDB::EraseName(const std::string& strAddress)
+bool WalletBatch::EraseName(const std::string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
return EraseIC(std::make_pair(std::string("name"), strAddress));
}
-bool CWalletDB::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
+bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
{
return WriteIC(std::make_pair(std::string("purpose"), strAddress), strPurpose);
}
-bool CWalletDB::ErasePurpose(const std::string& strAddress)
+bool WalletBatch::ErasePurpose(const std::string& strAddress)
{
return EraseIC(std::make_pair(std::string("purpose"), strAddress));
}
-bool CWalletDB::WriteTx(const CWalletTx& wtx)
+bool WalletBatch::WriteTx(const CWalletTx& wtx)
{
return WriteIC(std::make_pair(std::string("tx"), wtx.GetHash()), wtx);
}
-bool CWalletDB::EraseTx(uint256 hash)
+bool WalletBatch::EraseTx(uint256 hash)
{
return EraseIC(std::make_pair(std::string("tx"), hash));
}
-bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
+bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
if (!WriteIC(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta, false)) {
return false;
@@ -71,7 +71,7 @@ bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, c
return WriteIC(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
-bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
+bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
@@ -87,17 +87,17 @@ bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
return true;
}
-bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
+bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
return WriteIC(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
-bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript)
+bool WalletBatch::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
return WriteIC(std::make_pair(std::string("cscript"), hash), redeemScript, false);
}
-bool CWalletDB::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
+bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
{
if (!WriteIC(std::make_pair(std::string("watchmeta"), dest), keyMeta)) {
return false;
@@ -105,7 +105,7 @@ bool CWalletDB::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
return WriteIC(std::make_pair(std::string("watchs"), dest), '1');
}
-bool CWalletDB::EraseWatchOnly(const CScript &dest)
+bool WalletBatch::EraseWatchOnly(const CScript &dest)
{
if (!EraseIC(std::make_pair(std::string("watchmeta"), dest))) {
return false;
@@ -113,60 +113,60 @@ bool CWalletDB::EraseWatchOnly(const CScript &dest)
return EraseIC(std::make_pair(std::string("watchs"), dest));
}
-bool CWalletDB::WriteBestBlock(const CBlockLocator& locator)
+bool WalletBatch::WriteBestBlock(const CBlockLocator& locator)
{
WriteIC(std::string("bestblock"), CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
return WriteIC(std::string("bestblock_nomerkle"), locator);
}
-bool CWalletDB::ReadBestBlock(CBlockLocator& locator)
+bool WalletBatch::ReadBestBlock(CBlockLocator& locator)
{
- if (batch.Read(std::string("bestblock"), locator) && !locator.vHave.empty()) return true;
- return batch.Read(std::string("bestblock_nomerkle"), locator);
+ if (m_batch.Read(std::string("bestblock"), locator) && !locator.vHave.empty()) return true;
+ return m_batch.Read(std::string("bestblock_nomerkle"), locator);
}
-bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
+bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
{
return WriteIC(std::string("orderposnext"), nOrderPosNext);
}
-bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
+bool WalletBatch::ReadPool(int64_t nPool, CKeyPool& keypool)
{
- return batch.Read(std::make_pair(std::string("pool"), nPool), keypool);
+ return m_batch.Read(std::make_pair(std::string("pool"), nPool), keypool);
}
-bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool)
+bool WalletBatch::WritePool(int64_t nPool, const CKeyPool& keypool)
{
return WriteIC(std::make_pair(std::string("pool"), nPool), keypool);
}
-bool CWalletDB::ErasePool(int64_t nPool)
+bool WalletBatch::ErasePool(int64_t nPool)
{
return EraseIC(std::make_pair(std::string("pool"), nPool));
}
-bool CWalletDB::WriteMinVersion(int nVersion)
+bool WalletBatch::WriteMinVersion(int nVersion)
{
return WriteIC(std::string("minversion"), nVersion);
}
-bool CWalletDB::ReadAccount(const std::string& strAccount, CAccount& account)
+bool WalletBatch::ReadAccount(const std::string& strAccount, CAccount& account)
{
account.SetNull();
- return batch.Read(std::make_pair(std::string("acc"), strAccount), account);
+ return m_batch.Read(std::make_pair(std::string("acc"), strAccount), account);
}
-bool CWalletDB::WriteAccount(const std::string& strAccount, const CAccount& account)
+bool WalletBatch::WriteAccount(const std::string& strAccount, const CAccount& account)
{
return WriteIC(std::make_pair(std::string("acc"), strAccount), account);
}
-bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
+bool WalletBatch::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return WriteIC(std::make_pair(std::string("acentry"), std::make_pair(acentry.strAccount, nAccEntryNum)), acentry);
}
-CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount)
+CAmount WalletBatch::GetAccountCreditDebit(const std::string& strAccount)
{
std::list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
@@ -178,11 +178,11 @@ CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount)
return nCreditDebit;
}
-void CWalletDB::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries)
+void WalletBatch::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
- Dbc* pcursor = batch.GetCursor();
+ Dbc* pcursor = m_batch.GetCursor();
if (!pcursor)
throw std::runtime_error(std::string(__func__) + ": cannot create DB cursor");
bool setRange = true;
@@ -193,7 +193,7 @@ void CWalletDB::ListAccountCreditDebit(const std::string& strAccount, std::list<
if (setRange)
ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? std::string("") : strAccount), uint64_t(0)));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
- int ret = batch.ReadAtCursor(pcursor, ssKey, ssValue, setRange);
+ int ret = m_batch.ReadAtCursor(pcursor, ssKey, ssValue, setRange);
setRange = false;
if (ret == DB_NOTFOUND)
break;
@@ -512,13 +512,13 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
return true;
}
-bool CWalletDB::IsKeyType(const std::string& strType)
+bool WalletBatch::IsKeyType(const std::string& strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
-DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
+DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
{
CWalletScanState wss;
bool fNoncriticalErrors = false;
@@ -527,7 +527,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
LOCK(pwallet->cs_wallet);
try {
int nMinVersion = 0;
- if (batch.Read((std::string)"minversion", nMinVersion))
+ if (m_batch.Read((std::string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DBErrors::TOO_NEW;
@@ -535,7 +535,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
}
// Get cursor
- Dbc* pcursor = batch.GetCursor();
+ Dbc* pcursor = m_batch.GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
@@ -547,7 +547,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
- int ret = batch.ReadAtCursor(pcursor, ssKey, ssValue);
+ int ret = m_batch.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
@@ -624,20 +624,20 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
return result;
}
-DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx)
+DBErrors WalletBatch::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx)
{
DBErrors result = DBErrors::LOAD_OK;
try {
int nMinVersion = 0;
- if (batch.Read((std::string)"minversion", nMinVersion))
+ if (m_batch.Read((std::string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DBErrors::TOO_NEW;
}
// Get cursor
- Dbc* pcursor = batch.GetCursor();
+ Dbc* pcursor = m_batch.GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
@@ -649,7 +649,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWal
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
- int ret = batch.ReadAtCursor(pcursor, ssKey, ssValue);
+ int ret = m_batch.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
@@ -683,7 +683,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWal
return result;
}
-DBErrors CWalletDB::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uint256>& vTxHashOut)
+DBErrors WalletBatch::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uint256>& vTxHashOut)
{
// build list of wallet TXs and hashes
std::vector<uint256> vTxHash;
@@ -721,7 +721,7 @@ DBErrors CWalletDB::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uin
return DBErrors::LOAD_OK;
}
-DBErrors CWalletDB::ZapWalletTx(std::vector<CWalletTx>& vWtx)
+DBErrors WalletBatch::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
// build list of wallet TXs
std::vector<uint256> vTxHash;
@@ -749,7 +749,7 @@ void MaybeCompactWalletDB()
}
for (CWalletRef pwallet : vpwallets) {
- CWalletDBWrapper& dbh = pwallet->GetDBHandle();
+ WalletDatabase& dbh = pwallet->GetDBHandle();
unsigned int nUpdateCounter = dbh.nUpdateCounter;
@@ -759,7 +759,7 @@ void MaybeCompactWalletDB()
}
if (dbh.nLastFlushed != nUpdateCounter && GetTime() - dbh.nLastWalletUpdate >= 2) {
- if (CDB::PeriodicFlush(dbh)) {
+ if (BerkeleyBatch::PeriodicFlush(dbh)) {
dbh.nLastFlushed = nUpdateCounter;
}
}
@@ -771,19 +771,19 @@ void MaybeCompactWalletDB()
//
// Try to (very carefully!) recover wallet file if there is a problem.
//
-bool CWalletDB::Recover(const fs::path& wallet_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& out_backup_filename)
+bool WalletBatch::Recover(const fs::path& wallet_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& out_backup_filename)
{
- return CDB::Recover(wallet_path, callbackDataIn, recoverKVcallback, out_backup_filename);
+ return BerkeleyBatch::Recover(wallet_path, callbackDataIn, recoverKVcallback, out_backup_filename);
}
-bool CWalletDB::Recover(const fs::path& wallet_path, std::string& out_backup_filename)
+bool WalletBatch::Recover(const fs::path& wallet_path, std::string& out_backup_filename)
{
// recover without a key filter callback
// results in recovering all record types
- return CWalletDB::Recover(wallet_path, nullptr, nullptr, out_backup_filename);
+ return WalletBatch::Recover(wallet_path, nullptr, nullptr, out_backup_filename);
}
-bool CWalletDB::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
+bool WalletBatch::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
{
CWallet *dummyWallet = reinterpret_cast<CWallet*>(callbackData);
CWalletScanState dummyWss;
@@ -799,60 +799,60 @@ bool CWalletDB::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDa
return false;
if (!fReadOK)
{
- LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
+ LogPrintf("WARNING: WalletBatch::Recover skipping %s: %s\n", strType, strErr);
return false;
}
return true;
}
-bool CWalletDB::VerifyEnvironment(const fs::path& wallet_path, std::string& errorStr)
+bool WalletBatch::VerifyEnvironment(const fs::path& wallet_path, std::string& errorStr)
{
- return CDB::VerifyEnvironment(wallet_path, errorStr);
+ return BerkeleyBatch::VerifyEnvironment(wallet_path, errorStr);
}
-bool CWalletDB::VerifyDatabaseFile(const fs::path& wallet_path, std::string& warningStr, std::string& errorStr)
+bool WalletBatch::VerifyDatabaseFile(const fs::path& wallet_path, std::string& warningStr, std::string& errorStr)
{
- return CDB::VerifyDatabaseFile(wallet_path, warningStr, errorStr, CWalletDB::Recover);
+ return BerkeleyBatch::VerifyDatabaseFile(wallet_path, warningStr, errorStr, WalletBatch::Recover);
}
-bool CWalletDB::WriteDestData(const std::string &address, const std::string &key, const std::string &value)
+bool WalletBatch::WriteDestData(const std::string &address, const std::string &key, const std::string &value)
{
return WriteIC(std::make_pair(std::string("destdata"), std::make_pair(address, key)), value);
}
-bool CWalletDB::EraseDestData(const std::string &address, const std::string &key)
+bool WalletBatch::EraseDestData(const std::string &address, const std::string &key)
{
return EraseIC(std::make_pair(std::string("destdata"), std::make_pair(address, key)));
}
-bool CWalletDB::WriteHDChain(const CHDChain& chain)
+bool WalletBatch::WriteHDChain(const CHDChain& chain)
{
return WriteIC(std::string("hdchain"), chain);
}
-bool CWalletDB::TxnBegin()
+bool WalletBatch::TxnBegin()
{
- return batch.TxnBegin();
+ return m_batch.TxnBegin();
}
-bool CWalletDB::TxnCommit()
+bool WalletBatch::TxnCommit()
{
- return batch.TxnCommit();
+ return m_batch.TxnCommit();
}
-bool CWalletDB::TxnAbort()
+bool WalletBatch::TxnAbort()
{
- return batch.TxnAbort();
+ return m_batch.TxnAbort();
}
-bool CWalletDB::ReadVersion(int& nVersion)
+bool WalletBatch::ReadVersion(int& nVersion)
{
- return batch.ReadVersion(nVersion);
+ return m_batch.ReadVersion(nVersion);
}
-bool CWalletDB::WriteVersion(int nVersion)
+bool WalletBatch::WriteVersion(int nVersion)
{
- return batch.WriteVersion(nVersion);
+ return m_batch.WriteVersion(nVersion);
}
diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h
index 606b7dace7..040aa092e1 100644
--- a/src/wallet/walletdb.h
+++ b/src/wallet/walletdb.h
@@ -20,16 +20,13 @@
/**
* Overview of wallet database classes:
*
- * - CDBEnv is an environment in which the database exists (has no analog in dbwrapper.h)
- * - CWalletDBWrapper represents a wallet database (similar to CDBWrapper in dbwrapper.h)
- * - CDB is a low-level database transaction (similar to CDBBatch in dbwrapper.h)
- * - CWalletDB is a modifier object for the wallet, and encapsulates a database
- * transaction as well as methods to act on the database (no analog in
- * dbwrapper.h)
+ * - WalletBatch is an abstract modifier object for the wallet database, and encapsulates a database
+ * batch update as well as methods to act on the database. It should be agnostic to the database implementation.
*
- * The latter two are named confusingly, in contrast to what the names CDB
- * and CWalletDB suggest they are transient transaction objects and don't
- * represent the database itself.
+ * The following classes are implementation specific:
+ * - BerkeleyEnvironment is an environment in which the database exists.
+ * - BerkeleyDatabase represents a wallet database.
+ * - BerkeleyBatch is a low-level database batch update.
*/
static const bool DEFAULT_FLUSHWALLET = true;
@@ -45,6 +42,9 @@ class CWalletTx;
class uint160;
class uint256;
+/** Backend-agnostic database type. */
+using WalletDatabase = BerkeleyDatabase;
+
/** Error statuses for the wallet database */
enum class DBErrors
{
@@ -134,41 +134,41 @@ public:
};
/** Access to the wallet database.
- * This should really be named CWalletDBBatch, as it represents a single transaction at the
+ * This represents a single transaction at the
* database. It will be committed when the object goes out of scope.
* Optionally (on by default) it will flush to disk as well.
*/
-class CWalletDB
+class WalletBatch
{
private:
template <typename K, typename T>
bool WriteIC(const K& key, const T& value, bool fOverwrite = true)
{
- if (!batch.Write(key, value, fOverwrite)) {
+ if (!m_batch.Write(key, value, fOverwrite)) {
return false;
}
- m_dbw.IncrementUpdateCounter();
+ m_database.IncrementUpdateCounter();
return true;
}
template <typename K>
bool EraseIC(const K& key)
{
- if (!batch.Erase(key)) {
+ if (!m_batch.Erase(key)) {
return false;
}
- m_dbw.IncrementUpdateCounter();
+ m_database.IncrementUpdateCounter();
return true;
}
public:
- explicit CWalletDB(CWalletDBWrapper& dbw, const char* pszMode = "r+", bool _fFlushOnClose = true) :
- batch(dbw, pszMode, _fFlushOnClose),
- m_dbw(dbw)
+ explicit WalletBatch(WalletDatabase& database, const char* pszMode = "r+", bool _fFlushOnClose = true) :
+ m_batch(database, pszMode, _fFlushOnClose),
+ m_database(database)
{
}
- CWalletDB(const CWalletDB&) = delete;
- CWalletDB& operator=(const CWalletDB&) = delete;
+ WalletBatch(const WalletBatch&) = delete;
+ WalletBatch& operator=(const WalletBatch&) = delete;
bool WriteName(const std::string& strAddress, const std::string& strName);
bool EraseName(const std::string& strAddress);
@@ -244,8 +244,8 @@ public:
//! Write wallet version
bool WriteVersion(int nVersion);
private:
- CDB batch;
- CWalletDBWrapper& m_dbw;
+ BerkeleyBatch m_batch;
+ WalletDatabase& m_database;
};
//! Compacts BDB state so that wallet.dat is self-contained (if there are changes)
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