aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/.clang-tidy2
-rw-r--r--src/bench/checkqueue.cpp3
-rw-r--r--src/bench/prevector.cpp4
-rw-r--r--src/bitcoin-cli.cpp40
-rw-r--r--src/bitcoin-tx.cpp2
-rw-r--r--src/blockencodings.cpp4
-rw-r--r--src/blockencodings.h2
-rw-r--r--src/httprpc.cpp2
-rw-r--r--src/httpserver.cpp9
-rw-r--r--src/index/base.cpp2
-rw-r--r--src/index/txindex.cpp2
-rw-r--r--src/init.cpp1
-rw-r--r--src/net.cpp2
-rw-r--r--src/net_processing.cpp250
-rw-r--r--src/net_types.cpp8
-rw-r--r--src/netaddress.cpp2
-rw-r--r--src/node/context.cpp4
-rw-r--r--src/node/interfaces.cpp2
-rw-r--r--src/policy/fees.cpp4
-rw-r--r--src/qt/addresstablemodel.cpp2
-rw-r--r--src/qt/bantablemodel.cpp5
-rw-r--r--src/qt/notificator.cpp2
-rw-r--r--src/qt/overviewpage.cpp5
-rw-r--r--src/qt/paymentserver.cpp4
-rw-r--r--src/qt/peertablemodel.cpp5
-rw-r--r--src/qt/recentrequeststablemodel.cpp5
-rw-r--r--src/qt/rpcconsole.cpp6
-rw-r--r--src/qt/transactiontablemodel.cpp2
-rw-r--r--src/qt/walletframe.cpp4
-rw-r--r--src/qt/walletview.cpp4
-rw-r--r--src/random.cpp4
-rw-r--r--src/rpc/blockchain.cpp28
-rw-r--r--src/rpc/mining.cpp18
-rw-r--r--src/rpc/net.cpp6
-rw-r--r--src/rpc/node.cpp4
-rw-r--r--src/rpc/output_script.cpp2
-rw-r--r--src/rpc/rawtransaction.cpp2
-rw-r--r--src/rpc/rawtransaction_util.cpp8
-rw-r--r--src/rpc/request.cpp2
-rw-r--r--src/rpc/server.cpp2
-rw-r--r--src/rpc/util.cpp15
-rw-r--r--src/rpc/util.h2
-rw-r--r--src/scheduler.cpp4
-rw-r--r--src/script/sign.cpp2
-rw-r--r--src/support/lockedpool.cpp5
-rw-r--r--src/test/blockencodings_tests.cpp6
-rw-r--r--src/test/blockfilter_tests.cpp2
-rw-r--r--src/test/checkqueue_tests.cpp4
-rw-r--r--src/test/dbwrapper_tests.cpp2
-rw-r--r--src/test/fuzz/script_assets_test_minimizer.cpp2
-rw-r--r--src/test/fuzz/signature_checker.cpp2
-rw-r--r--src/test/rpc_tests.cpp30
-rw-r--r--src/test/script_standard_tests.cpp4
-rw-r--r--src/test/script_tests.cpp14
-rw-r--r--src/test/sighash_tests.cpp4
-rw-r--r--src/test/transaction_tests.cpp8
-rw-r--r--src/test/util_tests.cpp4
-rw-r--r--src/torcontrol.cpp3
-rw-r--r--src/txdb.cpp2
-rw-r--r--src/util/settings.h2
-rw-r--r--src/util/system.cpp6
-rw-r--r--src/validation.cpp2
-rw-r--r--src/wallet/context.cpp4
-rw-r--r--src/wallet/rpc/addresses.cpp6
-rw-r--r--src/wallet/rpc/backup.cpp4
-rw-r--r--src/wallet/rpc/coins.cpp12
-rw-r--r--src/wallet/rpc/encrypt.cpp2
-rw-r--r--src/wallet/rpc/spend.cpp8
-rw-r--r--src/wallet/rpc/transactions.cpp16
-rw-r--r--src/wallet/rpc/wallet.cpp2
-rw-r--r--src/wallet/walletdb.cpp3
71 files changed, 333 insertions, 314 deletions
diff --git a/src/.clang-tidy b/src/.clang-tidy
index b1f543f610..e9807d4cb7 100644
--- a/src/.clang-tidy
+++ b/src/.clang-tidy
@@ -1,11 +1,13 @@
Checks: '
-*,
bugprone-argument-comment,
+modernize-use-default-member-init,
modernize-use-nullptr,
readability-redundant-declaration,
'
WarningsAsErrors: '
bugprone-argument-comment,
+modernize-use-default-member-init,
modernize-use-nullptr,
readability-redundant-declaration,
'
diff --git a/src/bench/checkqueue.cpp b/src/bench/checkqueue.cpp
index 53591f8905..602081fb9b 100644
--- a/src/bench/checkqueue.cpp
+++ b/src/bench/checkqueue.cpp
@@ -30,8 +30,7 @@ static void CCheckQueueSpeedPrevectorJob(benchmark::Bench& bench)
struct PrevectorJob {
prevector<PREVECTOR_SIZE, uint8_t> p;
- PrevectorJob(){
- }
+ PrevectorJob() = default;
explicit PrevectorJob(FastRandomContext& insecure_rand){
p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2));
}
diff --git a/src/bench/prevector.cpp b/src/bench/prevector.cpp
index 6343ed7848..b3688bab1b 100644
--- a/src/bench/prevector.cpp
+++ b/src/bench/prevector.cpp
@@ -10,8 +10,8 @@
#include <bench/bench.h>
struct nontrivial_t {
- int x;
- nontrivial_t() :x(-1) {}
+ int x{-1};
+ nontrivial_t() = default;
SERIALIZE_METHODS(nontrivial_t, obj) { READWRITE(obj.x); }
};
static_assert(!std::is_trivially_default_constructible<nontrivial_t>::value,
diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp
index cbbea3d8fa..88cbab1d11 100644
--- a/src/bitcoin-cli.cpp
+++ b/src/bitcoin-cli.cpp
@@ -179,10 +179,10 @@ static int AppInitRPC(int argc, char* argv[])
/** Reply structure for request_done to fill in */
struct HTTPReply
{
- HTTPReply(): status(0), error(-1) {}
+ HTTPReply() = default;
- int status;
- int error;
+ int status{0};
+ int error{-1};
std::string body;
};
@@ -243,7 +243,7 @@ static void http_error_cb(enum evhttp_request_error err, void *ctx)
class BaseRequestHandler
{
public:
- virtual ~BaseRequestHandler() {}
+ virtual ~BaseRequestHandler() = default;
virtual UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) = 0;
virtual UniValue ProcessReply(const UniValue &batch_in) = 0;
};
@@ -466,7 +466,7 @@ public:
if (!batch[ID_NETWORKINFO]["error"].isNull()) return batch[ID_NETWORKINFO];
const UniValue& networkinfo{batch[ID_NETWORKINFO]["result"]};
- if (networkinfo["version"].get_int() < 209900) {
+ if (networkinfo["version"].getInt<int>() < 209900) {
throw std::runtime_error("-netinfo requires bitcoind server to be running v0.21.0 and up");
}
const int64_t time_now{TicksSinceEpoch<std::chrono::seconds>(CliClock::now())};
@@ -487,16 +487,16 @@ public:
if (conn_type == "manual") ++m_manual_peers_count;
if (DetailsRequested()) {
// Push data for this peer to the peers vector.
- const int peer_id{peer["id"].get_int()};
- const int mapped_as{peer["mapped_as"].isNull() ? 0 : peer["mapped_as"].get_int()};
- const int version{peer["version"].get_int()};
- const int64_t addr_processed{peer["addr_processed"].isNull() ? 0 : peer["addr_processed"].get_int64()};
- const int64_t addr_rate_limited{peer["addr_rate_limited"].isNull() ? 0 : peer["addr_rate_limited"].get_int64()};
- const int64_t conn_time{peer["conntime"].get_int64()};
- const int64_t last_blck{peer["last_block"].get_int64()};
- const int64_t last_recv{peer["lastrecv"].get_int64()};
- const int64_t last_send{peer["lastsend"].get_int64()};
- const int64_t last_trxn{peer["last_transaction"].get_int64()};
+ const int peer_id{peer["id"].getInt<int>()};
+ const int mapped_as{peer["mapped_as"].isNull() ? 0 : peer["mapped_as"].getInt<int>()};
+ const int version{peer["version"].getInt<int>()};
+ const int64_t addr_processed{peer["addr_processed"].isNull() ? 0 : peer["addr_processed"].getInt<int64_t>()};
+ const int64_t addr_rate_limited{peer["addr_rate_limited"].isNull() ? 0 : peer["addr_rate_limited"].getInt<int64_t>()};
+ const int64_t conn_time{peer["conntime"].getInt<int64_t>()};
+ const int64_t last_blck{peer["last_block"].getInt<int64_t>()};
+ const int64_t last_recv{peer["lastrecv"].getInt<int64_t>()};
+ const int64_t last_send{peer["lastsend"].getInt<int64_t>()};
+ const int64_t last_trxn{peer["last_transaction"].getInt<int64_t>()};
const double min_ping{peer["minping"].isNull() ? -1 : peer["minping"].get_real()};
const double ping{peer["pingtime"].isNull() ? -1 : peer["pingtime"].get_real()};
const std::string addr{peer["addr"].get_str()};
@@ -516,7 +516,7 @@ public:
}
// Generate report header.
- std::string result{strprintf("%s client %s%s - server %i%s\n\n", PACKAGE_NAME, FormatFullVersion(), ChainToString(), networkinfo["protocolversion"].get_int(), networkinfo["subversion"].get_str())};
+ std::string result{strprintf("%s client %s%s - server %i%s\n\n", PACKAGE_NAME, FormatFullVersion(), ChainToString(), networkinfo["protocolversion"].getInt<int>(), networkinfo["subversion"].get_str())};
// Report detailed peer connections list sorted by direction and minimum ping time.
if (DetailsRequested() && !m_peers.empty()) {
@@ -597,7 +597,7 @@ public:
max_addr_size = std::max(addr["address"].get_str().length() + 1, max_addr_size);
}
for (const UniValue& addr : local_addrs) {
- result += strprintf("\n%-*s port %6i score %6i", max_addr_size, addr["address"].get_str(), addr["port"].get_int(), addr["score"].get_int());
+ result += strprintf("\n%-*s port %6i score %6i", max_addr_size, addr["address"].get_str(), addr["port"].getInt<int>(), addr["score"].getInt<int>());
}
}
@@ -850,7 +850,7 @@ static UniValue ConnectAndCallRPC(BaseRequestHandler* rh, const std::string& str
response = CallRPC(rh, strMethod, args, rpcwallet);
if (fWait) {
const UniValue& error = find_value(response, "error");
- if (!error.isNull() && error["code"].get_int() == RPC_IN_WARMUP) {
+ if (!error.isNull() && error["code"].getInt<int>() == RPC_IN_WARMUP) {
throw CConnectionFailed("server in warmup");
}
}
@@ -885,13 +885,13 @@ static void ParseError(const UniValue& error, std::string& strPrint, int& nRet)
if (err_msg.isStr()) {
strPrint += ("error message:\n" + err_msg.get_str());
}
- if (err_code.isNum() && err_code.get_int() == RPC_WALLET_NOT_SPECIFIED) {
+ if (err_code.isNum() && err_code.getInt<int>() == RPC_WALLET_NOT_SPECIFIED) {
strPrint += "\nTry adding \"-rpcwallet=<filename>\" option to bitcoin-cli command line.";
}
} else {
strPrint = "error: " + error.write();
}
- nRet = abs(error["code"].get_int());
+ nRet = abs(error["code"].getInt<int>());
}
/**
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index 580cc5839a..bcefb3f18e 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -612,7 +612,7 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
throw std::runtime_error("txid must be hexadecimal string (not '" + prevOut["txid"].get_str() + "')");
}
- const int nOut = prevOut["vout"].get_int();
+ const int nOut = prevOut["vout"].getInt<int>();
if (nOut < 0)
throw std::runtime_error("vout cannot be negative");
diff --git a/src/blockencodings.cpp b/src/blockencodings.cpp
index 2a7bf9397c..f96353510f 100644
--- a/src/blockencodings.cpp
+++ b/src/blockencodings.cpp
@@ -16,7 +16,7 @@
#include <unordered_map>
-CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, bool fUseWTXID) :
+CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block) :
nonce(GetRand<uint64_t>()),
shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) {
FillShortTxIDSelector();
@@ -24,7 +24,7 @@ CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, bool f
prefilledtxn[0] = {0, block.vtx[0]};
for (size_t i = 1; i < block.vtx.size(); i++) {
const CTransaction& tx = *block.vtx[i];
- shorttxids[i - 1] = GetShortID(fUseWTXID ? tx.GetWitnessHash() : tx.GetHash());
+ shorttxids[i - 1] = GetShortID(tx.GetWitnessHash());
}
}
diff --git a/src/blockencodings.h b/src/blockencodings.h
index 326db1b4a7..67c4e57156 100644
--- a/src/blockencodings.h
+++ b/src/blockencodings.h
@@ -104,7 +104,7 @@ public:
// Dummy for deserialization
CBlockHeaderAndShortTxIDs() {}
- CBlockHeaderAndShortTxIDs(const CBlock& block, bool fUseWTXID);
+ CBlockHeaderAndShortTxIDs(const CBlock& block);
uint64_t GetShortID(const uint256& txhash) const;
diff --git a/src/httprpc.cpp b/src/httprpc.cpp
index 3bf165495c..4e7e72b037 100644
--- a/src/httprpc.cpp
+++ b/src/httprpc.cpp
@@ -75,7 +75,7 @@ static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const Uni
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
- int code = find_value(objError, "code").get_int();
+ int code = find_value(objError, "code").getInt<int>();
if (code == RPC_INVALID_REQUEST)
nStatus = HTTP_BAD_REQUEST;
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index dba66becc0..b9a1fc672a 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -73,19 +73,16 @@ private:
Mutex cs;
std::condition_variable cond GUARDED_BY(cs);
std::deque<std::unique_ptr<WorkItem>> queue GUARDED_BY(cs);
- bool running GUARDED_BY(cs);
+ bool running GUARDED_BY(cs){true};
const size_t maxDepth;
public:
- explicit WorkQueue(size_t _maxDepth) : running(true),
- maxDepth(_maxDepth)
+ explicit WorkQueue(size_t _maxDepth) : maxDepth(_maxDepth)
{
}
/** Precondition: worker threads have all stopped (they have been joined).
*/
- ~WorkQueue()
- {
- }
+ ~WorkQueue() = default;
/** Enqueue a work item */
bool Enqueue(WorkItem* item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
{
diff --git a/src/index/base.cpp b/src/index/base.cpp
index a00ae13e5c..9f0c1dea24 100644
--- a/src/index/base.cpp
+++ b/src/index/base.cpp
@@ -168,7 +168,7 @@ void BaseIndex::ThreadSync()
}
if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) {
- SetBestBlockIndex(pindex);
+ SetBestBlockIndex(pindex->pprev);
last_locator_write_time = current_time;
// No need to handle errors in Commit. See rationale above.
Commit();
diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp
index e1d807f39a..97c11c4383 100644
--- a/src/index/txindex.cpp
+++ b/src/index/txindex.cpp
@@ -52,7 +52,7 @@ TxIndex::TxIndex(size_t n_cache_size, bool f_memory, bool f_wipe)
: m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe))
{}
-TxIndex::~TxIndex() {}
+TxIndex::~TxIndex() = default;
bool TxIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex)
{
diff --git a/src/init.cpp b/src/init.cpp
index e180a2b5cd..f06b5bd0d0 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -570,6 +570,7 @@ void SetupServerArgs(ArgsManager& argsman)
argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
argsman.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
argsman.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
+ argsman.AddArg("-rpcdoccheck", strprintf("Throw a non-fatal error at runtime if the documentation for an RPC is incorrect (default: %u)", DEFAULT_RPC_DOC_CHECK), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
diff --git a/src/net.cpp b/src/net.cpp
index 1c775f9a3f..676037a357 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -2691,7 +2691,7 @@ bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
class CNetCleanup
{
public:
- CNetCleanup() {}
+ CNetCleanup() = default;
~CNetCleanup()
{
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 166a3bebe3..f9178baf25 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -239,36 +239,62 @@ struct Peer {
/** Whether this peer relays txs via wtxid */
std::atomic<bool> m_wtxid_relay{false};
+ /** The feerate in the most recent BIP133 `feefilter` message sent to the peer.
+ * It is *not* a p2p protocol violation for the peer to send us
+ * transactions with a lower fee rate than this. See BIP133. */
+ CAmount m_fee_filter_sent{0};
+ /** Timestamp after which we will send the next BIP133 `feefilter` message
+ * to the peer. */
+ std::chrono::microseconds m_next_send_feefilter{0};
struct TxRelay {
mutable RecursiveMutex m_bloom_filter_mutex;
- // We use m_relay_txs for two purposes -
- // a) it allows us to not relay tx invs before receiving the peer's version message
- // b) the peer may tell us in its version message that we should not relay tx invs
- // unless it loads a bloom filter.
+ /** Whether the peer wishes to receive transaction announcements.
+ *
+ * This is initially set based on the fRelay flag in the received
+ * `version` message. If initially set to false, it can only be flipped
+ * to true if we have offered the peer NODE_BLOOM services and it sends
+ * us a `filterload` or `filterclear` message. See BIP37. */
bool m_relay_txs GUARDED_BY(m_bloom_filter_mutex){false};
+ /** A bloom filter for which transactions to announce to the peer. See BIP37. */
std::unique_ptr<CBloomFilter> m_bloom_filter PT_GUARDED_BY(m_bloom_filter_mutex) GUARDED_BY(m_bloom_filter_mutex){nullptr};
mutable RecursiveMutex m_tx_inventory_mutex;
+ /** A filter of all the txids and wtxids that the peer has announced to
+ * us or we have announced to the peer. We use this to avoid announcing
+ * the same txid/wtxid to a peer that already has the transaction. */
CRollingBloomFilter m_tx_inventory_known_filter GUARDED_BY(m_tx_inventory_mutex){50000, 0.000001};
- // Set of transaction ids we still have to announce.
- // They are sorted by the mempool before relay, so the order is not important.
+ /** Set of transaction ids we still have to announce (txid for
+ * non-wtxid-relay peers, wtxid for wtxid-relay peers). We use the
+ * mempool to sort transactions in dependency order before relay, so
+ * this does not have to be sorted. */
std::set<uint256> m_tx_inventory_to_send;
- // Used for BIP35 mempool sending
+ /** Whether the peer has requested us to send our complete mempool. Only
+ * permitted if the peer has NetPermissionFlags::Mempool. See BIP35. */
bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
- // Last time a "MEMPOOL" request was serviced.
+ /** The last time a BIP35 `mempool` request was serviced. */
std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
+ /** The next time after which we will send an `inv` message containing
+ * transaction announcements to this peer. */
std::chrono::microseconds m_next_inv_send_time{0};
- /** Minimum fee rate with which to filter inv's to this node */
+ /** Minimum fee rate with which to filter transaction announcements to this node. See BIP133. */
std::atomic<CAmount> m_fee_filter_received{0};
- CAmount m_fee_filter_sent{0};
- std::chrono::microseconds m_next_send_feefilter{0};
};
- /** Transaction relay data. Will be a nullptr if we're not relaying
- * transactions with this peer (e.g. if it's a block-relay-only peer) */
- std::unique_ptr<TxRelay> m_tx_relay;
+ /* Initializes a TxRelay struct for this peer. Can be called at most once for a peer. */
+ TxRelay* SetTxRelay()
+ {
+ LOCK(m_tx_relay_mutex);
+ Assume(!m_tx_relay);
+ m_tx_relay = std::make_unique<Peer::TxRelay>();
+ return m_tx_relay.get();
+ };
+
+ TxRelay* GetTxRelay()
+ {
+ return WITH_LOCK(m_tx_relay_mutex, return m_tx_relay.get());
+ };
/** A vector of addresses to send to the peer, limited to MAX_ADDR_TO_SEND. */
std::vector<CAddress> m_addrs_to_send;
@@ -328,10 +354,17 @@ struct Peer {
/** Work queue of items requested by this peer **/
std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
- explicit Peer(NodeId id, bool tx_relay)
- : m_id(id)
- , m_tx_relay(tx_relay ? std::make_unique<TxRelay>() : nullptr)
+ Peer(NodeId id)
+ : m_id{id}
{}
+
+private:
+ Mutex m_tx_relay_mutex;
+
+ /** Transaction relay data. Will be a nullptr if we're not relaying
+ * transactions with this peer (e.g. if it's a block-relay-only peer or
+ * the peer has sent us fRelay=false with bloom filters disabled). */
+ std::unique_ptr<TxRelay> m_tx_relay GUARDED_BY(m_tx_relay_mutex);
};
using PeerRef = std::shared_ptr<Peer>;
@@ -883,10 +916,11 @@ static void PushAddress(Peer& peer, const CAddress& addr, FastRandomContext& ins
static void AddKnownTx(Peer& peer, const uint256& hash)
{
- if (peer.m_tx_relay != nullptr) {
- LOCK(peer.m_tx_relay->m_tx_inventory_mutex);
- peer.m_tx_relay->m_tx_inventory_known_filter.insert(hash);
- }
+ auto tx_relay = peer.GetTxRelay();
+ if (!tx_relay) return;
+
+ LOCK(tx_relay->m_tx_inventory_mutex);
+ tx_relay->m_tx_inventory_known_filter.insert(hash);
}
std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::microseconds now,
@@ -1186,7 +1220,7 @@ void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)
CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService();
uint64_t your_services{addr.nServices};
- const bool tx_relay = !m_ignore_incoming_txs && peer.m_tx_relay != nullptr && !pnode.IsFeelerConn();
+ const bool tx_relay = !m_ignore_incoming_txs && !pnode.IsBlockOnlyConn() && !pnode.IsFeelerConn();
m_connman.PushMessage(&pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime,
your_services, addr_you, // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime)
my_services, CService(), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime)
@@ -1241,7 +1275,7 @@ void PeerManagerImpl::InitializeNode(CNode *pnode)
m_node_states.emplace_hint(m_node_states.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(pnode->IsInboundConn()));
assert(m_txrequest.Count(nodeid) == 0);
}
- PeerRef peer = std::make_shared<Peer>(nodeid, /*tx_relay=*/ !pnode->IsBlockOnlyConn());
+ PeerRef peer = std::make_shared<Peer>(nodeid);
{
LOCK(m_peer_mutex);
m_peer_map.emplace_hint(m_peer_map.end(), nodeid, peer);
@@ -1377,9 +1411,9 @@ bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) c
ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
}
- if (peer->m_tx_relay != nullptr) {
- stats.m_relay_txs = WITH_LOCK(peer->m_tx_relay->m_bloom_filter_mutex, return peer->m_tx_relay->m_relay_txs);
- stats.m_fee_filter_received = peer->m_tx_relay->m_fee_filter_received.load();
+ if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
+ stats.m_relay_txs = WITH_LOCK(tx_relay->m_bloom_filter_mutex, return tx_relay->m_relay_txs);
+ stats.m_fee_filter_received = tx_relay->m_fee_filter_received.load();
} else {
stats.m_relay_txs = false;
stats.m_fee_filter_received = 0;
@@ -1632,7 +1666,7 @@ void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &blo
*/
void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
{
- std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
+ auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock);
const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
LOCK(cs_main);
@@ -1794,12 +1828,13 @@ void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid
LOCK(m_peer_mutex);
for(auto& it : m_peer_map) {
Peer& peer = *it.second;
- if (!peer.m_tx_relay) continue;
+ auto tx_relay = peer.GetTxRelay();
+ if (!tx_relay) continue;
const uint256& hash{peer.m_wtxid_relay ? wtxid : txid};
- LOCK(peer.m_tx_relay->m_tx_inventory_mutex);
- if (!peer.m_tx_relay->m_tx_inventory_known_filter.contains(hash)) {
- peer.m_tx_relay->m_tx_inventory_to_send.insert(hash);
+ LOCK(tx_relay->m_tx_inventory_mutex);
+ if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) {
+ tx_relay->m_tx_inventory_to_send.insert(hash);
}
};
}
@@ -1948,11 +1983,11 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv&
} else if (inv.IsMsgFilteredBlk()) {
bool sendMerkleBlock = false;
CMerkleBlock merkleBlock;
- if (peer.m_tx_relay != nullptr) {
- LOCK(peer.m_tx_relay->m_bloom_filter_mutex);
- if (peer.m_tx_relay->m_bloom_filter) {
+ if (auto tx_relay = peer.GetTxRelay(); tx_relay != nullptr) {
+ LOCK(tx_relay->m_bloom_filter_mutex);
+ if (tx_relay->m_bloom_filter) {
sendMerkleBlock = true;
- merkleBlock = CMerkleBlock(*pblock, *peer.m_tx_relay->m_bloom_filter);
+ merkleBlock = CMerkleBlock(*pblock, *tx_relay->m_bloom_filter);
}
}
if (sendMerkleBlock) {
@@ -1978,7 +2013,7 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv&
if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
} else {
- CBlockHeaderAndShortTxIDs cmpctblock(*pblock, true);
+ CBlockHeaderAndShortTxIDs cmpctblock{*pblock};
m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock));
}
} else {
@@ -2033,13 +2068,15 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic
{
AssertLockNotHeld(cs_main);
+ auto tx_relay = peer.GetTxRelay();
+
std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
std::vector<CInv> vNotFound;
const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
const auto now{GetTime<std::chrono::seconds>()};
// Get last mempool request time
- const auto mempool_req = peer.m_tx_relay != nullptr ? peer.m_tx_relay->m_last_mempool_req.load() : std::chrono::seconds::min();
+ const auto mempool_req = tx_relay != nullptr ? tx_relay->m_last_mempool_req.load() : std::chrono::seconds::min();
// Process as many TX items from the front of the getdata queue as
// possible, since they're common and it's efficient to batch process
@@ -2052,8 +2089,9 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic
const CInv &inv = *it++;
- if (peer.m_tx_relay == nullptr) {
- // Ignore GETDATA requests for transactions from blocks-only peers.
+ if (tx_relay == nullptr) {
+ // Ignore GETDATA requests for transactions from block-relay-only
+ // peers and peers that asked us not to announce transactions.
continue;
}
@@ -2080,7 +2118,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic
}
for (const uint256& parent_txid : parent_ids_to_add) {
// Relaying a transaction with a recent but unconfirmed parent.
- if (WITH_LOCK(peer.m_tx_relay->m_tx_inventory_mutex, return !peer.m_tx_relay->m_tx_inventory_known_filter.contains(parent_txid))) {
+ if (WITH_LOCK(tx_relay->m_tx_inventory_mutex, return !tx_relay->m_tx_inventory_known_filter.contains(parent_txid))) {
LOCK(cs_main);
State(pfrom.GetId())->m_recently_announced_invs.insert(parent_txid);
}
@@ -2715,10 +2753,16 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
// set nodes not capable of serving the complete blockchain history as "limited nodes"
pfrom.m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED));
- if (peer->m_tx_relay != nullptr) {
+ // We only initialize the m_tx_relay data structure if:
+ // - this isn't an outbound block-relay-only connection; and
+ // - fRelay=true or we're offering NODE_BLOOM to this peer
+ // (NODE_BLOOM means that the peer may turn on tx relay later)
+ if (!pfrom.IsBlockOnlyConn() &&
+ (fRelay || (pfrom.GetLocalServices() & NODE_BLOOM))) {
+ auto* const tx_relay = peer->SetTxRelay();
{
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
- peer->m_tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message
+ LOCK(tx_relay->m_bloom_filter_mutex);
+ tx_relay->m_relay_txs = fRelay; // set to true after we get the first filter* message
}
if (fRelay) pfrom.m_relays_txs = true;
}
@@ -3038,7 +3082,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
// Reject tx INVs when the -blocksonly setting is enabled, or this is a
// block-relay-only peer
- bool reject_tx_invs{m_ignore_incoming_txs || (peer->m_tx_relay == nullptr)};
+ bool reject_tx_invs{m_ignore_incoming_txs || pfrom.IsBlockOnlyConn()};
// Allow peers with relay permission to send data other than blocks in blocks only mode
if (pfrom.HasPermission(NetPermissionFlags::Relay)) {
@@ -3311,9 +3355,9 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
if (msg_type == NetMsgType::TX) {
// Stop processing the transaction early if
- // 1) We are in blocks only mode and peer has no relay permission
+ // 1) We are in blocks only mode and peer has no relay permission; OR
// 2) This peer is a block-relay-only peer
- if ((m_ignore_incoming_txs && !pfrom.HasPermission(NetPermissionFlags::Relay)) || (peer->m_tx_relay == nullptr)) {
+ if ((m_ignore_incoming_txs && !pfrom.HasPermission(NetPermissionFlags::Relay)) || pfrom.IsBlockOnlyConn()) {
LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId());
pfrom.fDisconnect = true;
return;
@@ -3919,9 +3963,9 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
return;
}
- if (peer->m_tx_relay != nullptr) {
- LOCK(peer->m_tx_relay->m_tx_inventory_mutex);
- peer->m_tx_relay->m_send_mempool = true;
+ if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
+ LOCK(tx_relay->m_tx_inventory_mutex);
+ tx_relay->m_send_mempool = true;
}
return;
}
@@ -4014,16 +4058,13 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
{
// There is no excuse for sending a too-large filter
Misbehaving(pfrom.GetId(), 100, "too-large bloom filter");
- }
- else if (peer->m_tx_relay != nullptr)
- {
+ } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
{
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
- peer->m_tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
- peer->m_tx_relay->m_relay_txs = true;
+ LOCK(tx_relay->m_bloom_filter_mutex);
+ tx_relay->m_bloom_filter.reset(new CBloomFilter(filter));
+ tx_relay->m_relay_txs = true;
}
pfrom.m_bloom_filter_loaded = true;
- pfrom.m_relays_txs = true;
}
return;
}
@@ -4042,10 +4083,10 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
bool bad = false;
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
bad = true;
- } else if (peer->m_tx_relay != nullptr) {
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
- if (peer->m_tx_relay->m_bloom_filter) {
- peer->m_tx_relay->m_bloom_filter->insert(vData);
+ } else if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
+ LOCK(tx_relay->m_bloom_filter_mutex);
+ if (tx_relay->m_bloom_filter) {
+ tx_relay->m_bloom_filter->insert(vData);
} else {
bad = true;
}
@@ -4062,14 +4103,13 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
pfrom.fDisconnect = true;
return;
}
- if (peer->m_tx_relay == nullptr) {
- return;
- }
+ auto tx_relay = peer->GetTxRelay();
+ if (!tx_relay) return;
{
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
- peer->m_tx_relay->m_bloom_filter = nullptr;
- peer->m_tx_relay->m_relay_txs = true;
+ LOCK(tx_relay->m_bloom_filter_mutex);
+ tx_relay->m_bloom_filter = nullptr;
+ tx_relay->m_relay_txs = true;
}
pfrom.m_bloom_filter_loaded = false;
pfrom.m_relays_txs = true;
@@ -4080,8 +4120,8 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
CAmount newFeeFilter = 0;
vRecv >> newFeeFilter;
if (MoneyRange(newFeeFilter)) {
- if (peer->m_tx_relay != nullptr) {
- peer->m_tx_relay->m_fee_filter_received = newFeeFilter;
+ if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
+ tx_relay->m_fee_filter_received = newFeeFilter;
}
LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
}
@@ -4542,10 +4582,12 @@ void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::micros
void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::microseconds current_time)
{
if (m_ignore_incoming_txs) return;
- if (!peer.m_tx_relay) return;
if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
// peers with the forcerelay permission should not filter txs to us
if (pto.HasPermission(NetPermissionFlags::ForceRelay)) return;
+ // Don't send feefilter messages to outbound block-relay-only peers since they should never announce
+ // transactions to us, regardless of feefilter state.
+ if (pto.IsBlockOnlyConn()) return;
CAmount currentFilter = m_mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
static FeeFilterRounder g_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}};
@@ -4556,27 +4598,27 @@ void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, Peer& peer, std::chrono::mi
currentFilter = MAX_MONEY;
} else {
static const CAmount MAX_FILTER{g_filter_rounder.round(MAX_MONEY)};
- if (peer.m_tx_relay->m_fee_filter_sent == MAX_FILTER) {
+ if (peer.m_fee_filter_sent == MAX_FILTER) {
// Send the current filter if we sent MAX_FILTER previously
// and made it out of IBD.
- peer.m_tx_relay->m_next_send_feefilter = 0us;
+ peer.m_next_send_feefilter = 0us;
}
}
- if (current_time > peer.m_tx_relay->m_next_send_feefilter) {
+ if (current_time > peer.m_next_send_feefilter) {
CAmount filterToSend = g_filter_rounder.round(currentFilter);
// We always have a fee filter of at least minRelayTxFee
filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
- if (filterToSend != peer.m_tx_relay->m_fee_filter_sent) {
+ if (filterToSend != peer.m_fee_filter_sent) {
m_connman.PushMessage(&pto, CNetMsgMaker(pto.GetCommonVersion()).Make(NetMsgType::FEEFILTER, filterToSend));
- peer.m_tx_relay->m_fee_filter_sent = filterToSend;
+ peer.m_fee_filter_sent = filterToSend;
}
- peer.m_tx_relay->m_next_send_feefilter = GetExponentialRand(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL);
+ peer.m_next_send_feefilter = GetExponentialRand(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL);
}
// If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
// until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
- else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_tx_relay->m_next_send_feefilter &&
- (currentFilter < 3 * peer.m_tx_relay->m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_tx_relay->m_fee_filter_sent / 3)) {
- peer.m_tx_relay->m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
+ else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < peer.m_next_send_feefilter &&
+ (currentFilter < 3 * peer.m_fee_filter_sent / 4 || currentFilter > 4 * peer.m_fee_filter_sent / 3)) {
+ peer.m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
}
}
@@ -4772,7 +4814,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
CBlock block;
bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
assert(ret);
- CBlockHeaderAndShortTxIDs cmpctblock(block, true);
+ CBlockHeaderAndShortTxIDs cmpctblock{block};
m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock));
}
state.pindexBestHeaderSent = pBestIndex;
@@ -4838,45 +4880,45 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
peer->m_blocks_for_inv_relay.clear();
}
- if (peer->m_tx_relay != nullptr) {
- LOCK(peer->m_tx_relay->m_tx_inventory_mutex);
+ if (auto tx_relay = peer->GetTxRelay(); tx_relay != nullptr) {
+ LOCK(tx_relay->m_tx_inventory_mutex);
// Check whether periodic sends should happen
bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
- if (peer->m_tx_relay->m_next_inv_send_time < current_time) {
+ if (tx_relay->m_next_inv_send_time < current_time) {
fSendTrickle = true;
if (pto->IsInboundConn()) {
- peer->m_tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
+ tx_relay->m_next_inv_send_time = NextInvToInbounds(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
} else {
- peer->m_tx_relay->m_next_inv_send_time = GetExponentialRand(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
+ tx_relay->m_next_inv_send_time = GetExponentialRand(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
}
}
// Time to send but the peer has requested we not relay transactions.
if (fSendTrickle) {
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
- if (!peer->m_tx_relay->m_relay_txs) peer->m_tx_relay->m_tx_inventory_to_send.clear();
+ LOCK(tx_relay->m_bloom_filter_mutex);
+ if (!tx_relay->m_relay_txs) tx_relay->m_tx_inventory_to_send.clear();
}
// Respond to BIP35 mempool requests
- if (fSendTrickle && peer->m_tx_relay->m_send_mempool) {
+ if (fSendTrickle && tx_relay->m_send_mempool) {
auto vtxinfo = m_mempool.infoAll();
- peer->m_tx_relay->m_send_mempool = false;
- const CFeeRate filterrate{peer->m_tx_relay->m_fee_filter_received.load()};
+ tx_relay->m_send_mempool = false;
+ const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
+ LOCK(tx_relay->m_bloom_filter_mutex);
for (const auto& txinfo : vtxinfo) {
const uint256& hash = peer->m_wtxid_relay ? txinfo.tx->GetWitnessHash() : txinfo.tx->GetHash();
CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
- peer->m_tx_relay->m_tx_inventory_to_send.erase(hash);
+ tx_relay->m_tx_inventory_to_send.erase(hash);
// Don't send transactions that peers will not put into their mempool
if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
continue;
}
- if (peer->m_tx_relay->m_bloom_filter) {
- if (!peer->m_tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
+ if (tx_relay->m_bloom_filter) {
+ if (!tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
}
- peer->m_tx_relay->m_tx_inventory_known_filter.insert(hash);
+ tx_relay->m_tx_inventory_known_filter.insert(hash);
// Responses to MEMPOOL requests bypass the m_recently_announced_invs filter.
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
@@ -4884,18 +4926,18 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
vInv.clear();
}
}
- peer->m_tx_relay->m_last_mempool_req = std::chrono::duration_cast<std::chrono::seconds>(current_time);
+ tx_relay->m_last_mempool_req = std::chrono::duration_cast<std::chrono::seconds>(current_time);
}
// Determine transactions to relay
if (fSendTrickle) {
// Produce a vector with all candidates for sending
std::vector<std::set<uint256>::iterator> vInvTx;
- vInvTx.reserve(peer->m_tx_relay->m_tx_inventory_to_send.size());
- for (std::set<uint256>::iterator it = peer->m_tx_relay->m_tx_inventory_to_send.begin(); it != peer->m_tx_relay->m_tx_inventory_to_send.end(); it++) {
+ vInvTx.reserve(tx_relay->m_tx_inventory_to_send.size());
+ for (std::set<uint256>::iterator it = tx_relay->m_tx_inventory_to_send.begin(); it != tx_relay->m_tx_inventory_to_send.end(); it++) {
vInvTx.push_back(it);
}
- const CFeeRate filterrate{peer->m_tx_relay->m_fee_filter_received.load()};
+ const CFeeRate filterrate{tx_relay->m_fee_filter_received.load()};
// Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
// A heap is used so that not all items need sorting if only a few are being sent.
CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, peer->m_wtxid_relay);
@@ -4903,7 +4945,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
// No reason to drain out at many times the network's capacity,
// especially since we have many peers and some will draw much shorter delays.
unsigned int nRelayedTransactions = 0;
- LOCK(peer->m_tx_relay->m_bloom_filter_mutex);
+ LOCK(tx_relay->m_bloom_filter_mutex);
while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
// Fetch the top element from the heap
std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
@@ -4912,9 +4954,9 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
uint256 hash = *it;
CInv inv(peer->m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
// Remove it from the to-be-sent set
- peer->m_tx_relay->m_tx_inventory_to_send.erase(it);
+ tx_relay->m_tx_inventory_to_send.erase(it);
// Check if not in the filter already
- if (peer->m_tx_relay->m_tx_inventory_known_filter.contains(hash)) {
+ if (tx_relay->m_tx_inventory_known_filter.contains(hash)) {
continue;
}
// Not in the mempool anymore? don't bother sending it.
@@ -4928,7 +4970,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
continue;
}
- if (peer->m_tx_relay->m_bloom_filter && !peer->m_tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
+ if (tx_relay->m_bloom_filter && !tx_relay->m_bloom_filter->IsRelevantAndUpdate(*txinfo.tx)) continue;
// Send
State(pto->GetId())->m_recently_announced_invs.insert(hash);
vInv.push_back(inv);
@@ -4955,14 +4997,14 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear();
}
- peer->m_tx_relay->m_tx_inventory_known_filter.insert(hash);
+ tx_relay->m_tx_inventory_known_filter.insert(hash);
if (hash != txid) {
// Insert txid into m_tx_inventory_known_filter, even for
// wtxidrelay peers. This prevents re-adding of
// unconfirmed parents to the recently_announced
// filter, when a child tx is requested. See
// ProcessGetData().
- peer->m_tx_relay->m_tx_inventory_known_filter.insert(txid);
+ tx_relay->m_tx_inventory_known_filter.insert(txid);
}
}
}
diff --git a/src/net_types.cpp b/src/net_types.cpp
index e4101a9876..90346715f0 100644
--- a/src/net_types.cpp
+++ b/src/net_types.cpp
@@ -12,9 +12,9 @@
static const char* BANMAN_JSON_VERSION_KEY{"version"};
CBanEntry::CBanEntry(const UniValue& json)
- : nVersion(json[BANMAN_JSON_VERSION_KEY].get_int()),
- nCreateTime(json["ban_created"].get_int64()),
- nBanUntil(json["banned_until"].get_int64())
+ : nVersion(json[BANMAN_JSON_VERSION_KEY].getInt<int>()),
+ nCreateTime(json["ban_created"].getInt<int64_t>()),
+ nBanUntil(json["banned_until"].getInt<int64_t>())
{
}
@@ -58,7 +58,7 @@ UniValue BanMapToJson(const banmap_t& bans)
void BanMapFromJson(const UniValue& bans_json, banmap_t& bans)
{
for (const auto& ban_entry_json : bans_json.getValues()) {
- const int version{ban_entry_json[BANMAN_JSON_VERSION_KEY].get_int()};
+ const int version{ban_entry_json[BANMAN_JSON_VERSION_KEY].getInt<int>()};
if (version != CBanEntry::CURRENT_VERSION) {
LogPrintf("Dropping entry with unknown version (%s) from ban list\n", version);
continue;
diff --git a/src/netaddress.cpp b/src/netaddress.cpp
index 9717f7abce..ca148bfa51 100644
--- a/src/netaddress.cpp
+++ b/src/netaddress.cpp
@@ -98,7 +98,7 @@ bool CNetAddr::SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t addre
*
* @note This address is considered invalid by CNetAddr::IsValid()
*/
-CNetAddr::CNetAddr() {}
+CNetAddr::CNetAddr() = default;
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
diff --git a/src/node/context.cpp b/src/node/context.cpp
index 0b31c10f44..4787efa1de 100644
--- a/src/node/context.cpp
+++ b/src/node/context.cpp
@@ -16,6 +16,6 @@
#include <validation.h>
namespace node {
-NodeContext::NodeContext() {}
-NodeContext::~NodeContext() {}
+NodeContext::NodeContext() = default;
+NodeContext::~NodeContext() = default;
} // namespace node
diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp
index 954bd1c31d..f2debc790c 100644
--- a/src/node/interfaces.cpp
+++ b/src/node/interfaces.cpp
@@ -426,7 +426,7 @@ public:
// try to handle the request. Otherwise, reraise the exception.
if (!last_handler) {
const UniValue& code = e["code"];
- if (code.isNum() && code.get_int() == RPC_WALLET_NOT_FOUND) {
+ if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
return false;
}
}
diff --git a/src/policy/fees.cpp b/src/policy/fees.cpp
index 6499dbd97f..d2deaf69d0 100644
--- a/src/policy/fees.cpp
+++ b/src/policy/fees.cpp
@@ -537,9 +537,7 @@ CBlockPolicyEstimator::CBlockPolicyEstimator()
}
}
-CBlockPolicyEstimator::~CBlockPolicyEstimator()
-{
-}
+CBlockPolicyEstimator::~CBlockPolicyEstimator() = default;
void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool validFeeEstimate)
{
diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp
index dcab631d98..27ee9509e6 100644
--- a/src/qt/addresstablemodel.cpp
+++ b/src/qt/addresstablemodel.cpp
@@ -30,7 +30,7 @@ struct AddressTableEntry
QString label;
QString address;
- AddressTableEntry() {}
+ AddressTableEntry() = default;
AddressTableEntry(Type _type, const QString &_label, const QString &_address):
type(_type), label(_label), address(_address) {}
};
diff --git a/src/qt/bantablemodel.cpp b/src/qt/bantablemodel.cpp
index e004fba308..3d0be69302 100644
--- a/src/qt/bantablemodel.cpp
+++ b/src/qt/bantablemodel.cpp
@@ -89,10 +89,7 @@ BanTableModel::BanTableModel(interfaces::Node& node, QObject* parent) :
refresh();
}
-BanTableModel::~BanTableModel()
-{
- // Intentionally left empty
-}
+BanTableModel::~BanTableModel() = default;
int BanTableModel::rowCount(const QModelIndex &parent) const
{
diff --git a/src/qt/notificator.cpp b/src/qt/notificator.cpp
index 51151b0be8..483db2892b 100644
--- a/src/qt/notificator.cpp
+++ b/src/qt/notificator.cpp
@@ -71,7 +71,7 @@ Notificator::~Notificator()
class FreedesktopImage
{
public:
- FreedesktopImage() {}
+ FreedesktopImage() = default;
explicit FreedesktopImage(const QImage &img);
// Image to variant that can be marshalled over DBus
diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp
index 820bcbf3cd..a8133f481e 100644
--- a/src/qt/overviewpage.cpp
+++ b/src/qt/overviewpage.cpp
@@ -35,8 +35,7 @@ class TxViewDelegate : public QAbstractItemDelegate
Q_OBJECT
public:
explicit TxViewDelegate(const PlatformStyle* _platformStyle, QObject* parent = nullptr)
- : QAbstractItemDelegate(parent), unit(BitcoinUnit::BTC),
- platformStyle(_platformStyle)
+ : QAbstractItemDelegate(parent), platformStyle(_platformStyle)
{
connect(this, &TxViewDelegate::width_changed, this, &TxViewDelegate::sizeHintChanged);
}
@@ -125,7 +124,7 @@ public:
return {DECORATION_SIZE + 8 + minimum_text_width, DECORATION_SIZE};
}
- BitcoinUnit unit;
+ BitcoinUnit unit{BitcoinUnit::BTC};
Q_SIGNALS:
//! An intermediate signal for emitting from the `paint() const` member function.
diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp
index c82f0683fc..be6f604932 100644
--- a/src/qt/paymentserver.cpp
+++ b/src/qt/paymentserver.cpp
@@ -158,9 +158,7 @@ PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) :
}
}
-PaymentServer::~PaymentServer()
-{
-}
+PaymentServer::~PaymentServer() = default;
//
// OSX-specific way of handling bitcoin: URIs
diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp
index 41c389d9cc..b7de88225e 100644
--- a/src/qt/peertablemodel.cpp
+++ b/src/qt/peertablemodel.cpp
@@ -28,10 +28,7 @@ PeerTableModel::PeerTableModel(interfaces::Node& node, QObject* parent) :
refresh();
}
-PeerTableModel::~PeerTableModel()
-{
- // Intentionally left empty
-}
+PeerTableModel::~PeerTableModel() = default;
void PeerTableModel::startAutoRefresh()
{
diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp
index 03ca9ad7dc..061513b58f 100644
--- a/src/qt/recentrequeststablemodel.cpp
+++ b/src/qt/recentrequeststablemodel.cpp
@@ -34,10 +34,7 @@ RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) :
connect(walletModel->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &RecentRequestsTableModel::updateDisplayUnit);
}
-RecentRequestsTableModel::~RecentRequestsTableModel()
-{
- /* Intentionally left empty */
-}
+RecentRequestsTableModel::~RecentRequestsTableModel() = default;
int RecentRequestsTableModel::rowCount(const QModelIndex &parent) const
{
diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp
index 4a51990f88..023c2bf362 100644
--- a/src/qt/rpcconsole.cpp
+++ b/src/qt/rpcconsole.cpp
@@ -120,7 +120,7 @@ public:
connect(&timer, &QTimer::timeout, [this]{ func(); });
timer.start(millis);
}
- ~QtRPCTimerBase() {}
+ ~QtRPCTimerBase() = default;
private:
QTimer timer;
std::function<void()> func;
@@ -129,7 +129,7 @@ private:
class QtRPCTimerInterface: public RPCTimerInterface
{
public:
- ~QtRPCTimerInterface() {}
+ ~QtRPCTimerInterface() = default;
const char *Name() override { return "Qt"; }
RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) override
{
@@ -457,7 +457,7 @@ void RPCExecutor::request(const QString &command, const WalletModel* wallet_mode
{
try // Nice formatting for standard-format error
{
- int code = find_value(objError, "code").get_int();
+ int code = find_value(objError, "code").getInt<int>();
std::string message = find_value(objError, "message").get_str();
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp
index 7b932890cf..4312b3cd24 100644
--- a/src/qt/transactiontablemodel.cpp
+++ b/src/qt/transactiontablemodel.cpp
@@ -62,7 +62,7 @@ struct TxLessThan
struct TransactionNotification
{
public:
- TransactionNotification() {}
+ TransactionNotification() = default;
TransactionNotification(uint256 _hash, ChangeType _status, bool _showTransaction):
hash(_hash), status(_status), showTransaction(_showTransaction) {}
diff --git a/src/qt/walletframe.cpp b/src/qt/walletframe.cpp
index dc4e25a02b..11bea85b21 100644
--- a/src/qt/walletframe.cpp
+++ b/src/qt/walletframe.cpp
@@ -55,9 +55,7 @@ WalletFrame::WalletFrame(const PlatformStyle* _platformStyle, QWidget* parent)
walletStack->addWidget(no_wallet_group);
}
-WalletFrame::~WalletFrame()
-{
-}
+WalletFrame::~WalletFrame() = default;
void WalletFrame::setClientModel(ClientModel *_clientModel)
{
diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp
index 344bf628bb..2f92c57607 100644
--- a/src/qt/walletview.cpp
+++ b/src/qt/walletview.cpp
@@ -111,9 +111,7 @@ WalletView::WalletView(WalletModel* wallet_model, const PlatformStyle* _platform
connect(walletModel, &WalletModel::showProgress, this, &WalletView::showProgress);
}
-WalletView::~WalletView()
-{
-}
+WalletView::~WalletView() = default;
void WalletView::setClientModel(ClientModel *_clientModel)
{
diff --git a/src/random.cpp b/src/random.cpp
index ec4e44ccc2..74ceb3d2a3 100644
--- a/src/random.cpp
+++ b/src/random.cpp
@@ -370,9 +370,7 @@ public:
InitHardwareRand();
}
- ~RNGState()
- {
- }
+ ~RNGState() = default;
void AddEvent(uint32_t event_info) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_events_mutex)
{
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index daf94afc31..0148544dc9 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -110,7 +110,7 @@ static const CBlockIndex* ParseHashOrHeight(const UniValue& param, ChainstateMan
CChain& active_chain = chainman.ActiveChain();
if (param.isNum()) {
- const int height{param.get_int()};
+ const int height{param.getInt<int>()};
if (height < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
}
@@ -271,7 +271,7 @@ static RPCHelpMan waitfornewblock()
{
int timeout = 0;
if (!request.params[0].isNull())
- timeout = request.params[0].get_int();
+ timeout = request.params[0].getInt<int>();
CUpdatedBlock block;
{
@@ -317,7 +317,7 @@ static RPCHelpMan waitforblock()
uint256 hash(ParseHashV(request.params[0], "blockhash"));
if (!request.params[1].isNull())
- timeout = request.params[1].get_int();
+ timeout = request.params[1].getInt<int>();
CUpdatedBlock block;
{
@@ -361,10 +361,10 @@ static RPCHelpMan waitforblockheight()
{
int timeout = 0;
- int height = request.params[0].get_int();
+ int height = request.params[0].getInt<int>();
if (!request.params[1].isNull())
- timeout = request.params[1].get_int();
+ timeout = request.params[1].getInt<int>();
CUpdatedBlock block;
{
@@ -445,7 +445,7 @@ static RPCHelpMan getblockfrompeer()
PeerManager& peerman = EnsurePeerman(node);
const uint256& block_hash{ParseHashV(request.params[0], "blockhash")};
- const NodeId peer_id{request.params[1].get_int64()};
+ const NodeId peer_id{request.params[1].getInt<int64_t>()};
const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(block_hash););
@@ -485,7 +485,7 @@ static RPCHelpMan getblockhash()
LOCK(cs_main);
const CChain& active_chain = chainman.ActiveChain();
- int nHeight = request.params[0].get_int();
+ int nHeight = request.params[0].getInt<int>();
if (nHeight < 0 || nHeight > active_chain.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
@@ -694,7 +694,7 @@ static RPCHelpMan getblock()
if (request.params[1].isBool()) {
verbosity = request.params[1].get_bool() ? 1 : 0;
} else {
- verbosity = request.params[1].get_int();
+ verbosity = request.params[1].getInt<int>();
}
}
@@ -759,7 +759,7 @@ static RPCHelpMan pruneblockchain()
CChainState& active_chainstate = chainman.ActiveChainstate();
CChain& active_chain = active_chainstate.m_chain;
- int heightParam = request.params[0].get_int();
+ int heightParam = request.params[0].getInt<int>();
if (heightParam < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
}
@@ -1050,8 +1050,8 @@ static RPCHelpMan verifychain()
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
- const int check_level{request.params[0].isNull() ? DEFAULT_CHECKLEVEL : request.params[0].get_int()};
- const int check_depth{request.params[1].isNull() ? DEFAULT_CHECKBLOCKS : request.params[1].get_int()};
+ const int check_level{request.params[0].isNull() ? DEFAULT_CHECKLEVEL : request.params[0].getInt<int>()};
+ const int check_depth{request.params[1].isNull() ? DEFAULT_CHECKBLOCKS : request.params[1].getInt<int>()};
ChainstateManager& chainman = EnsureAnyChainman(request.context);
LOCK(cs_main);
@@ -1585,7 +1585,7 @@ static RPCHelpMan getchaintxstats()
if (request.params[0].isNull()) {
blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
} else {
- blockcount = request.params[0].get_int();
+ blockcount = request.params[0].getInt<int>();
if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
@@ -1948,9 +1948,9 @@ static std::atomic<bool> g_should_abort_scan;
class CoinsViewScanReserver
{
private:
- bool m_could_reserve;
+ bool m_could_reserve{false};
public:
- explicit CoinsViewScanReserver() : m_could_reserve(false) {}
+ explicit CoinsViewScanReserver() = default;
bool reserve() {
CHECK_NONFATAL(!m_could_reserve);
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index 568474fcb9..16b4b6728c 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -109,7 +109,7 @@ static RPCHelpMan getnetworkhashps()
{
ChainstateManager& chainman = EnsureAnyChainman(request.context);
LOCK(cs_main);
- return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, chainman.ActiveChain());
+ return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].getInt<int>() : 120, !request.params[1].isNull() ? request.params[1].getInt<int>() : -1, chainman.ActiveChain());
},
};
}
@@ -217,8 +217,8 @@ static RPCHelpMan generatetodescriptor()
"\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
- const int num_blocks{request.params[0].get_int()};
- const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
+ const int num_blocks{request.params[0].getInt<int>()};
+ const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
CScript coinbase_script;
std::string error;
@@ -264,8 +264,8 @@ static RPCHelpMan generatetoaddress()
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
- const int num_blocks{request.params[0].get_int()};
- const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
+ const int num_blocks{request.params[0].getInt<int>()};
+ const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
CTxDestination destination = DecodeDestination(request.params[1].get_str());
if (!IsValidDestination(destination)) {
@@ -462,7 +462,7 @@ static RPCHelpMan prioritisetransaction()
LOCK(cs_main);
uint256 hash(ParseHashV(request.params[0], "txid"));
- CAmount nAmount = request.params[2].get_int64();
+ CAmount nAmount = request.params[2].getInt<int64_t>();
if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
@@ -657,7 +657,7 @@ static RPCHelpMan getblocktemplate()
// NOTE: It is important that this NOT be read if versionbits is supported
const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
if (uvMaxVersion.isNum()) {
- nMaxVersionPreVB = uvMaxVersion.get_int64();
+ nMaxVersionPreVB = uvMaxVersion.getInt<int64_t>();
}
}
}
@@ -930,10 +930,10 @@ class submitblock_StateCatcher final : public CValidationInterface
{
public:
uint256 hash;
- bool found;
+ bool found{false};
BlockValidationState state;
- explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
+ explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), state() {}
protected:
void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
index ff714eaf36..0a061f2451 100644
--- a/src/rpc/net.cpp
+++ b/src/rpc/net.cpp
@@ -412,7 +412,7 @@ static RPCHelpMan disconnectnode()
success = connman.DisconnectNode(address_arg.get_str());
} else if (!id_arg.isNull() && (address_arg.isNull() || (address_arg.isStr() && address_arg.get_str().empty()))) {
/* handle disconnect-by-id */
- NodeId nodeid = (NodeId) id_arg.get_int64();
+ NodeId nodeid = (NodeId) id_arg.getInt<int64_t>();
success = connman.DisconnectNode(nodeid);
} else {
throw JSONRPCError(RPC_INVALID_PARAMS, "Only one of address and nodeid should be provided.");
@@ -720,7 +720,7 @@ static RPCHelpMan setban()
int64_t banTime = 0; //use standard bantime if not specified
if (!request.params[2].isNull())
- banTime = request.params[2].get_int64();
+ banTime = request.params[2].getInt<int64_t>();
bool absolute = false;
if (request.params[3].isTrue())
@@ -879,7 +879,7 @@ static RPCHelpMan getnodeaddresses()
NodeContext& node = EnsureAnyNodeContext(request.context);
const CConnman& connman = EnsureConnman(node);
- const int count{request.params[0].isNull() ? 1 : request.params[0].get_int()};
+ const int count{request.params[0].isNull() ? 1 : request.params[0].getInt<int>()};
if (count < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Address count out of range");
const std::optional<Network> network{request.params[1].isNull() ? std::nullopt : std::optional<Network>{ParseNetwork(request.params[1].get_str())}};
diff --git a/src/rpc/node.cpp b/src/rpc/node.cpp
index 24697a606e..5475662b82 100644
--- a/src/rpc/node.cpp
+++ b/src/rpc/node.cpp
@@ -53,7 +53,7 @@ static RPCHelpMan setmocktime()
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VNUM});
- const int64_t time{request.params[0].get_int64()};
+ const int64_t time{request.params[0].getInt<int64_t>()};
if (time < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime cannot be negative: %s.", time));
}
@@ -108,7 +108,7 @@ static RPCHelpMan mockscheduler()
// check params are valid values
RPCTypeCheck(request.params, {UniValue::VNUM});
- int64_t delta_seconds = request.params[0].get_int64();
+ int64_t delta_seconds = request.params[0].getInt<int64_t>();
if (delta_seconds <= 0 || delta_seconds > 3600) {
throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
}
diff --git a/src/rpc/output_script.cpp b/src/rpc/output_script.cpp
index 1cf952d0c8..115a656e12 100644
--- a/src/rpc/output_script.cpp
+++ b/src/rpc/output_script.cpp
@@ -124,7 +124,7 @@ static RPCHelpMan createmultisig()
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
- int required = request.params[0].get_int();
+ int required = request.params[0].getInt<int>();
// Get the public keys
const UniValue& keys = request.params[1].get_array();
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index e8713fbd2e..84b8e8dbe0 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -225,7 +225,7 @@ static RPCHelpMan getrawtransaction()
// Accept either a bool (true) or a num (>=1) to indicate verbose output.
bool fVerbose = false;
if (!request.params[1].isNull()) {
- fVerbose = request.params[1].isNum() ? (request.params[1].get_int() != 0) : request.params[1].get_bool();
+ fVerbose = request.params[1].isNum() ? (request.params[1].getInt<int>() != 0) : request.params[1].get_bool();
}
if (!request.params[2].isNull()) {
diff --git a/src/rpc/rawtransaction_util.cpp b/src/rpc/rawtransaction_util.cpp
index e23fe34480..86b5b7e960 100644
--- a/src/rpc/rawtransaction_util.cpp
+++ b/src/rpc/rawtransaction_util.cpp
@@ -40,7 +40,7 @@ CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniVal
CMutableTransaction rawTx;
if (!locktime.isNull()) {
- int64_t nLockTime = locktime.get_int64();
+ int64_t nLockTime = locktime.getInt<int64_t>();
if (nLockTime < 0 || nLockTime > LOCKTIME_MAX)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
@@ -55,7 +55,7 @@ CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniVal
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
- int nOutput = vout_v.get_int();
+ int nOutput = vout_v.getInt<int>();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
@@ -71,7 +71,7 @@ CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniVal
// set the sequence number if passed in the parameters object
const UniValue& sequenceObj = find_value(o, "sequence");
if (sequenceObj.isNum()) {
- int64_t seqNr64 = sequenceObj.get_int64();
+ int64_t seqNr64 = sequenceObj.getInt<int64_t>();
if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
} else {
@@ -177,7 +177,7 @@ void ParsePrevouts(const UniValue& prevTxsUnival, FillableSigningProvider* keyst
uint256 txid = ParseHashO(prevOut, "txid");
- int nOut = find_value(prevOut, "vout").get_int();
+ int nOut = find_value(prevOut, "vout").getInt<int>();
if (nOut < 0) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout cannot be negative");
}
diff --git a/src/rpc/request.cpp b/src/rpc/request.cpp
index d0e068de19..304c265b31 100644
--- a/src/rpc/request.cpp
+++ b/src/rpc/request.cpp
@@ -146,7 +146,7 @@ std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in)
if (!rec.isObject()) {
throw std::runtime_error("Batch member must be an object");
}
- size_t id = rec["id"].get_int();
+ size_t id = rec["id"].getInt<int>();
if (id >= num) {
throw std::runtime_error("Batch member id is larger than batch size");
}
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index 3817a4a45c..af00acdc9f 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -176,7 +176,7 @@ static RPCHelpMan stop()
// this reply will get back to the client.
StartShutdown();
if (jsonRequest.params[0].isNum()) {
- UninterruptibleSleep(std::chrono::milliseconds{jsonRequest.params[0].get_int()});
+ UninterruptibleSleep(std::chrono::milliseconds{jsonRequest.params[0].getInt<int>()});
}
return RESULT;
},
diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp
index ef3e58494e..2d5d4a4cb9 100644
--- a/src/rpc/util.cpp
+++ b/src/rpc/util.cpp
@@ -12,6 +12,7 @@
#include <util/check.h>
#include <util/strencodings.h>
#include <util/string.h>
+#include <util/system.h>
#include <util/translation.h>
#include <tuple>
@@ -267,7 +268,7 @@ CTxDestination AddAndGetMultisigDestination(const int required, const std::vecto
class DescribeAddressVisitor
{
public:
- explicit DescribeAddressVisitor() {}
+ explicit DescribeAddressVisitor() = default;
UniValue operator()(const CNoDestination& dest) const
{
@@ -337,7 +338,7 @@ UniValue DescribeAddress(const CTxDestination& dest)
unsigned int ParseConfirmTarget(const UniValue& value, unsigned int max_target)
{
- const int target{value.get_int()};
+ const int target{value.getInt<int>()};
const unsigned int unsigned_target{static_cast<unsigned int>(target)};
if (target < 1 || unsigned_target > max_target) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u and %u", 1, max_target));
@@ -581,7 +582,9 @@ UniValue RPCHelpMan::HandleRequest(const JSONRPCRequest& request) const
throw std::runtime_error(ToString());
}
const UniValue ret = m_fun(*this, request);
- CHECK_NONFATAL(std::any_of(m_results.m_results.begin(), m_results.m_results.end(), [ret](const RPCResult& res) { return res.MatchesType(ret); }));
+ if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
+ CHECK_NONFATAL(std::any_of(m_results.m_results.begin(), m_results.m_results.end(), [ret](const RPCResult& res) { return res.MatchesType(ret); }));
+ }
return ret;
}
@@ -1023,11 +1026,11 @@ std::string RPCArg::ToString(const bool oneline) const
static std::pair<int64_t, int64_t> ParseRange(const UniValue& value)
{
if (value.isNum()) {
- return {0, value.get_int64()};
+ return {0, value.getInt<int64_t>()};
}
if (value.isArray() && value.size() == 2 && value[0].isNum() && value[1].isNum()) {
- int64_t low = value[0].get_int64();
- int64_t high = value[1].get_int64();
+ int64_t low = value[0].getInt<int64_t>();
+ int64_t high = value[1].getInt<int64_t>();
if (low > high) throw JSONRPCError(RPC_INVALID_PARAMETER, "Range specified as [begin,end] must not have begin after end");
return {low, high};
}
diff --git a/src/rpc/util.h b/src/rpc/util.h
index e16fed75bc..6e23caff6c 100644
--- a/src/rpc/util.h
+++ b/src/rpc/util.h
@@ -22,6 +22,8 @@
#include <variant>
#include <vector>
+static constexpr bool DEFAULT_RPC_DOC_CHECK{false};
+
/**
* String used to describe UNIX epoch time in documentation, factored out to a
* constant for consistency.
diff --git a/src/scheduler.cpp b/src/scheduler.cpp
index 570b417ff5..3df1d48b3c 100644
--- a/src/scheduler.cpp
+++ b/src/scheduler.cpp
@@ -12,9 +12,7 @@
#include <functional>
#include <utility>
-CScheduler::CScheduler()
-{
-}
+CScheduler::CScheduler() = default;
CScheduler::~CScheduler()
{
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index 7328e8d1ad..2d569d674a 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -563,7 +563,7 @@ namespace {
class DummySignatureChecker final : public BaseSignatureChecker
{
public:
- DummySignatureChecker() {}
+ DummySignatureChecker() = default;
bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return true; }
bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return true; }
};
diff --git a/src/support/lockedpool.cpp b/src/support/lockedpool.cpp
index ea1a27c6f6..6907749c6d 100644
--- a/src/support/lockedpool.cpp
+++ b/src/support/lockedpool.cpp
@@ -282,9 +282,8 @@ LockedPool::LockedPool(std::unique_ptr<LockedPageAllocator> allocator_in, Lockin
{
}
-LockedPool::~LockedPool()
-{
-}
+LockedPool::~LockedPool() = default;
+
void* LockedPool::alloc(size_t size)
{
std::lock_guard<std::mutex> lock(mutex);
diff --git a/src/test/blockencodings_tests.cpp b/src/test/blockencodings_tests.cpp
index 9dfbd7ba7c..875241094d 100644
--- a/src/test/blockencodings_tests.cpp
+++ b/src/test/blockencodings_tests.cpp
@@ -64,7 +64,7 @@ BOOST_AUTO_TEST_CASE(SimpleRoundTripTest)
// Do a simple ShortTxIDs RT
{
- CBlockHeaderAndShortTxIDs shortIDs(block, true);
+ CBlockHeaderAndShortTxIDs shortIDs{block};
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << shortIDs;
@@ -122,7 +122,7 @@ public:
stream >> *this;
}
explicit TestHeaderAndShortIDs(const CBlock& block) :
- TestHeaderAndShortIDs(CBlockHeaderAndShortTxIDs(block, true)) {}
+ TestHeaderAndShortIDs(CBlockHeaderAndShortTxIDs{block}) {}
uint64_t GetShortID(const uint256& txhash) const {
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
@@ -279,7 +279,7 @@ BOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest)
// Test simple header round-trip with only coinbase
{
- CBlockHeaderAndShortTxIDs shortIDs(block, false);
+ CBlockHeaderAndShortTxIDs shortIDs{block};
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << shortIDs;
diff --git a/src/test/blockfilter_tests.cpp b/src/test/blockfilter_tests.cpp
index 8eb4dbc592..178757e7b4 100644
--- a/src/test/blockfilter_tests.cpp
+++ b/src/test/blockfilter_tests.cpp
@@ -148,7 +148,7 @@ BOOST_AUTO_TEST_CASE(blockfilters_json_test)
}
unsigned int pos = 0;
- /*int block_height =*/ test[pos++].get_int();
+ /*int block_height =*/ test[pos++].getInt<int>();
uint256 block_hash;
BOOST_CHECK(ParseHashStr(test[pos++].get_str(), block_hash));
diff --git a/src/test/checkqueue_tests.cpp b/src/test/checkqueue_tests.cpp
index 79d6b94dff..875522d744 100644
--- a/src/test/checkqueue_tests.cpp
+++ b/src/test/checkqueue_tests.cpp
@@ -95,7 +95,7 @@ struct MemoryCheck {
{
return true;
}
- MemoryCheck(){};
+ MemoryCheck() = default;
MemoryCheck(const MemoryCheck& x)
{
// We have to do this to make sure that destructor calls are paired
@@ -129,7 +129,7 @@ struct FrozenCleanupCheck {
{
return true;
}
- FrozenCleanupCheck() {}
+ FrozenCleanupCheck() = default;
~FrozenCleanupCheck()
{
if (should_freeze) {
diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp
index fc89fe1450..ab4c587c46 100644
--- a/src/test/dbwrapper_tests.cpp
+++ b/src/test/dbwrapper_tests.cpp
@@ -321,7 +321,7 @@ struct StringContentsSerializer {
// Used to make two serialized objects the same while letting them have different lengths
// This is a terrible idea
std::string str;
- StringContentsSerializer() {}
+ StringContentsSerializer() = default;
explicit StringContentsSerializer(const std::string& inp) : str(inp) {}
StringContentsSerializer& operator+=(const std::string& s) {
diff --git a/src/test/fuzz/script_assets_test_minimizer.cpp b/src/test/fuzz/script_assets_test_minimizer.cpp
index a18a0de47e..35d7246ed8 100644
--- a/src/test/fuzz/script_assets_test_minimizer.cpp
+++ b/src/test/fuzz/script_assets_test_minimizer.cpp
@@ -149,7 +149,7 @@ void Test(const std::string& str)
CMutableTransaction tx = TxFromHex(test["tx"].get_str());
const std::vector<CTxOut> prevouts = TxOutsFromJSON(test["prevouts"]);
if (prevouts.size() != tx.vin.size()) throw std::runtime_error("Incorrect number of prevouts");
- size_t idx = test["index"].get_int64();
+ size_t idx = test["index"].getInt<int64_t>();
if (idx >= tx.vin.size()) throw std::runtime_error("Invalid index");
unsigned int test_flags = ParseScriptFlags(test["flags"].get_str());
bool final = test.exists("final") && test["final"].get_bool();
diff --git a/src/test/fuzz/signature_checker.cpp b/src/test/fuzz/signature_checker.cpp
index f6c591aca4..a585680de1 100644
--- a/src/test/fuzz/signature_checker.cpp
+++ b/src/test/fuzz/signature_checker.cpp
@@ -49,7 +49,7 @@ public:
return m_fuzzed_data_provider.ConsumeBool();
}
- virtual ~FuzzedSignatureChecker() {}
+ virtual ~FuzzedSignatureChecker() = default;
};
} // namespace
diff --git a/src/test/rpc_tests.cpp b/src/test/rpc_tests.cpp
index 7cec287e8f..3e9e04da25 100644
--- a/src/test/rpc_tests.cpp
+++ b/src/test/rpc_tests.cpp
@@ -66,9 +66,9 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams)
BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), std::runtime_error);
std::string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx));
- BOOST_CHECK_EQUAL(find_value(r.get_obj(), "size").get_int(), 193);
- BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1);
- BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0);
+ BOOST_CHECK_EQUAL(find_value(r.get_obj(), "size").getInt<int>(), 193);
+ BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").getInt<int>(), 1);
+ BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").getInt<int>(), 0);
BOOST_CHECK_THROW(CallRPC(std::string("decoderawtransaction ")+rawtx+" extra"), std::runtime_error);
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" false"));
BOOST_CHECK_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" false extra"), std::runtime_error);
@@ -90,7 +90,7 @@ BOOST_AUTO_TEST_CASE(rpc_togglenetwork)
BOOST_CHECK_NO_THROW(CallRPC("setnetworkactive false"));
r = CallRPC("getnetworkinfo");
- int numConnection = find_value(r.get_obj(), "connections").get_int();
+ int numConnection = find_value(r.get_obj(), "connections").getInt<int>();
BOOST_CHECK_EQUAL(numConnection, 0);
netState = find_value(r.get_obj(), "networkactive").get_bool();
@@ -264,7 +264,7 @@ BOOST_AUTO_TEST_CASE(rpc_ban)
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
- int64_t banned_until{find_value(o1, "banned_until").get_int64()};
+ int64_t banned_until{find_value(o1, "banned_until").getInt<int64_t>()};
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24");
BOOST_CHECK_EQUAL(banned_until, 9907731200); // absolute time check
@@ -279,10 +279,10 @@ BOOST_AUTO_TEST_CASE(rpc_ban)
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
- banned_until = find_value(o1, "banned_until").get_int64();
- const int64_t ban_created{find_value(o1, "ban_created").get_int64()};
- const int64_t ban_duration{find_value(o1, "ban_duration").get_int64()};
- const int64_t time_remaining{find_value(o1, "time_remaining").get_int64()};
+ banned_until = find_value(o1, "banned_until").getInt<int64_t>();
+ const int64_t ban_created{find_value(o1, "ban_created").getInt<int64_t>()};
+ const int64_t ban_duration{find_value(o1, "ban_duration").getInt<int64_t>()};
+ const int64_t time_remaining{find_value(o1, "time_remaining").getInt<int64_t>()};
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24");
BOOST_CHECK_EQUAL(banned_until, time_remaining_expected + now.count());
BOOST_CHECK_EQUAL(ban_duration, banned_until - ban_created);
@@ -337,22 +337,22 @@ BOOST_AUTO_TEST_CASE(rpc_convert_values_generatetoaddress)
UniValue result;
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"101", "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a"}));
- BOOST_CHECK_EQUAL(result[0].get_int(), 101);
+ BOOST_CHECK_EQUAL(result[0].getInt<int>(), 101);
BOOST_CHECK_EQUAL(result[1].get_str(), "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a");
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"101", "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU"}));
- BOOST_CHECK_EQUAL(result[0].get_int(), 101);
+ BOOST_CHECK_EQUAL(result[0].getInt<int>(), 101);
BOOST_CHECK_EQUAL(result[1].get_str(), "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU");
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"1", "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a", "9"}));
- BOOST_CHECK_EQUAL(result[0].get_int(), 1);
+ BOOST_CHECK_EQUAL(result[0].getInt<int>(), 1);
BOOST_CHECK_EQUAL(result[1].get_str(), "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a");
- BOOST_CHECK_EQUAL(result[2].get_int(), 9);
+ BOOST_CHECK_EQUAL(result[2].getInt<int>(), 9);
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"1", "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU", "9"}));
- BOOST_CHECK_EQUAL(result[0].get_int(), 1);
+ BOOST_CHECK_EQUAL(result[0].getInt<int>(), 1);
BOOST_CHECK_EQUAL(result[1].get_str(), "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU");
- BOOST_CHECK_EQUAL(result[2].get_int(), 9);
+ BOOST_CHECK_EQUAL(result[2].getInt<int>(), 9);
}
BOOST_AUTO_TEST_CASE(rpc_getblockstats_calculate_percentiles_by_weight)
diff --git a/src/test/script_standard_tests.cpp b/src/test/script_standard_tests.cpp
index 75bc616cf9..25e47c0fb0 100644
--- a/src/test/script_standard_tests.cpp
+++ b/src/test/script_standard_tests.cpp
@@ -406,8 +406,8 @@ BOOST_AUTO_TEST_CASE(bip341_spk_test_vectors)
if (node.isObject()) {
auto script_bytes = ParseHex(node["script"].get_str());
CScript script(script_bytes.begin(), script_bytes.end());
- int idx = node["id"].get_int();
- int leaf_version = node["leafVersion"].get_int();
+ int idx = node["id"].getInt<int>();
+ int leaf_version = node["leafVersion"].getInt<int>();
scriptposes[{script, leaf_version}] = idx;
spktest.Add(depth, script, leaf_version);
} else {
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 19e32d0c36..05bb89ab55 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -257,11 +257,11 @@ private:
CScriptWitness scriptWitness;
CTransactionRef creditTx;
CMutableTransaction spendTx;
- bool havePush;
+ bool havePush{false};
std::vector<unsigned char> push;
std::string comment;
uint32_t flags;
- int scriptError;
+ int scriptError{SCRIPT_ERR_OK};
CAmount nValue;
void DoPush()
@@ -280,7 +280,7 @@ private:
}
public:
- TestBuilder(const CScript& script_, const std::string& comment_, uint32_t 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_)
+ TestBuilder(const CScript& script_, const std::string& comment_, uint32_t flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), comment(comment_), flags(flags_), nValue(nValue_)
{
CScript scriptPubKey = script;
if (wm == WitnessMode::PKH) {
@@ -1678,7 +1678,7 @@ static void AssetTest(const UniValue& test)
CMutableTransaction mtx = TxFromHex(test["tx"].get_str());
const std::vector<CTxOut> prevouts = TxOutsFromJSON(test["prevouts"]);
BOOST_CHECK(prevouts.size() == mtx.vin.size());
- size_t idx = test["index"].get_int64();
+ size_t idx = test["index"].getInt<int64_t>();
uint32_t test_flags{ParseScriptFlags(test["flags"].get_str())};
bool fin = test.exists("final") && test["final"].get_bool();
@@ -1760,7 +1760,7 @@ BOOST_AUTO_TEST_CASE(bip341_keypath_test_vectors)
for (const auto& utxo_spent : vec["given"]["utxosSpent"].getValues()) {
auto script_bytes = ParseHex(utxo_spent["scriptPubKey"].get_str());
CScript script{script_bytes.begin(), script_bytes.end()};
- CAmount amount{utxo_spent["amountSats"].get_int()};
+ CAmount amount{utxo_spent["amountSats"].getInt<int>()};
utxos.emplace_back(amount, script);
}
@@ -1775,8 +1775,8 @@ BOOST_AUTO_TEST_CASE(bip341_keypath_test_vectors)
BOOST_CHECK_EQUAL(HexStr(txdata.m_sequences_single_hash), vec["intermediary"]["hashSequences"].get_str());
for (const auto& input : vec["inputSpending"].getValues()) {
- int txinpos = input["given"]["txinIndex"].get_int();
- int hashtype = input["given"]["hashType"].get_int();
+ int txinpos = input["given"]["txinIndex"].getInt<int>();
+ int hashtype = input["given"]["hashType"].getInt<int>();
// Load key.
auto privkey = ParseHex(input["given"]["internalPrivkey"].get_str());
diff --git a/src/test/sighash_tests.cpp b/src/test/sighash_tests.cpp
index 1601b02356..7376f2ff5c 100644
--- a/src/test/sighash_tests.cpp
+++ b/src/test/sighash_tests.cpp
@@ -184,8 +184,8 @@ BOOST_AUTO_TEST_CASE(sighash_from_data)
// deserialize test data
raw_tx = test[0].get_str();
raw_script = test[1].get_str();
- nIn = test[2].get_int();
- nHashType = test[3].get_int();
+ nIn = test[2].getInt<int>();
+ nHashType = test[3].getInt<int>();
sigHashHex = test[4].get_str();
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index c3a2a66027..4e6c223ccc 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -217,11 +217,11 @@ BOOST_AUTO_TEST_CASE(tx_valid)
fValid = false;
break;
}
- COutPoint outpoint{uint256S(vinput[0].get_str()), uint32_t(vinput[1].get_int())};
+ COutPoint outpoint{uint256S(vinput[0].get_str()), uint32_t(vinput[1].getInt<int>())};
mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
if (vinput.size() >= 4)
{
- mapprevOutValues[outpoint] = vinput[3].get_int64();
+ mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
}
}
if (!fValid)
@@ -305,11 +305,11 @@ BOOST_AUTO_TEST_CASE(tx_invalid)
fValid = false;
break;
}
- COutPoint outpoint{uint256S(vinput[0].get_str()), uint32_t(vinput[1].get_int())};
+ COutPoint outpoint{uint256S(vinput[0].get_str()), uint32_t(vinput[1].getInt<int>())};
mapprevOutScriptPubKeys[outpoint] = ParseScript(vinput[2].get_str());
if (vinput.size() >= 4)
{
- mapprevOutValues[outpoint] = vinput[3].get_int64();
+ mapprevOutValues[outpoint] = vinput[3].getInt<int64_t>();
}
}
if (!fValid)
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp
index eeecbe5ea9..56a1155469 100644
--- a/src/test/util_tests.cpp
+++ b/src/test/util_tests.cpp
@@ -2454,9 +2454,9 @@ struct Tracker
//! Points to the original object (possibly itself) we moved/copied from
const Tracker* origin;
//! How many copies where involved between the original object and this one (moves are not counted)
- int copies;
+ int copies{0};
- Tracker() noexcept : origin(this), copies(0) {}
+ Tracker() noexcept : origin(this) {}
Tracker(const Tracker& t) noexcept : origin(t.origin), copies(t.copies + 1) {}
Tracker(Tracker&& t) noexcept : origin(t.origin), copies(t.copies) {}
Tracker& operator=(const Tracker& t) noexcept
diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
index 05dbc6057f..2064f0fb8a 100644
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -304,8 +304,7 @@ std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
base(_base),
- m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(nullptr),
- reconnect_timeout(RECONNECT_TIMEOUT_START),
+ m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_timeout(RECONNECT_TIMEOUT_START),
m_target(target)
{
reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
diff --git a/src/txdb.cpp b/src/txdb.cpp
index afcd1985f5..a0939873ad 100644
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -207,7 +207,7 @@ public:
// cache warmup on instantiation.
CCoinsViewDBCursor(CDBIterator* pcursorIn, const uint256&hashBlockIn):
CCoinsViewCursor(hashBlockIn), pcursor(pcursorIn) {}
- ~CCoinsViewDBCursor() {}
+ ~CCoinsViewDBCursor() = default;
bool GetKey(COutPoint &key) const override;
bool GetValue(Coin &coin) const override;
diff --git a/src/util/settings.h b/src/util/settings.h
index ed36349232..261a0a032f 100644
--- a/src/util/settings.h
+++ b/src/util/settings.h
@@ -20,7 +20,7 @@ namespace util {
//! @note UniValue is used here for convenience and because it can be easily
//! serialized in a readable format. But any other variant type that can
//! be assigned strings, int64_t, and bool values and has get_str(),
-//! get_int64(), get_bool(), isNum(), isBool(), isFalse(), isTrue() and
+//! getInt<int64_t>(), get_bool(), isNum(), isBool(), isFalse(), isTrue() and
//! isNull() methods can be substituted if there's a need to move away
//! from UniValue. (An implementation with boost::variant was posted at
//! https://github.com/bitcoin/bitcoin/pull/15934/files#r337691812)
diff --git a/src/util/system.cpp b/src/util/system.cpp
index 44ebf5cb3e..cbe9d2ceb0 100644
--- a/src/util/system.cpp
+++ b/src/util/system.cpp
@@ -258,8 +258,8 @@ static std::optional<util::SettingsValue> InterpretValue(const KeyInfo& key, con
// Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
// #include class definitions for all members.
// For example, m_settings has an internal dependency on univalue.
-ArgsManager::ArgsManager() {}
-ArgsManager::~ArgsManager() {}
+ArgsManager::ArgsManager() = default;
+ArgsManager::~ArgsManager() = default;
const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
{
@@ -606,7 +606,7 @@ std::string ArgsManager::GetArg(const std::string& strArg, const std::string& st
int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
{
const util::SettingsValue value = GetSetting(strArg);
- return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : LocaleIndependentAtoi<int64_t>(value.get_str());
+ return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.getInt<int64_t>() : LocaleIndependentAtoi<int64_t>(value.get_str());
}
bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
diff --git a/src/validation.cpp b/src/validation.cpp
index 51d77b7945..a7cdf63a2a 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -2654,7 +2654,7 @@ static int64_t nTimePostConnect = 0;
struct PerBlockConnectTrace {
CBlockIndex* pindex = nullptr;
std::shared_ptr<const CBlock> pblock;
- PerBlockConnectTrace() {}
+ PerBlockConnectTrace() = default;
};
/**
* Used to track blocks whose transactions were applied to the UTXO state as a
diff --git a/src/wallet/context.cpp b/src/wallet/context.cpp
index 800aa5bf9c..3d4bf9d703 100644
--- a/src/wallet/context.cpp
+++ b/src/wallet/context.cpp
@@ -5,6 +5,6 @@
#include <wallet/context.h>
namespace wallet {
-WalletContext::WalletContext() {}
-WalletContext::~WalletContext() {}
+WalletContext::WalletContext() = default;
+WalletContext::~WalletContext() = default;
} // namespace wallet
diff --git a/src/wallet/rpc/addresses.cpp b/src/wallet/rpc/addresses.cpp
index d4f6c9d805..d5444f5051 100644
--- a/src/wallet/rpc/addresses.cpp
+++ b/src/wallet/rpc/addresses.cpp
@@ -264,7 +264,7 @@ RPCHelpMan addmultisigaddress()
if (!request.params[2].isNull())
label = LabelFromValue(request.params[2]);
- int required = request.params[0].get_int();
+ int required = request.params[0].getInt<int>();
// Get the public keys
const UniValue& keys_or_addrs = request.params[1].get_array();
@@ -340,9 +340,9 @@ RPCHelpMan keypoolrefill()
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (!request.params[0].isNull()) {
- if (request.params[0].get_int() < 0)
+ if (request.params[0].getInt<int>() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
- kpSize = (unsigned int)request.params[0].get_int();
+ kpSize = (unsigned int)request.params[0].getInt<int>();
}
EnsureWalletIsUnlocked(*pwallet);
diff --git a/src/wallet/rpc/backup.cpp b/src/wallet/rpc/backup.cpp
index b4f01b00de..c289c05f2c 100644
--- a/src/wallet/rpc/backup.cpp
+++ b/src/wallet/rpc/backup.cpp
@@ -1232,7 +1232,7 @@ static int64_t GetImportTimestamp(const UniValue& data, int64_t now)
if (data.exists("timestamp")) {
const UniValue& timestamp = data["timestamp"];
if (timestamp.isNum()) {
- return timestamp.get_int64();
+ return timestamp.getInt<int64_t>();
} else if (timestamp.isStr() && timestamp.get_str() == "now") {
return now;
}
@@ -1473,7 +1473,7 @@ static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, c
next_index = range_start;
if (data.exists("next_index")) {
- next_index = data["next_index"].get_int64();
+ next_index = data["next_index"].getInt<int64_t>();
// bound checks
if (next_index < range_start || next_index >= range_end) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "next_index is out of range");
diff --git a/src/wallet/rpc/coins.cpp b/src/wallet/rpc/coins.cpp
index bd61c9c62f..0e7bf34c11 100644
--- a/src/wallet/rpc/coins.cpp
+++ b/src/wallet/rpc/coins.cpp
@@ -45,7 +45,7 @@ static CAmount GetReceived(const CWallet& wallet, const UniValue& params, bool b
// Minimum confirmations
int min_depth = 1;
if (!params[1].isNull())
- min_depth = params[1].get_int();
+ min_depth = params[1].getInt<int>();
const bool include_immature_coinbase{params[2].isNull() ? false : params[2].get_bool()};
@@ -204,7 +204,7 @@ RPCHelpMan getbalance()
int min_depth = 0;
if (!request.params[1].isNull()) {
- min_depth = request.params[1].get_int();
+ min_depth = request.params[1].getInt<int>();
}
bool include_watchonly = ParseIncludeWatchonly(request.params[2], *pwallet);
@@ -328,7 +328,7 @@ RPCHelpMan lockunspent()
});
const uint256 txid(ParseHashO(o, "txid"));
- const int nOutput = find_value(o, "vout").get_int();
+ const int nOutput = find_value(o, "vout").getInt<int>();
if (nOutput < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
}
@@ -569,13 +569,13 @@ RPCHelpMan listunspent()
int nMinDepth = 1;
if (!request.params[0].isNull()) {
RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
- nMinDepth = request.params[0].get_int();
+ nMinDepth = request.params[0].getInt<int>();
}
int nMaxDepth = 9999999;
if (!request.params[1].isNull()) {
RPCTypeCheckArgument(request.params[1], UniValue::VNUM);
- nMaxDepth = request.params[1].get_int();
+ nMaxDepth = request.params[1].getInt<int>();
}
std::set<CTxDestination> destinations;
@@ -627,7 +627,7 @@ RPCHelpMan listunspent()
nMinimumSumAmount = AmountFromValue(options["minimumSumAmount"]);
if (options.exists("maximumCount"))
- nMaximumCount = options["maximumCount"].get_int64();
+ nMaximumCount = options["maximumCount"].getInt<int64_t>();
}
// Make sure the results are valid at least up to the most recent block
diff --git a/src/wallet/rpc/encrypt.cpp b/src/wallet/rpc/encrypt.cpp
index 802cc63d6d..931c64ca06 100644
--- a/src/wallet/rpc/encrypt.cpp
+++ b/src/wallet/rpc/encrypt.cpp
@@ -54,7 +54,7 @@ RPCHelpMan walletpassphrase()
strWalletPass = request.params[0].get_str().c_str();
// Get the timeout
- nSleepTime = request.params[1].get_int64();
+ nSleepTime = request.params[1].getInt<int64_t>();
// Timeout cannot be negative, otherwise it will relock immediately
if (nSleepTime < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Timeout cannot be negative.");
diff --git a/src/wallet/rpc/spend.cpp b/src/wallet/rpc/spend.cpp
index 3d975b5402..c7b57ba4be 100644
--- a/src/wallet/rpc/spend.cpp
+++ b/src/wallet/rpc/spend.cpp
@@ -551,7 +551,7 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
}
if (options.exists("changePosition") || options.exists("change_position")) {
- change_position = (options.exists("change_position") ? options["change_position"] : options["changePosition"]).get_int();
+ change_position = (options.exists("change_position") ? options["change_position"] : options["changePosition"]).getInt<int>();
}
if (options.exists("change_type")) {
@@ -659,7 +659,7 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
if (!vout_v.isNum()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
}
- int vout = vout_v.get_int();
+ int vout = vout_v.getInt<int>();
if (vout < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
}
@@ -668,7 +668,7 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
if (!weight_v.isNum()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing weight key");
}
- int64_t weight = weight_v.get_int64();
+ int64_t weight = weight_v.getInt<int64_t>();
const int64_t min_input_weight = GetTransactionInputWeight(CTxIn());
CHECK_NONFATAL(min_input_weight == 165);
if (weight < min_input_weight) {
@@ -689,7 +689,7 @@ void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out,
throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) {
- int pos = subtractFeeFromOutputs[idx].get_int();
+ int pos = subtractFeeFromOutputs[idx].getInt<int>();
if (setSubtractFeeFromOutputs.count(pos))
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos));
if (pos < 0)
diff --git a/src/wallet/rpc/transactions.cpp b/src/wallet/rpc/transactions.cpp
index 1b06973f78..09dbf16881 100644
--- a/src/wallet/rpc/transactions.cpp
+++ b/src/wallet/rpc/transactions.cpp
@@ -64,9 +64,7 @@ struct tallyitem
int nConf{std::numeric_limits<int>::max()};
std::vector<uint256> txids;
bool fIsWatchonly{false};
- tallyitem()
- {
- }
+ tallyitem() = default;
};
static UniValue ListReceived(const CWallet& wallet, const UniValue& params, const bool by_label, const bool include_immature_coinbase) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
@@ -74,7 +72,7 @@ static UniValue ListReceived(const CWallet& wallet, const UniValue& params, cons
// Minimum confirmations
int nMinDepth = 1;
if (!params[0].isNull())
- nMinDepth = params[0].get_int();
+ nMinDepth = params[0].getInt<int>();
// Whether to include empty labels
bool fIncludeEmpty = false;
@@ -514,10 +512,10 @@ RPCHelpMan listtransactions()
}
int nCount = 10;
if (!request.params[1].isNull())
- nCount = request.params[1].get_int();
+ nCount = request.params[1].getInt<int>();
int nFrom = 0;
if (!request.params[2].isNull())
- nFrom = request.params[2].get_int();
+ nFrom = request.params[2].getInt<int>();
isminefilter filter = ISMINE_SPENDABLE;
if (ParseIncludeWatchonly(request.params[3], *pwallet)) {
@@ -640,7 +638,7 @@ RPCHelpMan listsinceblock()
}
if (!request.params[1].isNull()) {
- target_confirms = request.params[1].get_int();
+ target_confirms = request.params[1].getInt<int>();
if (target_confirms < 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
@@ -894,14 +892,14 @@ RPCHelpMan rescanblockchain()
int tip_height = pwallet->GetLastBlockHeight();
if (!request.params[0].isNull()) {
- start_height = request.params[0].get_int();
+ start_height = request.params[0].getInt<int>();
if (start_height < 0 || start_height > tip_height) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height");
}
}
if (!request.params[1].isNull()) {
- stop_height = request.params[1].get_int();
+ stop_height = request.params[1].getInt<int>();
if (*stop_height < 0 || *stop_height > tip_height) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height");
} else if (*stop_height < start_height) {
diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp
index efb4d8fc7e..4c44c333a6 100644
--- a/src/wallet/rpc/wallet.cpp
+++ b/src/wallet/rpc/wallet.cpp
@@ -559,7 +559,7 @@ static RPCHelpMan upgradewallet()
int version = 0;
if (!request.params[0].isNull()) {
- version = request.params[0].get_int();
+ version = request.params[0].getInt<int>();
}
bilingual_str error;
const int previous_version{pwallet->GetVersion()};
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
index 7bbed7973f..79e0a330b7 100644
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -314,8 +314,7 @@ public:
std::map<uint160, CHDChain> m_hd_chains;
bool tx_corrupt{false};
- CWalletScanState() {
- }
+ CWalletScanState() = default;
};
static bool