aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Makefile.am15
-rw-r--r--src/Makefile.qt.include4
-rw-r--r--src/Makefile.qttest.include2
-rw-r--r--src/Makefile.test.include3
-rw-r--r--src/addrdb.cpp6
-rw-r--r--src/addrman.h2
-rw-r--r--src/base58.cpp25
-rw-r--r--src/bech32.h5
-rw-r--r--src/bench/bench_bitcoin.cpp2
-rw-r--r--src/bench/coin_selection.cpp50
-rw-r--r--src/bench/lockedpool.cpp2
-rw-r--r--src/bench/perf.h6
-rw-r--r--src/bench/verify_script.cpp2
-rw-r--r--src/bitcoin-cli.cpp29
-rw-r--r--src/bitcoin-tx.cpp14
-rw-r--r--src/bitcoind.cpp6
-rw-r--r--src/blockencodings.h12
-rw-r--r--src/chain.h8
-rw-r--r--src/chainparams.cpp2
-rw-r--r--src/chainparamsbase.cpp1
-rw-r--r--src/checkpoints.cpp7
-rw-r--r--src/checkpoints.h2
-rw-r--r--src/coins.h2
-rw-r--r--src/compressor.cpp30
-rw-r--r--src/compressor.h35
-rw-r--r--src/consensus/merkle.h6
-rw-r--r--src/consensus/validation.h5
-rw-r--r--src/core_write.cpp2
-rw-r--r--src/cuckoocache.h2
-rw-r--r--src/dbwrapper.cpp44
-rw-r--r--src/hash.h2
-rw-r--r--src/httprpc.cpp8
-rw-r--r--src/httpserver.cpp1
-rw-r--r--src/init.cpp127
-rw-r--r--src/init.h10
-rw-r--r--src/interface/README.md17
-rw-r--r--src/interface/handler.cpp33
-rw-r--r--src/interface/handler.h35
-rw-r--r--src/interface/node.cpp308
-rw-r--r--src/interface/node.h259
-rw-r--r--src/interface/wallet.cpp441
-rw-r--r--src/interface/wallet.h352
-rw-r--r--src/key_io.h6
-rw-r--r--src/keystore.cpp6
-rw-r--r--src/keystore.h15
-rw-r--r--src/memusage.h1
-rw-r--r--src/miner.cpp9
-rw-r--r--src/miner.h2
-rw-r--r--src/net.cpp10
-rw-r--r--src/net.h7
-rw-r--r--src/net_processing.cpp89
-rw-r--r--src/net_processing.h8
-rw-r--r--src/netaddress.h8
-rw-r--r--src/netbase.cpp2
-rw-r--r--src/policy/fees.h9
-rw-r--r--src/policy/policy.cpp9
-rw-r--r--src/policy/policy.h1
-rw-r--r--src/policy/rbf.cpp8
-rw-r--r--src/policy/rbf.h8
-rw-r--r--src/protocol.h6
-rw-r--r--src/pubkey.h5
-rw-r--r--src/qt/addressbookpage.cpp68
-rw-r--r--src/qt/addressbookpage.h4
-rw-r--r--src/qt/addresstablemodel.cpp59
-rw-r--r--src/qt/addresstablemodel.h11
-rw-r--r--src/qt/bantablemodel.cpp11
-rw-r--r--src/qt/bantablemodel.h9
-rw-r--r--src/qt/bitcoin.cpp132
-rw-r--r--src/qt/bitcoingui.cpp91
-rw-r--r--src/qt/bitcoingui.h30
-rw-r--r--src/qt/clientmodel.cpp160
-rw-r--r--src/qt/clientmodel.h46
-rw-r--r--src/qt/coincontroldialog.cpp79
-rw-r--r--src/qt/editaddressdialog.cpp10
-rw-r--r--src/qt/editaddressdialog.h1
-rw-r--r--src/qt/forms/addressbookpage.ui7
-rw-r--r--src/qt/forms/debugwindow.ui16
-rw-r--r--src/qt/guiutil.cpp23
-rw-r--r--src/qt/guiutil.h12
-rw-r--r--src/qt/intro.cpp8
-rw-r--r--src/qt/intro.h6
-rw-r--r--src/qt/modaloverlay.cpp2
-rw-r--r--src/qt/optionsdialog.cpp7
-rw-r--r--src/qt/optionsmodel.cpp36
-rw-r--r--src/qt/optionsmodel.h9
-rw-r--r--src/qt/overviewpage.cpp54
-rw-r--r--src/qt/overviewpage.h12
-rw-r--r--src/qt/paymentserver.cpp44
-rw-r--r--src/qt/paymentserver.h8
-rw-r--r--src/qt/peertablemodel.cpp36
-rw-r--r--src/qt/peertablemodel.h9
-rw-r--r--src/qt/receivecoinsdialog.cpp14
-rw-r--r--src/qt/receiverequestdialog.cpp9
-rw-r--r--src/qt/receiverequestdialog.h6
-rw-r--r--src/qt/recentrequeststablemodel.cpp6
-rw-r--r--src/qt/recentrequeststablemodel.h4
-rw-r--r--src/qt/rpcconsole.cpp108
-rw-r--r--src/qt/rpcconsole.h18
-rw-r--r--src/qt/sendcoinsdialog.cpp53
-rw-r--r--src/qt/sendcoinsdialog.h3
-rw-r--r--src/qt/sendcoinsentry.cpp4
-rw-r--r--src/qt/sendcoinsentry.h2
-rw-r--r--src/qt/signverifymessagedialog.cpp2
-rw-r--r--src/qt/splashscreen.cpp42
-rw-r--r--src/qt/splashscreen.h20
-rw-r--r--src/qt/test/paymentrequestdata.h5
-rw-r--r--src/qt/test/paymentservertests.cpp6
-rw-r--r--src/qt/test/rpcnestedtests.cpp84
-rw-r--r--src/qt/test/rpcnestedtests.h6
-rw-r--r--src/qt/test/uritests.cpp2
-rw-r--r--src/qt/test/wallettests.cpp17
-rw-r--r--src/qt/trafficgraphwidget.cpp13
-rw-r--r--src/qt/transactiondesc.cpp138
-rw-r--r--src/qt/transactiondesc.h12
-rw-r--r--src/qt/transactionfilterproxy.cpp28
-rw-r--r--src/qt/transactionrecord.cpp89
-rw-r--r--src/qt/transactionrecord.h16
-rw-r--r--src/qt/transactiontablemodel.cpp100
-rw-r--r--src/qt/transactiontablemodel.h13
-rw-r--r--src/qt/transactionview.cpp10
-rw-r--r--src/qt/utilitydialog.cpp5
-rw-r--r--src/qt/utilitydialog.h6
-rw-r--r--src/qt/walletframe.cpp11
-rw-r--r--src/qt/walletframe.h3
-rw-r--r--src/qt/walletmodel.cpp343
-rw-r--r--src/qt/walletmodel.h68
-rw-r--r--src/qt/walletmodeltransaction.cpp30
-rw-r--r--src/qt/walletmodeltransaction.h18
-rw-r--r--src/qt/walletview.cpp19
-rw-r--r--src/qt/walletview.h7
-rw-r--r--src/random.h9
-rw-r--r--src/rest.cpp100
-rw-r--r--src/rpc/blockchain.cpp65
-rw-r--r--src/rpc/client.cpp6
-rw-r--r--src/rpc/client.h6
-rw-r--r--src/rpc/mining.cpp28
-rw-r--r--src/rpc/protocol.h11
-rw-r--r--src/rpc/rawtransaction.cpp184
-rw-r--r--src/rpc/register.h6
-rw-r--r--src/rpc/server.cpp17
-rw-r--r--src/rpc/server.h24
-rw-r--r--src/rpc/util.cpp1
-rw-r--r--src/rpc/util.h1
-rw-r--r--src/script/bitcoinconsensus.cpp2
-rw-r--r--src/script/bitcoinconsensus.h6
-rw-r--r--src/script/interpreter.cpp30
-rw-r--r--src/script/interpreter.h6
-rw-r--r--src/script/ismine.cpp10
-rw-r--r--src/script/ismine.h10
-rw-r--r--src/script/sign.cpp48
-rw-r--r--src/script/sign.h34
-rw-r--r--src/script/standard.cpp4
-rw-r--r--src/serialize.h102
-rw-r--r--src/streams.h8
-rw-r--r--src/support/lockedpool.cpp73
-rw-r--r--src/support/lockedpool.h19
-rw-r--r--src/sync.cpp1
-rw-r--r--src/test/addrman_tests.cpp2
-rw-r--r--src/test/allocator_tests.cpp2
-rw-r--r--src/test/blockchain_tests.cpp2
-rw-r--r--src/test/coins_tests.cpp2
-rw-r--r--src/test/compress_tests.cpp8
-rw-r--r--src/test/cuckoocache_tests.cpp4
-rw-r--r--src/test/data/base58_encode_decode.json4
-rw-r--r--src/test/data/script_tests.json28
-rw-r--r--src/test/data/tx_invalid.json4
-rw-r--r--src/test/dbwrapper_tests.cpp4
-rw-r--r--src/test/mempool_tests.cpp2
-rw-r--r--src/test/multisig_tests.cpp2
-rw-r--r--src/test/net_tests.cpp8
-rw-r--r--src/test/prevector_tests.cpp2
-rw-r--r--src/test/random_tests.cpp22
-rw-r--r--src/test/rpc_tests.cpp1
-rw-r--r--src/test/script_tests.cpp134
-rw-r--r--src/test/serialize_tests.cpp42
-rw-r--r--src/test/sighash_tests.cpp4
-rw-r--r--src/test/streams_tests.cpp8
-rw-r--r--src/test/test_bitcoin.cpp2
-rw-r--r--src/test/test_bitcoin.h2
-rw-r--r--src/test/test_bitcoin_fuzzy.cpp1
-rw-r--r--src/test/test_bitcoin_main.cpp2
-rw-r--r--src/test/transaction_tests.cpp2
-rw-r--r--src/test/txvalidationcache_tests.cpp10
-rw-r--r--src/test/util_tests.cpp98
-rw-r--r--src/test/versionbits_tests.cpp20
-rw-r--r--src/tinyformat.h4
-rw-r--r--src/txdb.cpp8
-rw-r--r--src/txdb.h1
-rw-r--r--src/txmempool.cpp4
-rw-r--r--src/txmempool.h6
-rw-r--r--src/undo.h12
-rw-r--r--src/util.cpp177
-rw-r--r--src/util.h27
-rw-r--r--src/utiltime.cpp12
-rw-r--r--src/utiltime.h8
-rw-r--r--src/validation.cpp189
-rw-r--r--src/validation.h15
-rw-r--r--src/validationinterface.h5
-rw-r--r--src/versionbits.cpp28
-rw-r--r--src/versionbits.h18
-rw-r--r--src/wallet/coincontrol.h6
-rw-r--r--src/wallet/coinselection.cpp300
-rw-r--r--src/wallet/coinselection.h54
-rw-r--r--src/wallet/crypter.h4
-rw-r--r--src/wallet/db.cpp10
-rw-r--r--src/wallet/db.h3
-rw-r--r--src/wallet/feebumper.cpp44
-rw-r--r--src/wallet/fees.cpp52
-rw-r--r--src/wallet/fees.h12
-rw-r--r--src/wallet/init.cpp76
-rw-r--r--src/wallet/init.h43
-rw-r--r--src/wallet/rpcdump.cpp23
-rw-r--r--src/wallet/rpcwallet.cpp293
-rw-r--r--src/wallet/test/accounting_tests.cpp10
-rw-r--r--src/wallet/test/coinselector_tests.cpp575
-rw-r--r--src/wallet/test/crypto_tests.cpp2
-rw-r--r--src/wallet/test/wallet_test_fixture.cpp2
-rw-r--r--src/wallet/test/wallet_test_fixture.h9
-rw-r--r--src/wallet/test/wallet_tests.cpp358
-rw-r--r--src/wallet/wallet.cpp607
-rw-r--r--src/wallet/wallet.h296
-rw-r--r--src/wallet/walletdb.cpp48
-rw-r--r--src/wallet/walletdb.h14
-rw-r--r--src/wallet/walletutil.h6
-rw-r--r--src/walletinitinterface.h37
225 files changed, 5808 insertions, 3296 deletions
diff --git a/src/Makefile.am b/src/Makefile.am
index 0a9370c85c..d2cfdc104b 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -4,9 +4,10 @@
DIST_SUBDIRS = secp256k1 univalue
-AM_LDFLAGS = $(PTHREAD_CFLAGS) $(LIBTOOL_LDFLAGS) $(HARDENED_LDFLAGS) $(GPROF_LDFLAGS)
-AM_CXXFLAGS = $(HARDENED_CXXFLAGS) $(ERROR_CXXFLAGS) $(GPROF_CXXFLAGS)
+AM_LDFLAGS = $(PTHREAD_CFLAGS) $(LIBTOOL_LDFLAGS) $(HARDENED_LDFLAGS) $(GPROF_LDFLAGS) $(SANITIZER_LDFLAGS)
+AM_CXXFLAGS = $(HARDENED_CXXFLAGS) $(ERROR_CXXFLAGS) $(GPROF_CXXFLAGS) $(SANITIZER_CXXFLAGS)
AM_CPPFLAGS = $(HARDENED_CPPFLAGS)
+AM_LIBTOOLFLAGS = --preserve-dup-deps
EXTRA_LIBRARIES =
if EMBEDDED_UNIVALUE
@@ -104,6 +105,9 @@ BITCOIN_CORE_H = \
httpserver.h \
indirectmap.h \
init.h \
+ interface/handler.h \
+ interface/node.h \
+ interface/wallet.h \
key.h \
key_io.h \
keystore.h \
@@ -162,16 +166,17 @@ BITCOIN_CORE_H = \
validation.h \
validationinterface.h \
versionbits.h \
+ walletinitinterface.h \
wallet/coincontrol.h \
wallet/crypter.h \
wallet/db.h \
wallet/feebumper.h \
wallet/fees.h \
- wallet/init.h \
wallet/rpcwallet.h \
wallet/wallet.h \
wallet/walletdb.h \
wallet/walletutil.h \
+ wallet/coinselection.h \
warnings.h \
zmq/zmqabstractnotifier.h \
zmq/zmqconfig.h\
@@ -243,6 +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 \
wallet/crypter.cpp \
wallet/db.cpp \
wallet/feebumper.cpp \
@@ -253,6 +259,7 @@ libbitcoin_wallet_a_SOURCES = \
wallet/wallet.cpp \
wallet/walletdb.cpp \
wallet/walletutil.cpp \
+ wallet/coinselection.cpp \
$(BITCOIN_CORE_H)
# crypto primitives library
@@ -354,6 +361,8 @@ libbitcoin_util_a_SOURCES = \
compat/glibcxx_sanity.cpp \
compat/strnlen.cpp \
fs.cpp \
+ interface/handler.cpp \
+ interface/node.cpp \
random.cpp \
rpc/protocol.cpp \
rpc/util.cpp \
diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include
index 0bdde06772..38eb12ce0d 100644
--- a/src/Makefile.qt.include
+++ b/src/Makefile.qt.include
@@ -402,7 +402,7 @@ if TARGET_WINDOWS
endif
qt_bitcoin_qt_LDADD = qt/libbitcoinqt.a $(LIBBITCOIN_SERVER)
if ENABLE_WALLET
-qt_bitcoin_qt_LDADD += $(LIBBITCOIN_WALLET)
+qt_bitcoin_qt_LDADD += $(LIBBITCOIN_UTIL) $(LIBBITCOIN_WALLET)
endif
if ENABLE_ZMQ
qt_bitcoin_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS)
@@ -411,7 +411,7 @@ qt_bitcoin_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL)
$(BOOST_LIBS) $(QT_LIBS) $(QT_DBUS_LIBS) $(QR_LIBS) $(PROTOBUF_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(LIBSECP256K1) \
$(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
qt_bitcoin_qt_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(QT_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
-qt_bitcoin_qt_LIBTOOLFLAGS = --tag CXX
+qt_bitcoin_qt_LIBTOOLFLAGS = $(AM_LIBTOOLFLAGS) --tag CXX
#locale/foo.ts -> locale/foo.qm
QT_QM=$(QT_TS:.ts=.qm)
diff --git a/src/Makefile.qttest.include b/src/Makefile.qttest.include
index ea2ed17472..1279152198 100644
--- a/src/Makefile.qttest.include
+++ b/src/Makefile.qttest.include
@@ -52,7 +52,7 @@ nodist_qt_test_test_bitcoin_qt_SOURCES = $(TEST_QT_MOC_CPP)
qt_test_test_bitcoin_qt_LDADD = $(LIBBITCOINQT) $(LIBBITCOIN_SERVER)
if ENABLE_WALLET
-qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_WALLET)
+qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_UTIL) $(LIBBITCOIN_WALLET)
endif
if ENABLE_ZMQ
qt_test_test_bitcoin_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS)
diff --git a/src/Makefile.test.include b/src/Makefile.test.include
index 4ee9102519..4d0819ab79 100644
--- a/src/Makefile.test.include
+++ b/src/Makefile.test.include
@@ -94,7 +94,8 @@ BITCOIN_TESTS += \
wallet/test/wallet_test_fixture.h \
wallet/test/accounting_tests.cpp \
wallet/test/wallet_tests.cpp \
- wallet/test/crypto_tests.cpp
+ wallet/test/crypto_tests.cpp \
+ wallet/test/coinselector_tests.cpp
endif
test_test_bitcoin_SOURCES = $(BITCOIN_TESTS) $(JSON_TEST_FILES) $(RAW_TEST_FILES)
diff --git a/src/addrdb.cpp b/src/addrdb.cpp
index 675f3c28af..e4620e63c6 100644
--- a/src/addrdb.cpp
+++ b/src/addrdb.cpp
@@ -22,8 +22,8 @@ bool SerializeDB(Stream& stream, const Data& data)
// Write and commit header, data
try {
CHashWriter hasher(SER_DISK, CLIENT_VERSION);
- stream << FLATDATA(Params().MessageStart()) << data;
- hasher << FLATDATA(Params().MessageStart()) << data;
+ stream << Params().MessageStart() << data;
+ hasher << Params().MessageStart() << data;
stream << hasher.GetHash();
} catch (const std::exception& e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
@@ -66,7 +66,7 @@ bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
CHashVerifier<Stream> verifier(&stream);
// de-serialize file header (network specific magic number) and ..
unsigned char pchMsgTmp[4];
- verifier >> FLATDATA(pchMsgTmp);
+ verifier >> pchMsgTmp;
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
diff --git a/src/addrman.h b/src/addrman.h
index 67423c6c55..6dec3fe416 100644
--- a/src/addrman.h
+++ b/src/addrman.h
@@ -218,7 +218,7 @@ private:
//! last time Good was called (memory only)
int64_t nLastGood;
- //! Holds addrs inserted into tried table that collide with existing entries. Test-before-evict discpline used to resolve these collisions.
+ //! Holds addrs inserted into tried table that collide with existing entries. Test-before-evict discipline used to resolve these collisions.
std::set<int> m_tried_collisions;
protected:
diff --git a/src/base58.cpp b/src/base58.cpp
index 982e123a1d..feec2d4e05 100644
--- a/src/base58.cpp
+++ b/src/base58.cpp
@@ -12,6 +12,24 @@
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
+static const int8_t mapBase58[256] = {
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,-1,-1,-1,-1,-1,-1,
+ -1, 9,10,11,12,13,14,15, 16,-1,17,18,19,20,21,-1,
+ 22,23,24,25,26,27,28,29, 30,31,32,-1,-1,-1,-1,-1,
+ -1,33,34,35,36,37,38,39, 40,41,42,43,-1,44,45,46,
+ 47,48,49,50,51,52,53,54, 55,56,57,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,
+};
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
@@ -29,13 +47,12 @@ bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
int size = strlen(psz) * 733 /1000 + 1; // log(58) / log(256), rounded up.
std::vector<unsigned char> b256(size);
// Process the characters.
+ static_assert(sizeof(mapBase58)/sizeof(mapBase58[0]) == 256, "mapBase58.size() should be 256"); // guarantee not out of range
while (*psz && !isspace(*psz)) {
// Decode base58 character
- const char* ch = strchr(pszBase58, *psz);
- if (ch == nullptr)
+ int carry = mapBase58[(uint8_t)*psz];
+ if (carry == -1) // Invalid b58 character
return false;
- // Apply "b256 = b256 * 58 + ch".
- int carry = ch - pszBase58;
int i = 0;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {
carry += 58 * (*it);
diff --git a/src/bech32.h b/src/bech32.h
index 7ef7b22213..2e2823e974 100644
--- a/src/bech32.h
+++ b/src/bech32.h
@@ -9,6 +9,9 @@
//
// For more information, see BIP 173.
+#ifndef BITCOIN_BECH32_H
+#define BITCOIN_BECH32_H
+
#include <stdint.h>
#include <string>
#include <vector>
@@ -23,3 +26,5 @@ std::string Encode(const std::string& hrp, const std::vector<uint8_t>& values);
std::pair<std::string, std::vector<uint8_t>> Decode(const std::string& str);
} // namespace bech32
+
+#endif // BITCOIN_BECH32_H
diff --git a/src/bench/bench_bitcoin.cpp b/src/bench/bench_bitcoin.cpp
index fc92a46c0f..1d87883522 100644
--- a/src/bench/bench_bitcoin.cpp
+++ b/src/bench/bench_bitcoin.cpp
@@ -27,7 +27,7 @@ main(int argc, char** argv)
{
gArgs.ParseParameters(argc, argv);
- if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help")) {
+ if (HelpRequested(gArgs)) {
std::cout << HelpMessageGroup(_("Options:"))
<< HelpMessageOpt("-?", _("Print this help message and exit"))
<< HelpMessageOpt("-list", _("List benchmarks without executing them. Can be combined with -scaling and -filter"))
diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp
index 98965840c7..4b2a0e72fe 100644
--- a/src/bench/coin_selection.cpp
+++ b/src/bench/coin_selection.cpp
@@ -4,6 +4,7 @@
#include <bench/bench.h>
#include <wallet/wallet.h>
+#include <wallet/coinselection.h>
#include <set>
@@ -44,7 +45,11 @@ static void CoinSelection(benchmark::State& state)
std::set<CInputCoin> setCoinsRet;
CAmount nValueRet;
- bool success = wallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet);
+ bool bnb_used;
+ CoinEligibilityFilter filter_standard(1, 6, 0);
+ CoinSelectionParams coin_selection_params(false, 34, 148, CFeeRate(0), 0);
+ bool success = wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)
+ || wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used);
assert(success);
assert(nValueRet == 1003 * COIN);
assert(setCoinsRet.size() == 2);
@@ -57,4 +62,47 @@ static void CoinSelection(benchmark::State& state)
}
}
+typedef std::set<CInputCoin> CoinSet;
+
+// Copied from src/wallet/test/coinselector_tests.cpp
+static void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set)
+{
+ CMutableTransaction tx;
+ tx.vout.resize(nInput + 1);
+ tx.vout[nInput].nValue = nValue;
+ set.emplace_back(MakeTransactionRef(tx), nInput);
+}
+// Copied from src/wallet/test/coinselector_tests.cpp
+static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool)
+{
+ utxo_pool.clear();
+ CAmount target = 0;
+ for (int i = 0; i < utxos; ++i) {
+ target += (CAmount)1 << (utxos+i);
+ add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);
+ add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);
+ }
+ return target;
+}
+
+static void BnBExhaustion(benchmark::State& state)
+{
+ // Setup
+ std::vector<CInputCoin> utxo_pool;
+ CoinSet selection;
+ CAmount value_ret = 0;
+ CAmount not_input_fees = 0;
+
+ while (state.KeepRunning()) {
+ // Benchmark
+ CAmount target = make_hard_case(17, utxo_pool);
+ SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees); // Should exhaust
+
+ // Cleanup
+ utxo_pool.clear();
+ selection.clear();
+ }
+}
+
BENCHMARK(CoinSelection, 650);
+BENCHMARK(BnBExhaustion, 650);
diff --git a/src/bench/lockedpool.cpp b/src/bench/lockedpool.cpp
index ca30d81e59..55a00318c1 100644
--- a/src/bench/lockedpool.cpp
+++ b/src/bench/lockedpool.cpp
@@ -43,4 +43,4 @@ static void BenchLockedPool(benchmark::State& state)
addr.clear();
}
-BENCHMARK(BenchLockedPool, 530);
+BENCHMARK(BenchLockedPool, 1300);
diff --git a/src/bench/perf.h b/src/bench/perf.h
index 681bd0c8a2..73ea8b9647 100644
--- a/src/bench/perf.h
+++ b/src/bench/perf.h
@@ -3,8 +3,8 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/** Functions for measurement of CPU cycles */
-#ifndef H_PERF
-#define H_PERF
+#ifndef BITCOIN_BENCH_PERF_H
+#define BITCOIN_BENCH_PERF_H
#include <stdint.h>
@@ -34,4 +34,4 @@ uint64_t perf_cpucycles(void);
void perf_init(void);
void perf_fini(void);
-#endif // H_PERF
+#endif // BITCOIN_BENCH_PERF_H
diff --git a/src/bench/verify_script.cpp b/src/bench/verify_script.cpp
index 29dedeef0b..705fa368a5 100644
--- a/src/bench/verify_script.cpp
+++ b/src/bench/verify_script.cpp
@@ -75,7 +75,7 @@ static void VerifyScriptBench(benchmark::State& state)
CMutableTransaction txSpend = BuildSpendingTransaction(scriptSig, txCredit);
CScriptWitness& witness = txSpend.vin[0].scriptWitness;
witness.stack.emplace_back();
- key.Sign(SignatureHash(witScriptPubkey, txSpend, 0, SIGHASH_ALL, txCredit.vout[0].nValue, SIGVERSION_WITNESS_V0), witness.stack.back(), 0);
+ key.Sign(SignatureHash(witScriptPubkey, txSpend, 0, SIGHASH_ALL, txCredit.vout[0].nValue, SigVersion::WITNESS_V0), witness.stack.back(), 0);
witness.stack.back().push_back(static_cast<unsigned char>(SIGHASH_ALL));
witness.stack.push_back(ToByteVector(pubkey));
diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
index 41f1e5786c..618b0d16bc 100644
--- a/src/bitcoin-cli.cpp
+++ b/src/bitcoin-cli.cpp
@@ -15,6 +15,7 @@
#include <util.h>
#include <utilstrencodings.h>
+#include <memory>
#include <stdio.h>
#include <event2/buffer.h>
@@ -82,7 +83,7 @@ static int AppInitRPC(int argc, char* argv[])
// Parameters
//
gArgs.ParseParameters(argc, argv);
- if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) {
+ if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!gArgs.IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
@@ -313,13 +314,11 @@ static UniValue CallRPC(BaseRequestHandler *rh, const std::string& strMethod, co
// Get credentials
std::string strRPCUserColonPass;
+ bool failedToGetAuthCookie = false;
if (gArgs.GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
- throw std::runtime_error(strprintf(
- _("Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)"),
- GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
-
+ failedToGetAuthCookie = true;
}
} else {
strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", "");
@@ -358,11 +357,21 @@ static UniValue CallRPC(BaseRequestHandler *rh, const std::string& strMethod, co
event_base_dispatch(base.get());
- if (response.status == 0)
- throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
- else if (response.status == HTTP_UNAUTHORIZED)
- throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
- else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
+ if (response.status == 0) {
+ std::string responseErrorMessage;
+ if (response.error != -1) {
+ responseErrorMessage = strprintf(" (error code %d - \"%s\")", response.error, http_errorstring(response.error));
+ }
+ throw CConnectionFailed(strprintf("Could not connect to the server %s:%d%s\n\nMake sure the bitcoind server is running and that you are connecting to the correct RPC port.", host, port, responseErrorMessage));
+ } else if (response.status == HTTP_UNAUTHORIZED) {
+ if (failedToGetAuthCookie) {
+ throw std::runtime_error(strprintf(
+ _("Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)"),
+ GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
+ } else {
+ throw std::runtime_error("Authorization failed: Incorrect rpcuser or rpcpassword");
+ }
+ } else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index fcd836fb45..65f8177daf 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -22,6 +22,7 @@
#include <utilmoneystr.h>
#include <utilstrencodings.h>
+#include <memory>
#include <stdio.h>
#include <boost/algorithm/string.hpp>
@@ -51,8 +52,7 @@ static int AppInitRawTx(int argc, char* argv[])
fCreateBlank = gArgs.GetBoolArg("-create", false);
- if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help"))
- {
+ if (argc < 2 || HelpRequested(gArgs)) {
// First part of help message is specific to this utility
std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
@@ -551,7 +551,6 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
// mergedTx will end up with all the signatures; it
// starts as a clone of the raw tx:
CMutableTransaction mergedTx(txVariants[0]);
- bool fComplete = true;
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
@@ -637,7 +636,6 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
- fComplete = false;
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
@@ -652,14 +650,6 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
for (const CTransaction& txv : txVariants)
sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
UpdateTransaction(mergedTx, i, sigdata);
-
- if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
- fComplete = false;
- }
-
- if (fComplete) {
- // do nothing... for now
- // perhaps store this for later optional JSON output
}
tx = mergedTx;
diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp
index d3eb60725f..b00c2a6308 100644
--- a/src/bitcoind.cpp
+++ b/src/bitcoind.cpp
@@ -18,6 +18,7 @@
#include <httpserver.h>
#include <httprpc.h>
#include <utilstrencodings.h>
+#include <walletinitinterface.h>
#include <boost/thread.hpp>
@@ -66,8 +67,7 @@ bool AppInit(int argc, char* argv[])
gArgs.ParseParameters(argc, argv);
// Process help and version before taking care about datadir
- if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version"))
- {
+ if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";
if (gArgs.IsArgSet("-version"))
@@ -79,7 +79,7 @@ bool AppInit(int argc, char* argv[])
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";
- strUsage += "\n" + HelpMessage(HMM_BITCOIND);
+ strUsage += "\n" + HelpMessage(HelpMessageMode::BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
diff --git a/src/blockencodings.h b/src/blockencodings.h
index ba8c1d6a2a..3a0828b307 100644
--- a/src/blockencodings.h
+++ b/src/blockencodings.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_BLOCK_ENCODINGS_H
-#define BITCOIN_BLOCK_ENCODINGS_H
+#ifndef BITCOIN_BLOCKENCODINGS_H
+#define BITCOIN_BLOCKENCODINGS_H
#include <primitives/block.h>
@@ -90,11 +90,11 @@ public:
while (txn.size() < txn_size) {
txn.resize(std::min((uint64_t)(1000 + txn.size()), txn_size));
for (; i < txn.size(); i++)
- READWRITE(REF(TransactionCompressor(txn[i])));
+ READWRITE(TransactionCompressor(txn[i]));
}
} else {
for (size_t i = 0; i < txn.size(); i++)
- READWRITE(REF(TransactionCompressor(txn[i])));
+ READWRITE(TransactionCompressor(txn[i]));
}
}
};
@@ -115,7 +115,7 @@ struct PrefilledTransaction {
if (idx > std::numeric_limits<uint16_t>::max())
throw std::ios_base::failure("index overflowed 16-bits");
index = idx;
- READWRITE(REF(TransactionCompressor(tx)));
+ READWRITE(TransactionCompressor(tx));
}
};
@@ -206,4 +206,4 @@ public:
ReadStatus FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing);
};
-#endif
+#endif // BITCOIN_BLOCKENCODINGS_H
diff --git a/src/chain.h b/src/chain.h
index 3728f768c4..757840bb23 100644
--- a/src/chain.h
+++ b/src/chain.h
@@ -91,7 +91,7 @@ struct CDiskBlockPos
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
- READWRITE(VARINT(nFile));
+ READWRITE(VARINT(nFile, VarIntMode::NONNEGATIVE_SIGNED));
READWRITE(VARINT(nPos));
}
@@ -386,13 +386,13 @@ public:
inline void SerializationOp(Stream& s, Operation ser_action) {
int _nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
- READWRITE(VARINT(_nVersion));
+ READWRITE(VARINT(_nVersion, VarIntMode::NONNEGATIVE_SIGNED));
- READWRITE(VARINT(nHeight));
+ READWRITE(VARINT(nHeight, VarIntMode::NONNEGATIVE_SIGNED));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
- READWRITE(VARINT(nFile));
+ READWRITE(VARINT(nFile, VarIntMode::NONNEGATIVE_SIGNED));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
diff --git a/src/chainparams.cpp b/src/chainparams.cpp
index c2b3480f9d..adf8e6ae5b 100644
--- a/src/chainparams.cpp
+++ b/src/chainparams.cpp
@@ -11,6 +11,7 @@
#include <utilstrencodings.h>
#include <assert.h>
+#include <memory>
#include <chainparamsseeds.h>
@@ -135,6 +136,7 @@ public:
vSeeds.emplace_back("seed.bitcoinstats.com"); // Christian Decker, supports x1 - xf
vSeeds.emplace_back("seed.bitcoin.jonasschnelli.ch"); // Jonas Schnelli, only supports x1, x5, x9, and xd
vSeeds.emplace_back("seed.btc.petertodd.org"); // Peter Todd, only supports x1, x5, x9, and xd
+ vSeeds.emplace_back("seed.bitcoin.sprovoost.nl"); // Sjors Provoost
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp
index a04258fd40..726616e650 100644
--- a/src/chainparamsbase.cpp
+++ b/src/chainparamsbase.cpp
@@ -9,6 +9,7 @@
#include <util.h>
#include <assert.h>
+#include <memory>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
diff --git a/src/checkpoints.cpp b/src/checkpoints.cpp
index 9189c9a8ad..816d854db3 100644
--- a/src/checkpoints.cpp
+++ b/src/checkpoints.cpp
@@ -21,9 +21,10 @@ namespace Checkpoints {
for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
{
const uint256& hash = i.second;
- BlockMap::const_iterator t = mapBlockIndex.find(hash);
- if (t != mapBlockIndex.end())
- return t->second;
+ CBlockIndex* pindex = LookupBlockIndex(hash);
+ if (pindex) {
+ return pindex;
+ }
}
return nullptr;
}
diff --git a/src/checkpoints.h b/src/checkpoints.h
index bf935f80a7..564b486393 100644
--- a/src/checkpoints.h
+++ b/src/checkpoints.h
@@ -19,7 +19,7 @@ struct CCheckpointData;
namespace Checkpoints
{
-//! Returns last CBlockIndex* in mapBlockIndex that is a checkpoint
+//! Returns last CBlockIndex* that is a checkpoint
CBlockIndex* GetLastCheckpoint(const CCheckpointData& data);
} //namespace Checkpoints
diff --git a/src/coins.h b/src/coins.h
index c6850947e2..a73f016a31 100644
--- a/src/coins.h
+++ b/src/coins.h
@@ -69,7 +69,7 @@ public:
::Unserialize(s, VARINT(code));
nHeight = code >> 1;
fCoinBase = code & 1;
- ::Unserialize(s, REF(CTxOutCompressor(out)));
+ ::Unserialize(s, CTxOutCompressor(out));
}
bool IsSpent() const {
diff --git a/src/compressor.cpp b/src/compressor.cpp
index 86de2900e9..da639a01af 100644
--- a/src/compressor.cpp
+++ b/src/compressor.cpp
@@ -9,7 +9,15 @@
#include <pubkey.h>
#include <script/standard.h>
-bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
+/*
+ * These check for scripts for which a special case with a shorter encoding is defined.
+ * They are implemented separately from the CScript test, as these test for exact byte
+ * sequence correspondences, and are more strict. For example, IsToPubKey also verifies
+ * whether the public key is valid (as invalid ones cannot be represented in compressed
+ * form).
+ */
+
+static bool IsToKeyID(const CScript& script, CKeyID &hash)
{
if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
&& script[2] == 20 && script[23] == OP_EQUALVERIFY
@@ -20,7 +28,7 @@ bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
return false;
}
-bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
+static bool IsToScriptID(const CScript& script, CScriptID &hash)
{
if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
&& script[22] == OP_EQUAL) {
@@ -30,7 +38,7 @@ bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
return false;
}
-bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
+static bool IsToPubKey(const CScript& script, CPubKey &pubkey)
{
if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
&& (script[1] == 0x02 || script[1] == 0x03)) {
@@ -45,24 +53,24 @@ bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
return false;
}
-bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
+bool CompressScript(const CScript& script, std::vector<unsigned char> &out)
{
CKeyID keyID;
- if (IsToKeyID(keyID)) {
+ if (IsToKeyID(script, keyID)) {
out.resize(21);
out[0] = 0x00;
memcpy(&out[1], &keyID, 20);
return true;
}
CScriptID scriptID;
- if (IsToScriptID(scriptID)) {
+ if (IsToScriptID(script, scriptID)) {
out.resize(21);
out[0] = 0x01;
memcpy(&out[1], &scriptID, 20);
return true;
}
CPubKey pubkey;
- if (IsToPubKey(pubkey)) {
+ if (IsToPubKey(script, pubkey)) {
out.resize(33);
memcpy(&out[1], &pubkey[1], 32);
if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
@@ -76,7 +84,7 @@ bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
return false;
}
-unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
+unsigned int GetSpecialScriptSize(unsigned int nSize)
{
if (nSize == 0 || nSize == 1)
return 20;
@@ -85,7 +93,7 @@ unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
return 0;
}
-bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
+bool DecompressScript(CScript& script, unsigned int nSize, const std::vector<unsigned char> &in)
{
switch(nSize) {
case 0x00:
@@ -139,7 +147,7 @@ bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigne
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
-uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
+uint64_t CompressAmount(uint64_t n)
{
if (n == 0)
return 0;
@@ -158,7 +166,7 @@ uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
}
}
-uint64_t CTxOutCompressor::DecompressAmount(uint64_t x)
+uint64_t DecompressAmount(uint64_t x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
diff --git a/src/compressor.h b/src/compressor.h
index ee26f4c533..561c8e66d0 100644
--- a/src/compressor.h
+++ b/src/compressor.h
@@ -14,6 +14,13 @@ class CKeyID;
class CPubKey;
class CScriptID;
+bool CompressScript(const CScript& script, std::vector<unsigned char> &out);
+unsigned int GetSpecialScriptSize(unsigned int nSize);
+bool DecompressScript(CScript& script, unsigned int nSize, const std::vector<unsigned char> &out);
+
+uint64_t CompressAmount(uint64_t nAmount);
+uint64_t DecompressAmount(uint64_t nAmount);
+
/** Compact serializer for scripts.
*
* It detects common cases and encodes them much more efficiently.
@@ -37,28 +44,13 @@ private:
static const unsigned int nSpecialScripts = 6;
CScript &script;
-protected:
- /**
- * These check for scripts for which a special case with a shorter encoding is defined.
- * They are implemented separately from the CScript test, as these test for exact byte
- * sequence correspondences, and are more strict. For example, IsToPubKey also verifies
- * whether the public key is valid (as invalid ones cannot be represented in compressed
- * form).
- */
- bool IsToKeyID(CKeyID &hash) const;
- bool IsToScriptID(CScriptID &hash) const;
- bool IsToPubKey(CPubKey &pubkey) const;
-
- bool Compress(std::vector<unsigned char> &out) const;
- unsigned int GetSpecialSize(unsigned int nSize) const;
- bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
public:
explicit CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
template<typename Stream>
void Serialize(Stream &s) const {
std::vector<unsigned char> compr;
- if (Compress(compr)) {
+ if (CompressScript(script, compr)) {
s << CFlatData(compr);
return;
}
@@ -72,9 +64,9 @@ public:
unsigned int nSize = 0;
s >> VARINT(nSize);
if (nSize < nSpecialScripts) {
- std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
- s >> REF(CFlatData(vch));
- Decompress(nSize, vch);
+ std::vector<unsigned char> vch(GetSpecialScriptSize(nSize), 0x00);
+ s >> CFlatData(vch);
+ DecompressScript(script, nSize, vch);
return;
}
nSize -= nSpecialScripts;
@@ -84,7 +76,7 @@ public:
s.ignore(nSize);
} else {
script.resize(nSize);
- s >> REF(CFlatData(script));
+ s >> CFlatData(script);
}
}
};
@@ -96,9 +88,6 @@ private:
CTxOut &txout;
public:
- static uint64_t CompressAmount(uint64_t nAmount);
- static uint64_t DecompressAmount(uint64_t nAmount);
-
explicit CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
ADD_SERIALIZE_METHODS;
diff --git a/src/consensus/merkle.h b/src/consensus/merkle.h
index d57bb3412e..0afb73adb5 100644
--- a/src/consensus/merkle.h
+++ b/src/consensus/merkle.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_MERKLE
-#define BITCOIN_MERKLE
+#ifndef BITCOIN_CONSENSUS_MERKLE_H
+#define BITCOIN_CONSENSUS_MERKLE_H
#include <stdint.h>
#include <vector>
@@ -35,4 +35,4 @@ uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = nullptr);
*/
std::vector<uint256> BlockMerkleBranch(const CBlock& block, uint32_t position);
-#endif
+#endif // BITCOIN_CONSENSUS_MERKLE_H
diff --git a/src/consensus/validation.h b/src/consensus/validation.h
index c2a343c155..28d3c4a119 100644
--- a/src/consensus/validation.h
+++ b/src/consensus/validation.h
@@ -101,5 +101,10 @@ static inline int64_t GetBlockWeight(const CBlock& block)
{
return ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION);
}
+static inline int64_t GetTransactionInputWeight(const CTxIn& txin)
+{
+ // scriptWitness size is added here because witnesses and txins are split up in segwit serialization.
+ return ::GetSerializeSize(txin, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(txin, SER_NETWORK, PROTOCOL_VERSION) + ::GetSerializeSize(txin.scriptWitness.stack, SER_NETWORK, PROTOCOL_VERSION);
+}
#endif // BITCOIN_CONSENSUS_VALIDATION_H
diff --git a/src/core_write.cpp b/src/core_write.cpp
index 91742b7d1b..54b18a4931 100644
--- a/src/core_write.cpp
+++ b/src/core_write.cpp
@@ -209,6 +209,6 @@ void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry,
entry.pushKV("blockhash", hashBlock.GetHex());
if (include_hex) {
- entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction".
+ entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // The hex-encoded transaction. Used the name "hex" to be consistent with the verbose output of "getrawtransaction".
}
}
diff --git a/src/cuckoocache.h b/src/cuckoocache.h
index 947e1a7185..d1de712024 100644
--- a/src/cuckoocache.h
+++ b/src/cuckoocache.h
@@ -224,7 +224,7 @@ private:
*
* Instead we treat the 32-bit random number as a Q32 fixed-point number in the range
* [0,1) and simply multiply it by the size. Then we just shift the result down by
- * 32-bits to get our bucket number. The results has non-uniformity the same as a
+ * 32-bits to get our bucket number. The result has non-uniformity the same as a
* mod, but it is much faster to compute. More about this technique can be found at
* http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
*
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index 6cac625abc..ca446c92fe 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -4,6 +4,7 @@
#include <dbwrapper.h>
+#include <memory>
#include <random.h>
#include <leveldb/cache.h>
@@ -71,6 +72,31 @@ public:
}
};
+static void SetMaxOpenFiles(leveldb::Options *options) {
+ // On most platforms the default setting of max_open_files (which is 1000)
+ // is optimal. On Windows using a large file count is OK because the handles
+ // do not interfere with select() loops. On 64-bit Unix hosts this value is
+ // also OK, because up to that amount LevelDB will use an mmap
+ // implementation that does not use extra file descriptors (the fds are
+ // closed after being mmaped).
+ //
+ // Increasing the value beyond the default is dangerous because LevelDB will
+ // fall back to a non-mmap implementation when the file count is too large.
+ // On 32-bit Unix host we should decrease the value because the handles use
+ // up real fds, and we want to avoid fd exhaustion issues.
+ //
+ // See PR #12495 for further discussion.
+
+ int default_open_files = options->max_open_files;
+#ifndef WIN32
+ if (sizeof(void*) < 8) {
+ options->max_open_files = 64;
+ }
+#endif
+ LogPrint(BCLog::LEVELDB, "LevelDB using max_open_files=%d (default=%d)\n",
+ options->max_open_files, default_open_files);
+}
+
static leveldb::Options GetOptions(size_t nCacheSize)
{
leveldb::Options options;
@@ -78,13 +104,13 @@ static leveldb::Options GetOptions(size_t nCacheSize)
options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
options.compression = leveldb::kNoCompression;
- options.max_open_files = 64;
options.info_log = new CBitcoinLevelDBLogger();
if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
// LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
// on corruption in later versions.
options.paranoid_checks = true;
}
+ SetMaxOpenFiles(&options);
return options;
}
@@ -159,12 +185,12 @@ bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
const bool log_memory = LogAcceptCategory(BCLog::LEVELDB);
double mem_before = 0;
if (log_memory) {
- mem_before = DynamicMemoryUsage() / 1024 / 1024;
+ mem_before = DynamicMemoryUsage() / 1024.0 / 1024;
}
leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
dbwrapper_private::HandleError(status);
if (log_memory) {
- double mem_after = DynamicMemoryUsage() / 1024 / 1024;
+ double mem_after = DynamicMemoryUsage() / 1024.0 / 1024;
LogPrint(BCLog::LEVELDB, "WriteBatch memory usage: db=%s, before=%.1fMiB, after=%.1fMiB\n",
m_name, mem_before, mem_after);
}
@@ -218,14 +244,10 @@ void HandleError(const leveldb::Status& status)
{
if (status.ok())
return;
- LogPrintf("%s\n", status.ToString());
- if (status.IsCorruption())
- throw dbwrapper_error("Database corrupted");
- if (status.IsIOError())
- throw dbwrapper_error("Database I/O error");
- if (status.IsNotFound())
- throw dbwrapper_error("Database entry missing");
- throw dbwrapper_error("Unknown database error");
+ const std::string errmsg = "Fatal LevelDB error: " + status.ToString();
+ LogPrintf("%s\n", errmsg);
+ LogPrintf("You can use -debug=leveldb to get more complete diagnostic messages\n");
+ throw dbwrapper_error(errmsg);
}
const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
diff --git a/src/hash.h b/src/hash.h
index 35995a2d15..75353e0c0f 100644
--- a/src/hash.h
+++ b/src/hash.h
@@ -173,7 +173,7 @@ public:
}
template<typename T>
- CHashVerifier<Source>& operator>>(T& obj)
+ CHashVerifier<Source>& operator>>(T&& obj)
{
// Unserialize from this stream
::Unserialize(*this, obj);
diff --git a/src/httprpc.cpp b/src/httprpc.cpp
index 82ae733006..de2437943e 100644
--- a/src/httprpc.cpp
+++ b/src/httprpc.cpp
@@ -17,6 +17,8 @@
#include <crypto/hmac_sha256.h>
#include <stdio.h>
+#include <memory>
+
#include <boost/algorithm/string.hpp> // boost::trim
/** WWW-Authenticate to present with 401 Unauthorized response */
@@ -158,8 +160,9 @@ static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
}
JSONRPCRequest jreq;
+ jreq.peerAddr = req->GetPeer().ToString();
if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
- LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString());
+ LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", jreq.peerAddr);
/* Deter brute-forcing
If this results in a DoS the user really
@@ -252,6 +255,9 @@ void StopHTTPRPC()
{
LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
UnregisterHTTPHandler("/", true);
+#ifdef ENABLE_WALLET
+ UnregisterHTTPHandler("/wallet/", false);
+#endif
if (httpRPCTimerInterface) {
RPCUnsetTimerInterface(httpRPCTimerInterface.get());
httpRPCTimerInterface.reset();
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 36db530c82..b8b338dfbc 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -13,6 +13,7 @@
#include <sync.h>
#include <ui_interface.h>
+#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/src/init.cpp b/src/init.cpp
index 659f97fec6..880c8bce1e 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -43,10 +43,8 @@
#include <util.h>
#include <utilmoneystr.h>
#include <validationinterface.h>
-#ifdef ENABLE_WALLET
-#include <wallet/init.h>
-#endif
#include <warnings.h>
+#include <walletinitinterface.h>
#include <stdint.h>
#include <stdio.h>
#include <memory>
@@ -75,6 +73,25 @@ static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
std::unique_ptr<CConnman> g_connman;
std::unique_ptr<PeerLogicValidation> peerLogic;
+#if !(ENABLE_WALLET)
+class DummyWalletInit : public WalletInitInterface {
+public:
+
+ std::string GetHelpString(bool showDebug) override {return std::string{};}
+ bool ParameterInteraction() override {return true;}
+ void RegisterRPC(CRPCTable &) override {}
+ bool Verify() override {return true;}
+ bool Open() override {return true;}
+ void Start(CScheduler& scheduler) override {}
+ void Flush() override {}
+ void Stop() override {}
+ void Close() override {}
+};
+
+static DummyWalletInit g_dummy_wallet_init;
+WalletInitInterface* const g_wallet_init_interface = &g_dummy_wallet_init;
+#endif
+
#if ENABLE_ZMQ
static CZMQNotificationInterface* pzmqNotificationInterface = nullptr;
#endif
@@ -116,7 +133,6 @@ static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
//
std::atomic<bool> fRequestShutdown(false);
-std::atomic<bool> fDumpMempoolLater(false);
void StartShutdown()
{
@@ -189,9 +205,7 @@ void Shutdown()
StopREST();
StopRPC();
StopHTTPServer();
-#ifdef ENABLE_WALLET
- FlushWallets();
-#endif
+ g_wallet_init_interface->Flush();
StopMapPort();
// Because these depend on each-other, we make sure that neither can be
@@ -208,7 +222,7 @@ void Shutdown()
threadGroup.interrupt_all();
threadGroup.join_all();
- if (fDumpMempoolLater && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
+ if (g_is_mempool_loaded && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
DumpMempool();
}
@@ -249,9 +263,7 @@ void Shutdown()
pcoinsdbview.reset();
pblocktree.reset();
}
-#ifdef ENABLE_WALLET
- StopWallets();
-#endif
+ g_wallet_init_interface->Stop();
#if ENABLE_ZMQ
if (pzmqNotificationInterface) {
@@ -271,9 +283,7 @@ void Shutdown()
UnregisterAllValidationInterfaces();
GetMainSignals().UnregisterBackgroundSignalScheduler();
GetMainSignals().UnregisterWithMempoolSignals(mempool);
-#ifdef ENABLE_WALLET
- CloseWallets();
-#endif
+ g_wallet_init_interface->Close();
globalVerifyHandle.reset();
ECC_Stop();
LogPrintf("%s: done\n", __func__);
@@ -333,12 +343,13 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-version", _("Print version and exit"));
strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
strUsage +=HelpMessageOpt("-assumevalid=<hex>", strprintf(_("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)"), defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()));
+ strUsage += HelpMessageOpt("-blocksdir=<dir>", _("Specify blocks directory (default: <datadir>/blocks)"));
strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
if (showDebug)
strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)"), BITCOIN_CONF_FILENAME));
- if (mode == HMM_BITCOIND)
+ if (mode == HelpMessageMode::BITCOIND)
{
#if HAVE_DECL_DAEMON
strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
@@ -415,9 +426,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-whitelist=<IP address or network>", _("Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.") +
" " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway"));
-#ifdef ENABLE_WALLET
- strUsage += GetWalletHelpString(showDebug);
-#endif
+ strUsage += g_wallet_init_interface->GetHelpString(showDebug);
#if ENABLE_ZMQ
strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
@@ -428,18 +437,16 @@ std::string HelpMessage(HelpMessageMode mode)
#endif
strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
- if (showDebug)
- {
+ if (showDebug) {
strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
- strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
+ strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
strUsage += HelpMessageOpt("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used");
strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
- strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
@@ -491,8 +498,6 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
strUsage += HelpMessageGroup(_("Block creation options:"));
- if (showDebug)
- strUsage += HelpMessageOpt("-blockmaxsize=<n>", "Set maximum BIP141 block weight to this * 4. Deprecated, use blockmaxweight");
strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
strUsage += HelpMessageOpt("-blockmintxfee=<amt>", strprintf(_("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)));
if (showDebug)
@@ -596,7 +601,7 @@ void CleanupBlockRevFiles()
// Remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index.
LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
- fs::path blocksdir = GetDataDir() / "blocks";
+ fs::path blocksdir = GetBlocksDir();
for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
if (fs::is_regular_file(*it) &&
it->path().filename().string().length() == 12 &&
@@ -680,7 +685,7 @@ void ThreadImport(std::vector<fs::path> vImportFiles)
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ActivateBestChain(state, chainparams)) {
- LogPrintf("Failed to connect best block");
+ LogPrintf("Failed to connect best block\n");
StartShutdown();
return;
}
@@ -693,8 +698,8 @@ void ThreadImport(std::vector<fs::path> vImportFiles)
} // End scope of CImportingNow
if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
LoadMempool();
- fDumpMempoolLater = !fRequestShutdown;
}
+ g_is_mempool_loaded = !fRequestShutdown;
}
/** Sanity checks
@@ -798,15 +803,6 @@ void InitParameterInteraction()
if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
}
-
- if (gArgs.IsArgSet("-blockmaxsize")) {
- unsigned int max_size = gArgs.GetArg("-blockmaxsize", 0);
- if (gArgs.SoftSetArg("blockmaxweight", strprintf("%d", max_size * WITNESS_SCALE_FACTOR))) {
- LogPrintf("%s: parameter interaction: -blockmaxsize=%d -> setting -blockmaxweight=%d (-blockmaxsize is deprecated!)\n", __func__, max_size, max_size * WITNESS_SCALE_FACTOR);
- } else {
- LogPrintf("%s: Ignoring blockmaxsize setting which is overridden by blockmaxweight", __func__);
- }
- }
}
static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
@@ -908,6 +904,10 @@ bool AppInitParameterInteraction()
// also see: InitParameterInteraction()
+ if (!fs::is_directory(GetBlocksDir(false))) {
+ return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist.\n"), gArgs.GetArg("-blocksdir", "").c_str()));
+ }
+
// if using block pruning, then disallow txindex
if (gArgs.GetArg("-prune", 0)) {
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
@@ -1093,10 +1093,7 @@ bool AppInitParameterInteraction()
return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
-#ifdef ENABLE_WALLET
- if (!WalletParameterInteraction())
- return false;
-#endif
+ if (!g_wallet_init_interface->ParameterInteraction()) return false;
fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
@@ -1165,6 +1162,9 @@ static bool LockDataDirectory(bool probeOnly)
{
// Make sure only a single Bitcoin process is using the data directory.
fs::path datadir = GetDataDir();
+ if (!DirIsWritable(datadir)) {
+ return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string()));
+ }
if (!LockDirectory(datadir, ".lock", probeOnly)) {
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), _(PACKAGE_NAME)));
}
@@ -1224,7 +1224,7 @@ bool AppInitMain()
}
if (!fLogTimestamps)
- LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
+ LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
LogPrintf("Using data directory %s\n", GetDataDir().string());
LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
@@ -1259,9 +1259,7 @@ bool AppInitMain()
* available in the GUI RPC console even if external calls are disabled.
*/
RegisterAllCoreRPCCommands(tableRPC);
-#ifdef ENABLE_WALLET
- RegisterWalletRPC(tableRPC);
-#endif
+ g_wallet_init_interface->RegisterRPC(tableRPC);
/* Start the RPC server already. It will be started in "warmup" mode
* and not really process calls already (but it will signify connections
@@ -1278,10 +1276,8 @@ bool AppInitMain()
int64_t nStart;
// ********************************************************* Step 5: verify wallet database integrity
-#ifdef ENABLE_WALLET
- if (!VerifyWallets())
- return false;
-#endif
+ if (!g_wallet_init_interface->Verify()) return false;
+
// ********************************************************* Step 6: network initialization
// Note that we absolutely cannot open any actual connections
// until the very end ("start node") as the UTXO/block state
@@ -1424,6 +1420,8 @@ bool AppInitMain()
uiInterface.InitMessage(_("Loading block index..."));
+ LOCK(cs_main);
+
nStart = GetTimeMillis();
do {
try {
@@ -1457,8 +1455,9 @@ bool AppInitMain()
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
- if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
+ if (!mapBlockIndex.empty() && !LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
+ }
// Check for changed -txindex state
if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
@@ -1532,16 +1531,13 @@ bool AppInitMain()
MIN_BLOCKS_TO_KEEP);
}
- {
- LOCK(cs_main);
- CBlockIndex* tip = chainActive.Tip();
- RPCNotifyBlockChange(true, tip);
- if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
- strLoadError = _("The block database contains a block which appears to be from the future. "
- "This may be due to your computer's date and time being set incorrectly. "
- "Only rebuild the block database if you are sure that your computer's date and time are correct");
- break;
- }
+ CBlockIndex* tip = chainActive.Tip();
+ RPCNotifyBlockChange(true, tip);
+ if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
+ strLoadError = _("The block database contains a block which appears to be from the future. "
+ "This may be due to your computer's date and time being set incorrectly. "
+ "Only rebuild the block database if you are sure that your computer's date and time are correct");
+ break;
}
if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
@@ -1599,12 +1595,7 @@ bool AppInitMain()
fFeeEstimatesInitialized = true;
// ********************************************************* Step 8: load wallet
-#ifdef ENABLE_WALLET
- if (!OpenWallets())
- return false;
-#else
- LogPrintf("No wallet support compiled in!\n");
-#endif
+ if (!g_wallet_init_interface->Open()) return false;
// ********************************************************* Step 9: data directory maintenance
@@ -1630,7 +1621,7 @@ bool AppInitMain()
// ********************************************************* Step 10: import blocks
- if (!CheckDiskSpace())
+ if (!CheckDiskSpace() && !CheckDiskSpace(0, true))
return false;
// Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
@@ -1750,9 +1741,7 @@ bool AppInitMain()
SetRPCWarmupFinished();
uiInterface.InitMessage(_("Done loading"));
-#ifdef ENABLE_WALLET
- StartWallets(scheduler);
-#endif
+ g_wallet_init_interface->Start(scheduler);
return true;
}
diff --git a/src/init.h b/src/init.h
index 33f97a55a5..829c110112 100644
--- a/src/init.h
+++ b/src/init.h
@@ -6,11 +6,15 @@
#ifndef BITCOIN_INIT_H
#define BITCOIN_INIT_H
+#include <memory>
#include <string>
class CScheduler;
class CWallet;
+class WalletInitInterface;
+extern WalletInitInterface* const g_wallet_init_interface;
+
namespace boost
{
class thread_group;
@@ -57,9 +61,9 @@ bool AppInitLockDataDirectory();
bool AppInitMain();
/** The help message mode determines what help message to show */
-enum HelpMessageMode {
- HMM_BITCOIND,
- HMM_BITCOIN_QT
+enum class HelpMessageMode {
+ BITCOIND,
+ BITCOIN_QT
};
/** Help for options shared between UI and daemon (for -help) */
diff --git a/src/interface/README.md b/src/interface/README.md
new file mode 100644
index 0000000000..e93b91d23c
--- /dev/null
+++ b/src/interface/README.md
@@ -0,0 +1,17 @@
+# Internal c++ interfaces
+
+The following interfaces are defined here:
+
+* [`Chain`](chain.h) — used by wallet to access blockchain and mempool state. Added in [#10973](https://github.com/bitcoin/bitcoin/pull/10973).
+
+* [`Chain::Client`](chain.h) — used by node to start & stop `Chain` clients. Added in [#10973](https://github.com/bitcoin/bitcoin/pull/10973).
+
+* [`Node`](node.h) — used by GUI to start & stop bitcoin node. Added in [#10244](https://github.com/bitcoin/bitcoin/pull/10244).
+
+* [`Wallet`](wallet.h) — used by GUI to access wallets. Added in [#10244](https://github.com/bitcoin/bitcoin/pull/10244).
+
+* [`Handler`](handler.h) — returned by `handleEvent` methods on interfaces above and used to manage lifetimes of event handlers.
+
+* [`Init`](init.h) — used by multiprocess code to access interfaces above on startup. Added in [#10102](https://github.com/bitcoin/bitcoin/pull/10102).
+
+The interfaces above define boundaries between major components of bitcoin code (node, wallet, and gui), making it possible for them to run in different processes, and be tested, developed, and understood independently. These interfaces are not currently designed to be stable or to be used externally.
diff --git a/src/interface/handler.cpp b/src/interface/handler.cpp
new file mode 100644
index 0000000000..4b27f374f4
--- /dev/null
+++ b/src/interface/handler.cpp
@@ -0,0 +1,33 @@
+// Copyright (c) 2018 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <interface/handler.h>
+
+#include <util.h>
+
+#include <boost/signals2/connection.hpp>
+#include <memory>
+#include <utility>
+
+namespace interface {
+namespace {
+
+class HandlerImpl : public Handler
+{
+public:
+ HandlerImpl(boost::signals2::connection connection) : m_connection(std::move(connection)) {}
+
+ void disconnect() override { m_connection.disconnect(); }
+
+ boost::signals2::scoped_connection m_connection;
+};
+
+} // namespace
+
+std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection)
+{
+ return MakeUnique<HandlerImpl>(std::move(connection));
+}
+
+} // namespace interface
diff --git a/src/interface/handler.h b/src/interface/handler.h
new file mode 100644
index 0000000000..a76334bfbf
--- /dev/null
+++ b/src/interface/handler.h
@@ -0,0 +1,35 @@
+// Copyright (c) 2018 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_INTERFACE_HANDLER_H
+#define BITCOIN_INTERFACE_HANDLER_H
+
+#include <memory>
+
+namespace boost {
+namespace signals2 {
+class connection;
+} // namespace signals2
+} // namespace boost
+
+namespace interface {
+
+//! Generic interface for managing an event handler or callback function
+//! registered with another interface. Has a single disconnect method to cancel
+//! the registration and prevent any future notifications.
+class Handler
+{
+public:
+ virtual ~Handler() {}
+
+ //! Disconnect the handler.
+ virtual void disconnect() = 0;
+};
+
+//! Return handler wrapping a boost signal connection.
+std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection);
+
+} // namespace interface
+
+#endif // BITCOIN_INTERFACE_HANDLER_H
diff --git a/src/interface/node.cpp b/src/interface/node.cpp
new file mode 100644
index 0000000000..f04da4e176
--- /dev/null
+++ b/src/interface/node.cpp
@@ -0,0 +1,308 @@
+// Copyright (c) 2018 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <interface/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 <net.h>
+#include <net_processing.h>
+#include <netaddress.h>
+#include <netbase.h>
+#include <policy/feerate.h>
+#include <policy/fees.h>
+#include <policy/policy.h>
+#include <primitives/block.h>
+#include <rpc/server.h>
+#include <scheduler.h>
+#include <sync.h>
+#include <txmempool.h>
+#include <ui_interface.h>
+#include <util.h>
+#include <validation.h>
+#include <warnings.h>
+
+#if defined(HAVE_CONFIG_H)
+#include <config/bitcoin-config.h>
+#endif
+#ifdef ENABLE_WALLET
+#include <wallet/fees.h>
+#include <wallet/wallet.h>
+#define CHECK_WALLET(x) x
+#else
+#define CHECK_WALLET(x) throw std::logic_error("Wallet function called in non-wallet build.")
+#endif
+
+#include <atomic>
+#include <boost/thread/thread.hpp>
+#include <univalue.h>
+
+namespace interface {
+namespace {
+
+class NodeImpl : public Node
+{
+ void parseParameters(int argc, const char* const argv[]) override
+ {
+ gArgs.ParseParameters(argc, argv);
+ }
+ void readConfigFile(const std::string& conf_path) override { gArgs.ReadConfigFile(conf_path); }
+ bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); }
+ bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); }
+ void selectParams(const std::string& network) override { SelectParams(network); }
+ std::string getNetwork() override { return Params().NetworkIDString(); }
+ void initLogging() override { InitLogging(); }
+ void initParameterInteraction() override { InitParameterInteraction(); }
+ std::string getWarnings(const std::string& type) override { return GetWarnings(type); }
+ uint32_t getLogCategories() override { return ::logCategories; }
+ bool baseInitialize() override
+ {
+ return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() &&
+ AppInitLockDataDirectory();
+ }
+ bool appInitMain() override { return AppInitMain(); }
+ void appShutdown() override
+ {
+ Interrupt();
+ Shutdown();
+ }
+ void startShutdown() override { StartShutdown(); }
+ bool shutdownRequested() override { return ShutdownRequested(); }
+ void mapPort(bool use_upnp) override
+ {
+ if (use_upnp) {
+ StartMapPort();
+ } else {
+ InterruptMapPort();
+ StopMapPort();
+ }
+ }
+ std::string helpMessage(HelpMessageMode mode) override { return HelpMessage(mode); }
+ bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); }
+ size_t getNodeCount(CConnman::NumConnections flags) override
+ {
+ return g_connman ? g_connman->GetNodeCount(flags) : 0;
+ }
+ bool getNodesStats(NodesStats& stats) override
+ {
+ stats.clear();
+
+ if (g_connman) {
+ std::vector<CNodeStats> stats_temp;
+ g_connman->GetNodeStats(stats_temp);
+
+ stats.reserve(stats_temp.size());
+ for (auto& node_stats_temp : stats_temp) {
+ stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
+ }
+
+ // Try to retrieve the CNodeStateStats for each node.
+ TRY_LOCK(::cs_main, lockMain);
+ if (lockMain) {
+ for (auto& node_stats : stats) {
+ std::get<1>(node_stats) =
+ GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ bool getBanned(banmap_t& banmap) override
+ {
+ if (g_connman) {
+ g_connman->GetBanned(banmap);
+ return true;
+ }
+ return false;
+ }
+ bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override
+ {
+ if (g_connman) {
+ g_connman->Ban(net_addr, reason, ban_time_offset);
+ return true;
+ }
+ return false;
+ }
+ bool unban(const CSubNet& ip) override
+ {
+ if (g_connman) {
+ g_connman->Unban(ip);
+ return true;
+ }
+ return false;
+ }
+ bool disconnect(NodeId id) override
+ {
+ if (g_connman) {
+ return g_connman->DisconnectNode(id);
+ }
+ return false;
+ }
+ int64_t getTotalBytesRecv() override { return g_connman ? g_connman->GetTotalBytesRecv() : 0; }
+ int64_t getTotalBytesSent() override { return g_connman ? g_connman->GetTotalBytesSent() : 0; }
+ size_t getMempoolSize() override { return ::mempool.size(); }
+ size_t getMempoolDynamicUsage() override { return ::mempool.DynamicMemoryUsage(); }
+ bool getHeaderTip(int& height, int64_t& block_time) override
+ {
+ LOCK(::cs_main);
+ if (::pindexBestHeader) {
+ height = ::pindexBestHeader->nHeight;
+ block_time = ::pindexBestHeader->GetBlockTime();
+ return true;
+ }
+ return false;
+ }
+ int getNumBlocks() override
+ {
+ LOCK(::cs_main);
+ return ::chainActive.Height();
+ }
+ int64_t getLastBlockTime() override
+ {
+ LOCK(::cs_main);
+ if (::chainActive.Tip()) {
+ return ::chainActive.Tip()->GetBlockTime();
+ }
+ return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
+ }
+ double getVerificationProgress() override
+ {
+ const CBlockIndex* tip;
+ {
+ LOCK(::cs_main);
+ tip = ::chainActive.Tip();
+ }
+ return GuessVerificationProgress(Params().TxData(), tip);
+ }
+ bool isInitialBlockDownload() override { return IsInitialBlockDownload(); }
+ bool getReindex() override { return ::fReindex; }
+ bool getImporting() override { return ::fImporting; }
+ void setNetworkActive(bool active) override
+ {
+ if (g_connman) {
+ g_connman->SetNetworkActive(active);
+ }
+ }
+ bool getNetworkActive() override { return g_connman && g_connman->GetNetworkActive(); }
+ unsigned int getTxConfirmTarget() override { CHECK_WALLET(return ::nTxConfirmTarget); }
+ CAmount getRequiredFee(unsigned int tx_bytes) override { CHECK_WALLET(return GetRequiredFee(tx_bytes)); }
+ CAmount getMinimumFee(unsigned int tx_bytes,
+ const CCoinControl& coin_control,
+ int* returned_target,
+ FeeReason* reason) override
+ {
+ FeeCalculation fee_calc;
+ CAmount result;
+ CHECK_WALLET(result = GetMinimumFee(tx_bytes, coin_control, ::mempool, ::feeEstimator, &fee_calc));
+ if (returned_target) *returned_target = fee_calc.returnedTarget;
+ if (reason) *reason = fee_calc.reason;
+ return result;
+ }
+ CAmount getMaxTxFee() override { return ::maxTxFee; }
+ CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override
+ {
+ FeeCalculation fee_calc;
+ CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative);
+ if (returned_target) {
+ *returned_target = fee_calc.returnedTarget;
+ }
+ return result;
+ }
+ CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
+ CFeeRate getFallbackFee() override { CHECK_WALLET(return CWallet::fallbackFee); }
+ CFeeRate getPayTxFee() override { CHECK_WALLET(return ::payTxFee); }
+ void setPayTxFee(CFeeRate rate) override { CHECK_WALLET(::payTxFee = rate); }
+ UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
+ {
+ JSONRPCRequest req;
+ req.params = params;
+ req.strMethod = command;
+ req.URI = uri;
+ return ::tableRPC.execute(req);
+ }
+ std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
+ void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
+ void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
+ bool getUnspentOutput(const COutPoint& output, Coin& coin) override
+ {
+ LOCK(::cs_main);
+ return ::pcoinsTip->GetCoin(output, coin);
+ }
+ std::vector<std::unique_ptr<Wallet>> getWallets() override
+ {
+#ifdef ENABLE_WALLET
+ std::vector<std::unique_ptr<Wallet>> wallets;
+ for (CWalletRef wallet : ::vpwallets) {
+ wallets.emplace_back(MakeWallet(*wallet));
+ }
+ return wallets;
+#else
+ throw std::logic_error("Node::getWallets() called in non-wallet build.");
+#endif
+ }
+ std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
+ {
+ return MakeHandler(::uiInterface.InitMessage.connect(fn));
+ }
+ std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
+ {
+ return MakeHandler(::uiInterface.ThreadSafeMessageBox.connect(fn));
+ }
+ std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
+ {
+ return MakeHandler(::uiInterface.ThreadSafeQuestion.connect(fn));
+ }
+ std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
+ {
+ return MakeHandler(::uiInterface.ShowProgress.connect(fn));
+ }
+ std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
+ {
+ CHECK_WALLET(
+ return MakeHandler(::uiInterface.LoadWallet.connect([fn](CWallet* wallet) { fn(MakeWallet(*wallet)); })));
+ }
+ std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
+ {
+ return MakeHandler(::uiInterface.NotifyNumConnectionsChanged.connect(fn));
+ }
+ std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
+ {
+ return MakeHandler(::uiInterface.NotifyNetworkActiveChanged.connect(fn));
+ }
+ std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
+ {
+ return MakeHandler(::uiInterface.NotifyAlertChanged.connect(fn));
+ }
+ std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
+ {
+ return MakeHandler(::uiInterface.BannedListChanged.connect(fn));
+ }
+ std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
+ {
+ return MakeHandler(::uiInterface.NotifyBlockTip.connect([fn](bool initial_download, const CBlockIndex* block) {
+ fn(initial_download, block->nHeight, block->GetBlockTime(),
+ GuessVerificationProgress(Params().TxData(), block));
+ }));
+ }
+ std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
+ {
+ return MakeHandler(
+ ::uiInterface.NotifyHeaderTip.connect([fn](bool initial_download, const CBlockIndex* block) {
+ fn(initial_download, block->nHeight, block->GetBlockTime(),
+ GuessVerificationProgress(Params().TxData(), block));
+ }));
+ }
+};
+
+} // namespace
+
+std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
+
+} // namespace interface
diff --git a/src/interface/node.h b/src/interface/node.h
new file mode 100644
index 0000000000..6ae7f9e46c
--- /dev/null
+++ b/src/interface/node.h
@@ -0,0 +1,259 @@
+// Copyright (c) 2018 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_INTERFACE_NODE_H
+#define BITCOIN_INTERFACE_NODE_H
+
+#include <addrdb.h> // For banmap_t
+#include <amount.h> // For CAmount
+#include <init.h> // For HelpMessageMode
+#include <net.h> // For CConnman::NumConnections
+#include <netaddress.h> // For Network
+
+#include <functional>
+#include <memory>
+#include <stddef.h>
+#include <stdint.h>
+#include <string>
+#include <tuple>
+#include <vector>
+
+class CCoinControl;
+class CFeeRate;
+class CNodeStats;
+class Coin;
+class RPCTimerInterface;
+class UniValue;
+class proxyType;
+enum class FeeReason;
+struct CNodeStateStats;
+
+namespace interface {
+
+class Handler;
+class Wallet;
+
+//! Top-level interface for a bitcoin node (bitcoind process).
+class Node
+{
+public:
+ virtual ~Node() {}
+
+ //! Set command line arguments.
+ virtual void parseParameters(int argc, const char* const argv[]) = 0;
+
+ //! Set a command line argument if it doesn't already have a value
+ virtual bool softSetArg(const std::string& arg, const std::string& value) = 0;
+
+ //! Set a command line boolean argument if it doesn't already have a value
+ virtual bool softSetBoolArg(const std::string& arg, bool value) = 0;
+
+ //! Load settings from configuration file.
+ virtual void readConfigFile(const std::string& conf_path) = 0;
+
+ //! Choose network parameters.
+ virtual void selectParams(const std::string& network) = 0;
+
+ //! Get network name.
+ virtual std::string getNetwork() = 0;
+
+ //! Init logging.
+ virtual void initLogging() = 0;
+
+ //! Init parameter interaction.
+ virtual void initParameterInteraction() = 0;
+
+ //! Get warnings.
+ virtual std::string getWarnings(const std::string& type) = 0;
+
+ // Get log flags.
+ virtual uint32_t getLogCategories() = 0;
+
+ //! Initialize app dependencies.
+ virtual bool baseInitialize() = 0;
+
+ //! Start node.
+ virtual bool appInitMain() = 0;
+
+ //! Stop node.
+ virtual void appShutdown() = 0;
+
+ //! Start shutdown.
+ virtual void startShutdown() = 0;
+
+ //! Return whether shutdown was requested.
+ virtual bool shutdownRequested() = 0;
+
+ //! Get help message string.
+ virtual std::string helpMessage(HelpMessageMode mode) = 0;
+
+ //! Map port.
+ virtual void mapPort(bool use_upnp) = 0;
+
+ //! Get proxy.
+ virtual bool getProxy(Network net, proxyType& proxy_info) = 0;
+
+ //! Get number of connections.
+ virtual size_t getNodeCount(CConnman::NumConnections flags) = 0;
+
+ //! Get stats for connected nodes.
+ using NodesStats = std::vector<std::tuple<CNodeStats, bool, CNodeStateStats>>;
+ virtual bool getNodesStats(NodesStats& stats) = 0;
+
+ //! Get ban map entries.
+ virtual bool getBanned(banmap_t& banmap) = 0;
+
+ //! Ban node.
+ virtual bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) = 0;
+
+ //! Unban node.
+ virtual bool unban(const CSubNet& ip) = 0;
+
+ //! Disconnect node.
+ virtual bool disconnect(NodeId id) = 0;
+
+ //! Get total bytes recv.
+ virtual int64_t getTotalBytesRecv() = 0;
+
+ //! Get total bytes sent.
+ virtual int64_t getTotalBytesSent() = 0;
+
+ //! Get mempool size.
+ virtual size_t getMempoolSize() = 0;
+
+ //! Get mempool dynamic usage.
+ virtual size_t getMempoolDynamicUsage() = 0;
+
+ //! Get header tip height and time.
+ virtual bool getHeaderTip(int& height, int64_t& block_time) = 0;
+
+ //! Get num blocks.
+ virtual int getNumBlocks() = 0;
+
+ //! Get last block time.
+ virtual int64_t getLastBlockTime() = 0;
+
+ //! Get verification progress.
+ virtual double getVerificationProgress() = 0;
+
+ //! Is initial block download.
+ virtual bool isInitialBlockDownload() = 0;
+
+ //! Get reindex.
+ virtual bool getReindex() = 0;
+
+ //! Get importing.
+ virtual bool getImporting() = 0;
+
+ //! Set network active.
+ virtual void setNetworkActive(bool active) = 0;
+
+ //! Get network active.
+ virtual bool getNetworkActive() = 0;
+
+ //! Get tx confirm target.
+ virtual unsigned int getTxConfirmTarget() = 0;
+
+ //! Get required fee.
+ virtual CAmount getRequiredFee(unsigned int tx_bytes) = 0;
+
+ //! Get minimum fee.
+ virtual CAmount getMinimumFee(unsigned int tx_bytes,
+ const CCoinControl& coin_control,
+ int* returned_target,
+ FeeReason* reason) = 0;
+
+ //! Get max tx fee.
+ virtual CAmount getMaxTxFee() = 0;
+
+ //! Estimate smart fee.
+ virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) = 0;
+
+ //! Get dust relay fee.
+ virtual CFeeRate getDustRelayFee() = 0;
+
+ //! Get fallback fee.
+ virtual CFeeRate getFallbackFee() = 0;
+
+ //! Get pay tx fee.
+ virtual CFeeRate getPayTxFee() = 0;
+
+ //! Set pay tx fee.
+ virtual void setPayTxFee(CFeeRate rate) = 0;
+
+ //! Execute rpc command.
+ virtual UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) = 0;
+
+ //! List rpc commands.
+ virtual std::vector<std::string> listRpcCommands() = 0;
+
+ //! Set RPC timer interface if unset.
+ virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) = 0;
+
+ //! Unset RPC timer interface.
+ virtual void rpcUnsetTimerInterface(RPCTimerInterface* iface) = 0;
+
+ //! Get unspent outputs associated with a transaction.
+ virtual bool getUnspentOutput(const COutPoint& output, Coin& coin) = 0;
+
+ //! Return interfaces for accessing wallets (if any).
+ virtual std::vector<std::unique_ptr<Wallet>> getWallets() = 0;
+
+ //! Register handler for init messages.
+ using InitMessageFn = std::function<void(const std::string& message)>;
+ virtual std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) = 0;
+
+ //! Register handler for message box messages.
+ using MessageBoxFn =
+ std::function<bool(const std::string& message, const std::string& caption, unsigned int style)>;
+ virtual std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) = 0;
+
+ //! Register handler for question messages.
+ using QuestionFn = std::function<bool(const std::string& message,
+ const std::string& non_interactive_message,
+ const std::string& caption,
+ unsigned int style)>;
+ virtual std::unique_ptr<Handler> handleQuestion(QuestionFn fn) = 0;
+
+ //! Register handler for progress messages.
+ using ShowProgressFn = std::function<void(const std::string& title, int progress, bool resume_possible)>;
+ virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0;
+
+ //! Register handler for load wallet messages.
+ using LoadWalletFn = std::function<void(std::unique_ptr<Wallet> wallet)>;
+ virtual std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) = 0;
+
+ //! Register handler for number of connections changed messages.
+ using NotifyNumConnectionsChangedFn = std::function<void(int new_num_connections)>;
+ virtual std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) = 0;
+
+ //! Register handler for network active messages.
+ using NotifyNetworkActiveChangedFn = std::function<void(bool network_active)>;
+ virtual std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) = 0;
+
+ //! Register handler for notify alert messages.
+ using NotifyAlertChangedFn = std::function<void()>;
+ virtual std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) = 0;
+
+ //! Register handler for ban list messages.
+ using BannedListChangedFn = std::function<void()>;
+ virtual std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) = 0;
+
+ //! Register handler for block tip messages.
+ using NotifyBlockTipFn =
+ std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>;
+ virtual std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) = 0;
+
+ //! Register handler for header tip messages.
+ using NotifyHeaderTipFn =
+ std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>;
+ virtual std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) = 0;
+};
+
+//! Return implementation of Node interface.
+std::unique_ptr<Node> MakeNode();
+
+} // namespace interface
+
+#endif // BITCOIN_INTERFACE_NODE_H
diff --git a/src/interface/wallet.cpp b/src/interface/wallet.cpp
new file mode 100644
index 0000000000..a6bce7d3de
--- /dev/null
+++ b/src/interface/wallet.cpp
@@ -0,0 +1,441 @@
+// Copyright (c) 2018 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <interface/wallet.h>
+
+#include <amount.h>
+#include <chain.h>
+#include <consensus/validation.h>
+#include <interface/handler.h>
+#include <net.h>
+#include <policy/policy.h>
+#include <primitives/transaction.h>
+#include <script/ismine.h>
+#include <script/standard.h>
+#include <support/allocators/secure.h>
+#include <sync.h>
+#include <timedata.h>
+#include <ui_interface.h>
+#include <uint256.h>
+#include <validation.h>
+#include <wallet/feebumper.h>
+#include <wallet/wallet.h>
+
+#include <memory>
+
+namespace interface {
+namespace {
+
+class PendingWalletTxImpl : public PendingWalletTx
+{
+public:
+ PendingWalletTxImpl(CWallet& wallet) : m_wallet(wallet), m_key(&wallet) {}
+
+ const CTransaction& get() override { return *m_tx; }
+
+ int64_t getVirtualSize() override { return GetVirtualTransactionSize(*m_tx); }
+
+ bool commit(WalletValueMap value_map,
+ WalletOrderForm order_form,
+ std::string from_account,
+ std::string& reject_reason) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ CValidationState state;
+ if (!m_wallet.CommitTransaction(m_tx, std::move(value_map), std::move(order_form), std::move(from_account), m_key, g_connman.get(), state)) {
+ reject_reason = state.GetRejectReason();
+ return false;
+ }
+ return true;
+ }
+
+ CTransactionRef m_tx;
+ CWallet& m_wallet;
+ CReserveKey m_key;
+};
+
+//! Construct wallet tx struct.
+WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx)
+{
+ WalletTx result;
+ result.tx = wtx.tx;
+ result.txin_is_mine.reserve(wtx.tx->vin.size());
+ for (const auto& txin : wtx.tx->vin) {
+ result.txin_is_mine.emplace_back(wallet.IsMine(txin));
+ }
+ result.txout_is_mine.reserve(wtx.tx->vout.size());
+ result.txout_address.reserve(wtx.tx->vout.size());
+ result.txout_address_is_mine.reserve(wtx.tx->vout.size());
+ for (const auto& txout : wtx.tx->vout) {
+ result.txout_is_mine.emplace_back(wallet.IsMine(txout));
+ result.txout_address.emplace_back();
+ result.txout_address_is_mine.emplace_back(ExtractDestination(txout.scriptPubKey, result.txout_address.back()) ?
+ IsMine(wallet, result.txout_address.back()) :
+ ISMINE_NO);
+ }
+ result.credit = wtx.GetCredit(ISMINE_ALL);
+ result.debit = wtx.GetDebit(ISMINE_ALL);
+ result.change = wtx.GetChange();
+ result.time = wtx.GetTxTime();
+ result.value_map = wtx.mapValue;
+ result.is_coinbase = wtx.IsCoinBase();
+ return result;
+}
+
+//! Construct wallet tx status struct.
+WalletTxStatus MakeWalletTxStatus(const CWalletTx& wtx)
+{
+ WalletTxStatus result;
+ auto mi = ::mapBlockIndex.find(wtx.hashBlock);
+ CBlockIndex* block = mi != ::mapBlockIndex.end() ? mi->second : nullptr;
+ result.block_height = (block ? block->nHeight : std::numeric_limits<int>::max()),
+ result.blocks_to_maturity = wtx.GetBlocksToMaturity();
+ result.depth_in_main_chain = wtx.GetDepthInMainChain();
+ result.request_count = wtx.GetRequestCount();
+ result.time_received = wtx.nTimeReceived;
+ result.lock_time = wtx.tx->nLockTime;
+ result.is_final = CheckFinalTx(*wtx.tx);
+ result.is_trusted = wtx.IsTrusted();
+ result.is_abandoned = wtx.isAbandoned();
+ result.is_coinbase = wtx.IsCoinBase();
+ result.is_in_main_chain = wtx.IsInMainChain();
+ return result;
+}
+
+//! Construct wallet TxOut struct.
+WalletTxOut MakeWalletTxOut(CWallet& wallet, const CWalletTx& wtx, int n, int depth)
+{
+ WalletTxOut result;
+ result.txout = wtx.tx->vout[n];
+ result.time = wtx.GetTxTime();
+ result.depth_in_main_chain = depth;
+ result.is_spent = wallet.IsSpent(wtx.GetHash(), n);
+ return result;
+}
+
+class WalletImpl : public Wallet
+{
+public:
+ WalletImpl(CWallet& wallet) : m_wallet(wallet) {}
+
+ bool encryptWallet(const SecureString& wallet_passphrase) override
+ {
+ return m_wallet.EncryptWallet(wallet_passphrase);
+ }
+ bool isCrypted() override { return m_wallet.IsCrypted(); }
+ bool lock() override { return m_wallet.Lock(); }
+ bool unlock(const SecureString& wallet_passphrase) override { return m_wallet.Unlock(wallet_passphrase); }
+ bool isLocked() override { return m_wallet.IsLocked(); }
+ bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
+ const SecureString& new_wallet_passphrase) override
+ {
+ return m_wallet.ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase);
+ }
+ bool backupWallet(const std::string& filename) override { return m_wallet.BackupWallet(filename); }
+ std::string getWalletName() override { return m_wallet.GetName(); }
+ bool getKeyFromPool(bool internal, CPubKey& pub_key) override
+ {
+ return m_wallet.GetKeyFromPool(pub_key, internal);
+ }
+ bool getPubKey(const CKeyID& address, CPubKey& pub_key) override { return m_wallet.GetPubKey(address, pub_key); }
+ bool getPrivKey(const CKeyID& address, CKey& key) override { return m_wallet.GetKey(address, key); }
+ bool isSpendable(const CTxDestination& dest) override { return IsMine(m_wallet, dest) & ISMINE_SPENDABLE; }
+ bool haveWatchOnly() override { return m_wallet.HaveWatchOnly(); };
+ bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) override
+ {
+ return m_wallet.SetAddressBook(dest, name, purpose);
+ }
+ bool delAddressBook(const CTxDestination& dest) override
+ {
+ return m_wallet.DelAddressBook(dest);
+ }
+ bool getAddress(const CTxDestination& dest, std::string* name, isminetype* is_mine) override
+ {
+ LOCK(m_wallet.cs_wallet);
+ auto it = m_wallet.mapAddressBook.find(dest);
+ if (it == m_wallet.mapAddressBook.end()) {
+ return false;
+ }
+ if (name) {
+ *name = it->second.name;
+ }
+ if (is_mine) {
+ *is_mine = IsMine(m_wallet, dest);
+ }
+ return true;
+ }
+ std::vector<WalletAddress> getAddresses() override
+ {
+ LOCK(m_wallet.cs_wallet);
+ std::vector<WalletAddress> result;
+ for (const auto& item : m_wallet.mapAddressBook) {
+ result.emplace_back(item.first, IsMine(m_wallet, item.first), item.second.name, item.second.purpose);
+ }
+ return result;
+ }
+ void learnRelatedScripts(const CPubKey& key, OutputType type) override { m_wallet.LearnRelatedScripts(key, type); }
+ bool addDestData(const CTxDestination& dest, const std::string& key, const std::string& value) override
+ {
+ LOCK(m_wallet.cs_wallet);
+ return m_wallet.AddDestData(dest, key, value);
+ }
+ bool eraseDestData(const CTxDestination& dest, const std::string& key) override
+ {
+ LOCK(m_wallet.cs_wallet);
+ return m_wallet.EraseDestData(dest, key);
+ }
+ std::vector<std::string> getDestValues(const std::string& prefix) override
+ {
+ return m_wallet.GetDestValues(prefix);
+ }
+ void lockCoin(const COutPoint& output) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ return m_wallet.LockCoin(output);
+ }
+ void unlockCoin(const COutPoint& output) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ return m_wallet.UnlockCoin(output);
+ }
+ bool isLockedCoin(const COutPoint& output) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ return m_wallet.IsLockedCoin(output.hash, output.n);
+ }
+ void listLockedCoins(std::vector<COutPoint>& outputs) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ return m_wallet.ListLockedCoins(outputs);
+ }
+ std::unique_ptr<PendingWalletTx> createTransaction(const std::vector<CRecipient>& recipients,
+ const CCoinControl& coin_control,
+ bool sign,
+ int& change_pos,
+ CAmount& fee,
+ std::string& fail_reason) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ auto pending = MakeUnique<PendingWalletTxImpl>(m_wallet);
+ if (!m_wallet.CreateTransaction(recipients, pending->m_tx, pending->m_key, fee, change_pos,
+ fail_reason, coin_control, sign)) {
+ return {};
+ }
+ return std::move(pending);
+ }
+ bool transactionCanBeAbandoned(const uint256& txid) override { return m_wallet.TransactionCanBeAbandoned(txid); }
+ bool abandonTransaction(const uint256& txid) override
+ {
+ LOCK2(cs_main, m_wallet.cs_wallet);
+ return m_wallet.AbandonTransaction(txid);
+ }
+ bool transactionCanBeBumped(const uint256& txid) override
+ {
+ return feebumper::TransactionCanBeBumped(&m_wallet, txid);
+ }
+ bool createBumpTransaction(const uint256& txid,
+ const CCoinControl& coin_control,
+ CAmount total_fee,
+ std::vector<std::string>& errors,
+ CAmount& old_fee,
+ CAmount& new_fee,
+ CMutableTransaction& mtx) override
+ {
+ return feebumper::CreateTransaction(&m_wallet, txid, coin_control, total_fee, errors, old_fee, new_fee, mtx) ==
+ feebumper::Result::OK;
+ }
+ bool signBumpTransaction(CMutableTransaction& mtx) override { return feebumper::SignTransaction(&m_wallet, mtx); }
+ bool commitBumpTransaction(const uint256& txid,
+ CMutableTransaction&& mtx,
+ std::vector<std::string>& errors,
+ uint256& bumped_txid) override
+ {
+ return feebumper::CommitTransaction(&m_wallet, txid, std::move(mtx), errors, bumped_txid) ==
+ feebumper::Result::OK;
+ }
+ CTransactionRef getTx(const uint256& txid) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ auto mi = m_wallet.mapWallet.find(txid);
+ if (mi != m_wallet.mapWallet.end()) {
+ return mi->second.tx;
+ }
+ return {};
+ }
+ WalletTx getWalletTx(const uint256& txid) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ auto mi = m_wallet.mapWallet.find(txid);
+ if (mi != m_wallet.mapWallet.end()) {
+ return MakeWalletTx(m_wallet, mi->second);
+ }
+ return {};
+ }
+ std::vector<WalletTx> getWalletTxs() override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ std::vector<WalletTx> result;
+ result.reserve(m_wallet.mapWallet.size());
+ for (const auto& entry : m_wallet.mapWallet) {
+ result.emplace_back(MakeWalletTx(m_wallet, entry.second));
+ }
+ return result;
+ }
+ bool tryGetTxStatus(const uint256& txid,
+ interface::WalletTxStatus& tx_status,
+ int& num_blocks,
+ int64_t& adjusted_time) override
+ {
+ TRY_LOCK(::cs_main, locked_chain);
+ if (!locked_chain) {
+ return false;
+ }
+ TRY_LOCK(m_wallet.cs_wallet, locked_wallet);
+ if (!locked_wallet) {
+ return false;
+ }
+ auto mi = m_wallet.mapWallet.find(txid);
+ if (mi == m_wallet.mapWallet.end()) {
+ return false;
+ }
+ num_blocks = ::chainActive.Height();
+ adjusted_time = GetAdjustedTime();
+ tx_status = MakeWalletTxStatus(mi->second);
+ return true;
+ }
+ WalletTx getWalletTxDetails(const uint256& txid,
+ WalletTxStatus& tx_status,
+ WalletOrderForm& order_form,
+ bool& in_mempool,
+ int& num_blocks,
+ int64_t& adjusted_time) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ auto mi = m_wallet.mapWallet.find(txid);
+ if (mi != m_wallet.mapWallet.end()) {
+ num_blocks = ::chainActive.Height();
+ adjusted_time = GetAdjustedTime();
+ in_mempool = mi->second.InMempool();
+ order_form = mi->second.vOrderForm;
+ tx_status = MakeWalletTxStatus(mi->second);
+ return MakeWalletTx(m_wallet, mi->second);
+ }
+ return {};
+ }
+ WalletBalances getBalances() override
+ {
+ WalletBalances result;
+ result.balance = m_wallet.GetBalance();
+ result.unconfirmed_balance = m_wallet.GetUnconfirmedBalance();
+ result.immature_balance = m_wallet.GetImmatureBalance();
+ result.have_watch_only = m_wallet.HaveWatchOnly();
+ if (result.have_watch_only) {
+ result.watch_only_balance = m_wallet.GetWatchOnlyBalance();
+ result.unconfirmed_watch_only_balance = m_wallet.GetUnconfirmedWatchOnlyBalance();
+ result.immature_watch_only_balance = m_wallet.GetImmatureWatchOnlyBalance();
+ }
+ return result;
+ }
+ bool tryGetBalances(WalletBalances& balances, int& num_blocks) override
+ {
+ TRY_LOCK(cs_main, locked_chain);
+ if (!locked_chain) return false;
+ TRY_LOCK(m_wallet.cs_wallet, locked_wallet);
+ if (!locked_wallet) {
+ return false;
+ }
+ balances = getBalances();
+ num_blocks = ::chainActive.Height();
+ return true;
+ }
+ CAmount getBalance() override { return m_wallet.GetBalance(); }
+ CAmount getAvailableBalance(const CCoinControl& coin_control) override
+ {
+ return m_wallet.GetAvailableBalance(&coin_control);
+ }
+ isminetype txinIsMine(const CTxIn& txin) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ return m_wallet.IsMine(txin);
+ }
+ isminetype txoutIsMine(const CTxOut& txout) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ return m_wallet.IsMine(txout);
+ }
+ CAmount getDebit(const CTxIn& txin, isminefilter filter) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ return m_wallet.GetDebit(txin, filter);
+ }
+ CAmount getCredit(const CTxOut& txout, isminefilter filter) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ return m_wallet.GetCredit(txout, filter);
+ }
+ CoinsList listCoins() override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ CoinsList result;
+ for (const auto& entry : m_wallet.ListCoins()) {
+ auto& group = result[entry.first];
+ for (const auto& coin : entry.second) {
+ group.emplace_back(
+ COutPoint(coin.tx->GetHash(), coin.i), MakeWalletTxOut(m_wallet, *coin.tx, coin.i, coin.nDepth));
+ }
+ }
+ return result;
+ }
+ std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override
+ {
+ LOCK2(::cs_main, m_wallet.cs_wallet);
+ std::vector<WalletTxOut> result;
+ result.reserve(outputs.size());
+ for (const auto& output : outputs) {
+ result.emplace_back();
+ auto it = m_wallet.mapWallet.find(output.hash);
+ if (it != m_wallet.mapWallet.end()) {
+ int depth = it->second.GetDepthInMainChain();
+ if (depth >= 0) {
+ result.back() = MakeWalletTxOut(m_wallet, it->second, output.n, depth);
+ }
+ }
+ }
+ return result;
+ }
+ bool hdEnabled() override { return m_wallet.IsHDEnabled(); }
+ OutputType getDefaultAddressType() override { return m_wallet.m_default_address_type; }
+ OutputType getDefaultChangeType() override { return m_wallet.m_default_change_type; }
+ std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
+ {
+ return MakeHandler(m_wallet.ShowProgress.connect(fn));
+ }
+ std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override
+ {
+ return MakeHandler(m_wallet.NotifyStatusChanged.connect([fn](CCryptoKeyStore*) { fn(); }));
+ }
+ std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override
+ {
+ return MakeHandler(m_wallet.NotifyAddressBookChanged.connect(
+ [fn](CWallet*, const CTxDestination& address, const std::string& label, bool is_mine,
+ const std::string& purpose, ChangeType status) { fn(address, label, is_mine, purpose, status); }));
+ }
+ std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override
+ {
+ return MakeHandler(m_wallet.NotifyTransactionChanged.connect(
+ [fn, this](CWallet*, const uint256& txid, ChangeType status) { fn(txid, status); }));
+ }
+ std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) override
+ {
+ return MakeHandler(m_wallet.NotifyWatchonlyChanged.connect(fn));
+ }
+
+ CWallet& m_wallet;
+};
+
+} // namespace
+
+std::unique_ptr<Wallet> MakeWallet(CWallet& wallet) { return MakeUnique<WalletImpl>(wallet); }
+
+} // namespace interface
diff --git a/src/interface/wallet.h b/src/interface/wallet.h
new file mode 100644
index 0000000000..b66ed63398
--- /dev/null
+++ b/src/interface/wallet.h
@@ -0,0 +1,352 @@
+// Copyright (c) 2018 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_INTERFACE_WALLET_H
+#define BITCOIN_INTERFACE_WALLET_H
+
+#include <amount.h> // For CAmount
+#include <pubkey.h> // For CTxDestination (CKeyID and CScriptID)
+#include <script/ismine.h> // For isminefilter, isminetype
+#include <script/standard.h> // For CTxDestination
+#include <support/allocators/secure.h> // For SecureString
+#include <ui_interface.h> // For ChangeType
+
+#include <functional>
+#include <map>
+#include <memory>
+#include <stdint.h>
+#include <string>
+#include <tuple>
+#include <utility>
+#include <vector>
+
+class CCoinControl;
+class CKey;
+class CWallet;
+enum class OutputType;
+struct CRecipient;
+
+namespace interface {
+
+class Handler;
+class PendingWalletTx;
+struct WalletAddress;
+struct WalletBalances;
+struct WalletTx;
+struct WalletTxOut;
+struct WalletTxStatus;
+
+using WalletOrderForm = std::vector<std::pair<std::string, std::string>>;
+using WalletValueMap = std::map<std::string, std::string>;
+
+//! Interface for accessing a wallet.
+class Wallet
+{
+public:
+ virtual ~Wallet() {}
+
+ //! Encrypt wallet.
+ virtual bool encryptWallet(const SecureString& wallet_passphrase) = 0;
+
+ //! Return whether wallet is encrypted.
+ virtual bool isCrypted() = 0;
+
+ //! Lock wallet.
+ virtual bool lock() = 0;
+
+ //! Unlock wallet.
+ virtual bool unlock(const SecureString& wallet_passphrase) = 0;
+
+ //! Return whether wallet is locked.
+ virtual bool isLocked() = 0;
+
+ //! Change wallet passphrase.
+ virtual bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
+ const SecureString& new_wallet_passphrase) = 0;
+
+ //! Back up wallet.
+ virtual bool backupWallet(const std::string& filename) = 0;
+
+ //! Get wallet name.
+ virtual std::string getWalletName() = 0;
+
+ // Get key from pool.
+ virtual bool getKeyFromPool(bool internal, CPubKey& pub_key) = 0;
+
+ //! Get public key.
+ virtual bool getPubKey(const CKeyID& address, CPubKey& pub_key) = 0;
+
+ //! Get private key.
+ virtual bool getPrivKey(const CKeyID& address, CKey& key) = 0;
+
+ //! Return whether wallet has private key.
+ virtual bool isSpendable(const CTxDestination& dest) = 0;
+
+ //! Return whether wallet has watch only keys.
+ virtual bool haveWatchOnly() = 0;
+
+ //! Add or update address.
+ virtual bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) = 0;
+
+ // Remove address.
+ virtual bool delAddressBook(const CTxDestination& dest) = 0;
+
+ //! Look up address in wallet, return whether exists.
+ virtual bool getAddress(const CTxDestination& dest,
+ std::string* name = nullptr,
+ isminetype* is_mine = nullptr) = 0;
+
+ //! Get wallet address list.
+ virtual std::vector<WalletAddress> getAddresses() = 0;
+
+ //! Add scripts to key store so old so software versions opening the wallet
+ //! database can detect payments to newer address types.
+ virtual void learnRelatedScripts(const CPubKey& key, OutputType type) = 0;
+
+ //! Add dest data.
+ virtual bool addDestData(const CTxDestination& dest, const std::string& key, const std::string& value) = 0;
+
+ //! Erase dest data.
+ virtual bool eraseDestData(const CTxDestination& dest, const std::string& key) = 0;
+
+ //! Get dest values with prefix.
+ virtual std::vector<std::string> getDestValues(const std::string& prefix) = 0;
+
+ //! Lock coin.
+ virtual void lockCoin(const COutPoint& output) = 0;
+
+ //! Unlock coin.
+ virtual void unlockCoin(const COutPoint& output) = 0;
+
+ //! Return whether coin is locked.
+ virtual bool isLockedCoin(const COutPoint& output) = 0;
+
+ //! List locked coins.
+ virtual void listLockedCoins(std::vector<COutPoint>& outputs) = 0;
+
+ //! Create transaction.
+ virtual std::unique_ptr<PendingWalletTx> createTransaction(const std::vector<CRecipient>& recipients,
+ const CCoinControl& coin_control,
+ bool sign,
+ int& change_pos,
+ CAmount& fee,
+ std::string& fail_reason) = 0;
+
+ //! Return whether transaction can be abandoned.
+ virtual bool transactionCanBeAbandoned(const uint256& txid) = 0;
+
+ //! Abandon transaction.
+ virtual bool abandonTransaction(const uint256& txid) = 0;
+
+ //! Return whether transaction can be bumped.
+ virtual bool transactionCanBeBumped(const uint256& txid) = 0;
+
+ //! Create bump transaction.
+ virtual bool createBumpTransaction(const uint256& txid,
+ const CCoinControl& coin_control,
+ CAmount total_fee,
+ std::vector<std::string>& errors,
+ CAmount& old_fee,
+ CAmount& new_fee,
+ CMutableTransaction& mtx) = 0;
+
+ //! Sign bump transaction.
+ virtual bool signBumpTransaction(CMutableTransaction& mtx) = 0;
+
+ //! Commit bump transaction.
+ virtual bool commitBumpTransaction(const uint256& txid,
+ CMutableTransaction&& mtx,
+ std::vector<std::string>& errors,
+ uint256& bumped_txid) = 0;
+
+ //! Get a transaction.
+ virtual CTransactionRef getTx(const uint256& txid) = 0;
+
+ //! Get transaction information.
+ virtual WalletTx getWalletTx(const uint256& txid) = 0;
+
+ //! Get list of all wallet transactions.
+ virtual std::vector<WalletTx> getWalletTxs() = 0;
+
+ //! Try to get updated status for a particular transaction, if possible without blocking.
+ virtual bool tryGetTxStatus(const uint256& txid,
+ WalletTxStatus& tx_status,
+ int& num_blocks,
+ int64_t& adjusted_time) = 0;
+
+ //! Get transaction details.
+ virtual WalletTx getWalletTxDetails(const uint256& txid,
+ WalletTxStatus& tx_status,
+ WalletOrderForm& order_form,
+ bool& in_mempool,
+ int& num_blocks,
+ int64_t& adjusted_time) = 0;
+
+ //! Get balances.
+ virtual WalletBalances getBalances() = 0;
+
+ //! Get balances if possible without blocking.
+ virtual bool tryGetBalances(WalletBalances& balances, int& num_blocks) = 0;
+
+ //! Get balance.
+ virtual CAmount getBalance() = 0;
+
+ //! Get available balance.
+ virtual CAmount getAvailableBalance(const CCoinControl& coin_control) = 0;
+
+ //! Return whether transaction input belongs to wallet.
+ virtual isminetype txinIsMine(const CTxIn& txin) = 0;
+
+ //! Return whether transaction output belongs to wallet.
+ virtual isminetype txoutIsMine(const CTxOut& txout) = 0;
+
+ //! Return debit amount if transaction input belongs to wallet.
+ virtual CAmount getDebit(const CTxIn& txin, isminefilter filter) = 0;
+
+ //! Return credit amount if transaction input belongs to wallet.
+ virtual CAmount getCredit(const CTxOut& txout, isminefilter filter) = 0;
+
+ //! Return AvailableCoins + LockedCoins grouped by wallet address.
+ //! (put change in one group with wallet address)
+ using CoinsList = std::map<CTxDestination, std::vector<std::tuple<COutPoint, WalletTxOut>>>;
+ virtual CoinsList listCoins() = 0;
+
+ //! Return wallet transaction output information.
+ virtual std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) = 0;
+
+ // Return whether HD enabled.
+ virtual bool hdEnabled() = 0;
+
+ // Get default address type.
+ virtual OutputType getDefaultAddressType() = 0;
+
+ // Get default change type.
+ virtual OutputType getDefaultChangeType() = 0;
+
+ //! Register handler for show progress messages.
+ using ShowProgressFn = std::function<void(const std::string& title, int progress)>;
+ virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0;
+
+ //! Register handler for status changed messages.
+ using StatusChangedFn = std::function<void()>;
+ virtual std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) = 0;
+
+ //! Register handler for address book changed messages.
+ using AddressBookChangedFn = std::function<void(const CTxDestination& address,
+ const std::string& label,
+ bool is_mine,
+ const std::string& purpose,
+ ChangeType status)>;
+ virtual std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) = 0;
+
+ //! Register handler for transaction changed messages.
+ using TransactionChangedFn = std::function<void(const uint256& txid, ChangeType status)>;
+ virtual std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) = 0;
+
+ //! Register handler for watchonly changed messages.
+ using WatchOnlyChangedFn = std::function<void(bool have_watch_only)>;
+ virtual std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) = 0;
+};
+
+//! Tracking object returned by CreateTransaction and passed to CommitTransaction.
+class PendingWalletTx
+{
+public:
+ virtual ~PendingWalletTx() {}
+
+ //! Get transaction data.
+ virtual const CTransaction& get() = 0;
+
+ //! Get virtual transaction size.
+ virtual int64_t getVirtualSize() = 0;
+
+ //! Send pending transaction and commit to wallet.
+ virtual bool commit(WalletValueMap value_map,
+ WalletOrderForm order_form,
+ std::string from_account,
+ std::string& reject_reason) = 0;
+};
+
+//! Information about one wallet address.
+struct WalletAddress
+{
+ CTxDestination dest;
+ isminetype is_mine;
+ std::string name;
+ std::string purpose;
+
+ WalletAddress(CTxDestination dest, isminetype is_mine, std::string name, std::string purpose)
+ : dest(std::move(dest)), is_mine(is_mine), name(std::move(name)), purpose(std::move(purpose))
+ {
+ }
+};
+
+//! Collection of wallet balances.
+struct WalletBalances
+{
+ CAmount balance = 0;
+ CAmount unconfirmed_balance = 0;
+ CAmount immature_balance = 0;
+ bool have_watch_only = false;
+ CAmount watch_only_balance = 0;
+ CAmount unconfirmed_watch_only_balance = 0;
+ CAmount immature_watch_only_balance = 0;
+
+ bool balanceChanged(const WalletBalances& prev) const
+ {
+ return balance != prev.balance || unconfirmed_balance != prev.unconfirmed_balance ||
+ immature_balance != prev.immature_balance || watch_only_balance != prev.watch_only_balance ||
+ unconfirmed_watch_only_balance != prev.unconfirmed_watch_only_balance ||
+ immature_watch_only_balance != prev.immature_watch_only_balance;
+ }
+};
+
+// Wallet transaction information.
+struct WalletTx
+{
+ CTransactionRef tx;
+ std::vector<isminetype> txin_is_mine;
+ std::vector<isminetype> txout_is_mine;
+ std::vector<CTxDestination> txout_address;
+ std::vector<isminetype> txout_address_is_mine;
+ CAmount credit;
+ CAmount debit;
+ CAmount change;
+ int64_t time;
+ std::map<std::string, std::string> value_map;
+ bool is_coinbase;
+};
+
+//! Updated transaction status.
+struct WalletTxStatus
+{
+ int block_height;
+ int blocks_to_maturity;
+ int depth_in_main_chain;
+ int request_count;
+ unsigned int time_received;
+ uint32_t lock_time;
+ bool is_final;
+ bool is_trusted;
+ bool is_abandoned;
+ bool is_coinbase;
+ bool is_in_main_chain;
+};
+
+//! Wallet transaction output.
+struct WalletTxOut
+{
+ CTxOut txout;
+ int64_t time;
+ int depth_in_main_chain = -1;
+ bool is_spent = false;
+};
+
+//! Return implementation of Wallet interface. This function will be undefined
+//! in builds where ENABLE_WALLET is false.
+std::unique_ptr<Wallet> MakeWallet(CWallet& wallet);
+
+} // namespace interface
+
+#endif // BITCOIN_INTERFACE_WALLET_H
diff --git a/src/key_io.h b/src/key_io.h
index 6fc9a8059a..d75b5b31c8 100644
--- a/src/key_io.h
+++ b/src/key_io.h
@@ -3,8 +3,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_KEYIO_H
-#define BITCOIN_KEYIO_H
+#ifndef BITCOIN_KEY_IO_H
+#define BITCOIN_KEY_IO_H
#include <chainparams.h>
#include <key.h>
@@ -26,4 +26,4 @@ CTxDestination DecodeDestination(const std::string& str);
bool IsValidDestinationString(const std::string& str);
bool IsValidDestinationString(const std::string& str, const CChainParams& params);
-#endif // BITCOIN_KEYIO_H
+#endif // BITCOIN_KEY_IO_H
diff --git a/src/keystore.cpp b/src/keystore.cpp
index fab1b81c9a..e69d518890 100644
--- a/src/keystore.cpp
+++ b/src/keystore.cpp
@@ -7,10 +7,6 @@
#include <util.h>
-bool CKeyStore::AddKey(const CKey &key) {
- return AddKeyPubKey(key, key.GetPubKey());
-}
-
void CBasicKeyStore::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
{
AssertLockHeld(cs_KeyStore);
@@ -131,7 +127,7 @@ static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
CScript::const_iterator pc = dest.begin();
opcodetype opcode;
std::vector<unsigned char> vch;
- if (!dest.GetOp(pc, opcode, vch) || vch.size() < 33 || vch.size() > 65)
+ if (!dest.GetOp(pc, opcode, vch) || !CPubKey::ValidSize(vch))
return false;
pubKeyOut = CPubKey(vch);
if (!pubKeyOut.IsFullyValid())
diff --git a/src/keystore.h b/src/keystore.h
index ffd3238fd6..fa912cb195 100644
--- a/src/keystore.h
+++ b/src/keystore.h
@@ -9,35 +9,27 @@
#include <key.h>
#include <pubkey.h>
#include <script/script.h>
+#include <script/sign.h>
#include <script/standard.h>
#include <sync.h>
#include <boost/signals2/signal.hpp>
/** A virtual base class for key stores */
-class CKeyStore
+class CKeyStore : public SigningProvider
{
-protected:
- mutable CCriticalSection cs_KeyStore;
-
public:
- virtual ~CKeyStore() {}
-
//! Add a key to the store.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) =0;
- virtual bool AddKey(const CKey &key);
//! Check whether a key corresponding to a given address is present in the store.
virtual bool HaveKey(const CKeyID &address) const =0;
- virtual bool GetKey(const CKeyID &address, CKey& keyOut) const =0;
virtual std::set<CKeyID> GetKeys() const =0;
- virtual bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const =0;
//! Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki
virtual bool AddCScript(const CScript& redeemScript) =0;
virtual bool HaveCScript(const CScriptID &hash) const =0;
virtual std::set<CScriptID> GetCScripts() const =0;
- virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const =0;
//! Support for Watch-only addresses
virtual bool AddWatchOnly(const CScript &dest) =0;
@@ -55,6 +47,8 @@ typedef std::set<CScript> WatchOnlySet;
class CBasicKeyStore : public CKeyStore
{
protected:
+ mutable CCriticalSection cs_KeyStore;
+
KeyMap mapKeys;
WatchKeyMap mapWatchKeys;
ScriptMap mapScripts;
@@ -64,6 +58,7 @@ protected:
public:
bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
+ bool AddKey(const CKey &key) { return AddKeyPubKey(key, key.GetPubKey()); }
bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
bool HaveKey(const CKeyID &address) const override;
std::set<CKeyID> GetKeys() const override;
diff --git a/src/memusage.h b/src/memusage.h
index fea7ecdf9f..0b92e53b48 100644
--- a/src/memusage.h
+++ b/src/memusage.h
@@ -10,6 +10,7 @@
#include <stdlib.h>
#include <map>
+#include <memory>
#include <set>
#include <vector>
#include <unordered_map>
diff --git a/src/miner.cpp b/src/miner.cpp
index fcb376c6cb..d2be393538 100644
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -27,6 +27,7 @@
#include <validationinterface.h>
#include <algorithm>
+#include <memory>
#include <queue>
#include <utility>
@@ -68,9 +69,7 @@ BlockAssembler::BlockAssembler(const CChainParams& params, const Options& option
static BlockAssembler::Options DefaultOptions(const CChainParams& params)
{
// Block resource limits
- // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
- // If only one is given, only restrict the specified resource.
- // If both are given, restrict both.
+ // If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
BlockAssembler::Options options;
options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
if (gArgs.IsArgSet("-blockmintxfee")) {
@@ -282,7 +281,7 @@ bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_tran
return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
}
-void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
+void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
@@ -418,7 +417,7 @@ void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpda
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
- SortForBlock(ancestors, iter, sortedEntries);
+ SortForBlock(ancestors, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
diff --git a/src/miner.h b/src/miner.h
index 9c086332d4..33a22ba75f 100644
--- a/src/miner.h
+++ b/src/miner.h
@@ -185,7 +185,7 @@ private:
* or if the transaction's cached data in mapTx is incorrect. */
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx);
/** Sort the package in an order that is valid to appear in a block */
- void SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries);
+ void SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries);
/** Add descendants of given transactions to mapModifiedTx with ancestor
* state updated assuming given transactions are inBlock. Returns number
* of updated descendants. */
diff --git a/src/net.cpp b/src/net.cpp
index 33a60ac96e..f45592ab83 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -20,6 +20,7 @@
#include <ui_interface.h>
#include <utilstrencodings.h>
+#include <memory>
#ifdef WIN32
#include <string.h>
#else
@@ -42,12 +43,13 @@
// We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
#define FEELER_SLEEP_WINDOW 1
-#if !defined(HAVE_MSG_NOSIGNAL)
+// MSG_NOSIGNAL is not available on some platforms, if it doesn't exist define it as 0
+#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
-#if !defined(HAVE_MSG_DONTWAIT)
+#if !defined(MSG_DONTWAIT)
#define MSG_DONTWAIT 0
#endif
@@ -1954,7 +1956,7 @@ void CConnman::ThreadOpenAddedConnections()
for (const AddedNodeInfo& info : vInfo) {
if (!info.fConnected) {
if (!grant.TryAcquire()) {
- // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
+ // If we've used up our semaphore and need a new one, let's not wait here since while we are waiting
// the addednodeinfo state might change.
break;
}
@@ -2795,7 +2797,7 @@ void CNode::AskFor(const CInv& inv)
nRequestTime = it->second;
else
nRequestTime = 0;
- LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
+ LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, FormatISO8601Time(nRequestTime/1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
diff --git a/src/net.h b/src/net.h
index 96f04d83e0..7839b75a86 100644
--- a/src/net.h
+++ b/src/net.h
@@ -469,6 +469,13 @@ public:
virtual bool SendMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
virtual void InitializeNode(CNode* pnode) = 0;
virtual void FinalizeNode(NodeId id, bool& update_connection_time) = 0;
+
+protected:
+ /**
+ * Protected destructor so that instances can only be deleted by derived classes.
+ * If that restriction is no longer desired, this should be made public and virtual.
+ */
+ ~NetEventsInterface() = default;
};
enum
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 482a206c8b..dbdae705de 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -30,6 +30,8 @@
#include <utilmoneystr.h>
#include <utilstrencodings.h>
+#include <memory>
+
#if defined(NDEBUG)
# error "Bitcoin cannot be compiled without assertions."
#endif
@@ -339,7 +341,7 @@ bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex*
CNodeState *state = State(nodeid);
assert(state != nullptr);
- // Short-circuit most stuff in case its from the same node
+ // Short-circuit most stuff in case it is from the same node
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
if (pit) {
@@ -374,10 +376,11 @@ void ProcessBlockAvailability(NodeId nodeid) {
assert(state != nullptr);
if (!state->hashLastUnknownBlock.IsNull()) {
- BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
- if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
- if (state->pindexBestKnownBlock == nullptr || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
- state->pindexBestKnownBlock = itOld->second;
+ const CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock);
+ if (pindex && pindex->nChainWork > 0) {
+ if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
+ state->pindexBestKnownBlock = pindex;
+ }
state->hashLastUnknownBlock.SetNull();
}
}
@@ -390,11 +393,12 @@ void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
ProcessBlockAvailability(nodeid);
- BlockMap::iterator it = mapBlockIndex.find(hash);
- if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
+ const CBlockIndex* pindex = LookupBlockIndex(hash);
+ if (pindex && pindex->nChainWork > 0) {
// An actually better block was announced.
- if (state->pindexBestKnownBlock == nullptr || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
- state->pindexBestKnownBlock = it->second;
+ if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
+ state->pindexBestKnownBlock = pindex;
+ }
} else {
// An unknown block was announced; just assume that the latest one is the best one.
state->hashLastUnknownBlock = hash;
@@ -516,7 +520,7 @@ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<con
}
// Iterate over those blocks in vToFetch (in forward direction), adding the ones that
- // are not yet downloaded and not in flight to vBlocks. In the mean time, update
+ // are not yet downloaded and not in flight to vBlocks. In the meantime, update
// pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
// already part of our chain (and therefore don't need it even if pruned).
for (const CBlockIndex* pindex : vToFetch) {
@@ -1015,7 +1019,7 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
}
case MSG_BLOCK:
case MSG_WITNESS_BLOCK:
- return mapBlockIndex.count(inv.hash);
+ return LookupBlockIndex(inv.hash) != nullptr;
}
// Don't know what it is, just say we already got one
return true;
@@ -1082,11 +1086,10 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
bool need_activate_chain = false;
{
LOCK(cs_main);
- BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
- if (mi != mapBlockIndex.end())
- {
- if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
- mi->second->IsValid(BLOCK_VALID_TREE)) {
+ const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
+ if (pindex) {
+ if (pindex->nChainTx && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
+ pindex->IsValid(BLOCK_VALID_TREE)) {
// If we have the block and all of its parents, but have not yet validated it,
// we might be in the middle of connecting it (ie in the unlock of cs_main
// before ActivateBestChain but after AcceptBlock).
@@ -1102,9 +1105,9 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
}
LOCK(cs_main);
- BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
- if (mi != mapBlockIndex.end()) {
- send = BlockRequestAllowed(mi->second, consensusParams);
+ const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
+ if (pindex) {
+ send = BlockRequestAllowed(pindex, consensusParams);
if (!send) {
LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
}
@@ -1112,7 +1115,7 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
// disconnect node in case we have reached the outbound limit for serving historical blocks
// never disconnect whitelisted nodes
- if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
+ if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
{
LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
@@ -1122,7 +1125,7 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
}
// Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
if (send && !pfrom->fWhitelisted && (
- (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - mi->second->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
+ (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
)) {
LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId());
@@ -1132,15 +1135,15 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
}
// Pruned nodes may have deleted the block, so check whether
// it's available before trying to send.
- if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
+ if (send && (pindex->nStatus & BLOCK_HAVE_DATA))
{
std::shared_ptr<const CBlock> pblock;
- if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
+ if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
pblock = a_recent_block;
} else {
// Send block from disk
std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
- if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
+ if (!ReadBlockFromDisk(*pblockRead, pindex, consensusParams))
assert(!"cannot load block from disk");
pblock = pblockRead;
}
@@ -1182,8 +1185,8 @@ void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensus
// instead we respond with the full, non-compact block.
bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
- if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
- if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
+ if (CanDirectFetch(consensusParams) && pindex->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
+ if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
} else {
CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
@@ -1323,7 +1326,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve
// don't connect before giving DoS points
// - Once a headers message is received that is valid and does connect,
// nUnconnectingHeaders gets reset back to 0.
- if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
+ if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
nodestate->nUnconnectingHeaders++;
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
@@ -1353,7 +1356,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve
// If we don't have the last header, then they'll have given us
// something new (if these headers are valid).
- if (mapBlockIndex.find(hashLastBlock) == mapBlockIndex.end()) {
+ if (!LookupBlockIndex(hashLastBlock)) {
received_new_header = true;
}
}
@@ -1369,7 +1372,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve
} else {
LogPrint(BCLog::NET, "peer=%d: invalid header received\n", pfrom->GetId());
}
- if (punish_duplicate_invalid && mapBlockIndex.find(first_invalid_header.GetHash()) != mapBlockIndex.end()) {
+ if (punish_duplicate_invalid && LookupBlockIndex(first_invalid_header.GetHash())) {
// Goal: don't allow outbound peers to use up our outbound
// connection slots if they are on incompatible chains.
//
@@ -2050,13 +2053,13 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
LOCK(cs_main);
- BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
- if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
+ const CBlockIndex* pindex = LookupBlockIndex(req.blockhash);
+ if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
return true;
}
- if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
+ if (pindex->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
// If an older block is requested (should never happen in practice,
// but can happen in tests) send a block response instead of a
// blocktxn response. Sending a full block response instead of a
@@ -2074,7 +2077,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
}
CBlock block;
- bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
+ bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus());
assert(ret);
SendBlockTransactions(block, req, pfrom, connman);
@@ -2098,10 +2101,10 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
if (locator.IsNull())
{
// If locator is null, return the hashStop block
- BlockMap::iterator mi = mapBlockIndex.find(hashStop);
- if (mi == mapBlockIndex.end())
+ pindex = LookupBlockIndex(hashStop);
+ if (!pindex) {
return true;
- pindex = (*mi).second;
+ }
if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) {
LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
@@ -2340,14 +2343,14 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
{
LOCK(cs_main);
- if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
+ if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
// Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
if (!IsInitialBlockDownload())
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
return true;
}
- if (mapBlockIndex.find(cmpctblock.header.GetHash()) == mapBlockIndex.end()) {
+ if (!LookupBlockIndex(cmpctblock.header.GetHash())) {
received_new_header = true;
}
}
@@ -3329,9 +3332,8 @@ bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptM
// then send all headers past that one. If we come across any
// headers that aren't on chainActive, give up.
for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
- BlockMap::iterator mi = mapBlockIndex.find(hash);
- assert(mi != mapBlockIndex.end());
- const CBlockIndex *pindex = mi->second;
+ const CBlockIndex* pindex = LookupBlockIndex(hash);
+ assert(pindex);
if (chainActive[pindex->nHeight] != pindex) {
// Bail out if we reorged away from this block
fRevertToInv = true;
@@ -3422,9 +3424,8 @@ bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptM
// in the past.
if (!pto->vBlockHashesToAnnounce.empty()) {
const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
- BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
- assert(mi != mapBlockIndex.end());
- const CBlockIndex *pindex = mi->second;
+ const CBlockIndex* pindex = LookupBlockIndex(hashToAnnounce);
+ assert(pindex);
// Warn if we're announcing a block that is not on the main chain.
// This should be very rare and could be optimized out.
diff --git a/src/net_processing.h b/src/net_processing.h
index ff1ebc59da..195d0d2033 100644
--- a/src/net_processing.h
+++ b/src/net_processing.h
@@ -35,7 +35,7 @@ static constexpr int64_t EXTRA_PEER_CHECK_INTERVAL = 45;
/** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict, in seconds */
static constexpr int64_t MINIMUM_CONNECT_TIME = 30;
-class PeerLogicValidation : public CValidationInterface, public NetEventsInterface {
+class PeerLogicValidation final : public CValidationInterface, public NetEventsInterface {
private:
CConnman* const connman;
@@ -86,9 +86,9 @@ private:
};
struct CNodeStateStats {
- int nMisbehavior;
- int nSyncHeight;
- int nCommonHeight;
+ int nMisbehavior = 0;
+ int nSyncHeight = -1;
+ int nCommonHeight = -1;
std::vector<int> vHeightInFlight;
};
diff --git a/src/netaddress.h b/src/netaddress.h
index 93bbb66491..ad6b55eb58 100644
--- a/src/netaddress.h
+++ b/src/netaddress.h
@@ -93,7 +93,7 @@ class CNetAddr
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
- READWRITE(FLATDATA(ip));
+ READWRITE(ip);
}
friend class CSubNet;
@@ -131,8 +131,8 @@ class CSubNet
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(network);
- READWRITE(FLATDATA(netmask));
- READWRITE(FLATDATA(valid));
+ READWRITE(netmask);
+ READWRITE(valid);
}
};
@@ -166,7 +166,7 @@ class CService : public CNetAddr
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
- READWRITE(FLATDATA(ip));
+ READWRITE(ip);
unsigned short portN = htons(port);
READWRITE(FLATDATA(portN));
if (ser_action.ForRead())
diff --git a/src/netbase.cpp b/src/netbase.cpp
index 3ea3141d5e..92ac1c4c85 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -21,7 +21,7 @@
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
-#if !defined(HAVE_MSG_NOSIGNAL)
+#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
diff --git a/src/policy/fees.h b/src/policy/fees.h
index 5f69e989c1..8c34bee237 100644
--- a/src/policy/fees.h
+++ b/src/policy/fees.h
@@ -2,8 +2,8 @@
// 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_POLICYESTIMATOR_H
-#define BITCOIN_POLICYESTIMATOR_H
+#ifndef BITCOIN_POLICY_FEES_H
+#define BITCOIN_POLICY_FEES_H
#include <amount.h>
#include <policy/feerate.h>
@@ -12,6 +12,7 @@
#include <sync.h>
#include <map>
+#include <memory>
#include <string>
#include <vector>
@@ -68,7 +69,7 @@ class TxConfirmStats;
/* Identifier for each of the 3 different TxConfirmStats which will track
* history over different time horizons. */
-enum FeeEstimateHorizon {
+enum class FeeEstimateHorizon {
SHORT_HALFLIFE = 0,
MED_HALFLIFE = 1,
LONG_HALFLIFE = 2
@@ -294,4 +295,4 @@ private:
FastRandomContext insecure_rand;
};
-#endif /*BITCOIN_POLICYESTIMATOR_H */
+#endif // BITCOIN_POLICY_FEES_H
diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp
index bff58932b4..c3f65fb2ab 100644
--- a/src/policy/policy.cpp
+++ b/src/policy/policy.cpp
@@ -179,7 +179,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
{
std::vector<std::vector<unsigned char> > stack;
// convert the scriptSig into a stack, so we can inspect the redeemScript
- if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SIGVERSION_BASE))
+ if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
return false;
if (stack.empty())
return false;
@@ -215,7 +215,7 @@ bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
// If the scriptPubKey is P2SH, we try to extract the redeemScript casually by converting the scriptSig
// into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
// If the check fails at this stage, we know that this txid must be a bad one.
- if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SIGVERSION_BASE))
+ if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
return false;
if (stack.empty())
return false;
@@ -258,3 +258,8 @@ int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost)
{
return GetVirtualTransactionSize(GetTransactionWeight(tx), nSigOpCost);
}
+
+int64_t GetVirtualTransactionInputSize(const CTxIn& txin, int64_t nSigOpCost)
+{
+ return GetVirtualTransactionSize(GetTransactionInputWeight(txin), nSigOpCost);
+}
diff --git a/src/policy/policy.h b/src/policy/policy.h
index 3d96406bbc..e4eda4b635 100644
--- a/src/policy/policy.h
+++ b/src/policy/policy.h
@@ -102,5 +102,6 @@ extern unsigned int nBytesPerSigOp;
/** Compute the virtual transaction size (weight reinterpreted as bytes). */
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost);
int64_t GetVirtualTransactionSize(const CTransaction& tx, int64_t nSigOpCost = 0);
+int64_t GetVirtualTransactionInputSize(const CTxIn& tx, int64_t nSigOpCost = 0);
#endif // BITCOIN_POLICY_POLICY_H
diff --git a/src/policy/rbf.cpp b/src/policy/rbf.cpp
index c5a1741608..81b2a7fadc 100644
--- a/src/policy/rbf.cpp
+++ b/src/policy/rbf.cpp
@@ -22,13 +22,13 @@ RBFTransactionState IsRBFOptIn(const CTransaction &tx, CTxMemPool &pool)
// First check the transaction itself.
if (SignalsOptInRBF(tx)) {
- return RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125;
+ return RBFTransactionState::REPLACEABLE_BIP125;
}
// If this transaction is not in our mempool, then we can't be sure
// we will know about all its inputs.
if (!pool.exists(tx.GetHash())) {
- return RBF_TRANSACTIONSTATE_UNKNOWN;
+ return RBFTransactionState::UNKNOWN;
}
// If all the inputs have nSequence >= maxint-1, it still might be
@@ -40,8 +40,8 @@ RBFTransactionState IsRBFOptIn(const CTransaction &tx, CTxMemPool &pool)
for (CTxMemPool::txiter it : setAncestors) {
if (SignalsOptInRBF(it->GetTx())) {
- return RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125;
+ return RBFTransactionState::REPLACEABLE_BIP125;
}
}
- return RBF_TRANSACTIONSTATE_FINAL;
+ return RBFTransactionState::FINAL;
}
diff --git a/src/policy/rbf.h b/src/policy/rbf.h
index 72f51b0f03..b10532addf 100644
--- a/src/policy/rbf.h
+++ b/src/policy/rbf.h
@@ -9,10 +9,10 @@
static const uint32_t MAX_BIP125_RBF_SEQUENCE = 0xfffffffd;
-enum RBFTransactionState {
- RBF_TRANSACTIONSTATE_UNKNOWN,
- RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125,
- RBF_TRANSACTIONSTATE_FINAL
+enum class RBFTransactionState {
+ UNKNOWN,
+ REPLACEABLE_BIP125,
+ FINAL
};
// Check whether the sequence numbers on this transaction are signaling
diff --git a/src/protocol.h b/src/protocol.h
index e518d11944..a07c5ea862 100644
--- a/src/protocol.h
+++ b/src/protocol.h
@@ -48,10 +48,10 @@ public:
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
- READWRITE(FLATDATA(pchMessageStart));
- READWRITE(FLATDATA(pchCommand));
+ READWRITE(pchMessageStart);
+ READWRITE(pchCommand);
READWRITE(nMessageSize);
- READWRITE(FLATDATA(pchChecksum));
+ READWRITE(pchChecksum);
}
char pchMessageStart[MESSAGE_START_SIZE];
diff --git a/src/pubkey.h b/src/pubkey.h
index 59bf56395c..9c6c6b085e 100644
--- a/src/pubkey.h
+++ b/src/pubkey.h
@@ -70,6 +70,11 @@ private:
}
public:
+
+ bool static ValidSize(const std::vector<unsigned char> &vch) {
+ return vch.size() > 0 && GetLen(vch[0]) == vch.size();
+ }
+
//! Construct an invalid public key.
CPubKey()
{
diff --git a/src/qt/addressbookpage.cpp b/src/qt/addressbookpage.cpp
index 517aa49e2b..f2ddbf259b 100644
--- a/src/qt/addressbookpage.cpp
+++ b/src/qt/addressbookpage.cpp
@@ -21,6 +21,41 @@
#include <QMessageBox>
#include <QSortFilterProxyModel>
+class AddressBookSortFilterProxyModel final : public QSortFilterProxyModel
+{
+ const QString m_type;
+
+public:
+ AddressBookSortFilterProxyModel(const QString& type, QObject* parent)
+ : QSortFilterProxyModel(parent)
+ , m_type(type)
+ {
+ setDynamicSortFilter(true);
+ setFilterCaseSensitivity(Qt::CaseInsensitive);
+ setSortCaseSensitivity(Qt::CaseInsensitive);
+ }
+
+protected:
+ bool filterAcceptsRow(int row, const QModelIndex& parent) const
+ {
+ auto model = sourceModel();
+ auto label = model->index(row, AddressTableModel::Label, parent);
+
+ if (model->data(label, AddressTableModel::TypeRole).toString() != m_type) {
+ return false;
+ }
+
+ auto address = model->index(row, AddressTableModel::Address, parent);
+
+ if (filterRegExp().indexIn(model->data(address).toString()) < 0 &&
+ filterRegExp().indexIn(model->data(label).toString()) < 0) {
+ return false;
+ }
+
+ return true;
+ }
+};
+
AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookPage),
@@ -69,10 +104,12 @@ AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode,
case SendingTab:
ui->labelExplanation->setText(tr("These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
+ ui->newAddress->setVisible(true);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Bitcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction."));
ui->deleteAddress->setVisible(false);
+ ui->newAddress->setVisible(false);
break;
}
@@ -113,24 +150,12 @@ void AddressBookPage::setModel(AddressTableModel *_model)
if(!_model)
return;
- proxyModel = new QSortFilterProxyModel(this);
+ auto type = tab == ReceivingTab ? AddressTableModel::Receive : AddressTableModel::Send;
+ proxyModel = new AddressBookSortFilterProxyModel(type, this);
proxyModel->setSourceModel(_model);
- proxyModel->setDynamicSortFilter(true);
- proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
- proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
- switch(tab)
- {
- case ReceivingTab:
- // Receive filter
- proxyModel->setFilterRole(AddressTableModel::TypeRole);
- proxyModel->setFilterFixedString(AddressTableModel::Receive);
- break;
- case SendingTab:
- // Send filter
- proxyModel->setFilterRole(AddressTableModel::TypeRole);
- proxyModel->setFilterFixedString(AddressTableModel::Send);
- break;
- }
+
+ connect(ui->searchLineEdit, SIGNAL(textChanged(QString)), proxyModel, SLOT(setFilterWildcard(QString)));
+
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
@@ -188,10 +213,11 @@ void AddressBookPage::on_newAddress_clicked()
if(!model)
return;
- EditAddressDialog dlg(
- tab == SendingTab ?
- EditAddressDialog::NewSendingAddress :
- EditAddressDialog::NewReceivingAddress, this);
+ if (tab == ReceivingTab) {
+ return;
+ }
+
+ EditAddressDialog dlg(EditAddressDialog::NewSendingAddress, this);
dlg.setModel(model);
if(dlg.exec())
{
diff --git a/src/qt/addressbookpage.h b/src/qt/addressbookpage.h
index 54a43478d1..8877d07330 100644
--- a/src/qt/addressbookpage.h
+++ b/src/qt/addressbookpage.h
@@ -7,6 +7,7 @@
#include <QDialog>
+class AddressBookSortFilterProxyModel;
class AddressTableModel;
class PlatformStyle;
@@ -18,7 +19,6 @@ QT_BEGIN_NAMESPACE
class QItemSelection;
class QMenu;
class QModelIndex;
-class QSortFilterProxyModel;
QT_END_NAMESPACE
/** Widget that shows a list of sending or receiving addresses.
@@ -53,7 +53,7 @@ private:
Mode mode;
Tabs tab;
QString returnValue;
- QSortFilterProxyModel *proxyModel;
+ AddressBookSortFilterProxyModel *proxyModel;
QMenu *contextMenu;
QAction *deleteAction; // to be able to explicitly disable it
QString newAddressToSelect;
diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp
index 4f9a79d654..a9408895d9 100644
--- a/src/qt/addresstablemodel.cpp
+++ b/src/qt/addresstablemodel.cpp
@@ -7,6 +7,7 @@
#include <qt/guiutil.h>
#include <qt/walletmodel.h>
+#include <interface/node.h>
#include <key_io.h>
#include <wallet/wallet.h>
@@ -67,28 +68,23 @@ static AddressTableEntry::Type translateTransactionType(const QString &strPurpos
class AddressTablePriv
{
public:
- CWallet *wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel *parent;
- AddressTablePriv(CWallet *_wallet, AddressTableModel *_parent):
- wallet(_wallet), parent(_parent) {}
+ AddressTablePriv(AddressTableModel *_parent):
+ parent(_parent) {}
- void refreshAddressTable()
+ void refreshAddressTable(interface::Wallet& wallet)
{
cachedAddressTable.clear();
{
- LOCK(wallet->cs_wallet);
- for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook)
+ for (const auto& address : wallet.getAddresses())
{
- const CTxDestination& address = item.first;
- bool fMine = IsMine(*wallet, address);
AddressTableEntry::Type addressType = translateTransactionType(
- QString::fromStdString(item.second.purpose), fMine);
- const std::string& strName = item.second.name;
+ QString::fromStdString(address.purpose), address.is_mine);
cachedAddressTable.append(AddressTableEntry(addressType,
- QString::fromStdString(strName),
- QString::fromStdString(EncodeDestination(address))));
+ QString::fromStdString(address.name),
+ QString::fromStdString(EncodeDestination(address.dest))));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
@@ -162,12 +158,12 @@ public:
}
};
-AddressTableModel::AddressTableModel(CWallet *_wallet, WalletModel *parent) :
- QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0)
+AddressTableModel::AddressTableModel(WalletModel *parent) :
+ QAbstractTableModel(parent),walletModel(parent),priv(0)
{
columns << tr("Label") << tr("Address");
- priv = new AddressTablePriv(wallet, this);
- priv->refreshAddressTable();
+ priv = new AddressTablePriv(this);
+ priv->refreshAddressTable(parent->wallet());
}
AddressTableModel::~AddressTableModel()
@@ -244,7 +240,6 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value,
if(role == Qt::EditRole)
{
- LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = DecodeDestination(rec->address.toStdString());
if(index.column() == Label)
{
@@ -254,7 +249,7 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value,
editStatus = NO_CHANGES;
return false;
}
- wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
+ walletModel->wallet().setAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if(index.column() == Address) {
CTxDestination newAddress = DecodeDestination(value.toString().toStdString());
// Refuse to set invalid address, set error status and return false
@@ -271,7 +266,7 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value,
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
- else if(wallet->mapAddressBook.count(newAddress))
+ if (walletModel->wallet().getAddress(newAddress))
{
editStatus = DUPLICATE_ADDRESS;
return false;
@@ -280,9 +275,9 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value,
else if(rec->type == AddressTableEntry::Sending)
{
// Remove old entry
- wallet->DelAddressBook(curAddress);
+ walletModel->wallet().delAddressBook(curAddress);
// Add new entry with new address
- wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
+ walletModel->wallet().setAddressBook(newAddress, value.toString().toStdString(), strPurpose);
}
}
return true;
@@ -356,8 +351,7 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con
}
// Check for duplicate addresses
{
- LOCK(wallet->cs_wallet);
- if(wallet->mapAddressBook.count(DecodeDestination(strAddress)))
+ if(walletModel->wallet().getAddress(DecodeDestination(strAddress)))
{
editStatus = DUPLICATE_ADDRESS;
return QString();
@@ -368,7 +362,7 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con
{
// Generate a new address to associate with given label
CPubKey newKey;
- if(!wallet->GetKeyFromPool(newKey))
+ if(!walletModel->wallet().getKeyFromPool(false /* internal */, newKey))
{
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if(!ctx.isValid())
@@ -377,13 +371,13 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
- if(!wallet->GetKeyFromPool(newKey))
+ if(!walletModel->wallet().getKeyFromPool(false /* internal */, newKey))
{
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
- wallet->LearnRelatedScripts(newKey, address_type);
+ walletModel->wallet().learnRelatedScripts(newKey, address_type);
strAddress = EncodeDestination(GetDestinationForKey(newKey, address_type));
}
else
@@ -392,7 +386,7 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con
}
// Add entry
- wallet->SetAddressBook(DecodeDestination(strAddress), strLabel,
+ walletModel->wallet().setAddressBook(DecodeDestination(strAddress), strLabel,
(type == Send ? "send" : "receive"));
return QString::fromStdString(strAddress);
}
@@ -407,7 +401,7 @@ bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent
// Also refuse to remove receiving addresses.
return false;
}
- wallet->DelAddressBook(DecodeDestination(rec->address.toStdString()));
+ walletModel->wallet().delAddressBook(DecodeDestination(rec->address.toStdString()));
return true;
}
@@ -416,12 +410,11 @@ bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent
QString AddressTableModel::labelForAddress(const QString &address) const
{
{
- LOCK(wallet->cs_wallet);
CTxDestination destination = DecodeDestination(address.toStdString());
- std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(destination);
- if (mi != wallet->mapAddressBook.end())
+ std::string name;
+ if (walletModel->wallet().getAddress(destination, &name))
{
- return QString::fromStdString(mi->second.name);
+ return QString::fromStdString(name);
}
}
return QString();
@@ -441,6 +434,8 @@ int AddressTableModel::lookupAddress(const QString &address) const
}
}
+OutputType AddressTableModel::GetDefaultAddressType() const { return walletModel->wallet().getDefaultAddressType(); };
+
void AddressTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
diff --git a/src/qt/addresstablemodel.h b/src/qt/addresstablemodel.h
index 11439e25d5..954f0f593e 100644
--- a/src/qt/addresstablemodel.h
+++ b/src/qt/addresstablemodel.h
@@ -8,12 +8,14 @@
#include <QAbstractTableModel>
#include <QStringList>
-enum OutputType : int;
+enum class OutputType;
class AddressTablePriv;
class WalletModel;
-class CWallet;
+namespace interface {
+class Wallet;
+}
/**
Qt model of the address book in the core. This allows views to access and modify the address book.
@@ -23,7 +25,7 @@ class AddressTableModel : public QAbstractTableModel
Q_OBJECT
public:
- explicit AddressTableModel(CWallet *wallet, WalletModel *parent = 0);
+ explicit AddressTableModel(WalletModel *parent = 0);
~AddressTableModel();
enum ColumnIndex {
@@ -76,9 +78,10 @@ public:
EditStatus getEditStatus() const { return editStatus; }
+ OutputType GetDefaultAddressType() const;
+
private:
WalletModel *walletModel;
- CWallet *wallet;
AddressTablePriv *priv;
QStringList columns;
EditStatus editStatus;
diff --git a/src/qt/bantablemodel.cpp b/src/qt/bantablemodel.cpp
index c89c90e118..cbd67d70ab 100644
--- a/src/qt/bantablemodel.cpp
+++ b/src/qt/bantablemodel.cpp
@@ -8,6 +8,7 @@
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
+#include <interface/node.h>
#include <sync.h>
#include <utiltime.h>
@@ -45,11 +46,10 @@ public:
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
- void refreshBanlist()
+ void refreshBanlist(interface::Node& node)
{
banmap_t banMap;
- if(g_connman)
- g_connman->GetBanned(banMap);
+ node.getBanned(banMap);
cachedBanlist.clear();
#if QT_VERSION >= 0x040700
@@ -82,8 +82,9 @@ public:
}
};
-BanTableModel::BanTableModel(ClientModel *parent) :
+BanTableModel::BanTableModel(interface::Node& node, ClientModel *parent) :
QAbstractTableModel(parent),
+ m_node(node),
clientModel(parent)
{
columns << tr("IP/Netmask") << tr("Banned Until");
@@ -168,7 +169,7 @@ QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent)
void BanTableModel::refresh()
{
Q_EMIT layoutAboutToBeChanged();
- priv->refreshBanlist();
+ priv->refreshBanlist(m_node);
Q_EMIT layoutChanged();
}
diff --git a/src/qt/bantablemodel.h b/src/qt/bantablemodel.h
index a54f8793d0..4c171e6fbe 100644
--- a/src/qt/bantablemodel.h
+++ b/src/qt/bantablemodel.h
@@ -7,12 +7,18 @@
#include <net.h>
+#include <memory>
+
#include <QAbstractTableModel>
#include <QStringList>
class ClientModel;
class BanTablePriv;
+namespace interface {
+ class Node;
+}
+
struct CCombinedBan {
CSubNet subnet;
CBanEntry banEntry;
@@ -39,7 +45,7 @@ class BanTableModel : public QAbstractTableModel
Q_OBJECT
public:
- explicit BanTableModel(ClientModel *parent = 0);
+ explicit BanTableModel(interface::Node& node, ClientModel *parent = 0);
~BanTableModel();
void startAutoRefresh();
void stopAutoRefresh();
@@ -65,6 +71,7 @@ public Q_SLOTS:
void refresh();
private:
+ interface::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 ab381bfb5d..d164ca435c 100644
--- a/src/qt/bitcoin.cpp
+++ b/src/qt/bitcoin.cpp
@@ -27,16 +27,17 @@
#endif
#include <init.h>
+#include <interface/handler.h>
+#include <interface/node.h>
#include <rpc/server.h>
#include <ui_interface.h>
#include <uint256.h>
#include <util.h>
#include <warnings.h>
-#ifdef ENABLE_WALLET
-#include <wallet/wallet.h>
-#endif
+#include <walletinitinterface.h>
+#include <memory>
#include <stdint.h>
#include <boost/thread.hpp>
@@ -178,11 +179,7 @@ class BitcoinCore: public QObject
{
Q_OBJECT
public:
- explicit BitcoinCore();
- /** Basic initialization, before starting initialization/shutdown thread.
- * Return true on success.
- */
- static bool baseInitialize();
+ explicit BitcoinCore(interface::Node& node);
public Q_SLOTS:
void initialize();
@@ -194,9 +191,10 @@ Q_SIGNALS:
void runawayException(const QString &message);
private:
-
/// Pass fatal exception message to UI thread
void handleRunawayException(const std::exception *e);
+
+ interface::Node& m_node;
};
/** Main Bitcoin application object */
@@ -204,7 +202,7 @@ class BitcoinApplication: public QApplication
{
Q_OBJECT
public:
- explicit BitcoinApplication(int &argc, char **argv);
+ explicit BitcoinApplication(interface::Node& node, int &argc, char **argv);
~BitcoinApplication();
#ifdef ENABLE_WALLET
@@ -245,13 +243,14 @@ Q_SIGNALS:
private:
QThread *coreThread;
+ interface::Node& m_node;
OptionsModel *optionsModel;
ClientModel *clientModel;
BitcoinGUI *window;
QTimer *pollShutdownTimer;
#ifdef ENABLE_WALLET
PaymentServer* paymentServer;
- WalletModel *walletModel;
+ std::vector<WalletModel*> m_wallet_models;
#endif
int returnValue;
const PlatformStyle *platformStyle;
@@ -262,36 +261,15 @@ private:
#include <qt/bitcoin.moc>
-BitcoinCore::BitcoinCore():
- QObject()
+BitcoinCore::BitcoinCore(interface::Node& node) :
+ QObject(), m_node(node)
{
}
void BitcoinCore::handleRunawayException(const std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
- Q_EMIT runawayException(QString::fromStdString(GetWarnings("gui")));
-}
-
-bool BitcoinCore::baseInitialize()
-{
- if (!AppInitBasicSetup())
- {
- return false;
- }
- if (!AppInitParameterInteraction())
- {
- return false;
- }
- if (!AppInitSanityChecks())
- {
- return false;
- }
- if (!AppInitLockDataDirectory())
- {
- return false;
- }
- return true;
+ Q_EMIT runawayException(QString::fromStdString(m_node.getWarnings("gui")));
}
void BitcoinCore::initialize()
@@ -299,7 +277,7 @@ void BitcoinCore::initialize()
try
{
qDebug() << __func__ << ": Running initialization in thread";
- bool rv = AppInitMain();
+ bool rv = m_node.appInitMain();
Q_EMIT initializeResult(rv);
} catch (const std::exception& e) {
handleRunawayException(&e);
@@ -313,8 +291,7 @@ void BitcoinCore::shutdown()
try
{
qDebug() << __func__ << ": Running Shutdown in thread";
- Interrupt();
- Shutdown();
+ m_node.appShutdown();
qDebug() << __func__ << ": Shutdown finished";
Q_EMIT shutdownResult();
} catch (const std::exception& e) {
@@ -324,16 +301,17 @@ void BitcoinCore::shutdown()
}
}
-BitcoinApplication::BitcoinApplication(int &argc, char **argv):
+BitcoinApplication::BitcoinApplication(interface::Node& node, int &argc, char **argv):
QApplication(argc, argv),
coreThread(0),
+ m_node(node),
optionsModel(0),
clientModel(0),
window(0),
pollShutdownTimer(0),
#ifdef ENABLE_WALLET
paymentServer(0),
- walletModel(0),
+ m_wallet_models(),
#endif
returnValue(0)
{
@@ -381,12 +359,12 @@ void BitcoinApplication::createPaymentServer()
void BitcoinApplication::createOptionsModel(bool resetSettings)
{
- optionsModel = new OptionsModel(nullptr, resetSettings);
+ optionsModel = new OptionsModel(m_node, nullptr, resetSettings);
}
void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
{
- window = new BitcoinGUI(platformStyle, networkStyle, 0);
+ window = new BitcoinGUI(m_node, platformStyle, networkStyle, 0);
pollShutdownTimer = new QTimer(window);
connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
@@ -394,7 +372,7 @@ void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
{
- SplashScreen *splash = new SplashScreen(0, networkStyle);
+ SplashScreen *splash = new SplashScreen(m_node, 0, networkStyle);
// We don't hold a direct pointer to the splash screen after creation, but the splash
// screen will take care of deleting itself when slotFinish happens.
splash->show();
@@ -407,7 +385,7 @@ void BitcoinApplication::startThread()
if(coreThread)
return;
coreThread = new QThread(this);
- BitcoinCore *executor = new BitcoinCore();
+ BitcoinCore *executor = new BitcoinCore(m_node);
executor->moveToThread(coreThread);
/* communication to and from thread */
@@ -425,8 +403,8 @@ void BitcoinApplication::startThread()
void BitcoinApplication::parameterSetup()
{
- InitLogging();
- InitParameterInteraction();
+ m_node.initLogging();
+ m_node.initParameterInteraction();
}
void BitcoinApplication::requestInitialize()
@@ -451,13 +429,15 @@ void BitcoinApplication::requestShutdown()
#ifdef ENABLE_WALLET
window->removeAllWallets();
- delete walletModel;
- walletModel = 0;
+ for (WalletModel *walletModel : m_wallet_models) {
+ delete walletModel;
+ }
+ m_wallet_models.clear();
#endif
delete clientModel;
clientModel = 0;
- StartShutdown();
+ m_node.startShutdown();
// Request shutdown from core thread
Q_EMIT requestedShutdown();
@@ -477,20 +457,25 @@ void BitcoinApplication::initializeResult(bool success)
paymentServer->setOptionsModel(optionsModel);
#endif
- clientModel = new ClientModel(optionsModel);
+ clientModel = new ClientModel(m_node, optionsModel);
window->setClientModel(clientModel);
#ifdef ENABLE_WALLET
- // TODO: Expose secondary wallets
- if (!vpwallets.empty())
- {
- walletModel = new WalletModel(platformStyle, vpwallets[0], optionsModel);
+ bool fFirstWallet = true;
+ auto wallets = m_node.getWallets();
+ for (auto& wallet : wallets) {
+ WalletModel * const walletModel = new WalletModel(std::move(wallet), m_node, platformStyle, optionsModel);
+
+ window->addWallet(walletModel);
+ if (fFirstWallet) {
+ window->setCurrentWallet(walletModel->getWalletName());
+ fFirstWallet = false;
+ }
- window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel);
- window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET);
+ connect(walletModel, SIGNAL(coinsSent(WalletModel*,SendCoinsRecipient,QByteArray)),
+ paymentServer, SLOT(fetchPaymentACK(WalletModel*,const SendCoinsRecipient&,QByteArray)));
- connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
- paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
+ m_wallet_models.push_back(walletModel);
}
#endif
@@ -547,9 +532,11 @@ int main(int argc, char *argv[])
{
SetupEnvironment();
+ std::unique_ptr<interface::Node> node = interface::MakeNode();
+
/// 1. Parse command-line options. These take precedence over anything else.
// Command-line options take precedence:
- gArgs.ParseParameters(argc, argv);
+ node->parseParameters(argc, argv);
// Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
@@ -563,7 +550,7 @@ int main(int argc, char *argv[])
Q_INIT_RESOURCE(bitcoin);
Q_INIT_RESOURCE(bitcoin_locale);
- BitcoinApplication app(argc, argv);
+ BitcoinApplication app(*node, argc, argv);
#if QT_VERSION > 0x050100
// Generate high-dpi pixmaps
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
@@ -605,19 +592,18 @@ int main(int argc, char *argv[])
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
- if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version"))
- {
- HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version"));
+ if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
+ HelpMessageDialog help(*node, nullptr, gArgs.IsArgSet("-version"));
help.showOrPrint();
return EXIT_SUCCESS;
}
/// 5. Now that settings and translations are available, ask user for data directory
// User language is set up: pick a data directory
- if (!Intro::pickDataDirectory())
+ if (!Intro::pickDataDirectory(*node))
return EXIT_SUCCESS;
- /// 6. Determine availability of data directory and parse bitcoin.conf
+ /// 6. Determine availability of data and blocks directory and parse bitcoin.conf
/// - Do not call GetDataDir(true) before this step finishes
if (!fs::is_directory(GetDataDir(false)))
{
@@ -626,7 +612,7 @@ int main(int argc, char *argv[])
return EXIT_FAILURE;
}
try {
- gArgs.ReadConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
+ node->readConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
QMessageBox::critical(0, QObject::tr(PACKAGE_NAME),
QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
@@ -641,14 +627,14 @@ int main(int argc, char *argv[])
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
- SelectParams(ChainNameFromCommandLine());
+ node->selectParams(ChainNameFromCommandLine());
} catch(std::exception &e) {
QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QObject::tr("Error: %1").arg(e.what()));
return EXIT_FAILURE;
}
#ifdef ENABLE_WALLET
// Parse URIs on command line -- this can affect Params()
- PaymentServer::ipcParseCommandLine(argc, argv);
+ PaymentServer::ipcParseCommandLine(*node, argc, argv);
#endif
QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString())));
@@ -690,10 +676,10 @@ int main(int argc, char *argv[])
// Allow parameter interaction before we create the options model
app.parameterSetup();
// Load GUI settings from QSettings
- app.createOptionsModel(gArgs.IsArgSet("-resetguisettings"));
+ app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
// Subscribe to global signals from core
- uiInterface.InitMessage.connect(InitMessage);
+ std::unique_ptr<interface::Handler> handler = node->handleInitMessage(InitMessage);
if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());
@@ -705,7 +691,7 @@ int main(int argc, char *argv[])
// Perform base initialization before spinning up initialization/shutdown thread
// This is acceptable because this function only contains steps that are quick to execute,
// so the GUI thread won't be held up.
- if (BitcoinCore::baseInitialize()) {
+ if (node->baseInitialize()) {
app.requestInitialize();
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(QObject::tr(PACKAGE_NAME)), (HWND)app.getMainWinId());
@@ -720,10 +706,10 @@ int main(int argc, char *argv[])
}
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "Runaway exception");
- app.handleRunawayException(QString::fromStdString(GetWarnings("gui")));
+ app.handleRunawayException(QString::fromStdString(node->getWarnings("gui")));
} catch (...) {
PrintExceptionContinue(nullptr, "Runaway exception");
- app.handleRunawayException(QString::fromStdString(GetWarnings("gui")));
+ app.handleRunawayException(QString::fromStdString(node->getWarnings("gui")));
}
return rv;
}
diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp
index 427eb95a84..63a2a200b2 100644
--- a/src/qt/bitcoingui.cpp
+++ b/src/qt/bitcoingui.cpp
@@ -21,6 +21,7 @@
#ifdef ENABLE_WALLET
#include <qt/walletframe.h>
#include <qt/walletmodel.h>
+#include <qt/walletview.h>
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
@@ -29,6 +30,8 @@
#include <chainparams.h>
#include <init.h>
+#include <interface/handler.h>
+#include <interface/node.h>
#include <ui_interface.h>
#include <util.h>
@@ -36,6 +39,7 @@
#include <QAction>
#include <QApplication>
+#include <QComboBox>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
@@ -70,13 +74,10 @@ const std::string BitcoinGUI::DEFAULT_UIPLATFORM =
#endif
;
-/** Display name for default wallet name. Uses tilde to avoid name
- * collisions in the future with additional wallets */
-const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
-
-BitcoinGUI::BitcoinGUI(const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
+BitcoinGUI::BitcoinGUI(interface::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
QMainWindow(parent),
enableWallet(false),
+ m_node(node),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
@@ -88,6 +89,7 @@ BitcoinGUI::BitcoinGUI(const PlatformStyle *_platformStyle, const NetworkStyle *
progressBar(0),
progressDialog(0),
appMenuBar(0),
+ appToolBar(0),
overviewAction(0),
historyAction(0),
quitAction(0),
@@ -150,8 +152,8 @@ BitcoinGUI::BitcoinGUI(const PlatformStyle *_platformStyle, const NetworkStyle *
setUnifiedTitleAndToolBarOnMac(true);
#endif
- rpcConsole = new RPCConsole(_platformStyle, 0);
- helpMessageDialog = new HelpMessageDialog(this, false);
+ rpcConsole = new RPCConsole(node, _platformStyle, 0);
+ helpMessageDialog = new HelpMessageDialog(node, this, false);
#ifdef ENABLE_WALLET
if(enableWallet)
{
@@ -455,6 +457,7 @@ void BitcoinGUI::createToolBars()
if(walletFrame)
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
+ appToolBar = toolbar;
toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
toolbar->setMovable(false);
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
@@ -463,6 +466,15 @@ void BitcoinGUI::createToolBars()
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
overviewAction->setChecked(true);
+
+#ifdef ENABLE_WALLET
+ QWidget *spacer = new QWidget();
+ spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ toolbar->addWidget(spacer);
+
+ m_wallet_selector = new QComboBox();
+ connect(m_wallet_selector, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(setCurrentWallet(const QString&)));
+#endif
}
}
@@ -481,7 +493,7 @@ void BitcoinGUI::setClientModel(ClientModel *_clientModel)
connect(_clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
modalOverlay->setKnownBestHeight(_clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(_clientModel->getHeaderTipTime()));
- setNumBlocks(_clientModel->getNumBlocks(), _clientModel->getLastBlockDate(), _clientModel->getVerificationProgress(nullptr), false);
+ setNumBlocks(m_node.getNumBlocks(), QDateTime::fromTime_t(m_node.getLastBlockTime()), m_node.getVerificationProgress(), false);
connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
// Receive and report messages from client model
@@ -529,12 +541,22 @@ void BitcoinGUI::setClientModel(ClientModel *_clientModel)
}
#ifdef ENABLE_WALLET
-bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
+bool BitcoinGUI::addWallet(WalletModel *walletModel)
{
if(!walletFrame)
return false;
+ const QString name = walletModel->getWalletName();
setWalletActionsEnabled(true);
- return walletFrame->addWallet(name, walletModel);
+ m_wallet_selector->addItem(name);
+ if (m_wallet_selector->count() == 2) {
+ m_wallet_selector_label = new QLabel();
+ m_wallet_selector_label->setText(tr("Wallet:") + " ");
+ m_wallet_selector_label->setBuddy(m_wallet_selector);
+ appToolBar->addWidget(m_wallet_selector_label);
+ appToolBar->addWidget(m_wallet_selector);
+ }
+ rpcConsole->addWallet(walletModel);
+ return walletFrame->addWallet(walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
@@ -646,7 +668,7 @@ void BitcoinGUI::aboutClicked()
if(!clientModel)
return;
- HelpMessageDialog dlg(this, true);
+ HelpMessageDialog dlg(m_node, this, true);
dlg.exec();
}
@@ -729,7 +751,7 @@ void BitcoinGUI::updateNetworkState()
QString tooltip;
- if (clientModel->getNetworkActive()) {
+ if (m_node.getNetworkActive()) {
tooltip = tr("%n active connection(s) to Bitcoin network", "", count) + QString(".<br>") + tr("Click to disable network activity.");
} else {
tooltip = tr("Network activity disabled.") + QString("<br>") + tr("Click to enable network activity again.");
@@ -780,7 +802,7 @@ void BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVer
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
- case BLOCK_SOURCE_NETWORK:
+ case BlockSource::NETWORK:
if (header) {
updateHeadersSyncProgressLabel();
return;
@@ -788,17 +810,17 @@ void BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVer
progressBarLabel->setText(tr("Synchronizing with network..."));
updateHeadersSyncProgressLabel();
break;
- case BLOCK_SOURCE_DISK:
+ case BlockSource::DISK:
if (header) {
progressBarLabel->setText(tr("Indexing blocks on disk..."));
} else {
progressBarLabel->setText(tr("Processing blocks on disk..."));
}
break;
- case BLOCK_SOURCE_REINDEX:
+ case BlockSource::REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
- case BLOCK_SOURCE_NONE:
+ case BlockSource::NONE:
if (header) {
return;
}
@@ -983,12 +1005,15 @@ void BitcoinGUI::showEvent(QShowEvent *event)
}
#ifdef ENABLE_WALLET
-void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label)
+void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName)
{
// On new transaction, make an info balloon
QString msg = tr("Date: %1\n").arg(date) +
- tr("Amount: %1\n").arg(BitcoinUnits::formatWithUnit(unit, amount, true)) +
- tr("Type: %1\n").arg(type);
+ tr("Amount: %1\n").arg(BitcoinUnits::formatWithUnit(unit, amount, true));
+ if (m_node.getWallets().size() > 1 && !walletName.isEmpty()) {
+ msg += tr("Wallet: %1\n").arg(walletName);
+ }
+ msg += tr("Type: %1\n").arg(type);
if (!label.isEmpty())
msg += tr("Label: %1\n").arg(label);
else if (!address.isEmpty())
@@ -1079,6 +1104,20 @@ void BitcoinGUI::setEncryptionStatus(int status)
break;
}
}
+
+void BitcoinGUI::updateWalletStatus()
+{
+ if (!walletFrame) {
+ return;
+ }
+ WalletView * const walletView = walletFrame->currentWalletView();
+ if (!walletView) {
+ return;
+ }
+ WalletModel * const walletModel = walletView->getWalletModel();
+ setEncryptionStatus(walletModel->getEncryptionStatus());
+ setHDStatus(walletModel->wallet().hdEnabled());
+}
#endif // ENABLE_WALLET
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
@@ -1113,7 +1152,7 @@ void BitcoinGUI::toggleHidden()
void BitcoinGUI::detectShutdown()
{
- if (ShutdownRequested())
+ if (m_node.shutdownRequested())
{
if(rpcConsole)
rpcConsole->hide();
@@ -1178,22 +1217,20 @@ static bool ThreadSafeMessageBox(BitcoinGUI *gui, const std::string& message, co
void BitcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
- uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
- uiInterface.ThreadSafeQuestion.connect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));
+ m_handler_message_box = m_node.handleMessageBox(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
+ m_handler_question = m_node.handleQuestion(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));
}
void BitcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
- uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
- uiInterface.ThreadSafeQuestion.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));
+ m_handler_message_box->disconnect();
+ m_handler_question->disconnect();
}
void BitcoinGUI::toggleNetworkActive()
{
- if (clientModel) {
- clientModel->setNetworkActive(!clientModel->getNetworkActive());
- }
+ m_node.setNetworkActive(!m_node.getNetworkActive());
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) :
diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h
index ddb7ecb76a..3a4b25d804 100644
--- a/src/qt/bitcoingui.h
+++ b/src/qt/bitcoingui.h
@@ -18,6 +18,8 @@
#include <QPoint>
#include <QSystemTrayIcon>
+#include <memory>
+
class ClientModel;
class NetworkStyle;
class Notificator;
@@ -31,8 +33,14 @@ class WalletModel;
class HelpMessageDialog;
class ModalOverlay;
+namespace interface {
+class Handler;
+class Node;
+}
+
QT_BEGIN_NAMESPACE
class QAction;
+class QComboBox;
class QProgressBar;
class QProgressDialog;
QT_END_NAMESPACE
@@ -46,10 +54,9 @@ class BitcoinGUI : public QMainWindow
Q_OBJECT
public:
- static const QString DEFAULT_WALLET;
static const std::string DEFAULT_UIPLATFORM;
- explicit BitcoinGUI(const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = 0);
+ explicit BitcoinGUI(interface::Node& node, const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = 0);
~BitcoinGUI();
/** Set the client model.
@@ -62,8 +69,7 @@ public:
The wallet model represents a bitcoin wallet, and offers access to the list of transactions, address book and sending
functionality.
*/
- bool addWallet(const QString& name, WalletModel *walletModel);
- bool setCurrentWallet(const QString& name);
+ bool addWallet(WalletModel *walletModel);
void removeAllWallets();
#endif // ENABLE_WALLET
bool enableWallet;
@@ -77,6 +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;
ClientModel *clientModel;
WalletFrame *walletFrame;
@@ -90,6 +99,7 @@ private:
QProgressDialog *progressDialog;
QMenuBar *appMenuBar;
+ QToolBar *appToolBar;
QAction *overviewAction;
QAction *historyAction;
QAction *quitAction;
@@ -112,6 +122,9 @@ private:
QAction *openAction;
QAction *showHelpMessageAction;
+ QLabel *m_wallet_selector_label;
+ QComboBox *m_wallet_selector;
+
QSystemTrayIcon *trayIcon;
QMenu *trayIconMenu;
Notificator *notificator;
@@ -171,6 +184,12 @@ public Q_SLOTS:
void message(const QString &title, const QString &message, unsigned int style, bool *ret = nullptr);
#ifdef ENABLE_WALLET
+ bool setCurrentWallet(const QString& name);
+ /** Set the UI status indicators based on the currently selected wallet.
+ */
+ void updateWalletStatus();
+
+private:
/** Set the encryption status as shown in the UI.
@param[in] status current encryption status
@see WalletModel::EncryptionStatus
@@ -183,10 +202,11 @@ public Q_SLOTS:
*/
void setHDStatus(int hdEnabled);
+public Q_SLOTS:
bool handlePaymentRequest(const SendCoinsRecipient& recipient);
/** Show incoming transaction notification for new transactions. */
- void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label);
+ void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName);
#endif // ENABLE_WALLET
private Q_SLOTS:
diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp
index eaf2896bc3..1dbfc815b6 100644
--- a/src/qt/clientmodel.cpp
+++ b/src/qt/clientmodel.cpp
@@ -13,6 +13,8 @@
#include <chainparams.h>
#include <checkpoints.h>
#include <clientversion.h>
+#include <interface/handler.h>
+#include <interface/node.h>
#include <validation.h>
#include <net.h>
#include <txmempool.h>
@@ -30,8 +32,9 @@ class CBlockIndex;
static int64_t nLastHeaderTipUpdateNotification = 0;
static int64_t nLastBlockTipUpdateNotification = 0;
-ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) :
+ClientModel::ClientModel(interface::Node& node, OptionsModel *_optionsModel, QObject *parent) :
QObject(parent),
+ m_node(node),
optionsModel(_optionsModel),
peerTableModel(0),
banTableModel(0),
@@ -39,8 +42,8 @@ ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) :
{
cachedBestHeaderHeight = -1;
cachedBestHeaderTime = -1;
- peerTableModel = new PeerTableModel(this);
- banTableModel = new BanTableModel(this);
+ peerTableModel = new PeerTableModel(m_node, this);
+ banTableModel = new BanTableModel(m_node, this);
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
pollTimer->start(MODEL_UPDATE_DELAY);
@@ -64,15 +67,7 @@ int ClientModel::getNumConnections(unsigned int flags) const
else if (flags == CONNECTIONS_ALL)
connections = CConnman::CONNECTIONS_ALL;
- if(g_connman)
- return g_connman->GetNodeCount(connections);
- return 0;
-}
-
-int ClientModel::getNumBlocks() const
-{
- LOCK(cs_main);
- return chainActive.Height();
+ return m_node.getNodeCount(connections);
}
int ClientModel::getHeaderTipHeight() const
@@ -80,10 +75,11 @@ int ClientModel::getHeaderTipHeight() const
if (cachedBestHeaderHeight == -1) {
// make sure we initially populate the cache via a cs_main lock
// otherwise we need to wait for a tip update
- LOCK(cs_main);
- if (pindexBestHeader) {
- cachedBestHeaderHeight = pindexBestHeader->nHeight;
- cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
+ int height;
+ int64_t blockTime;
+ if (m_node.getHeaderTip(height, blockTime)) {
+ cachedBestHeaderHeight = height;
+ cachedBestHeaderTime = blockTime;
}
}
return cachedBestHeaderHeight;
@@ -92,66 +88,22 @@ int ClientModel::getHeaderTipHeight() const
int64_t ClientModel::getHeaderTipTime() const
{
if (cachedBestHeaderTime == -1) {
- LOCK(cs_main);
- if (pindexBestHeader) {
- cachedBestHeaderHeight = pindexBestHeader->nHeight;
- cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
+ int height;
+ int64_t blockTime;
+ if (m_node.getHeaderTip(height, blockTime)) {
+ cachedBestHeaderHeight = height;
+ cachedBestHeaderTime = blockTime;
}
}
return cachedBestHeaderTime;
}
-quint64 ClientModel::getTotalBytesRecv() const
-{
- if(!g_connman)
- return 0;
- return g_connman->GetTotalBytesRecv();
-}
-
-quint64 ClientModel::getTotalBytesSent() const
-{
- if(!g_connman)
- return 0;
- return g_connman->GetTotalBytesSent();
-}
-
-QDateTime ClientModel::getLastBlockDate() const
-{
- LOCK(cs_main);
-
- if (chainActive.Tip())
- return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime());
-
- return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network
-}
-
-long ClientModel::getMempoolSize() const
-{
- return mempool.size();
-}
-
-size_t ClientModel::getMempoolDynamicUsage() const
-{
- return mempool.DynamicMemoryUsage();
-}
-
-double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const
-{
- CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn);
- LOCK(cs_main);
- if (!tip)
- {
- tip = chainActive.Tip();
- }
- return GuessVerificationProgress(Params().TxData(), tip);
-}
-
void ClientModel::updateTimer()
{
// no locking required at this point
// the following calls will acquire the required lock
- Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage());
- Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
+ Q_EMIT mempoolSizeChanged(m_node.getMempoolSize(), m_node.getMempoolDynamicUsage());
+ Q_EMIT bytesChanged(m_node.getTotalBytesRecv(), m_node.getTotalBytesSent());
}
void ClientModel::updateNumConnections(int numConnections)
@@ -169,41 +121,21 @@ void ClientModel::updateAlert()
Q_EMIT alertsChanged(getStatusBarWarnings());
}
-bool ClientModel::inInitialBlockDownload() const
-{
- return IsInitialBlockDownload();
-}
-
enum BlockSource ClientModel::getBlockSource() const
{
- if (fReindex)
- return BLOCK_SOURCE_REINDEX;
- else if (fImporting)
- return BLOCK_SOURCE_DISK;
+ if (m_node.getReindex())
+ return BlockSource::REINDEX;
+ else if (m_node.getImporting())
+ return BlockSource::DISK;
else if (getNumConnections() > 0)
- return BLOCK_SOURCE_NETWORK;
+ return BlockSource::NETWORK;
- return BLOCK_SOURCE_NONE;
-}
-
-void ClientModel::setNetworkActive(bool active)
-{
- if (g_connman) {
- g_connman->SetNetworkActive(active);
- }
-}
-
-bool ClientModel::getNetworkActive() const
-{
- if (g_connman) {
- return g_connman->GetNetworkActive();
- }
- return false;
+ return BlockSource::NONE;
}
QString ClientModel::getStatusBarWarnings() const
{
- return QString::fromStdString(GetWarnings("gui"));
+ return QString::fromStdString(m_node.getWarnings("gui"));
}
OptionsModel *ClientModel::getOptionsModel()
@@ -285,7 +217,7 @@ static void BannedListChanged(ClientModel *clientmodel)
QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}
-static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader)
+static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, int height, int64_t blockTime, double verificationProgress, bool fHeader)
{
// lock free async UI updates in case we have a new block tip
// during initial sync, only update the UI if the last update
@@ -298,16 +230,16 @@ static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CB
if (fHeader) {
// cache best headers time and height to reduce future cs_main locks
- clientmodel->cachedBestHeaderHeight = pIndex->nHeight;
- clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime();
+ clientmodel->cachedBestHeaderHeight = height;
+ clientmodel->cachedBestHeaderTime = blockTime;
}
// if we are in-sync, update the UI regardless of last update time
if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) {
//pass an async signal to the UI thread
QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
- Q_ARG(int, pIndex->nHeight),
- Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())),
- Q_ARG(double, clientmodel->getVerificationProgress(pIndex)),
+ Q_ARG(int, height),
+ Q_ARG(QDateTime, QDateTime::fromTime_t(blockTime)),
+ Q_ARG(double, verificationProgress),
Q_ARG(bool, fHeader));
nLastUpdateNotification = now;
}
@@ -316,23 +248,23 @@ static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CB
void ClientModel::subscribeToCoreSignals()
{
// Connect signals to client
- uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
- uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
- uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1));
- uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this));
- uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
- uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false));
- uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true));
+ m_handler_show_progress = m_node.handleShowProgress(boost::bind(ShowProgress, this, _1, _2));
+ m_handler_notify_num_connections_changed = m_node.handleNotifyNumConnectionsChanged(boost::bind(NotifyNumConnectionsChanged, this, _1));
+ m_handler_notify_network_active_changed = m_node.handleNotifyNetworkActiveChanged(boost::bind(NotifyNetworkActiveChanged, this, _1));
+ m_handler_notify_alert_changed = m_node.handleNotifyAlertChanged(boost::bind(NotifyAlertChanged, this));
+ m_handler_banned_list_changed = m_node.handleBannedListChanged(boost::bind(BannedListChanged, this));
+ m_handler_notify_block_tip = m_node.handleNotifyBlockTip(boost::bind(BlockTipChanged, this, _1, _2, _3, _4, false));
+ m_handler_notify_header_tip = m_node.handleNotifyHeaderTip(boost::bind(BlockTipChanged, this, _1, _2, _3, _4, true));
}
void ClientModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
- uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
- uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
- uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1));
- uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this));
- uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
- uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false));
- uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true));
+ m_handler_show_progress->disconnect();
+ m_handler_notify_num_connections_changed->disconnect();
+ m_handler_notify_network_active_changed->disconnect();
+ m_handler_notify_alert_changed->disconnect();
+ m_handler_banned_list_changed->disconnect();
+ m_handler_notify_block_tip->disconnect();
+ m_handler_notify_header_tip->disconnect();
}
diff --git a/src/qt/clientmodel.h b/src/qt/clientmodel.h
index 99ec2365a9..9faa10b87e 100644
--- a/src/qt/clientmodel.h
+++ b/src/qt/clientmodel.h
@@ -9,6 +9,7 @@
#include <QDateTime>
#include <atomic>
+#include <memory>
class BanTableModel;
class OptionsModel;
@@ -16,15 +17,20 @@ class PeerTableModel;
class CBlockIndex;
+namespace interface {
+class Handler;
+class Node;
+}
+
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
-enum BlockSource {
- BLOCK_SOURCE_NONE,
- BLOCK_SOURCE_REINDEX,
- BLOCK_SOURCE_DISK,
- BLOCK_SOURCE_NETWORK
+enum class BlockSource {
+ NONE,
+ REINDEX,
+ DISK,
+ NETWORK
};
enum NumConnections {
@@ -40,37 +46,21 @@ class ClientModel : public QObject
Q_OBJECT
public:
- explicit ClientModel(OptionsModel *optionsModel, QObject *parent = 0);
+ explicit ClientModel(interface::Node& node, OptionsModel *optionsModel, QObject *parent = 0);
~ClientModel();
+ interface::Node& node() const { return m_node; }
OptionsModel *getOptionsModel();
PeerTableModel *getPeerTableModel();
BanTableModel *getBanTableModel();
//! Return number of connections, default is in- and outbound (total)
int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const;
- int getNumBlocks() const;
int getHeaderTipHeight() const;
int64_t getHeaderTipTime() const;
- //! Return number of transactions in the mempool
- long getMempoolSize() const;
- //! Return the dynamic memory usage of the mempool
- size_t getMempoolDynamicUsage() const;
-
- quint64 getTotalBytesRecv() const;
- quint64 getTotalBytesSent() const;
-
- double getVerificationProgress(const CBlockIndex *tip) const;
- QDateTime getLastBlockDate() const;
-
- //! Return true if core is doing initial block download
- bool inInitialBlockDownload() const;
+
//! Returns enum BlockSource of the current importing/syncing state
enum BlockSource getBlockSource() const;
- //! Return true if network activity in core is enabled
- bool getNetworkActive() const;
- //! Toggle network activity state in core
- void setNetworkActive(bool active);
//! Return warnings to be displayed in status bar
QString getStatusBarWarnings() const;
@@ -85,6 +75,14 @@ public:
mutable std::atomic<int64_t> cachedBestHeaderTime;
private:
+ 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;
OptionsModel *optionsModel;
PeerTableModel *peerTableModel;
BanTableModel *banTableModel;
diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp
index b83755ab30..2081d6ca08 100644
--- a/src/qt/coincontroldialog.cpp
+++ b/src/qt/coincontroldialog.cpp
@@ -14,7 +14,7 @@
#include <qt/walletmodel.h>
#include <wallet/coincontrol.h>
-#include <init.h>
+#include <interface/node.h>
#include <key_io.h>
#include <policy/fees.h>
#include <policy/policy.h>
@@ -206,10 +206,10 @@ void CoinControlDialog::showMenu(const QPoint &point)
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
- if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
+ if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means it is a child node, so it is not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
- if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
+ if (model->wallet().isLockedCoin(COutPoint(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())))
{
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
@@ -269,7 +269,7 @@ void CoinControlDialog::lockCoin()
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
- model->lockCoin(outpt);
+ model->wallet().lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
updateLabelLocked();
@@ -279,7 +279,7 @@ void CoinControlDialog::lockCoin()
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
- model->unlockCoin(outpt);
+ model->wallet().unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
@@ -374,7 +374,7 @@ void CoinControlDialog::radioListMode(bool checked)
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
- if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
+ if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means it is a child node, so it is not a parent node in tree mode)
{
COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
@@ -405,7 +405,7 @@ void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
void CoinControlDialog::updateLabelLocked()
{
std::vector<COutPoint> vOutpts;
- model->listLockedCoins(vOutpts);
+ model->wallet().listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
@@ -431,7 +431,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
CTxOut txout(amount, static_cast<CScript>(std::vector<unsigned char>(24, 0)));
txDummy.vout.push_back(txout);
- fDust |= IsDust(txout, ::dustRelayFee);
+ fDust |= IsDust(txout, model->node().getDustRelayFee());
}
}
@@ -445,16 +445,16 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
bool fWitness = false;
std::vector<COutPoint> vCoinControl;
- std::vector<COutput> vOutputs;
coinControl()->ListSelected(vCoinControl);
- model->getOutputs(vCoinControl, vOutputs);
- for (const COutput& out : vOutputs) {
+ size_t i = 0;
+ for (const auto& out : model->wallet().getCoins(vCoinControl)) {
+ if (out.depth_in_main_chain < 0) continue;
+
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
- uint256 txhash = out.tx->GetHash();
- COutPoint outpt(txhash, out.i);
- if (model->isSpent(outpt))
+ const COutPoint& outpt = vCoinControl[i++];
+ if (out.is_spent)
{
coinControl()->UnSelect(outpt);
continue;
@@ -464,22 +464,22 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
nQuantity++;
// Amount
- nAmount += out.tx->tx->vout[out.i].nValue;
+ nAmount += out.txout.nValue;
// Bytes
CTxDestination address;
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
- if (out.tx->tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram))
+ if (out.txout.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram))
{
nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
fWitness = true;
}
- else if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address))
+ else if(ExtractDestination(out.txout.scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&address);
- if (keyid && model->getPubKey(*keyid, pubkey))
+ if (keyid && model->wallet().getPubKey(*keyid, pubkey))
{
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
}
@@ -509,7 +509,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
nBytes -= 34;
// Fee
- nPayFee = GetMinimumFee(nBytes, *coinControl(), ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
+ nPayFee = model->node().getMinimumFee(nBytes, *coinControl(), nullptr /* returned_target */, nullptr /* reason */);
if (nPayAmount > 0)
{
@@ -521,7 +521,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
if (nChange > 0 && nChange < MIN_CHANGE)
{
CTxOut txout(nChange, static_cast<CScript>(std::vector<unsigned char>(24, 0)));
- if (IsDust(txout, ::dustRelayFee))
+ if (IsDust(txout, model->node().getDustRelayFee()))
{
nPayFee += nChange;
nChange = 0;
@@ -621,13 +621,10 @@ void CoinControlDialog::updateView()
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
- std::map<QString, std::vector<COutput> > mapCoins;
- model->listCoins(mapCoins);
-
- for (const std::pair<QString, std::vector<COutput>>& coins : mapCoins) {
+ for (const auto& coins : model->wallet().listCoins()) {
CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
- QString sWalletAddress = coins.first;
+ QString sWalletAddress = QString::fromStdString(EncodeDestination(coins.first));
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
@@ -649,8 +646,10 @@ void CoinControlDialog::updateView()
CAmount nSum = 0;
int nChildren = 0;
- for (const COutput& out : coins.second) {
- nSum += out.tx->tx->vout[out.i].nValue;
+ for (const auto& outpair : coins.second) {
+ const COutPoint& output = std::get<0>(outpair);
+ const interface::WalletTxOut& out = std::get<1>(outpair);
+ nSum += out.txout.nValue;
nChildren++;
CCoinControlWidgetItem *itemOutput;
@@ -662,7 +661,7 @@ void CoinControlDialog::updateView()
// address
CTxDestination outputAddress;
QString sAddress = "";
- if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, outputAddress))
+ if(ExtractDestination(out.txout.scriptPubKey, outputAddress))
{
sAddress = QString::fromStdString(EncodeDestination(outputAddress));
@@ -687,35 +686,33 @@ void CoinControlDialog::updateView()
}
// amount
- itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue));
- itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->tx->vout[out.i].nValue)); // padding so that sorting works correctly
+ itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.txout.nValue));
+ itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.txout.nValue)); // padding so that sorting works correctly
// date
- itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
- itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime()));
+ itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.time));
+ itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.time));
// confirmations
- itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth));
- itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth));
+ itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.depth_in_main_chain));
+ itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.depth_in_main_chain));
// transaction hash
- uint256 txhash = out.tx->GetHash();
- itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
+ itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(output.hash.GetHex()));
// vout index
- itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
+ itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(output.n));
// disable locked coins
- if (model->isLockedCoin(txhash, out.i))
+ if (model->wallet().isLockedCoin(output))
{
- COutPoint outpt(txhash, out.i);
- coinControl()->UnSelect(outpt); // just to be sure
+ coinControl()->UnSelect(output); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
}
// set checkbox
- if (coinControl()->IsSelected(COutPoint(txhash, out.i)))
+ if (coinControl()->IsSelected(output))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
diff --git a/src/qt/editaddressdialog.cpp b/src/qt/editaddressdialog.cpp
index a945fc6aa0..38411c499f 100644
--- a/src/qt/editaddressdialog.cpp
+++ b/src/qt/editaddressdialog.cpp
@@ -11,7 +11,6 @@
#include <QDataWidgetMapper>
#include <QMessageBox>
-extern OutputType g_address_type;
EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) :
QDialog(parent),
@@ -26,10 +25,6 @@ EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) :
switch(mode)
{
- case NewReceivingAddress:
- setWindowTitle(tr("New receiving address"));
- ui->addressEdit->setEnabled(false);
- break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
@@ -74,13 +69,12 @@ bool EditAddressDialog::saveCurrentRow()
switch(mode)
{
- case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
- mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
+ AddressTableModel::Send,
ui->labelEdit->text(),
ui->addressEdit->text(),
- g_address_type);
+ model->GetDefaultAddressType());
break;
case EditReceivingAddress:
case EditSendingAddress:
diff --git a/src/qt/editaddressdialog.h b/src/qt/editaddressdialog.h
index ddb67ece72..41c5d1708a 100644
--- a/src/qt/editaddressdialog.h
+++ b/src/qt/editaddressdialog.h
@@ -25,7 +25,6 @@ class EditAddressDialog : public QDialog
public:
enum Mode {
- NewReceivingAddress,
NewSendingAddress,
EditReceivingAddress,
EditSendingAddress
diff --git a/src/qt/forms/addressbookpage.ui b/src/qt/forms/addressbookpage.ui
index 264edeb720..7ac216286c 100644
--- a/src/qt/forms/addressbookpage.ui
+++ b/src/qt/forms/addressbookpage.ui
@@ -22,6 +22,13 @@
</widget>
</item>
<item>
+ <widget class="QLineEdit" name="searchLineEdit">
+ <property name="placeholderText">
+ <string>Enter address or label to search</string>
+ </property>
+ </widget>
+ </item>
+ <item>
<widget class="QTableView" name="tableView">
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
diff --git a/src/qt/forms/debugwindow.ui b/src/qt/forms/debugwindow.ui
index bba822882e..695ed61228 100644
--- a/src/qt/forms/debugwindow.ui
+++ b/src/qt/forms/debugwindow.ui
@@ -413,6 +413,22 @@
<number>4</number>
</property>
<item>
+ <widget class="QLabel" name="WalletSelectorLabel">
+ <property name="text">
+ <string>Wallet: </string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="WalletSelector">
+ <item>
+ <property name="text">
+ <string>(none)</string>
+ </property>
+ </item>
+ </widget>
+ </item>
+ <item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
diff --git a/src/qt/guiutil.cpp b/src/qt/guiutil.cpp
index 7c3c68bfef..3501f97908 100644
--- a/src/qt/guiutil.cpp
+++ b/src/qt/guiutil.cpp
@@ -13,7 +13,7 @@
#include <chainparams.h>
#include <primitives/transaction.h>
#include <key_io.h>
-#include <init.h>
+#include <interface/node.h>
#include <policy/policy.h>
#include <protocol.h>
#include <script/script.h>
@@ -137,15 +137,6 @@ void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
}
-void setupAmountWidget(QLineEdit *widget, QWidget *parent)
-{
- QDoubleValidator *amountValidator = new QDoubleValidator(parent);
- amountValidator->setDecimals(8);
- amountValidator->setBottom(0.0);
- widget->setValidator(amountValidator);
- widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-}
-
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin: URI
@@ -209,14 +200,6 @@ bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
- // Convert bitcoin:// to bitcoin:
- //
- // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
- // which will lower-case it (and thus invalidate the address).
- if(uri.startsWith("bitcoin://", Qt::CaseInsensitive))
- {
- uri.replace(0, 10, "bitcoin:");
- }
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
@@ -249,12 +232,12 @@ QString formatBitcoinURI(const SendCoinsRecipient &info)
return ret;
}
-bool isDust(const QString& address, const CAmount& amount)
+bool isDust(interface::Node& node, const QString& address, const CAmount& amount)
{
CTxDestination dest = DecodeDestination(address.toStdString());
CScript script = GetScriptForDestination(dest);
CTxOut txOut(amount, script);
- return IsDust(txOut, ::dustRelayFee);
+ return IsDust(txOut, node.getDustRelayFee());
}
QString HtmlEscape(const QString& str, bool fMultiLine)
diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h
index 71a69483f5..40037edb9d 100644
--- a/src/qt/guiutil.h
+++ b/src/qt/guiutil.h
@@ -20,6 +20,11 @@
class QValidatedLineEdit;
class SendCoinsRecipient;
+namespace interface
+{
+ class Node;
+}
+
QT_BEGIN_NAMESPACE
class QAbstractItemView;
class QDateTime;
@@ -40,9 +45,8 @@ namespace GUIUtil
// Return a monospace font
QFont fixedPitchFont();
- // Set up widgets for address and amounts
+ // Set up widget for address
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent);
- void setupAmountWidget(QLineEdit *widget, QWidget *parent);
// Parse "bitcoin:" URI into recipient object, return true on successful parsing
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out);
@@ -50,7 +54,7 @@ namespace GUIUtil
QString formatBitcoinURI(const SendCoinsRecipient &info);
// Returns true if given address+amount meets "dust" definition
- bool isDust(const QString& address, const CAmount& amount);
+ bool isDust(interface::Node& node, const QString& address, const CAmount& amount);
// HTML escaping for rich text controls
QString HtmlEscape(const QString& str, bool fMultiLine=false);
@@ -141,7 +145,7 @@ namespace GUIUtil
* Makes a QTableView last column feel as if it was being resized from its left border.
* Also makes sure the column widths are never larger than the table's viewport.
* In Qt, all columns are resizable from the right, but it's not intuitive resizing the last column from the right.
- * Usually our second to last columns behave as if stretched, and when on strech mode, columns aren't resizable
+ * Usually our second to last columns behave as if stretched, and when on stretch mode, columns aren't resizable
* interactively or programmatically.
*
* This helper object takes care of this issue.
diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp
index e69f196238..4eb7482018 100644
--- a/src/qt/intro.cpp
+++ b/src/qt/intro.cpp
@@ -12,6 +12,7 @@
#include <qt/guiutil.h>
+#include <interface/node.h>
#include <util.h>
#include <QFileDialog>
@@ -186,7 +187,7 @@ QString Intro::getDefaultDataDirectory()
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
-bool Intro::pickDataDirectory()
+bool Intro::pickDataDirectory(interface::Node& node)
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
@@ -233,8 +234,9 @@ bool Intro::pickDataDirectory()
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
- if(dataDir != getDefaultDataDirectory())
- gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
+ if(dataDir != getDefaultDataDirectory()) {
+ node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
+ }
return true;
}
diff --git a/src/qt/intro.h b/src/qt/intro.h
index 5b428b379c..07d2025bb6 100644
--- a/src/qt/intro.h
+++ b/src/qt/intro.h
@@ -13,6 +13,10 @@ static const bool DEFAULT_CHOOSE_DATADIR = false;
class FreespaceChecker;
+namespace interface {
+ class Node;
+}
+
namespace Ui {
class Intro;
}
@@ -41,7 +45,7 @@ public:
* @note do NOT call global GetDataDir() before calling this function, this
* will cause the wrong path to be cached.
*/
- static bool pickDataDirectory();
+ static bool pickDataDirectory(interface::Node& node);
/**
* Determine default data directory for operating system.
diff --git a/src/qt/modaloverlay.cpp b/src/qt/modaloverlay.cpp
index b573dbe226..249418213f 100644
--- a/src/qt/modaloverlay.cpp
+++ b/src/qt/modaloverlay.cpp
@@ -81,7 +81,7 @@ void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVeri
// keep a vector of samples of verification progress at height
blockProcessTime.push_front(qMakePair(currentDate.toMSecsSinceEpoch(), nVerificationProgress));
- // show progress speed if we have more then one sample
+ // show progress speed if we have more than one sample
if (blockProcessTime.size() >= 2) {
double progressDelta = 0;
double progressPerHour = 0;
diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp
index 5bef473c63..438e9e70f1 100644
--- a/src/qt/optionsdialog.cpp
+++ b/src/qt/optionsdialog.cpp
@@ -13,6 +13,7 @@
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
+#include <interface/node.h>
#include <validation.h> // for DEFAULT_SCRIPTCHECK_THREADS and MAX_SCRIPTCHECK_THREADS
#include <netbase.h>
#include <txdb.h> // for -dbcache defaults
@@ -313,17 +314,17 @@ void OptionsDialog::updateDefaultProxyNets()
std::string strProxy;
QString strDefaultProxyGUI;
- GetProxy(NET_IPV4, proxy);
+ model->node().getProxy(NET_IPV4, proxy);
strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort();
strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text();
(strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv4->setChecked(true) : ui->proxyReachIPv4->setChecked(false);
- GetProxy(NET_IPV6, proxy);
+ model->node().getProxy(NET_IPV6, proxy);
strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort();
strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text();
(strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv6->setChecked(true) : ui->proxyReachIPv6->setChecked(false);
- GetProxy(NET_TOR, proxy);
+ model->node().getProxy(NET_TOR, proxy);
strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort();
strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text();
(strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachTor->setChecked(true) : ui->proxyReachTor->setChecked(false);
diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp
index 909be1c264..d8197b6ec6 100644
--- a/src/qt/optionsmodel.cpp
+++ b/src/qt/optionsmodel.cpp
@@ -11,26 +11,21 @@
#include <qt/bitcoinunits.h>
#include <qt/guiutil.h>
-#include <init.h>
+#include <interface/node.h>
#include <validation.h> // For DEFAULT_SCRIPTCHECK_THREADS
#include <net.h>
#include <netbase.h>
#include <txdb.h> // for -dbcache defaults
#include <qt/intro.h>
-#ifdef ENABLE_WALLET
-#include <wallet/wallet.h>
-#include <wallet/walletdb.h>
-#endif
-
#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>
const char *DEFAULT_GUI_PROXY_HOST = "127.0.0.1";
-OptionsModel::OptionsModel(QObject *parent, bool resetSettings) :
- QAbstractListModel(parent)
+OptionsModel::OptionsModel(interface::Node& node, QObject *parent, bool resetSettings) :
+ QAbstractListModel(parent), m_node(node)
{
Init(resetSettings);
}
@@ -93,12 +88,12 @@ void OptionsModel::Init(bool resetSettings)
// Main
if (!settings.contains("nDatabaseCache"))
settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache);
- if (!gArgs.SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
+ if (!m_node.softSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
addOverriddenOption("-dbcache");
if (!settings.contains("nThreadsScriptVerif"))
settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS);
- if (!gArgs.SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
+ if (!m_node.softSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
addOverriddenOption("-par");
if (!settings.contains("strDataDir"))
@@ -108,19 +103,19 @@ void OptionsModel::Init(bool resetSettings)
#ifdef ENABLE_WALLET
if (!settings.contains("bSpendZeroConfChange"))
settings.setValue("bSpendZeroConfChange", true);
- if (!gArgs.SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
+ if (!m_node.softSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
addOverriddenOption("-spendzeroconfchange");
#endif
// Network
if (!settings.contains("fUseUPnP"))
settings.setValue("fUseUPnP", DEFAULT_UPNP);
- if (!gArgs.SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
+ if (!m_node.softSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
addOverriddenOption("-upnp");
if (!settings.contains("fListen"))
settings.setValue("fListen", DEFAULT_LISTEN);
- if (!gArgs.SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
+ if (!m_node.softSetBoolArg("-listen", settings.value("fListen").toBool()))
addOverriddenOption("-listen");
if (!settings.contains("fUseProxy"))
@@ -128,7 +123,7 @@ void OptionsModel::Init(bool resetSettings)
if (!settings.contains("addrProxy"))
settings.setValue("addrProxy", QString("%1:%2").arg(DEFAULT_GUI_PROXY_HOST, DEFAULT_GUI_PROXY_PORT));
// Only try to set -proxy, if user has enabled fUseProxy
- if (settings.value("fUseProxy").toBool() && !gArgs.SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
+ if (settings.value("fUseProxy").toBool() && !m_node.softSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
addOverriddenOption("-proxy");
else if(!settings.value("fUseProxy").toBool() && !gArgs.GetArg("-proxy", "").empty())
addOverriddenOption("-proxy");
@@ -138,7 +133,7 @@ void OptionsModel::Init(bool resetSettings)
if (!settings.contains("addrSeparateProxyTor"))
settings.setValue("addrSeparateProxyTor", QString("%1:%2").arg(DEFAULT_GUI_PROXY_HOST, DEFAULT_GUI_PROXY_PORT));
// Only try to set -onion, if user has enabled fUseSeparateProxyTor
- if (settings.value("fUseSeparateProxyTor").toBool() && !gArgs.SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString()))
+ if (settings.value("fUseSeparateProxyTor").toBool() && !m_node.softSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString()))
addOverriddenOption("-onion");
else if(!settings.value("fUseSeparateProxyTor").toBool() && !gArgs.GetArg("-onion", "").empty())
addOverriddenOption("-onion");
@@ -146,7 +141,7 @@ void OptionsModel::Init(bool resetSettings)
// Display
if (!settings.contains("language"))
settings.setValue("language", "");
- if (!gArgs.SoftSetArg("-lang", settings.value("language").toString().toStdString()))
+ if (!m_node.softSetArg("-lang", settings.value("language").toString().toStdString()))
addOverriddenOption("-lang");
language = settings.value("language").toString();
@@ -315,12 +310,7 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in
break;
case MapPortUPnP: // core option - can be changed on-the-fly
settings.setValue("fUseUPnP", value.toBool());
- if (value.toBool()) {
- StartMapPort();
- } else {
- InterruptMapPort();
- StopMapPort();
- }
+ m_node.mapPort(value.toBool());
break;
case MinimizeOnClose:
fMinimizeOnClose = value.toBool();
@@ -453,7 +443,7 @@ bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
// Directly query current base proxy, because
// GUI settings can be overridden with -proxy.
proxyType curProxy;
- if (GetProxy(NET_IPV4, curProxy)) {
+ if (m_node.getProxy(NET_IPV4, curProxy)) {
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(QString::fromStdString(curProxy.proxy.ToStringIP()));
proxy.setPort(curProxy.proxy.GetPort());
diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h
index 3f50541eb4..96c6b8fa45 100644
--- a/src/qt/optionsmodel.h
+++ b/src/qt/optionsmodel.h
@@ -9,6 +9,10 @@
#include <QAbstractListModel>
+namespace interface {
+class Node;
+}
+
QT_BEGIN_NAMESPACE
class QNetworkProxy;
QT_END_NAMESPACE
@@ -27,7 +31,7 @@ class OptionsModel : public QAbstractListModel
Q_OBJECT
public:
- explicit OptionsModel(QObject *parent = 0, bool resetSettings = false);
+ explicit OptionsModel(interface::Node& node, QObject *parent = 0, bool resetSettings = false);
enum OptionID {
StartAtStartup, // bool
@@ -75,7 +79,10 @@ public:
void setRestartRequired(bool fRequired);
bool isRestartRequired() const;
+ interface::Node& node() const { return m_node; }
+
private:
+ interface::Node& m_node;
/* Qt-only settings */
bool fHideTrayIcon;
bool fMinimizeToTray;
diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp
index d1c9f17961..76d0220648 100644
--- a/src/qt/overviewpage.cpp
+++ b/src/qt/overviewpage.cpp
@@ -21,6 +21,8 @@
#define DECORATION_SIZE 54
#define NUM_ITEMS 5
+Q_DECLARE_METATYPE(interface::WalletBalances)
+
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
@@ -113,16 +115,12 @@ OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent)
ui(new Ui::OverviewPage),
clientModel(0),
walletModel(0),
- currentBalance(-1),
- currentUnconfirmedBalance(-1),
- currentImmatureBalance(-1),
- currentWatchOnlyBalance(-1),
- currentWatchUnconfBalance(-1),
- currentWatchImmatureBalance(-1),
txdelegate(new TxViewDelegate(platformStyle, this))
{
ui->setupUi(this);
+ m_balances.balance = -1;
+
// use a SingleColorIcon for the "out of sync warning" icon
QIcon icon = platformStyle->SingleColorIcon(":/icons/warning");
icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503)
@@ -159,28 +157,23 @@ OverviewPage::~OverviewPage()
delete ui;
}
-void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
+void OverviewPage::setBalance(const interface::WalletBalances& balances)
{
int unit = walletModel->getOptionsModel()->getDisplayUnit();
- currentBalance = balance;
- currentUnconfirmedBalance = unconfirmedBalance;
- currentImmatureBalance = immatureBalance;
- currentWatchOnlyBalance = watchOnlyBalance;
- currentWatchUnconfBalance = watchUnconfBalance;
- currentWatchImmatureBalance = watchImmatureBalance;
- ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways));
- ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));
- ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance, false, BitcoinUnits::separatorAlways));
- ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance, false, BitcoinUnits::separatorAlways));
- ui->labelWatchAvailable->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));
- ui->labelWatchPending->setText(BitcoinUnits::formatWithUnit(unit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));
- ui->labelWatchImmature->setText(BitcoinUnits::formatWithUnit(unit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));
- ui->labelWatchTotal->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));
+ m_balances = balances;
+ ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balances.balance, false, BitcoinUnits::separatorAlways));
+ ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, balances.unconfirmed_balance, false, BitcoinUnits::separatorAlways));
+ ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, balances.immature_balance, false, BitcoinUnits::separatorAlways));
+ ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, false, BitcoinUnits::separatorAlways));
+ ui->labelWatchAvailable->setText(BitcoinUnits::formatWithUnit(unit, balances.watch_only_balance, false, BitcoinUnits::separatorAlways));
+ ui->labelWatchPending->setText(BitcoinUnits::formatWithUnit(unit, balances.unconfirmed_watch_only_balance, false, BitcoinUnits::separatorAlways));
+ ui->labelWatchImmature->setText(BitcoinUnits::formatWithUnit(unit, balances.immature_watch_only_balance, false, BitcoinUnits::separatorAlways));
+ ui->labelWatchTotal->setText(BitcoinUnits::formatWithUnit(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, false, BitcoinUnits::separatorAlways));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
- bool showImmature = immatureBalance != 0;
- bool showWatchOnlyImmature = watchImmatureBalance != 0;
+ bool showImmature = balances.immature_balance != 0;
+ bool showWatchOnlyImmature = balances.immature_watch_only_balance != 0;
// for symmetry reasons also show immature label when the watch-only one is shown
ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);
@@ -231,13 +224,14 @@ void OverviewPage::setWalletModel(WalletModel *model)
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
- setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
- model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
- connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));
+ interface::Wallet& wallet = model->wallet();
+ interface::WalletBalances balances = wallet.getBalances();
+ setBalance(balances);
+ connect(model, SIGNAL(balanceChanged(interface::WalletBalances)), this, SLOT(setBalance(interface::WalletBalances)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
- updateWatchOnlyLabels(model->haveWatchOnly());
+ updateWatchOnlyLabels(wallet.haveWatchOnly());
connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));
}
@@ -249,9 +243,9 @@ void OverviewPage::updateDisplayUnit()
{
if(walletModel && walletModel->getOptionsModel())
{
- if(currentBalance != -1)
- setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance,
- currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);
+ if (m_balances.balance != -1) {
+ setBalance(m_balances);
+ }
// Update txdelegate->unit with the current unit
txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();
diff --git a/src/qt/overviewpage.h b/src/qt/overviewpage.h
index 0ce9f98c8c..36333536e5 100644
--- a/src/qt/overviewpage.h
+++ b/src/qt/overviewpage.h
@@ -5,7 +5,7 @@
#ifndef BITCOIN_QT_OVERVIEWPAGE_H
#define BITCOIN_QT_OVERVIEWPAGE_H
-#include <amount.h>
+#include <interface/wallet.h>
#include <QWidget>
#include <memory>
@@ -38,8 +38,7 @@ public:
void showOutOfSyncWarning(bool fShow);
public Q_SLOTS:
- void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
- const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance);
+ void setBalance(const interface::WalletBalances& balances);
Q_SIGNALS:
void transactionClicked(const QModelIndex &index);
@@ -49,12 +48,7 @@ private:
Ui::OverviewPage *ui;
ClientModel *clientModel;
WalletModel *walletModel;
- CAmount currentBalance;
- CAmount currentUnconfirmedBalance;
- CAmount currentImmatureBalance;
- CAmount currentWatchOnlyBalance;
- CAmount currentWatchUnconfBalance;
- CAmount currentWatchImmatureBalance;
+ interface::WalletBalances m_balances;
TxViewDelegate *txdelegate;
std::unique_ptr<TransactionFilterProxy> filter;
diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp
index 8ad4fa31f1..926a699754 100644
--- a/src/qt/paymentserver.cpp
+++ b/src/qt/paymentserver.cpp
@@ -9,6 +9,7 @@
#include <qt/optionsmodel.h>
#include <chainparams.h>
+#include <interface/node.h>
#include <policy/policy.h>
#include <key_io.h>
#include <ui_interface.h>
@@ -16,6 +17,7 @@
#include <wallet/wallet.h>
#include <cstdlib>
+#include <memory>
#include <openssl/x509_vfy.h>
@@ -199,7 +201,7 @@ void PaymentServer::LoadRootCAs(X509_STORE* _store)
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "Q_EMIT message()", but "QMessageBox::"!
//
-void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
+void PaymentServer::ipcParseCommandLine(interface::Node& node, int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
@@ -221,11 +223,11 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
auto tempChainParams = CreateChainParams(CBaseChainParams::MAIN);
if (IsValidDestinationString(r.address.toStdString(), *tempChainParams)) {
- SelectParams(CBaseChainParams::MAIN);
+ node.selectParams(CBaseChainParams::MAIN);
} else {
tempChainParams = CreateChainParams(CBaseChainParams::TESTNET);
if (IsValidDestinationString(r.address.toStdString(), *tempChainParams)) {
- SelectParams(CBaseChainParams::TESTNET);
+ node.selectParams(CBaseChainParams::TESTNET);
}
}
}
@@ -239,11 +241,11 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
if (request.getDetails().network() == "main")
{
- SelectParams(CBaseChainParams::MAIN);
+ node.selectParams(CBaseChainParams::MAIN);
}
else if (request.getDetails().network() == "test")
{
- SelectParams(CBaseChainParams::TESTNET);
+ node.selectParams(CBaseChainParams::TESTNET);
}
}
}
@@ -404,7 +406,12 @@ void PaymentServer::handleURIOrFile(const QString& s)
return;
}
- if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
+ if (s.startsWith("bitcoin://", Qt::CaseInsensitive))
+ {
+ Q_EMIT message(tr("URI handling"), tr("'bitcoin://' is not a valid URI. Use 'bitcoin:' instead."),
+ CClientUIInterface::MSG_ERROR);
+ }
+ else if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
@@ -521,7 +528,7 @@ bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, Sen
if (request.IsInitialized()) {
// Payment request network matches client network?
- if (!verifyNetwork(request.getDetails())) {
+ if (!verifyNetwork(optionsModel->node(), request.getDetails())) {
Q_EMIT message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."),
CClientUIInterface::MSG_ERROR);
@@ -578,7 +585,7 @@ bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, Sen
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
- if (IsDust(txOut, ::dustRelayFee)) {
+ if (IsDust(txOut, optionsModel->node().getDustRelayFee())) {
Q_EMIT message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).")
.arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),
CClientUIInterface::MSG_ERROR);
@@ -616,7 +623,7 @@ void PaymentServer::fetchRequest(const QUrl& url)
netManager->get(netRequest);
}
-void PaymentServer::fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction)
+void PaymentServer::fetchPaymentACK(WalletModel* walletModel, const SendCoinsRecipient& recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
@@ -634,19 +641,18 @@ void PaymentServer::fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& r
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
- QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant);
- std::string strAccount = account.toStdString();
CPubKey newKey;
- if (wallet->GetKeyFromPool(newKey)) {
+ if (walletModel->wallet().getKeyFromPool(false /* internal */, newKey)) {
// BIP70 requests encode the scriptPubKey directly, so we are not restricted to address
// types supported by the receiver. As a result, we choose the address format we also
// use for change. Despite an actual payment and not change, this is a close match:
// it's the output type we use subject to privacy issues, but not restricted by what
// other software supports.
- const OutputType change_type = g_change_type != OUTPUT_TYPE_NONE ? g_change_type : g_address_type;
- wallet->LearnRelatedScripts(newKey, change_type);
+ const OutputType change_type = walletModel->wallet().getDefaultChangeType() != OutputType::NONE ? walletModel->wallet().getDefaultChangeType() : walletModel->wallet().getDefaultAddressType();
+ walletModel->wallet().learnRelatedScripts(newKey, change_type);
CTxDestination dest = GetDestinationForKey(newKey, change_type);
- wallet->SetAddressBook(dest, strAccount, "refund");
+ std::string label = tr("Refund from %1").arg(recipient.authenticatedMerchant).toStdString();
+ walletModel->wallet().setAddressBook(dest, label, "refund");
CScript s = GetScriptForDestination(dest);
payments::Output* refund_to = payment.add_refund_to();
@@ -754,14 +760,14 @@ void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
-bool PaymentServer::verifyNetwork(const payments::PaymentDetails& requestDetails)
+bool PaymentServer::verifyNetwork(interface::Node& node, const payments::PaymentDetails& requestDetails)
{
- bool fVerified = requestDetails.network() == Params().NetworkIDString();
+ bool fVerified = requestDetails.network() == node.getNetwork();
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request network \"%2\" doesn't match client network \"%3\".")
.arg(__func__)
.arg(QString::fromStdString(requestDetails.network()))
- .arg(QString::fromStdString(Params().NetworkIDString()));
+ .arg(QString::fromStdString(node.getNetwork()));
}
return fVerified;
}
@@ -770,7 +776,7 @@ bool PaymentServer::verifyExpired(const payments::PaymentDetails& requestDetails
{
bool fVerified = (requestDetails.has_expires() && (int64_t)requestDetails.expires() < GetTime());
if (fVerified) {
- const QString requestExpires = QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", (int64_t)requestDetails.expires()));
+ const QString requestExpires = QString::fromStdString(FormatISO8601DateTime((int64_t)requestDetails.expires()));
qWarning() << QString("PaymentServer::%1: Payment request expired \"%2\".")
.arg(__func__)
.arg(requestExpires);
diff --git a/src/qt/paymentserver.h b/src/qt/paymentserver.h
index e262fc6bf7..e139899e22 100644
--- a/src/qt/paymentserver.h
+++ b/src/qt/paymentserver.h
@@ -40,8 +40,6 @@
class OptionsModel;
-class CWallet;
-
QT_BEGIN_NAMESPACE
class QApplication;
class QByteArray;
@@ -62,7 +60,7 @@ class PaymentServer : public QObject
public:
// Parse URIs on command line
// Returns false on error
- static void ipcParseCommandLine(int argc, char *argv[]);
+ static void ipcParseCommandLine(interface::Node& node, int argc, char *argv[]);
// Returns true if there were URIs on the command line
// which were successfully sent to an already-running
@@ -89,7 +87,7 @@ public:
void setOptionsModel(OptionsModel *optionsModel);
// Verify that the payment request network matches the client network
- static bool verifyNetwork(const payments::PaymentDetails& requestDetails);
+ static bool verifyNetwork(interface::Node& node, const payments::PaymentDetails& requestDetails);
// Verify if the payment request is expired
static bool verifyExpired(const payments::PaymentDetails& requestDetails);
// Verify the payment request size is valid as per BIP70
@@ -113,7 +111,7 @@ public Q_SLOTS:
void uiReady();
// Submit Payment message to a merchant, get back PaymentACK:
- void fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction);
+ void fetchPaymentACK(WalletModel* walletModel, const SendCoinsRecipient& recipient, QByteArray transaction);
// Handle an incoming URI, URI with local file scheme or file
void handleURIOrFile(const QString& s);
diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp
index 0a57dcfca3..f33db8e761 100644
--- a/src/qt/peertablemodel.cpp
+++ b/src/qt/peertablemodel.cpp
@@ -8,6 +8,7 @@
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
+#include <interface/node.h>
#include <validation.h> // for cs_main
#include <sync.h>
@@ -56,38 +57,26 @@ public:
std::map<NodeId, int> mapNodeRows;
/** Pull a full list of peers from vNodes into our cache */
- void refreshPeers()
+ void refreshPeers(interface::Node& node)
{
{
cachedNodeStats.clear();
- std::vector<CNodeStats> vstats;
- if(g_connman)
- g_connman->GetNodeStats(vstats);
+
+ interface::Node::NodesStats nodes_stats;
+ node.getNodesStats(nodes_stats);
#if QT_VERSION >= 0x040700
- cachedNodeStats.reserve(vstats.size());
+ cachedNodeStats.reserve(nodes_stats.size());
#endif
- for (const CNodeStats& nodestats : vstats)
+ for (auto& node_stats : nodes_stats)
{
CNodeCombinedStats stats;
- stats.nodeStateStats.nMisbehavior = 0;
- stats.nodeStateStats.nSyncHeight = -1;
- stats.nodeStateStats.nCommonHeight = -1;
- stats.fNodeStateStatsAvailable = false;
- stats.nodeStats = nodestats;
+ stats.nodeStats = std::get<0>(node_stats);
+ stats.fNodeStateStatsAvailable = std::get<1>(node_stats);
+ stats.nodeStateStats = std::get<2>(node_stats);
cachedNodeStats.append(stats);
}
}
- // Try to retrieve the CNodeStateStats for each node.
- {
- TRY_LOCK(cs_main, lockMain);
- if (lockMain)
- {
- for (CNodeCombinedStats &stats : cachedNodeStats)
- stats.fNodeStateStatsAvailable = GetNodeStateStats(stats.nodeStats.nodeid, stats.nodeStateStats);
- }
- }
-
if (sortColumn >= 0)
// sort cacheNodeStats (use stable sort to prevent rows jumping around unnecessarily)
qStableSort(cachedNodeStats.begin(), cachedNodeStats.end(), NodeLessThan(sortColumn, sortOrder));
@@ -113,8 +102,9 @@ public:
}
};
-PeerTableModel::PeerTableModel(ClientModel *parent) :
+PeerTableModel::PeerTableModel(interface::Node& node, ClientModel *parent) :
QAbstractTableModel(parent),
+ m_node(node),
clientModel(parent),
timer(0)
{
@@ -235,7 +225,7 @@ const CNodeCombinedStats *PeerTableModel::getNodeStats(int idx)
void PeerTableModel::refresh()
{
Q_EMIT layoutAboutToBeChanged();
- priv->refreshPeers();
+ priv->refreshPeers(m_node);
Q_EMIT layoutChanged();
}
diff --git a/src/qt/peertablemodel.h b/src/qt/peertablemodel.h
index e3c9c6e5a3..c53462c57c 100644
--- a/src/qt/peertablemodel.h
+++ b/src/qt/peertablemodel.h
@@ -8,12 +8,18 @@
#include <net_processing.h> // For CNodeStateStats
#include <net.h>
+#include <memory>
+
#include <QAbstractTableModel>
#include <QStringList>
class ClientModel;
class PeerTablePriv;
+namespace interface {
+class Node;
+}
+
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
@@ -45,7 +51,7 @@ class PeerTableModel : public QAbstractTableModel
Q_OBJECT
public:
- explicit PeerTableModel(ClientModel *parent = 0);
+ explicit PeerTableModel(interface::Node& node, ClientModel *parent = 0);
~PeerTableModel();
const CNodeCombinedStats *getNodeStats(int idx);
int getRowByNodeId(NodeId nodeid);
@@ -76,6 +82,7 @@ public Q_SLOTS:
void refresh();
private:
+ interface::Node& m_node;
ClientModel *clientModel;
QStringList columns;
std::unique_ptr<PeerTablePriv> priv;
diff --git a/src/qt/receivecoinsdialog.cpp b/src/qt/receivecoinsdialog.cpp
index 7fd5285467..70e11f0296 100644
--- a/src/qt/receivecoinsdialog.cpp
+++ b/src/qt/receivecoinsdialog.cpp
@@ -95,13 +95,13 @@ void ReceiveCoinsDialog::setModel(WalletModel *_model)
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);
// configure bech32 checkbox, disable if launched with legacy as default:
- if (model->getDefaultAddressType() == OUTPUT_TYPE_BECH32) {
+ if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {
ui->useBech32->setCheckState(Qt::Checked);
} else {
ui->useBech32->setCheckState(Qt::Unchecked);
}
- ui->useBech32->setVisible(model->getDefaultAddressType() != OUTPUT_TYPE_LEGACY);
+ ui->useBech32->setVisible(model->wallet().getDefaultAddressType() != OutputType::LEGACY);
}
}
@@ -144,16 +144,16 @@ void ReceiveCoinsDialog::on_receiveButton_clicked()
QString address;
QString label = ui->reqLabel->text();
/* Generate new receiving address */
- OutputType address_type = model->getDefaultAddressType();
- if (address_type != OUTPUT_TYPE_LEGACY) {
- address_type = ui->useBech32->isChecked() ? OUTPUT_TYPE_BECH32 : OUTPUT_TYPE_P2SH_SEGWIT;
+ OutputType address_type = model->wallet().getDefaultAddressType();
+ if (address_type != OutputType::LEGACY) {
+ address_type = ui->useBech32->isChecked() ? OutputType::BECH32 : OutputType::P2SH_SEGWIT;
}
address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type);
SendCoinsRecipient info(address, label,
ui->reqAmount->value(), ui->reqMessage->text());
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
- dialog->setModel(model->getOptionsModel());
+ dialog->setModel(model);
dialog->setInfo(info);
dialog->show();
clear();
@@ -166,7 +166,7 @@ void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &
{
const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();
ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);
- dialog->setModel(model->getOptionsModel());
+ dialog->setModel(model);
dialog->setInfo(submodel->entry(index.row()).recipient);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
diff --git a/src/qt/receiverequestdialog.cpp b/src/qt/receiverequestdialog.cpp
index d4cb0e5ba2..75146e2214 100644
--- a/src/qt/receiverequestdialog.cpp
+++ b/src/qt/receiverequestdialog.cpp
@@ -108,12 +108,12 @@ ReceiveRequestDialog::~ReceiveRequestDialog()
delete ui;
}
-void ReceiveRequestDialog::setModel(OptionsModel *_model)
+void ReceiveRequestDialog::setModel(WalletModel *_model)
{
this->model = _model;
if (_model)
- connect(_model, SIGNAL(displayUnitChanged(int)), this, SLOT(update()));
+ connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(update()));
// update the display unit if necessary
update();
@@ -143,11 +143,14 @@ void ReceiveRequestDialog::update()
html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>";
html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>";
if(info.amount)
- html += "<b>"+tr("Amount")+"</b>: " + BitcoinUnits::formatHtmlWithUnit(model->getDisplayUnit(), info.amount) + "<br>";
+ html += "<b>"+tr("Amount")+"</b>: " + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), info.amount) + "<br>";
if(!info.label.isEmpty())
html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>";
if(!info.message.isEmpty())
html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>";
+ if(model->isMultiwallet()) {
+ html += "<b>"+tr("Wallet")+"</b>: " + GUIUtil::HtmlEscape(model->getWalletName()) + "<br>";
+ }
ui->outUri->setText(html);
#ifdef USE_QRCODE
diff --git a/src/qt/receiverequestdialog.h b/src/qt/receiverequestdialog.h
index 21bbf1edb7..23c5529535 100644
--- a/src/qt/receiverequestdialog.h
+++ b/src/qt/receiverequestdialog.h
@@ -12,8 +12,6 @@
#include <QLabel>
#include <QPainter>
-class OptionsModel;
-
namespace Ui {
class ReceiveRequestDialog;
}
@@ -53,7 +51,7 @@ public:
explicit ReceiveRequestDialog(QWidget *parent = 0);
~ReceiveRequestDialog();
- void setModel(OptionsModel *model);
+ void setModel(WalletModel *model);
void setInfo(const SendCoinsRecipient &info);
private Q_SLOTS:
@@ -64,7 +62,7 @@ private Q_SLOTS:
private:
Ui::ReceiveRequestDialog *ui;
- OptionsModel *model;
+ WalletModel *model;
SendCoinsRecipient info;
};
diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp
index 0dd7d46960..1c910926d4 100644
--- a/src/qt/recentrequeststablemodel.cpp
+++ b/src/qt/recentrequeststablemodel.cpp
@@ -12,10 +12,9 @@
#include <streams.h>
-RecentRequestsTableModel::RecentRequestsTableModel(CWallet *wallet, WalletModel *parent) :
+RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) :
QAbstractTableModel(parent), walletModel(parent)
{
- Q_UNUSED(wallet);
nReceiveRequestsMaxId = 0;
// Load entries from wallet
@@ -139,10 +138,9 @@ bool RecentRequestsTableModel::removeRows(int row, int count, const QModelIndex
if(count > 0 && row >= 0 && (row+count) <= list.size())
{
- const RecentRequestEntry *rec;
for (int i = 0; i < count; ++i)
{
- rec = &list[row+i];
+ const RecentRequestEntry* rec = &list[row+i];
if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, ""))
return false;
}
diff --git a/src/qt/recentrequeststablemodel.h b/src/qt/recentrequeststablemodel.h
index ebad98cee8..80c7834a19 100644
--- a/src/qt/recentrequeststablemodel.h
+++ b/src/qt/recentrequeststablemodel.h
@@ -11,8 +11,6 @@
#include <QStringList>
#include <QDateTime>
-class CWallet;
-
class RecentRequestEntry
{
public:
@@ -60,7 +58,7 @@ class RecentRequestsTableModel: public QAbstractTableModel
Q_OBJECT
public:
- explicit RecentRequestsTableModel(CWallet *wallet, WalletModel *parent);
+ explicit RecentRequestsTableModel(WalletModel *parent);
~RecentRequestsTableModel();
enum ColumnIndex {
diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp
index 1aa4de03ca..745055b944 100644
--- a/src/qt/rpcconsole.cpp
+++ b/src/qt/rpcconsole.cpp
@@ -12,7 +12,9 @@
#include <qt/bantablemodel.h>
#include <qt/clientmodel.h>
#include <qt/platformstyle.h>
+#include <qt/walletmodel.h>
#include <chainparams.h>
+#include <interface/node.h>
#include <netbase.h>
#include <rpc/server.h>
#include <rpc/client.h>
@@ -82,12 +84,17 @@ const QStringList historyFilter = QStringList()
class RPCExecutor : public QObject
{
Q_OBJECT
+public:
+ RPCExecutor(interface::Node& node) : m_node(node) {}
public Q_SLOTS:
- void request(const QString &command);
+ void request(const QString &command, const QString &walletID);
Q_SIGNALS:
void reply(int category, const QString &command);
+
+private:
+ interface::Node& m_node;
};
/** Class for handling RPC timers
@@ -139,13 +146,14 @@ public:
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
+ * @param[in] node optional node to execute command on
* @param[out] result stringified Result from the executed command(chain)
* @param[in] strCommand Command line to split
* @param[in] fExecute set true if you want the command to be executed
* @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data
*/
-bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut)
+bool RPCConsole::RPCParseCommandLine(interface::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>());
@@ -299,18 +307,17 @@ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &
if (fExecute) {
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
- JSONRPCRequest req;
- req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
- req.strMethod = stack.back()[0];
+ UniValue params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end()));
+ std::string method = stack.back()[0];
+ std::string uri;
#ifdef ENABLE_WALLET
- // TODO: Move this logic to WalletModel
- if (!vpwallets.empty()) {
- // in Qt, use always the wallet with index 0 when running with multiple wallets
- QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName()));
- req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
+ if (walletID && !walletID->empty()) {
+ QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(*walletID));
+ uri = "/wallet/"+std::string(encodedName.constData(), encodedName.length());
}
#endif
- lastResult = tableRPC.execute(req);
+ assert(node);
+ lastResult = node->executeRpc(method, params, uri);
}
state = STATE_COMMAND_EXECUTED;
@@ -385,7 +392,7 @@ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &
}
}
-void RPCExecutor::request(const QString &command)
+void RPCExecutor::request(const QString &command, const QString &walletID)
{
try
{
@@ -416,7 +423,8 @@ void RPCExecutor::request(const QString &command)
" example: getblock(getblockhash(0),true)[tx][0]\n\n")));
return;
}
- if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand))
+ std::string wallet_id = walletID.toStdString();
+ if(!RPCConsole::RPCExecuteCommandLine(m_node, result, executableCommand, nullptr, &wallet_id))
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
@@ -443,8 +451,9 @@ void RPCExecutor::request(const QString &command)
}
}
-RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
+RPCConsole::RPCConsole(interface::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) :
QWidget(parent),
+ m_node(node),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
@@ -478,6 +487,10 @@ RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
+ // disable the wallet selector by default
+ ui->WalletSelector->setVisible(false);
+ ui->WalletSelectorLabel->setVisible(false);
+
// set library version labels
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
@@ -489,7 +502,7 @@ RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) :
rpcTimerInterface = new QtRPCTimerInterface();
// avoid accidentally overwriting an existing, non QTThread
// based timer interface
- RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
+ m_node.rpcSetTimerInterfaceIfUnset(rpcTimerInterface);
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
@@ -504,7 +517,7 @@ RPCConsole::~RPCConsole()
{
QSettings settings;
settings.setValue("RPCConsoleWindowGeometry", saveGeometry());
- RPCUnsetTimerInterface(rpcTimerInterface);
+ m_node.rpcUnsetTimerInterface(rpcTimerInterface);
delete rpcTimerInterface;
delete ui;
}
@@ -562,13 +575,14 @@ void RPCConsole::setClientModel(ClientModel *model)
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
- setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(nullptr), false);
+ interface::Node& node = clientModel->node();
+ setNumBlocks(node.getNumBlocks(), QDateTime::fromTime_t(node.getLastBlockTime()), node.getVerificationProgress(), false);
connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
updateNetworkState();
connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
- updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
+ updateTrafficStats(node.getTotalBytesRecv(), node.getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
@@ -663,7 +677,7 @@ void RPCConsole::setClientModel(ClientModel *model)
//Setup autocomplete and attach it
QStringList wordList;
- std::vector<std::string> commandList = tableRPC.listCommands();
+ std::vector<std::string> commandList = m_node.listRpcCommands();
for (size_t i = 0; i < commandList.size(); ++i)
{
wordList << commandList[i].c_str();
@@ -687,6 +701,23 @@ void RPCConsole::setClientModel(ClientModel *model)
}
}
+#ifdef ENABLE_WALLET
+void RPCConsole::addWallet(WalletModel * const walletModel)
+{
+ const QString name = walletModel->getWalletName();
+ // use name for text and internal data object (to allow to move to a wallet id later)
+ ui->WalletSelector->addItem(name, name);
+ if (ui->WalletSelector->count() == 2 && !isVisible()) {
+ // First wallet added, set to default so long as the window isn't presently visible (and potentially in use)
+ ui->WalletSelector->setCurrentIndex(1);
+ }
+ if (ui->WalletSelector->count() > 2) {
+ ui->WalletSelector->setVisible(true);
+ ui->WalletSelectorLabel->setVisible(true);
+ }
+}
+#endif
+
static QString categoryClass(int category)
{
switch(category)
@@ -814,7 +845,7 @@ void RPCConsole::updateNetworkState()
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
- if(!clientModel->getNetworkActive()) {
+ if(!clientModel->node().getNetworkActive()) {
connections += " (" + tr("Network activity disabled") + ")";
}
@@ -861,7 +892,7 @@ void RPCConsole::on_lineEdit_returnPressed()
std::string strFilteredCmd;
try {
std::string dummy;
- if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) {
+ if (!RPCParseCommandLine(nullptr, dummy, cmd.toStdString(), false, &strFilteredCmd)) {
// Failed to parse command, so we cannot even filter it for the history
throw std::runtime_error("Invalid command line");
}
@@ -874,8 +905,25 @@ void RPCConsole::on_lineEdit_returnPressed()
cmdBeforeBrowsing = QString();
+ QString walletID;
+#ifdef ENABLE_WALLET
+ const int wallet_index = ui->WalletSelector->currentIndex();
+ if (wallet_index > 0) {
+ walletID = (QString)ui->WalletSelector->itemData(wallet_index).value<QString>();
+ }
+
+ if (m_last_wallet_id != walletID) {
+ if (walletID.isEmpty()) {
+ message(CMD_REQUEST, tr("Executing command without any wallet"));
+ } else {
+ message(CMD_REQUEST, tr("Executing command using \"%1\" wallet").arg(walletID));
+ }
+ m_last_wallet_id = walletID;
+ }
+#endif
+
message(CMD_REQUEST, QString::fromStdString(strFilteredCmd));
- Q_EMIT cmdRequest(cmd);
+ Q_EMIT cmdRequest(cmd, walletID);
cmd = QString::fromStdString(strFilteredCmd);
@@ -917,13 +965,13 @@ void RPCConsole::browseHistory(int offset)
void RPCConsole::startExecutor()
{
- RPCExecutor *executor = new RPCExecutor();
+ RPCExecutor *executor = new RPCExecutor(m_node);
executor->moveToThread(&thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
- connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
+ connect(this, SIGNAL(cmdRequest(QString, QString)), executor, SLOT(request(QString, QString)));
// On stopExecutor signal
// - quit the Qt event loop in the execution thread
@@ -1143,9 +1191,6 @@ void RPCConsole::showBanTableContextMenu(const QPoint& point)
void RPCConsole::disconnectSelectedNode()
{
- if(!g_connman)
- return;
-
// Get selected peer addresses
QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId);
for(int i = 0; i < nodes.count(); i++)
@@ -1153,14 +1198,14 @@ void RPCConsole::disconnectSelectedNode()
// Get currently selected peer address
NodeId id = nodes.at(i).data().toLongLong();
// Find the node, disconnect it and clear the selected node
- if(g_connman->DisconnectNode(id))
+ if(m_node.disconnect(id))
clearSelectedNode();
}
}
void RPCConsole::banSelectedNode(int bantime)
{
- if (!clientModel || !g_connman)
+ if (!clientModel)
return;
// Get selected peer addresses
@@ -1178,7 +1223,7 @@ void RPCConsole::banSelectedNode(int bantime)
// Find possible nodes, ban it and clear the selected node
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
if(stats) {
- g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
+ m_node.ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime);
}
}
clearSelectedNode();
@@ -1199,9 +1244,8 @@ void RPCConsole::unbanSelectedNode()
CSubNet possibleSubnet;
LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
- if (possibleSubnet.IsValid() && g_connman)
+ if (possibleSubnet.IsValid() && m_node.unban(possibleSubnet))
{
- g_connman->Unban(possibleSubnet);
clientModel->getBanTableModel()->refresh();
}
}
diff --git a/src/qt/rpcconsole.h b/src/qt/rpcconsole.h
index c41cbb0933..8381301759 100644
--- a/src/qt/rpcconsole.h
+++ b/src/qt/rpcconsole.h
@@ -17,6 +17,11 @@
class ClientModel;
class PlatformStyle;
class RPCTimerInterface;
+class WalletModel;
+
+namespace interface {
+ class Node;
+}
namespace Ui {
class RPCConsole;
@@ -33,15 +38,16 @@ class RPCConsole: public QWidget
Q_OBJECT
public:
- explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent);
+ explicit RPCConsole(interface::Node& node, const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole();
- static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr);
- static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr) {
- return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut);
+ 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) {
+ return RPCParseCommandLine(&node, strResult, strCommand, true, pstrFilteredOut, walletID);
}
void setClientModel(ClientModel *model);
+ void addWallet(WalletModel * const walletModel);
enum MessageClass {
MC_ERROR,
@@ -120,7 +126,7 @@ public Q_SLOTS:
Q_SIGNALS:
// For RPC command executor
void stopExecutor();
- void cmdRequest(const QString &command);
+ void cmdRequest(const QString &command, const QString &walletID);
private:
void startExecutor();
@@ -138,6 +144,7 @@ private:
};
+ interface::Node& m_node;
Ui::RPCConsole *ui;
ClientModel *clientModel;
QStringList history;
@@ -151,6 +158,7 @@ private:
int consoleFontSize;
QCompleter *autoCompleter;
QThread thread;
+ QString m_last_wallet_id;
/** Update UI with latest network info from model. */
void updateNetworkState();
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index ec7edd48cd..b4c1471a4f 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -15,9 +15,9 @@
#include <qt/sendcoinsentry.h>
#include <chainparams.h>
+#include <interface/node.h>
#include <key_io.h>
#include <wallet/coincontrol.h>
-#include <validation.h> // mempool and minRelayTxFee
#include <ui_interface.h>
#include <txmempool.h>
#include <policy/fees.h>
@@ -149,9 +149,9 @@ void SendCoinsDialog::setModel(WalletModel *_model)
}
}
- setBalance(_model->getBalance(), _model->getUnconfirmedBalance(), _model->getImmatureBalance(),
- _model->getWatchBalance(), _model->getWatchUnconfirmedBalance(), _model->getWatchImmatureBalance());
- connect(_model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));
+ interface::WalletBalances balances = _model->wallet().getBalances();
+ setBalance(balances);
+ connect(_model, SIGNAL(balanceChanged(interface::WalletBalances)), this, SLOT(setBalance(interface::WalletBalances)));
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
@@ -175,7 +175,7 @@ void SendCoinsDialog::setModel(WalletModel *_model)
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(updateSmartFeeLabel()));
connect(ui->optInRBF, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
- ui->customFee->setSingleStep(GetRequiredFee(1000));
+ ui->customFee->setSingleStep(model->node().getRequiredFee(1000));
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
@@ -193,7 +193,7 @@ void SendCoinsDialog::setModel(WalletModel *_model)
settings.remove("nSmartFeeSliderPosition");
}
if (settings.value("nConfTarget").toInt() == 0)
- ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->getDefaultConfirmTarget()));
+ ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(model->node().getTxConfirmTarget()));
else
ui->confTargetSelector->setCurrentIndex(getIndexForConfTarget(settings.value("nConfTarget").toInt()));
}
@@ -224,7 +224,7 @@ void SendCoinsDialog::on_sendButton_clicked()
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
- if(entry->validate())
+ if(entry->validate(model->node()))
{
recipients.append(entry->getValue());
}
@@ -277,8 +277,11 @@ void SendCoinsDialog::on_sendButton_clicked()
QStringList formatted;
for (const SendCoinsRecipient &rcp : currentTransaction.getRecipients())
{
- // generate bold amount string
+ // generate bold amount string with wallet name in case of multiwallet
QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
+ if (model->isMultiwallet()) {
+ amount.append(" <u>"+tr("from wallet %1").arg(GUIUtil::HtmlEscape(model->getWalletName()))+"</u> ");
+ }
amount.append("</b>");
// generate monospace address string
QString address = "<span style='font-family: monospace;'>" + rcp.address;
@@ -369,7 +372,7 @@ void SendCoinsDialog::on_sendButton_clicked()
accept();
CoinControlDialog::coinControl()->UnSelectAll();
coinControlUpdateLabels();
- Q_EMIT coinsSent(currentTransaction.getTransaction()->GetHash());
+ Q_EMIT coinsSent(currentTransaction.getWtx()->get().GetHash());
}
fNewRecipientAllowed = true;
}
@@ -512,24 +515,17 @@ bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
return true;
}
-void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
- const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance)
+void SendCoinsDialog::setBalance(const interface::WalletBalances& balances)
{
- Q_UNUSED(unconfirmedBalance);
- Q_UNUSED(immatureBalance);
- Q_UNUSED(watchBalance);
- Q_UNUSED(watchUnconfirmedBalance);
- Q_UNUSED(watchImmatureBalance);
-
if(model && model->getOptionsModel())
{
- ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
+ ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balances.balance));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
- setBalance(model->getBalance(), 0, 0, 0, 0, 0);
+ setBalance(model->wallet().getBalances());
ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
updateMinFeeLabel();
updateSmartFeeLabel();
@@ -570,7 +566,7 @@ void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::AbsurdFee:
- msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), maxTxFee));
+ msgParams.first = tr("A fee higher than %1 is considered an absurdly high fee.").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->node().getMaxTxFee()));
break;
case WalletModel::PaymentRequestExpired:
msgParams.first = tr("Payment request expired.");
@@ -615,7 +611,7 @@ void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry)
}
// Calculate available amount to send.
- CAmount amount = model->getBalance(&coin_control);
+ CAmount amount = model->wallet().getAvailableBalance(coin_control);
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* e = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (e && !e->isHidden() && e != entry) {
@@ -633,7 +629,7 @@ void SendCoinsDialog::useAvailableBalance(SendCoinsEntry* entry)
void SendCoinsDialog::setMinimumFee()
{
- ui->customFee->setValue(GetRequiredFee(1000));
+ ui->customFee->setValue(model->node().getRequiredFee(1000));
}
void SendCoinsDialog::updateFeeSectionControls()
@@ -665,7 +661,7 @@ void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the required fee of %1").arg(
- BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), GetRequiredFee(1000)) + "/kB")
+ BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->node().getRequiredFee(1000)) + "/kB")
);
}
@@ -689,12 +685,13 @@ void SendCoinsDialog::updateSmartFeeLabel()
CCoinControl coin_control;
updateCoinControlState(coin_control);
coin_control.m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels
- FeeCalculation feeCalc;
- CFeeRate feeRate = CFeeRate(GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
+ int returned_target;
+ FeeReason reason;
+ CFeeRate feeRate = CFeeRate(model->node().getMinimumFee(1000, coin_control, &returned_target, &reason));
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
- if (feeCalc.reason == FeeReason::FALLBACK) {
+ if (reason == FeeReason::FALLBACK) {
ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...)
ui->labelFeeEstimation->setText("");
ui->fallbackFeeWarningLabel->setVisible(true);
@@ -706,7 +703,7 @@ void SendCoinsDialog::updateSmartFeeLabel()
else
{
ui->labelSmartFee2->hide();
- ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", feeCalc.returnedTarget));
+ ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", returned_target));
ui->fallbackFeeWarningLabel->setVisible(false);
}
@@ -811,7 +808,7 @@ void SendCoinsDialog::coinControlChangeEdited(const QString& text)
}
else // Valid address
{
- if (!model->IsSpendable(dest)) {
+ if (!model->wallet().isSpendable(dest)) {
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
// confirmation dialog
diff --git a/src/qt/sendcoinsdialog.h b/src/qt/sendcoinsdialog.h
index 48885bbcad..43757e3186 100644
--- a/src/qt/sendcoinsdialog.h
+++ b/src/qt/sendcoinsdialog.h
@@ -51,8 +51,7 @@ public Q_SLOTS:
void accept();
SendCoinsEntry *addEntry();
void updateTabsAndLabels();
- void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
- const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance);
+ void setBalance(const interface::WalletBalances& balances);
Q_SIGNALS:
void coinsSent(const uint256& txid);
diff --git a/src/qt/sendcoinsentry.cpp b/src/qt/sendcoinsentry.cpp
index b7decbb69b..6a961d83ea 100644
--- a/src/qt/sendcoinsentry.cpp
+++ b/src/qt/sendcoinsentry.cpp
@@ -127,7 +127,7 @@ void SendCoinsEntry::useAvailableBalanceClicked()
Q_EMIT useAvailableBalance(this);
}
-bool SendCoinsEntry::validate()
+bool SendCoinsEntry::validate(interface::Node& node)
{
if (!model)
return false;
@@ -158,7 +158,7 @@ bool SendCoinsEntry::validate()
}
// Reject dust outputs:
- if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
+ if (retval && GUIUtil::isDust(node, ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
diff --git a/src/qt/sendcoinsentry.h b/src/qt/sendcoinsentry.h
index a9fdd5938c..715f4cfde5 100644
--- a/src/qt/sendcoinsentry.h
+++ b/src/qt/sendcoinsentry.h
@@ -30,7 +30,7 @@ public:
~SendCoinsEntry();
void setModel(WalletModel *model);
- bool validate();
+ bool validate(interface::Node& node);
SendCoinsRecipient getValue();
/** Return whether the entry is still empty and unedited */
diff --git a/src/qt/signverifymessagedialog.cpp b/src/qt/signverifymessagedialog.cpp
index 8dade8df79..94a3ad7987 100644
--- a/src/qt/signverifymessagedialog.cpp
+++ b/src/qt/signverifymessagedialog.cpp
@@ -140,7 +140,7 @@ void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
}
CKey key;
- if (!model->getPrivKey(*keyID, key))
+ if (!model->wallet().getPrivKey(*keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp
index 5df1282f73..2475a82ef9 100644
--- a/src/qt/splashscreen.cpp
+++ b/src/qt/splashscreen.cpp
@@ -12,22 +12,21 @@
#include <clientversion.h>
#include <init.h>
+#include <interface/handler.h>
+#include <interface/node.h>
+#include <interface/wallet.h>
#include <util.h>
#include <ui_interface.h>
#include <version.h>
-#ifdef ENABLE_WALLET
-#include <wallet/wallet.h>
-#endif
-
#include <QApplication>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QPainter>
#include <QRadialGradient>
-SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) :
- QWidget(0, f), curAlignment(0)
+SplashScreen::SplashScreen(interface::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) :
+ QWidget(0, f), curAlignment(0), m_node(node)
{
// set reference point, paddings
int paddingRight = 50;
@@ -91,7 +90,7 @@ SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle)
pixPaint.setFont(QFont(font, 15*fontFactor));
- // if the version string is to long, reduce size
+ // if the version string is too long, reduce size
fm = pixPaint.fontMetrics();
int versionTextWidth = fm.width(versionText);
if(versionTextWidth > titleTextWidth+paddingRight-10) {
@@ -143,7 +142,7 @@ bool SplashScreen::eventFilter(QObject * obj, QEvent * ev) {
if (ev->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
if(keyEvent->text()[0] == 'q') {
- StartShutdown();
+ m_node.startShutdown();
}
}
return QObject::eventFilter(obj, ev);
@@ -177,35 +176,34 @@ static void ShowProgress(SplashScreen *splash, const std::string &title, int nPr
: _("press q to shutdown")) +
strprintf("\n%d", nProgress) + "%");
}
-
#ifdef ENABLE_WALLET
-void SplashScreen::ConnectWallet(CWallet* wallet)
+void SplashScreen::ConnectWallet(std::unique_ptr<interface::Wallet> wallet)
{
- wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2, false));
- connectedWallets.push_back(wallet);
+ m_connected_wallet_handlers.emplace_back(wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2, false)));
+ m_connected_wallets.emplace_back(std::move(wallet));
}
#endif
void SplashScreen::subscribeToCoreSignals()
{
// Connect signals to client
- uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));
- uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2, _3));
+ m_handler_init_message = m_node.handleInitMessage(boost::bind(InitMessage, this, _1));
+ m_handler_show_progress = m_node.handleShowProgress(boost::bind(ShowProgress, this, _1, _2, _3));
#ifdef ENABLE_WALLET
- uiInterface.LoadWallet.connect(boost::bind(&SplashScreen::ConnectWallet, this, _1));
+ m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interface::Wallet> wallet) { ConnectWallet(std::move(wallet)); });
#endif
}
void SplashScreen::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
- uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
- uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2, _3));
-#ifdef ENABLE_WALLET
- for (CWallet* const & pwallet : connectedWallets) {
- pwallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2, false));
+ m_handler_init_message->disconnect();
+ m_handler_show_progress->disconnect();
+ for (auto& handler : m_connected_wallet_handlers) {
+ handler->disconnect();
}
-#endif
+ m_connected_wallet_handlers.clear();
+ m_connected_wallets.clear();
}
void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color)
@@ -227,6 +225,6 @@ void SplashScreen::paintEvent(QPaintEvent *event)
void SplashScreen::closeEvent(QCloseEvent *event)
{
- StartShutdown(); // allows an "emergency" shutdown during startup
+ m_node.startShutdown(); // allows an "emergency" shutdown during startup
event->ignore();
}
diff --git a/src/qt/splashscreen.h b/src/qt/splashscreen.h
index e1568e406b..419f36f641 100644
--- a/src/qt/splashscreen.h
+++ b/src/qt/splashscreen.h
@@ -8,9 +8,16 @@
#include <functional>
#include <QSplashScreen>
-class CWallet;
+#include <memory>
+
class NetworkStyle;
+namespace interface {
+class Handler;
+class Node;
+class Wallet;
+};
+
/** Class for the splashscreen with information of the running client.
*
* @note this is intentionally not a QSplashScreen. Bitcoin Core initialization
@@ -22,7 +29,7 @@ class SplashScreen : public QWidget
Q_OBJECT
public:
- explicit SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle);
+ explicit SplashScreen(interface::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle);
~SplashScreen();
protected:
@@ -45,14 +52,19 @@ private:
/** Disconnect core signals to splash screen */
void unsubscribeFromCoreSignals();
/** Connect wallet signals to splash screen */
- void ConnectWallet(CWallet*);
+ void ConnectWallet(std::unique_ptr<interface::Wallet> wallet);
QPixmap pixmap;
QString curMessage;
QColor curColor;
int curAlignment;
- QList<CWallet*> connectedWallets;
+ 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;
};
#endif // BITCOIN_QT_SPLASHSCREEN_H
diff --git a/src/qt/test/paymentrequestdata.h b/src/qt/test/paymentrequestdata.h
index 74a2db8ea2..8e5a259f68 100644
--- a/src/qt/test/paymentrequestdata.h
+++ b/src/qt/test/paymentrequestdata.h
@@ -2,6 +2,9 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#ifndef BITCOIN_QT_TEST_PAYMENTREQUESTDATA_H
+#define BITCOIN_QT_TEST_PAYMENTREQUESTDATA_H
+
//
// Data for paymentservertests.cpp
//
@@ -458,3 +461,5 @@ iEBFUrBDJZU+UEezGwr7/zoECjo5ZY3PmtZcM2sILNjyweJF6XVzGqTxUw6pN6sW\
XR2T3Gy2LzRvhVA25QgGqpz0/juS2BtmNbsZPkN9gMMwKimgzc+PuCzmEKwPK9cQ\
YQ==\
";
+
+#endif // BITCOIN_QT_TEST_PAYMENTREQUESTDATA_H
diff --git a/src/qt/test/paymentservertests.cpp b/src/qt/test/paymentservertests.cpp
index 29ef4b4c9e..46e9d4d0a4 100644
--- a/src/qt/test/paymentservertests.cpp
+++ b/src/qt/test/paymentservertests.cpp
@@ -9,6 +9,7 @@
#include <amount.h>
#include <chainparams.h>
+#include <interface/node.h>
#include <random.h>
#include <script/script.h>
#include <script/standard.h>
@@ -66,7 +67,8 @@ static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsig
void PaymentServerTests::paymentServerTests()
{
SelectParams(CBaseChainParams::MAIN);
- OptionsModel optionsModel;
+ auto node = interface::MakeNode();
+ OptionsModel optionsModel(*node);
PaymentServer* server = new PaymentServer(nullptr, false);
X509_STORE* caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));
@@ -145,7 +147,7 @@ void PaymentServerTests::paymentServerTests()
// Ensure the request is initialized, because network "main" is default, even for
// uninitialized payment requests and that will fail our test here.
QVERIFY(r.paymentRequest.IsInitialized());
- QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);
+ QCOMPARE(PaymentServer::verifyNetwork(*node, r.paymentRequest.getDetails()), false);
// Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
data = DecodeBase64(paymentrequest2_cert2_BASE64);
diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp
index 9d0e0b97d1..467107dc4c 100644
--- a/src/qt/test/rpcnestedtests.cpp
+++ b/src/qt/test/rpcnestedtests.cpp
@@ -7,6 +7,7 @@
#include <chainparams.h>
#include <consensus/validation.h>
#include <fs.h>
+#include <interface/node.h>
#include <validation.h>
#include <rpc/register.h>
#include <rpc/server.h>
@@ -45,89 +46,90 @@ void RPCNestedTests::rpcNestedTests()
std::string result;
std::string result2;
std::string filtered;
- RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
+ auto node = interface::MakeNode();
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
- RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting
- RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)");
- RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
- RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
- RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
- RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
- (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
+ (RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
- (RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
- (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
+ (RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
+ (RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
- (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
+ (RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
- RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered);
+ RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
- RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
- RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
- RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
- RPCConsole::RPCParseCommandLine(result, "signrawtransactionwithkey(abc)", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
- RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
- RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
- RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
- RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
- RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
- RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
+ RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest");
QVERIFY(result == "[]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\"");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
- RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )");
+ RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
#if QT_VERSION >= 0x050300
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
- (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
- (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
- QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
+ (RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
+ (RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
+ QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
}
diff --git a/src/qt/test/rpcnestedtests.h b/src/qt/test/rpcnestedtests.h
index 0ce1c66f44..7b3b38f62e 100644
--- a/src/qt/test/rpcnestedtests.h
+++ b/src/qt/test/rpcnestedtests.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_QT_TEST_RPC_NESTED_TESTS_H
-#define BITCOIN_QT_TEST_RPC_NESTED_TESTS_H
+#ifndef BITCOIN_QT_TEST_RPCNESTEDTESTS_H
+#define BITCOIN_QT_TEST_RPCNESTEDTESTS_H
#include <QObject>
#include <QTest>
@@ -19,4 +19,4 @@ class RPCNestedTests : public QObject
void rpcNestedTests();
};
-#endif // BITCOIN_QT_TEST_RPC_NESTED_TESTS_H
+#endif // BITCOIN_QT_TEST_RPCNESTEDTESTS_H
diff --git a/src/qt/test/uritests.cpp b/src/qt/test/uritests.cpp
index 8415250630..59938f704a 100644
--- a/src/qt/test/uritests.cpp
+++ b/src/qt/test/uritests.cpp
@@ -51,7 +51,7 @@ void URITests::uriTests()
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
- QVERIFY(GUIUtil::parseBitcoinURI("bitcoin://175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address", &rv));
+ QVERIFY(GUIUtil::parseBitcoinURI("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp
index 976aadc0af..b60c5b979f 100644
--- a/src/qt/test/wallettests.cpp
+++ b/src/qt/test/wallettests.cpp
@@ -1,5 +1,6 @@
#include <qt/test/wallettests.h>
+#include <interface/node.h>
#include <qt/bitcoinamountfield.h>
#include <qt/callback.h>
#include <qt/optionsmodel.h>
@@ -19,6 +20,8 @@
#include <qt/recentrequeststablemodel.h>
#include <qt/receiverequestdialog.h>
+#include <memory>
+
#include <QAbstractButton>
#include <QAction>
#include <QApplication>
@@ -150,9 +153,6 @@ void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, st
// src/qt/test/test_bitcoin-qt -platform cocoa # macOS
void TestGUI()
{
- g_address_type = OUTPUT_TYPE_P2SH_SEGWIT;
- g_change_type = OUTPUT_TYPE_P2SH_SEGWIT;
-
// Set up wallet and chain with 105 blocks (5 mature blocks for spending).
TestChain100Setup test;
for (int i = 0; i < 5; ++i) {
@@ -163,7 +163,7 @@ void TestGUI()
wallet.LoadWallet(firstRun);
{
LOCK(wallet.cs_wallet);
- wallet.SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), g_address_type), "", "receive");
+ wallet.SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), wallet.m_default_address_type), "", "receive");
wallet.AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey());
}
{
@@ -178,8 +178,11 @@ void TestGUI()
std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
SendCoinsDialog sendCoinsDialog(platformStyle.get());
TransactionView transactionView(platformStyle.get());
- OptionsModel optionsModel;
- WalletModel walletModel(platformStyle.get(), &wallet, &optionsModel);
+ auto node = interface::MakeNode();
+ OptionsModel optionsModel(*node);
+ vpwallets.insert(vpwallets.begin(), &wallet);
+ WalletModel walletModel(std::move(node->getWallets()[0]), *node, platformStyle.get(), &optionsModel);
+ vpwallets.erase(vpwallets.begin());
sendCoinsDialog.setModel(&walletModel);
transactionView.setModel(&walletModel);
@@ -204,7 +207,7 @@ void TestGUI()
QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance");
QString balanceText = balanceLabel->text();
int unit = walletModel.getOptionsModel()->getDisplayUnit();
- CAmount balance = walletModel.getBalance();
+ CAmount balance = walletModel.wallet().getBalance();
QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways);
QCOMPARE(balanceText, balanceComparison);
diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp
index f869799462..ff378ed1bf 100644
--- a/src/qt/trafficgraphwidget.cpp
+++ b/src/qt/trafficgraphwidget.cpp
@@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#include <interface/node.h>
#include <qt/trafficgraphwidget.h>
#include <qt/clientmodel.h>
@@ -35,8 +36,8 @@ void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
- nLastBytesIn = model->getTotalBytesRecv();
- nLastBytesOut = model->getTotalBytesSent();
+ nLastBytesIn = model->node().getTotalBytesRecv();
+ nLastBytesOut = model->node().getTotalBytesSent();
}
}
@@ -123,8 +124,8 @@ void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
- quint64 bytesIn = clientModel->getTotalBytesRecv(),
- bytesOut = clientModel->getTotalBytesSent();
+ quint64 bytesIn = clientModel->node().getTotalBytesRecv(),
+ bytesOut = clientModel->node().getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
@@ -169,8 +170,8 @@ void TrafficGraphWidget::clear()
fMax = 0.0f;
if(clientModel) {
- nLastBytesIn = clientModel->getTotalBytesRecv();
- nLastBytesOut = clientModel->getTotalBytesSent();
+ nLastBytesIn = clientModel->node().getTotalBytesRecv();
+ nLastBytesOut = clientModel->node().getTotalBytesSent();
}
timer->start();
}
diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp
index ec5a66bc9f..409835592f 100644
--- a/src/qt/transactiondesc.cpp
+++ b/src/qt/transactiondesc.cpp
@@ -10,6 +10,7 @@
#include <qt/transactionrecord.h>
#include <consensus/consensus.h>
+#include <interface/node.h>
#include <key_io.h>
#include <validation.h>
#include <script/script.h>
@@ -22,25 +23,24 @@
#include <stdint.h>
#include <string>
-QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
+QString TransactionDesc::FormatTxStatus(const interface::WalletTx& wtx, const interface::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime)
{
- AssertLockHeld(cs_main);
- if (!CheckFinalTx(*wtx.tx))
+ if (!status.is_final)
{
if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)
- return tr("Open for %n more block(s)", "", wtx.tx->nLockTime - chainActive.Height());
+ return tr("Open for %n more block(s)", "", wtx.tx->nLockTime - numBlocks);
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime));
}
else
{
- int nDepth = wtx.GetDepthInMainChain();
+ int nDepth = status.depth_in_main_chain;
if (nDepth < 0)
return tr("conflicted with a transaction with %1 confirmations").arg(-nDepth);
- else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
+ else if (adjustedTime - status.time_received > 2 * 60 && status.request_count == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth == 0)
- return tr("0/unconfirmed, %1").arg((wtx.InMempool() ? tr("in memory pool") : tr("not in memory pool"))) + (wtx.isAbandoned() ? ", "+tr("abandoned") : "");
+ return tr("0/unconfirmed, %1").arg((inMempool ? tr("in memory pool") : tr("not in memory pool"))) + (status.is_abandoned ? ", "+tr("abandoned") : "");
else if (nDepth < 6)
return tr("%1/unconfirmed").arg(nDepth);
else
@@ -48,21 +48,27 @@ QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
}
}
-QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
+QString TransactionDesc::toHTML(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit)
{
+ int numBlocks;
+ int64_t adjustedTime;
+ interface::WalletTxStatus status;
+ interface::WalletOrderForm orderForm;
+ bool inMempool;
+ interface::WalletTx wtx = wallet.getWalletTxDetails(rec->hash, status, orderForm, inMempool, numBlocks, adjustedTime);
+
QString strHTML;
- LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
- int64_t nTime = wtx.GetTxTime();
- CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
- CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
+ int64_t nTime = wtx.time;
+ CAmount nCredit = wtx.credit;
+ CAmount nDebit = wtx.debit;
CAmount nNet = nCredit - nDebit;
- strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
- int nRequests = wtx.GetRequestCount();
+ strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx, status, inMempool, numBlocks, adjustedTime);
+ int nRequests = status.request_count;
if (nRequests != -1)
{
if (nRequests == 0)
@@ -77,14 +83,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// From
//
- if (wtx.IsCoinBase())
+ if (wtx.is_coinbase)
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
- else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
+ else if (wtx.value_map.count("from") && !wtx.value_map["from"].empty())
{
// Online transaction
- strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
+ strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.value_map["from"]) + "<br>";
}
else
{
@@ -94,14 +100,16 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
// Credit
CTxDestination address = DecodeDestination(rec->address);
if (IsValidDestination(address)) {
- if (wallet->mapAddressBook.count(address))
+ std::string name;
+ isminetype ismine;
+ if (wallet.getAddress(address, &name, &ismine))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
- QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only");
- if (!wallet->mapAddressBook[address].name.empty())
- strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")";
+ QString addressOwned = ismine == ISMINE_SPENDABLE ? tr("own address") : tr("watch-only");
+ if (!name.empty())
+ strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(name) + ")";
else
strHTML += " (" + addressOwned + ")";
strHTML += "<br>";
@@ -113,31 +121,32 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// To
//
- if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
+ if (wtx.value_map.count("to") && !wtx.value_map["to"].empty())
{
// Online transaction
- std::string strAddress = wtx.mapValue["to"];
+ std::string strAddress = wtx.value_map["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = DecodeDestination(strAddress);
- if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())
- strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " ";
+ std::string name;
+ if (wallet.getAddress(dest, &name) && !name.empty())
+ strHTML += GUIUtil::HtmlEscape(name) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
- if (wtx.IsCoinBase() && nCredit == 0)
+ if (wtx.is_coinbase && nCredit == 0)
{
//
// Coinbase
//
CAmount nUnmatured = 0;
for (const CTxOut& txout : wtx.tx->vout)
- nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);
+ nUnmatured += wallet.getCredit(txout, ISMINE_ALL);
strHTML += "<b>" + tr("Credit") + ":</b> ";
- if (wtx.IsInMainChain())
- strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
+ if (status.is_in_main_chain)
+ strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", status.blocks_to_maturity) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
@@ -152,16 +161,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
else
{
isminetype fAllFromMe = ISMINE_SPENDABLE;
- for (const CTxIn& txin : wtx.tx->vin)
+ for (isminetype mine : wtx.txin_is_mine)
{
- isminetype mine = wallet->IsMine(txin);
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
- for (const CTxOut& txout : wtx.tx->vout)
+ for (isminetype mine : wtx.txout_is_mine)
{
- isminetype mine = wallet->IsMine(txout);
if(fAllToMe > mine) fAllToMe = mine;
}
@@ -173,22 +180,24 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// Debit
//
+ auto mine = wtx.txout_is_mine.begin();
for (const CTxOut& txout : wtx.tx->vout)
{
// Ignore change
- isminetype toSelf = wallet->IsMine(txout);
+ isminetype toSelf = *(mine++);
if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))
continue;
- if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
+ if (!wtx.value_map.count("to") || wtx.value_map["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
- if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
- strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
+ std::string name;
+ if (wallet.getAddress(address, &name) && !name.empty())
+ strHTML += GUIUtil::HtmlEscape(name) + " ";
strHTML += GUIUtil::HtmlEscape(EncodeDestination(address));
if(toSelf == ISMINE_SPENDABLE)
strHTML += " (own address)";
@@ -206,7 +215,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
if (fAllToMe)
{
// Payment to self
- CAmount nChange = wtx.GetChange();
+ CAmount nChange = wtx.change;
CAmount nValue = nCredit - nChange;
strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>";
@@ -221,12 +230,18 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// Mixed debit transaction
//
- for (const CTxIn& txin : wtx.tx->vin)
- if (wallet->IsMine(txin))
- strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
- for (const CTxOut& txout : wtx.tx->vout)
- if (wallet->IsMine(txout))
- strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
+ auto mine = wtx.txin_is_mine.begin();
+ for (const CTxIn& txin : wtx.tx->vin) {
+ if (*(mine++)) {
+ strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet.getDebit(txin, ISMINE_ALL)) + "<br>";
+ }
+ }
+ mine = wtx.txout_is_mine.begin();
+ for (const CTxOut& txout : wtx.tx->vout) {
+ if (*(mine++)) {
+ strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet.getCredit(txout, ISMINE_ALL)) + "<br>";
+ }
+ }
}
}
@@ -235,10 +250,10 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// Message
//
- if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
- strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
- if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
- strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
+ if (wtx.value_map.count("message") && !wtx.value_map["message"].empty())
+ strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.value_map["message"], true) + "<br>";
+ if (wtx.value_map.count("comment") && !wtx.value_map["comment"].empty())
+ strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.value_map["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxHash() + "<br>";
strHTML += "<b>" + tr("Transaction total size") + ":</b> " + QString::number(wtx.tx->GetTotalSize()) + " bytes<br>";
@@ -246,14 +261,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>";
// Message from normal bitcoin:URI (bitcoin:123...?message=example)
- for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
+ for (const std::pair<std::string, std::string>& r : orderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
- for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
+ for (const std::pair<std::string, std::string>& r : orderForm)
{
if (r.first == "PaymentRequest")
{
@@ -265,7 +280,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
}
}
- if (wtx.IsCoinBase())
+ if (wtx.is_coinbase)
{
quint32 numBlocksToMaturity = COINBASE_MATURITY + 1;
strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>";
@@ -274,15 +289,15 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// Debug view
//
- if (logCategories != BCLog::NONE)
+ if (node.getLogCategories() != BCLog::NONE)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
for (const CTxIn& txin : wtx.tx->vin)
- if(wallet->IsMine(txin))
- strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
+ if(wallet.txinIsMine(txin))
+ strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet.getDebit(txin, ISMINE_ALL)) + "<br>";
for (const CTxOut& txout : wtx.tx->vout)
- if(wallet->IsMine(txout))
- strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
+ if(wallet.txoutIsMine(txout))
+ strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet.getCredit(txout, ISMINE_ALL)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true);
@@ -295,7 +310,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
COutPoint prevout = txin.prevout;
Coin prev;
- if(pcoinsTip->GetCoin(prevout, prev))
+ if(node.getUnspentOutput(prevout, prev))
{
{
strHTML += "<li>";
@@ -303,13 +318,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
- if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
- strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
+ std::string name;
+ if (wallet.getAddress(address, &name) && !name.empty())
+ strHTML += GUIUtil::HtmlEscape(name) + " ";
strHTML += QString::fromStdString(EncodeDestination(address));
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);
- strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>";
- strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>";
+ strHTML = strHTML + " IsMine=" + (wallet.txoutIsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>";
+ strHTML = strHTML + " IsWatchOnly=" + (wallet.txoutIsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>";
}
}
}
diff --git a/src/qt/transactiondesc.h b/src/qt/transactiondesc.h
index 01b90b130f..ea9ab28ee3 100644
--- a/src/qt/transactiondesc.h
+++ b/src/qt/transactiondesc.h
@@ -10,8 +10,12 @@
class TransactionRecord;
-class CWallet;
-class CWalletTx;
+namespace interface {
+class Node;
+class Wallet;
+struct WalletTx;
+struct WalletTxStatus;
+}
/** Provide a human-readable extended HTML description of a transaction.
*/
@@ -20,12 +24,12 @@ class TransactionDesc: public QObject
Q_OBJECT
public:
- static QString toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit);
+ static QString toHTML(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit);
private:
TransactionDesc() {}
- static QString FormatTxStatus(const CWalletTx& wtx);
+ static QString FormatTxStatus(const interface::WalletTx& wtx, const interface::WalletTxStatus& status, bool inMempool, int numBlocks, int64_t adjustedTime);
};
#endif // BITCOIN_QT_TRANSACTIONDESC_H
diff --git a/src/qt/transactionfilterproxy.cpp b/src/qt/transactionfilterproxy.cpp
index a702461f7a..6301af7553 100644
--- a/src/qt/transactionfilterproxy.cpp
+++ b/src/qt/transactionfilterproxy.cpp
@@ -31,31 +31,35 @@ bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
- int type = index.data(TransactionTableModel::TypeRole).toInt();
- QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
- bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();
- QString address = index.data(TransactionTableModel::AddressRole).toString();
- QString label = index.data(TransactionTableModel::LabelRole).toString();
- QString txid = index.data(TransactionTableModel::TxHashRole).toString();
- qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
int status = index.data(TransactionTableModel::StatusRole).toInt();
-
- if(!showInactive && status == TransactionStatus::Conflicted)
+ if (!showInactive && status == TransactionStatus::Conflicted)
return false;
- if(!(TYPE(type) & typeFilter))
+
+ int type = index.data(TransactionTableModel::TypeRole).toInt();
+ if (!(TYPE(type) & typeFilter))
return false;
+
+ bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();
if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)
return false;
if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)
return false;
- if(datetime < dateFrom || datetime > dateTo)
+
+ QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
+ if (datetime < dateFrom || datetime > dateTo)
return false;
+
+ QString address = index.data(TransactionTableModel::AddressRole).toString();
+ QString label = index.data(TransactionTableModel::LabelRole).toString();
+ QString txid = index.data(TransactionTableModel::TxHashRole).toString();
if (!address.contains(m_search_string, Qt::CaseInsensitive) &&
! label.contains(m_search_string, Qt::CaseInsensitive) &&
! txid.contains(m_search_string, Qt::CaseInsensitive)) {
return false;
}
- if(amount < minAmount)
+
+ qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
+ if (amount < minAmount)
return false;
return true;
diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp
index 19cdb0fdea..60ab2d57d7 100644
--- a/src/qt/transactionrecord.cpp
+++ b/src/qt/transactionrecord.cpp
@@ -5,17 +5,17 @@
#include <qt/transactionrecord.h>
#include <consensus/consensus.h>
+#include <interface/wallet.h>
#include <key_io.h>
-#include <validation.h>
#include <timedata.h>
-#include <wallet/wallet.h>
+#include <validation.h>
#include <stdint.h>
/* Return positive answer if transaction should be shown in list.
*/
-bool TransactionRecord::showTransaction(const CWalletTx &wtx)
+bool TransactionRecord::showTransaction()
{
// There are currently no cases where we hide transactions, but
// we may want to use this in the future for things like RBF.
@@ -25,17 +25,17 @@ bool TransactionRecord::showTransaction(const CWalletTx &wtx)
/*
* Decompose CWallet transaction to model transaction records.
*/
-QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
+QList<TransactionRecord> TransactionRecord::decomposeTransaction(const interface::WalletTx& wtx)
{
QList<TransactionRecord> parts;
- int64_t nTime = wtx.GetTxTime();
- CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
- CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
+ int64_t nTime = wtx.time;
+ CAmount nCredit = wtx.credit;
+ CAmount nDebit = wtx.debit;
CAmount nNet = nCredit - nDebit;
- uint256 hash = wtx.GetHash();
- std::map<std::string, std::string> mapValue = wtx.mapValue;
+ uint256 hash = wtx.tx->GetHash();
+ std::map<std::string, std::string> mapValue = wtx.value_map;
- if (nNet > 0 || wtx.IsCoinBase())
+ if (nNet > 0 || wtx.is_coinbase)
{
//
// Credit
@@ -43,7 +43,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
for(unsigned int i = 0; i < wtx.tx->vout.size(); i++)
{
const CTxOut& txout = wtx.tx->vout[i];
- isminetype mine = wallet->IsMine(txout);
+ isminetype mine = wtx.txout_is_mine[i];
if(mine)
{
TransactionRecord sub(hash, nTime);
@@ -51,11 +51,11 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
sub.idx = i; // vout index
sub.credit = txout.nValue;
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
- if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
+ if (wtx.txout_address_is_mine[i])
{
// Received by Bitcoin Address
sub.type = TransactionRecord::RecvWithAddress;
- sub.address = EncodeDestination(address);
+ sub.address = EncodeDestination(wtx.txout_address[i]);
}
else
{
@@ -63,7 +63,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
- if (wtx.IsCoinBase())
+ if (wtx.is_coinbase)
{
// Generated
sub.type = TransactionRecord::Generated;
@@ -77,17 +77,15 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
{
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
- for (const CTxIn& txin : wtx.tx->vin)
+ for (isminetype mine : wtx.txin_is_mine)
{
- isminetype mine = wallet->IsMine(txin);
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
- for (const CTxOut& txout : wtx.tx->vout)
+ for (isminetype mine : wtx.txout_is_mine)
{
- isminetype mine = wallet->IsMine(txout);
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllToMe > mine) fAllToMe = mine;
}
@@ -95,7 +93,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
if (fAllFromMe && fAllToMe)
{
// Payment to self
- CAmount nChange = wtx.GetChange();
+ CAmount nChange = wtx.change;
parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "",
-(nDebit - nChange), nCredit - nChange));
@@ -115,19 +113,18 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
sub.idx = nOut;
sub.involvesWatchAddress = involvesWatchAddress;
- if(wallet->IsMine(txout))
+ if(wtx.txout_is_mine[nOut])
{
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
- CTxDestination address;
- if (ExtractDestination(txout.scriptPubKey, address))
+ if (!boost::get<CNoDestination>(&wtx.txout_address[nOut]))
{
// Sent to Bitcoin Address
sub.type = TransactionRecord::SendToAddress;
- sub.address = EncodeDestination(address);
+ sub.address = EncodeDestination(wtx.txout_address[nOut]);
}
else
{
@@ -161,53 +158,46 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
return parts;
}
-void TransactionRecord::updateStatus(const CWalletTx &wtx)
+void TransactionRecord::updateStatus(const interface::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime)
{
- AssertLockHeld(cs_main);
// Determine transaction status
- // Find the block the tx is in
- CBlockIndex* pindex = nullptr;
- BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
- if (mi != mapBlockIndex.end())
- pindex = (*mi).second;
-
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
- (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
- (wtx.IsCoinBase() ? 1 : 0),
- wtx.nTimeReceived,
+ wtx.block_height,
+ wtx.is_coinbase ? 1 : 0,
+ wtx.time_received,
idx);
- status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
- status.depth = wtx.GetDepthInMainChain();
- status.cur_num_blocks = chainActive.Height();
+ status.countsForBalance = wtx.is_trusted && !(wtx.blocks_to_maturity > 0);
+ status.depth = wtx.depth_in_main_chain;
+ status.cur_num_blocks = numBlocks;
- if (!CheckFinalTx(*wtx.tx))
+ if (!wtx.is_final)
{
- if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)
+ if (wtx.lock_time < LOCKTIME_THRESHOLD)
{
status.status = TransactionStatus::OpenUntilBlock;
- status.open_for = wtx.tx->nLockTime - chainActive.Height();
+ status.open_for = wtx.lock_time - numBlocks;
}
else
{
status.status = TransactionStatus::OpenUntilDate;
- status.open_for = wtx.tx->nLockTime;
+ status.open_for = wtx.lock_time;
}
}
// For generated transactions, determine maturity
else if(type == TransactionRecord::Generated)
{
- if (wtx.GetBlocksToMaturity() > 0)
+ if (wtx.blocks_to_maturity > 0)
{
status.status = TransactionStatus::Immature;
- if (wtx.IsInMainChain())
+ if (wtx.is_in_main_chain)
{
- status.matures_in = wtx.GetBlocksToMaturity();
+ status.matures_in = wtx.blocks_to_maturity;
// Check if the block was requested by anyone
- if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
+ if (adjustedTime - wtx.time_received > 2 * 60 && wtx.request_count == 0)
status.status = TransactionStatus::MaturesWarning;
}
else
@@ -226,14 +216,14 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
status.status = TransactionStatus::Conflicted;
}
- else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
+ else if (adjustedTime - wtx.time_received > 2 * 60 && wtx.request_count == 0)
{
status.status = TransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TransactionStatus::Unconfirmed;
- if (wtx.isAbandoned())
+ if (wtx.is_abandoned)
status.status = TransactionStatus::Abandoned;
}
else if (status.depth < RecommendedNumConfirmations)
@@ -248,10 +238,9 @@ void TransactionRecord::updateStatus(const CWalletTx &wtx)
status.needsUpdate = false;
}
-bool TransactionRecord::statusUpdateNeeded() const
+bool TransactionRecord::statusUpdateNeeded(int numBlocks) const
{
- AssertLockHeld(cs_main);
- return status.cur_num_blocks != chainActive.Height() || status.needsUpdate;
+ return status.cur_num_blocks != numBlocks || status.needsUpdate;
}
QString TransactionRecord::getTxHash() const
diff --git a/src/qt/transactionrecord.h b/src/qt/transactionrecord.h
index 5321d05d15..c653584b52 100644
--- a/src/qt/transactionrecord.h
+++ b/src/qt/transactionrecord.h
@@ -11,8 +11,12 @@
#include <QList>
#include <QString>
-class CWallet;
-class CWalletTx;
+namespace interface {
+class Node;
+class Wallet;
+struct WalletTx;
+struct WalletTxStatus;
+}
/** UI model for transaction status. The transaction status is the part of a transaction that will change over time.
*/
@@ -106,8 +110,8 @@ public:
/** Decompose CWallet transaction to model transaction records.
*/
- static bool showTransaction(const CWalletTx &wtx);
- static QList<TransactionRecord> decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx);
+ static bool showTransaction();
+ static QList<TransactionRecord> decomposeTransaction(const interface::WalletTx& wtx);
/** @name Immutable transaction attributes
@{*/
@@ -136,11 +140,11 @@ public:
/** Update status from core wallet tx.
*/
- void updateStatus(const CWalletTx &wtx);
+ void updateStatus(const interface::WalletTxStatus& wtx, int numBlocks, int64_t adjustedTime);
/** Return whether a status update is needed.
*/
- bool statusUpdateNeeded() const;
+ bool statusUpdateNeeded(int numBlocks) const;
};
#endif // BITCOIN_QT_TRANSACTIONRECORD_H
diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp
index 84800125fe..2148ff1728 100644
--- a/src/qt/transactiontablemodel.cpp
+++ b/src/qt/transactiontablemodel.cpp
@@ -14,11 +14,12 @@
#include <qt/walletmodel.h>
#include <core_io.h>
+#include <interface/handler.h>
+#include <interface/node.h>
#include <validation.h>
#include <sync.h>
#include <uint256.h>
#include <util.h>
-#include <wallet/wallet.h>
#include <QColor>
#include <QDateTime>
@@ -57,13 +58,11 @@ struct TxLessThan
class TransactionTablePriv
{
public:
- TransactionTablePriv(CWallet *_wallet, TransactionTableModel *_parent) :
- wallet(_wallet),
+ TransactionTablePriv(TransactionTableModel *_parent) :
parent(_parent)
{
}
- CWallet *wallet;
TransactionTableModel *parent;
/* Local cache of wallet.
@@ -74,16 +73,15 @@ public:
/* Query entire wallet anew from core.
*/
- void refreshWallet()
+ void refreshWallet(interface::Wallet& wallet)
{
qDebug() << "TransactionTablePriv::refreshWallet";
cachedWallet.clear();
{
- LOCK2(cs_main, wallet->cs_wallet);
- for (const auto& entry : wallet->mapWallet)
- {
- if (TransactionRecord::showTransaction(entry.second))
- cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, entry.second));
+ for (const auto& wtx : wallet.getWalletTxs()) {
+ if (TransactionRecord::showTransaction()) {
+ cachedWallet.append(TransactionRecord::decomposeTransaction(wtx));
+ }
}
}
}
@@ -93,7 +91,7 @@ public:
Call with transaction that was added, removed or changed.
*/
- void updateWallet(const uint256 &hash, int status, bool showTransaction)
+ void updateWallet(interface::Wallet& wallet, const uint256 &hash, int status, bool showTransaction)
{
qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);
@@ -128,17 +126,16 @@ public:
}
if(showTransaction)
{
- LOCK2(cs_main, wallet->cs_wallet);
// Find transaction in wallet
- std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
- if(mi == wallet->mapWallet.end())
+ interface::WalletTx wtx = wallet.getWalletTx(hash);
+ if(!wtx.tx)
{
qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet";
break;
}
// Added -- insert at the right position
QList<TransactionRecord> toInsert =
- TransactionRecord::decomposeTransaction(wallet, mi->second);
+ TransactionRecord::decomposeTransaction(wtx);
if(!toInsert.isEmpty()) /* only if something to insert */
{
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);
@@ -179,7 +176,7 @@ public:
return cachedWallet.size();
}
- TransactionRecord *index(int idx)
+ TransactionRecord *index(interface::Wallet& wallet, int idx)
{
if(idx >= 0 && idx < cachedWallet.size())
{
@@ -192,61 +189,42 @@ public:
// If a status update is needed (blocks came in since last check),
// update the status of this transaction from the wallet. Otherwise,
// simply re-use the cached status.
- TRY_LOCK(cs_main, lockMain);
- if(lockMain)
- {
- TRY_LOCK(wallet->cs_wallet, lockWallet);
- if(lockWallet && rec->statusUpdateNeeded())
- {
- std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
-
- if(mi != wallet->mapWallet.end())
- {
- rec->updateStatus(mi->second);
- }
- }
+ interface::WalletTxStatus wtx;
+ int numBlocks;
+ int64_t adjustedTime;
+ if (wallet.tryGetTxStatus(rec->hash, wtx, numBlocks, adjustedTime) && rec->statusUpdateNeeded(numBlocks)) {
+ rec->updateStatus(wtx, numBlocks, adjustedTime);
}
return rec;
}
return 0;
}
- QString describe(TransactionRecord *rec, int unit)
+ QString describe(interface::Node& node, interface::Wallet& wallet, TransactionRecord *rec, int unit)
{
- {
- LOCK2(cs_main, wallet->cs_wallet);
- std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
- if(mi != wallet->mapWallet.end())
- {
- return TransactionDesc::toHTML(wallet, mi->second, rec, unit);
- }
- }
- return QString();
+ return TransactionDesc::toHTML(node, wallet, rec, unit);
}
- QString getTxHex(TransactionRecord *rec)
+ QString getTxHex(interface::Wallet& wallet, TransactionRecord *rec)
{
- LOCK2(cs_main, wallet->cs_wallet);
- std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
- if(mi != wallet->mapWallet.end())
- {
- std::string strHex = EncodeHexTx(*mi->second.tx);
+ auto tx = wallet.getTx(rec->hash);
+ if (tx) {
+ std::string strHex = EncodeHexTx(*tx);
return QString::fromStdString(strHex);
}
return QString();
}
};
-TransactionTableModel::TransactionTableModel(const PlatformStyle *_platformStyle, CWallet* _wallet, WalletModel *parent):
+TransactionTableModel::TransactionTableModel(const PlatformStyle *_platformStyle, WalletModel *parent):
QAbstractTableModel(parent),
- wallet(_wallet),
walletModel(parent),
- priv(new TransactionTablePriv(_wallet, this)),
+ priv(new TransactionTablePriv(this)),
fProcessingQueuedTransactions(false),
platformStyle(_platformStyle)
{
columns << QString() << QString() << tr("Date") << tr("Type") << tr("Label") << BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
- priv->refreshWallet();
+ priv->refreshWallet(walletModel->wallet());
connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
@@ -271,7 +249,7 @@ void TransactionTableModel::updateTransaction(const QString &hash, int status, b
uint256 updated;
updated.SetHex(hash.toStdString());
- priv->updateWallet(updated, status, showTransaction);
+ priv->updateWallet(walletModel->wallet(), updated, status, showTransaction);
}
void TransactionTableModel::updateConfirmations()
@@ -608,7 +586,7 @@ QVariant TransactionTableModel::data(const QModelIndex &index, int role) const
case WatchonlyDecorationRole:
return txWatchonlyDecoration(rec);
case LongDescriptionRole:
- return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit());
+ return priv->describe(walletModel->node(), walletModel->wallet(), rec, walletModel->getOptionsModel()->getDisplayUnit());
case AddressRole:
return QString::fromStdString(rec->address);
case LabelRole:
@@ -618,7 +596,7 @@ QVariant TransactionTableModel::data(const QModelIndex &index, int role) const
case TxHashRole:
return rec->getTxHash();
case TxHexRole:
- return priv->getTxHex(rec);
+ return priv->getTxHex(walletModel->wallet(), rec);
case TxPlainTextRole:
{
QString details;
@@ -694,10 +672,10 @@ QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientat
QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
- TransactionRecord *data = priv->index(row);
+ TransactionRecord *data = priv->index(walletModel->wallet(), row);
if(data)
{
- return createIndex(row, column, priv->index(row));
+ return createIndex(row, column, priv->index(walletModel->wallet(), row));
}
return QModelIndex();
}
@@ -735,13 +713,11 @@ private:
static bool fQueueNotifications = false;
static std::vector< TransactionNotification > vQueueNotifications;
-static void NotifyTransactionChanged(TransactionTableModel *ttm, CWallet *wallet, const uint256 &hash, ChangeType status)
+static void NotifyTransactionChanged(TransactionTableModel *ttm, const uint256 &hash, ChangeType status)
{
// Find transaction in wallet
- std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
// Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread)
- bool inWallet = mi != wallet->mapWallet.end();
- bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));
+ bool showTransaction = TransactionRecord::showTransaction();
TransactionNotification notification(hash, status, showTransaction);
@@ -777,13 +753,13 @@ static void ShowProgress(TransactionTableModel *ttm, const std::string &title, i
void TransactionTableModel::subscribeToCoreSignals()
{
// Connect signals to wallet
- wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
- wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
+ m_handler_transaction_changed = walletModel->wallet().handleTransactionChanged(boost::bind(NotifyTransactionChanged, this, _1, _2));
+ m_handler_show_progress = walletModel->wallet().handleShowProgress(boost::bind(ShowProgress, this, _1, _2));
}
void TransactionTableModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
- wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
- wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
+ m_handler_transaction_changed->disconnect();
+ m_handler_show_progress->disconnect();
}
diff --git a/src/qt/transactiontablemodel.h b/src/qt/transactiontablemodel.h
index 781874d160..57566db638 100644
--- a/src/qt/transactiontablemodel.h
+++ b/src/qt/transactiontablemodel.h
@@ -10,13 +10,17 @@
#include <QAbstractTableModel>
#include <QStringList>
+#include <memory>
+
+namespace interface {
+class Handler;
+}
+
class PlatformStyle;
class TransactionRecord;
class TransactionTablePriv;
class WalletModel;
-class CWallet;
-
/** UI model for the transaction table of a wallet.
*/
class TransactionTableModel : public QAbstractTableModel
@@ -24,7 +28,7 @@ class TransactionTableModel : public QAbstractTableModel
Q_OBJECT
public:
- explicit TransactionTableModel(const PlatformStyle *platformStyle, CWallet* wallet, WalletModel *parent = 0);
+ explicit TransactionTableModel(const PlatformStyle *platformStyle, WalletModel *parent = 0);
~TransactionTableModel();
enum ColumnIndex {
@@ -80,8 +84,9 @@ public:
bool processingQueuedTransactions() const { return fProcessingQueuedTransactions; }
private:
- CWallet* wallet;
WalletModel *walletModel;
+ std::unique_ptr<interface::Handler> m_handler_transaction_changed;
+ std::unique_ptr<interface::Handler> m_handler_show_progress;
QStringList columns;
TransactionTablePriv *priv;
bool fProcessingQueuedTransactions;
diff --git a/src/qt/transactionview.cpp b/src/qt/transactionview.cpp
index 26391452da..aa6444245a 100644
--- a/src/qt/transactionview.cpp
+++ b/src/qt/transactionview.cpp
@@ -254,7 +254,7 @@ void TransactionView::setModel(WalletModel *_model)
}
// show/hide column Watch-only
- updateWatchOnlyColumn(_model->haveWatchOnly());
+ updateWatchOnlyColumn(_model->wallet().haveWatchOnly());
// Watch-only signal
connect(_model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyColumn(bool)));
@@ -364,7 +364,7 @@ void TransactionView::exportClicked()
// name, column, role
writer.setModel(transactionProxyModel);
writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
- if (model->haveWatchOnly())
+ if (model->wallet().haveWatchOnly())
writer.addColumn(tr("Watch-only"), TransactionTableModel::Watchonly);
writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
@@ -393,8 +393,8 @@ void TransactionView::contextualMenu(const QPoint &point)
// check if transaction can be abandoned, disable context menu action in case it doesn't
uint256 hash;
hash.SetHex(selection.at(0).data(TransactionTableModel::TxHashRole).toString().toStdString());
- abandonAction->setEnabled(model->transactionCanBeAbandoned(hash));
- bumpFeeAction->setEnabled(model->transactionCanBeBumped(hash));
+ abandonAction->setEnabled(model->wallet().transactionCanBeAbandoned(hash));
+ bumpFeeAction->setEnabled(model->wallet().transactionCanBeBumped(hash));
if(index.isValid())
{
@@ -414,7 +414,7 @@ void TransactionView::abandonTx()
hash.SetHex(hashQStr.toStdString());
// Abandon the wallet transaction over the walletModel
- model->abandonTransaction(hash);
+ model->wallet().abandonTransaction(hash);
// Update the table
model->getTransactionTableModel()->updateTransaction(hashQStr, CT_UPDATED, false);
diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp
index 65e7775f2b..6114ea0de1 100644
--- a/src/qt/utilitydialog.cpp
+++ b/src/qt/utilitydialog.cpp
@@ -19,6 +19,7 @@
#include <clientversion.h>
#include <init.h>
+#include <interface/node.h>
#include <util.h>
#include <stdio.h>
@@ -31,7 +32,7 @@
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
-HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
+HelpMessageDialog::HelpMessageDialog(interface::Node& node, QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
@@ -77,7 +78,7 @@ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
cursor.insertText(header);
cursor.insertBlock();
- std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
+ std::string strUsage = node.helpMessage(HelpMessageMode::BITCOIN_QT);
const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
if (showDebug) {
diff --git a/src/qt/utilitydialog.h b/src/qt/utilitydialog.h
index d43d9a82c0..e6ad7be5d0 100644
--- a/src/qt/utilitydialog.h
+++ b/src/qt/utilitydialog.h
@@ -10,6 +10,10 @@
class BitcoinGUI;
+namespace interface {
+ class Node;
+}
+
namespace Ui {
class HelpMessageDialog;
}
@@ -20,7 +24,7 @@ class HelpMessageDialog : public QDialog
Q_OBJECT
public:
- explicit HelpMessageDialog(QWidget *parent, bool about);
+ explicit HelpMessageDialog(interface::Node& node, QWidget *parent, bool about);
~HelpMessageDialog();
void printToConsole();
diff --git a/src/qt/walletframe.cpp b/src/qt/walletframe.cpp
index c0b9d04269..5b13353d7b 100644
--- a/src/qt/walletframe.cpp
+++ b/src/qt/walletframe.cpp
@@ -3,6 +3,7 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/walletframe.h>
+#include <qt/walletmodel.h>
#include <qt/bitcoingui.h>
#include <qt/walletview.h>
@@ -39,10 +40,16 @@ void WalletFrame::setClientModel(ClientModel *_clientModel)
this->clientModel = _clientModel;
}
-bool WalletFrame::addWallet(const QString& name, WalletModel *walletModel)
+bool WalletFrame::addWallet(WalletModel *walletModel)
{
- if (!gui || !clientModel || !walletModel || mapWalletViews.count(name) > 0)
+ if (!gui || !clientModel || !walletModel) {
return false;
+ }
+
+ const QString name = walletModel->getWalletName();
+ if (mapWalletViews.count(name) > 0) {
+ return false;
+ }
WalletView *walletView = new WalletView(platformStyle, this);
walletView->setBitcoinGUI(gui);
diff --git a/src/qt/walletframe.h b/src/qt/walletframe.h
index 42ce69fea1..6eedcf370c 100644
--- a/src/qt/walletframe.h
+++ b/src/qt/walletframe.h
@@ -36,7 +36,7 @@ public:
void setClientModel(ClientModel *clientModel);
- bool addWallet(const QString& name, WalletModel *walletModel);
+ bool addWallet(WalletModel *walletModel);
bool setCurrentWallet(const QString& name);
bool removeWallet(const QString &name);
void removeAllWallets();
@@ -59,6 +59,7 @@ private:
const PlatformStyle *platformStyle;
+public:
WalletView *currentWalletView();
public Q_SLOTS:
diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp
index e7d9d276d7..d9db437dc5 100644
--- a/src/qt/walletmodel.cpp
+++ b/src/qt/walletmodel.cpp
@@ -5,29 +5,20 @@
#include <qt/walletmodel.h>
#include <qt/addresstablemodel.h>
-#include <consensus/validation.h>
#include <qt/guiconstants.h>
-#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/paymentserver.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/sendcoinsdialog.h>
#include <qt/transactiontablemodel.h>
-#include <chain.h>
+#include <interface/handler.h>
+#include <interface/node.h>
#include <key_io.h>
-#include <keystore.h>
-#include <validation.h>
-#include <net.h> // for g_connman
-#include <policy/fees.h>
-#include <policy/rbf.h>
-#include <sync.h>
#include <ui_interface.h>
#include <util.h> // for GetBoolArg
#include <wallet/coincontrol.h>
-#include <wallet/feebumper.h>
#include <wallet/wallet.h>
-#include <wallet/walletdb.h> // for BackupWallet
#include <stdint.h>
@@ -37,21 +28,19 @@
#include <QTimer>
-WalletModel::WalletModel(const PlatformStyle *platformStyle, CWallet *_wallet, OptionsModel *_optionsModel, QObject *parent) :
- QObject(parent), wallet(_wallet), optionsModel(_optionsModel), addressTableModel(0),
+WalletModel::WalletModel(std::unique_ptr<interface::Wallet> wallet, interface::Node& node, const PlatformStyle *platformStyle, OptionsModel *_optionsModel, QObject *parent) :
+ QObject(parent), m_wallet(std::move(wallet)), m_node(node), optionsModel(_optionsModel), addressTableModel(0),
transactionTableModel(0),
recentRequestsTableModel(0),
- cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
- cachedWatchOnlyBalance{0}, cachedWatchUnconfBalance{0}, cachedWatchImmatureBalance{0},
cachedEncryptionStatus(Unencrypted),
cachedNumBlocks(0)
{
- fHaveWatchOnly = wallet->HaveWatchOnly();
+ fHaveWatchOnly = m_wallet->haveWatchOnly();
fForceCheckBalanceChanged = false;
- addressTableModel = new AddressTableModel(wallet, this);
- transactionTableModel = new TransactionTableModel(platformStyle, wallet, this);
- recentRequestsTableModel = new RecentRequestsTableModel(wallet, this);
+ addressTableModel = new AddressTableModel(this);
+ transactionTableModel = new TransactionTableModel(platformStyle, this);
+ recentRequestsTableModel = new RecentRequestsTableModel(this);
// This timer will be fired repeatedly to update the balance
pollTimer = new QTimer(this);
@@ -66,105 +55,45 @@ WalletModel::~WalletModel()
unsubscribeFromCoreSignals();
}
-CAmount WalletModel::getBalance(const CCoinControl *coinControl) const
-{
- if (coinControl)
- {
- return wallet->GetAvailableBalance(coinControl);
- }
-
- return wallet->GetBalance();
-}
-
-CAmount WalletModel::getUnconfirmedBalance() const
-{
- return wallet->GetUnconfirmedBalance();
-}
-
-CAmount WalletModel::getImmatureBalance() const
-{
- return wallet->GetImmatureBalance();
-}
-
-bool WalletModel::haveWatchOnly() const
-{
- return fHaveWatchOnly;
-}
-
-CAmount WalletModel::getWatchBalance() const
-{
- return wallet->GetWatchOnlyBalance();
-}
-
-CAmount WalletModel::getWatchUnconfirmedBalance() const
-{
- return wallet->GetUnconfirmedWatchOnlyBalance();
-}
-
-CAmount WalletModel::getWatchImmatureBalance() const
-{
- return wallet->GetImmatureWatchOnlyBalance();
-}
-
void WalletModel::updateStatus()
{
EncryptionStatus newEncryptionStatus = getEncryptionStatus();
- if(cachedEncryptionStatus != newEncryptionStatus)
- Q_EMIT encryptionStatusChanged(newEncryptionStatus);
+ if(cachedEncryptionStatus != newEncryptionStatus) {
+ Q_EMIT encryptionStatusChanged();
+ }
}
void WalletModel::pollBalanceChanged()
{
- // Get required locks upfront. This avoids the GUI from getting stuck on
- // periodical polls if the core is holding the locks for a longer time -
- // for example, during a wallet rescan.
- TRY_LOCK(cs_main, lockMain);
- if(!lockMain)
- return;
- TRY_LOCK(wallet->cs_wallet, lockWallet);
- if(!lockWallet)
+ // Try to get balances and return early if locks can't be acquired. This
+ // avoids the GUI from getting stuck on periodical polls if the core is
+ // holding the locks for a longer time - for example, during a wallet
+ // rescan.
+ interface::WalletBalances new_balances;
+ int numBlocks = -1;
+ if (!m_wallet->tryGetBalances(new_balances, numBlocks)) {
return;
+ }
- if(fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks)
+ if(fForceCheckBalanceChanged || m_node.getNumBlocks() != cachedNumBlocks)
{
fForceCheckBalanceChanged = false;
// Balance and number of transactions might have changed
- cachedNumBlocks = chainActive.Height();
+ cachedNumBlocks = m_node.getNumBlocks();
- checkBalanceChanged();
+ checkBalanceChanged(new_balances);
if(transactionTableModel)
transactionTableModel->updateConfirmations();
}
}
-void WalletModel::checkBalanceChanged()
+void WalletModel::checkBalanceChanged(const interface::WalletBalances& new_balances)
{
- CAmount newBalance = getBalance();
- CAmount newUnconfirmedBalance = getUnconfirmedBalance();
- CAmount newImmatureBalance = getImmatureBalance();
- CAmount newWatchOnlyBalance = 0;
- CAmount newWatchUnconfBalance = 0;
- CAmount newWatchImmatureBalance = 0;
- if (haveWatchOnly())
- {
- newWatchOnlyBalance = getWatchBalance();
- newWatchUnconfBalance = getWatchUnconfirmedBalance();
- newWatchImmatureBalance = getWatchImmatureBalance();
- }
-
- if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance ||
- cachedWatchOnlyBalance != newWatchOnlyBalance || cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance)
- {
- cachedBalance = newBalance;
- cachedUnconfirmedBalance = newUnconfirmedBalance;
- cachedImmatureBalance = newImmatureBalance;
- cachedWatchOnlyBalance = newWatchOnlyBalance;
- cachedWatchUnconfBalance = newWatchUnconfBalance;
- cachedWatchImmatureBalance = newWatchImmatureBalance;
- Q_EMIT balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance,
- newWatchOnlyBalance, newWatchUnconfBalance, newWatchImmatureBalance);
+ if(new_balances.balanceChanged(m_cached_balances)) {
+ m_cached_balances = new_balances;
+ Q_EMIT balanceChanged(new_balances);
}
}
@@ -259,7 +188,7 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact
return DuplicateAddress;
}
- CAmount nBalance = getBalance(&coinControl);
+ CAmount nBalance = m_wallet->getAvailableBalance(coinControl);
if(total > nBalance)
{
@@ -267,22 +196,17 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact
}
{
- LOCK2(cs_main, wallet->cs_wallet);
-
- transaction.newPossibleKeyChange(wallet);
-
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
- CWalletTx *newTx = transaction.getTransaction();
- CReserveKey *keyChange = transaction.getPossibleKeyChange();
- bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl);
+ auto& newTx = transaction.getWtx();
+ newTx = m_wallet->createTransaction(vecSend, coinControl, true /* sign */, nChangePosRet, nFeeRequired, strFailReason);
transaction.setTransactionFee(nFeeRequired);
- if (fSubtractFeeFromAmount && fCreated)
+ if (fSubtractFeeFromAmount && newTx)
transaction.reassignAmounts(nChangePosRet);
- if(!fCreated)
+ if(!newTx)
{
if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance)
{
@@ -296,7 +220,7 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact
// reject absurdly high fee. (This can never happen because the
// wallet caps the fee at maxTxFee. This merely serves as a
// belt-and-suspenders check)
- if (nFeeRequired > maxTxFee)
+ if (nFeeRequired > m_node.getMaxTxFee())
return AbsurdFee;
}
@@ -308,9 +232,7 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran
QByteArray transaction_array; /* store serialized transaction */
{
- LOCK2(cs_main, wallet->cs_wallet);
- CWalletTx *newTx = transaction.getTransaction();
-
+ std::vector<std::pair<std::string, std::string>> vOrderForm;
for (const SendCoinsRecipient &rcp : transaction.getRecipients())
{
if (rcp.paymentRequest.IsInitialized())
@@ -321,22 +243,21 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran
}
// Store PaymentRequests in wtx.vOrderForm in wallet.
- std::string key("PaymentRequest");
std::string value;
rcp.paymentRequest.SerializeToString(&value);
- newTx->vOrderForm.push_back(make_pair(key, value));
+ vOrderForm.emplace_back("PaymentRequest", std::move(value));
}
else if (!rcp.message.isEmpty()) // Message from normal bitcoin:URI (bitcoin:123...?message=example)
- newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString()));
+ vOrderForm.emplace_back("Message", rcp.message.toStdString());
}
- CReserveKey *keyChange = transaction.getPossibleKeyChange();
- CValidationState state;
- if(!wallet->CommitTransaction(*newTx, *keyChange, g_connman.get(), state))
- return SendCoinsReturn(TransactionCommitFailed, QString::fromStdString(state.GetRejectReason()));
+ auto& newTx = transaction.getWtx();
+ std::string rejectReason;
+ if (!newTx->commit({} /* mapValue */, std::move(vOrderForm), {} /* fromAccount */, rejectReason))
+ return SendCoinsReturn(TransactionCommitFailed, QString::fromStdString(rejectReason));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
- ssTx << *newTx->tx;
+ ssTx << newTx->get();
transaction_array.append(&(ssTx[0]), ssTx.size());
}
@@ -351,24 +272,22 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran
CTxDestination dest = DecodeDestination(strAddress);
std::string strLabel = rcp.label.toStdString();
{
- LOCK(wallet->cs_wallet);
-
- std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest);
-
// Check if we have a new address or an updated label
- if (mi == wallet->mapAddressBook.end())
+ std::string name;
+ if (!m_wallet->getAddress(dest, &name))
{
- wallet->SetAddressBook(dest, strLabel, "send");
+ m_wallet->setAddressBook(dest, strLabel, "send");
}
- else if (mi->second.name != strLabel)
+ else if (name != strLabel)
{
- wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose
+ m_wallet->setAddressBook(dest, strLabel, ""); // "" means don't change purpose
}
}
}
- Q_EMIT coinsSent(wallet, rcp, transaction_array);
+ Q_EMIT coinsSent(this, rcp, transaction_array);
}
- checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits
+
+ checkBalanceChanged(m_wallet->getBalances()); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits
return SendCoinsReturn(OK);
}
@@ -395,11 +314,11 @@ RecentRequestsTableModel *WalletModel::getRecentRequestsTableModel()
WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
- if(!wallet->IsCrypted())
+ if(!m_wallet->isCrypted())
{
return Unencrypted;
}
- else if(wallet->IsLocked())
+ else if(m_wallet->isLocked())
{
return Locked;
}
@@ -414,7 +333,7 @@ bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphr
if(encrypted)
{
// Encrypt
- return wallet->EncryptWallet(passphrase);
+ return m_wallet->encryptWallet(passphrase);
}
else
{
@@ -428,39 +347,29 @@ bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
if(locked)
{
// Lock
- return wallet->Lock();
+ return m_wallet->lock();
}
else
{
// Unlock
- return wallet->Unlock(passPhrase);
+ return m_wallet->unlock(passPhrase);
}
}
bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
- bool retval;
- {
- LOCK(wallet->cs_wallet);
- wallet->Lock(); // Make sure wallet is locked before attempting pass change
- retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
- }
- return retval;
-}
-
-bool WalletModel::backupWallet(const QString &filename)
-{
- return wallet->BackupWallet(filename.toLocal8Bit().data());
+ m_wallet->lock(); // Make sure wallet is locked before attempting pass change
+ return m_wallet->changeWalletPassphrase(oldPass, newPass);
}
// Handlers for core signals
-static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
+static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel)
{
qDebug() << "NotifyKeyStoreStatusChanged";
QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
}
-static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet,
+static void NotifyAddressBookChanged(WalletModel *walletmodel,
const CTxDestination &address, const std::string &label, bool isMine,
const std::string &purpose, ChangeType status)
{
@@ -477,9 +386,8 @@ static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet,
Q_ARG(int, status));
}
-static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
+static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status)
{
- Q_UNUSED(wallet);
Q_UNUSED(hash);
Q_UNUSED(status);
QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection);
@@ -502,21 +410,21 @@ static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly
void WalletModel::subscribeToCoreSignals()
{
// Connect signals to wallet
- wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
- wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6));
- wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
- wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
- wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1));
+ m_handler_status_changed = m_wallet->handleStatusChanged(boost::bind(&NotifyKeyStoreStatusChanged, this));
+ m_handler_address_book_changed = m_wallet->handleAddressBookChanged(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
+ m_handler_transaction_changed = m_wallet->handleTransactionChanged(boost::bind(NotifyTransactionChanged, this, _1, _2));
+ m_handler_show_progress = m_wallet->handleShowProgress(boost::bind(ShowProgress, this, _1, _2));
+ m_handler_watch_only_changed = m_wallet->handleWatchOnlyChanged(boost::bind(NotifyWatchonlyChanged, this, _1));
}
void WalletModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
- wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
- wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6));
- wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
- wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
- wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1));
+ m_handler_status_changed->disconnect();
+ m_handler_address_book_changed->disconnect();
+ m_handler_transaction_changed->disconnect();
+ m_handler_show_progress->disconnect();
+ m_handler_watch_only_changed->disconnect();
}
// WalletModel::UnlockContext implementation
@@ -556,80 +464,9 @@ void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
rhs.relock = false;
}
-bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
-{
- return wallet->GetPubKey(address, vchPubKeyOut);
-}
-
-bool WalletModel::IsSpendable(const CTxDestination& dest) const
-{
- return IsMine(*wallet, dest) & ISMINE_SPENDABLE;
-}
-
-bool WalletModel::getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const
-{
- return wallet->GetKey(address, vchPrivKeyOut);
-}
-
-// returns a list of COutputs from COutPoints
-void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
-{
- LOCK2(cs_main, wallet->cs_wallet);
- for (const COutPoint& outpoint : vOutpoints)
- {
- auto it = wallet->mapWallet.find(outpoint.hash);
- if (it == wallet->mapWallet.end()) continue;
- int nDepth = it->second.GetDepthInMainChain();
- if (nDepth < 0) continue;
- COutput out(&it->second, outpoint.n, nDepth, true /* spendable */, true /* solvable */, true /* safe */);
- vOutputs.push_back(out);
- }
-}
-
-bool WalletModel::isSpent(const COutPoint& outpoint) const
-{
- LOCK2(cs_main, wallet->cs_wallet);
- return wallet->IsSpent(outpoint.hash, outpoint.n);
-}
-
-// AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
-void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
-{
- for (auto& group : wallet->ListCoins()) {
- auto& resultGroup = mapCoins[QString::fromStdString(EncodeDestination(group.first))];
- for (auto& coin : group.second) {
- resultGroup.emplace_back(std::move(coin));
- }
- }
-}
-
-bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
-{
- LOCK2(cs_main, wallet->cs_wallet);
- return wallet->IsLockedCoin(hash, n);
-}
-
-void WalletModel::lockCoin(COutPoint& output)
-{
- LOCK2(cs_main, wallet->cs_wallet);
- wallet->LockCoin(output);
-}
-
-void WalletModel::unlockCoin(COutPoint& output)
-{
- LOCK2(cs_main, wallet->cs_wallet);
- wallet->UnlockCoin(output);
-}
-
-void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
-{
- LOCK2(cs_main, wallet->cs_wallet);
- wallet->ListLockedCoins(vOutpts);
-}
-
void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests)
{
- vReceiveRequests = wallet->GetDestValues("rr"); // receive request
+ vReceiveRequests = m_wallet->getDestValues("rr"); // receive request
}
bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest)
@@ -640,27 +477,10 @@ bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t
ss << nId;
std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata
- LOCK(wallet->cs_wallet);
if (sRequest.empty())
- return wallet->EraseDestData(dest, key);
+ return m_wallet->eraseDestData(dest, key);
else
- return wallet->AddDestData(dest, key, sRequest);
-}
-
-bool WalletModel::transactionCanBeAbandoned(uint256 hash) const
-{
- return wallet->TransactionCanBeAbandoned(hash);
-}
-
-bool WalletModel::abandonTransaction(uint256 hash) const
-{
- LOCK2(cs_main, wallet->cs_wallet);
- return wallet->AbandonTransaction(hash);
-}
-
-bool WalletModel::transactionCanBeBumped(uint256 hash) const
-{
- return feebumper::TransactionCanBeBumped(wallet, hash);
+ return m_wallet->addDestData(dest, key, sRequest);
}
bool WalletModel::bumpFee(uint256 hash)
@@ -671,7 +491,7 @@ bool WalletModel::bumpFee(uint256 hash)
CAmount old_fee;
CAmount new_fee;
CMutableTransaction mtx;
- if (feebumper::CreateTransaction(wallet, hash, coin_control, 0 /* totalFee */, errors, old_fee, new_fee, mtx) != feebumper::Result::OK) {
+ if (!m_wallet->createBumpTransaction(hash, coin_control, 0 /* totalFee */, errors, old_fee, new_fee, mtx)) {
QMessageBox::critical(0, tr("Fee bump error"), tr("Increasing transaction fee failed") + "<br />(" +
(errors.size() ? QString::fromStdString(errors[0]) : "") +")");
return false;
@@ -698,7 +518,7 @@ bool WalletModel::bumpFee(uint256 hash)
confirmationDialog.exec();
QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result());
- // cancel sign&broadcast if users doesn't want to bump the fee
+ // cancel sign&broadcast if user doesn't want to bump the fee
if (retval != QMessageBox::Yes) {
return false;
}
@@ -710,13 +530,13 @@ bool WalletModel::bumpFee(uint256 hash)
}
// sign bumped transaction
- if (!feebumper::SignTransaction(wallet, mtx)) {
+ if (!m_wallet->signBumpTransaction(mtx)) {
QMessageBox::critical(0, tr("Fee bump error"), tr("Can't sign transaction."));
return false;
}
// commit the bumped transaction
uint256 txid;
- if (feebumper::CommitTransaction(wallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) {
+ if(!m_wallet->commitBumpTransaction(hash, std::move(mtx), errors, txid)) {
QMessageBox::critical(0, tr("Fee bump error"), tr("Could not commit transaction") + "<br />(" +
QString::fromStdString(errors[0])+")");
return false;
@@ -729,17 +549,12 @@ bool WalletModel::isWalletEnabled()
return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET);
}
-bool WalletModel::hdEnabled() const
-{
- return wallet->IsHDEnabled();
-}
-
-OutputType WalletModel::getDefaultAddressType() const
+QString WalletModel::getWalletName() const
{
- return g_address_type;
+ return QString::fromStdString(m_wallet->getWalletName());
}
-int WalletModel::getDefaultConfirmTarget() const
+bool WalletModel::isMultiwallet()
{
- return nTxConfirmTarget;
+ return m_node.getWallets().size() > 1;
}
diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h
index 811996b98f..bc409b10ee 100644
--- a/src/qt/walletmodel.h
+++ b/src/qt/walletmodel.h
@@ -13,6 +13,7 @@
#include <qt/paymentrequestplus.h>
#include <qt/walletmodeltransaction.h>
+#include <interface/wallet.h>
#include <support/allocators/secure.h>
#include <map>
@@ -20,7 +21,7 @@
#include <QObject>
-enum OutputType : int;
+enum class OutputType;
class AddressTableModel;
class OptionsModel;
@@ -34,9 +35,12 @@ class CKeyID;
class COutPoint;
class COutput;
class CPubKey;
-class CWallet;
class uint256;
+namespace interface {
+class Node;
+} // namespace interface
+
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
@@ -107,7 +111,7 @@ class WalletModel : public QObject
Q_OBJECT
public:
- explicit WalletModel(const PlatformStyle *platformStyle, CWallet *wallet, OptionsModel *optionsModel, QObject *parent = 0);
+ explicit WalletModel(std::unique_ptr<interface::Wallet> wallet, interface::Node& node, const PlatformStyle *platformStyle, OptionsModel *optionsModel, QObject *parent = 0);
~WalletModel();
enum StatusCode // Returned by sendCoins
@@ -136,13 +140,6 @@ public:
TransactionTableModel *getTransactionTableModel();
RecentRequestsTableModel *getRecentRequestsTableModel();
- CAmount getBalance(const CCoinControl *coinControl = nullptr) const;
- CAmount getUnconfirmedBalance() const;
- CAmount getImmatureBalance() const;
- bool haveWatchOnly() const;
- CAmount getWatchBalance() const;
- CAmount getWatchUnconfirmedBalance() const;
- CAmount getWatchImmatureBalance() const;
EncryptionStatus getEncryptionStatus() const;
// Check address for validity
@@ -171,8 +168,6 @@ public:
// Passphrase only needed when unlocking
bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString());
bool changePassphrase(const SecureString &oldPass, const SecureString &newPass);
- // Wallet backup
- bool backupWallet(const QString &filename);
// RAI object for unlocking wallet, returned by requestUnlock()
class UnlockContext
@@ -196,37 +191,28 @@ public:
UnlockContext requestUnlock();
- bool getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
- bool IsSpendable(const CTxDestination& dest) const;
- bool getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const;
- void getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs);
- bool isSpent(const COutPoint& outpoint) const;
- void listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const;
-
- bool isLockedCoin(uint256 hash, unsigned int n) const;
- void lockCoin(COutPoint& output);
- void unlockCoin(COutPoint& output);
- void listLockedCoins(std::vector<COutPoint>& vOutpts);
-
void loadReceiveRequests(std::vector<std::string>& vReceiveRequests);
bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest);
- bool transactionCanBeAbandoned(uint256 hash) const;
- bool abandonTransaction(uint256 hash) const;
-
- bool transactionCanBeBumped(uint256 hash) const;
bool bumpFee(uint256 hash);
static bool isWalletEnabled();
- bool hdEnabled() const;
-
- OutputType getDefaultAddressType() const;
+ interface::Node& node() const { return m_node; }
+ interface::Wallet& wallet() const { return *m_wallet; }
- int getDefaultConfirmTarget() const;
+ QString getWalletName() const;
+ bool isMultiwallet();
private:
- CWallet *wallet;
+ 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;
+
bool fHaveWatchOnly;
bool fForceCheckBalanceChanged;
@@ -239,12 +225,7 @@ private:
RecentRequestsTableModel *recentRequestsTableModel;
// Cache some values to be able to detect changes
- CAmount cachedBalance;
- CAmount cachedUnconfirmedBalance;
- CAmount cachedImmatureBalance;
- CAmount cachedWatchOnlyBalance;
- CAmount cachedWatchUnconfBalance;
- CAmount cachedWatchImmatureBalance;
+ interface::WalletBalances m_cached_balances;
EncryptionStatus cachedEncryptionStatus;
int cachedNumBlocks;
@@ -252,15 +233,14 @@ private:
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
- void checkBalanceChanged();
+ void checkBalanceChanged(const interface::WalletBalances& new_balances);
Q_SIGNALS:
// Signal that balance in wallet changed
- void balanceChanged(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
- const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance);
+ void balanceChanged(const interface::WalletBalances& balances);
// Encryption status of wallet changed
- void encryptionStatusChanged(int status);
+ void encryptionStatusChanged();
// Signal emitted when wallet needs to be unlocked
// It is valid behaviour for listeners to keep the wallet locked after this signal;
@@ -271,7 +251,7 @@ Q_SIGNALS:
void message(const QString &title, const QString &message, unsigned int style);
// Coins sent: from wallet, to recipient, in (serialized) transaction:
- void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction);
+ void coinsSent(WalletModel* wallet, SendCoinsRecipient recipient, QByteArray transaction);
// Show progress dialog e.g. for rescan
void showProgress(const QString &title, int nProgress);
diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp
index 4b2bef2690..21bdfe3818 100644
--- a/src/qt/walletmodeltransaction.cpp
+++ b/src/qt/walletmodeltransaction.cpp
@@ -4,20 +4,13 @@
#include <qt/walletmodeltransaction.h>
+#include <interface/node.h>
#include <policy/policy.h>
-#include <wallet/wallet.h>
WalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient> &_recipients) :
recipients(_recipients),
- walletTransaction(0),
fee(0)
{
- walletTransaction = new CWalletTx();
-}
-
-WalletModelTransaction::~WalletModelTransaction()
-{
- delete walletTransaction;
}
QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const
@@ -25,14 +18,14 @@ QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const
return recipients;
}
-CWalletTx *WalletModelTransaction::getTransaction() const
+std::unique_ptr<interface::PendingWalletTx>& WalletModelTransaction::getWtx()
{
- return walletTransaction;
+ return wtx;
}
unsigned int WalletModelTransaction::getTransactionSize()
{
- return (!walletTransaction ? 0 : ::GetVirtualTransactionSize(*walletTransaction->tx));
+ return wtx ? wtx->getVirtualSize() : 0;
}
CAmount WalletModelTransaction::getTransactionFee() const
@@ -47,6 +40,7 @@ void WalletModelTransaction::setTransactionFee(const CAmount& newFee)
void WalletModelTransaction::reassignAmounts(int nChangePosRet)
{
+ const CTransaction* walletTransaction = &wtx->get();
int i = 0;
for (QList<SendCoinsRecipient>::iterator it = recipients.begin(); it != recipients.end(); ++it)
{
@@ -62,7 +56,7 @@ void WalletModelTransaction::reassignAmounts(int nChangePosRet)
if (out.amount() <= 0) continue;
if (i == nChangePosRet)
i++;
- subtotal += walletTransaction->tx->vout[i].nValue;
+ subtotal += walletTransaction->vout[i].nValue;
i++;
}
rcp.amount = subtotal;
@@ -71,7 +65,7 @@ void WalletModelTransaction::reassignAmounts(int nChangePosRet)
{
if (i == nChangePosRet)
i++;
- rcp.amount = walletTransaction->tx->vout[i].nValue;
+ rcp.amount = walletTransaction->vout[i].nValue;
i++;
}
}
@@ -86,13 +80,3 @@ CAmount WalletModelTransaction::getTotalTransactionAmount() const
}
return totalTransactionAmount;
}
-
-void WalletModelTransaction::newPossibleKeyChange(CWallet *wallet)
-{
- keyChange.reset(new CReserveKey(wallet));
-}
-
-CReserveKey *WalletModelTransaction::getPossibleKeyChange()
-{
- return keyChange.get();
-}
diff --git a/src/qt/walletmodeltransaction.h b/src/qt/walletmodeltransaction.h
index cd531dba4b..32fd0d2110 100644
--- a/src/qt/walletmodeltransaction.h
+++ b/src/qt/walletmodeltransaction.h
@@ -7,24 +7,26 @@
#include <qt/walletmodel.h>
+#include <memory>
+
#include <QObject>
class SendCoinsRecipient;
-class CReserveKey;
-class CWallet;
-class CWalletTx;
+namespace interface {
+class Node;
+class PendingWalletTx;
+}
/** Data model for a walletmodel transaction. */
class WalletModelTransaction
{
public:
explicit WalletModelTransaction(const QList<SendCoinsRecipient> &recipients);
- ~WalletModelTransaction();
QList<SendCoinsRecipient> getRecipients() const;
- CWalletTx *getTransaction() const;
+ std::unique_ptr<interface::PendingWalletTx>& getWtx();
unsigned int getTransactionSize();
void setTransactionFee(const CAmount& newFee);
@@ -32,15 +34,11 @@ public:
CAmount getTotalTransactionAmount() const;
- void newPossibleKeyChange(CWallet *wallet);
- CReserveKey *getPossibleKeyChange();
-
void reassignAmounts(int nChangePosRet); // needed for the subtract-fee-from-amount feature
private:
QList<SendCoinsRecipient> recipients;
- CWalletTx *walletTransaction;
- std::unique_ptr<CReserveKey> keyChange;
+ std::unique_ptr<interface::PendingWalletTx> wtx;
CAmount fee;
};
diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp
index 64497a3431..1505557244 100644
--- a/src/qt/walletview.cpp
+++ b/src/qt/walletview.cpp
@@ -19,6 +19,7 @@
#include <qt/transactionview.h>
#include <qt/walletmodel.h>
+#include <interface/node.h>
#include <ui_interface.h>
#include <QAction>
@@ -101,13 +102,13 @@ void WalletView::setBitcoinGUI(BitcoinGUI *gui)
connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));
// Pass through encryption status changed signals
- connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));
+ connect(this, SIGNAL(encryptionStatusChanged()), gui, SLOT(updateWalletStatus()));
// Pass through transaction notifications
- connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString,QString)));
+ connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString,QString,QString)));
// Connect HD enabled state signal
- connect(this, SIGNAL(hdEnabledStatusChanged(int)), gui, SLOT(setHDStatus(int)));
+ connect(this, SIGNAL(hdEnabledStatusChanged()), gui, SLOT(updateWalletStatus()));
}
}
@@ -137,11 +138,11 @@ void WalletView::setWalletModel(WalletModel *_walletModel)
connect(_walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Handle changes in encryption status
- connect(_walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));
+ connect(_walletModel, SIGNAL(encryptionStatusChanged()), this, SIGNAL(encryptionStatusChanged()));
updateEncryptionStatus();
// update HD status
- Q_EMIT hdEnabledStatusChanged(_walletModel->hdEnabled());
+ Q_EMIT hdEnabledStatusChanged();
// Balloon pop-up for new transaction
connect(_walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
@@ -158,7 +159,7 @@ void WalletView::setWalletModel(WalletModel *_walletModel)
void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/)
{
// Prevent balloon-spam when initial block download is in progress
- if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
+ if (!walletModel || !clientModel || clientModel->node().isInitialBlockDownload())
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
@@ -172,7 +173,7 @@ void WalletView::processNewTransaction(const QModelIndex& parent, int start, int
QString address = ttm->data(index, TransactionTableModel::AddressRole).toString();
QString label = ttm->data(index, TransactionTableModel::LabelRole).toString();
- Q_EMIT incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address, label);
+ Q_EMIT incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address, label, walletModel->getWalletName());
}
void WalletView::gotoOverviewPage()
@@ -234,7 +235,7 @@ void WalletView::showOutOfSyncWarning(bool fShow)
void WalletView::updateEncryptionStatus()
{
- Q_EMIT encryptionStatusChanged(walletModel->getEncryptionStatus());
+ Q_EMIT encryptionStatusChanged();
}
void WalletView::encryptWallet(bool status)
@@ -257,7 +258,7 @@ void WalletView::backupWallet()
if (filename.isEmpty())
return;
- if (!walletModel->backupWallet(filename)) {
+ if (!walletModel->wallet().backupWallet(filename.toLocal8Bit().data())) {
Q_EMIT message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename),
CClientUIInterface::MSG_ERROR);
}
diff --git a/src/qt/walletview.h b/src/qt/walletview.h
index 30d68e4eff..878a5966d6 100644
--- a/src/qt/walletview.h
+++ b/src/qt/walletview.h
@@ -44,6 +44,7 @@ public:
The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic.
*/
void setClientModel(ClientModel *clientModel);
+ WalletModel *getWalletModel() { return walletModel; }
/** Set the wallet model.
The wallet model represents a bitcoin wallet, and offers access to the list of transactions, address book and sending
functionality.
@@ -119,11 +120,11 @@ Q_SIGNALS:
/** Fired when a message should be reported to the user */
void message(const QString &title, const QString &message, unsigned int style);
/** Encryption status of wallet changed */
- void encryptionStatusChanged(int status);
+ void encryptionStatusChanged();
/** HD-Enabled status of wallet changed (only possible during startup) */
- void hdEnabledStatusChanged(int hdEnabled);
+ void hdEnabledStatusChanged();
/** Notify that a new transaction appeared */
- void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label);
+ void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName);
/** Notify that the out of sync warning icon has been pressed */
void outOfSyncWarningClicked();
};
diff --git a/src/random.h b/src/random.h
index ea88670a37..1d6b13a537 100644
--- a/src/random.h
+++ b/src/random.h
@@ -11,6 +11,7 @@
#include <uint256.h>
#include <stdint.h>
+#include <limits>
/* Seed OpenSSL PRNG with additional entropy data */
void RandAddSeed();
@@ -32,7 +33,7 @@ void RandAddSeedSleep();
/**
* Function to gather random data from multiple sources, failing whenever any
- * of those source fail to provide a result.
+ * of those sources fail to provide a result.
*/
void GetStrongRandBytes(unsigned char* buf, int num);
@@ -121,6 +122,12 @@ public:
/** Generate a random boolean. */
bool randbool() { return randbits(1); }
+
+ // Compatibility with the C++11 UniformRandomBitGenerator concept
+ typedef uint64_t result_type;
+ static constexpr uint64_t min() { return 0; }
+ static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
+ inline uint64_t operator()() { return rand64(); }
};
/* Number of random bytes returned by GetOSRand.
diff --git a/src/rest.cpp b/src/rest.cpp
index 8cba59dbbc..5871b554a6 100644
--- a/src/rest.cpp
+++ b/src/rest.cpp
@@ -24,21 +24,21 @@
static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
-enum RetFormat {
- RF_UNDEF,
- RF_BINARY,
- RF_HEX,
- RF_JSON,
+enum class RetFormat {
+ UNDEF,
+ BINARY,
+ HEX,
+ JSON,
};
static const struct {
enum RetFormat rf;
const char* name;
} rf_names[] = {
- {RF_UNDEF, ""},
- {RF_BINARY, "bin"},
- {RF_HEX, "hex"},
- {RF_JSON, "json"},
+ {RetFormat::UNDEF, ""},
+ {RetFormat::BINARY, "bin"},
+ {RetFormat::HEX, "hex"},
+ {RetFormat::JSON, "json"},
};
struct CCoin {
@@ -147,8 +147,7 @@ static bool rest_headers(HTTPRequest* req,
headers.reserve(count);
{
LOCK(cs_main);
- BlockMap::const_iterator it = mapBlockIndex.find(hash);
- const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : nullptr;
+ const CBlockIndex* pindex = LookupBlockIndex(hash);
while (pindex != nullptr && chainActive.Contains(pindex)) {
headers.push_back(pindex);
if (headers.size() == (unsigned long)count)
@@ -163,20 +162,20 @@ static bool rest_headers(HTTPRequest* req,
}
switch (rf) {
- case RF_BINARY: {
+ case RetFormat::BINARY: {
std::string binaryHeader = ssHeader.str();
req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, binaryHeader);
return true;
}
- case RF_HEX: {
+ case RetFormat::HEX: {
std::string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex);
return true;
}
- case RF_JSON: {
+ case RetFormat::JSON: {
UniValue jsonHeaders(UniValue::VARR);
{
LOCK(cs_main);
@@ -212,10 +211,11 @@ static bool rest_block(HTTPRequest* req,
CBlockIndex* pblockindex = nullptr;
{
LOCK(cs_main);
- if (mapBlockIndex.count(hash) == 0)
+ pblockindex = LookupBlockIndex(hash);
+ if (!pblockindex) {
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
+ }
- pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
@@ -227,21 +227,21 @@ static bool rest_block(HTTPRequest* req,
ssBlock << block;
switch (rf) {
- case RF_BINARY: {
+ case RetFormat::BINARY: {
std::string binaryBlock = ssBlock.str();
req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, binaryBlock);
return true;
}
- case RF_HEX: {
+ case RetFormat::HEX: {
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex);
return true;
}
- case RF_JSON: {
+ case RetFormat::JSON: {
UniValue objBlock;
{
LOCK(cs_main);
@@ -280,7 +280,7 @@ static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
const RetFormat rf = ParseDataFormat(param, strURIPart);
switch (rf) {
- case RF_JSON: {
+ case RetFormat::JSON: {
JSONRPCRequest jsonRequest;
jsonRequest.params = UniValue(UniValue::VARR);
UniValue chainInfoObject = getblockchaininfo(jsonRequest);
@@ -303,7 +303,7 @@ static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
const RetFormat rf = ParseDataFormat(param, strURIPart);
switch (rf) {
- case RF_JSON: {
+ case RetFormat::JSON: {
UniValue mempoolInfoObject = mempoolInfoToJSON();
std::string strJSON = mempoolInfoObject.write() + "\n";
@@ -325,7 +325,7 @@ static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPar
const RetFormat rf = ParseDataFormat(param, strURIPart);
switch (rf) {
- case RF_JSON: {
+ case RetFormat::JSON: {
UniValue mempoolObject = mempoolToJSON(true);
std::string strJSON = mempoolObject.write() + "\n";
@@ -359,21 +359,21 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
ssTx << tx;
switch (rf) {
- case RF_BINARY: {
+ case RetFormat::BINARY: {
std::string binaryTx = ssTx.str();
req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, binaryTx);
return true;
}
- case RF_HEX: {
+ case RetFormat::HEX: {
std::string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex);
return true;
}
- case RF_JSON: {
+ case RetFormat::JSON: {
UniValue objTx(UniValue::VOBJ);
TxToUniv(*tx, hashBlock, objTx);
std::string strJSON = objTx.write() + "\n";
@@ -440,13 +440,13 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
}
switch (rf) {
- case RF_HEX: {
+ case RetFormat::HEX: {
// convert hex to bin, continue then with bin part
std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
}
- case RF_BINARY: {
+ case RetFormat::BINARY: {
try {
//deserialize only if user sent a request
if (strRequestMutable.size() > 0)
@@ -466,7 +466,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
break;
}
- case RF_JSON: {
+ case RetFormat::JSON: {
if (!fInputParsed)
return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
break;
@@ -487,33 +487,35 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
std::vector<bool> hits;
bitmap.resize((vOutPoints.size() + 7) / 8);
{
- LOCK2(cs_main, mempool.cs);
-
- CCoinsView viewDummy;
- CCoinsViewCache view(&viewDummy);
-
- CCoinsViewCache& viewChain = *pcoinsTip;
- CCoinsViewMemPool viewMempool(&viewChain, mempool);
-
- if (fCheckMemPool)
- view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
-
- for (size_t i = 0; i < vOutPoints.size(); i++) {
- bool hit = false;
- Coin coin;
- if (view.GetCoin(vOutPoints[i], coin) && !mempool.isSpent(vOutPoints[i])) {
- hit = true;
- outs.emplace_back(std::move(coin));
+ auto process_utxos = [&vOutPoints, &outs, &hits](const CCoinsView& view, const CTxMemPool& mempool) {
+ for (const COutPoint& vOutPoint : vOutPoints) {
+ Coin coin;
+ bool hit = !mempool.isSpent(vOutPoint) && view.GetCoin(vOutPoint, coin);
+ hits.push_back(hit);
+ if (hit) outs.emplace_back(std::move(coin));
}
+ };
+
+ if (fCheckMemPool) {
+ // use db+mempool as cache backend in case user likes to query mempool
+ LOCK2(cs_main, mempool.cs);
+ CCoinsViewCache& viewChain = *pcoinsTip;
+ CCoinsViewMemPool viewMempool(&viewChain, mempool);
+ process_utxos(viewMempool, mempool);
+ } else {
+ LOCK(cs_main); // no need to lock mempool!
+ process_utxos(*pcoinsTip, CTxMemPool());
+ }
- hits.push_back(hit);
+ for (size_t i = 0; i < hits.size(); ++i) {
+ const bool hit = hits[i];
bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
}
}
switch (rf) {
- case RF_BINARY: {
+ case RetFormat::BINARY: {
// serialize data
// use exact same output as mentioned in Bip64
CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
@@ -525,7 +527,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
return true;
}
- case RF_HEX: {
+ case RetFormat::HEX: {
CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
std::string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
@@ -535,7 +537,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
return true;
}
- case RF_JSON: {
+ case RetFormat::JSON: {
UniValue objGetUTXOResponse(UniValue::VOBJ);
// pack in some essentials
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index f2a1fd048f..06c68ea27c 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -33,6 +33,7 @@
#include <boost/thread/thread.hpp> // boost::thread::interrupt
+#include <memory>
#include <mutex>
#include <condition_variable>
@@ -709,10 +710,10 @@ UniValue getblockheader(const JSONRPCRequest& request)
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
- if (mapBlockIndex.count(hash) == 0)
+ const CBlockIndex* pblockindex = LookupBlockIndex(hash);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
-
- CBlockIndex* pblockindex = mapBlockIndex[hash];
+ }
if (!fVerbose)
{
@@ -788,12 +789,12 @@ UniValue getblock(const JSONRPCRequest& request)
verbosity = request.params[1].get_bool() ? 1 : 0;
}
- if (mapBlockIndex.count(hash) == 0)
+ const CBlockIndex* pblockindex = LookupBlockIndex(hash);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
+ }
CBlock block;
- CBlockIndex* pblockindex = mapBlockIndex[hash];
-
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
@@ -834,18 +835,18 @@ static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash,
{
assert(!outputs.empty());
ss << hash;
- ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
+ ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u);
stats.nTransactions++;
for (const auto output : outputs) {
ss << VARINT(output.first + 1);
ss << output.second.out.scriptPubKey;
- ss << VARINT(output.second.out.nValue);
+ ss << VARINT(output.second.out.nValue, VarIntMode::NONNEGATIVE_SIGNED);
stats.nTransactionOutputs++;
stats.nTotalAmount += output.second.out.nValue;
stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ +
2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */;
}
- ss << VARINT(0);
+ ss << VARINT(0u);
}
//! Calculate statistics about the unspent transaction output set
@@ -858,7 +859,7 @@ static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
- stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
+ stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight;
}
ss << stats.hashBlock;
uint256 prevkey;
@@ -1041,8 +1042,7 @@ UniValue gettxout(const JSONRPCRequest& request)
}
}
- BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
- CBlockIndex *pindex = it->second;
+ const CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock());
ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.pushKV("confirmations", 0);
@@ -1121,20 +1121,20 @@ static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Conse
UniValue rv(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
- case THRESHOLD_DEFINED: rv.pushKV("status", "defined"); break;
- case THRESHOLD_STARTED: rv.pushKV("status", "started"); break;
- case THRESHOLD_LOCKED_IN: rv.pushKV("status", "locked_in"); break;
- case THRESHOLD_ACTIVE: rv.pushKV("status", "active"); break;
- case THRESHOLD_FAILED: rv.pushKV("status", "failed"); break;
+ case ThresholdState::DEFINED: rv.pushKV("status", "defined"); break;
+ case ThresholdState::STARTED: rv.pushKV("status", "started"); break;
+ case ThresholdState::LOCKED_IN: rv.pushKV("status", "locked_in"); break;
+ case ThresholdState::ACTIVE: rv.pushKV("status", "active"); break;
+ case ThresholdState::FAILED: rv.pushKV("status", "failed"); break;
}
- if (THRESHOLD_STARTED == thresholdState)
+ if (ThresholdState::STARTED == thresholdState)
{
rv.pushKV("bit", consensusParams.vDeployments[id].bit);
}
rv.pushKV("startTime", consensusParams.vDeployments[id].nStartTime);
rv.pushKV("timeout", consensusParams.vDeployments[id].nTimeout);
rv.pushKV("since", VersionBitsTipStateSinceHeight(consensusParams, id));
- if (THRESHOLD_STARTED == thresholdState)
+ if (ThresholdState::STARTED == thresholdState)
{
UniValue statsUV(UniValue::VOBJ);
BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
@@ -1436,10 +1436,10 @@ UniValue preciousblock(const JSONRPCRequest& request)
{
LOCK(cs_main);
- if (mapBlockIndex.count(hash) == 0)
+ pblockindex = LookupBlockIndex(hash);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
-
- pblockindex = mapBlockIndex[hash];
+ }
}
CValidationState state;
@@ -1472,10 +1472,11 @@ UniValue invalidateblock(const JSONRPCRequest& request)
{
LOCK(cs_main);
- if (mapBlockIndex.count(hash) == 0)
+ CBlockIndex* pblockindex = LookupBlockIndex(hash);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
+ }
- CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, Params(), pblockindex);
}
@@ -1510,10 +1511,11 @@ UniValue reconsiderblock(const JSONRPCRequest& request)
{
LOCK(cs_main);
- if (mapBlockIndex.count(hash) == 0)
+ CBlockIndex* pblockindex = LookupBlockIndex(hash);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
+ }
- CBlockIndex* pblockindex = mapBlockIndex[hash];
ResetBlockFailureFlags(pblockindex);
}
@@ -1560,11 +1562,10 @@ UniValue getchaintxstats(const JSONRPCRequest& request)
} else {
uint256 hash = uint256S(request.params[1].get_str());
LOCK(cs_main);
- auto it = mapBlockIndex.find(hash);
- if (it == mapBlockIndex.end()) {
+ pindex = LookupBlockIndex(hash);
+ if (!pindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
- pindex = it->second;
if (!chainActive.Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
}
@@ -1607,13 +1608,17 @@ UniValue savemempool(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"savemempool\n"
- "\nDumps the mempool to disk.\n"
+ "\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n"
"\nExamples:\n"
+ HelpExampleCli("savemempool", "")
+ HelpExampleRpc("savemempool", "")
);
}
+ if (!g_is_mempool_loaded) {
+ throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet");
+ }
+
if (!DumpMempool()) {
throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
}
diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp
index 0eeb3f98b3..01f932dbb4 100644
--- a/src/rpc/client.cpp
+++ b/src/rpc/client.cpp
@@ -40,6 +40,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "settxfee", 0, "amount" },
{ "getreceivedbyaddress", 1, "minconf" },
{ "getreceivedbyaccount", 1, "minconf" },
+ { "getreceivedbylabel", 1, "minconf" },
{ "listreceivedbyaddress", 0, "minconf" },
{ "listreceivedbyaddress", 1, "include_empty" },
{ "listreceivedbyaddress", 2, "include_watchonly" },
@@ -47,6 +48,9 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "listreceivedbyaccount", 0, "minconf" },
{ "listreceivedbyaccount", 1, "include_empty" },
{ "listreceivedbyaccount", 2, "include_watchonly" },
+ { "listreceivedbylabel", 0, "minconf" },
+ { "listreceivedbylabel", 1, "include_empty" },
+ { "listreceivedbylabel", 2, "include_watchonly" },
{ "getbalance", 1, "minconf" },
{ "getbalance", 2, "include_watchonly" },
{ "getblockhash", 0, "height" },
@@ -99,6 +103,8 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "signrawtransactionwithkey", 2, "prevtxs" },
{ "signrawtransactionwithwallet", 1, "prevtxs" },
{ "sendrawtransaction", 1, "allowhighfees" },
+ { "testmempoolaccept", 0, "rawtxs" },
+ { "testmempoolaccept", 1, "allowhighfees" },
{ "combinerawtransaction", 0, "txs" },
{ "fundrawtransaction", 1, "options" },
{ "fundrawtransaction", 2, "iswitness" },
diff --git a/src/rpc/client.h b/src/rpc/client.h
index e7cf035d8f..e09e1dedf3 100644
--- a/src/rpc/client.h
+++ b/src/rpc/client.h
@@ -3,8 +3,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_RPCCLIENT_H
-#define BITCOIN_RPCCLIENT_H
+#ifndef BITCOIN_RPC_CLIENT_H
+#define BITCOIN_RPC_CLIENT_H
#include <univalue.h>
@@ -19,4 +19,4 @@ UniValue RPCConvertNamedValues(const std::string& strMethod, const std::vector<s
*/
UniValue ParseNonRFCJSONValue(const std::string& strVal);
-#endif // BITCOIN_RPCCLIENT_H
+#endif // BITCOIN_RPC_CLIENT_H
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index 3073a49d0d..06882c0dfd 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -396,9 +396,8 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
uint256 hash = block.GetHash();
- BlockMap::iterator mi = mapBlockIndex.find(hash);
- if (mi != mapBlockIndex.end()) {
- CBlockIndex *pindex = mi->second;
+ const CBlockIndex* pindex = LookupBlockIndex(hash);
+ if (pindex) {
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
@@ -533,7 +532,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
pblock->nNonce = 0;
// NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
- const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
+ const bool fPreSegWit = (ThresholdState::ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
@@ -594,15 +593,15 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
switch (state) {
- case THRESHOLD_DEFINED:
- case THRESHOLD_FAILED:
+ case ThresholdState::DEFINED:
+ case ThresholdState::FAILED:
// Not exposed to GBT at all
break;
- case THRESHOLD_LOCKED_IN:
+ case ThresholdState::LOCKED_IN:
// Ensure bit is set in block version
pblock->nVersion |= VersionBitsMask(consensusParams, pos);
// FALL THROUGH to get vbavailable set...
- case THRESHOLD_STARTED:
+ case ThresholdState::STARTED:
{
const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
@@ -614,7 +613,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
}
break;
}
- case THRESHOLD_ACTIVE:
+ case ThresholdState::ACTIVE:
{
// Add to rules only
const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
@@ -727,9 +726,8 @@ UniValue submitblock(const JSONRPCRequest& request)
bool fBlockPresent = false;
{
LOCK(cs_main);
- BlockMap::iterator mi = mapBlockIndex.find(hash);
- if (mi != mapBlockIndex.end()) {
- CBlockIndex *pindex = mi->second;
+ const CBlockIndex* pindex = LookupBlockIndex(hash);
+ if (pindex) {
if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
return "duplicate";
}
@@ -743,9 +741,9 @@ UniValue submitblock(const JSONRPCRequest& request)
{
LOCK(cs_main);
- BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
- if (mi != mapBlockIndex.end()) {
- UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
+ const CBlockIndex* pindex = LookupBlockIndex(block.hashPrevBlock);
+ if (pindex) {
+ UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus());
}
}
diff --git a/src/rpc/protocol.h b/src/rpc/protocol.h
index 00b92f1956..4a265735d2 100644
--- a/src/rpc/protocol.h
+++ b/src/rpc/protocol.h
@@ -3,8 +3,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_RPCPROTOCOL_H
-#define BITCOIN_RPCPROTOCOL_H
+#ifndef BITCOIN_RPC_PROTOCOL_H
+#define BITCOIN_RPC_PROTOCOL_H
#include <fs.h>
@@ -76,7 +76,7 @@ enum RPCErrorCode
//! Wallet errors
RPC_WALLET_ERROR = -4, //!< Unspecified problem with wallet (key not found etc.)
RPC_WALLET_INSUFFICIENT_FUNDS = -6, //!< Not enough funds in wallet or account
- RPC_WALLET_INVALID_ACCOUNT_NAME = -11, //!< Invalid account name
+ RPC_WALLET_INVALID_LABEL_NAME = -11, //!< Invalid label name
RPC_WALLET_KEYPOOL_RAN_OUT = -12, //!< Keypool ran out, call keypoolrefill first
RPC_WALLET_UNLOCK_NEEDED = -13, //!< Enter the wallet passphrase with walletpassphrase first
RPC_WALLET_PASSPHRASE_INCORRECT = -14, //!< The wallet passphrase entered was incorrect
@@ -85,6 +85,9 @@ enum RPCErrorCode
RPC_WALLET_ALREADY_UNLOCKED = -17, //!< Wallet is already unlocked
RPC_WALLET_NOT_FOUND = -18, //!< Invalid wallet specified
RPC_WALLET_NOT_SPECIFIED = -19, //!< No wallet specified (error when there are multiple wallets loaded)
+
+ //! Backwards compatible aliases
+ RPC_WALLET_INVALID_ACCOUNT_NAME = RPC_WALLET_INVALID_LABEL_NAME,
};
UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id);
@@ -101,4 +104,4 @@ void DeleteAuthCookie();
/** Parse JSON-RPC batch reply into a vector */
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in, size_t num);
-#endif // BITCOIN_RPCPROTOCOL_H
+#endif // BITCOIN_RPC_PROTOCOL_H
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 8dcfb48e9a..9d7aa58894 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -48,9 +48,8 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
if (!hashBlock.IsNull()) {
entry.pushKV("blockhash", hashBlock.GetHex());
- BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
- if (mi != mapBlockIndex.end() && (*mi).second) {
- CBlockIndex* pindex = (*mi).second;
+ CBlockIndex* pindex = LookupBlockIndex(hashBlock);
+ if (pindex) {
if (chainActive.Contains(pindex)) {
entry.pushKV("confirmations", 1 + chainActive.Height() - pindex->nHeight);
entry.pushKV("time", pindex->GetBlockTime());
@@ -160,11 +159,10 @@ UniValue getrawtransaction(const JSONRPCRequest& request)
if (!request.params[2].isNull()) {
uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
- BlockMap::iterator it = mapBlockIndex.find(blockhash);
- if (it == mapBlockIndex.end()) {
+ blockindex = LookupBlockIndex(blockhash);
+ if (!blockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
}
- blockindex = it->second;
in_active_chain = chainActive.Contains(blockindex);
}
@@ -238,9 +236,10 @@ UniValue gettxoutproof(const JSONRPCRequest& request)
if (!request.params[1].isNull())
{
hashBlock = uint256S(request.params[1].get_str());
- if (!mapBlockIndex.count(hashBlock))
+ pblockindex = LookupBlockIndex(hashBlock);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
- pblockindex = mapBlockIndex[hashBlock];
+ }
} else {
// Loop through txids and try to find which block they're in. Exit loop once a block is found.
for (const auto& tx : setTxids) {
@@ -257,9 +256,10 @@ UniValue gettxoutproof(const JSONRPCRequest& request)
CTransactionRef tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
- if (!mapBlockIndex.count(hashBlock))
+ pblockindex = LookupBlockIndex(hashBlock);
+ if (!pblockindex) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
- pblockindex = mapBlockIndex[hashBlock];
+ }
}
CBlock block;
@@ -306,8 +306,10 @@ UniValue verifytxoutproof(const JSONRPCRequest& request)
LOCK(cs_main);
- if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
+ const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash());
+ if (!pindex || !chainActive.Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
+ }
for (const uint256& hash : vMatch)
res.push_back(hash.GetHex());
@@ -316,9 +318,10 @@ UniValue verifytxoutproof(const JSONRPCRequest& request)
UniValue createrawtransaction(const JSONRPCRequest& request)
{
- if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
+ if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {
throw std::runtime_error(
- "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime ) ( replaceable )\n"
+ // clang-format off
+ "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
@@ -329,18 +332,23 @@ UniValue createrawtransaction(const JSONRPCRequest& request)
"1. \"inputs\" (array, required) A json array of json objects\n"
" [\n"
" {\n"
- " \"txid\":\"id\", (string, required) The transaction id\n"
+ " \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"sequence\":n (numeric, optional) The sequence number\n"
" } \n"
" ,...\n"
" ]\n"
- "2. \"outputs\" (object, required) a json object with outputs\n"
+ "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n"
+ " [\n"
" {\n"
- " \"address\": x.xxx, (numeric or string, required) The key is the bitcoin address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
- " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
- " ,...\n"
+ " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n"
+ " },\n"
+ " {\n"
+ " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n"
" }\n"
+ " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
+ " accepted as second parameter.\n"
+ " ]\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
" Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"
@@ -348,18 +356,29 @@ UniValue createrawtransaction(const JSONRPCRequest& request)
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples:\n"
- + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
- + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
- + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
- + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
+ + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
+ + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"")
+ + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
+ // clang-format on
);
+ }
- RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VOBJ, UniValue::VNUM, UniValue::VBOOL}, true);
+ RPCTypeCheck(request.params, {
+ UniValue::VARR,
+ UniValueType(), // ARR or OBJ, checked later
+ UniValue::VNUM,
+ UniValue::VBOOL
+ }, true
+ );
if (request.params[0].isNull() || request.params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = request.params[0].get_array();
- UniValue sendTo = request.params[1].get_obj();
+ const bool outputs_is_obj = request.params[1].isObject();
+ UniValue outputs = outputs_is_obj ?
+ request.params[1].get_obj() :
+ request.params[1].get_array();
CMutableTransaction rawTx;
@@ -411,11 +430,24 @@ UniValue createrawtransaction(const JSONRPCRequest& request)
}
std::set<CTxDestination> destinations;
- std::vector<std::string> addrList = sendTo.getKeys();
- for (const std::string& name_ : addrList) {
-
+ if (!outputs_is_obj) {
+ // Translate array of key-value pairs into dict
+ UniValue outputs_dict = UniValue(UniValue::VOBJ);
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ const UniValue& output = outputs[i];
+ if (!output.isObject()) {
+ throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");
+ }
+ if (output.size() != 1) {
+ throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key");
+ }
+ outputs_dict.pushKVs(output);
+ }
+ outputs = std::move(outputs_dict);
+ }
+ for (const std::string& name_ : outputs.getKeys()) {
if (name_ == "data") {
- std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
+ std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
@@ -430,7 +462,7 @@ UniValue createrawtransaction(const JSONRPCRequest& request)
}
CScript scriptPubKey = GetScriptForDestination(destination);
- CAmount nAmount = AmountFromValue(sendTo[name_]);
+ CAmount nAmount = AmountFromValue(outputs[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
@@ -991,18 +1023,18 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
new_request.params.push_back(request.params[1]);
new_request.params.push_back(request.params[3]);
return signrawtransactionwithkey(new_request);
- }
- // Otherwise sign with the wallet which does not take a privkeys parameter
+ } else {
#ifdef ENABLE_WALLET
- else {
+ // Otherwise sign with the wallet which does not take a privkeys parameter
new_request.params.push_back(request.params[0]);
new_request.params.push_back(request.params[1]);
new_request.params.push_back(request.params[3]);
return signrawtransactionwithwallet(new_request);
- }
+#else
+ // If we have made it this far, then wallet is disabled and no private keys were given, so fail here.
+ throw JSONRPCError(RPC_INVALID_PARAMETER, "No private keys available.");
#endif
- // If we have made it this far, then wallet is disabled and no private keys were given, so fail here.
- throw JSONRPCError(RPC_INVALID_PARAMETER, "No private keys available.");
+ }
}
UniValue sendrawtransaction(const JSONRPCRequest& request)
@@ -1102,6 +1134,87 @@ UniValue sendrawtransaction(const JSONRPCRequest& request)
return hashTx.GetHex();
}
+UniValue testmempoolaccept(const JSONRPCRequest& request)
+{
+ if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
+ throw std::runtime_error(
+ // clang-format off
+ "testmempoolaccept [\"rawtxs\"] ( allowhighfees )\n"
+ "\nReturns if raw transaction (serialized, hex-encoded) would be accepted by mempool.\n"
+ "\nThis checks if the transaction violates the consensus or policy rules.\n"
+ "\nSee sendrawtransaction call.\n"
+ "\nArguments:\n"
+ "1. [\"rawtxs\"] (array, required) An array of hex strings of raw transactions.\n"
+ " Length must be one for now.\n"
+ "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
+ "\nResult:\n"
+ "[ (array) The result of the mempool acceptance test for each raw transaction in the input array.\n"
+ " Length is exactly one for now.\n"
+ " {\n"
+ " \"txid\" (string) The transaction hash in hex\n"
+ " \"allowed\" (boolean) If the mempool allows this tx to be inserted\n"
+ " \"reject-reason\" (string) Rejection string (only present when 'allowed' is false)\n"
+ " }\n"
+ "]\n"
+ "\nExamples:\n"
+ "\nCreate a transaction\n"
+ + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
+ "Sign the transaction, and get back the hex\n"
+ + HelpExampleCli("signrawtransaction", "\"myhex\"") +
+ "\nTest acceptance of the transaction (signed hex)\n"
+ + HelpExampleCli("testmempoolaccept", "\"signedhex\"") +
+ "\nAs a json rpc call\n"
+ + HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")
+ // clang-format on
+ );
+ }
+
+ ObserveSafeMode();
+
+ RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VBOOL});
+ if (request.params[0].get_array().size() != 1) {
+ throw JSONRPCError(RPC_INVALID_PARAMETER, "Array must contain exactly one raw transaction for now");
+ }
+
+ CMutableTransaction mtx;
+ if (!DecodeHexTx(mtx, request.params[0].get_array()[0].get_str())) {
+ throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
+ }
+ CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
+ const uint256& tx_hash = tx->GetHash();
+
+ CAmount max_raw_tx_fee = ::maxTxFee;
+ if (!request.params[1].isNull() && request.params[1].get_bool()) {
+ max_raw_tx_fee = 0;
+ }
+
+ UniValue result(UniValue::VARR);
+ UniValue result_0(UniValue::VOBJ);
+ result_0.pushKV("txid", tx_hash.GetHex());
+
+ CValidationState state;
+ bool missing_inputs;
+ bool test_accept_res;
+ {
+ 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);
+ }
+ result_0.pushKV("allowed", test_accept_res);
+ if (!test_accept_res) {
+ if (state.IsInvalid()) {
+ result_0.pushKV("reject-reason", strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
+ } else if (missing_inputs) {
+ result_0.pushKV("reject-reason", "missing-inputs");
+ } else {
+ result_0.pushKV("reject-reason", state.GetRejectReason());
+ }
+ }
+
+ result.push_back(std::move(result_0));
+ return result;
+}
+
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
@@ -1113,6 +1226,7 @@ static const CRPCCommand commands[] =
{ "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
{ "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
{ "rawtransactions", "signrawtransactionwithkey", &signrawtransactionwithkey, {"hexstring","privkeys","prevtxs","sighashtype"} },
+ { "rawtransactions", "testmempoolaccept", &testmempoolaccept, {"rawtxs","allowhighfees"} },
{ "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
{ "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
diff --git a/src/rpc/register.h b/src/rpc/register.h
index 49aee2365f..b689740681 100644
--- a/src/rpc/register.h
+++ b/src/rpc/register.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_RPCREGISTER_H
-#define BITCOIN_RPCREGISTER_H
+#ifndef BITCOIN_RPC_REGISTER_H
+#define BITCOIN_RPC_REGISTER_H
/** These are in one header file to avoid creating tons of single-function
* headers for everything under src/rpc/ */
@@ -29,4 +29,4 @@ static inline void RegisterAllCoreRPCCommands(CRPCTable &t)
RegisterRawTransactionRPCCommands(t);
}
-#endif
+#endif // BITCOIN_RPC_REGISTER_H
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index 35401bf876..c7c3b1f0d3 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -50,12 +50,11 @@ void RPCServer::OnStopped(std::function<void ()> slot)
}
void RPCTypeCheck(const UniValue& params,
- const std::list<UniValue::VType>& typesExpected,
+ const std::list<UniValueType>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
- for (UniValue::VType t : typesExpected)
- {
+ for (const UniValueType& t : typesExpected) {
if (params.size() <= i)
break;
@@ -67,10 +66,10 @@ void RPCTypeCheck(const UniValue& params,
}
}
-void RPCTypeCheckArgument(const UniValue& value, UniValue::VType typeExpected)
+void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected)
{
- if (value.type() != typeExpected) {
- throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected), uvTypeName(value.type())));
+ if (!typeExpected.typeAny && value.type() != typeExpected.type) {
+ throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected.type), uvTypeName(value.type())));
}
}
@@ -368,7 +367,11 @@ void JSONRPCRequest::parse(const UniValue& valRequest)
if (!valMethod.isStr())
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
- LogPrint(BCLog::RPC, "ThreadRPCServer method=%s\n", SanitizeString(strMethod));
+ if (fLogIPs)
+ LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s\n", SanitizeString(strMethod),
+ this->authUser, this->peerAddr);
+ else
+ LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s\n", SanitizeString(strMethod), this->authUser);
// Parse params
UniValue valParams = find_value(request, "params");
diff --git a/src/rpc/server.h b/src/rpc/server.h
index 075940cb90..373914885c 100644
--- a/src/rpc/server.h
+++ b/src/rpc/server.h
@@ -3,8 +3,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_RPCSERVER_H
-#define BITCOIN_RPCSERVER_H
+#ifndef BITCOIN_RPC_SERVER_H
+#define BITCOIN_RPC_SERVER_H
#include <amount.h>
#include <rpc/protocol.h>
@@ -28,9 +28,9 @@ namespace RPCServer
}
/** Wrapper for UniValue::VType, which includes typeAny:
- * Used to denote don't care type. Only used by RPCTypeCheckObj */
+ * Used to denote don't care type. */
struct UniValueType {
- explicit UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
+ UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
UniValueType() : typeAny(true) {}
bool typeAny;
UniValue::VType type;
@@ -45,6 +45,7 @@ public:
bool fHelp;
std::string URI;
std::string authUser;
+ std::string peerAddr;
JSONRPCRequest() : id(NullUniValue), params(NullUniValue), fHelp(false) {}
void parse(const UniValue& valRequest);
@@ -69,12 +70,12 @@ bool RPCIsInWarmup(std::string *outStatus);
* the right number of arguments are passed, just that any passed are the correct type.
*/
void RPCTypeCheck(const UniValue& params,
- const std::list<UniValue::VType>& typesExpected, bool fAllowNull=false);
+ const std::list<UniValueType>& typesExpected, bool fAllowNull=false);
/**
* Type-check one argument; throws JSONRPCError if wrong type given.
*/
-void RPCTypeCheckArgument(const UniValue& value, UniValue::VType typeExpected);
+void RPCTypeCheckArgument(const UniValue& value, const UniValueType& typeExpected);
/*
Check for expected keys/value types in an Object.
@@ -165,8 +166,17 @@ public:
/**
* Appends a CRPCCommand to the dispatch table.
+ *
* Returns false if RPC server is already running (dump concurrency protection).
+ *
* Commands cannot be overwritten (returns false).
+ *
+ * Commands with different method names but the same callback function will
+ * be considered aliases, and only the first registered method name will
+ * show up in the help text command listing. Aliased commands do not have
+ * to have the same behavior. Server and client code can distinguish
+ * between calls based on method name, and aliased commands can also
+ * register different names, types, and numbers of parameters.
*/
bool appendCommand(const std::string& name, const CRPCCommand* pcmd);
};
@@ -196,4 +206,4 @@ std::string JSONRPCExecBatch(const JSONRPCRequest& jreq, const UniValue& vReq);
// Retrieves any serialization flags requested in command line argument
int RPCSerializationFlags();
-#endif // BITCOIN_RPCSERVER_H
+#endif // BITCOIN_RPC_SERVER_H
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index 593962e710..e72b1c4840 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -4,7 +4,6 @@
#include <key_io.h>
#include <keystore.h>
-#include <pubkey.h>
#include <rpc/protocol.h>
#include <rpc/util.h>
#include <tinyformat.h>
diff --git a/src/rpc/util.h b/src/rpc/util.h
index 5380d45a83..c6a79d5cf9 100644
--- a/src/rpc/util.h
+++ b/src/rpc/util.h
@@ -8,7 +8,6 @@
#include <pubkey.h>
#include <script/standard.h>
#include <univalue.h>
-#include <utilstrencodings.h>
#include <boost/variant/static_visitor.hpp>
diff --git a/src/script/bitcoinconsensus.cpp b/src/script/bitcoinconsensus.cpp
index 7d3587e2c2..8cc44b675f 100644
--- a/src/script/bitcoinconsensus.cpp
+++ b/src/script/bitcoinconsensus.cpp
@@ -40,7 +40,7 @@ public:
}
template<typename T>
- TxInputStream& operator>>(T& obj)
+ TxInputStream& operator>>(T&& obj)
{
::Unserialize(*this, obj);
return *this;
diff --git a/src/script/bitcoinconsensus.h b/src/script/bitcoinconsensus.h
index bb94c17528..5973808fa5 100644
--- a/src/script/bitcoinconsensus.h
+++ b/src/script/bitcoinconsensus.h
@@ -3,8 +3,8 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_BITCOINCONSENSUS_H
-#define BITCOIN_BITCOINCONSENSUS_H
+#ifndef BITCOIN_SCRIPT_BITCOINCONSENSUS_H
+#define BITCOIN_SCRIPT_BITCOINCONSENSUS_H
#include <stdint.h>
@@ -80,4 +80,4 @@ EXPORT_SYMBOL unsigned int bitcoinconsensus_version();
#undef EXPORT_SYMBOL
-#endif // BITCOIN_BITCOINCONSENSUS_H
+#endif // BITCOIN_SCRIPT_BITCOINCONSENSUS_H
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 927b0267ca..182f4a3327 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -61,17 +61,17 @@ static inline void popstack(std::vector<valtype>& stack)
}
bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
- if (vchPubKey.size() < 33) {
+ if (vchPubKey.size() < CPubKey::COMPRESSED_PUBLIC_KEY_SIZE) {
// Non-canonical public key: too short
return false;
}
if (vchPubKey[0] == 0x04) {
- if (vchPubKey.size() != 65) {
+ if (vchPubKey.size() != CPubKey::PUBLIC_KEY_SIZE) {
// Non-canonical public key: invalid length for uncompressed key
return false;
}
} else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
- if (vchPubKey.size() != 33) {
+ if (vchPubKey.size() != CPubKey::COMPRESSED_PUBLIC_KEY_SIZE) {
// Non-canonical public key: invalid length for compressed key
return false;
}
@@ -83,7 +83,7 @@ bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
}
bool static IsCompressedPubKey(const valtype &vchPubKey) {
- if (vchPubKey.size() != 33) {
+ if (vchPubKey.size() != CPubKey::COMPRESSED_PUBLIC_KEY_SIZE) {
// Non-canonical public key: invalid length for compressed key
return false;
}
@@ -110,7 +110,7 @@ bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
// excluding the sighash byte.
// * R-length: 1-byte length descriptor of the R value that follows.
// * R: arbitrary-length big-endian encoded R value. It must use the shortest
- // possible encoding for a positive integers (which means no null bytes at
+ // possible encoding for a positive integer (which means no null bytes at
// the start, except a single one when the next byte has its highest bit set).
// * S-length: 1-byte length descriptor of the S value that follows.
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
@@ -219,7 +219,7 @@ bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, co
return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
}
// Only compressed keys are accepted in segwit
- if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SIGVERSION_WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
+ if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
}
return true;
@@ -443,7 +443,7 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
valtype& vch = stacktop(-1);
- if (sigversion == SIGVERSION_WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
+ if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
if (vch.size() > 1)
return set_error(serror, SCRIPT_ERR_MINIMALIF);
if (vch.size() == 1 && vch[0] != 1)
@@ -890,7 +890,7 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
CScript scriptCode(pbegincodehash, pend);
// Drop the signature in pre-segwit scripts but not segwit scripts
- if (sigversion == SIGVERSION_BASE) {
+ if (sigversion == SigVersion::BASE) {
scriptCode.FindAndDelete(CScript(vchSig));
}
@@ -954,7 +954,7 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
for (int k = 0; k < nSigsCount; k++)
{
valtype& vchSig = stacktop(-isig-k);
- if (sigversion == SIGVERSION_BASE) {
+ if (sigversion == SigVersion::BASE) {
scriptCode.FindAndDelete(CScript(vchSig));
}
}
@@ -1182,7 +1182,7 @@ uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsig
{
assert(nIn < txTo.vin.size());
- if (sigversion == SIGVERSION_WITNESS_V0) {
+ if (sigversion == SigVersion::WITNESS_V0) {
uint256 hashPrevouts;
uint256 hashSequence;
uint256 hashOutputs;
@@ -1396,13 +1396,13 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
}
- if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V0, serror)) {
+ if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::WITNESS_V0, serror)) {
return false;
}
// Scripts inside witness implicitly require cleanstack behaviour
if (stack.size() != 1)
- return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
+ return set_error(serror, SCRIPT_ERR_CLEANSTACK);
if (!CastToBool(stack.back()))
return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
return true;
@@ -1423,12 +1423,12 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
}
std::vector<std::vector<unsigned char> > stack, stackCopy;
- if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
+ if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
// serror is set
return false;
if (flags & SCRIPT_VERIFY_P2SH)
stackCopy = stack;
- if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
+ if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
// serror is set
return false;
if (stack.empty())
@@ -1474,7 +1474,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
popstack(stack);
- if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
+ if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
// serror is set
return false;
if (stack.empty())
diff --git a/src/script/interpreter.h b/src/script/interpreter.h
index 4dad6b44c5..bb7750d783 100644
--- a/src/script/interpreter.h
+++ b/src/script/interpreter.h
@@ -123,10 +123,10 @@ struct PrecomputedTransactionData
explicit PrecomputedTransactionData(const CTransaction& tx);
};
-enum SigVersion
+enum class SigVersion
{
- SIGVERSION_BASE = 0,
- SIGVERSION_WITNESS_V0 = 1,
+ BASE = 0,
+ WITNESS_V0 = 1,
};
uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache = nullptr);
diff --git a/src/script/ismine.cpp b/src/script/ismine.cpp
index 35d794b983..05bc5e9bd6 100644
--- a/src/script/ismine.cpp
+++ b/src/script/ismine.cpp
@@ -61,7 +61,7 @@ isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey, bool&
break;
case TX_PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
- if (sigversion != SIGVERSION_BASE && vSolutions[0].size() != 33) {
+ if (sigversion != SigVersion::BASE && vSolutions[0].size() != 33) {
isInvalid = true;
return ISMINE_NO;
}
@@ -76,14 +76,14 @@ isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey, bool&
// This also applies to the P2WSH case.
break;
}
- isminetype ret = ::IsMine(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), isInvalid, SIGVERSION_WITNESS_V0);
+ isminetype ret = ::IsMine(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), isInvalid, SigVersion::WITNESS_V0);
if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid))
return ret;
break;
}
case TX_PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
- if (sigversion != SIGVERSION_BASE) {
+ if (sigversion != SigVersion::BASE) {
CPubKey pubkey;
if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
isInvalid = true;
@@ -114,7 +114,7 @@ isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey, bool&
CScriptID scriptID = CScriptID(hash);
CScript subscript;
if (keystore.GetCScript(scriptID, subscript)) {
- isminetype ret = IsMine(keystore, subscript, isInvalid, SIGVERSION_WITNESS_V0);
+ isminetype ret = IsMine(keystore, subscript, isInvalid, SigVersion::WITNESS_V0);
if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid))
return ret;
}
@@ -129,7 +129,7 @@ isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey, bool&
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
- if (sigversion != SIGVERSION_BASE) {
+ if (sigversion != SigVersion::BASE) {
for (size_t i = 0; i < keys.size(); i++) {
if (keys[i].size() != 33) {
isInvalid = true;
diff --git a/src/script/ismine.h b/src/script/ismine.h
index c1338c3a8e..f93a66e35a 100644
--- a/src/script/ismine.h
+++ b/src/script/ismine.h
@@ -31,11 +31,11 @@ typedef uint8_t isminefilter;
/* isInvalid becomes true when the script is found invalid by consensus or policy. This will terminate the recursion
* and return ISMINE_NO immediately, as an invalid script should never be considered as "mine". This is needed as
* different SIGVERSION may have different network rules. Currently the only use of isInvalid is indicate uncompressed
- * keys in SIGVERSION_WITNESS_V0 script, but could also be used in similar cases in the future
+ * keys in SigVersion::WITNESS_V0 script, but could also be used in similar cases in the future
*/
-isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid, SigVersion = SIGVERSION_BASE);
-isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, SigVersion = SIGVERSION_BASE);
-isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest, bool& isInvalid, SigVersion = SIGVERSION_BASE);
-isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest, SigVersion = SIGVERSION_BASE);
+isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid, SigVersion = SigVersion::BASE);
+isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, SigVersion = SigVersion::BASE);
+isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest, bool& isInvalid, SigVersion = SigVersion::BASE);
+isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest, SigVersion = SigVersion::BASE);
#endif // BITCOIN_SCRIPT_ISMINE_H
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index aaba5e5926..910bb39ce6 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -6,7 +6,6 @@
#include <script/sign.h>
#include <key.h>
-#include <keystore.h>
#include <policy/policy.h>
#include <primitives/transaction.h>
#include <script/standard.h>
@@ -15,16 +14,16 @@
typedef std::vector<unsigned char> valtype;
-TransactionSignatureCreator::TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : BaseSignatureCreator(keystoreIn), txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {}
+TransactionSignatureCreator::TransactionSignatureCreator(const SigningProvider* provider, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : BaseSignatureCreator(provider), txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {}
bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
{
CKey key;
- if (!keystore->GetKey(address, key))
+ if (!m_provider->GetKey(address, key))
return false;
// Signing with uncompressed keys is disabled in witness scripts
- if (sigversion == SIGVERSION_WITNESS_V0 && !key.IsCompressed())
+ if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
return false;
uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion);
@@ -91,12 +90,12 @@ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptP
else
{
CPubKey vch;
- creator.KeyStore().GetPubKey(keyID, vch);
+ creator.Provider().GetPubKey(keyID, vch);
ret.push_back(ToByteVector(vch));
}
return true;
case TX_SCRIPTHASH:
- if (creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptRet)) {
+ if (creator.Provider().GetCScript(uint160(vSolutions[0]), scriptRet)) {
ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
return true;
}
@@ -112,7 +111,7 @@ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptP
case TX_WITNESS_V0_SCRIPTHASH:
CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin());
- if (creator.KeyStore().GetCScript(h160, scriptRet)) {
+ if (creator.Provider().GetCScript(h160, scriptRet)) {
ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
return true;
}
@@ -142,7 +141,7 @@ bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPu
{
std::vector<valtype> result;
txnouttype whichType;
- bool solved = SignStep(creator, fromPubKey, result, whichType, SIGVERSION_BASE);
+ bool solved = SignStep(creator, fromPubKey, result, whichType, SigVersion::BASE);
bool P2SH = false;
CScript subscript;
sigdata.scriptWitness.stack.clear();
@@ -153,7 +152,7 @@ bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPu
// the final scriptSig is the signatures from that
// and then the serialized subscript:
subscript = CScript(result[0].begin(), result[0].end());
- solved = solved && SignStep(creator, subscript, result, whichType, SIGVERSION_BASE) && whichType != TX_SCRIPTHASH;
+ solved = solved && SignStep(creator, subscript, result, whichType, SigVersion::BASE) && whichType != TX_SCRIPTHASH;
P2SH = true;
}
@@ -162,7 +161,7 @@ bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPu
CScript witnessscript;
witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
txnouttype subType;
- solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0);
+ solved = solved && SignStep(creator, witnessscript, result, subType, SigVersion::WITNESS_V0);
sigdata.scriptWitness.stack = result;
result.clear();
}
@@ -170,7 +169,7 @@ bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPu
{
CScript witnessscript(result[0].begin(), result[0].end());
txnouttype subType;
- solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH;
+ solved = solved && SignStep(creator, witnessscript, result, subType, SigVersion::WITNESS_V0) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH;
result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));
sigdata.scriptWitness.stack = result;
result.clear();
@@ -194,19 +193,24 @@ SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nI
return data;
}
+void UpdateInput(CTxIn& input, const SignatureData& data)
+{
+ input.scriptSig = data.scriptSig;
+ input.scriptWitness = data.scriptWitness;
+}
+
void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data)
{
assert(tx.vin.size() > nIn);
- tx.vin[nIn].scriptSig = data.scriptSig;
- tx.vin[nIn].scriptWitness = data.scriptWitness;
+ UpdateInput(tx.vin[nIn], data);
}
-bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)
+bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)
{
assert(nIn < txTo.vin.size());
CTransaction txToConst(txTo);
- TransactionSignatureCreator creator(&keystore, &txToConst, nIn, amount, nHashType);
+ TransactionSignatureCreator creator(&provider, &txToConst, nIn, amount, nHashType);
SignatureData sigdata;
bool ret = ProduceSignature(creator, fromPubKey, sigdata);
@@ -214,14 +218,14 @@ bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutabl
return ret;
}
-bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
+bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
{
assert(nIn < txTo.vin.size());
CTxIn& txin = txTo.vin[nIn];
assert(txin.prevout.n < txFrom.vout.size());
const CTxOut& txout = txFrom.vout[txin.prevout.n];
- return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
+ return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
}
static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
@@ -289,7 +293,7 @@ struct Stacks
Stacks() {}
explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_), witness() {}
explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
- EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SIGVERSION_BASE);
+ EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
}
SignatureData Output() const {
@@ -365,7 +369,7 @@ static Stacks CombineSignatures(const CScript& scriptPubKey, const BaseSignature
sigs2.witness.pop_back();
sigs2.script = sigs2.witness;
sigs2.witness.clear();
- Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, SIGVERSION_WITNESS_V0);
+ Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, SigVersion::WITNESS_V0);
result.witness = result.script;
result.script.clear();
result.witness.push_back(valtype(pubKey2.begin(), pubKey2.end()));
@@ -383,7 +387,7 @@ SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignature
std::vector<std::vector<unsigned char> > vSolutions;
Solver(scriptPubKey, txType, vSolutions);
- return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1), Stacks(scriptSig2), SIGVERSION_BASE).Output();
+ return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1), Stacks(scriptSig2), SigVersion::BASE).Output();
}
namespace {
@@ -422,13 +426,13 @@ bool DummySignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const
return true;
}
-bool IsSolvable(const CKeyStore& store, const CScript& script)
+bool IsSolvable(const SigningProvider& provider, const CScript& script)
{
// This check is to make sure that the script we created can actually be solved for and signed by us
// if we were to have the private keys. This is just to make sure that the script is valid and that,
// if found in a transaction, we would still accept and relay that transaction. In particular,
// it will reject witness outputs that require signing with an uncompressed public key.
- DummySignatureCreator creator(&store);
+ DummySignatureCreator creator(&provider);
SignatureData sigs;
// Make sure that STANDARD_SCRIPT_VERIFY_FLAGS includes SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, the most
// important property this function is designed to test for.
diff --git a/src/script/sign.h b/src/script/sign.h
index 97c0014cd0..c301f0544f 100644
--- a/src/script/sign.h
+++ b/src/script/sign.h
@@ -8,21 +8,32 @@
#include <script/interpreter.h>
+class CKey;
class CKeyID;
-class CKeyStore;
class CScript;
+class CScriptID;
class CTransaction;
struct CMutableTransaction;
+/** An interface to be implemented by keystores that support signing. */
+class SigningProvider
+{
+public:
+ virtual ~SigningProvider() {}
+ virtual bool GetCScript(const CScriptID &scriptid, CScript& script) const =0;
+ virtual bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const =0;
+ virtual bool GetKey(const CKeyID &address, CKey& key) const =0;
+};
+
/** Virtual base class for signature creators. */
class BaseSignatureCreator {
protected:
- const CKeyStore* keystore;
+ const SigningProvider* m_provider;
public:
- explicit BaseSignatureCreator(const CKeyStore* keystoreIn) : keystore(keystoreIn) {}
- const CKeyStore& KeyStore() const { return *keystore; };
+ explicit BaseSignatureCreator(const SigningProvider* provider) : m_provider(provider) {}
+ const SigningProvider& Provider() const { return *m_provider; }
virtual ~BaseSignatureCreator() {}
virtual const BaseSignatureChecker& Checker() const =0;
@@ -39,7 +50,7 @@ class TransactionSignatureCreator : public BaseSignatureCreator {
const TransactionSignatureChecker checker;
public:
- TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn=SIGHASH_ALL);
+ TransactionSignatureCreator(const SigningProvider* provider, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn=SIGHASH_ALL);
const BaseSignatureChecker& Checker() const override { return checker; }
bool CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override;
};
@@ -48,13 +59,13 @@ class MutableTransactionSignatureCreator : public TransactionSignatureCreator {
CTransaction tx;
public:
- MutableTransactionSignatureCreator(const CKeyStore* keystoreIn, const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : TransactionSignatureCreator(keystoreIn, &tx, nInIn, amountIn, nHashTypeIn), tx(*txToIn) {}
+ MutableTransactionSignatureCreator(const SigningProvider* provider, const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : TransactionSignatureCreator(provider, &tx, nInIn, amountIn, nHashTypeIn), tx(*txToIn) {}
};
/** A signature creator that just produces 72-byte empty signatures. */
class DummySignatureCreator : public BaseSignatureCreator {
public:
- explicit DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {}
+ explicit DummySignatureCreator(const SigningProvider* provider) : BaseSignatureCreator(provider) {}
const BaseSignatureChecker& Checker() const override;
bool CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override;
};
@@ -71,8 +82,8 @@ struct SignatureData {
bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata);
/** Produce a script signature for a transaction. */
-bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType);
-bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType);
+bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType);
+bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType);
/** Combine two script signatures using a generic signature checker, intelligently, possibly with OP_0 placeholders. */
SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const SignatureData& scriptSig1, const SignatureData& scriptSig2);
@@ -80,11 +91,12 @@ SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignature
/** Extract signature data from a transaction, and insert it. */
SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn);
void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data);
+void UpdateInput(CTxIn& input, const SignatureData& data);
/* Check whether we know how to sign for an output like this, assuming we
* have all private keys. While this function does not need private keys, the passed
- * keystore is used to look up public keys and redeemscripts by hash.
+ * provider is used to look up public keys and redeemscripts by hash.
* Solvability is unrelated to whether we consider this output to be ours. */
-bool IsSolvable(const CKeyStore& store, const CScript& script);
+bool IsSolvable(const SigningProvider& provider, const CScript& script);
#endif // BITCOIN_SCRIPT_SIGN_H
diff --git a/src/script/standard.cpp b/src/script/standard.cpp
index cfb3c58588..0b9053d7fc 100644
--- a/src/script/standard.cpp
+++ b/src/script/standard.cpp
@@ -132,7 +132,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::v
// Template matching opcodes:
if (opcode2 == OP_PUBKEYS)
{
- while (vch1.size() >= 33 && vch1.size() <= 65)
+ while (CPubKey::ValidSize(vch1))
{
vSolutionsRet.push_back(vch1);
if (!script1.GetOp(pc1, opcode1, vch1))
@@ -146,7 +146,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::v
if (opcode2 == OP_PUBKEY)
{
- if (vch1.size() < 33 || vch1.size() > 65)
+ if (!CPubKey::ValidSize(vch1))
break;
vSolutionsRet.push_back(vch1);
}
diff --git a/src/serialize.h b/src/serialize.h
index dcc8d8691e..247e915298 100644
--- a/src/serialize.h
+++ b/src/serialize.h
@@ -59,6 +59,12 @@ inline T* NCONST_PTR(const T* val)
return const_cast<T*>(val);
}
+//! Safely convert odd char pointer types to standard ones.
+inline char* CharCast(char* c) { return c; }
+inline char* CharCast(unsigned char* c) { return (char*)c; }
+inline const char* CharCast(const char* c) { return c; }
+inline const char* CharCast(const unsigned char* c) { return (const char*)c; }
+
/*
* Lowest-level serialization and conversion.
* @note Sizes of these types are verified in the tests
@@ -148,8 +154,7 @@ enum
SER_GETHASH = (1 << 2),
};
-#define READWRITE(obj) (::SerReadWrite(s, (obj), ser_action))
-#define READWRITEMANY(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
+#define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
/**
* Implement three methods for serializable objects. These are actually wrappers over
@@ -178,6 +183,8 @@ template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_wri
template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
template<typename Stream> inline void Serialize(Stream& s, float a ) { ser_writedata32(s, ser_float_to_uint32(a)); }
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 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); }
@@ -190,6 +197,8 @@ template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a =
template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
template<typename Stream> inline void Unserialize(Stream& s, float& a ) { a = ser_uint32_to_float(ser_readdata32(s)); }
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 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; }
@@ -297,9 +306,31 @@ uint64_t ReadCompactSize(Stream& is)
* 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
*/
-template<typename I>
+/**
+ * Mode for encoding VarInts.
+ *
+ * Currently there is no support for signed encodings. The default mode will not
+ * compile with signed values, and the legacy "nonnegative signed" mode will
+ * accept signed values, but improperly encode and decode them if they are
+ * negative. In the future, the DEFAULT mode could be extended to support
+ * negative numbers in a backwards compatible way, and additional modes could be
+ * added to support different varint formats (e.g. zigzag encoding).
+ */
+enum class VarIntMode { DEFAULT, NONNEGATIVE_SIGNED };
+
+template <VarIntMode Mode, typename I>
+struct CheckVarIntMode {
+ constexpr CheckVarIntMode()
+ {
+ static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
+ static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
+ }
+};
+
+template<VarIntMode Mode, typename I>
inline unsigned int GetSizeOfVarInt(I n)
{
+ CheckVarIntMode<Mode, I>();
int nRet = 0;
while(true) {
nRet++;
@@ -313,9 +344,10 @@ inline unsigned int GetSizeOfVarInt(I n)
template<typename I>
inline void WriteVarInt(CSizeComputer& os, I n);
-template<typename Stream, typename I>
+template<typename Stream, VarIntMode Mode, typename I>
void WriteVarInt(Stream& os, I n)
{
+ CheckVarIntMode<Mode, I>();
unsigned char tmp[(sizeof(n)*8+6)/7];
int len=0;
while(true) {
@@ -330,9 +362,10 @@ void WriteVarInt(Stream& os, I n)
} while(len--);
}
-template<typename Stream, typename I>
+template<typename Stream, VarIntMode Mode, typename I>
I ReadVarInt(Stream& is)
{
+ CheckVarIntMode<Mode, I>();
I n = 0;
while(true) {
unsigned char chData = ser_readdata8(is);
@@ -351,10 +384,10 @@ I ReadVarInt(Stream& is)
}
}
-#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
-#define VARINT(obj) REF(WrapVarInt(REF(obj)))
-#define COMPACTSIZE(obj) REF(CCompactSize(REF(obj)))
-#define LIMITED_STRING(obj,n) REF(LimitedString< n >(REF(obj)))
+#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.
@@ -396,7 +429,7 @@ public:
}
};
-template<typename I>
+template<VarIntMode Mode, typename I>
class CVarInt
{
protected:
@@ -406,12 +439,12 @@ public:
template<typename Stream>
void Serialize(Stream &s) const {
- WriteVarInt<Stream,I>(s, n);
+ WriteVarInt<Stream,Mode,I>(s, n);
}
template<typename Stream>
void Unserialize(Stream& s) {
- n = ReadVarInt<Stream,I>(s);
+ n = ReadVarInt<Stream,Mode,I>(s);
}
};
@@ -462,8 +495,8 @@ public:
}
};
-template<typename I>
-CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
+template<VarIntMode Mode=VarIntMode::DEFAULT, typename I>
+CVarInt<Mode, I> WrapVarInt(I& n) { return CVarInt<Mode, I>{n}; }
/**
* Forward declarations
@@ -539,7 +572,7 @@ inline void Serialize(Stream& os, const T& a)
}
template<typename Stream, typename T>
-inline void Unserialize(Stream& is, T& a)
+inline void Unserialize(Stream& is, T&& a)
{
a.Unserialize(is);
}
@@ -825,19 +858,6 @@ struct CSerActionUnserialize
constexpr bool ForRead() const { return true; }
};
-template<typename Stream, typename T>
-inline void SerReadWrite(Stream& s, const T& obj, CSerActionSerialize ser_action)
-{
- ::Serialize(s, obj);
-}
-
-template<typename Stream, typename T>
-inline void SerReadWrite(Stream& s, T& obj, CSerActionUnserialize ser_action)
-{
- ::Unserialize(s, obj);
-}
-
-
@@ -897,17 +917,11 @@ void SerializeMany(Stream& s)
{
}
-template<typename Stream, typename Arg>
-void SerializeMany(Stream& s, Arg&& arg)
-{
- ::Serialize(s, std::forward<Arg>(arg));
-}
-
template<typename Stream, typename Arg, typename... Args>
-void SerializeMany(Stream& s, Arg&& arg, Args&&... args)
+void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
{
- ::Serialize(s, std::forward<Arg>(arg));
- ::SerializeMany(s, std::forward<Args>(args)...);
+ ::Serialize(s, arg);
+ ::SerializeMany(s, args...);
}
template<typename Stream>
@@ -915,27 +929,21 @@ inline void UnserializeMany(Stream& s)
{
}
-template<typename Stream, typename Arg>
-inline void UnserializeMany(Stream& s, Arg& arg)
-{
- ::Unserialize(s, arg);
-}
-
template<typename Stream, typename Arg, typename... Args>
-inline void UnserializeMany(Stream& s, Arg& arg, Args&... args)
+inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
{
::Unserialize(s, arg);
::UnserializeMany(s, args...);
}
template<typename Stream, typename... Args>
-inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, Args&&... args)
+inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
{
- ::SerializeMany(s, std::forward<Args>(args)...);
+ ::SerializeMany(s, args...);
}
template<typename Stream, typename... Args>
-inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&... args)
+inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
{
::UnserializeMany(s, args...);
}
diff --git a/src/streams.h b/src/streams.h
index 9f86c4a163..6ba4f103da 100644
--- a/src/streams.h
+++ b/src/streams.h
@@ -42,7 +42,7 @@ public:
}
template<typename T>
- OverrideStream<Stream>& operator>>(T& obj)
+ OverrideStream<Stream>& operator>>(T&& obj)
{
// Unserialize from this stream
::Unserialize(*this, obj);
@@ -399,7 +399,7 @@ public:
}
template<typename T>
- CDataStream& operator>>(T& obj)
+ CDataStream& operator>>(T&& obj)
{
// Unserialize from this stream
::Unserialize(*this, obj);
@@ -543,7 +543,7 @@ public:
}
template<typename T>
- CAutoFile& operator>>(T& obj)
+ CAutoFile& operator>>(T&& obj)
{
// Unserialize from this stream
if (!file)
@@ -686,7 +686,7 @@ public:
}
template<typename T>
- CBufferedFile& operator>>(T& obj) {
+ CBufferedFile& operator>>(T&& obj) {
// Unserialize from this stream
::Unserialize(*this, obj);
return (*this);
diff --git a/src/support/lockedpool.cpp b/src/support/lockedpool.cpp
index d92ab02d6b..51c337ed2f 100644
--- a/src/support/lockedpool.cpp
+++ b/src/support/lockedpool.cpp
@@ -27,6 +27,7 @@
#endif
#include <algorithm>
+#include <memory>
LockedPoolManager* LockedPoolManager::_instance = nullptr;
std::once_flag LockedPoolManager::init_flag;
@@ -47,7 +48,9 @@ Arena::Arena(void *base_in, size_t size_in, size_t alignment_in):
base(static_cast<char*>(base_in)), end(static_cast<char*>(base_in) + size_in), alignment(alignment_in)
{
// Start with one free chunk that covers the entire arena
- chunks_free.emplace(base, size_in);
+ auto it = size_to_free_chunk.emplace(size_in, base);
+ chunks_free.emplace(base, it);
+ chunks_free_end.emplace(base + size_in, it);
}
Arena::~Arena()
@@ -63,26 +66,30 @@ void* Arena::alloc(size_t size)
if (size == 0)
return nullptr;
- // Pick a large enough free-chunk
- auto it = std::find_if(chunks_free.begin(), chunks_free.end(),
- [=](const std::map<char*, size_t>::value_type& chunk){ return chunk.second >= size; });
- if (it == chunks_free.end())
+ // Pick a large enough free-chunk. Returns an iterator pointing to the first element that is not less than key.
+ // This allocation strategy is best-fit. According to "Dynamic Storage Allocation: A Survey and Critical Review",
+ // Wilson et. al. 1995, http://www.scs.stanford.edu/14wi-cs140/sched/readings/wilson.pdf, best-fit and first-fit
+ // policies seem to work well in practice.
+ auto size_ptr_it = size_to_free_chunk.lower_bound(size);
+ if (size_ptr_it == size_to_free_chunk.end())
return nullptr;
// Create the used-chunk, taking its space from the end of the free-chunk
- auto alloced = chunks_used.emplace(it->first + it->second - size, size).first;
- if (!(it->second -= size))
- chunks_free.erase(it);
- return reinterpret_cast<void*>(alloced->first);
-}
-
-/* extend the Iterator if other begins at its end */
-template <class Iterator, class Pair> bool extend(Iterator it, const Pair& other) {
- if (it->first + it->second == other.first) {
- it->second += other.second;
- return true;
+ const size_t size_remaining = size_ptr_it->first - size;
+ auto alloced = chunks_used.emplace(size_ptr_it->second + size_remaining, size).first;
+ chunks_free_end.erase(size_ptr_it->second + size_ptr_it->first);
+ if (size_ptr_it->first == size) {
+ // whole chunk is used up
+ chunks_free.erase(size_ptr_it->second);
+ } else {
+ // still some memory left in the chunk
+ auto it_remaining = size_to_free_chunk.emplace(size_remaining, size_ptr_it->second);
+ chunks_free[size_ptr_it->second] = it_remaining;
+ chunks_free_end.emplace(size_ptr_it->second + size_remaining, it_remaining);
}
- return false;
+ size_to_free_chunk.erase(size_ptr_it);
+
+ return reinterpret_cast<void*>(alloced->first);
}
void Arena::free(void *ptr)
@@ -97,16 +104,30 @@ void Arena::free(void *ptr)
if (i == chunks_used.end()) {
throw std::runtime_error("Arena: invalid or double free");
}
- auto freed = *i;
+ std::pair<char*, size_t> freed = *i;
chunks_used.erase(i);
- // Add space to free map, coalescing contiguous chunks
- auto next = chunks_free.upper_bound(freed.first);
- auto prev = (next == chunks_free.begin()) ? chunks_free.end() : std::prev(next);
- if (prev == chunks_free.end() || !extend(prev, freed))
- prev = chunks_free.emplace_hint(next, freed);
- if (next != chunks_free.end() && extend(prev, *next))
+ // coalesce freed with previous chunk
+ auto prev = chunks_free_end.find(freed.first);
+ if (prev != chunks_free_end.end()) {
+ freed.first -= prev->second->first;
+ freed.second += prev->second->first;
+ size_to_free_chunk.erase(prev->second);
+ chunks_free_end.erase(prev);
+ }
+
+ // coalesce freed with chunk after freed
+ auto next = chunks_free.find(freed.first + freed.second);
+ if (next != chunks_free.end()) {
+ freed.second += next->second->first;
+ size_to_free_chunk.erase(next->second);
chunks_free.erase(next);
+ }
+
+ // Add/set space with coalesced free chunk
+ auto it = size_to_free_chunk.emplace(freed.second, freed.first);
+ chunks_free[freed.first] = it;
+ chunks_free_end[freed.first + freed.second] = it;
}
Arena::Stats Arena::stats() const
@@ -115,7 +136,7 @@ Arena::Stats Arena::stats() const
for (const auto& chunk: chunks_used)
r.used += chunk.second;
for (const auto& chunk: chunks_free)
- r.free += chunk.second;
+ r.free += chunk.second->first;
r.total = r.used + r.free;
return r;
}
@@ -184,7 +205,7 @@ void Win32LockedPageAllocator::FreeLocked(void* addr, size_t len)
size_t Win32LockedPageAllocator::GetLimit()
{
- // TODO is there a limit on windows, how to get it?
+ // TODO is there a limit on Windows, how to get it?
return std::numeric_limits<size_t>::max();
}
#endif
diff --git a/src/support/lockedpool.h b/src/support/lockedpool.h
index fc85e6c73c..ccfae16701 100644
--- a/src/support/lockedpool.h
+++ b/src/support/lockedpool.h
@@ -10,6 +10,7 @@
#include <map>
#include <mutex>
#include <memory>
+#include <unordered_map>
/**
* OS-dependent allocation and deallocation of locked/pinned memory pages.
@@ -88,11 +89,19 @@ public:
*/
bool addressInArena(void *ptr) const { return ptr >= base && ptr < end; }
private:
- /** Map of chunk address to chunk information. This class makes use of the
- * sorted order to merge previous and next chunks during deallocation.
- */
- std::map<char*, size_t> chunks_free;
- std::map<char*, size_t> chunks_used;
+ typedef std::multimap<size_t, char*> SizeToChunkSortedMap;
+ /** Map to enable O(log(n)) best-fit allocation, as it's sorted by size */
+ SizeToChunkSortedMap size_to_free_chunk;
+
+ typedef std::unordered_map<char*, SizeToChunkSortedMap::const_iterator> ChunkToSizeMap;
+ /** Map from begin of free chunk to its node in size_to_free_chunk */
+ ChunkToSizeMap chunks_free;
+ /** Map from end of free chunk to its node in size_to_free_chunk */
+ ChunkToSizeMap chunks_free_end;
+
+ /** Map from begin of used chunk to its size */
+ std::unordered_map<char*, size_t> chunks_used;
+
/** Base address of arena */
char* base;
/** End address of arena */
diff --git a/src/sync.cpp b/src/sync.cpp
index bf3d131e4e..fdf7c44e4c 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -4,6 +4,7 @@
#include <sync.h>
+#include <memory>
#include <set>
#include <util.h>
#include <utilstrencodings.h>
diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp
index 0d8bd90119..6b188a06b4 100644
--- a/src/test/addrman_tests.cpp
+++ b/src/test/addrman_tests.cpp
@@ -491,7 +491,7 @@ BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
// this test could be a security issue.
BOOST_CHECK(info1.GetNewBucket(nKey1) != info1.GetNewBucket(nKey2));
- // Test: Ports should not effect bucket placement in the addr
+ // Test: Ports should not affect bucket placement in the addr
CAddrInfo info2 = CAddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK_EQUAL(info1.GetNewBucket(nKey1), info2.GetNewBucket(nKey1));
diff --git a/src/test/allocator_tests.cpp b/src/test/allocator_tests.cpp
index c177f0bf00..24cd88c7a7 100644
--- a/src/test/allocator_tests.cpp
+++ b/src/test/allocator_tests.cpp
@@ -7,6 +7,8 @@
#include <support/allocators/secure.h>
#include <test/test_bitcoin.h>
+#include <memory>
+
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup)
diff --git a/src/test/blockchain_tests.cpp b/src/test/blockchain_tests.cpp
index 55fdd2c071..32b408838c 100644
--- a/src/test/blockchain_tests.cpp
+++ b/src/test/blockchain_tests.cpp
@@ -54,7 +54,7 @@ void TestDifficulty(uint32_t nbits, double expected_difficulty)
RejectDifficultyMismatch(difficulty, expected_difficulty);
}
-BOOST_FIXTURE_TEST_SUITE(blockchain_difficulty_tests, BasicTestingSetup)
+BOOST_FIXTURE_TEST_SUITE(blockchain_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(get_difficulty_for_very_low_target)
{
diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
index 36e271295a..de7d8f7b90 100644
--- a/src/test/coins_tests.cpp
+++ b/src/test/coins_tests.cpp
@@ -313,7 +313,7 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
auto utxod = FindRandomFrom(coinbase_coins);
// Reuse the exact same coinbase
tx = std::get<0>(utxod->second);
- // shouldn't be available for reconnection if its been duplicated
+ // shouldn't be available for reconnection if it's been duplicated
disconnected_coins.erase(utxod->first);
duplicate_coins.insert(utxod->first);
diff --git a/src/test/compress_tests.cpp b/src/test/compress_tests.cpp
index 3c26013622..127cc154df 100644
--- a/src/test/compress_tests.cpp
+++ b/src/test/compress_tests.cpp
@@ -25,16 +25,16 @@
BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)
bool static TestEncode(uint64_t in) {
- return in == CTxOutCompressor::DecompressAmount(CTxOutCompressor::CompressAmount(in));
+ return in == DecompressAmount(CompressAmount(in));
}
bool static TestDecode(uint64_t in) {
- return in == CTxOutCompressor::CompressAmount(CTxOutCompressor::DecompressAmount(in));
+ return in == CompressAmount(DecompressAmount(in));
}
bool static TestPair(uint64_t dec, uint64_t enc) {
- return CTxOutCompressor::CompressAmount(dec) == enc &&
- CTxOutCompressor::DecompressAmount(enc) == dec;
+ return CompressAmount(dec) == enc &&
+ DecompressAmount(enc) == dec;
}
BOOST_AUTO_TEST_CASE(compress_amounts)
diff --git a/src/test/cuckoocache_tests.cpp b/src/test/cuckoocache_tests.cpp
index 51ebfc3800..ccd5caacd5 100644
--- a/src/test/cuckoocache_tests.cpp
+++ b/src/test/cuckoocache_tests.cpp
@@ -163,7 +163,7 @@ void test_cache_erase(size_t megabytes)
for (uint32_t i = (n_insert / 2); i < n_insert; ++i)
set.insert(hashes_insert_copy[i]);
- /** elements that we marked erased but that are still there */
+ /** elements that we marked as erased but are still there */
size_t count_erased_but_contained = 0;
/** elements that we did not erase but are older */
size_t count_stale = 0;
@@ -303,7 +303,7 @@ void test_cache_generations()
local_rand_ctx = FastRandomContext(true);
// block_activity models a chunk of network activity. n_insert elements are
- // adde to the cache. The first and last n/4 are stored for removal later
+ // added to the cache. The first and last n/4 are stored for removal later
// and the middle n/2 are not stored. This models a network which uses half
// the signatures of recently (since the last block) added transactions
// immediately and never uses the other half.
diff --git a/src/test/data/base58_encode_decode.json b/src/test/data/base58_encode_decode.json
index 9448f256d9..1a4bd7f458 100644
--- a/src/test/data/base58_encode_decode.json
+++ b/src/test/data/base58_encode_decode.json
@@ -10,5 +10,7 @@
["572e4794", "3EFU7m"],
["ecac89cad93923c02321", "EJDM8drfXA6uyA"],
["10c8511e", "Rt5zm"],
-["00000000000000000000", "1111111111"]
+["00000000000000000000", "1111111111"],
+["000111d38e5fc9071ffcd20b4a763cc9ae4f252bb4e48fd66a835e252ada93ff480d6dd43dc62a641155a5", "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],
+["000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", "1cWB5HCBdLjAuqGGReWE3R3CguuwSjw6RHn39s2yuDRTS5NsBgNiFpWgAnEx6VQi8csexkgYw3mdYrMHr8x9i7aEwP8kZ7vccXWqKDvGv3u1GxFKPuAkn8JCPPGDMf3vMMnbzm6Nh9zh1gcNsMvH3ZNLmP5fSG6DGbbi2tuwMWPthr4boWwCxf7ewSgNQeacyozhKDDQQ1qL5fQFUW52QKUZDZ5fw3KXNQJMcNTcaB723LchjeKun7MuGW5qyCBZYzA1KjofN1gYBV3NqyhQJ3Ns746GNuf9N2pQPmHz4xpnSrrfCvy6TVVz5d4PdrjeshsWQwpZsZGzvbdAdN8MKV5QsBDY"]
]
diff --git a/src/test/data/script_tests.json b/src/test/data/script_tests.json
index ccefe52246..97edc98bf6 100644
--- a/src/test/data/script_tests.json
+++ b/src/test/data/script_tests.json
@@ -2553,22 +2553,22 @@
[["01", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "OK"],
[["02", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "OK"],
[["0100", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "OK"],
-[["", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "EVAL_FALSE"],
-[["00", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "EVAL_FALSE"],
+[["", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "CLEANSTACK"],
+[["00", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "CLEANSTACK"],
[["01", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "OK"],
[["02", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
-[["", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
+[["", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "CLEANSTACK"],
[["00", "635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS", "UNBALANCED_CONDITIONAL"],
[["635168", 0.00000001], "", "0 0x20 0xc7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["P2WSH NOTIF 1 ENDIF"],
-[["01", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "EVAL_FALSE"],
-[["02", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "EVAL_FALSE"],
-[["0100", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "EVAL_FALSE"],
+[["01", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "CLEANSTACK"],
+[["02", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "CLEANSTACK"],
+[["0100", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "CLEANSTACK"],
[["", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "OK"],
[["00", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS", "OK"],
-[["01", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
+[["01", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "CLEANSTACK"],
[["02", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["", "645168", 0.00000001], "", "0 0x20 0xf913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "P2SH,WITNESS,MINIMALIF", "OK"],
@@ -2582,22 +2582,22 @@
[["01", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "OK"],
[["02", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "OK"],
[["0100", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "OK"],
-[["", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
-[["00", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
+[["", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "CLEANSTACK"],
+[["00", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "CLEANSTACK"],
[["01", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
[["02", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
-[["", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
+[["", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "CLEANSTACK"],
[["00", "635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS", "UNBALANCED_CONDITIONAL"],
[["635168", 0.00000001], "0x22 0x0020c7eaf06d5ae01a58e376e126eb1e6fab2036076922b96b2711ffbec1e590665d", "HASH160 0x14 0x9b27ee6d9010c21bf837b334d043be5d150e7ba7 EQUAL", "P2SH,WITNESS,MINIMALIF", "UNBALANCED_CONDITIONAL"],
["P2SH-P2WSH NOTIF 1 ENDIF"],
-[["01", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
-[["02", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
-[["0100", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "EVAL_FALSE"],
+[["01", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "CLEANSTACK"],
+[["02", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "CLEANSTACK"],
+[["0100", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "CLEANSTACK"],
[["", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "OK"],
[["00", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS", "OK"],
-[["01", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "EVAL_FALSE"],
+[["01", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "CLEANSTACK"],
[["02", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["0100", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "MINIMALIF"],
[["", "645168", 0.00000001], "0x22 0x0020f913eacf2e38a5d6fc3a8311d72ae704cb83866350a984dd3e5eb76d2a8c28e8", "HASH160 0x14 0xdbb7d1c0a56b7a9c423300c8cca6e6e065baf1dc EQUAL", "P2SH,WITNESS,MINIMALIF", "OK"],
diff --git a/src/test/data/tx_invalid.json b/src/test/data/tx_invalid.json
index f8a1347c31..abb46fe533 100644
--- a/src/test/data/tx_invalid.json
+++ b/src/test/data/tx_invalid.json
@@ -321,7 +321,7 @@
["where the pubkey is obtained through key recovery with sig and the wrong sighash."],
["This is to show that FindAndDelete is applied only to non-segwit scripts"],
["To show that the tests are 'correctly wrong', they should pass by modifying OP_CHECKSIG under interpreter.cpp"],
-["by replacing (sigversion == SIGVERSION_BASE) with (sigversion != SIGVERSION_BASE)"],
+["by replacing (sigversion == SigVersion::BASE) with (sigversion != SigVersion::BASE)"],
["Non-segwit: wrong sighash (without FindAndDelete) = 1ba1fe3bc90c5d1265460e684ce6774e324f0fabdf67619eda729e64e8b6bc08"],
[[["f18783ace138abac5d3a7a5cf08e88fe6912f267ef936452e0c27d090621c169", 7000, "HASH160 0x14 0x0c746489e2d83cdbb5b90b432773342ba809c134 EQUAL", 200000]],
"010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f1581b0000b64830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012103b12a1ec8428fc74166926318c15e17408fea82dbb157575e16a8c365f546248f4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01ffffffff0101000000000000000000000000", "P2SH,WITNESS"],
@@ -332,7 +332,7 @@
["Script is 2 CHECKMULTISIGVERIFY <sig1> <sig2> DROP"],
["52af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175"],
["Signature is 0 <sig1> <sig2> 2 <key1> <key2>"],
-["Should pass by replacing (sigversion == SIGVERSION_BASE) with (sigversion != SIGVERSION_BASE) under OP_CHECKMULTISIG"],
+["Should pass by replacing (sigversion == SigVersion::BASE) with (sigversion != SigVersion::BASE) under OP_CHECKMULTISIG"],
["Non-segwit: wrong sighash (without FindAndDelete) = 4bc6a53e8e16ef508c19e38bba08831daba85228b0211f323d4cb0999cf2a5e8"],
[[["9628667ad48219a169b41b020800162287d2c0f713c04157e95c484a8dcb7592", 7000, "HASH160 0x14 0x5748407f5ca5cdca53ba30b79040260770c9ee1b EQUAL", 200000]],
"01000000019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a662896581b0000fd6f01004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c039596015221023fd5dd42b44769c5653cbc5947ff30ab8871f240ad0c0e7432aefe84b5b4ff3421039d52178dbde360b83f19cf348deb04fa8360e1bf5634577be8e50fafc2b0e4ef4c9552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175ffffffff0101000000000000000000000000", "P2SH,WITNESS"],
diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp
index 754a86344f..35f0463e3e 100644
--- a/src/test/dbwrapper_tests.cpp
+++ b/src/test/dbwrapper_tests.cpp
@@ -7,6 +7,8 @@
#include <random.h>
#include <test/test_bitcoin.h>
+#include <memory>
+
#include <boost/test/unit_test.hpp>
// Test if a string consists entirely of null characters
@@ -237,7 +239,7 @@ BOOST_AUTO_TEST_CASE(iterator_ordering)
}
struct StringContentsSerializer {
- // Used to make two serialized objects the same while letting them have a different lengths
+ // Used to make two serialized objects the same while letting them have different lengths
// This is a terrible idea
std::string str;
StringContentsSerializer() {}
diff --git a/src/test/mempool_tests.cpp b/src/test/mempool_tests.cpp
index 1766c6a093..19cd3b0963 100644
--- a/src/test/mempool_tests.cpp
+++ b/src/test/mempool_tests.cpp
@@ -523,7 +523,7 @@ BOOST_AUTO_TEST_CASE(MempoolSizeLimitTest)
pool.addUnchecked(tx6.GetHash(), entry.Fee(1100LL).FromTx(tx6));
pool.addUnchecked(tx7.GetHash(), entry.Fee(9000LL).FromTx(tx7));
- // we only require this remove, at max, 2 txn, because its not clear what we're really optimizing for aside from that
+ // we only require this to remove, at max, 2 txn, because it's not clear what we're really optimizing for aside from that
pool.TrimToSize(pool.DynamicMemoryUsage() - 1);
BOOST_CHECK(pool.exists(tx4.GetHash()));
BOOST_CHECK(pool.exists(tx6.GetHash()));
diff --git a/src/test/multisig_tests.cpp b/src/test/multisig_tests.cpp
index 72d9d3d75c..b593f9633c 100644
--- a/src/test/multisig_tests.cpp
+++ b/src/test/multisig_tests.cpp
@@ -21,7 +21,7 @@ BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup)
CScript
sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction, int whichIn)
{
- uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL, 0, SigVersion::BASE);
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index e03234060d..436ae696d1 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -13,6 +13,8 @@
#include <chainparams.h>
#include <util.h>
+#include <memory>
+
class CAddrManSerializationMock : public CAddrMan
{
public:
@@ -64,7 +66,7 @@ public:
CDataStream AddrmanToStream(CAddrManSerializationMock& _addrman)
{
CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);
- ssPeersIn << FLATDATA(Params().MessageStart());
+ ssPeersIn << Params().MessageStart();
ssPeersIn << _addrman;
std::string str = ssPeersIn.str();
std::vector<unsigned char> vchData(str.begin(), str.end());
@@ -110,7 +112,7 @@ BOOST_AUTO_TEST_CASE(caddrdb_read)
BOOST_CHECK(addrman1.size() == 0);
try {
unsigned char pchMsgTmp[4];
- ssPeers1 >> FLATDATA(pchMsgTmp);
+ ssPeers1 >> pchMsgTmp;
ssPeers1 >> addrman1;
} catch (const std::exception& e) {
exceptionThrown = true;
@@ -142,7 +144,7 @@ BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)
BOOST_CHECK(addrman1.size() == 0);
try {
unsigned char pchMsgTmp[4];
- ssPeers1 >> FLATDATA(pchMsgTmp);
+ ssPeers1 >> pchMsgTmp;
ssPeers1 >> addrman1;
} catch (const std::exception& e) {
exceptionThrown = true;
diff --git a/src/test/prevector_tests.cpp b/src/test/prevector_tests.cpp
index 01c3a6cedd..fe6f10d845 100644
--- a/src/test/prevector_tests.cpp
+++ b/src/test/prevector_tests.cpp
@@ -13,7 +13,7 @@
#include <boost/test/unit_test.hpp>
-BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)
+BOOST_FIXTURE_TEST_SUITE(prevector_tests, TestingSetup)
template<unsigned int N, typename T>
class prevector_tester {
diff --git a/src/test/random_tests.cpp b/src/test/random_tests.cpp
index 1ca5a53d72..623ed239f0 100644
--- a/src/test/random_tests.cpp
+++ b/src/test/random_tests.cpp
@@ -8,6 +8,9 @@
#include <boost/test/unit_test.hpp>
+#include <random>
+#include <algorithm>
+
BOOST_FIXTURE_TEST_SUITE(random_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(osrandom_tests)
@@ -57,4 +60,23 @@ BOOST_AUTO_TEST_CASE(fastrandom_randbits)
}
}
+/** Does-it-compile test for compatibility with standard C++11 RNG interface. */
+BOOST_AUTO_TEST_CASE(stdrandom_test)
+{
+ FastRandomContext ctx;
+ std::uniform_int_distribution<int> distribution(3, 9);
+ for (int i = 0; i < 100; ++i) {
+ int x = distribution(ctx);
+ BOOST_CHECK(x >= 3);
+ BOOST_CHECK(x <= 9);
+
+ std::vector<int> test{1,2,3,4,5,6,7,8,9,10};
+ std::shuffle(test.begin(), test.end(), ctx);
+ for (int j = 1; j <= 10; ++j) {
+ BOOST_CHECK(std::find(test.begin(), test.end(), j) != test.end());
+ }
+ }
+
+}
+
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/rpc_tests.cpp b/src/test/rpc_tests.cpp
index 892e4f2dac..8d9f80ada0 100644
--- a/src/test/rpc_tests.cpp
+++ b/src/test/rpc_tests.cpp
@@ -52,7 +52,6 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams)
BOOST_CHECK_THROW(CallRPC("createrawtransaction"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), std::runtime_error);
- BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), std::runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}"));
BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), std::runtime_error);
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index c7a497f3a7..46a2d13745 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -267,10 +267,10 @@ struct KeyData
}
};
-enum WitnessMode {
- WITNESS_NONE,
- WITNESS_PKH,
- WITNESS_SH
+enum class WitnessMode {
+ NONE,
+ PKH,
+ SH
};
class TestBuilder
@@ -308,15 +308,15 @@ private:
}
public:
- TestBuilder(const CScript& script_, const std::string& comment_, int flags_, bool P2SH = false, WitnessMode wm = WITNESS_NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), havePush(false), comment(comment_), flags(flags_), scriptError(SCRIPT_ERR_OK), nValue(nValue_)
+ TestBuilder(const CScript& script_, const std::string& comment_, int flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), havePush(false), comment(comment_), flags(flags_), scriptError(SCRIPT_ERR_OK), nValue(nValue_)
{
CScript scriptPubKey = script;
- if (wm == WITNESS_PKH) {
+ if (wm == WitnessMode::PKH) {
uint160 hash;
CHash160().Write(&script[1], script.size() - 1).Finalize(hash.begin());
script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(hash) << OP_EQUALVERIFY << OP_CHECKSIG;
scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
- } else if (wm == WITNESS_SH) {
+ } else if (wm == WitnessMode::SH) {
witscript = scriptPubKey;
uint256 hash;
CSHA256().Write(&witscript[0], witscript.size()).Finalize(hash.begin());
@@ -361,7 +361,7 @@ public:
return *this;
}
- TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SIGVERSION_BASE, CAmount amount = 0)
+ TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::BASE, CAmount amount = 0)
{
uint256 hash = SignatureHash(script, spendTx, 0, nHashType, amount, sigversion);
std::vector<unsigned char> vchSig, r, s;
@@ -379,7 +379,7 @@ public:
return *this;
}
- TestBuilder& PushWitSig(const CKey& key, CAmount amount = -1, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SIGVERSION_WITNESS_V0)
+ TestBuilder& PushWitSig(const CKey& key, CAmount amount = -1, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::WITNESS_V0)
{
if (amount == -1)
amount = nValue;
@@ -747,57 +747,57 @@ BOOST_AUTO_TEST_CASE(script_build)
).PushSig(keys.key0).PushRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH,
+ "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
0, 1).PushWitSig(keys.key0).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH,
+ "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH,
+ "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH,
+ "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
- "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH
+ "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
- "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH
+ "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
- "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH
+ "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
- "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH
+ "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
- "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WITNESS_SH
+ "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
).PushWitSig(keys.key0).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
- "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WITNESS_PKH
+ "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
- "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WITNESS_SH
+ "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
- "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WITNESS_PKH
+ "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH,
+ "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH,
+ "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH,
+ "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH,
+ "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
"P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH |
- SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WITNESS_PKH, 1
+ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WitnessMode::PKH, 1
).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM));
{
CScript witscript = CScript() << ToByteVector(keys.pubkey0);
@@ -810,22 +810,22 @@ BOOST_AUTO_TEST_CASE(script_build)
).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH));
}
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH
+ "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
).ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY));
{
CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG;
tests.push_back(TestBuilder(witscript,
- "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH
+ "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
}
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH
+ "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH
+ "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
- "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH
+ "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
"P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH
@@ -833,95 +833,95 @@ BOOST_AUTO_TEST_CASE(script_build)
// Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
- "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).PushWitSig(keys.key0C).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
- "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_PKH,
+ "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
- "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
- "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_PKH,
+ "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem());
// Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_PKH,
+ "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
- "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
- "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_PKH,
+ "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
// P2WSH 1-of-2 multisig with compressed keys
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
// P2WSH 1-of-2 multisig with first key uncompressed
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
// P2WSH 1-of-2 multisig with second key uncompressed
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem());
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH,
+ "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
- "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH,
+ "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
std::set<std::string> tests_set;
@@ -1009,21 +1009,21 @@ BOOST_AUTO_TEST_CASE(script_PushData)
ScriptError err;
std::vector<std::vector<unsigned char> > directStack;
- BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
+ BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
std::vector<std::vector<unsigned char> > pushdata1Stack;
- BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
+ BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
BOOST_CHECK(pushdata1Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
std::vector<std::vector<unsigned char> > pushdata2Stack;
- BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
+ BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
BOOST_CHECK(pushdata2Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
std::vector<std::vector<unsigned char> > pushdata4Stack;
- BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err));
+ BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
BOOST_CHECK(pushdata4Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
@@ -1031,7 +1031,7 @@ BOOST_AUTO_TEST_CASE(script_PushData)
CScript
sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction)
{
- uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SigVersion::BASE);
CScript result;
//
@@ -1227,15 +1227,15 @@ BOOST_AUTO_TEST_CASE(script_combineSigs)
// A couple of partially-signed versions:
std::vector<unsigned char> sig1;
- uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SigVersion::BASE);
BOOST_CHECK(keys[0].Sign(hash1, sig1));
sig1.push_back(SIGHASH_ALL);
std::vector<unsigned char> sig2;
- uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SIGVERSION_BASE);
+ uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SigVersion::BASE);
BOOST_CHECK(keys[1].Sign(hash2, sig2));
sig2.push_back(SIGHASH_NONE);
std::vector<unsigned char> sig3;
- uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SIGVERSION_BASE);
+ uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SigVersion::BASE);
BOOST_CHECK(keys[2].Sign(hash3, sig3));
sig3.push_back(SIGHASH_SINGLE);
diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp
index 4595519435..9b8b7bdc56 100644
--- a/src/test/serialize_tests.cpp
+++ b/src/test/serialize_tests.cpp
@@ -19,11 +19,15 @@ protected:
int intval;
bool boolval;
std::string stringval;
- const char* charstrval;
+ char charstrval[16];
CTransactionRef txval;
public:
CSerializeMethodsTestSingle() = default;
- CSerializeMethodsTestSingle(int intvalin, bool boolvalin, std::string stringvalin, const char* charstrvalin, CTransaction txvalin) : intval(intvalin), boolval(boolvalin), stringval(std::move(stringvalin)), charstrval(charstrvalin), txval(MakeTransactionRef(txvalin)){}
+ CSerializeMethodsTestSingle(int intvalin, bool boolvalin, std::string stringvalin, const char* charstrvalin, CTransaction txvalin) : intval(intvalin), boolval(boolvalin), stringval(std::move(stringvalin)), txval(MakeTransactionRef(txvalin))
+ {
+ memcpy(charstrval, charstrvalin, sizeof(charstrval));
+ }
+
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
@@ -31,7 +35,7 @@ public:
READWRITE(intval);
READWRITE(boolval);
READWRITE(stringval);
- READWRITE(FLATDATA(charstrval));
+ READWRITE(charstrval);
READWRITE(txval);
}
@@ -53,7 +57,7 @@ public:
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
- READWRITEMANY(intval, boolval, stringval, FLATDATA(charstrval), txval);
+ READWRITE(intval, boolval, stringval, charstrval, txval);
}
};
@@ -177,8 +181,8 @@ BOOST_AUTO_TEST_CASE(varints)
CDataStream ss(SER_DISK, 0);
CDataStream::size_type size = 0;
for (int i = 0; i < 100000; i++) {
- ss << VARINT(i);
- size += ::GetSerializeSize(VARINT(i), 0, 0);
+ ss << VARINT(i, VarIntMode::NONNEGATIVE_SIGNED);
+ size += ::GetSerializeSize(VARINT(i, VarIntMode::NONNEGATIVE_SIGNED), 0, 0);
BOOST_CHECK(size == ss.size());
}
@@ -191,7 +195,7 @@ BOOST_AUTO_TEST_CASE(varints)
// decode
for (int i = 0; i < 100000; i++) {
int j = -1;
- ss >> VARINT(j);
+ ss >> VARINT(j, VarIntMode::NONNEGATIVE_SIGNED);
BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
}
@@ -205,21 +209,21 @@ BOOST_AUTO_TEST_CASE(varints)
BOOST_AUTO_TEST_CASE(varints_bitpatterns)
{
CDataStream ss(SER_DISK, 0);
- ss << VARINT(0); BOOST_CHECK_EQUAL(HexStr(ss), "00"); ss.clear();
- ss << VARINT(0x7f); BOOST_CHECK_EQUAL(HexStr(ss), "7f"); ss.clear();
- ss << VARINT((int8_t)0x7f); BOOST_CHECK_EQUAL(HexStr(ss), "7f"); ss.clear();
- ss << VARINT(0x80); BOOST_CHECK_EQUAL(HexStr(ss), "8000"); ss.clear();
+ ss << VARINT(0, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "00"); ss.clear();
+ ss << VARINT(0x7f, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "7f"); ss.clear();
+ ss << VARINT((int8_t)0x7f, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "7f"); ss.clear();
+ ss << VARINT(0x80, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "8000"); ss.clear();
ss << VARINT((uint8_t)0x80); BOOST_CHECK_EQUAL(HexStr(ss), "8000"); ss.clear();
- ss << VARINT(0x1234); BOOST_CHECK_EQUAL(HexStr(ss), "a334"); ss.clear();
- ss << VARINT((int16_t)0x1234); BOOST_CHECK_EQUAL(HexStr(ss), "a334"); ss.clear();
- ss << VARINT(0xffff); BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f"); ss.clear();
+ ss << VARINT(0x1234, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "a334"); ss.clear();
+ ss << VARINT((int16_t)0x1234, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "a334"); ss.clear();
+ ss << VARINT(0xffff, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f"); ss.clear();
ss << VARINT((uint16_t)0xffff); BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f"); ss.clear();
- ss << VARINT(0x123456); BOOST_CHECK_EQUAL(HexStr(ss), "c7e756"); ss.clear();
- ss << VARINT((int32_t)0x123456); BOOST_CHECK_EQUAL(HexStr(ss), "c7e756"); ss.clear();
+ ss << VARINT(0x123456, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "c7e756"); ss.clear();
+ ss << VARINT((int32_t)0x123456, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "c7e756"); ss.clear();
ss << VARINT(0x80123456U); BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756"); ss.clear();
ss << VARINT((uint32_t)0x80123456U); BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756"); ss.clear();
ss << VARINT(0xffffffff); BOOST_CHECK_EQUAL(HexStr(ss), "8efefefe7f"); ss.clear();
- ss << VARINT(0x7fffffffffffffffLL); BOOST_CHECK_EQUAL(HexStr(ss), "fefefefefefefefe7f"); ss.clear();
+ ss << VARINT(0x7fffffffffffffffLL, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "fefefefefefefefe7f"); ss.clear();
ss << VARINT(0xffffffffffffffffULL); BOOST_CHECK_EQUAL(HexStr(ss), "80fefefefefefefefe7f"); ss.clear();
}
@@ -344,7 +348,7 @@ BOOST_AUTO_TEST_CASE(class_methods)
int intval(100);
bool boolval(true);
std::string stringval("testing");
- const char* charstrval("testing charstr");
+ const char charstrval[16] = "testing charstr";
CMutableTransaction txval;
CSerializeMethodsTestSingle methodtest1(intval, boolval, stringval, charstrval, txval);
CSerializeMethodsTestMany methodtest2(intval, boolval, stringval, charstrval, txval);
@@ -360,7 +364,7 @@ BOOST_AUTO_TEST_CASE(class_methods)
BOOST_CHECK(methodtest2 == methodtest3);
BOOST_CHECK(methodtest3 == methodtest4);
- CDataStream ss2(SER_DISK, PROTOCOL_VERSION, intval, boolval, stringval, FLATDATA(charstrval), txval);
+ CDataStream ss2(SER_DISK, PROTOCOL_VERSION, intval, boolval, stringval, charstrval, txval);
ss2 >> methodtest3;
BOOST_CHECK(methodtest3 == methodtest4);
}
diff --git a/src/test/sighash_tests.cpp b/src/test/sighash_tests.cpp
index 32cd3a50b0..a2bd8998b1 100644
--- a/src/test/sighash_tests.cpp
+++ b/src/test/sighash_tests.cpp
@@ -138,7 +138,7 @@ BOOST_AUTO_TEST_CASE(sighash_test)
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
- sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SIGVERSION_BASE);
+ sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SigVersion::BASE);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
@@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(sighash_from_data)
continue;
}
- sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SIGVERSION_BASE);
+ sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SigVersion::BASE);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
diff --git a/src/test/streams_tests.cpp b/src/test/streams_tests.cpp
index 1108dab584..5d057108b1 100644
--- a/src/test/streams_tests.cpp
+++ b/src/test/streams_tests.cpp
@@ -57,16 +57,16 @@ BOOST_AUTO_TEST_CASE(streams_vector_writer)
BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 0, 1, 2}}));
vch.clear();
- CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, FLATDATA(bytes));
+ CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, bytes);
BOOST_CHECK((vch == std::vector<unsigned char>{{3, 4, 5, 6}}));
- CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, FLATDATA(bytes));
+ CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 0, bytes);
BOOST_CHECK((vch == std::vector<unsigned char>{{3, 4, 5, 6}}));
vch.clear();
vch.resize(4, 8);
- CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, FLATDATA(bytes), b);
+ CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, bytes, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{8, 8, 1, 3, 4, 5, 6, 2}}));
- CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, FLATDATA(bytes), b);
+ CVectorWriter(SER_NETWORK, INIT_PROTO_VERSION, vch, 2, a, bytes, b);
BOOST_CHECK((vch == std::vector<unsigned char>{{8, 8, 1, 3, 4, 5, 6, 2}}));
vch.clear();
}
diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp
index 95c4825b84..9390a93b99 100644
--- a/src/test/test_bitcoin.cpp
+++ b/src/test/test_bitcoin.cpp
@@ -145,9 +145,9 @@ TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>&
for (const CMutableTransaction& tx : txns)
block.vtx.push_back(MakeTransactionRef(tx));
// IncrementExtraNonce creates a valid coinbase and merkleRoot
- unsigned int extraNonce = 0;
{
LOCK(cs_main);
+ unsigned int extraNonce = 0;
IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
}
diff --git a/src/test/test_bitcoin.h b/src/test/test_bitcoin.h
index 944835cccf..8136da3aa9 100644
--- a/src/test/test_bitcoin.h
+++ b/src/test/test_bitcoin.h
@@ -14,6 +14,8 @@
#include <txdb.h>
#include <txmempool.h>
+#include <memory>
+
#include <boost/thread.hpp>
extern uint256 insecure_rand_seed;
diff --git a/src/test/test_bitcoin_fuzzy.cpp b/src/test/test_bitcoin_fuzzy.cpp
index aaba2095e0..69e9804c2f 100644
--- a/src/test/test_bitcoin_fuzzy.cpp
+++ b/src/test/test_bitcoin_fuzzy.cpp
@@ -25,6 +25,7 @@
#include <unistd.h>
#include <algorithm>
+#include <memory>
#include <vector>
enum TEST_ID {
diff --git a/src/test/test_bitcoin_main.cpp b/src/test/test_bitcoin_main.cpp
index 64408e9c5b..e48c685b6b 100644
--- a/src/test/test_bitcoin_main.cpp
+++ b/src/test/test_bitcoin_main.cpp
@@ -6,6 +6,8 @@
#include <net.h>
+#include <memory>
+
#include <boost/test/unit_test.hpp>
std::unique_ptr<CConnman> g_connman;
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index edfb35d155..b222392ee5 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -407,7 +407,7 @@ static CScript PushAll(const std::vector<valtype>& values)
void ReplaceRedeemScript(CScript& script, const CScript& redeemScript)
{
std::vector<valtype> stack;
- EvalScript(stack, script, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SIGVERSION_BASE);
+ EvalScript(stack, script, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
assert(stack.size() > 0);
stack.back() = std::vector<unsigned char>(redeemScript.begin(), redeemScript.end());
script = PushAll(stack);
diff --git a/src/test/txvalidationcache_tests.cpp b/src/test/txvalidationcache_tests.cpp
index 9ec9d6cba3..7087c26774 100644
--- a/src/test/txvalidationcache_tests.cpp
+++ b/src/test/txvalidationcache_tests.cpp
@@ -35,7 +35,7 @@ ToMemPool(CMutableTransaction& tx)
BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup)
{
- // Make sure skipping validation of transctions that were
+ // Make sure skipping validation of transactions that were
// validated going into the memory pool does not allow
// double-spends in blocks to pass validation when they should not.
@@ -56,7 +56,7 @@ BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup)
// Sign:
std::vector<unsigned char> vchSig;
- uint256 hash = SignatureHash(scriptPubKey, spends[i], 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash = SignatureHash(scriptPubKey, spends[i], 0, SIGHASH_ALL, 0, SigVersion::BASE);
BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
spends[i].vin[0].scriptSig << vchSig;
@@ -182,7 +182,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup)
// Sign, with a non-DER signature
{
std::vector<unsigned char> vchSig;
- uint256 hash = SignatureHash(p2pk_scriptPubKey, spend_tx, 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash = SignatureHash(p2pk_scriptPubKey, spend_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE);
BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
vchSig.push_back((unsigned char) 0); // padding byte makes this non-DER
vchSig.push_back((unsigned char)SIGHASH_ALL);
@@ -256,7 +256,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup)
// Sign
std::vector<unsigned char> vchSig;
- uint256 hash = SignatureHash(spend_tx.vout[2].scriptPubKey, invalid_with_cltv_tx, 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash = SignatureHash(spend_tx.vout[2].scriptPubKey, invalid_with_cltv_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE);
BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 101;
@@ -284,7 +284,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup)
// Sign
std::vector<unsigned char> vchSig;
- uint256 hash = SignatureHash(spend_tx.vout[3].scriptPubKey, invalid_with_csv_tx, 0, SIGHASH_ALL, 0, SIGVERSION_BASE);
+ uint256 hash = SignatureHash(spend_tx.vout[3].scriptPubKey, invalid_with_csv_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE);
BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 101;
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp
index 58f033cd89..4b44bbadac 100644
--- a/src/test/util_tests.cpp
+++ b/src/test/util_tests.cpp
@@ -164,21 +164,32 @@ BOOST_AUTO_TEST_CASE(util_DateTimeStrFormat)
BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 0), "1970-01-01 00:00:00");
BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 0x7FFFFFFF), "2038-01-19 03:14:07");
BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 1317425777), "2011-09-30 23:36:17");
+ BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", 1317425777), "2011-09-30T23:36:17Z");
+ BOOST_CHECK_EQUAL(DateTimeStrFormat("%H:%M:%SZ", 1317425777), "23:36:17Z");
BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M", 1317425777), "2011-09-30 23:36");
BOOST_CHECK_EQUAL(DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", 1317425777), "Fri, 30 Sep 2011 23:36:17 +0000");
}
-class TestArgsManager : public ArgsManager
+BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTime)
{
-public:
- std::map<std::string, std::string>& GetMapArgs()
- {
- return mapArgs;
- };
- const std::map<std::string, std::vector<std::string> >& GetMapMultiArgs()
- {
- return mapMultiArgs;
- };
+ BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), "2011-09-30T23:36:17Z");
+}
+
+BOOST_AUTO_TEST_CASE(util_FormatISO8601Date)
+{
+ BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), "2011-09-30");
+}
+
+BOOST_AUTO_TEST_CASE(util_FormatISO8601Time)
+{
+ BOOST_CHECK_EQUAL(FormatISO8601Time(1317425777), "23:36:17Z");
+}
+
+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; }
};
BOOST_AUTO_TEST_CASE(util_ParseParameters)
@@ -206,6 +217,54 @@ BOOST_AUTO_TEST_CASE(util_ParseParameters)
BOOST_CHECK(testArgs.GetArgs("-ccc").size() == 2);
}
+BOOST_AUTO_TEST_CASE(util_GetBoolArg)
+{
+ TestArgsManager testArgs;
+ const char *argv_test[] = {
+ "ignored", "-a", "-nob", "-c=0", "-d=1", "-e=false", "-f=true"};
+ testArgs.ParseParameters(7, (char**)argv_test);
+
+ // Each letter should be set.
+ for (char opt : "abcdef")
+ BOOST_CHECK(testArgs.IsArgSet({'-', opt}) || !opt);
+
+ // Nothing else should be in the map
+ BOOST_CHECK(testArgs.GetMapArgs().size() == 6 &&
+ testArgs.GetMapMultiArgs().size() == 6);
+
+ // The -no prefix should get stripped on the way in.
+ BOOST_CHECK(!testArgs.IsArgSet("-nob"));
+
+ // The -b option is flagged as negated, and nothing else is
+ BOOST_CHECK(testArgs.IsArgNegated("-b"));
+ BOOST_CHECK(testArgs.GetNegatedArgs().size() == 1);
+ BOOST_CHECK(!testArgs.IsArgNegated("-a"));
+
+ // Check expected values.
+ BOOST_CHECK(testArgs.GetBoolArg("-a", false) == true);
+ BOOST_CHECK(testArgs.GetBoolArg("-b", true) == false);
+ BOOST_CHECK(testArgs.GetBoolArg("-c", true) == false);
+ BOOST_CHECK(testArgs.GetBoolArg("-d", false) == true);
+ BOOST_CHECK(testArgs.GetBoolArg("-e", true) == false);
+ BOOST_CHECK(testArgs.GetBoolArg("-f", true) == false);
+}
+
+BOOST_AUTO_TEST_CASE(util_GetBoolArgEdgeCases)
+{
+ // Test some awful edge cases that hopefully no user will ever exercise.
+ TestArgsManager testArgs;
+ 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);
+
+ // A double negative is a positive.
+ BOOST_CHECK(testArgs.IsArgNegated("-bar"));
+ BOOST_CHECK(testArgs.GetBoolArg("-bar", false) == true);
+}
+
BOOST_AUTO_TEST_CASE(util_GetArg)
{
TestArgsManager testArgs;
@@ -687,9 +746,8 @@ static constexpr char ExitCommand = 'X';
static void TestOtherProcess(fs::path dirname, std::string lockname, int fd)
{
char ch;
- int rv;
while (true) {
- rv = read(fd, &ch, 1); // Wait for command
+ int rv = read(fd, &ch, 1); // Wait for command
assert(rv == 1);
switch(ch) {
case LockCommand:
@@ -800,4 +858,20 @@ BOOST_AUTO_TEST_CASE(test_LockDirectory)
fs::remove_all(dirname);
}
+BOOST_AUTO_TEST_CASE(test_DirIsWritable)
+{
+ // Should be able to write to the system tmp dir.
+ fs::path tmpdirname = fs::temp_directory_path();
+ BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true);
+
+ // Should not be able to write to a non-existent dir.
+ tmpdirname = fs::temp_directory_path() / fs::unique_path();
+ BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), false);
+
+ fs::create_directory(tmpdirname);
+ // Should be able to write to it now.
+ BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true);
+ fs::remove(tmpdirname);
+}
+
BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/test/versionbits_tests.cpp b/src/test/versionbits_tests.cpp
index 5d6f781404..92ef58e517 100644
--- a/src/test/versionbits_tests.cpp
+++ b/src/test/versionbits_tests.cpp
@@ -101,8 +101,8 @@ public:
VersionBitsTester& TestDefined() {
for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) {
- BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_DEFINED, strprintf("Test %i for DEFINED", num));
- BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
+ BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::DEFINED, strprintf("Test %i for DEFINED", num));
+ BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
}
}
num++;
@@ -112,8 +112,8 @@ public:
VersionBitsTester& TestStarted() {
for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) {
- BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_STARTED, strprintf("Test %i for STARTED", num));
- BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
+ BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::STARTED, strprintf("Test %i for STARTED", num));
+ BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
}
}
num++;
@@ -123,8 +123,8 @@ public:
VersionBitsTester& TestLockedIn() {
for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) {
- BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_LOCKED_IN, strprintf("Test %i for LOCKED_IN", num));
- BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
+ BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::LOCKED_IN, strprintf("Test %i for LOCKED_IN", num));
+ BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
}
}
num++;
@@ -134,8 +134,8 @@ public:
VersionBitsTester& TestActive() {
for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) {
- BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE", num));
- BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
+ BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::ACTIVE, strprintf("Test %i for ACTIVE", num));
+ BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
}
}
num++;
@@ -145,8 +145,8 @@ public:
VersionBitsTester& TestFailed() {
for (int i = 0; i < CHECKERS; i++) {
if (InsecureRandBits(i) == 0) {
- BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_FAILED, strprintf("Test %i for FAILED", num));
- BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
+ BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::FAILED, strprintf("Test %i for FAILED", num));
+ BOOST_CHECK_MESSAGE(checker_always[i].GetStateFor(vpblock.empty() ? nullptr : vpblock.back()) == ThresholdState::ACTIVE, strprintf("Test %i for ACTIVE (always active)", num));
}
}
num++;
diff --git a/src/tinyformat.h b/src/tinyformat.h
index d34cfaa94f..14b7cd3026 100644
--- a/src/tinyformat.h
+++ b/src/tinyformat.h
@@ -155,7 +155,7 @@ namespace tfm = tinyformat;
#endif
#ifdef __APPLE__
-// Workaround OSX linker warning: xcode uses different default symbol
+// Workaround OSX linker warning: Xcode uses different default symbol
// visibilities for static libs vs executables (see issue #25)
# define TINYFORMAT_HIDDEN __attribute__((visibility("hidden")))
#else
@@ -592,7 +592,7 @@ inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt)
// Formatting options which can't be natively represented using the ostream
// state are returned in spacePadPositive (for space padded positive numbers)
// and ntrunc (for truncating conversions). argIndex is incremented if
-// necessary to pull out variable width and precision . The function returns a
+// necessary to pull out variable width and precision. The function returns a
// pointer to the character after the end of the current format spec.
inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositive,
int& ntrunc, const char* fmtStart,
diff --git a/src/txdb.cpp b/src/txdb.cpp
index 293d43c7b3..8550a7e889 100644
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -147,7 +147,7 @@ size_t CCoinsViewDB::EstimateSize() const
return db.EstimateSize(DB_COIN, (char)(DB_COIN+1));
}
-CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
+CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(gArgs.IsArgSet("-blocksdir") ? GetDataDir() / "blocks" / "index" : GetBlocksDir() / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
@@ -324,7 +324,7 @@ public:
void Unserialize(Stream &s) {
unsigned int nCode = 0;
// version
- int nVersionDummy;
+ unsigned int nVersionDummy;
::Unserialize(s, VARINT(nVersionDummy));
// header code
::Unserialize(s, VARINT(nCode));
@@ -348,10 +348,10 @@ public:
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
- ::Unserialize(s, REF(CTxOutCompressor(vout[i])));
+ ::Unserialize(s, CTxOutCompressor(vout[i]));
}
// coinbase height
- ::Unserialize(s, VARINT(nHeight));
+ ::Unserialize(s, VARINT(nHeight, VarIntMode::NONNEGATIVE_SIGNED));
}
};
diff --git a/src/txdb.h b/src/txdb.h
index 2fc69e563b..ad76b3257d 100644
--- a/src/txdb.h
+++ b/src/txdb.h
@@ -11,6 +11,7 @@
#include <chain.h>
#include <map>
+#include <memory>
#include <string>
#include <utility>
#include <vector>
diff --git a/src/txmempool.cpp b/src/txmempool.cpp
index d1edde284f..d03429ca81 100644
--- a/src/txmempool.cpp
+++ b/src/txmempool.cpp
@@ -339,7 +339,7 @@ CTxMemPool::CTxMemPool(CBlockPolicyEstimator* estimator) :
nCheckFrequency = 0;
}
-bool CTxMemPool::isSpent(const COutPoint& outpoint)
+bool CTxMemPool::isSpent(const COutPoint& outpoint) const
{
LOCK(cs);
return mapNextTx.count(outpoint);
@@ -447,7 +447,7 @@ void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
// Also assumes that if an entry is in setDescendants already, then all
// in-mempool descendants of it are already in setDescendants as well, so that we
// can save time by not iterating over those entries.
-void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
+void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
{
setEntries stage;
if (setDescendants.count(entryit) == 0) {
diff --git a/src/txmempool.h b/src/txmempool.h
index c6a1bf08ce..a1cde6f779 100644
--- a/src/txmempool.h
+++ b/src/txmempool.h
@@ -550,7 +550,7 @@ public:
void _clear(); //lock free
bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
void queryHashes(std::vector<uint256>& vtxid);
- bool isSpent(const COutPoint& outpoint);
+ bool isSpent(const COutPoint& outpoint) const;
unsigned int GetTransactionsUpdated() const;
void AddTransactionsUpdated(unsigned int n);
/**
@@ -600,7 +600,7 @@ public:
/** Populate setDescendants with all in-mempool descendants of hash.
* Assumes that setDescendants includes all in-mempool descendants of anything
* already in it. */
- void CalculateDescendants(txiter it, setEntries &setDescendants);
+ void CalculateDescendants(txiter it, setEntries& setDescendants) const;
/** The minimum fee to get into the mempool, which may itself not be enough
* for larger-sized transactions.
@@ -689,7 +689,7 @@ private:
};
/**
- * CCoinsView that brings transactions from a memorypool into view.
+ * CCoinsView that brings transactions from a mempool into view.
* It does not check for spendings by memory pool transactions.
* Instead, it provides access to all Coins which are either unspent in the
* base CCoinsView, or are outputs from any mempool transaction!
diff --git a/src/undo.h b/src/undo.h
index 1f10c6652c..f292924165 100644
--- a/src/undo.h
+++ b/src/undo.h
@@ -15,7 +15,7 @@
*
* Contains the prevout's CTxOut being spent, and its metadata as well
* (coinbase or not, height). The serialization contains a dummy value of
- * zero. This is be compatible with older versions which expect to see
+ * zero. This is compatible with older versions which expect to see
* the transaction version there.
*/
class TxInUndoSerializer
@@ -25,7 +25,7 @@ class TxInUndoSerializer
public:
template<typename Stream>
void Serialize(Stream &s) const {
- ::Serialize(s, VARINT(txout->nHeight * 2 + (txout->fCoinBase ? 1 : 0)));
+ ::Serialize(s, VARINT(txout->nHeight * 2 + (txout->fCoinBase ? 1u : 0u)));
if (txout->nHeight > 0) {
// Required to maintain compatibility with older undo format.
::Serialize(s, (unsigned char)0);
@@ -51,10 +51,10 @@ public:
// Old versions stored the version number for the last spend of
// a transaction's outputs. Non-final spends were indicated with
// height = 0.
- int nVersionDummy;
+ unsigned int nVersionDummy;
::Unserialize(s, VARINT(nVersionDummy));
}
- ::Unserialize(s, REF(CTxOutCompressor(REF(txout->out))));
+ ::Unserialize(s, CTxOutCompressor(REF(txout->out)));
}
explicit TxInUndoDeserializer(Coin* coin) : txout(coin) {}
@@ -76,7 +76,7 @@ public:
uint64_t count = vprevout.size();
::Serialize(s, COMPACTSIZE(REF(count)));
for (const auto& prevout : vprevout) {
- ::Serialize(s, REF(TxInUndoSerializer(&prevout)));
+ ::Serialize(s, TxInUndoSerializer(&prevout));
}
}
@@ -90,7 +90,7 @@ public:
}
vprevout.resize(count);
for (auto& prevout : vprevout) {
- ::Unserialize(s, REF(TxInUndoDeserializer(&prevout)));
+ ::Unserialize(s, TxInUndoDeserializer(&prevout));
}
}
};
diff --git a/src/util.cpp b/src/util.cpp
index 82c99a3c2f..46054f5025 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -4,7 +4,6 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util.h>
-#include <fs.h>
#include <chainparamsbase.h>
#include <random.h>
@@ -71,8 +70,6 @@
#include <malloc.h>
#endif
-#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
-#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/thread.hpp>
@@ -160,10 +157,10 @@ instance_of_cinit;
* the mutex).
*/
-static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
+static std::once_flag debugPrintInitFlag;
/**
- * We use boost::call_once() to make sure mutexDebugLog and
+ * We use std::call_once() to make sure mutexDebugLog and
* vMsgsBeforeOpenLog are initialized in a thread-safe manner.
*
* NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
@@ -172,7 +169,7 @@ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
* tested, explicit destruction of these objects can be implemented.
*/
static FILE* fileout = nullptr;
-static boost::mutex* mutexDebugLog = nullptr;
+static std::mutex* mutexDebugLog = nullptr;
static std::list<std::string>* vMsgsBeforeOpenLog;
static int FileWriteStr(const std::string &str, FILE *fp)
@@ -183,7 +180,7 @@ static int FileWriteStr(const std::string &str, FILE *fp)
static void DebugPrintInit()
{
assert(mutexDebugLog == nullptr);
- mutexDebugLog = new boost::mutex();
+ mutexDebugLog = new std::mutex();
vMsgsBeforeOpenLog = new std::list<std::string>;
}
@@ -195,8 +192,8 @@ fs::path GetDebugLogPath()
bool OpenDebugLog()
{
- boost::call_once(&DebugPrintInit, debugPrintInitFlag);
- boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
+ std::call_once(debugPrintInitFlag, &DebugPrintInit);
+ std::lock_guard<std::mutex> scoped_lock(*mutexDebugLog);
assert(fileout == nullptr);
assert(vMsgsBeforeOpenLog);
@@ -315,12 +312,14 @@ static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fSt
if (*fStartedNewLine) {
int64_t nTimeMicros = GetTimeMicros();
- strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
- if (fLogTimeMicros)
- strStamped += strprintf(".%06d", nTimeMicros%1000000);
+ strStamped = FormatISO8601DateTime(nTimeMicros/1000000);
+ if (fLogTimeMicros) {
+ strStamped.pop_back();
+ strStamped += strprintf(".%06dZ", nTimeMicros%1000000);
+ }
int64_t mocktime = GetMockTime();
if (mocktime) {
- strStamped += " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime) + ")";
+ strStamped += " (mocktime: " + FormatISO8601DateTime(mocktime) + ")";
}
strStamped += ' ' + str;
} else
@@ -349,8 +348,8 @@ int LogPrintStr(const std::string &str)
}
else if (fPrintToDebugLog)
{
- boost::call_once(&DebugPrintInit, debugPrintInitFlag);
- boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
+ std::call_once(debugPrintInitFlag, &DebugPrintInit);
+ std::lock_guard<std::mutex> scoped_lock(*mutexDebugLog);
// buffer if we haven't opened the log yet
if (fileout == nullptr) {
@@ -418,7 +417,36 @@ void ReleaseDirectoryLocks()
dir_locks.clear();
}
-/** Interpret string as boolean, for argument parsing */
+bool DirIsWritable(const fs::path& directory)
+{
+ fs::path tmpFile = directory / fs::unique_path();
+
+ FILE* file = fsbridge::fopen(tmpFile, "a");
+ if (!file) return false;
+
+ fclose(file);
+ remove(tmpFile);
+
+ return true;
+}
+
+/**
+ * Interpret a string argument as a boolean.
+ *
+ * The definition of atoi() requires that non-numeric string values like "foo",
+ * return 0. This means that if a user unintentionally supplies a non-integer
+ * argument here, the return value is always false. This means that -foo=false
+ * does what the user probably expects, but -foo=true is well defined but does
+ * not do what they probably expected.
+ *
+ * The return value of atoi() is undefined when given input not representable as
+ * an int. On most systems this means string value between "-2147483648" and
+ * "2147483647" are well defined (this method will return true). Setting
+ * -txindex=2147483648 on most systems, however, is probably undefined.
+ *
+ * For a more extensive discussion of this topic (and a wide range of opinions
+ * on the Right Way to change this code), see PR12713.
+ */
static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
@@ -426,13 +454,30 @@ static bool InterpretBool(const std::string& strValue)
return (atoi(strValue) != 0);
}
-/** Turn -noX into -X=0 */
-static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
+/**
+ * Interpret -nofoo as if the user supplied -foo=0.
+ *
+ * This method also tracks when the -no form was supplied, and treats "-foo" as
+ * a negated option when this happens. This can be later checked using the
+ * IsArgNegated() method. One use case for this is to have a way to disable
+ * options that are not normally boolean (e.g. using -nodebuglogfile to request
+ * that debug log output is not sent to any file at all).
+ */
+void ArgsManager::InterpretNegatedOption(std::string& key, std::string& val)
{
- if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
- {
- strKey = "-" + strKey.substr(3);
- strValue = InterpretBool(strValue) ? "0" : "1";
+ if (key.substr(0, 3) == "-no") {
+ bool bool_val = InterpretBool(val);
+ if (!bool_val ) {
+ // Double negatives like -nofoo=0 are supported (but discouraged)
+ LogPrintf("Warning: parsed potentially confusing double-negative %s=%s\n", key, val);
+ }
+ key.erase(1, 2);
+ m_negated_args.insert(key);
+ val = bool_val ? "0" : "1";
+ } else {
+ // In an invocation like "bitcoind -nofoo -foo" we want to unmark -foo
+ // as negated when we see the second option.
+ m_negated_args.erase(key);
}
}
@@ -441,34 +486,34 @@ void ArgsManager::ParseParameters(int argc, const char* const argv[])
LOCK(cs_args);
mapArgs.clear();
mapMultiArgs.clear();
-
- for (int i = 1; i < argc; i++)
- {
- std::string str(argv[i]);
- std::string strValue;
- size_t is_index = str.find('=');
- if (is_index != std::string::npos)
- {
- strValue = str.substr(is_index+1);
- str = str.substr(0, is_index);
+ m_negated_args.clear();
+
+ for (int i = 1; i < argc; i++) {
+ std::string key(argv[i]);
+ std::string val;
+ size_t is_index = key.find('=');
+ if (is_index != std::string::npos) {
+ val = key.substr(is_index + 1);
+ key.erase(is_index);
}
#ifdef WIN32
- boost::to_lower(str);
- if (boost::algorithm::starts_with(str, "/"))
- str = "-" + str.substr(1);
+ std::transform(key.begin(), key.end(), key.begin(), ::tolower);
+ if (key[0] == '/')
+ key[0] = '-';
#endif
- if (str[0] != '-')
+ if (key[0] != '-')
break;
- // Interpret --foo as -foo.
- // If both --foo and -foo are set, the last takes effect.
- if (str.length() > 1 && str[1] == '-')
- str = str.substr(1);
- InterpretNegativeSetting(str, strValue);
+ // Transform --foo to -foo
+ if (key.length() > 1 && key[1] == '-')
+ key.erase(0, 1);
+
+ // Transform -nofoo to -foo=0
+ InterpretNegatedOption(key, val);
- mapArgs[str] = strValue;
- mapMultiArgs[str].push_back(strValue);
+ mapArgs[key] = val;
+ mapMultiArgs[key].push_back(val);
}
}
@@ -486,6 +531,12 @@ bool ArgsManager::IsArgSet(const std::string& strArg) const
return mapArgs.count(strArg);
}
+bool ArgsManager::IsArgNegated(const std::string& strArg) const
+{
+ LOCK(cs_args);
+ return m_negated_args.find(strArg) != m_negated_args.end();
+}
+
std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
{
LOCK(cs_args);
@@ -533,7 +584,10 @@ void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strV
mapMultiArgs[strArg] = {strValue};
}
-
+bool HelpRequested(const ArgsManager& args)
+{
+ return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help");
+}
static const int screenWidth = 79;
static const int optIndent = 2;
@@ -599,10 +653,41 @@ fs::path GetDefaultDataDir()
#endif
}
+static fs::path g_blocks_path_cached;
+static fs::path g_blocks_path_cache_net_specific;
static fs::path pathCached;
static fs::path pathCachedNetSpecific;
static CCriticalSection csPathCached;
+const fs::path &GetBlocksDir(bool fNetSpecific)
+{
+
+ LOCK(csPathCached);
+
+ fs::path &path = fNetSpecific ? g_blocks_path_cache_net_specific : g_blocks_path_cached;
+
+ // This can be called during exceptions by LogPrintf(), so we cache the
+ // value so we don't have to do memory allocations after that.
+ if (!path.empty())
+ return path;
+
+ if (gArgs.IsArgSet("-blocksdir")) {
+ path = fs::system_complete(gArgs.GetArg("-blocksdir", ""));
+ if (!fs::is_directory(path)) {
+ path = "";
+ return path;
+ }
+ } else {
+ path = GetDataDir(false);
+ }
+ if (fNetSpecific)
+ path /= BaseParams().DataDir();
+
+ path /= "blocks";
+ fs::create_directories(path);
+ return path;
+}
+
const fs::path &GetDataDir(bool fNetSpecific)
{
@@ -641,6 +726,8 @@ void ClearDatadirCache()
pathCached = fs::path();
pathCachedNetSpecific = fs::path();
+ g_blocks_path_cached = fs::path();
+ g_blocks_path_cache_net_specific = fs::path();
}
fs::path GetConfigFile(const std::string& confPath)
@@ -664,7 +751,7 @@ void ArgsManager::ReadConfigFile(const std::string& confPath)
// 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];
- InterpretNegativeSetting(strKey, strValue);
+ InterpretNegatedOption(strKey, strValue);
if (mapArgs.count(strKey) == 0)
mapArgs[strKey] = strValue;
mapMultiArgs[strKey].push_back(strValue);
diff --git a/src/util.h b/src/util.h
index e4170d8aa2..7114c0accd 100644
--- a/src/util.h
+++ b/src/util.h
@@ -23,8 +23,10 @@
#include <atomic>
#include <exception>
#include <map>
+#include <memory>
#include <stdint.h>
#include <string>
+#include <unordered_set>
#include <vector>
#include <boost/signals2/signal.hpp>
@@ -136,7 +138,7 @@ template<typename T, typename... Args> static inline void MarkUsed(const T& t, c
// Be conservative when using LogPrintf/error or other things which
// unconditionally log to debug.log! It should not be the case that an inbound
-// peer can fill up a users disk with debug.log entries.
+// peer can fill up a user's disk with debug.log entries.
#ifdef USE_COVERAGE
#define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
@@ -174,6 +176,7 @@ int RaiseFileDescriptorLimit(int nMinFD);
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
bool RenameOver(fs::path src, fs::path dest);
bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false);
+bool DirIsWritable(const fs::path& directory);
/** Release all directory locks. This is used for unit testing only, at runtime
* the global destructor will take care of the locks.
@@ -182,6 +185,7 @@ void ReleaseDirectoryLocks();
bool TryCreateDirectories(const fs::path& p);
fs::path GetDefaultDataDir();
+const fs::path &GetBlocksDir(bool fNetSpecific = true);
const fs::path &GetDataDir(bool fNetSpecific = true);
void ClearDatadirCache();
fs::path GetConfigFile(const std::string& confPath);
@@ -222,6 +226,8 @@ protected:
mutable CCriticalSection cs_args;
std::map<std::string, std::string> mapArgs;
std::map<std::string, std::vector<std::string>> mapMultiArgs;
+ std::unordered_set<std::string> m_negated_args;
+
public:
void ParseParameters(int argc, const char*const argv[]);
void ReadConfigFile(const std::string& confPath);
@@ -243,6 +249,15 @@ public:
bool IsArgSet(const std::string& strArg) const;
/**
+ * Return true if the argument was originally passed as a negated option,
+ * i.e. -nofoo.
+ *
+ * @param strArg Argument to get (e.g. "-foo")
+ * @return true if the argument was passed negated
+ */
+ bool IsArgNegated(const std::string& strArg) const;
+
+ /**
* Return string argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
@@ -290,11 +305,21 @@ public:
// Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
// been set. Also called directly in testing.
void ForceSetArg(const std::string& strArg, const std::string& strValue);
+
+private:
+
+ // Munge -nofoo into -foo=0 and track the value as negated.
+ void InterpretNegatedOption(std::string &key, std::string &val);
};
extern ArgsManager gArgs;
/**
+ * @return true if help has been requested via a command-line arg
+ */
+bool HelpRequested(const ArgsManager& args);
+
+/**
* Format a string to be used as group of options in help messages
*
* @param message Group name (e.g. "RPC server options:")
diff --git a/src/utiltime.cpp b/src/utiltime.cpp
index e908173135..8a861039b3 100644
--- a/src/utiltime.cpp
+++ b/src/utiltime.cpp
@@ -85,3 +85,15 @@ std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
+
+std::string FormatISO8601DateTime(int64_t nTime) {
+ return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
+}
+
+std::string FormatISO8601Date(int64_t nTime) {
+ return DateTimeStrFormat("%Y-%m-%d", nTime);
+}
+
+std::string FormatISO8601Time(int64_t nTime) {
+ return DateTimeStrFormat("%H:%M:%SZ", nTime);
+}
diff --git a/src/utiltime.h b/src/utiltime.h
index 56cc31da67..807c52ffaf 100644
--- a/src/utiltime.h
+++ b/src/utiltime.h
@@ -27,6 +27,14 @@ void SetMockTime(int64_t nMockTimeIn);
int64_t GetMockTime();
void MilliSleep(int64_t n);
+/**
+ * ISO 8601 formatting is preferred. Use the FormatISO8601{DateTime,Date,Time}
+ * helper functions if possible.
+ */
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime);
+std::string FormatISO8601DateTime(int64_t nTime);
+std::string FormatISO8601Date(int64_t nTime);
+std::string FormatISO8601Time(int64_t nTime);
+
#endif // BITCOIN_UTILTIME_H
diff --git a/src/validation.cpp b/src/validation.cpp
index 51e40c17b5..df8729e382 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -227,6 +227,7 @@ CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
CBlockPolicyEstimator feeEstimator;
CTxMemPool mempool(&feeEstimator);
+std::atomic_bool g_is_mempool_loaded{false};
/** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS;
@@ -260,12 +261,12 @@ namespace {
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
+ AssertLockHeld(cs_main);
+
// Find the first block the caller has in the main chain
for (const uint256& hash : locator.vHave) {
- BlockMap::iterator mi = mapBlockIndex.find(hash);
- if (mi != mapBlockIndex.end())
- {
- CBlockIndex* pindex = (*mi).second;
+ CBlockIndex* pindex = LookupBlockIndex(hash);
+ if (pindex) {
if (chain.Contains(pindex))
return pindex;
if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
@@ -280,11 +281,11 @@ std::unique_ptr<CCoinsViewDB> pcoinsdbview;
std::unique_ptr<CCoinsViewCache> pcoinsTip;
std::unique_ptr<CBlockTreeDB> pblocktree;
-enum FlushStateMode {
- FLUSH_STATE_NONE,
- FLUSH_STATE_IF_NEEDED,
- FLUSH_STATE_PERIODIC,
- FLUSH_STATE_ALWAYS
+enum class FlushStateMode {
+ NONE,
+ IF_NEEDED,
+ PERIODIC,
+ ALWAYS
};
// See definition for documentation
@@ -542,7 +543,7 @@ static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationSt
static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
- bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
+ bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache, bool test_accept)
{
const CTransaction& tx = *ptx;
const uint256 hash = tx.GetHash();
@@ -934,6 +935,11 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
}
}
+ if (test_accept) {
+ // Tx was accepted, but not added
+ return true;
+ }
+
// Remove conflicting transactions from the mempool
for (const CTxMemPool::txiter it : allConflicting)
{
@@ -949,7 +955,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// This transaction should only count for fee estimation if:
// - it isn't a BIP 125 replacement transaction (may not be widely supported)
- // - it's not being readded during a reorg which bypasses typical mempool fee limits
+ // - it's not being re-added during a reorg which bypasses typical mempool fee limits
// - the node is not behind
// - the transaction is not dependent on any other transactions in the mempool
bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
@@ -973,26 +979,26 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
/** (try to) add transaction to memory pool with a specified acceptance time **/
static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
- bool bypass_limits, const CAmount nAbsurdFee)
+ bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
{
std::vector<COutPoint> coins_to_uncache;
- bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
+ bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache, test_accept);
if (!res) {
for (const COutPoint& hashTx : coins_to_uncache)
pcoinsTip->Uncache(hashTx);
}
// After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
CValidationState stateDummy;
- FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
+ FlushStateToDisk(chainparams, stateDummy, FlushStateMode::PERIODIC);
return res;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
- bool bypass_limits, const CAmount nAbsurdFee)
+ bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
{
const CChainParams& chainparams = Params();
- return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
+ return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee, test_accept);
}
/**
@@ -1077,7 +1083,7 @@ static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMes
// Write index header
unsigned int nSize = GetSerializeSize(fileout, block);
- fileout << FLATDATA(messageStart) << nSize;
+ fileout << messageStart << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
@@ -1267,13 +1273,12 @@ void static InvalidChainFound(CBlockIndex* pindexNew)
LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
- log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
- pindexNew->GetBlockTime()));
+ log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
CBlockIndex *tip = chainActive.Tip();
assert (tip);
LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
+ FormatISO8601DateTime(tip->GetBlockTime()));
CheckForkWarningConditions();
}
@@ -1317,7 +1322,7 @@ bool CScriptCheck::operator()() {
int GetSpendHeight(const CCoinsViewCache& inputs)
{
LOCK(cs_main);
- CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
+ CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
return pindexPrev->nHeight + 1;
}
@@ -1442,7 +1447,7 @@ bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint
// Write index header
unsigned int nSize = GetSerializeSize(fileout, blockundo);
- fileout << FLATDATA(messageStart) << nSize;
+ fileout << messageStart << nSize;
// Write undo data
long fileOutPos = ftell(fileout.Get());
@@ -1685,7 +1690,7 @@ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Para
for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
ThresholdState state = VersionBitsState(pindexPrev, params, static_cast<Consensus::DeploymentPos>(i), versionbitscache);
- if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
+ if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) {
nVersion |= VersionBitsMask(params, static_cast<Consensus::DeploymentPos>(i));
}
}
@@ -1741,7 +1746,7 @@ static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consens
}
// Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
- if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
+ if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) {
flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
}
@@ -1853,7 +1858,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
// Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
// with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
// time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
- // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
+ // before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
// duplicate transactions descending from the known pairs either.
// If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
@@ -1927,7 +1932,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl
// Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
int nLockTimeFlags = 0;
- if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
+ if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) {
nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
}
@@ -2097,19 +2102,19 @@ bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &
int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
// The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
- bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
+ bool fCacheLarge = mode == FlushStateMode::PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
// The cache is over the limit, we have to write now.
- bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
+ bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cacheSize > nTotalSpace;
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
- bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
+ bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
- bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
+ bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
// Combine all conditions that result in a full cache flush.
- fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
+ fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
// Write blocks and block index to disk.
if (fDoFullFlush || fPeriodicWrite) {
// Depend on nMinDiskSpace to ensure we can write block index
- if (!CheckDiskSpace(0))
+ if (!CheckDiskSpace(0, true))
return state.Error("out of disk space");
// First make sure all block and undo data is flushed to disk.
FlushBlockFile();
@@ -2151,7 +2156,7 @@ bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &
nLastFlush = nNow;
}
}
- if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
+ if (fDoFullFlush || ((mode == FlushStateMode::ALWAYS || mode == FlushStateMode::PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
// Update best block in wallet (so we can detect restored wallets).
GetMainSignals().SetBestChain(chainActive.GetLocator());
nLastSetChain = nNow;
@@ -2165,14 +2170,14 @@ bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &
void FlushStateToDisk() {
CValidationState state;
const CChainParams& chainparams = Params();
- FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
+ FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS);
}
void PruneAndFlush() {
CValidationState state;
fCheckForPruning = true;
const CChainParams& chainparams = Params();
- FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
+ FlushStateToDisk(chainparams, state, FlushStateMode::NONE);
}
static void DoWarning(const std::string& strWarning)
@@ -2200,9 +2205,9 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar
for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
WarningBitsConditionChecker checker(bit);
ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
- if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
+ if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
- if (state == THRESHOLD_ACTIVE) {
+ if (state == ThresholdState::ACTIVE) {
DoWarning(strWarning);
} else {
warningMessages.push_back(strWarning);
@@ -2229,7 +2234,7 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar
LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()),
+ 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, ", "));
@@ -2268,7 +2273,7 @@ bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& cha
}
LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
// Write the chain state to disk, if necessary.
- if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
+ if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
return false;
if (disconnectpool) {
@@ -2406,7 +2411,7 @@ bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainp
int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
// Write the chain state to disk, if necessary.
- if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
+ if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
return false;
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
@@ -2683,7 +2688,7 @@ bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams&
CheckBlockIndex(chainparams.GetConsensus());
// Write changes periodically to disk, after relay.
- if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
+ if (!FlushStateToDisk(chainparams, state, FlushStateMode::PERIODIC)) {
return false;
}
@@ -2781,7 +2786,11 @@ bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& c
}
InvalidChainFound(pindex);
- uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
+
+ // Only notify about a new block tip if the active chain was modified.
+ if (pindex_was_in_chain) {
+ uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
+ }
return true;
}
bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
@@ -2827,6 +2836,8 @@ bool ResetBlockFailureFlags(CBlockIndex *pindex) {
CBlockIndex* CChainState::AddToBlockIndex(const CBlockHeader& block)
{
+ AssertLockHeld(cs_main);
+
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator it = mapBlockIndex.find(hash);
@@ -2948,7 +2959,7 @@ static bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
- if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
+ if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos, true)) {
FILE *file = OpenBlockFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
@@ -2981,7 +2992,7 @@ static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos,
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
- if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
+ if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos, true)) {
FILE *file = OpenUndoFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
@@ -3071,7 +3082,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::P
bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
{
LOCK(cs_main);
- return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
+ return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == ThresholdState::ACTIVE);
}
// Compute at which vout of the block's coinbase transaction the witness
@@ -3190,7 +3201,7 @@ static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, c
// Start enforcing BIP113 (Median Time Past) using versionbits logic.
int nLockTimeFlags = 0;
- if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
+ if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) {
nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
}
@@ -3218,13 +3229,13 @@ static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, c
// Validation for witness commitments.
// * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
// coinbase (where 0x0000....0000 is used instead).
- // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
+ // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
// * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
// * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
- // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
+ // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
// multiple, the last one is used.
bool fHaveWitness = false;
- if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
+ if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == ThresholdState::ACTIVE) {
int commitpos = GetWitnessCommitmentIndex(block);
if (commitpos != -1) {
bool malleated = false;
@@ -3233,7 +3244,7 @@ static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, c
// already does not permit it, it is impossible to trigger in the
// witness tree.
if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
- return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
+ return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness reserved value size", __func__));
}
CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
@@ -3252,7 +3263,7 @@ static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, c
}
}
- // After the coinbase witness nonce and commitment are verified,
+ // After the coinbase witness reserved value and commitment are verified,
// we can check if the block weight passes (before we've checked the
// coinbase witness, it would be possible for the weight to be too
// large by filling up the coinbase witness, which doesn't change
@@ -3273,7 +3284,6 @@ bool CChainState::AcceptBlockHeader(const CBlockHeader& block, CValidationState&
BlockMap::iterator miSelf = mapBlockIndex.find(hash);
CBlockIndex *pindex = nullptr;
if (hash != chainparams.GetConsensus().hashGenesisBlock) {
-
if (miSelf != mapBlockIndex.end()) {
// Block header is already known.
pindex = miSelf->second;
@@ -3439,7 +3449,7 @@ bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CVali
}
if (fCheckForPruning)
- FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
+ FlushStateToDisk(chainparams, state, FlushStateMode::NONE); // we just allocated more disk space for block files
CheckBlockIndex(chainparams.GetConsensus());
@@ -3592,7 +3602,7 @@ void PruneBlockFilesManual(int nManualPruneHeight)
{
CValidationState state;
const CChainParams& chainparams = Params();
- FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
+ FlushStateToDisk(chainparams, state, FlushStateMode::NONE, nManualPruneHeight);
}
/**
@@ -3657,9 +3667,9 @@ static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfte
nLastBlockWeCanPrune, count);
}
-bool CheckDiskSpace(uint64_t nAdditionalBytes)
+bool CheckDiskSpace(uint64_t nAdditionalBytes, bool blocks_dir)
{
- uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
+ uint64_t nFreeBytesAvailable = fs::space(blocks_dir ? GetBlocksDir() : GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
@@ -3702,11 +3712,13 @@ static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
{
- return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
+ return GetBlocksDir() / strprintf("%s%05u.dat", prefix, pos.nFile);
}
CBlockIndex * CChainState::InsertBlockIndex(const uint256& hash)
{
+ AssertLockHeld(cs_main);
+
if (hash.IsNull())
return nullptr;
@@ -3834,6 +3846,8 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams)
bool LoadChainTip(const CChainParams& chainparams)
{
+ AssertLockHeld(cs_main);
+
if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
@@ -3847,16 +3861,17 @@ bool LoadChainTip(const CChainParams& chainparams)
}
// Load pointer to end of best chain
- BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
- if (it == mapBlockIndex.end())
+ CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock());
+ if (!pindex) {
return false;
- chainActive.SetTip(it->second);
+ }
+ chainActive.SetTip(pindex);
g_chainstate.PruneBlockIndexCandidates();
LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
+ FormatISO8601DateTime(chainActive.Tip()->GetBlockTime()),
GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
return true;
}
@@ -4085,7 +4100,7 @@ bool CChainState::RewindBlockIndex(const CChainParams& params)
return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
}
// Occasionally flush state to disk.
- if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
+ if (!FlushStateToDisk(params, state, FlushStateMode::PERIODIC))
return false;
}
@@ -4151,7 +4166,7 @@ bool RewindBlockIndex(const CChainParams& params) {
// and skip it here, we're about to -reindex-chainstate anyway, so
// it'll get called a bunch real soon.
CValidationState state;
- if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
+ if (!FlushStateToDisk(params, state, FlushStateMode::ALWAYS)) {
return false;
}
}
@@ -4274,7 +4289,7 @@ bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskB
unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
blkdat.FindByte(chainparams.MessageStart()[0]);
nRewind = blkdat.GetPos()+1;
- blkdat >> FLATDATA(buf);
+ blkdat >> buf;
if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
continue;
// read size
@@ -4297,26 +4312,31 @@ bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskB
blkdat >> block;
nRewind = blkdat.GetPos();
- // detect out of order blocks, and store them for later
uint256 hash = block.GetHash();
- if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
- LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
- block.hashPrevBlock.ToString());
- if (dbp)
- mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
- continue;
- }
-
- // process in case the block isn't known yet
- if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
+ {
LOCK(cs_main);
- CValidationState state;
- if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
- nLoaded++;
- if (state.IsError())
- break;
- } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
- LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
+ // detect out of order blocks, and store them for later
+ if (hash != chainparams.GetConsensus().hashGenesisBlock && !LookupBlockIndex(block.hashPrevBlock)) {
+ LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
+ block.hashPrevBlock.ToString());
+ if (dbp)
+ mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
+ continue;
+ }
+
+ // process in case the block isn't known yet
+ CBlockIndex* pindex = LookupBlockIndex(hash);
+ if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
+ CValidationState state;
+ if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr)) {
+ nLoaded++;
+ }
+ if (state.IsError()) {
+ break;
+ }
+ } else if (hash != chainparams.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
+ LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
+ }
}
// Activate the genesis block so normal node progress can continue
@@ -4554,7 +4574,7 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
std::string CBlockFileInfo::ToString() const
{
- return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
+ return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
}
CBlockFileInfo* GetBlockFileInfo(size_t n)
@@ -4625,7 +4645,8 @@ bool LoadMempool(void)
if (nTime + nExpiryTimeout > nNow) {
LOCK(cs_main);
AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
- nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
+ nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */,
+ false /* test_accept */);
if (state.IsValid()) {
++count;
} else {
diff --git a/src/validation.h b/src/validation.h
index 99cbfdf1ee..dad6858b1e 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -22,6 +22,7 @@
#include <algorithm>
#include <exception>
#include <map>
+#include <memory>
#include <set>
#include <stdint.h>
#include <string>
@@ -158,6 +159,7 @@ extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern CBlockPolicyEstimator feeEstimator;
extern CTxMemPool mempool;
+extern std::atomic_bool g_is_mempool_loaded;
typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
extern BlockMap& mapBlockIndex;
extern uint64_t nLastBlockTx;
@@ -254,7 +256,7 @@ bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<cons
bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex=nullptr, CBlockHeader *first_invalid=nullptr);
/** Check whether enough disk space is available for an incoming block */
-bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
+bool CheckDiskSpace(uint64_t nAdditionalBytes = 0, bool blocks_dir = false);
/** Open a block file (blk?????.dat) */
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Translation to a filesystem path */
@@ -307,7 +309,7 @@ void PruneBlockFilesManual(int nManualPruneHeight);
* plTxnReplaced will be appended to with all transactions replaced from mempool **/
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
- bool bypass_limits, const CAmount nAbsurdFee);
+ bool bypass_limits, const CAmount nAbsurdFee, bool test_accept=false);
/** Convert CValidationState to a human-readable message for logging */
std::string FormatStateMessage(const CValidationState &state);
@@ -411,7 +413,7 @@ bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& pa
/** When there are blocks in the active chain with missing data, rewind the chainstate and remove them from the block index */
bool RewindBlockIndex(const CChainParams& params);
-/** Update uncommitted block structures (currently: only the witness nonce). This is safe for submitted blocks. */
+/** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */
void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
/** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
@@ -428,6 +430,13 @@ public:
/** Replay blocks that aren't fully applied to the database. */
bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
+inline CBlockIndex* LookupBlockIndex(const uint256& hash)
+{
+ AssertLockHeld(cs_main);
+ BlockMap::const_iterator it = mapBlockIndex.find(hash);
+ return it == mapBlockIndex.end() ? nullptr : it->second;
+}
+
/** Find the last common block between the parameter chain and a locator. */
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
diff --git a/src/validationinterface.h b/src/validationinterface.h
index 56ea698a2e..63097166af 100644
--- a/src/validationinterface.h
+++ b/src/validationinterface.h
@@ -56,6 +56,11 @@ void SyncWithValidationInterfaceQueue();
class CValidationInterface {
protected:
/**
+ * Protected destructor so that instances can only be deleted by derived classes.
+ * If that restriction is no longer desired, this should be made public and virtual.
+ */
+ ~CValidationInterface() = default;
+ /**
* Notifies listeners of updated block chain tip
*
* Called on a background thread.
diff --git a/src/versionbits.cpp b/src/versionbits.cpp
index d2ee49db20..e3ec078173 100644
--- a/src/versionbits.cpp
+++ b/src/versionbits.cpp
@@ -29,7 +29,7 @@ ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex*
// Check if this deployment is always active.
if (nTimeStart == Consensus::BIP9Deployment::ALWAYS_ACTIVE) {
- return THRESHOLD_ACTIVE;
+ return ThresholdState::ACTIVE;
}
// A block's state is always the same as that of the first of its period, so it is computed based on a pindexPrev whose height equals a multiple of nPeriod - 1.
@@ -42,12 +42,12 @@ ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex*
while (cache.count(pindexPrev) == 0) {
if (pindexPrev == nullptr) {
// The genesis block is by definition defined.
- cache[pindexPrev] = THRESHOLD_DEFINED;
+ cache[pindexPrev] = ThresholdState::DEFINED;
break;
}
if (pindexPrev->GetMedianTimePast() < nTimeStart) {
// Optimization: don't recompute down further, as we know every earlier block will be before the start time
- cache[pindexPrev] = THRESHOLD_DEFINED;
+ cache[pindexPrev] = ThresholdState::DEFINED;
break;
}
vToCompute.push_back(pindexPrev);
@@ -65,17 +65,17 @@ ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex*
vToCompute.pop_back();
switch (state) {
- case THRESHOLD_DEFINED: {
+ case ThresholdState::DEFINED: {
if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) {
- stateNext = THRESHOLD_FAILED;
+ stateNext = ThresholdState::FAILED;
} else if (pindexPrev->GetMedianTimePast() >= nTimeStart) {
- stateNext = THRESHOLD_STARTED;
+ stateNext = ThresholdState::STARTED;
}
break;
}
- case THRESHOLD_STARTED: {
+ case ThresholdState::STARTED: {
if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) {
- stateNext = THRESHOLD_FAILED;
+ stateNext = ThresholdState::FAILED;
break;
}
// We need to count
@@ -88,17 +88,17 @@ ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex*
pindexCount = pindexCount->pprev;
}
if (count >= nThreshold) {
- stateNext = THRESHOLD_LOCKED_IN;
+ stateNext = ThresholdState::LOCKED_IN;
}
break;
}
- case THRESHOLD_LOCKED_IN: {
+ case ThresholdState::LOCKED_IN: {
// Always progresses into ACTIVE.
- stateNext = THRESHOLD_ACTIVE;
+ stateNext = ThresholdState::ACTIVE;
break;
}
- case THRESHOLD_FAILED:
- case THRESHOLD_ACTIVE: {
+ case ThresholdState::FAILED:
+ case ThresholdState::ACTIVE: {
// Nothing happens, these are terminal states.
break;
}
@@ -149,7 +149,7 @@ int AbstractThresholdConditionChecker::GetStateSinceHeightFor(const CBlockIndex*
const ThresholdState initialState = GetStateFor(pindexPrev, params, cache);
// BIP 9 about state DEFINED: "The genesis block is by definition in this state for each deployment."
- if (initialState == THRESHOLD_DEFINED) {
+ if (initialState == ThresholdState::DEFINED) {
return 0;
}
diff --git a/src/versionbits.h b/src/versionbits.h
index 1600dc8c93..8962a65057 100644
--- a/src/versionbits.h
+++ b/src/versionbits.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_CONSENSUS_VERSIONBITS
-#define BITCOIN_CONSENSUS_VERSIONBITS
+#ifndef BITCOIN_VERSIONBITS_H
+#define BITCOIN_VERSIONBITS_H
#include <chain.h>
#include <map>
@@ -17,12 +17,12 @@ static const int32_t VERSIONBITS_TOP_MASK = 0xE0000000UL;
/** Total bits available for versionbits */
static const int32_t VERSIONBITS_NUM_BITS = 29;
-enum ThresholdState {
- THRESHOLD_DEFINED,
- THRESHOLD_STARTED,
- THRESHOLD_LOCKED_IN,
- THRESHOLD_ACTIVE,
- THRESHOLD_FAILED,
+enum class ThresholdState {
+ DEFINED,
+ STARTED,
+ LOCKED_IN,
+ ACTIVE,
+ FAILED,
};
// A map that gives the state for blocks whose height is a multiple of Period().
@@ -77,4 +77,4 @@ BIP9Stats VersionBitsStatistics(const CBlockIndex* pindexPrev, const Consensus::
int VersionBitsStateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, VersionBitsCache& cache);
uint32_t VersionBitsMask(const Consensus::Params& params, Consensus::DeploymentPos pos);
-#endif
+#endif // BITCOIN_VERSIONBITS_H
diff --git a/src/wallet/coincontrol.h b/src/wallet/coincontrol.h
index 458e770e03..52d6a291c9 100644
--- a/src/wallet/coincontrol.h
+++ b/src/wallet/coincontrol.h
@@ -18,8 +18,8 @@ class CCoinControl
public:
//! Custom change destination, if not set an address is generated
CTxDestination destChange;
- //! Custom change type, ignored if destChange is set, defaults to g_change_type
- OutputType change_type;
+ //! Override the default change type if set, ignored if destChange is set
+ boost::optional<OutputType> m_change_type;
//! If false, allows unselected inputs, but requires all selected inputs be used
bool fAllowOtherInputs;
//! Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria
@@ -43,7 +43,7 @@ public:
void SetNull()
{
destChange = CNoDestination();
- change_type = g_change_type;
+ m_change_type.reset();
fAllowOtherInputs = false;
fAllowWatchOnly = false;
setSelected.clear();
diff --git a/src/wallet/coinselection.cpp b/src/wallet/coinselection.cpp
new file mode 100644
index 0000000000..8596ad2adc
--- /dev/null
+++ b/src/wallet/coinselection.cpp
@@ -0,0 +1,300 @@
+// Copyright (c) 2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include <wallet/coinselection.h>
+#include <util.h>
+#include <utilmoneystr.h>
+
+// Descending order comparator
+struct {
+ bool operator()(const CInputCoin& a, const CInputCoin& b) const
+ {
+ return a.effective_value > b.effective_value;
+ }
+} descending;
+
+/*
+ * This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input
+ * set that can pay for the spending target and does not exceed the spending target by more than the
+ * cost of creating and spending a change output. The algorithm uses a depth-first search on a binary
+ * tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs
+ * are sorted by their effective values and the trees is explored deterministically per the inclusion
+ * branch first. At each node, the algorithm checks whether the selection is within the target range.
+ * While the selection has not reached the target range, more UTXOs are included. When a selection's
+ * value exceeds the target range, the complete subtree deriving from this selection can be omitted.
+ * At that point, the last included UTXO is deselected and the corresponding omission branch explored
+ * instead. The search ends after the complete tree has been searched or after a limited number of tries.
+ *
+ * The search continues to search for better solutions after one solution has been found. The best
+ * solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to
+ * spend the current inputs at the given fee rate minus the long term expected cost to spend the
+ * inputs, plus the amount the selection exceeds the spending target:
+ *
+ * waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate)
+ *
+ * The algorithm uses two additional optimizations. A lookahead keeps track of the total value of
+ * the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range
+ * cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us
+ * to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted
+ * predecessor.
+ *
+ * The Branch and Bound algorithm is described in detail in Murch's Master Thesis:
+ * https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf
+ *
+ * @param const std::vector<CInputCoin>& utxo_pool The set of UTXOs that we are choosing from.
+ * These UTXOs will be sorted in descending order by effective value and the CInputCoins'
+ * values are their effective values.
+ * @param const CAmount& target_value This is the value that we want to select. It is the lower
+ * bound of the range.
+ * @param const CAmount& cost_of_change This is the cost of creating and spending a change output.
+ * This plus target_value is the upper bound of the range.
+ * @param std::set<CInputCoin>& out_set -> This is an output parameter for the set of CInputCoins
+ * that have been selected.
+ * @param CAmount& value_ret -> This is an output parameter for the total value of the CInputCoins
+ * that were selected.
+ * @param CAmount not_input_fees -> The fees that need to be paid for the outputs and fixed size
+ * overhead (version, locktime, marker and flag)
+ */
+
+static const size_t TOTAL_TRIES = 100000;
+
+bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees)
+{
+ out_set.clear();
+ CAmount curr_value = 0;
+
+ std::vector<bool> curr_selection; // select the utxo at this index
+ curr_selection.reserve(utxo_pool.size());
+ CAmount actual_target = not_input_fees + target_value;
+
+ // Calculate curr_available_value
+ CAmount curr_available_value = 0;
+ for (const CInputCoin& utxo : utxo_pool) {
+ // Assert that this utxo is not negative. It should never be negative, effective value calculation should have removed it
+ assert(utxo.effective_value > 0);
+ curr_available_value += utxo.effective_value;
+ }
+ if (curr_available_value < actual_target) {
+ return false;
+ }
+
+ // Sort the utxo_pool
+ std::sort(utxo_pool.begin(), utxo_pool.end(), descending);
+
+ CAmount curr_waste = 0;
+ std::vector<bool> best_selection;
+ CAmount best_waste = MAX_MONEY;
+
+ // Depth First search loop for choosing the UTXOs
+ for (size_t i = 0; i < TOTAL_TRIES; ++i) {
+ // Conditions for starting a backtrack
+ bool backtrack = false;
+ if (curr_value + curr_available_value < actual_target || // Cannot possibly reach target with the amount remaining in the curr_available_value.
+ curr_value > actual_target + cost_of_change || // Selected value is out of range, go back and try other branch
+ (curr_waste > best_waste && (utxo_pool.at(0).fee - utxo_pool.at(0).long_term_fee) > 0)) { // Don't select things which we know will be more wasteful if the waste is increasing
+ backtrack = true;
+ } else if (curr_value >= actual_target) { // Selected value is within range
+ curr_waste += (curr_value - actual_target); // This is the excess value which is added to the waste for the below comparison
+ // Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee.
+ // However we are not going to explore that because this optimization for the waste is only done when we have hit our target
+ // value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to
+ // explore any more UTXOs to avoid burning money like that.
+ if (curr_waste <= best_waste) {
+ best_selection = curr_selection;
+ best_selection.resize(utxo_pool.size());
+ best_waste = curr_waste;
+ }
+ curr_waste -= (curr_value - actual_target); // Remove the excess value as we will be selecting different coins now
+ backtrack = true;
+ }
+
+ // Backtracking, moving backwards
+ if (backtrack) {
+ // Walk backwards to find the last included UTXO that still needs to have its omission branch traversed.
+ while (!curr_selection.empty() && !curr_selection.back()) {
+ curr_selection.pop_back();
+ curr_available_value += utxo_pool.at(curr_selection.size()).effective_value;
+ };
+
+ if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
+ break;
+ }
+
+ // Output was included on previous iterations, try excluding now.
+ curr_selection.back() = false;
+ CInputCoin& utxo = utxo_pool.at(curr_selection.size() - 1);
+ curr_value -= utxo.effective_value;
+ curr_waste -= utxo.fee - utxo.long_term_fee;
+ } else { // Moving forwards, continuing down this branch
+ CInputCoin& utxo = utxo_pool.at(curr_selection.size());
+
+ // Remove this utxo from the curr_available_value utxo amount
+ curr_available_value -= utxo.effective_value;
+
+ // Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded. Since the ratio of fee to
+ // long term fee is the same, we only need to check if one of those values match in order to know that the waste is the same.
+ if (!curr_selection.empty() && !curr_selection.back() &&
+ utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value &&
+ utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) {
+ curr_selection.push_back(false);
+ } else {
+ // Inclusion branch first (Largest First Exploration)
+ curr_selection.push_back(true);
+ curr_value += utxo.effective_value;
+ curr_waste += utxo.fee - utxo.long_term_fee;
+ }
+ }
+ }
+
+ // Check for solution
+ if (best_selection.empty()) {
+ return false;
+ }
+
+ // Set output set
+ value_ret = 0;
+ for (size_t i = 0; i < best_selection.size(); ++i) {
+ if (best_selection.at(i)) {
+ out_set.insert(utxo_pool.at(i));
+ value_ret += utxo_pool.at(i).txout.nValue;
+ }
+ }
+
+ return true;
+}
+
+static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
+ std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
+{
+ std::vector<char> vfIncluded;
+
+ vfBest.assign(vValue.size(), true);
+ nBest = nTotalLower;
+
+ FastRandomContext insecure_rand;
+
+ for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
+ {
+ vfIncluded.assign(vValue.size(), false);
+ CAmount nTotal = 0;
+ bool fReachedTarget = false;
+ for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
+ {
+ for (unsigned int i = 0; i < vValue.size(); i++)
+ {
+ //The solver here uses a randomized algorithm,
+ //the randomness serves no real security purpose but is just
+ //needed to prevent degenerate behavior and it is important
+ //that the rng is fast. We do not use a constant random sequence,
+ //because there may be some privacy improvement by making
+ //the selection random.
+ if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
+ {
+ nTotal += vValue[i].txout.nValue;
+ vfIncluded[i] = true;
+ if (nTotal >= nTargetValue)
+ {
+ fReachedTarget = true;
+ if (nTotal < nBest)
+ {
+ nBest = nTotal;
+ vfBest = vfIncluded;
+ }
+ nTotal -= vValue[i].txout.nValue;
+ vfIncluded[i] = false;
+ }
+ }
+ }
+ }
+ }
+}
+
+bool KnapsackSolver(const CAmount& nTargetValue, std::vector<CInputCoin>& vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)
+{
+ setCoinsRet.clear();
+ nValueRet = 0;
+
+ // List of values less than target
+ boost::optional<CInputCoin> coinLowestLarger;
+ std::vector<CInputCoin> vValue;
+ CAmount nTotalLower = 0;
+
+ random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
+
+ for (const CInputCoin &coin : vCoins)
+ {
+ if (coin.txout.nValue == nTargetValue)
+ {
+ setCoinsRet.insert(coin);
+ nValueRet += coin.txout.nValue;
+ return true;
+ }
+ else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
+ {
+ vValue.push_back(coin);
+ nTotalLower += coin.txout.nValue;
+ }
+ else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
+ {
+ coinLowestLarger = coin;
+ }
+ }
+
+ if (nTotalLower == nTargetValue)
+ {
+ for (const auto& input : vValue)
+ {
+ setCoinsRet.insert(input);
+ nValueRet += input.txout.nValue;
+ }
+ return true;
+ }
+
+ if (nTotalLower < nTargetValue)
+ {
+ if (!coinLowestLarger)
+ return false;
+ setCoinsRet.insert(coinLowestLarger.get());
+ nValueRet += coinLowestLarger->txout.nValue;
+ return true;
+ }
+
+ // Solve subset sum by stochastic approximation
+ std::sort(vValue.begin(), vValue.end(), descending);
+ std::vector<char> vfBest;
+ CAmount nBest;
+
+ ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
+ if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
+ ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
+
+ // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
+ // or the next bigger coin is closer), return the bigger coin
+ if (coinLowestLarger &&
+ ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
+ {
+ setCoinsRet.insert(coinLowestLarger.get());
+ nValueRet += coinLowestLarger->txout.nValue;
+ }
+ else {
+ for (unsigned int i = 0; i < vValue.size(); i++)
+ if (vfBest[i])
+ {
+ setCoinsRet.insert(vValue[i]);
+ nValueRet += vValue[i].txout.nValue;
+ }
+
+ if (LogAcceptCategory(BCLog::SELECTCOINS)) {
+ LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
+ for (unsigned int i = 0; i < vValue.size(); i++) {
+ if (vfBest[i]) {
+ LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
+ }
+ }
+ LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
+ }
+ }
+
+ return true;
+}
diff --git a/src/wallet/coinselection.h b/src/wallet/coinselection.h
new file mode 100644
index 0000000000..2b185879c6
--- /dev/null
+++ b/src/wallet/coinselection.h
@@ -0,0 +1,54 @@
+// Copyright (c) 2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_WALLET_COINSELECTION_H
+#define BITCOIN_WALLET_COINSELECTION_H
+
+#include <amount.h>
+#include <primitives/transaction.h>
+#include <random.h>
+
+//! target minimum change amount
+static const CAmount MIN_CHANGE = CENT;
+//! final minimum change amount after paying for fees
+static const CAmount MIN_FINAL_CHANGE = MIN_CHANGE/2;
+
+class CInputCoin {
+public:
+ CInputCoin(const CTransactionRef& tx, unsigned int i)
+ {
+ if (!tx)
+ throw std::invalid_argument("tx should not be null");
+ if (i >= tx->vout.size())
+ throw std::out_of_range("The output index is out of range");
+
+ outpoint = COutPoint(tx->GetHash(), i);
+ txout = tx->vout[i];
+ effective_value = txout.nValue;
+ }
+
+ COutPoint outpoint;
+ CTxOut txout;
+ CAmount effective_value;
+ CAmount fee = 0;
+ CAmount long_term_fee = 0;
+
+ bool operator<(const CInputCoin& rhs) const {
+ return outpoint < rhs.outpoint;
+ }
+
+ bool operator!=(const CInputCoin& rhs) const {
+ return outpoint != rhs.outpoint;
+ }
+
+ bool operator==(const CInputCoin& rhs) const {
+ return outpoint == rhs.outpoint;
+ }
+};
+
+bool SelectCoinsBnB(std::vector<CInputCoin>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees);
+
+// Original coin selection algorithm as a fallback
+bool KnapsackSolver(const CAmount& nTargetValue, std::vector<CInputCoin>& vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet);
+#endif // BITCOIN_WALLET_COINSELECTION_H
diff --git a/src/wallet/crypter.h b/src/wallet/crypter.h
index f3ae7144b4..fdeb4cfee0 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 wallet_crypto
+namespace crypto_tests
{
class TestCrypter;
}
@@ -75,7 +75,7 @@ namespace wallet_crypto
/** Encryption/decryption context with key information */
class CCrypter
{
-friend class wallet_crypto::TestCrypter; // for test access to chKey/chIV
+friend class 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 ebe7b48da0..553cae4d02 100644
--- a/src/wallet/db.cpp
+++ b/src/wallet/db.cpp
@@ -235,13 +235,13 @@ CDBEnv::VerifyResult CDBEnv::Verify(const std::string& strFile, recoverFunc_type
Db db(dbenv.get(), 0);
int result = db.verify(strFile.c_str(), nullptr, nullptr, 0);
if (result == 0)
- return VERIFY_OK;
+ return VerifyResult::VERIFY_OK;
else if (recoverFunc == nullptr)
- return RECOVER_FAIL;
+ return VerifyResult::RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(fs::path(strPath) / strFile, out_backup_filename);
- return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
+ 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)
@@ -347,7 +347,7 @@ bool CDB::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr,
{
std::string backup_filename;
CDBEnv::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename);
- if (r == CDBEnv::RECOVER_OK)
+ if (r == CDBEnv::VerifyResult::RECOVER_OK)
{
warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!"
" Original %s saved as %s in %s; if"
@@ -355,7 +355,7 @@ bool CDB::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr,
" restore from a backup."),
walletFile, backup_filename, walletDir);
}
- if (r == CDBEnv::RECOVER_FAIL)
+ if (r == CDBEnv::VerifyResult::RECOVER_FAIL)
{
errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile);
return false;
diff --git a/src/wallet/db.h b/src/wallet/db.h
index b1ce451534..49a9f3f082 100644
--- a/src/wallet/db.h
+++ b/src/wallet/db.h
@@ -16,6 +16,7 @@
#include <atomic>
#include <map>
+#include <memory>
#include <string>
#include <vector>
@@ -53,7 +54,7 @@ public:
* This must be called BEFORE strFile is opened.
* Returns true if strFile is OK.
*/
- enum VerifyResult { VERIFY_OK,
+ enum class VerifyResult { VERIFY_OK,
RECOVER_OK,
RECOVER_FAIL };
typedef bool (*recoverFunc_type)(const fs::path& file_path, std::string& out_backup_filename);
diff --git a/src/wallet/feebumper.cpp b/src/wallet/feebumper.cpp
index 9cae660c60..82a5017de0 100644
--- a/src/wallet/feebumper.cpp
+++ b/src/wallet/feebumper.cpp
@@ -16,33 +16,6 @@
#include <util.h>
#include <net.h>
-// Calculate the size of the transaction assuming all signatures are max size
-// Use DummySignatureCreator, which inserts 72 byte signatures everywhere.
-// TODO: re-use this in CWallet::CreateTransaction (right now
-// CreateTransaction uses the constructed dummy-signed tx to do a priority
-// calculation, but we should be able to refactor after priority is removed).
-// NOTE: this requires that all inputs must be in mapWallet (eg the tx should
-// be IsAllFromMe).
-static int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet)
-{
- CMutableTransaction txNew(tx);
- std::vector<CInputCoin> vCoins;
- // Look up the inputs. We should have already checked that this transaction
- // IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our
- // wallet, with a valid index into the vout array.
- for (auto& input : tx.vin) {
- const auto mi = wallet->mapWallet.find(input.prevout.hash);
- assert(mi != wallet->mapWallet.end() && input.prevout.n < mi->second.tx->vout.size());
- vCoins.emplace_back(CInputCoin(&(mi->second), input.prevout.n));
- }
- if (!wallet->DummySignTx(txNew, vCoins)) {
- // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
- // implies that we can sign for every input.
- return -1;
- }
- return GetVirtualTransactionSize(txNew);
-}
-
//! Check whether transaction has descendant in wallet or mempool, or has been
//! mined, or conflicts with a mined transaction. Return a feebumper::Result.
static feebumper::Result PreconditionChecks(const CWallet* wallet, const CWalletTx& wtx, std::vector<std::string>& errors)
@@ -262,23 +235,20 @@ Result CommitTransaction(CWallet* wallet, const uint256& txid, CMutableTransacti
return result;
}
- CWalletTx wtxBumped(wallet, MakeTransactionRef(std::move(mtx)));
// commit/broadcast the tx
+ CTransactionRef tx = MakeTransactionRef(std::move(mtx));
+ mapValue_t mapValue = oldWtx.mapValue;
+ mapValue["replaces_txid"] = oldWtx.GetHash().ToString();
+
CReserveKey reservekey(wallet);
- wtxBumped.mapValue = oldWtx.mapValue;
- wtxBumped.mapValue["replaces_txid"] = oldWtx.GetHash().ToString();
- wtxBumped.vOrderForm = oldWtx.vOrderForm;
- wtxBumped.strFromAccount = oldWtx.strFromAccount;
- wtxBumped.fTimeReceivedIsTxTime = true;
- wtxBumped.fFromMe = true;
CValidationState state;
- if (!wallet->CommitTransaction(wtxBumped, reservekey, g_connman.get(), state)) {
+ if (!wallet->CommitTransaction(tx, std::move(mapValue), oldWtx.vOrderForm, oldWtx.strFromAccount, reservekey, g_connman.get(), state)) {
// NOTE: CommitTransaction never returns false, so this should never happen.
errors.push_back(strprintf("The transaction was rejected: %s", FormatStateMessage(state)));
return Result::WALLET_ERROR;
}
- bumped_txid = wtxBumped.GetHash();
+ bumped_txid = tx->GetHash();
if (state.IsInvalid()) {
// This can happen if the mempool rejected the transaction. Report
// what happened in the "errors" response.
@@ -286,7 +256,7 @@ Result CommitTransaction(CWallet* wallet, const uint256& txid, CMutableTransacti
}
// mark the original tx as bumped
- if (!wallet->MarkReplaced(oldWtx.GetHash(), wtxBumped.GetHash())) {
+ if (!wallet->MarkReplaced(oldWtx.GetHash(), bumped_txid)) {
// TODO: see if JSON-RPC has a standard way of returning a response
// along with an exception. It would be good to return information about
// wtxBumped to the caller even if marking the original transaction
diff --git a/src/wallet/fees.cpp b/src/wallet/fees.cpp
index 385fdc963a..03c32d3b97 100644
--- a/src/wallet/fees.cpp
+++ b/src/wallet/fees.cpp
@@ -21,6 +21,22 @@ CAmount GetRequiredFee(unsigned int nTxBytes)
CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
{
+ CAmount fee_needed = GetMinimumFeeRate(coin_control, pool, estimator, feeCalc).GetFee(nTxBytes);
+ // Always obey the maximum
+ if (fee_needed > maxTxFee) {
+ fee_needed = maxTxFee;
+ if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
+ }
+ return fee_needed;
+}
+
+CFeeRate GetRequiredFeeRate()
+{
+ return std::max(CWallet::minTxFee, ::minRelayTxFee);
+}
+
+CFeeRate GetMinimumFeeRate(const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
+{
/* User control of how to calculate fee uses the following parameter precedence:
1. coin_control.m_feerate
2. coin_control.m_confirm_target
@@ -28,15 +44,15 @@ CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, c
4. nTxConfirmTarget (user-set global variable)
The first parameter that is set is used.
*/
- CAmount fee_needed;
+ CFeeRate feerate_needed ;
if (coin_control.m_feerate) { // 1.
- fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
+ feerate_needed = *(coin_control.m_feerate);
if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
// Allow to override automatic min/max check over coin control instance
- if (coin_control.fOverrideFeeRate) return fee_needed;
+ if (coin_control.fOverrideFeeRate) return feerate_needed;
}
else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
- fee_needed = ::payTxFee.GetFee(nTxBytes);
+ feerate_needed = ::payTxFee;
if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
}
else { // 2. or 4.
@@ -48,38 +64,32 @@ CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, c
if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
- fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
- if (fee_needed == 0) {
+ feerate_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate);
+ if (feerate_needed == CFeeRate(0)) {
// if we don't have enough data for estimateSmartFee, then use fallbackFee
- fee_needed = CWallet::fallbackFee.GetFee(nTxBytes);
+ feerate_needed = CWallet::fallbackFee;
if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
// directly return if fallback fee is disabled (feerate 0 == disabled)
- if (CWallet::fallbackFee.GetFee(1000) == 0) return fee_needed;
+ if (CWallet::fallbackFee == CFeeRate(0)) return feerate_needed;
}
// Obey mempool min fee when using smart fee estimation
- CAmount min_mempool_fee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
- if (fee_needed < min_mempool_fee) {
- fee_needed = min_mempool_fee;
+ CFeeRate min_mempool_feerate = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
+ if (feerate_needed < min_mempool_feerate) {
+ feerate_needed = min_mempool_feerate;
if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
}
}
// prevent user from paying a fee below minRelayTxFee or minTxFee
- CAmount required_fee = GetRequiredFee(nTxBytes);
- if (required_fee > fee_needed) {
- fee_needed = required_fee;
+ CFeeRate required_feerate = GetRequiredFeeRate();
+ if (required_feerate > feerate_needed) {
+ feerate_needed = required_feerate;
if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
}
- // But always obey the maximum
- if (fee_needed > maxTxFee) {
- fee_needed = maxTxFee;
- if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
- }
- return fee_needed;
+ return feerate_needed;
}
-
CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
{
unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
diff --git a/src/wallet/fees.h b/src/wallet/fees.h
index 225aff08ad..a627af70b0 100644
--- a/src/wallet/fees.h
+++ b/src/wallet/fees.h
@@ -27,6 +27,18 @@ CAmount GetRequiredFee(unsigned int nTxBytes);
CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc);
/**
+ * Return the minimum required feerate taking into account the
+ * floating relay feerate and user set minimum transaction feerate
+ */
+CFeeRate GetRequiredFeeRate();
+
+/**
+ * Estimate the minimum fee rate considering user set parameters
+ * and the required fee
+ */
+CFeeRate GetMinimumFeeRate(const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc);
+
+/**
* Return the maximum feerate for discarding change.
*/
CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator);
diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp
index e028cf4210..c860eede05 100644
--- a/src/wallet/init.cpp
+++ b/src/wallet/init.cpp
@@ -3,21 +3,57 @@
// 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>
-std::string GetWalletHelpString(bool showDebug)
+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:"));
- strUsage += HelpMessageOpt("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(OUTPUT_TYPE_DEFAULT)));
+ strUsage += HelpMessageOpt("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)));
strUsage += HelpMessageOpt("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)");
strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
@@ -56,7 +92,7 @@ std::string GetWalletHelpString(bool showDebug)
return strUsage;
}
-bool WalletParameterInteraction()
+bool WalletInit::ParameterInteraction()
{
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
for (const std::string& wallet : gArgs.GetArgs("-wallet")) {
@@ -181,22 +217,10 @@ bool WalletParameterInteraction()
bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
- g_address_type = ParseOutputType(gArgs.GetArg("-addresstype", ""));
- if (g_address_type == OUTPUT_TYPE_NONE) {
- return InitError(strprintf("Unknown address type '%s'", gArgs.GetArg("-addresstype", "")));
- }
-
- // If changetype is set in config file or parameter, check that it's valid.
- // Default to OUTPUT_TYPE_NONE if not set.
- g_change_type = ParseOutputType(gArgs.GetArg("-changetype", ""), OUTPUT_TYPE_NONE);
- if (g_change_type == OUTPUT_TYPE_NONE && !gArgs.GetArg("-changetype", "").empty()) {
- return InitError(strprintf("Unknown change type '%s'", gArgs.GetArg("-changetype", "")));
- }
-
return true;
}
-void RegisterWalletRPC(CRPCTable &t)
+void WalletInit::RegisterRPC(CRPCTable &t)
{
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
return;
@@ -205,7 +229,7 @@ void RegisterWalletRPC(CRPCTable &t)
RegisterWalletRPCCommands(t);
}
-bool VerifyWallets()
+bool WalletInit::Verify()
{
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
return true;
@@ -280,7 +304,7 @@ bool VerifyWallets()
return true;
}
-bool OpenWallets()
+bool WalletInit::Open()
{
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
LogPrintf("Wallet disabled!\n");
@@ -298,25 +322,29 @@ bool OpenWallets()
return true;
}
-void StartWallets(CScheduler& scheduler) {
+void WalletInit::Start(CScheduler& scheduler)
+{
for (CWalletRef pwallet : vpwallets) {
pwallet->postInitProcess(scheduler);
}
}
-void FlushWallets() {
+void WalletInit::Flush()
+{
for (CWalletRef pwallet : vpwallets) {
pwallet->Flush(false);
}
}
-void StopWallets() {
+void WalletInit::Stop()
+{
for (CWalletRef pwallet : vpwallets) {
pwallet->Flush(true);
}
}
-void CloseWallets() {
+void WalletInit::Close()
+{
for (CWalletRef pwallet : vpwallets) {
delete pwallet;
}
diff --git a/src/wallet/init.h b/src/wallet/init.h
deleted file mode 100644
index 0b3ee2dda2..0000000000
--- a/src/wallet/init.h
+++ /dev/null
@@ -1,43 +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 <string>
-
-class CRPCTable;
-class CScheduler;
-
-//! Return the wallets help message.
-std::string GetWalletHelpString(bool showDebug);
-
-//! Wallets parameter interaction
-bool WalletParameterInteraction();
-
-//! Register wallet RPCs.
-void RegisterWalletRPC(CRPCTable &tableRPC);
-
-//! 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 VerifyWallets();
-
-//! Load wallet databases.
-bool OpenWallets();
-
-//! Complete startup of wallets.
-void StartWallets(CScheduler& scheduler);
-
-//! Flush all wallets in preparation for shutdown.
-void FlushWallets();
-
-//! Stop all wallets. Wallets will be flushed first.
-void StopWallets();
-
-//! Close all wallets.
-void CloseWallets();
-
-#endif // BITCOIN_WALLET_INIT_H
diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp
index 0edc8d8d66..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>
@@ -28,10 +27,6 @@
#include <univalue.h>
-std::string static EncodeDumpTime(int64_t nTime) {
- return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
-}
-
int64_t static DecodeDumpTime(const std::string &str) {
static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
static const std::locale loc(std::locale::classic(),
@@ -87,7 +82,7 @@ bool GetWalletAddressesForKey(CWallet * const pwallet, const CKeyID &keyid, std:
}
}
if (!fLabelFound) {
- strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), g_address_type));
+ strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), pwallet->m_default_address_type));
}
return fLabelFound;
}
@@ -104,6 +99,7 @@ UniValue importprivkey(const JSONRPCRequest& request)
throw std::runtime_error(
"importprivkey \"privkey\" ( \"label\" ) ( rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n"
+ "Hint: use importmulti to import more than one private key.\n"
"\nArguments:\n"
"1. \"privkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
@@ -354,9 +350,10 @@ UniValue importprunedfunds(const JSONRPCRequest& request)
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
LOCK(cs_main);
-
- if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
+ const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash());
+ if (!pindex || !chainActive.Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
+ }
std::vector<uint256>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
@@ -409,7 +406,7 @@ UniValue removeprunedfunds(const JSONRPCRequest& request)
vHash.push_back(hash);
std::vector<uint256> vHashOut;
- if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
+ if (pwallet->ZapSelectTx(vHash, vHashOut) != DBErrors::LOAD_OK) {
throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction.");
}
@@ -722,9 +719,9 @@ UniValue dumpwallet(const JSONRPCRequest& request)
// produce output
file << strprintf("# Wallet dump created by Bitcoin %s\n", CLIENT_BUILD);
- file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
+ file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
- file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
+ file << strprintf("# mined on %s\n", FormatISO8601DateTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
// add the base58check encoded extended master if the wallet uses HD
@@ -741,7 +738,7 @@ UniValue dumpwallet(const JSONRPCRequest& request)
}
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
- std::string strTime = EncodeDumpTime(it->first);
+ std::string strTime = FormatISO8601DateTime(it->first);
std::string strAddr;
std::string strLabel;
CKey key;
@@ -769,7 +766,7 @@ UniValue dumpwallet(const JSONRPCRequest& request)
// get birth times for scripts with metadata
auto it = pwallet->m_script_metadata.find(scriptid);
if (it != pwallet->m_script_metadata.end()) {
- create_time = EncodeDumpTime(it->second.nCreateTime);
+ create_time = FormatISO8601DateTime(it->second.nCreateTime);
}
if(pwallet->GetCScript(scriptid, script)) {
file << strprintf("%s %s script=1", HexStr(script.begin(), script.end()), create_time);
diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
index 457abec1bc..c34b166a41 100644
--- a/src/wallet/rpcwallet.cpp
+++ b/src/wallet/rpcwallet.cpp
@@ -95,7 +95,7 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
entry.pushKV("blockhash", wtx.hashBlock.GetHex());
entry.pushKV("blockindex", wtx.nIndex);
- entry.pushKV("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime());
+ entry.pushKV("blocktime", LookupBlockIndex(wtx.hashBlock)->GetBlockTime());
} else {
entry.pushKV("trusted", wtx.IsTrusted());
}
@@ -113,9 +113,9 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
if (confirms <= 0) {
LOCK(mempool.cs);
RBFTransactionState rbfState = IsRBFOptIn(*wtx.tx, mempool);
- if (rbfState == RBF_TRANSACTIONSTATE_UNKNOWN)
+ if (rbfState == RBFTransactionState::UNKNOWN)
rbfStatus = "unknown";
- else if (rbfState == RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125)
+ else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125)
rbfStatus = "yes";
}
entry.pushKV("bip125-replaceable", rbfStatus);
@@ -124,12 +124,12 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
entry.pushKV(item.first, item.second);
}
-std::string AccountFromValue(const UniValue& value)
+std::string LabelFromValue(const UniValue& value)
{
- std::string strAccount = value.get_str();
- if (strAccount == "*")
- throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
- return strAccount;
+ std::string label = value.get_str();
+ if (label == "*")
+ throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, "Invalid label name");
+ return label;
}
UniValue getnewaddress(const JSONRPCRequest& request)
@@ -141,12 +141,12 @@ UniValue getnewaddress(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
- "getnewaddress ( \"account\" \"address_type\" )\n"
+ "getnewaddress ( \"label\" \"address_type\" )\n"
"\nReturns a new Bitcoin address for receiving payments.\n"
- "If 'account' is specified (DEPRECATED), it is added to the address book \n"
- "so payments received with the address will be credited to 'account'.\n"
+ "If 'label' is specified, it is added to the address book \n"
+ "so payments received with the address will be associated with 'label'.\n"
"\nArguments:\n"
- "1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
+ "1. \"label\" (string, optional) The label name for the address to be linked to. If not provided, the default label \"\" is used. It can also be set to the empty string \"\" to represent the default label. The label does not need to exist, it will be created if there is no label by the given name.\n"
"2. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -addresstype.\n"
"\nResult:\n"
"\"address\" (string) The new bitcoin address\n"
@@ -157,15 +157,15 @@ UniValue getnewaddress(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- // Parse the account first so we don't generate a key if there's an error
- std::string strAccount;
+ // Parse the label first so we don't generate a key if there's an error
+ std::string label;
if (!request.params[0].isNull())
- strAccount = AccountFromValue(request.params[0]);
+ label = LabelFromValue(request.params[0]);
- OutputType output_type = g_address_type;
+ OutputType output_type = pwallet->m_default_address_type;
if (!request.params[1].isNull()) {
- output_type = ParseOutputType(request.params[1].get_str(), g_address_type);
- if (output_type == OUTPUT_TYPE_NONE) {
+ output_type = ParseOutputType(request.params[1].get_str(), pwallet->m_default_address_type);
+ if (output_type == OutputType::NONE) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[1].get_str()));
}
}
@@ -182,23 +182,23 @@ UniValue getnewaddress(const JSONRPCRequest& request)
pwallet->LearnRelatedScripts(newKey, output_type);
CTxDestination dest = GetDestinationForKey(newKey, output_type);
- pwallet->SetAddressBook(dest, strAccount, "receive");
+ pwallet->SetAddressBook(dest, label, "receive");
return EncodeDestination(dest);
}
-CTxDestination GetAccountDestination(CWallet* const pwallet, std::string strAccount, bool bForceNew=false)
+CTxDestination GetLabelDestination(CWallet* const pwallet, const std::string& label, bool bForceNew=false)
{
CTxDestination dest;
- if (!pwallet->GetAccountDestination(dest, strAccount, bForceNew)) {
+ if (!pwallet->GetLabelDestination(dest, label, bForceNew)) {
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
}
return dest;
}
-UniValue getaccountaddress(const JSONRPCRequest& request)
+UniValue getlabeladdress(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
@@ -207,27 +207,27 @@ UniValue getaccountaddress(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
- "getaccountaddress \"account\"\n"
- "\nDEPRECATED. Returns the current Bitcoin address for receiving payments to this account.\n"
+ "getlabeladdress \"label\"\n"
+ "\nReturns the current Bitcoin address for receiving payments to this label.\n"
"\nArguments:\n"
- "1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
+ "1. \"label\" (string, required) The label name for the address. It can also be set to the empty string \"\" to represent the default label. The label does not need to exist, it will be created and a new address created if there is no label by the given name.\n"
"\nResult:\n"
- "\"address\" (string) The account bitcoin address\n"
+ "\"address\" (string) The label bitcoin address\n"
"\nExamples:\n"
- + HelpExampleCli("getaccountaddress", "")
- + HelpExampleCli("getaccountaddress", "\"\"")
- + HelpExampleCli("getaccountaddress", "\"myaccount\"")
- + HelpExampleRpc("getaccountaddress", "\"myaccount\"")
+ + HelpExampleCli("getlabeladdress", "")
+ + HelpExampleCli("getlabeladdress", "\"\"")
+ + HelpExampleCli("getlabeladdress", "\"mylabel\"")
+ + HelpExampleRpc("getlabeladdress", "\"mylabel\"")
);
LOCK2(cs_main, pwallet->cs_wallet);
- // Parse the account first so we don't generate a key if there's an error
- std::string strAccount = AccountFromValue(request.params[0]);
+ // Parse the label first so we don't generate a key if there's an error
+ std::string label = LabelFromValue(request.params[0]);
UniValue ret(UniValue::VSTR);
- ret = EncodeDestination(GetAccountDestination(pwallet, strAccount));
+ ret = EncodeDestination(GetLabelDestination(pwallet, label));
return ret;
}
@@ -259,10 +259,10 @@ UniValue getrawchangeaddress(const JSONRPCRequest& request)
pwallet->TopUpKeyPool();
}
- OutputType output_type = g_change_type != OUTPUT_TYPE_NONE ? g_change_type : g_address_type;
+ OutputType output_type = pwallet->m_default_change_type != OutputType::NONE ? pwallet->m_default_change_type : pwallet->m_default_address_type;
if (!request.params[0].isNull()) {
output_type = ParseOutputType(request.params[0].get_str(), output_type);
- if (output_type == OUTPUT_TYPE_NONE) {
+ if (output_type == OutputType::NONE) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
}
}
@@ -281,7 +281,7 @@ UniValue getrawchangeaddress(const JSONRPCRequest& request)
}
-UniValue setaccount(const JSONRPCRequest& request)
+UniValue setlabel(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
@@ -290,14 +290,14 @@ UniValue setaccount(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
- "setaccount \"address\" \"account\"\n"
- "\nDEPRECATED. Sets the account associated with the given address.\n"
+ "setlabel \"address\" \"label\"\n"
+ "\nSets the label associated with the given address.\n"
"\nArguments:\n"
- "1. \"address\" (string, required) The bitcoin address to be associated with an account.\n"
- "2. \"account\" (string, required) The account to assign the address to.\n"
+ "1. \"address\" (string, required) The bitcoin address to be associated with a label.\n"
+ "2. \"label\" (string, required) The label to assign the address to.\n"
"\nExamples:\n"
- + HelpExampleCli("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"tabby\"")
- + HelpExampleRpc("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"tabby\"")
+ + HelpExampleCli("setlabel", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"tabby\"")
+ + HelpExampleRpc("setlabel", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"tabby\"")
);
LOCK2(cs_main, pwallet->cs_wallet);
@@ -307,23 +307,23 @@ UniValue setaccount(const JSONRPCRequest& request)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
}
- std::string strAccount;
+ std::string label;
if (!request.params[1].isNull())
- strAccount = AccountFromValue(request.params[1]);
+ label = LabelFromValue(request.params[1]);
- // Only add the account if the address is yours.
+ // Only add the label if the address is yours.
if (IsMine(*pwallet, dest)) {
- // Detect when changing the account of an address that is the 'unused current key' of another account:
+ // Detect when changing the label of an address that is the 'unused current key' of another label:
if (pwallet->mapAddressBook.count(dest)) {
- std::string strOldAccount = pwallet->mapAddressBook[dest].name;
- if (dest == GetAccountDestination(pwallet, strOldAccount)) {
- GetAccountDestination(pwallet, strOldAccount, true);
+ std::string old_label = pwallet->mapAddressBook[dest].name;
+ if (dest == GetLabelDestination(pwallet, old_label)) {
+ GetLabelDestination(pwallet, old_label, true);
}
}
- pwallet->SetAddressBook(dest, strAccount, "receive");
+ pwallet->SetAddressBook(dest, label, "receive");
}
else
- throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
+ throw JSONRPCError(RPC_MISC_ERROR, "setlabel can only be used with own address");
return NullUniValue;
}
@@ -390,7 +390,7 @@ UniValue getaddressesbyaccount(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- std::string strAccount = AccountFromValue(request.params[0]);
+ std::string strAccount = LabelFromValue(request.params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
@@ -404,7 +404,7 @@ UniValue getaddressesbyaccount(const JSONRPCRequest& request)
return ret;
}
-static void SendMoney(CWallet * const pwallet, const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, const CCoinControl& coin_control)
+static CTransactionRef SendMoney(CWallet * const pwallet, const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, const CCoinControl& coin_control, mapValue_t mapValue, std::string fromAccount)
{
CAmount curBalance = pwallet->GetBalance();
@@ -430,16 +430,18 @@ static void SendMoney(CWallet * const pwallet, const CTxDestination &address, CA
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
- if (!pwallet->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError, coin_control)) {
+ CTransactionRef tx;
+ if (!pwallet->CreateTransaction(vecSend, tx, reservekey, nFeeRequired, nChangePosRet, strError, coin_control)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance)
strError = strprintf("Error: This transaction requires a transaction fee of at least %s", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
CValidationState state;
- if (!pwallet->CommitTransaction(wtxNew, reservekey, g_connman.get(), state)) {
+ if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, std::move(fromAccount), reservekey, g_connman.get(), state)) {
strError = strprintf("Error: The transaction was rejected! Reason given: %s", FormatStateMessage(state));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
+ return tx;
}
UniValue sendtoaddress(const JSONRPCRequest& request)
@@ -498,11 +500,11 @@ UniValue sendtoaddress(const JSONRPCRequest& request)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
- CWalletTx wtx;
+ mapValue_t mapValue;
if (!request.params[2].isNull() && !request.params[2].get_str().empty())
- wtx.mapValue["comment"] = request.params[2].get_str();
+ mapValue["comment"] = request.params[2].get_str();
if (!request.params[3].isNull() && !request.params[3].get_str().empty())
- wtx.mapValue["to"] = request.params[3].get_str();
+ mapValue["to"] = request.params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (!request.params[4].isNull()) {
@@ -527,9 +529,8 @@ UniValue sendtoaddress(const JSONRPCRequest& request)
EnsureWalletIsUnlocked(pwallet);
- SendMoney(pwallet, dest, nAmount, fSubtractFeeFromAmount, wtx, coin_control);
-
- return wtx.GetHash().GetHex();
+ CTransactionRef tx = SendMoney(pwallet, dest, nAmount, fSubtractFeeFromAmount, coin_control, std::move(mapValue), {} /* fromAccount */);
+ return tx->GetHash().GetHex();
}
UniValue listaddressgroupings(const JSONRPCRequest& request)
@@ -551,7 +552,7 @@ UniValue listaddressgroupings(const JSONRPCRequest& request)
" [\n"
" \"address\", (string) The bitcoin address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
- " \"account\" (string, optional) DEPRECATED. The account\n"
+ " \"label\" (string, optional) The label\n"
" ]\n"
" ,...\n"
" ]\n"
@@ -719,7 +720,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request)
}
-UniValue getreceivedbyaccount(const JSONRPCRequest& request)
+UniValue getreceivedbylabel(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
@@ -728,22 +729,22 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
- "getreceivedbyaccount \"account\" ( minconf )\n"
- "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
+ "getreceivedbylabel \"label\" ( minconf )\n"
+ "\nReturns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
- "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
+ "1. \"label\" (string, required) The selected label, may be the default label using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
- "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
+ "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this label.\n"
"\nExamples:\n"
- "\nAmount received by the default account with at least 1 confirmation\n"
- + HelpExampleCli("getreceivedbyaccount", "\"\"") +
- "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
- + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
+ "\nAmount received by the default label with at least 1 confirmation\n"
+ + HelpExampleCli("getreceivedbylabel", "\"\"") +
+ "\nAmount received at the tabby label including unconfirmed amounts with zero confirmations\n"
+ + HelpExampleCli("getreceivedbylabel", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmations\n"
- + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
+ + HelpExampleCli("getreceivedbylabel", "\"tabby\" 6") +
"\nAs a json rpc call\n"
- + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
+ + HelpExampleRpc("getreceivedbylabel", "\"tabby\", 6")
);
ObserveSafeMode();
@@ -759,9 +760,9 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request)
if (!request.params[1].isNull())
nMinDepth = request.params[1].get_int();
- // Get the set of pub keys assigned to account
- std::string strAccount = AccountFromValue(request.params[0]);
- std::set<CTxDestination> setAddress = pwallet->GetAccountAddresses(strAccount);
+ // Get the set of pub keys assigned to label
+ std::string label = LabelFromValue(request.params[0]);
+ std::set<CTxDestination> setAddress = pwallet->GetLabelAddresses(label);
// Tally
CAmount nAmount = 0;
@@ -919,8 +920,8 @@ UniValue movecmd(const JSONRPCRequest& request)
ObserveSafeMode();
LOCK2(cs_main, pwallet->cs_wallet);
- std::string strFrom = AccountFromValue(request.params[0]);
- std::string strTo = AccountFromValue(request.params[1]);
+ std::string strFrom = LabelFromValue(request.params[0]);
+ std::string strTo = LabelFromValue(request.params[1]);
CAmount nAmount = AmountFromValue(request.params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
@@ -983,7 +984,7 @@ UniValue sendfrom(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- std::string strAccount = AccountFromValue(request.params[0]);
+ std::string strAccount = LabelFromValue(request.params[0]);
CTxDestination dest = DecodeDestination(request.params[1].get_str());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
@@ -995,12 +996,11 @@ UniValue sendfrom(const JSONRPCRequest& request)
if (!request.params[3].isNull())
nMinDepth = request.params[3].get_int();
- CWalletTx wtx;
- wtx.strFromAccount = strAccount;
+ mapValue_t mapValue;
if (!request.params[4].isNull() && !request.params[4].get_str().empty())
- wtx.mapValue["comment"] = request.params[4].get_str();
+ mapValue["comment"] = request.params[4].get_str();
if (!request.params[5].isNull() && !request.params[5].get_str().empty())
- wtx.mapValue["to"] = request.params[5].get_str();
+ mapValue["to"] = request.params[5].get_str();
EnsureWalletIsUnlocked(pwallet);
@@ -1010,9 +1010,8 @@ UniValue sendfrom(const JSONRPCRequest& request)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
CCoinControl no_coin_control; // This is a deprecated API
- SendMoney(pwallet, dest, nAmount, false, wtx, no_coin_control);
-
- return wtx.GetHash().GetHex();
+ CTransactionRef tx = SendMoney(pwallet, dest, nAmount, false, no_coin_control, std::move(mapValue), std::move(strAccount));
+ return tx->GetHash().GetHex();
}
@@ -1077,16 +1076,15 @@ UniValue sendmany(const JSONRPCRequest& request)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
}
- std::string strAccount = AccountFromValue(request.params[0]);
+ std::string strAccount = LabelFromValue(request.params[0]);
UniValue sendTo = request.params[1].get_obj();
int nMinDepth = 1;
if (!request.params[2].isNull())
nMinDepth = request.params[2].get_int();
- CWalletTx wtx;
- wtx.strFromAccount = strAccount;
+ mapValue_t mapValue;
if (!request.params[3].isNull() && !request.params[3].get_str().empty())
- wtx.mapValue["comment"] = request.params[3].get_str();
+ mapValue["comment"] = request.params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (!request.params[4].isNull())
@@ -1147,21 +1145,25 @@ UniValue sendmany(const JSONRPCRequest& request)
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
+ // Shuffle recipient list
+ std::shuffle(vecSend.begin(), vecSend.end(), FastRandomContext());
+
// Send
CReserveKey keyChange(pwallet);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
- bool fCreated = pwallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason, coin_control);
+ CTransactionRef tx;
+ bool fCreated = pwallet->CreateTransaction(vecSend, tx, keyChange, nFeeRequired, nChangePosRet, strFailReason, coin_control);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
CValidationState state;
- if (!pwallet->CommitTransaction(wtx, keyChange, g_connman.get(), state)) {
+ if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, std::move(strAccount), keyChange, g_connman.get(), state)) {
strFailReason = strprintf("Transaction commit failed:: %s", FormatStateMessage(state));
throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
}
- return wtx.GetHash().GetHex();
+ return tx->GetHash().GetHex();
}
UniValue addmultisigaddress(const JSONRPCRequest& request)
@@ -1172,12 +1174,12 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
}
if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {
- std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" \"address_type\" )\n"
+ std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"label\" \"address_type\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n"
"Each key is a Bitcoin address or hex-encoded public key.\n"
"This functionality is only intended for use with non-watchonly addresses.\n"
"See `importaddress` for watchonly p2sh address support.\n"
- "If 'account' is specified (DEPRECATED), assign address to that account.\n"
+ "If 'label' is specified, assign address to that label.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
@@ -1186,7 +1188,7 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
" \"address\" (string) bitcoin address or hex-encoded public key\n"
" ...,\n"
" ]\n"
- "3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n"
+ "3. \"label\" (string, optional) A label to assign the addresses to.\n"
"4. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -addresstype.\n"
"\nResult:\n"
@@ -1205,9 +1207,9 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- std::string strAccount;
+ std::string label;
if (!request.params[2].isNull())
- strAccount = AccountFromValue(request.params[2]);
+ label = LabelFromValue(request.params[2]);
int required = request.params[0].get_int();
@@ -1222,10 +1224,10 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
}
}
- OutputType output_type = g_address_type;
+ OutputType output_type = pwallet->m_default_address_type;
if (!request.params[3].isNull()) {
output_type = ParseOutputType(request.params[3].get_str(), output_type);
- if (output_type == OUTPUT_TYPE_NONE) {
+ if (output_type == OutputType::NONE) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[3].get_str()));
}
}
@@ -1234,7 +1236,7 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
CScript inner = CreateMultisigRedeemscript(required, pubkeys);
pwallet->AddCScript(inner);
CTxDestination dest = pwallet->AddAndGetDestinationForScript(inner, output_type);
- pwallet->SetAddressBook(dest, strAccount, "send");
+ pwallet->SetAddressBook(dest, label, "send");
UniValue result(UniValue::VOBJ);
result.pushKV("address", EncodeDestination(dest));
@@ -1386,14 +1388,14 @@ struct tallyitem
}
};
-UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByAccounts)
+UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool by_label)
{
// Minimum confirmations
int nMinDepth = 1;
if (!params[0].isNull())
nMinDepth = params[0].get_int();
- // Whether to include empty accounts
+ // Whether to include empty labels
bool fIncludeEmpty = false;
if (!params[1].isNull())
fIncludeEmpty = params[1].get_bool();
@@ -1405,7 +1407,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
bool has_filtered_address = false;
CTxDestination filtered_address = CNoDestination();
- if (!fByAccounts && params.size() > 3) {
+ if (!by_label && params.size() > 3) {
if (!IsValidDestinationString(params[3].get_str())) {
throw JSONRPCError(RPC_WALLET_ERROR, "address_filter parameter was invalid");
}
@@ -1450,7 +1452,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
// Reply
UniValue ret(UniValue::VARR);
- std::map<std::string, tallyitem> mapAccountTally;
+ std::map<std::string, tallyitem> label_tally;
// Create mapAddressBook iterator
// If we aren't filtering, go from begin() to end()
@@ -1467,7 +1469,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
for (auto item_it = start; item_it != end; ++item_it)
{
const CTxDestination& address = item_it->first;
- const std::string& strAccount = item_it->second.name;
+ const std::string& label = item_it->second.name;
auto it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
@@ -1482,9 +1484,9 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
fIsWatchonly = (*it).second.fIsWatchonly;
}
- if (fByAccounts)
+ if (by_label)
{
- tallyitem& _item = mapAccountTally[strAccount];
+ tallyitem& _item = label_tally[label];
_item.nAmount += nAmount;
_item.nConf = std::min(_item.nConf, nConf);
_item.fIsWatchonly = fIsWatchonly;
@@ -1495,11 +1497,10 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
if(fIsWatchonly)
obj.pushKV("involvesWatchonly", true);
obj.pushKV("address", EncodeDestination(address));
- obj.pushKV("account", strAccount);
+ obj.pushKV("account", label);
obj.pushKV("amount", ValueFromAmount(nAmount));
obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
- if (!fByAccounts)
- obj.pushKV("label", strAccount);
+ obj.pushKV("label", label);
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
@@ -1513,9 +1514,9 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
}
}
- if (fByAccounts)
+ if (by_label)
{
- for (const auto& entry : mapAccountTally)
+ for (const auto& entry : label_tally)
{
CAmount nAmount = entry.second.nAmount;
int nConf = entry.second.nConf;
@@ -1525,6 +1526,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
obj.pushKV("account", entry.first);
obj.pushKV("amount", ValueFromAmount(nAmount));
obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
+ obj.pushKV("label", entry.first);
ret.push_back(obj);
}
}
@@ -1553,10 +1555,10 @@ UniValue listreceivedbyaddress(const JSONRPCRequest& request)
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
- " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
+ " \"account\" : \"accountname\", (string) DEPRECATED. Backwards compatible alias for label.\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
- " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
+ " \"label\" : \"label\", (string) The label of the receiving address. The default label is \"\".\n"
" \"txids\": [\n"
" n, (numeric) The ids of transactions received with the address \n"
" ...\n"
@@ -1583,7 +1585,7 @@ UniValue listreceivedbyaddress(const JSONRPCRequest& request)
return ListReceived(pwallet, request.params, false);
}
-UniValue listreceivedbyaccount(const JSONRPCRequest& request)
+UniValue listreceivedbylabel(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
@@ -1592,29 +1594,29 @@ UniValue listreceivedbyaccount(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() > 3)
throw std::runtime_error(
- "listreceivedbyaccount ( minconf include_empty include_watchonly)\n"
- "\nDEPRECATED. List balances by account.\n"
+ "listreceivedbylabel ( minconf include_empty include_watchonly)\n"
+ "\nList received transactions by label.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
- "2. include_empty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n"
+ "2. include_empty (bool, optional, default=false) Whether to include labels that haven't received any payments.\n"
"3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
- " \"account\" : \"accountname\", (string) The account name of the receiving account\n"
- " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
+ " \"account\" : \"accountname\", (string) DEPRECATED. Backwards compatible alias for label.\n"
+ " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this label\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
- " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
+ " \"label\" : \"label\" (string) The label of the receiving address. The default label is \"\".\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
- + HelpExampleCli("listreceivedbyaccount", "")
- + HelpExampleCli("listreceivedbyaccount", "6 true")
- + HelpExampleRpc("listreceivedbyaccount", "6, true, true")
+ + HelpExampleCli("listreceivedbylabel", "")
+ + HelpExampleCli("listreceivedbylabel", "6 true")
+ + HelpExampleRpc("listreceivedbylabel", "6, true, true")
);
ObserveSafeMode();
@@ -2016,7 +2018,7 @@ UniValue listsinceblock(const JSONRPCRequest& request)
" ],\n"
" \"removed\": [\n"
" <structure is the same as \"transactions\" above, only present if include_removed=true>\n"
- " Note: transactions that were readded in the active chain will appear as-is in this array, and may thus have a positive confirmation count.\n"
+ " Note: transactions that were re-added in the active chain will appear as-is in this array, and may thus have a positive confirmation count.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the block (target_confirmations-1) from the best block on the main chain. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones\n"
"}\n"
@@ -2043,11 +2045,10 @@ UniValue listsinceblock(const JSONRPCRequest& request)
uint256 blockId;
blockId.SetHex(request.params[0].get_str());
- BlockMap::iterator it = mapBlockIndex.find(blockId);
- if (it == mapBlockIndex.end()) {
+ paltindex = pindex = LookupBlockIndex(blockId);
+ if (!pindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
- paltindex = pindex = it->second;
if (chainActive[pindex->nHeight] != pindex) {
// the block being asked for is a part of a deactivated chain;
// we don't want to depend on its perceived height in the block
@@ -2365,8 +2366,6 @@ UniValue walletpassphrase(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- if (request.fHelp)
- return true;
if (!pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
}
@@ -2431,8 +2430,6 @@ UniValue walletpassphrasechange(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- if (request.fHelp)
- return true;
if (!pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
}
@@ -2487,8 +2484,6 @@ UniValue walletlock(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- if (request.fHelp)
- return true;
if (!pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
}
@@ -2534,8 +2529,6 @@ UniValue encryptwallet(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
- if (request.fHelp)
- return true;
if (pwallet->IsCrypted()) {
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
}
@@ -2937,7 +2930,8 @@ UniValue listunspent(const JSONRPCRequest& request)
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the bitcoin address\n"
- " \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n"
+ " \"label\" : \"label\", (string) The associated label, or \"\" for the default label\n"
+ " \"account\" : \"account\", (string) DEPRECATED. Backwards compatible alias for label.\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction output amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
@@ -3041,6 +3035,7 @@ UniValue listunspent(const JSONRPCRequest& request)
entry.pushKV("address", EncodeDestination(address));
if (pwallet->mapAddressBook.count(address)) {
+ entry.pushKV("label", pwallet->mapAddressBook[address].name);
entry.pushKV("account", pwallet->mapAddressBook[address].name);
}
@@ -3185,8 +3180,8 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
if (options.exists("changeAddress")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both changeAddress and address_type options");
}
- coinControl.change_type = ParseOutputType(options["change_type"].get_str(), coinControl.change_type);
- if (coinControl.change_type == OUTPUT_TYPE_NONE) {
+ coinControl.m_change_type = ParseOutputType(options["change_type"].get_str(), pwallet->m_default_change_type);
+ if (coinControl.m_change_type == OutputType::NONE) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str()));
}
}
@@ -3580,7 +3575,7 @@ UniValue rescanblockchain(const JSONRPCRequest& request)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height");
}
else if (pindexStop->nHeight < pindexStart->nHeight) {
- throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater then start_height");
+ throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater than start_height");
}
}
}
@@ -3836,21 +3831,23 @@ static const CRPCCommand commands[] =
{ "hidden", "resendwallettransactions", &resendwallettransactions, {} },
{ "wallet", "abandontransaction", &abandontransaction, {"txid"} },
{ "wallet", "abortrescan", &abortrescan, {} },
- { "wallet", "addmultisigaddress", &addmultisigaddress, {"nrequired","keys","account","address_type"} },
+ { "wallet", "addmultisigaddress", &addmultisigaddress, {"nrequired","keys","label|account","address_type"} },
{ "hidden", "addwitnessaddress", &addwitnessaddress, {"address","p2sh"} },
{ "wallet", "backupwallet", &backupwallet, {"destination"} },
{ "wallet", "bumpfee", &bumpfee, {"txid", "options"} },
{ "wallet", "dumpprivkey", &dumpprivkey, {"address"} },
{ "wallet", "dumpwallet", &dumpwallet, {"filename"} },
{ "wallet", "encryptwallet", &encryptwallet, {"passphrase"} },
- { "wallet", "getaccountaddress", &getaccountaddress, {"account"} },
+ { "wallet", "getlabeladdress", &getlabeladdress, {"label"} },
+ { "wallet", "getaccountaddress", &getlabeladdress, {"account"} },
{ "wallet", "getaccount", &getaccount, {"address"} },
{ "wallet", "getaddressesbyaccount", &getaddressesbyaccount, {"account"} },
{ "wallet", "getaddressinfo", &getaddressinfo, {"address"} },
{ "wallet", "getbalance", &getbalance, {"account","minconf","include_watchonly"} },
- { "wallet", "getnewaddress", &getnewaddress, {"account","address_type"} },
+ { "wallet", "getnewaddress", &getnewaddress, {"label|account","address_type"} },
{ "wallet", "getrawchangeaddress", &getrawchangeaddress, {"address_type"} },
- { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, {"account","minconf"} },
+ { "wallet", "getreceivedbylabel", &getreceivedbylabel, {"label","minconf"} },
+ { "wallet", "getreceivedbyaccount", &getreceivedbylabel, {"account","minconf"} },
{ "wallet", "getreceivedbyaddress", &getreceivedbyaddress, {"address","minconf"} },
{ "wallet", "gettransaction", &gettransaction, {"txid","include_watchonly"} },
{ "wallet", "getunconfirmedbalance", &getunconfirmedbalance, {} },
@@ -3865,7 +3862,8 @@ static const CRPCCommand commands[] =
{ "wallet", "listaccounts", &listaccounts, {"minconf","include_watchonly"} },
{ "wallet", "listaddressgroupings", &listaddressgroupings, {} },
{ "wallet", "listlockunspent", &listlockunspent, {} },
- { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, {"minconf","include_empty","include_watchonly"} },
+ { "wallet", "listreceivedbylabel", &listreceivedbylabel, {"minconf","include_empty","include_watchonly"} },
+ { "wallet", "listreceivedbyaccount", &listreceivedbylabel, {"minconf","include_empty","include_watchonly"} },
{ "wallet", "listreceivedbyaddress", &listreceivedbyaddress, {"minconf","include_empty","include_watchonly","address_filter"} },
{ "wallet", "listsinceblock", &listsinceblock, {"blockhash","target_confirmations","include_watchonly","include_removed"} },
{ "wallet", "listtransactions", &listtransactions, {"account","count","skip","include_watchonly"} },
@@ -3876,7 +3874,8 @@ static const CRPCCommand commands[] =
{ "wallet", "sendfrom", &sendfrom, {"fromaccount","toaddress","amount","minconf","comment","comment_to"} },
{ "wallet", "sendmany", &sendmany, {"fromaccount","amounts","minconf","comment","subtractfeefrom","replaceable","conf_target","estimate_mode"} },
{ "wallet", "sendtoaddress", &sendtoaddress, {"address","amount","comment","comment_to","subtractfeefromamount","replaceable","conf_target","estimate_mode"} },
- { "wallet", "setaccount", &setaccount, {"address","account"} },
+ { "wallet", "setlabel", &setlabel, {"address","label"} },
+ { "wallet", "setaccount", &setlabel, {"address","account"} },
{ "wallet", "settxfee", &settxfee, {"amount"} },
{ "wallet", "signmessage", &signmessage, {"address","message"} },
{ "wallet", "signrawtransactionwithwallet", &signrawtransactionwithwallet, {"hexstring","prevtxs","sighashtype"} },
diff --git a/src/wallet/test/accounting_tests.cpp b/src/wallet/test/accounting_tests.cpp
index 7b20bd7b02..cc6e491f53 100644
--- a/src/wallet/test/accounting_tests.cpp
+++ b/src/wallet/test/accounting_tests.cpp
@@ -18,7 +18,7 @@ GetResults(CWallet& wallet, std::map<CAmount, CAccountingEntry>& results)
std::list<CAccountingEntry> aes;
results.clear();
- BOOST_CHECK(wallet.ReorderTransactions() == DB_LOAD_OK);
+ BOOST_CHECK(wallet.ReorderTransactions() == DBErrors::LOAD_OK);
wallet.ListAccountCreditDebit("", aes);
for (CAccountingEntry& ae : aes)
{
@@ -29,7 +29,7 @@ GetResults(CWallet& wallet, std::map<CAmount, CAccountingEntry>& results)
BOOST_AUTO_TEST_CASE(acc_orderupgrade)
{
std::vector<CWalletTx*> vpwtx;
- CWalletTx wtx;
+ CWalletTx wtx(nullptr /* pwallet */, MakeTransactionRef());
CAccountingEntry ae;
std::map<CAmount, CAccountingEntry> results;
@@ -44,7 +44,7 @@ BOOST_AUTO_TEST_CASE(acc_orderupgrade)
wtx.mapValue["comment"] = "z";
m_wallet.AddToWallet(wtx);
- vpwtx.push_back(&m_wallet.mapWallet[wtx.GetHash()]);
+ vpwtx.push_back(&m_wallet.mapWallet.at(wtx.GetHash()));
vpwtx[0]->nTimeReceived = (unsigned int)1333333335;
vpwtx[0]->nOrderPos = -1;
@@ -86,7 +86,7 @@ BOOST_AUTO_TEST_CASE(acc_orderupgrade)
wtx.SetTx(MakeTransactionRef(std::move(tx)));
}
m_wallet.AddToWallet(wtx);
- vpwtx.push_back(&m_wallet.mapWallet[wtx.GetHash()]);
+ vpwtx.push_back(&m_wallet.mapWallet.at(wtx.GetHash()));
vpwtx[1]->nTimeReceived = (unsigned int)1333333336;
wtx.mapValue["comment"] = "x";
@@ -96,7 +96,7 @@ BOOST_AUTO_TEST_CASE(acc_orderupgrade)
wtx.SetTx(MakeTransactionRef(std::move(tx)));
}
m_wallet.AddToWallet(wtx);
- vpwtx.push_back(&m_wallet.mapWallet[wtx.GetHash()]);
+ vpwtx.push_back(&m_wallet.mapWallet.at(wtx.GetHash()));
vpwtx[2]->nTimeReceived = (unsigned int)1333333329;
vpwtx[2]->nOrderPos = -1;
diff --git a/src/wallet/test/coinselector_tests.cpp b/src/wallet/test/coinselector_tests.cpp
new file mode 100644
index 0000000000..184a8a3f1f
--- /dev/null
+++ b/src/wallet/test/coinselector_tests.cpp
@@ -0,0 +1,575 @@
+// Copyright (c) 2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "wallet/wallet.h"
+#include "wallet/coinselection.h"
+#include "wallet/coincontrol.h"
+#include "amount.h"
+#include "primitives/transaction.h"
+#include "random.h"
+#include "test/test_bitcoin.h"
+#include "wallet/test/wallet_test_fixture.h"
+
+#include <boost/test/unit_test.hpp>
+#include <random>
+
+BOOST_FIXTURE_TEST_SUITE(coinselector_tests, WalletTestingSetup)
+
+// how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
+#define RUN_TESTS 100
+
+// some tests fail 1% of the time due to bad luck.
+// we repeat those tests this many times and only complain if all iterations of the test fail
+#define RANDOM_REPEATS 5
+
+std::vector<std::unique_ptr<CWalletTx>> wtxn;
+
+typedef std::set<CInputCoin> CoinSet;
+
+static std::vector<COutput> vCoins;
+static CWallet testWallet("dummy", CWalletDBWrapper::CreateDummy());
+static CAmount balance = 0;
+
+CoinEligibilityFilter filter_standard(1, 6, 0);
+CoinEligibilityFilter filter_confirmed(1, 1, 0);
+CoinEligibilityFilter filter_standard_extra(6, 6, 0);
+CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0);
+
+static void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set)
+{
+ CMutableTransaction tx;
+ tx.vout.resize(nInput + 1);
+ tx.vout[nInput].nValue = nValue;
+ set.emplace_back(MakeTransactionRef(tx), nInput);
+}
+
+static void add_coin(const CAmount& nValue, int nInput, CoinSet& set)
+{
+ CMutableTransaction tx;
+ tx.vout.resize(nInput + 1);
+ tx.vout[nInput].nValue = nValue;
+ set.emplace(MakeTransactionRef(tx), nInput);
+}
+
+static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
+{
+ balance += nValue;
+ static int nextLockTime = 0;
+ CMutableTransaction tx;
+ tx.nLockTime = nextLockTime++; // so all transactions get different hashes
+ tx.vout.resize(nInput + 1);
+ tx.vout[nInput].nValue = nValue;
+ if (fIsFromMe) {
+ // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
+ // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
+ tx.vin.resize(1);
+ }
+ std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx))));
+ if (fIsFromMe)
+ {
+ wtx->fDebitCached = true;
+ wtx->nDebitCached = 1;
+ }
+ COutput output(wtx.get(), nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */);
+ vCoins.push_back(output);
+ testWallet.AddToWallet(*wtx.get());
+ wtxn.emplace_back(std::move(wtx));
+}
+
+static void empty_wallet(void)
+{
+ vCoins.clear();
+ wtxn.clear();
+ balance = 0;
+}
+
+static bool equal_sets(CoinSet a, CoinSet b)
+{
+ std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
+ return ret.first == a.end() && ret.second == b.end();
+}
+
+static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool)
+{
+ utxo_pool.clear();
+ CAmount target = 0;
+ for (int i = 0; i < utxos; ++i) {
+ target += (CAmount)1 << (utxos+i);
+ add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);
+ add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);
+ }
+ return target;
+}
+
+// Branch and bound coin selection tests
+BOOST_AUTO_TEST_CASE(bnb_search_test)
+{
+
+ LOCK(testWallet.cs_wallet);
+
+ // Setup
+ std::vector<CInputCoin> utxo_pool;
+ CoinSet selection;
+ CoinSet actual_selection;
+ CAmount value_ret = 0;
+ CAmount not_input_fees = 0;
+
+ /////////////////////////
+ // Known Outcome tests //
+ /////////////////////////
+ BOOST_TEST_MESSAGE("Testing known outcomes");
+
+ // Empty utxo pool
+ BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ selection.clear();
+
+ // Add utxos
+ add_coin(1 * CENT, 1, utxo_pool);
+ add_coin(2 * CENT, 2, utxo_pool);
+ add_coin(3 * CENT, 3, utxo_pool);
+ add_coin(4 * CENT, 4, utxo_pool);
+
+ // Select 1 Cent
+ add_coin(1 * CENT, 1, actual_selection);
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ BOOST_CHECK(equal_sets(selection, actual_selection));
+ actual_selection.clear();
+ selection.clear();
+
+ // Select 2 Cent
+ add_coin(2 * CENT, 2, actual_selection);
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, 2 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ BOOST_CHECK(equal_sets(selection, actual_selection));
+ actual_selection.clear();
+ selection.clear();
+
+ // Select 5 Cent
+ add_coin(3 * CENT, 3, actual_selection);
+ add_coin(2 * CENT, 2, actual_selection);
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, 5 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ BOOST_CHECK(equal_sets(selection, actual_selection));
+ actual_selection.clear();
+ selection.clear();
+
+ // Select 11 Cent, not possible
+ BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 11 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ actual_selection.clear();
+ selection.clear();
+
+ // Select 10 Cent
+ add_coin(5 * CENT, 5, utxo_pool);
+ add_coin(4 * CENT, 4, actual_selection);
+ add_coin(3 * CENT, 3, actual_selection);
+ add_coin(2 * CENT, 2, actual_selection);
+ add_coin(1 * CENT, 1, actual_selection);
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, 10 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ BOOST_CHECK(equal_sets(selection, actual_selection));
+ actual_selection.clear();
+ selection.clear();
+
+ // Negative effective value
+ // Select 10 Cent but have 1 Cent not be possible because too small
+ add_coin(5 * CENT, 5, actual_selection);
+ add_coin(3 * CENT, 3, actual_selection);
+ add_coin(2 * CENT, 2, actual_selection);
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, 10 * CENT, 5000, selection, value_ret, not_input_fees));
+
+ // Select 0.25 Cent, not possible
+ BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 0.25 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
+ actual_selection.clear();
+ selection.clear();
+
+ // Iteration exhaustion test
+ CAmount target = make_hard_case(17, utxo_pool);
+ BOOST_CHECK(!SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees)); // Should exhaust
+ target = make_hard_case(14, utxo_pool);
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees)); // Should not exhaust
+
+ // Test same value early bailout optimization
+ add_coin(7 * CENT, 7, actual_selection);
+ add_coin(7 * CENT, 7, actual_selection);
+ add_coin(7 * CENT, 7, actual_selection);
+ add_coin(7 * CENT, 7, actual_selection);
+ add_coin(2 * CENT, 7, actual_selection);
+ add_coin(7 * CENT, 7, utxo_pool);
+ add_coin(7 * CENT, 7, utxo_pool);
+ add_coin(7 * CENT, 7, utxo_pool);
+ add_coin(7 * CENT, 7, utxo_pool);
+ add_coin(2 * CENT, 7, utxo_pool);
+ for (int i = 0; i < 50000; ++i) {
+ add_coin(5 * CENT, 7, utxo_pool);
+ }
+ BOOST_CHECK(SelectCoinsBnB(utxo_pool, 30 * CENT, 5000, selection, value_ret, not_input_fees));
+
+ ////////////////////
+ // Behavior tests //
+ ////////////////////
+ // Select 1 Cent with pool of only greater than 5 Cent
+ utxo_pool.clear();
+ for (int i = 5; i <= 20; ++i) {
+ add_coin(i * CENT, i, utxo_pool);
+ }
+ // Run 100 times, to make sure it is never finding a solution
+ for (int i = 0; i < 100; ++i) {
+ BOOST_CHECK(!SelectCoinsBnB(utxo_pool, 1 * CENT, 2 * CENT, selection, value_ret, not_input_fees));
+ }
+
+ // Make sure that effective value is working in SelectCoinsMinConf when BnB is used
+ CoinSelectionParams coin_selection_params_bnb(true, 0, 0, CFeeRate(3000), 0);
+ CoinSet setCoinsRet;
+ CAmount nValueRet;
+ bool bnb_used;
+ empty_wallet();
+ add_coin(1);
+ vCoins.at(0).nInputBytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used));
+
+ // Make sure that we aren't using BnB when there are preset inputs
+ empty_wallet();
+ add_coin(5 * CENT);
+ add_coin(3 * CENT);
+ add_coin(2 * CENT);
+ CCoinControl coin_control;
+ coin_control.fAllowOtherInputs = true;
+ coin_control.Select(COutPoint(vCoins.at(0).tx->GetHash(), vCoins.at(0).i));
+ BOOST_CHECK(testWallet.SelectCoins(vCoins, 10 * CENT, setCoinsRet, nValueRet, coin_control, coin_selection_params_bnb, bnb_used));
+ BOOST_CHECK(!bnb_used);
+ BOOST_CHECK(!coin_selection_params_bnb.use_bnb);
+}
+
+BOOST_AUTO_TEST_CASE(knapsack_solver_test)
+{
+ CoinSet setCoinsRet, setCoinsRet2;
+ CAmount nValueRet;
+ bool bnb_used;
+
+ LOCK(testWallet.cs_wallet);
+
+ // test multiple times to allow for differences in the shuffle order
+ for (int i = 0; i < RUN_TESTS; i++)
+ {
+ empty_wallet();
+
+ // with an empty wallet we can't even pay one cent
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+
+ add_coin(1*CENT, 4); // add a new 1 cent coin
+
+ // with a new 1 cent coin, we still can't find a mature 1 cent
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+
+ // but we can find a new 1 cent
+ BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
+
+ add_coin(2*CENT); // add a mature 2 cent coin
+
+ // we can't make 3 cents of mature coins
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+
+ // we can make 3 cents of new coins
+ BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
+
+ add_coin(5*CENT); // add a mature 5 cent coin,
+ add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
+ add_coin(20*CENT); // and a mature 20 cent coin
+
+ // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
+
+ // we can't make 38 cents only if we disallow new coins:
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ // we can't even make 37 cents if we don't allow new coins even if they're from us
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard_extra, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ // but we can make 37 cents if we accept new coins from ourself
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
+ // and we can make 38 cents if we accept all new coins
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
+
+ // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible)
+
+ // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
+ BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
+
+ // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
+ BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK(nValueRet == 8 * CENT);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
+
+ // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
+ BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
+
+ // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
+ empty_wallet();
+
+ add_coin( 6*CENT);
+ add_coin( 7*CENT);
+ add_coin( 8*CENT);
+ add_coin(20*CENT);
+ add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total
+
+ // check that we have 71 and not 72
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+
+ // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
+
+ add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
+
+ // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
+
+ add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30
+
+ // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins
+
+ // now try making 11 cents. we should get 5+6
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
+
+ // check that the smallest bigger coin is used
+ add_coin( 1*COIN);
+ add_coin( 2*COIN);
+ add_coin( 3*COIN);
+ add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
+
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
+
+ // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
+
+ empty_wallet();
+ add_coin(MIN_CHANGE * 1 / 10);
+ add_coin(MIN_CHANGE * 2 / 10);
+ add_coin(MIN_CHANGE * 3 / 10);
+ add_coin(MIN_CHANGE * 4 / 10);
+ add_coin(MIN_CHANGE * 5 / 10);
+
+ // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
+ // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
+
+ // but if we add a bigger coin, small change is avoided
+ add_coin(1111*MIN_CHANGE);
+
+ // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
+
+ // if we add more small coins:
+ add_coin(MIN_CHANGE * 6 / 10);
+ add_coin(MIN_CHANGE * 7 / 10);
+
+ // and try again to make 1.0 * MIN_CHANGE
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
+
+ // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
+ // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
+ empty_wallet();
+ for (int j = 0; j < 20; j++)
+ add_coin(50000 * COIN);
+
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins
+
+ // if there's not enough in the smaller coins to make at least 1 * MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0),
+ // we need to try finding an exact subset anyway
+
+ // sometimes it will fail, and so we use the next biggest coin:
+ empty_wallet();
+ add_coin(MIN_CHANGE * 5 / 10);
+ add_coin(MIN_CHANGE * 6 / 10);
+ add_coin(MIN_CHANGE * 7 / 10);
+ add_coin(1111 * MIN_CHANGE);
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
+
+ // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
+ empty_wallet();
+ add_coin(MIN_CHANGE * 4 / 10);
+ add_coin(MIN_CHANGE * 6 / 10);
+ add_coin(MIN_CHANGE * 8 / 10);
+ add_coin(1111 * MIN_CHANGE);
+ BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6
+
+ // test avoiding small change
+ empty_wallet();
+ add_coin(MIN_CHANGE * 5 / 100);
+ add_coin(MIN_CHANGE * 1);
+ add_coin(MIN_CHANGE * 100);
+
+ // trying to make 100.01 from these three coins
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
+
+ // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
+
+ // test with many inputs
+ for (CAmount amt=1500; amt < COIN; amt*=10) {
+ empty_wallet();
+ // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
+ for (uint16_t j = 0; j < 676; j++)
+ add_coin(amt);
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ if (amt - 2000 < MIN_CHANGE) {
+ // needs more than one input:
+ uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt);
+ CAmount returnValue = amt * returnSize;
+ BOOST_CHECK_EQUAL(nValueRet, returnValue);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
+ } else {
+ // one input is sufficient:
+ BOOST_CHECK_EQUAL(nValueRet, amt);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
+ }
+ }
+
+ // test randomness
+ {
+ empty_wallet();
+ for (int i2 = 0; i2 < 100; i2++)
+ add_coin(COIN);
+
+ // picking 50 from 100 coins doesn't depend on the shuffle,
+ // but does depend on randomness in the stochastic approximation code
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
+
+ int fails = 0;
+ for (int j = 0; j < RANDOM_REPEATS; j++)
+ {
+ // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
+ // run the test RANDOM_REPEATS times and only complain if all of them fail
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used));
+ if (equal_sets(setCoinsRet, setCoinsRet2))
+ fails++;
+ }
+ BOOST_CHECK_NE(fails, RANDOM_REPEATS);
+
+ // add 75 cents in small change. not enough to make 90 cents,
+ // then try making 90 cents. there are multiple competing "smallest bigger" coins,
+ // one of which should be picked at random
+ add_coin(5 * CENT);
+ add_coin(10 * CENT);
+ add_coin(15 * CENT);
+ add_coin(20 * CENT);
+ add_coin(25 * CENT);
+
+ fails = 0;
+ for (int j = 0; j < RANDOM_REPEATS; j++)
+ {
+ // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
+ // run the test RANDOM_REPEATS times and only complain if all of them fail
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used));
+ if (equal_sets(setCoinsRet, setCoinsRet2))
+ fails++;
+ }
+ BOOST_CHECK_NE(fails, RANDOM_REPEATS);
+ }
+ }
+ empty_wallet();
+}
+
+BOOST_AUTO_TEST_CASE(ApproximateBestSubset)
+{
+ CoinSet setCoinsRet;
+ CAmount nValueRet;
+ bool bnb_used;
+
+ LOCK(testWallet.cs_wallet);
+
+ empty_wallet();
+
+ // Test vValue sort order
+ for (int i = 0; i < 1000; i++)
+ add_coin(1000 * COIN);
+ add_coin(3 * COIN);
+
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
+ BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
+ BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
+
+ empty_wallet();
+}
+
+// Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value
+BOOST_AUTO_TEST_CASE(SelectCoins_test)
+{
+ // Random generator stuff
+ std::default_random_engine generator;
+ std::exponential_distribution<double> distribution (100);
+ FastRandomContext rand;
+
+ // Output stuff
+ CAmount out_value = 0;
+ CoinSet out_set;
+ CAmount target = 0;
+ bool bnb_used;
+
+ // Run this test 100 times
+ for (int i = 0; i < 100; ++i)
+ {
+ // Reset
+ out_value = 0;
+ target = 0;
+ out_set.clear();
+ empty_wallet();
+
+ // Make a wallet with 1000 exponentially distributed random inputs
+ for (int j = 0; j < 1000; ++j)
+ {
+ add_coin((CAmount)(distribution(generator)*10000000));
+ }
+
+ // Generate a random fee rate in the range of 100 - 400
+ CFeeRate rate(rand.randrange(300) + 100);
+
+ // Generate a random target value between 1000 and wallet balance
+ target = rand.randrange(balance - 1000) + 1000;
+
+ // Perform selection
+ CoinSelectionParams coin_selection_params_knapsack(false, 34, 148, CFeeRate(0), 0);
+ CoinSelectionParams coin_selection_params_bnb(true, 34, 148, CFeeRate(0), 0);
+ BOOST_CHECK(testWallet.SelectCoinsMinConf(target, filter_standard, vCoins, out_set, out_value, coin_selection_params_bnb, bnb_used) ||
+ testWallet.SelectCoinsMinConf(target, filter_standard, vCoins, out_set, out_value, coin_selection_params_knapsack, bnb_used));
+ BOOST_CHECK_GE(out_value, target);
+ }
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/src/wallet/test/crypto_tests.cpp b/src/wallet/test/crypto_tests.cpp
index 89b2c4e796..d8c0cdf0f9 100644
--- a/src/wallet/test/crypto_tests.cpp
+++ b/src/wallet/test/crypto_tests.cpp
@@ -10,7 +10,7 @@
#include <boost/test/unit_test.hpp>
-BOOST_FIXTURE_TEST_SUITE(wallet_crypto, BasicTestingSetup)
+BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup)
class TestCrypter
{
diff --git a/src/wallet/test/wallet_test_fixture.cpp b/src/wallet/test/wallet_test_fixture.cpp
index 77ccd0b8d8..5c550742c8 100644
--- a/src/wallet/test/wallet_test_fixture.cpp
+++ b/src/wallet/test/wallet_test_fixture.cpp
@@ -12,8 +12,6 @@ WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
TestingSetup(chainName), m_wallet("mock", CWalletDBWrapper::CreateMock())
{
bool fFirstRun;
- g_address_type = OUTPUT_TYPE_DEFAULT;
- g_change_type = OUTPUT_TYPE_DEFAULT;
m_wallet.LoadWallet(fFirstRun);
RegisterValidationInterface(&m_wallet);
diff --git a/src/wallet/test/wallet_test_fixture.h b/src/wallet/test/wallet_test_fixture.h
index 663836a955..b328b3543b 100644
--- a/src/wallet/test/wallet_test_fixture.h
+++ b/src/wallet/test/wallet_test_fixture.h
@@ -2,13 +2,15 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#ifndef BITCOIN_WALLET_TEST_FIXTURE_H
-#define BITCOIN_WALLET_TEST_FIXTURE_H
+#ifndef BITCOIN_WALLET_TEST_WALLET_TEST_FIXTURE_H
+#define BITCOIN_WALLET_TEST_WALLET_TEST_FIXTURE_H
#include <test/test_bitcoin.h>
#include <wallet/wallet.h>
+#include <memory>
+
/** Testing setup and teardown for wallet.
*/
struct WalletTestingSetup: public TestingSetup {
@@ -18,5 +20,4 @@ struct WalletTestingSetup: public TestingSetup {
CWallet m_wallet;
};
-#endif
-
+#endif // BITCOIN_WALLET_TEST_WALLET_TEST_FIXTURE_H
diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp
index 41348b50a4..e93e0f1966 100644
--- a/src/wallet/test/wallet_tests.cpp
+++ b/src/wallet/test/wallet_tests.cpp
@@ -4,6 +4,7 @@
#include <wallet/wallet.h>
+#include <memory>
#include <set>
#include <stdint.h>
#include <utility>
@@ -23,345 +24,8 @@ extern UniValue importmulti(const JSONRPCRequest& request);
extern UniValue dumpwallet(const JSONRPCRequest& request);
extern UniValue importwallet(const JSONRPCRequest& request);
-// how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
-#define RUN_TESTS 100
-
-// some tests fail 1% of the time due to bad luck.
-// we repeat those tests this many times and only complain if all iterations of the test fail
-#define RANDOM_REPEATS 5
-
-std::vector<std::unique_ptr<CWalletTx>> wtxn;
-
-typedef std::set<CInputCoin> CoinSet;
-
BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
-static const CWallet testWallet("dummy", CWalletDBWrapper::CreateDummy());
-static std::vector<COutput> vCoins;
-
-static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
-{
- static int nextLockTime = 0;
- CMutableTransaction tx;
- tx.nLockTime = nextLockTime++; // so all transactions get different hashes
- tx.vout.resize(nInput+1);
- tx.vout[nInput].nValue = nValue;
- if (fIsFromMe) {
- // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
- // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
- tx.vin.resize(1);
- }
- std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx))));
- if (fIsFromMe)
- {
- wtx->fDebitCached = true;
- wtx->nDebitCached = 1;
- }
- COutput output(wtx.get(), nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */);
- vCoins.push_back(output);
- wtxn.emplace_back(std::move(wtx));
-}
-
-static void empty_wallet(void)
-{
- vCoins.clear();
- wtxn.clear();
-}
-
-static bool equal_sets(CoinSet a, CoinSet b)
-{
- std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
- return ret.first == a.end() && ret.second == b.end();
-}
-
-BOOST_AUTO_TEST_CASE(coin_selection_tests)
-{
- CoinSet setCoinsRet, setCoinsRet2;
- CAmount nValueRet;
-
- LOCK(testWallet.cs_wallet);
-
- // test multiple times to allow for differences in the shuffle order
- for (int i = 0; i < RUN_TESTS; i++)
- {
- empty_wallet();
-
- // with an empty wallet we can't even pay one cent
- BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
-
- add_coin(1*CENT, 4); // add a new 1 cent coin
-
- // with a new 1 cent coin, we still can't find a mature 1 cent
- BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
-
- // but we can find a new 1 cent
- BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
-
- add_coin(2*CENT); // add a mature 2 cent coin
-
- // we can't make 3 cents of mature coins
- BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
-
- // we can make 3 cents of new coins
- BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
-
- add_coin(5*CENT); // add a mature 5 cent coin,
- add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
- add_coin(20*CENT); // and a mature 20 cent coin
-
- // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
-
- // we can't make 38 cents only if we disallow new coins:
- BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
- // we can't even make 37 cents if we don't allow new coins even if they're from us
- BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 6, 6, 0, vCoins, setCoinsRet, nValueRet));
- // but we can make 37 cents if we accept new coins from ourself
- BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
- // and we can make 38 cents if we accept all new coins
- BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
-
- // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
- BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible)
-
- // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
- BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
-
- // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
- BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK(nValueRet == 8 * CENT);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
-
- // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
- BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
-
- // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
- empty_wallet();
-
- add_coin( 6*CENT);
- add_coin( 7*CENT);
- add_coin( 8*CENT);
- add_coin(20*CENT);
- add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total
-
- // check that we have 71 and not 72
- BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
-
- // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20
- BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
-
- add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
-
- // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20
- BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
-
- add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30
-
- // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18
- BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins
-
- // now try making 11 cents. we should get 5+6
- BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
-
- // check that the smallest bigger coin is used
- add_coin( 1*COIN);
- add_coin( 2*COIN);
- add_coin( 3*COIN);
- add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
- BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
-
- BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
-
- // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
-
- empty_wallet();
- add_coin(MIN_CHANGE * 1 / 10);
- add_coin(MIN_CHANGE * 2 / 10);
- add_coin(MIN_CHANGE * 3 / 10);
- add_coin(MIN_CHANGE * 4 / 10);
- add_coin(MIN_CHANGE * 5 / 10);
-
- // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
- // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly
- BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
-
- // but if we add a bigger coin, small change is avoided
- add_coin(1111*MIN_CHANGE);
-
- // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
- BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
-
- // if we add more small coins:
- add_coin(MIN_CHANGE * 6 / 10);
- add_coin(MIN_CHANGE * 7 / 10);
-
- // and try again to make 1.0 * MIN_CHANGE
- BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
-
- // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
- // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
- empty_wallet();
- for (int j = 0; j < 20; j++)
- add_coin(50000 * COIN);
-
- BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins
-
- // if there's not enough in the smaller coins to make at least 1 * MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0),
- // we need to try finding an exact subset anyway
-
- // sometimes it will fail, and so we use the next biggest coin:
- empty_wallet();
- add_coin(MIN_CHANGE * 5 / 10);
- add_coin(MIN_CHANGE * 6 / 10);
- add_coin(MIN_CHANGE * 7 / 10);
- add_coin(1111 * MIN_CHANGE);
- BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
-
- // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
- empty_wallet();
- add_coin(MIN_CHANGE * 4 / 10);
- add_coin(MIN_CHANGE * 6 / 10);
- add_coin(MIN_CHANGE * 8 / 10);
- add_coin(1111 * MIN_CHANGE);
- BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6
-
- // test avoiding small change
- empty_wallet();
- add_coin(MIN_CHANGE * 5 / 100);
- add_coin(MIN_CHANGE * 1);
- add_coin(MIN_CHANGE * 100);
-
- // trying to make 100.01 from these three coins
- BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
-
- // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
- BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
-
- // test with many inputs
- for (CAmount amt=1500; amt < COIN; amt*=10) {
- empty_wallet();
- // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
- for (uint16_t j = 0; j < 676; j++)
- add_coin(amt);
- BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
- if (amt - 2000 < MIN_CHANGE) {
- // needs more than one input:
- uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt);
- CAmount returnValue = amt * returnSize;
- BOOST_CHECK_EQUAL(nValueRet, returnValue);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
- } else {
- // one input is sufficient:
- BOOST_CHECK_EQUAL(nValueRet, amt);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
- }
- }
-
- // test randomness
- {
- empty_wallet();
- for (int i2 = 0; i2 < 100; i2++)
- add_coin(COIN);
-
- // picking 50 from 100 coins doesn't depend on the shuffle,
- // but does depend on randomness in the stochastic approximation code
- BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
- BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
- BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
-
- int fails = 0;
- for (int j = 0; j < RANDOM_REPEATS; j++)
- {
- // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
- // run the test RANDOM_REPEATS times and only complain if all of them fail
- BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
- BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
- if (equal_sets(setCoinsRet, setCoinsRet2))
- fails++;
- }
- BOOST_CHECK_NE(fails, RANDOM_REPEATS);
-
- // add 75 cents in small change. not enough to make 90 cents,
- // then try making 90 cents. there are multiple competing "smallest bigger" coins,
- // one of which should be picked at random
- add_coin(5 * CENT);
- add_coin(10 * CENT);
- add_coin(15 * CENT);
- add_coin(20 * CENT);
- add_coin(25 * CENT);
-
- fails = 0;
- for (int j = 0; j < RANDOM_REPEATS; j++)
- {
- // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
- // run the test RANDOM_REPEATS times and only complain if all of them fail
- BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
- BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
- if (equal_sets(setCoinsRet, setCoinsRet2))
- fails++;
- }
- BOOST_CHECK_NE(fails, RANDOM_REPEATS);
- }
- }
- empty_wallet();
-}
-
-BOOST_AUTO_TEST_CASE(ApproximateBestSubset)
-{
- CoinSet setCoinsRet;
- CAmount nValueRet;
-
- LOCK(testWallet.cs_wallet);
-
- empty_wallet();
-
- // Test vValue sort order
- for (int i = 0; i < 1000; i++)
- add_coin(1000 * COIN);
- add_coin(3 * COIN);
-
- BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
- BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
- BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
-
- empty_wallet();
-}
-
static void AddKey(CWallet& wallet, const CKey& key)
{
LOCK(wallet.cs_wallet);
@@ -451,9 +115,6 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
// than or equal to key birthday.
BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
{
- g_address_type = OUTPUT_TYPE_DEFAULT;
- g_change_type = OUTPUT_TYPE_DEFAULT;
-
// Create two blocks with same timestamp to verify that importwallet rescan
// will pick up both blocks, not just the first.
const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5;
@@ -553,7 +214,10 @@ static int64_t AddTx(CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64
if (block) {
wtx.SetMerkleBranch(block, 0);
}
- wallet.AddToWallet(wtx);
+ {
+ LOCK(cs_main);
+ wallet.AddToWallet(wtx);
+ }
LOCK(wallet.cs_wallet);
return wallet.mapWallet.at(wtx.GetHash()).nTimeSmart;
}
@@ -606,8 +270,6 @@ public:
ListCoinsTestingSetup()
{
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
- g_address_type = OUTPUT_TYPE_DEFAULT;
- g_change_type = OUTPUT_TYPE_DEFAULT;
wallet = MakeUnique<CWallet>("mock", CWalletDBWrapper::CreateMock());
bool firstRun;
wallet->LoadWallet(firstRun);
@@ -624,23 +286,23 @@ public:
CWalletTx& AddTx(CRecipient recipient)
{
- CWalletTx wtx;
+ CTransactionRef tx;
CReserveKey reservekey(wallet.get());
CAmount fee;
int changePos = -1;
std::string error;
CCoinControl dummy;
- BOOST_CHECK(wallet->CreateTransaction({recipient}, wtx, reservekey, fee, changePos, error, dummy));
+ BOOST_CHECK(wallet->CreateTransaction({recipient}, tx, reservekey, fee, changePos, error, dummy));
CValidationState state;
- BOOST_CHECK(wallet->CommitTransaction(wtx, reservekey, nullptr, state));
+ BOOST_CHECK(wallet->CommitTransaction(tx, {}, {}, {}, reservekey, nullptr, state));
CMutableTransaction blocktx;
{
LOCK(wallet->cs_wallet);
- blocktx = CMutableTransaction(*wallet->mapWallet.at(wtx.GetHash()).tx);
+ blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
}
CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
LOCK(wallet->cs_wallet);
- auto it = wallet->mapWallet.find(wtx.GetHash());
+ auto it = wallet->mapWallet.find(tx->GetHash());
BOOST_CHECK(it != wallet->mapWallet.end());
it->second.SetMerkleBranch(chainActive.Tip(), 1);
return it->second;
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index 0c468878e1..8dac547abb 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -8,10 +8,10 @@
#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>
@@ -41,8 +41,6 @@ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
bool fWalletRbf = DEFAULT_WALLET_RBF;
-OutputType g_address_type = OUTPUT_TYPE_NONE;
-OutputType g_change_type = OUTPUT_TYPE_NONE;
bool g_wallet_allow_fallback_fee = true; //<! will be defined via chainparams
const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
@@ -68,15 +66,6 @@ const uint256 CMerkleTx::ABANDON_HASH(uint256S("00000000000000000000000000000000
* @{
*/
-struct CompareValueOnly
-{
- bool operator()(const CInputCoin& t1,
- const CInputCoin& t2) const
- {
- return t1.txout.nValue < t2.txout.nValue;
- }
-};
-
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
@@ -531,7 +520,7 @@ void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> ran
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = nullptr;
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
- const CWalletTx* wtx = &mapWallet[it->second];
+ const CWalletTx* wtx = &mapWallet.at(it->second);
if (wtx->nOrderPos < nMinOrderPos) {
nMinOrderPos = wtx->nOrderPos;;
copyFrom = wtx;
@@ -544,7 +533,7 @@ void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> ran
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
- CWalletTx* copyTo = &mapWallet[hash];
+ CWalletTx* copyTo = &mapWallet.at(hash);
if (copyFrom == copyTo) continue;
assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
@@ -737,11 +726,11 @@ DBErrors CWallet::ReorderTransactions()
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
- return DB_LOAD_FAIL;
+ return DBErrors::LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
- return DB_LOAD_FAIL;
+ return DBErrors::LOAD_FAIL;
}
else
{
@@ -761,16 +750,16 @@ DBErrors CWallet::ReorderTransactions()
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
- return DB_LOAD_FAIL;
+ return DBErrors::LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
- return DB_LOAD_FAIL;
+ return DBErrors::LOAD_FAIL;
}
}
walletdb.WriteOrderPosNext(nOrderPosNext);
- return DB_LOAD_OK;
+ return DBErrors::LOAD_OK;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
@@ -819,19 +808,19 @@ bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmoun
return true;
}
-bool CWallet::GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew)
+bool CWallet::GetLabelDestination(CTxDestination &dest, const std::string& label, bool bForceNew)
{
CWalletDB walletdb(*dbw);
CAccount account;
- walletdb.ReadAccount(strAccount, account);
+ walletdb.ReadAccount(label, account);
if (!bForceNew) {
if (!account.vchPubKey.IsValid())
bForceNew = true;
else {
// Check if the current key has been used (TODO: check other addresses with the same key)
- CScript scriptPubKey = GetScriptForDestination(GetDestinationForKey(account.vchPubKey, g_address_type));
+ CScript scriptPubKey = GetScriptForDestination(GetDestinationForKey(account.vchPubKey, m_default_address_type));
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && account.vchPubKey.IsValid();
++it)
@@ -848,12 +837,12 @@ bool CWallet::GetAccountDestination(CTxDestination &dest, std::string strAccount
if (!GetKeyFromPool(account.vchPubKey, false))
return false;
- LearnRelatedScripts(account.vchPubKey, g_address_type);
- dest = GetDestinationForKey(account.vchPubKey, g_address_type);
- SetAddressBook(dest, strAccount, "receive");
- walletdb.WriteAccount(strAccount, account);
+ LearnRelatedScripts(account.vchPubKey, m_default_address_type);
+ dest = GetDestinationForKey(account.vchPubKey, m_default_address_type);
+ SetAddressBook(dest, label, "receive");
+ walletdb.WriteAccount(label, account);
} else {
- dest = GetDestinationForKey(account.vchPubKey, g_address_type);
+ dest = GetDestinationForKey(account.vchPubKey, m_default_address_type);
}
return true;
@@ -888,7 +877,7 @@ bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
bool success = true;
if (!walletdb.WriteTx(wtx)) {
- LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
+ LogPrintf("%s: Updating walletdb tx %s failed\n", __func__, wtx.GetHash().ToString());
success = false;
}
@@ -1147,11 +1136,9 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
LOCK2(cs_main, cs_wallet);
int conflictconfirms = 0;
- if (mapBlockIndex.count(hashBlock)) {
- CBlockIndex* pindex = mapBlockIndex[hashBlock];
- if (chainActive.Contains(pindex)) {
- conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
- }
+ CBlockIndex* pindex = LookupBlockIndex(hashBlock);
+ if (pindex && chainActive.Contains(pindex)) {
+ conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
}
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
@@ -1279,7 +1266,7 @@ void CWallet::BlockUntilSyncedToCurrentChain() {
// chainActive.Tip()...
// We could also take cs_wallet here, and call m_last_block_processed
// protected by cs_wallet instead of cs_main, but as long as we need
- // cs_main here anyway, its easier to just call it cs_main-protected.
+ // cs_main here anyway, it's easier to just call it cs_main-protected.
LOCK(cs_main);
const CBlockIndex* initialChainTip = chainActive.Tip();
@@ -1543,6 +1530,79 @@ int CWalletTx::GetRequestCount() const
return nRequests;
}
+// Helper for producing a max-sized low-S signature (eg 72 bytes)
+bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout) const
+{
+ // Fill in dummy signatures for fee calculation.
+ const CScript& scriptPubKey = txout.scriptPubKey;
+ SignatureData sigdata;
+
+ if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
+ {
+ return false;
+ } else {
+ UpdateInput(tx_in, sigdata);
+ }
+ return true;
+}
+
+// Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
+bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts) const
+{
+ // Fill in dummy signatures for fee calculation.
+ int nIn = 0;
+ for (const auto& txout : txouts)
+ {
+ if (!DummySignInput(txNew.vin[nIn], txout)) {
+ return false;
+ }
+
+ nIn++;
+ }
+ return true;
+}
+
+int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet)
+{
+ std::vector<CTxOut> txouts;
+ // Look up the inputs. We should have already checked that this transaction
+ // IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our
+ // wallet, with a valid index into the vout array, and the ability to sign.
+ for (auto& input : tx.vin) {
+ const auto mi = wallet->mapWallet.find(input.prevout.hash);
+ if (mi == wallet->mapWallet.end()) {
+ return -1;
+ }
+ assert(input.prevout.n < mi->second.tx->vout.size());
+ txouts.emplace_back(mi->second.tx->vout[input.prevout.n]);
+ }
+ return CalculateMaximumSignedTxSize(tx, wallet, txouts);
+}
+
+// txouts needs to be in the order of tx.vin
+int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts)
+{
+ CMutableTransaction txNew(tx);
+ if (!wallet->DummySignTx(txNew, txouts)) {
+ // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
+ // implies that we can sign for every input.
+ return -1;
+ }
+ return GetVirtualTransactionSize(txNew);
+}
+
+int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet)
+{
+ CMutableTransaction txn;
+ txn.vin.push_back(CTxIn(COutPoint()));
+ if (!wallet->DummySignInput(txn.vin[0], txout)) {
+ // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
+ // implies that we can sign for every input.
+ return -1;
+ }
+ return GetVirtualTransactionInputSize(txn.vin[0]);
+}
+
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
{
@@ -2159,7 +2219,7 @@ CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, cons
for (const CTxOut& out : wtx.tx->vout) {
if (outgoing && IsChange(out)) {
debit -= out.nValue;
- } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
+ } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetLabelName(out.scriptPubKey))) {
balance += out.nValue;
}
}
@@ -2364,171 +2424,88 @@ const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int out
return ptx->vout[n];
}
-static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
- std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
+bool CWallet::OutputEligibleForSpending(const COutput& output, const CoinEligibilityFilter& eligibility_filter) const
{
- std::vector<char> vfIncluded;
+ if (!output.fSpendable)
+ return false;
- vfBest.assign(vValue.size(), true);
- nBest = nTotalLower;
+ if (output.nDepth < (output.tx->IsFromMe(ISMINE_ALL) ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs))
+ return false;
- FastRandomContext insecure_rand;
+ if (!mempool.TransactionWithinChainLimit(output.tx->GetHash(), eligibility_filter.max_ancestors))
+ return false;
- for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
- {
- vfIncluded.assign(vValue.size(), false);
- CAmount nTotal = 0;
- bool fReachedTarget = false;
- for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
- {
- for (unsigned int i = 0; i < vValue.size(); i++)
- {
- //The solver here uses a randomized algorithm,
- //the randomness serves no real security purpose but is just
- //needed to prevent degenerate behavior and it is important
- //that the rng is fast. We do not use a constant random sequence,
- //because there may be some privacy improvement by making
- //the selection random.
- if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
- {
- nTotal += vValue[i].txout.nValue;
- vfIncluded[i] = true;
- if (nTotal >= nTargetValue)
- {
- fReachedTarget = true;
- if (nTotal < nBest)
- {
- nBest = nTotal;
- vfBest = vfIncluded;
- }
- nTotal -= vValue[i].txout.nValue;
- vfIncluded[i] = false;
- }
- }
- }
- }
- }
+ return true;
}
-bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
- std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
+bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<COutput> vCoins,
+ std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const
{
setCoinsRet.clear();
nValueRet = 0;
- // List of values less than target
- boost::optional<CInputCoin> coinLowestLarger;
- std::vector<CInputCoin> vValue;
- CAmount nTotalLower = 0;
-
- random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
-
- for (const COutput &output : vCoins)
- {
- if (!output.fSpendable)
- continue;
-
- const CWalletTx *pcoin = output.tx;
-
- if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
- continue;
-
- if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
- continue;
-
- int i = output.i;
+ std::vector<CInputCoin> utxo_pool;
+ if (coin_selection_params.use_bnb) {
- CInputCoin coin = CInputCoin(pcoin, i);
+ // Get long term estimate
+ FeeCalculation feeCalc;
+ CCoinControl temp;
+ temp.m_confirm_target = 1008;
+ CFeeRate long_term_feerate = GetMinimumFeeRate(temp, ::mempool, ::feeEstimator, &feeCalc);
- if (coin.txout.nValue == nTargetValue)
- {
- setCoinsRet.insert(coin);
- nValueRet += coin.txout.nValue;
- return true;
- }
- else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
- {
- vValue.push_back(coin);
- nTotalLower += coin.txout.nValue;
- }
- else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
- {
- coinLowestLarger = coin;
- }
- }
+ // Calculate cost of change
+ CAmount cost_of_change = GetDiscardRate(::feeEstimator).GetFee(coin_selection_params.change_spend_size) + coin_selection_params.effective_fee.GetFee(coin_selection_params.change_output_size);
- if (nTotalLower == nTargetValue)
- {
- for (const auto& input : vValue)
+ // Filter by the min conf specs and add to utxo_pool and calculate effective value
+ for (const COutput &output : vCoins)
{
- setCoinsRet.insert(input);
- nValueRet += input.txout.nValue;
- }
- return true;
- }
-
- if (nTotalLower < nTargetValue)
- {
- if (!coinLowestLarger)
- return false;
- setCoinsRet.insert(coinLowestLarger.get());
- nValueRet += coinLowestLarger->txout.nValue;
- return true;
- }
-
- // Solve subset sum by stochastic approximation
- std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
- std::reverse(vValue.begin(), vValue.end());
- std::vector<char> vfBest;
- CAmount nBest;
-
- ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
- if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
- ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
+ if (!OutputEligibleForSpending(output, eligibility_filter))
+ continue;
- // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
- // or the next bigger coin is closer), return the bigger coin
- if (coinLowestLarger &&
- ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
- {
- setCoinsRet.insert(coinLowestLarger.get());
- nValueRet += coinLowestLarger->txout.nValue;
- }
- else {
- for (unsigned int i = 0; i < vValue.size(); i++)
- if (vfBest[i])
- {
- setCoinsRet.insert(vValue[i]);
- nValueRet += vValue[i].txout.nValue;
+ CInputCoin coin(output.tx->tx, output.i);
+ coin.effective_value = coin.txout.nValue - (output.nInputBytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(output.nInputBytes));
+ // Only include outputs that are positive effective value (i.e. not dust)
+ if (coin.effective_value > 0) {
+ coin.fee = output.nInputBytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(output.nInputBytes);
+ coin.long_term_fee = output.nInputBytes < 0 ? 0 : long_term_feerate.GetFee(output.nInputBytes);
+ utxo_pool.push_back(coin);
}
+ }
+ // Calculate the fees for things that aren't inputs
+ CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size);
+ bnb_used = true;
+ return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
+ } else {
+ // Filter by the min conf specs and add to utxo_pool
+ for (const COutput &output : vCoins)
+ {
+ if (!OutputEligibleForSpending(output, eligibility_filter))
+ continue;
- if (LogAcceptCategory(BCLog::SELECTCOINS)) {
- LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
- for (unsigned int i = 0; i < vValue.size(); i++) {
- if (vfBest[i]) {
- LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
- }
- }
- LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
+ CInputCoin coin = CInputCoin(output.tx->tx, output.i);
+ utxo_pool.push_back(coin);
}
+ bnb_used = false;
+ return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
}
-
- return true;
}
-bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
+bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const
{
std::vector<COutput> vCoins(vAvailableCoins);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
- if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
+ if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs)
{
+ // We didn't use BnB here, so set it to false.
+ bnb_used = false;
+
for (const COutput& out : vCoins)
{
if (!out.fSpendable)
continue;
nValueRet += out.tx->tx->vout[out.i].nValue;
- setCoinsRet.insert(CInputCoin(out.tx, out.i));
+ setCoinsRet.insert(CInputCoin(out.tx->tx, out.i));
}
return (nValueRet >= nTargetValue);
}
@@ -2538,10 +2515,13 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs;
- if (coinControl)
- coinControl->ListSelected(vPresetInputs);
+ coin_control.ListSelected(vPresetInputs);
for (const COutPoint& outpoint : vPresetInputs)
{
+ // For now, don't use BnB if preset inputs are selected. TODO: Enable this later
+ bnb_used = false;
+ coin_selection_params.use_bnb = false;
+
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
@@ -2549,16 +2529,17 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
// Clearly invalid input, fail
if (pcoin->tx->vout.size() <= outpoint.n)
return false;
+ // Just to calculate the marginal byte size
nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
- setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
+ setPresetCoins.insert(CInputCoin(pcoin->tx, outpoint.n));
} else
return false; // TODO: Allow non-wallet inputs
}
// remove preset inputs from vCoins
- for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
+ for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();)
{
- if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
+ if (setPresetCoins.count(CInputCoin(it->tx->tx, it->i)))
it = vCoins.erase(it);
else
++it;
@@ -2568,13 +2549,13 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
bool res = nTargetValue <= nValueFromPresetInputs ||
- SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
- SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
- (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
- (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
- (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
- (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
- (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
+ SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 6, 0), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
+ SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 1, 0), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
+ (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, 2), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
+ (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::min((size_t)4, nMaxChainLength/3)), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
+ (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, nMaxChainLength/2), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
+ (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, nMaxChainLength), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
+ (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()), vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
@@ -2631,13 +2612,13 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
LOCK2(cs_main, cs_wallet);
CReserveKey reservekey(this);
- CWalletTx wtx;
- if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
+ CTransactionRef tx_new;
+ if (!CreateTransaction(vecSend, tx_new, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
return false;
}
if (nChangePosInOut != -1) {
- tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
+ tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
// We don't have the normal Create/Commit cycle, and don't want to risk
// reusing change, so just remove the key from the keypool here.
reservekey.KeepKey();
@@ -2646,11 +2627,11 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
// Copy output sizes from new transaction; they may have had the fee
// subtracted from them.
for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
- tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
+ tx.vout[idx].nValue = tx_new->vout[idx].nValue;
}
// Add new txins while keeping original txin scriptSig/order.
- for (const CTxIn& txin : wtx.tx->vin) {
+ for (const CTxIn& txin : tx_new->vin) {
if (!coinControl.IsSelected(txin.prevout)) {
tx.vin.push_back(txin);
@@ -2666,14 +2647,14 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend)
{
// If -changetype is specified, always use that change type.
- if (change_type != OUTPUT_TYPE_NONE) {
+ if (change_type != OutputType::NONE) {
return change_type;
}
- // if g_address_type is legacy, use legacy address as change (even
+ // if m_default_address_type is legacy, use legacy address as change (even
// if some of the outputs are P2WPKH or P2WSH).
- if (g_address_type == OUTPUT_TYPE_LEGACY) {
- return OUTPUT_TYPE_LEGACY;
+ if (m_default_address_type == OutputType::LEGACY) {
+ return OutputType::LEGACY;
}
// if any destination is P2WPKH or P2WSH, use P2WPKH for the change
@@ -2683,15 +2664,15 @@ OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vec
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
- return OUTPUT_TYPE_BECH32;
+ return OutputType::BECH32;
}
}
- // else use g_address_type for change
- return g_address_type;
+ // else use m_default_address_type for change
+ return m_default_address_type;
}
-bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
+bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet,
int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
{
CAmount nValue = 0;
@@ -2715,8 +2696,6 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
return false;
}
- wtxNew.fTimeReceivedIsTxTime = true;
- wtxNew.BindWallet(this);
CMutableTransaction txNew;
// Discourage fee sniping.
@@ -2752,13 +2731,14 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
FeeCalculation feeCalc;
CAmount nFeeNeeded;
- unsigned int nBytes;
+ int nBytes;
{
std::set<CInputCoin> setCoins;
LOCK2(cs_main, cs_wallet);
{
std::vector<COutput> vAvailableCoins;
AvailableCoins(vAvailableCoins, true, &coin_control);
+ CoinSelectionParams coin_selection_params; // Parameters for coin selection, init with dummy
// Create change script that will be used if we need change
// TODO: pass in scriptChange instead of reservekey so
@@ -2786,31 +2766,40 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
return false;
}
- const OutputType change_type = TransactionChangeType(coin_control.change_type, vecSend);
+ const OutputType change_type = TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : m_default_change_type, vecSend);
LearnRelatedScripts(vchPubKey, change_type);
scriptChange = GetScriptForDestination(GetDestinationForKey(vchPubKey, change_type));
}
CTxOut change_prototype_txout(0, scriptChange);
- size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
+ coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
+
+ // Get the fee rate to use effective values in coin selection
+ CFeeRate nFeeRateNeeded = GetMinimumFeeRate(coin_control, ::mempool, ::feeEstimator, &feeCalc);
+
nFeeRet = 0;
bool pick_new_inputs = true;
CAmount nValueIn = 0;
+
+ // BnB selector is the only selector used when this is true.
+ // That should only happen on the first pass through the loop.
+ coin_selection_params.use_bnb = nSubtractFeeFromAmount == 0; // If we are doing subtract fee from recipient, then don't use BnB
// Start with no fee and loop until there is enough fee
while (true)
{
nChangePosInOut = nChangePosRequest;
txNew.vin.clear();
txNew.vout.clear();
- wtxNew.fFromMe = true;
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (nSubtractFeeFromAmount == 0)
nValueToSelect += nFeeRet;
+
// vouts to the payees
+ coin_selection_params.tx_noinputs_size = 11; // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 output count, 1 witness overhead (dummy, flag, stack size)
for (const auto& recipient : vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
@@ -2826,6 +2815,8 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
}
}
+ // Include the fee cost for outputs. Note this is only used for BnB right now
+ coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, SER_NETWORK, PROTOCOL_VERSION);
if (IsDust(txout, ::dustRelayFee))
{
@@ -2844,18 +2835,27 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
}
// Choose coins to use
+ bool bnb_used;
if (pick_new_inputs) {
nValueIn = 0;
setCoins.clear();
- if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
+ coin_selection_params.change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, this);
+ coin_selection_params.effective_fee = nFeeRateNeeded;
+ if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coin_control, coin_selection_params, bnb_used))
{
- strFailReason = _("Insufficient funds");
- return false;
+ // If BnB was used, it was the first pass. No longer the first pass and continue loop with knapsack.
+ if (bnb_used) {
+ coin_selection_params.use_bnb = false;
+ continue;
+ }
+ else {
+ strFailReason = _("Insufficient funds");
+ return false;
+ }
}
}
const CAmount nChange = nValueIn - nValueToSelect;
-
if (nChange > 0)
{
// Fill a vout to ourself
@@ -2863,7 +2863,8 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
// Never create dust outputs; if we would, just
// add the dust to the fee.
- if (IsDust(newTxOut, discard_rate))
+ // The nChange when BnB is used is always going to go to fees.
+ if (IsDust(newTxOut, discard_rate) || bnb_used)
{
nChangePosInOut = -1;
nFeeRet += nChange;
@@ -2888,33 +2889,16 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
nChangePosInOut = -1;
}
- // Fill vin
- //
- // Note how the sequence number is set to non-maxint so that
- // the nLockTime set above actually works.
+ // Dummy fill vin for maximum size estimation
//
- // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
- // we use the highest possible value in that range (maxint-2)
- // to avoid conflicting with other possible uses of nSequence,
- // and in the spirit of "smallest possible change from prior
- // behavior."
- const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
- for (const auto& coin : setCoins)
- txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
- nSequence));
-
- // Fill in dummy signatures for fee calculation.
- if (!DummySignTx(txNew, setCoins)) {
- strFailReason = _("Signing transaction failed");
- return false;
+ for (const auto& coin : setCoins) {
+ txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));
}
- nBytes = GetVirtualTransactionSize(txNew);
-
- // Remove scriptSigs to eliminate the fee calculation dummy signatures
- for (auto& vin : txNew.vin) {
- vin.scriptSig = CScript();
- vin.scriptWitness.SetNull();
+ nBytes = CalculateMaximumSignedTxSize(txNew, this);
+ if (nBytes < 0) {
+ strFailReason = _("Signing transaction failed");
+ return false;
}
nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
@@ -2944,7 +2928,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
// (because of reduced tx size) and so we should add a
// change output. Only try this once.
if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
- unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
+ unsigned int tx_size_with_change = nBytes + coin_selection_params.change_output_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
@@ -2992,17 +2976,36 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
// Include more fee and try again.
nFeeRet = nFeeNeeded;
+ coin_selection_params.use_bnb = false;
continue;
}
}
if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
+ // Shuffle selected coins and fill in final vin
+ txNew.vin.clear();
+ std::vector<CInputCoin> selected_coins(setCoins.begin(), setCoins.end());
+ std::shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());
+
+ // Note how the sequence number is set to non-maxint so that
+ // the nLockTime set above actually works.
+ //
+ // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
+ // we use the highest possible value in that range (maxint-2)
+ // to avoid conflicting with other possible uses of nSequence,
+ // and in the spirit of "smallest possible change from prior
+ // behavior."
+ const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
+ for (const auto& coin : selected_coins) {
+ txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
+ }
+
if (sign)
{
CTransaction txNewConst(txNew);
int nIn = 0;
- for (const auto& coin : setCoins)
+ for (const auto& coin : selected_coins)
{
const CScript& scriptPubKey = coin.txout.scriptPubKey;
SignatureData sigdata;
@@ -3019,11 +3022,11 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
}
}
- // Embed the constructed transaction data in wtxNew.
- wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
+ // Return the constructed transaction data.
+ tx = MakeTransactionRef(std::move(txNew));
// Limit size
- if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
+ if (GetTransactionWeight(*tx) >= MAX_STANDARD_TX_WEIGHT)
{
strFailReason = _("Transaction too large");
return false;
@@ -3033,7 +3036,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
// Lastly, ensure this tx will pass the mempool's chain limits
LockPoints lp;
- CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
+ CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp);
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
@@ -3060,10 +3063,18 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
/**
* Call after CreateTransaction unless you want to abort
*/
-bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
+bool CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm, std::string fromAccount, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
{
{
LOCK2(cs_main, cs_wallet);
+
+ CWalletTx wtxNew(this, std::move(tx));
+ wtxNew.mapValue = std::move(mapValue);
+ wtxNew.vOrderForm = std::move(orderForm);
+ wtxNew.strFromAccount = std::move(fromAccount);
+ wtxNew.fTimeReceivedIsTxTime = true;
+ wtxNew.fFromMe = true;
+
LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
{
// Take key pair from key pool so it won't be used again
@@ -3076,7 +3087,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CCon
// Notify that old coins are spent
for (const CTxIn& txin : wtxNew.tx->vin)
{
- CWalletTx &coin = mapWallet[txin.prevout.hash];
+ CWalletTx &coin = mapWallet.at(txin.prevout.hash);
coin.BindWallet(this);
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
@@ -3087,7 +3098,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CCon
// Get the inserted-CWalletTx from mapWallet so that the
// fInMempool flag is cached properly
- CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
+ CWalletTx& wtx = mapWallet.at(wtxNew.GetHash());
if (fBroadcastTransactions)
{
@@ -3134,7 +3145,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
- if (nLoadWalletRet == DB_NEED_REWRITE)
+ if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
@@ -3150,12 +3161,12 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
// This wallet is in its first run if all of these are empty
fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
- if (nLoadWalletRet != DB_LOAD_OK)
+ if (nLoadWalletRet != DBErrors::LOAD_OK)
return nLoadWalletRet;
uiInterface.LoadWallet(this);
- return DB_LOAD_OK;
+ return DBErrors::LOAD_OK;
}
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
@@ -3165,7 +3176,7 @@ DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256
for (uint256 hash : vHashOut)
mapWallet.erase(hash);
- if (nZapSelectTxRet == DB_NEED_REWRITE)
+ if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
@@ -3178,19 +3189,19 @@ DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256
}
}
- if (nZapSelectTxRet != DB_LOAD_OK)
+ if (nZapSelectTxRet != DBErrors::LOAD_OK)
return nZapSelectTxRet;
MarkDirty();
- return DB_LOAD_OK;
+ return DBErrors::LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
- if (nZapWalletTxRet == DB_NEED_REWRITE)
+ if (nZapWalletTxRet == DBErrors::NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
@@ -3204,10 +3215,10 @@ DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
}
}
- if (nZapWalletTxRet != DB_LOAD_OK)
+ if (nZapWalletTxRet != DBErrors::LOAD_OK)
return nZapWalletTxRet;
- return DB_LOAD_OK;
+ return DBErrors::LOAD_OK;
}
@@ -3249,7 +3260,7 @@ bool CWallet::DelAddressBook(const CTxDestination& address)
return CWalletDB(*dbw).EraseName(EncodeDestination(address));
}
-const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
+const std::string& CWallet::GetLabelName(const CScript& scriptPubKey) const
{
CTxDestination address;
if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
@@ -3259,9 +3270,9 @@ const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
}
}
// A scriptPubKey that doesn't have an entry in the address book is
- // associated with the default account ("").
- const static std::string DEFAULT_ACCOUNT_NAME;
- return DEFAULT_ACCOUNT_NAME;
+ // associated with the default label ("").
+ const static std::string DEFAULT_LABEL_NAME;
+ return DEFAULT_LABEL_NAME;
}
/**
@@ -3543,7 +3554,7 @@ std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
- if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
+ if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
@@ -3617,7 +3628,7 @@ std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
return ret;
}
-std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
+std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
{
LOCK(cs_wallet);
std::set<CTxDestination> result;
@@ -3625,7 +3636,7 @@ std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAcco
{
const CTxDestination& address = item.first;
const std::string& strName = item.second.name;
- if (strName == strAccount)
+ if (strName == label)
result.insert(address);
}
return result;
@@ -3767,10 +3778,10 @@ void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) c
for (const auto& entry : mapWallet) {
// iterate over all wallet transactions...
const CWalletTx &wtx = entry.second;
- BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
- if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
+ CBlockIndex* pindex = LookupBlockIndex(wtx.hashBlock);
+ if (pindex && chainActive.Contains(pindex)) {
// ... which are already in a block
- int nHeight = blit->second->nHeight;
+ int nHeight = pindex->nHeight;
for (const CTxOut &txout : wtx.tx->vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
@@ -3778,7 +3789,7 @@ void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) c
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
- rit->second = blit->second;
+ rit->second = pindex;
}
vAffected.clear();
}
@@ -3815,7 +3826,7 @@ unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (!wtx.hashUnset()) {
- if (mapBlockIndex.count(wtx.hashBlock)) {
+ if (const CBlockIndex* pindex = LookupBlockIndex(wtx.hashBlock)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
@@ -3846,7 +3857,7 @@ unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
}
}
- int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
+ int64_t blocktime = pindex->GetBlockTime();
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else {
LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
@@ -3919,7 +3930,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(name, CWalletDBWrapper::Create(path));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
- if (nZapWalletRet != DB_LOAD_OK) {
+ if (nZapWalletRet != DBErrors::LOAD_OK) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
@@ -3931,23 +3942,23 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
bool fFirstRun = true;
CWallet *walletInstance = new CWallet(name, CWalletDBWrapper::Create(path));
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
- if (nLoadWalletRet != DB_LOAD_OK)
+ if (nLoadWalletRet != DBErrors::LOAD_OK)
{
- if (nLoadWalletRet == DB_CORRUPT) {
+ if (nLoadWalletRet == DBErrors::CORRUPT) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
- else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
+ else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
{
InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."),
walletFile));
}
- else if (nLoadWalletRet == DB_TOO_NEW) {
+ else if (nLoadWalletRet == DBErrors::TOO_NEW) {
InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
return nullptr;
}
- else if (nLoadWalletRet == DB_NEED_REWRITE)
+ else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
{
InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
return nullptr;
@@ -3998,8 +4009,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
}
walletInstance->SetBestChain(chainActive.GetLocator());
- }
- else if (gArgs.IsArgSet("-usehd")) {
+ } else if (gArgs.IsArgSet("-usehd")) {
bool useHD = gArgs.GetBoolArg("-usehd", true);
if (walletInstance->IsHDEnabled() && !useHD) {
InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
@@ -4011,11 +4021,27 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
}
}
+ walletInstance->m_default_address_type = ParseOutputType(gArgs.GetArg("-addresstype", ""), DEFAULT_ADDRESS_TYPE);
+ if (walletInstance->m_default_address_type == OutputType::NONE) {
+ InitError(strprintf("Unknown address type '%s'", gArgs.GetArg("-addresstype", "")));
+ return nullptr;
+ }
+
+ // If changetype is set in config file or parameter, check that it's valid.
+ // Default to OutputType::NONE if not set.
+ walletInstance->m_default_change_type = ParseOutputType(gArgs.GetArg("-changetype", ""), OutputType::NONE);
+ if (walletInstance->m_default_change_type == OutputType::NONE && !gArgs.GetArg("-changetype", "").empty()) {
+ InitError(strprintf("Unknown change type '%s'", gArgs.GetArg("-changetype", "")));
+ return nullptr;
+ }
+
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
// Try to top up keypool. No-op if the wallet is locked.
walletInstance->TopUpKeyPool();
+ LOCK(cs_main);
+
CBlockIndex *pindexRescan = chainActive.Genesis();
if (!gArgs.GetBoolArg("-rescan", false))
{
@@ -4159,10 +4185,7 @@ int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
AssertLockHeld(cs_main);
// Find the block it claims to be in
- BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
- if (mi == mapBlockIndex.end())
- return 0;
- CBlockIndex* pindex = (*mi).second;
+ CBlockIndex* pindex = LookupBlockIndex(hashBlock);
if (!pindex || !chainActive.Contains(pindex))
return 0;
@@ -4183,8 +4206,8 @@ bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState&
// We must set fInMempool here - while it will be re-set to true by the
// entered-mempool callback, if we did not there would be a race where a
// user could call sendmoney in a loop and hit spurious out of funds errors
- // because we think that the transaction they just generated's change is
- // unavailable as we're not yet aware its in mempool.
+ // because we think that this newly generated transaction's change is
+ // unavailable as we're not yet aware that it is in the mempool.
bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
fInMempool |= ret;
@@ -4200,29 +4223,29 @@ OutputType ParseOutputType(const std::string& type, OutputType default_type)
if (type.empty()) {
return default_type;
} else if (type == OUTPUT_TYPE_STRING_LEGACY) {
- return OUTPUT_TYPE_LEGACY;
+ return OutputType::LEGACY;
} else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) {
- return OUTPUT_TYPE_P2SH_SEGWIT;
+ return OutputType::P2SH_SEGWIT;
} else if (type == OUTPUT_TYPE_STRING_BECH32) {
- return OUTPUT_TYPE_BECH32;
+ return OutputType::BECH32;
} else {
- return OUTPUT_TYPE_NONE;
+ return OutputType::NONE;
}
}
const std::string& FormatOutputType(OutputType type)
{
switch (type) {
- case OUTPUT_TYPE_LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
- case OUTPUT_TYPE_P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
- case OUTPUT_TYPE_BECH32: return OUTPUT_TYPE_STRING_BECH32;
+ case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
+ case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
+ case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32;
default: assert(false);
}
}
void CWallet::LearnRelatedScripts(const CPubKey& key, OutputType type)
{
- if (key.IsCompressed() && (type == OUTPUT_TYPE_P2SH_SEGWIT || type == OUTPUT_TYPE_BECH32)) {
+ if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
CTxDestination witdest = WitnessV0KeyHash(key.GetID());
CScript witprog = GetScriptForDestination(witdest);
// Make sure the resulting program is solvable.
@@ -4233,20 +4256,20 @@ void CWallet::LearnRelatedScripts(const CPubKey& key, OutputType type)
void CWallet::LearnAllRelatedScripts(const CPubKey& key)
{
- // OUTPUT_TYPE_P2SH_SEGWIT always adds all necessary scripts for all types.
- LearnRelatedScripts(key, OUTPUT_TYPE_P2SH_SEGWIT);
+ // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
+ LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
}
CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
{
switch (type) {
- case OUTPUT_TYPE_LEGACY: return key.GetID();
- case OUTPUT_TYPE_P2SH_SEGWIT:
- case OUTPUT_TYPE_BECH32: {
+ case OutputType::LEGACY: return key.GetID();
+ case OutputType::P2SH_SEGWIT:
+ case OutputType::BECH32: {
if (!key.IsCompressed()) return key.GetID();
CTxDestination witdest = WitnessV0KeyHash(key.GetID());
CScript witprog = GetScriptForDestination(witdest);
- if (type == OUTPUT_TYPE_P2SH_SEGWIT) {
+ if (type == OutputType::P2SH_SEGWIT) {
return CScriptID(witprog);
} else {
return witdest;
@@ -4272,10 +4295,10 @@ CTxDestination CWallet::AddAndGetDestinationForScript(const CScript& script, Out
{
// Note that scripts over 520 bytes are not yet supported.
switch (type) {
- case OUTPUT_TYPE_LEGACY:
+ case OutputType::LEGACY:
return CScriptID(script);
- case OUTPUT_TYPE_P2SH_SEGWIT:
- case OUTPUT_TYPE_BECH32: {
+ case OutputType::P2SH_SEGWIT:
+ case OutputType::BECH32: {
WitnessV0ScriptHash hash;
CSHA256().Write(script.data(), script.size()).Finalize(hash.begin());
CTxDestination witdest = hash;
@@ -4284,7 +4307,7 @@ CTxDestination CWallet::AddAndGetDestinationForScript(const CScript& script, Out
if (!IsSolvable(*this, witprog)) return CScriptID(script);
// Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours.
AddCScript(witprog);
- if (type == OUTPUT_TYPE_BECH32) {
+ if (type == OutputType::BECH32) {
return witdest;
} else {
return CScriptID(witprog);
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index 3e2d1794d8..898c32c708 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -17,12 +17,14 @@
#include <script/sign.h>
#include <util.h>
#include <wallet/crypter.h>
+#include <wallet/coinselection.h>
#include <wallet/walletdb.h>
#include <wallet/rpcwallet.h>
#include <algorithm>
#include <atomic>
#include <map>
+#include <memory>
#include <set>
#include <stdexcept>
#include <stdint.h>
@@ -42,6 +44,7 @@ extern bool bSpendZeroConfChange;
extern bool fWalletRbf;
extern bool g_wallet_allow_fallback_fee;
+//! Default for -keypool
static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
//! -paytxfee default
static const CAmount DEFAULT_TRANSACTION_FEE = 0;
@@ -53,10 +56,6 @@ static const CAmount DEFAULT_DISCARD_FEE = 10000;
static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
//! minimum recommended increment for BIP 125 replacement txs
static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
-//! target minimum change amount
-static const CAmount MIN_CHANGE = CENT;
-//! final minimum change amount after paying for fees
-static const CAmount MIN_FINAL_CHANGE = MIN_CHANGE/2;
//! Default for -spendzeroconfchange
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
//! Default for -walletrejectlongchains
@@ -99,18 +98,15 @@ enum WalletFeature
FEATURE_LATEST = FEATURE_COMPRPUBKEY // HD is optional, use FEATURE_COMPRPUBKEY as latest version
};
-enum OutputType : int
-{
- OUTPUT_TYPE_NONE,
- OUTPUT_TYPE_LEGACY,
- OUTPUT_TYPE_P2SH_SEGWIT,
- OUTPUT_TYPE_BECH32,
-
- OUTPUT_TYPE_DEFAULT = OUTPUT_TYPE_P2SH_SEGWIT
+enum class OutputType {
+ NONE,
+ LEGACY,
+ P2SH_SEGWIT,
+ BECH32,
};
-extern OutputType g_address_type;
-extern OutputType g_change_type;
+//! Default for -addresstype
+constexpr OutputType DEFAULT_ADDRESS_TYPE{OutputType::P2SH_SEGWIT};
/** A key pool entry */
@@ -269,6 +265,9 @@ public:
bool IsCoinBase() const { return tx->IsCoinBase(); }
};
+//Get the marginal bytes of spending the specified output
+int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet);
+
/**
* A transaction with a bunch of additional info that only the owner cares about.
* It includes any unrecorded transactions needed to link it back to the block chain.
@@ -348,11 +347,6 @@ public:
mutable CAmount nAvailableWatchCreditCached;
mutable CAmount nChangeCached;
- CWalletTx()
- {
- Init(nullptr);
- }
-
CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
{
Init(pwalletIn);
@@ -390,42 +384,36 @@ public:
nOrderPos = -1;
}
- ADD_SERIALIZE_METHODS;
-
- template <typename Stream, typename Operation>
- inline void SerializationOp(Stream& s, Operation ser_action) {
- if (ser_action.ForRead())
- Init(nullptr);
+ template<typename Stream>
+ void Serialize(Stream& s) const
+ {
char fSpent = false;
+ mapValue_t mapValueCopy = mapValue;
- if (!ser_action.ForRead())
- {
- mapValue["fromaccount"] = strFromAccount;
-
- WriteOrderPos(nOrderPos, mapValue);
-
- if (nTimeSmart)
- mapValue["timesmart"] = strprintf("%u", nTimeSmart);
+ mapValueCopy["fromaccount"] = strFromAccount;
+ WriteOrderPos(nOrderPos, mapValueCopy);
+ if (nTimeSmart) {
+ mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
}
- READWRITE(*static_cast<CMerkleTx*>(this));
+ s << *static_cast<const CMerkleTx*>(this);
std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
- READWRITE(vUnused);
- READWRITE(mapValue);
- READWRITE(vOrderForm);
- READWRITE(fTimeReceivedIsTxTime);
- READWRITE(nTimeReceived);
- READWRITE(fFromMe);
- READWRITE(fSpent);
-
- if (ser_action.ForRead())
- {
- strFromAccount = mapValue["fromaccount"];
+ s << vUnused << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << fSpent;
+ }
+
+ template<typename Stream>
+ void Unserialize(Stream& s)
+ {
+ Init(nullptr);
+ char fSpent;
- ReadOrderPos(nOrderPos, mapValue);
+ s >> *static_cast<CMerkleTx*>(this);
+ std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
+ s >> vUnused >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> fSpent;
- nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
- }
+ strFromAccount = std::move(mapValue["fromaccount"]);
+ ReadOrderPos(nOrderPos, mapValue);
+ nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
mapValue.erase("fromaccount");
mapValue.erase("spent");
@@ -462,6 +450,12 @@ public:
CAmount GetAvailableWatchOnlyCredit(const bool fUseCache=true) const;
CAmount GetChange() const;
+ // Get the marginal bytes if spending the specified output from this transaction
+ int GetSpendSize(unsigned int out) const
+ {
+ return CalculateMaximumSignedInputSize(tx->vout[out], pwallet);
+ }
+
void GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
@@ -488,36 +482,6 @@ public:
std::set<uint256> GetConflicts() const;
};
-
-class CInputCoin {
-public:
- CInputCoin(const CWalletTx* walletTx, unsigned int i)
- {
- if (!walletTx)
- throw std::invalid_argument("walletTx should not be null");
- if (i >= walletTx->tx->vout.size())
- throw std::out_of_range("The output index is out of range");
-
- outpoint = COutPoint(walletTx->GetHash(), i);
- txout = walletTx->tx->vout[i];
- }
-
- COutPoint outpoint;
- CTxOut txout;
-
- bool operator<(const CInputCoin& rhs) const {
- return outpoint < rhs.outpoint;
- }
-
- bool operator!=(const CInputCoin& rhs) const {
- return outpoint != rhs.outpoint;
- }
-
- bool operator==(const CInputCoin& rhs) const {
- return outpoint == rhs.outpoint;
- }
-};
-
class COutput
{
public:
@@ -525,6 +489,9 @@ public:
int i;
int nDepth;
+ /** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */
+ int nInputBytes;
+
/** Whether we have the private keys to spend this output */
bool fSpendable;
@@ -540,7 +507,12 @@ public:
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
{
- tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
+ tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1;
+ // If known and signable by the given wallet, compute nInputBytes
+ // Failure will keep this value -1
+ if (fSpendable && tx) {
+ nInputBytes = tx->GetSpendSize(i);
+ }
}
std::string ToString() const;
@@ -608,48 +580,49 @@ public:
nEntryNo = 0;
}
- ADD_SERIALIZE_METHODS;
-
- template <typename Stream, typename Operation>
- inline void SerializationOp(Stream& s, Operation ser_action) {
+ template <typename Stream>
+ void Serialize(Stream& s) const {
int nVersion = s.GetVersion();
- if (!(s.GetType() & SER_GETHASH))
- READWRITE(nVersion);
+ if (!(s.GetType() & SER_GETHASH)) {
+ s << nVersion;
+ }
//! Note: strAccount is serialized as part of the key, not here.
- READWRITE(nCreditDebit);
- READWRITE(nTime);
- READWRITE(LIMITED_STRING(strOtherAccount, 65536));
-
- if (!ser_action.ForRead())
- {
- WriteOrderPos(nOrderPos, mapValue);
-
- if (!(mapValue.empty() && _ssExtra.empty()))
- {
- CDataStream ss(s.GetType(), s.GetVersion());
- ss.insert(ss.begin(), '\0');
- ss << mapValue;
- ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
- strComment.append(ss.str());
- }
+ s << nCreditDebit << nTime << strOtherAccount;
+
+ mapValue_t mapValueCopy = mapValue;
+ WriteOrderPos(nOrderPos, mapValueCopy);
+
+ std::string strCommentCopy = strComment;
+ if (!mapValueCopy.empty() || !_ssExtra.empty()) {
+ CDataStream ss(s.GetType(), s.GetVersion());
+ ss.insert(ss.begin(), '\0');
+ ss << mapValueCopy;
+ ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
+ strCommentCopy.append(ss.str());
}
+ s << strCommentCopy;
+ }
- READWRITE(LIMITED_STRING(strComment, 65536));
+ template <typename Stream>
+ void Unserialize(Stream& s) {
+ int nVersion = s.GetVersion();
+ if (!(s.GetType() & SER_GETHASH)) {
+ s >> nVersion;
+ }
+ //! Note: strAccount is serialized as part of the key, not here.
+ s >> nCreditDebit >> nTime >> LIMITED_STRING(strOtherAccount, 65536) >> LIMITED_STRING(strComment, 65536);
size_t nSepPos = strComment.find("\0", 0, 1);
- if (ser_action.ForRead())
- {
- mapValue.clear();
- if (std::string::npos != nSepPos)
- {
- CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
- ss >> mapValue;
- _ssExtra = std::vector<char>(ss.begin(), ss.end());
- }
- ReadOrderPos(nOrderPos, mapValue);
+ mapValue.clear();
+ if (std::string::npos != nSepPos) {
+ CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
+ ss >> mapValue;
+ _ssExtra = std::vector<char>(ss.begin(), ss.end());
}
- if (std::string::npos != nSepPos)
+ ReadOrderPos(nOrderPos, mapValue);
+ if (std::string::npos != nSepPos) {
strComment.erase(nSepPos);
+ }
mapValue.erase("n");
}
@@ -658,6 +631,26 @@ private:
std::vector<char> _ssExtra;
};
+struct CoinSelectionParams
+{
+ bool use_bnb = true;
+ size_t change_output_size = 0;
+ size_t change_spend_size = 0;
+ CFeeRate effective_fee = CFeeRate(0);
+ size_t tx_noinputs_size = 0;
+
+ CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_fee, size_t tx_noinputs_size) : use_bnb(use_bnb), change_output_size(change_output_size), change_spend_size(change_spend_size), effective_fee(effective_fee), tx_noinputs_size(tx_noinputs_size) {}
+ CoinSelectionParams() {}
+};
+
+struct CoinEligibilityFilter
+{
+ const int conf_mine;
+ const int conf_theirs;
+ const uint64_t max_ancestors;
+
+ CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors) {}
+};
class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
/**
@@ -673,14 +666,6 @@ private:
std::mutex mutexScanning;
friend class WalletRescanReserver;
-
- /**
- * Select a set of coins such that nValueRet >= nTargetValue and at least
- * all coins from coinControl are selected; Never select unconfirmed coins
- * if they are not ours
- */
- bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = nullptr) const;
-
CWalletDB *pwalletdbEncryption;
//! the current wallet version: clients below this version are not able to load the wallet
@@ -773,6 +758,14 @@ public:
return *dbw;
}
+ /**
+ * Select a set of coins such that nValueRet >= nTargetValue and at least
+ * all coins from coinControl are selected; Never select unconfirmed coins
+ * if they are not ours
+ */
+ bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
+ const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
+
/** Get a name for this wallet for logging/debugging purposes.
*/
const std::string& GetName() const { return m_name; }
@@ -860,7 +853,8 @@ public:
* completion the coin set and corresponding actual target value is
* assembled
*/
- bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
+ bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<COutput> vCoins,
+ std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
bool IsSpent(const uint256& hash, unsigned int n) const;
@@ -935,7 +929,7 @@ public:
int64_t IncOrderPosNext(CWalletDB *pwalletdb = nullptr);
DBErrors ReorderTransactions();
bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
- bool GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew = false);
+ bool GetLabelDestination(CTxDestination &dest, const std::string& label, bool bForceNew = false);
void MarkDirty();
bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
@@ -974,19 +968,27 @@ public:
* selected by SelectCoins(); Also create the change output, when needed
* @note passing nChangePosInOut as -1 will result in setting a random position
*/
- bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
+ bool CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
- bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
+ bool CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm, std::string fromAccount, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
bool AddAccountingEntry(const CAccountingEntry&);
bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
- template <typename ContainerType>
- bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
+ bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts) const
+ {
+ std::vector<CTxOut> v_txouts(txouts.size());
+ std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
+ return DummySignTx(txNew, v_txouts);
+ }
+ bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts) const;
+ bool DummySignInput(CTxIn &tx_in, const CTxOut &txout) const;
static CFeeRate minTxFee;
static CFeeRate fallbackFee;
static CFeeRate m_discard_rate;
+ OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
+ OutputType m_default_change_type{OutputType::NONE}; // Default to OutputType::NONE if not set by -changetype
bool NewKeyPool();
size_t KeypoolCountExternalKeys();
@@ -1005,7 +1007,7 @@ public:
std::set< std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
- std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
+ std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
isminetype IsMine(const CTxIn& txin) const;
/**
@@ -1035,7 +1037,7 @@ public:
bool DelAddressBook(const CTxDestination& address);
- const std::string& GetAccountName(const CScript& scriptPubKey) const;
+ const std::string& GetLabelName(const CScript& scriptPubKey) const;
void Inventory(const uint256 &hash) override
{
@@ -1163,6 +1165,9 @@ public:
* This function will automatically add the necessary scripts to the wallet.
*/
CTxDestination AddAndGetDestinationForScript(const CScript& script, OutputType);
+
+ /** Whether a given output is spendable by this wallet */
+ bool OutputEligibleForSpending(const COutput& output, const CoinEligibilityFilter& eligibility_filter) const;
};
/** A key allocated from the key pool. */
@@ -1227,32 +1232,7 @@ public:
}
};
-// Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
-// ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
-// so that each entry corresponds to each vIn, in order.
-template <typename ContainerType>
-bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
-{
- // Fill in dummy signatures for fee calculation.
- int nIn = 0;
- for (const auto& coin : coins)
- {
- const CScript& scriptPubKey = coin.txout.scriptPubKey;
- SignatureData sigdata;
-
- if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
- {
- return false;
- } else {
- UpdateTransaction(txNew, nIn, sigdata);
- }
-
- nIn++;
- }
- return true;
-}
-
-OutputType ParseOutputType(const std::string& str, OutputType default_type = OUTPUT_TYPE_DEFAULT);
+OutputType ParseOutputType(const std::string& str, OutputType default_type);
const std::string& FormatOutputType(OutputType type);
/**
@@ -1299,4 +1279,10 @@ public:
}
};
+// Calculate the size of the transaction assuming all signatures are max size
+// Use DummySignatureCreator, which inserts 72 byte signatures everywhere.
+// NOTE: this requires that all inputs must be in mapWallet (eg the tx should
+// be IsAllFromMe).
+int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet);
+int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts);
#endif // BITCOIN_WALLET_WALLET_H
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
index 0b0880a2ba..77cdfe7dd0 100644
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -265,7 +265,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
{
uint256 hash;
ssKey >> hash;
- CWalletTx wtx;
+ CWalletTx wtx(nullptr /* pwallet */, MakeTransactionRef());
ssValue >> wtx;
CValidationState state;
if (!(CheckTransaction(*wtx.tx, state) && (wtx.GetHash() == hash) && state.IsValid()))
@@ -522,7 +522,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
CWalletScanState wss;
bool fNoncriticalErrors = false;
- DBErrors result = DB_LOAD_OK;
+ DBErrors result = DBErrors::LOAD_OK;
LOCK(pwallet->cs_wallet);
try {
@@ -530,7 +530,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
if (batch.Read((std::string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
- return DB_TOO_NEW;
+ return DBErrors::TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
@@ -539,7 +539,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
- return DB_CORRUPT;
+ return DBErrors::CORRUPT;
}
while (true)
@@ -553,7 +553,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
- return DB_CORRUPT;
+ return DBErrors::CORRUPT;
}
// Try to be tolerant of single corrupt records:
@@ -563,7 +563,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType) || strType == "defaultkey")
- result = DB_CORRUPT;
+ result = DBErrors::CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
@@ -582,15 +582,15 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
throw;
}
catch (...) {
- result = DB_CORRUPT;
+ result = DBErrors::CORRUPT;
}
- if (fNoncriticalErrors && result == DB_LOAD_OK)
- result = DB_NONCRITICAL_ERROR;
+ if (fNoncriticalErrors && result == DBErrors::LOAD_OK)
+ result = DBErrors::NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
- if (result != DB_LOAD_OK)
+ if (result != DBErrors::LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
@@ -603,11 +603,11 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
pwallet->UpdateTimeFirstKey(1);
for (uint256 hash : wss.vWalletUpgrade)
- WriteTx(pwallet->mapWallet[hash]);
+ WriteTx(pwallet->mapWallet.at(hash));
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
- return DB_NEED_REWRITE;
+ return DBErrors::NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
@@ -626,14 +626,14 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx)
{
- DBErrors result = DB_LOAD_OK;
+ DBErrors result = DBErrors::LOAD_OK;
try {
int nMinVersion = 0;
if (batch.Read((std::string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
- return DB_TOO_NEW;
+ return DBErrors::TOO_NEW;
}
// Get cursor
@@ -641,7 +641,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWal
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
- return DB_CORRUPT;
+ return DBErrors::CORRUPT;
}
while (true)
@@ -655,7 +655,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWal
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
- return DB_CORRUPT;
+ return DBErrors::CORRUPT;
}
std::string strType;
@@ -664,7 +664,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWal
uint256 hash;
ssKey >> hash;
- CWalletTx wtx;
+ CWalletTx wtx(nullptr /* pwallet */, MakeTransactionRef());
ssValue >> wtx;
vTxHash.push_back(hash);
@@ -677,7 +677,7 @@ DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWal
throw;
}
catch (...) {
- result = DB_CORRUPT;
+ result = DBErrors::CORRUPT;
}
return result;
@@ -689,7 +689,7 @@ DBErrors CWalletDB::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uin
std::vector<uint256> vTxHash;
std::vector<CWalletTx> vWtx;
DBErrors err = FindWalletTx(vTxHash, vWtx);
- if (err != DB_LOAD_OK) {
+ if (err != DBErrors::LOAD_OK) {
return err;
}
@@ -716,9 +716,9 @@ DBErrors CWalletDB::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uin
}
if (delerror) {
- return DB_CORRUPT;
+ return DBErrors::CORRUPT;
}
- return DB_LOAD_OK;
+ return DBErrors::LOAD_OK;
}
DBErrors CWalletDB::ZapWalletTx(std::vector<CWalletTx>& vWtx)
@@ -726,16 +726,16 @@ DBErrors CWalletDB::ZapWalletTx(std::vector<CWalletTx>& vWtx)
// build list of wallet TXs
std::vector<uint256> vTxHash;
DBErrors err = FindWalletTx(vTxHash, vWtx);
- if (err != DB_LOAD_OK)
+ if (err != DBErrors::LOAD_OK)
return err;
// erase each wallet TX
for (uint256& hash : vTxHash) {
if (!EraseTx(hash))
- return DB_CORRUPT;
+ return DBErrors::CORRUPT;
}
- return DB_LOAD_OK;
+ return DBErrors::LOAD_OK;
}
void MaybeCompactWalletDB()
diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h
index 7d754c7284..606b7dace7 100644
--- a/src/wallet/walletdb.h
+++ b/src/wallet/walletdb.h
@@ -46,14 +46,14 @@ class uint160;
class uint256;
/** Error statuses for the wallet database */
-enum DBErrors
+enum class DBErrors
{
- DB_LOAD_OK,
- DB_CORRUPT,
- DB_NONCRITICAL_ERROR,
- DB_TOO_NEW,
- DB_LOAD_FAIL,
- DB_NEED_REWRITE
+ LOAD_OK,
+ CORRUPT,
+ NONCRITICAL_ERROR,
+ TOO_NEW,
+ LOAD_FAIL,
+ NEED_REWRITE
};
/* simple HD chain data model */
diff --git a/src/wallet/walletutil.h b/src/wallet/walletutil.h
index 50ff736402..f12acacd00 100644
--- a/src/wallet/walletutil.h
+++ b/src/wallet/walletutil.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_WALLET_UTIL_H
-#define BITCOIN_WALLET_UTIL_H
+#ifndef BITCOIN_WALLET_WALLETUTIL_H
+#define BITCOIN_WALLET_WALLETUTIL_H
#include <chainparamsbase.h>
#include <util.h>
@@ -11,4 +11,4 @@
//! Get the path of the wallet directory.
fs::path GetWalletDir();
-#endif // BITCOIN_WALLET_UTIL_H
+#endif // BITCOIN_WALLET_WALLETUTIL_H
diff --git a/src/walletinitinterface.h b/src/walletinitinterface.h
new file mode 100644
index 0000000000..c7eee37ce5
--- /dev/null
+++ b/src/walletinitinterface.h
@@ -0,0 +1,37 @@
+// Copyright (c) 2017 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_WALLETINITINTERFACE_H
+#define BITCOIN_WALLETINITINTERFACE_H
+
+#include <string>
+
+class CScheduler;
+class CRPCTable;
+
+class WalletInitInterface {
+public:
+ /** Get wallet help string */
+ virtual std::string GetHelpString(bool showDebug) = 0;
+ /** Check wallet parameter interaction */
+ virtual bool ParameterInteraction() = 0;
+ /** Register wallet RPC*/
+ virtual void RegisterRPC(CRPCTable &) = 0;
+ /** Verify wallets */
+ virtual bool Verify() = 0;
+ /** Open wallets*/
+ virtual bool Open() = 0;
+ /** Start wallets*/
+ virtual void Start(CScheduler& scheduler) = 0;
+ /** Flush Wallets*/
+ virtual void Flush() = 0;
+ /** Stop Wallets*/
+ virtual void Stop() = 0;
+ /** Close wallets */
+ virtual void Close() = 0;
+
+ virtual ~WalletInitInterface() {}
+};
+
+#endif // BITCOIN_WALLETINITINTERFACE_H