aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/.clang-format2
-rw-r--r--src/addrdb.cpp214
-rw-r--r--src/addrdb.h2
-rw-r--r--src/arith_uint256.cpp2
-rw-r--r--src/arith_uint256.h10
-rw-r--r--src/bench/bench_bitcoin.cpp2
-rw-r--r--src/bench/coin_selection.cpp2
-rw-r--r--src/bitcoin-tx.cpp3
-rw-r--r--src/bloom.cpp2
-rw-r--r--src/chain.cpp2
-rw-r--r--src/checkqueue.h4
-rw-r--r--src/coins.cpp5
-rw-r--r--src/coins.h11
-rw-r--r--src/consensus/tx_verify.cpp8
-rw-r--r--src/core_write.cpp2
-rw-r--r--src/cuckoocache.h35
-rw-r--r--src/dbwrapper.cpp2
-rw-r--r--src/httprpc.cpp4
-rw-r--r--src/httpserver.cpp24
-rw-r--r--src/httpserver.h4
-rw-r--r--src/init.cpp32
-rw-r--r--src/leveldb/db/version_set.h2
-rw-r--r--src/miner.cpp6
-rw-r--r--src/net.cpp68
-rw-r--r--src/net_processing.cpp38
-rw-r--r--src/policy/fees.cpp90
-rw-r--r--src/policy/fees.h36
-rw-r--r--src/policy/policy.cpp4
-rw-r--r--src/policy/rbf.cpp4
-rw-r--r--src/qt/addressbookpage.cpp2
-rw-r--r--src/qt/addresstablemodel.cpp2
-rw-r--r--src/qt/bitcoingui.cpp6
-rw-r--r--src/qt/clientmodel.cpp2
-rw-r--r--src/qt/coincontroldialog.cpp25
-rw-r--r--src/qt/forms/optionsdialog.ui6
-rw-r--r--src/qt/intro.cpp2
-rw-r--r--src/qt/modaloverlay.cpp2
-rw-r--r--src/qt/optionsdialog.cpp2
-rw-r--r--src/qt/paymentserver.cpp10
-rw-r--r--src/qt/peertablemodel.cpp6
-rw-r--r--src/qt/platformstyle.cpp3
-rw-r--r--src/qt/receivecoinsdialog.cpp2
-rw-r--r--src/qt/recentrequeststablemodel.cpp2
-rw-r--r--src/qt/rpcconsole.cpp4
-rw-r--r--src/qt/sendcoinsdialog.cpp16
-rw-r--r--src/qt/splashscreen.cpp2
-rw-r--r--src/qt/test/paymentservertests.cpp2
-rw-r--r--src/qt/test/rpcnestedtests.cpp2
-rw-r--r--src/qt/trafficgraphwidget.cpp4
-rw-r--r--src/qt/transactiondesc.cpp22
-rw-r--r--src/qt/transactionrecord.cpp4
-rw-r--r--src/qt/transactiontablemodel.cpp2
-rw-r--r--src/qt/utilitydialog.cpp2
-rw-r--r--src/qt/walletmodel.cpp10
-rw-r--r--src/qt/walletmodeltransaction.cpp2
-rw-r--r--src/random.cpp74
-rw-r--r--src/random.h3
-rw-r--r--src/rest.cpp8
-rw-r--r--src/rpc/blockchain.cpp20
-rw-r--r--src/rpc/mining.cpp8
-rw-r--r--src/rpc/misc.cpp2
-rw-r--r--src/rpc/net.cpp26
-rw-r--r--src/rpc/rawtransaction.cpp20
-rw-r--r--src/rpc/server.cpp6
-rw-r--r--src/script/ismine.cpp2
-rw-r--r--src/script/sign.cpp8
-rw-r--r--src/script/standard.cpp4
-rw-r--r--src/secp256k1/sage/group_prover.sage2
-rw-r--r--src/secp256k1/src/asm/field_10x26_arm.s2
-rw-r--r--src/support/events.h10
-rw-r--r--src/sync.cpp10
-rw-r--r--src/test/arith_uint256_tests.cpp2
-rw-r--r--src/test/bip32_tests.cpp2
-rw-r--r--src/test/coins_tests.cpp2
-rw-r--r--src/test/data/script_tests.json2
-rw-r--r--src/test/data/tx_valid.json2
-rw-r--r--src/test/getarg_tests.cpp2
-rw-r--r--src/test/multisig_tests.cpp2
-rw-r--r--src/test/prevector_tests.cpp4
-rw-r--r--src/test/script_tests.cpp4
-rw-r--r--src/test/test_bitcoin.cpp3
-rw-r--r--src/test/transaction_tests.cpp4
-rw-r--r--src/timedata.cpp4
-rw-r--r--src/torcontrol.cpp12
-rw-r--r--src/txmempool.cpp60
-rw-r--r--src/util.cpp8
-rw-r--r--src/util.h125
-rw-r--r--src/utilstrencodings.cpp8
-rw-r--r--src/utilstrencodings.h3
-rw-r--r--src/validation.cpp61
-rw-r--r--src/validation.h4
-rw-r--r--src/wallet/crypter.cpp3
-rw-r--r--src/wallet/db.cpp4
-rw-r--r--src/wallet/feebumper.cpp2
-rw-r--r--src/wallet/rpcdump.cpp6
-rw-r--r--src/wallet/rpcwallet.cpp35
-rw-r--r--src/wallet/test/accounting_tests.cpp2
-rw-r--r--src/wallet/wallet.cpp158
-rw-r--r--src/wallet/wallet.h3
-rw-r--r--src/wallet/walletdb.cpp20
100 files changed, 813 insertions, 703 deletions
diff --git a/src/.clang-format b/src/.clang-format
index fc53509138..5918819d13 100644
--- a/src/.clang-format
+++ b/src/.clang-format
@@ -47,6 +47,6 @@ SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
-Standard: Cpp03
+Standard: Cpp11
TabWidth: 8
UseTab: Never
diff --git a/src/addrdb.cpp b/src/addrdb.cpp
index a3743cd0d4..7f85c16585 100644
--- a/src/addrdb.cpp
+++ b/src/addrdb.cpp
@@ -15,25 +15,31 @@
#include "tinyformat.h"
#include "util.h"
+namespace {
-CBanDB::CBanDB()
+template <typename Stream, typename Data>
+bool SerializeDB(Stream& stream, const Data& data)
{
- pathBanlist = GetDataDir() / "banlist.dat";
+ // Write and commit header, data
+ try {
+ CHashWriter hasher(SER_DISK, CLIENT_VERSION);
+ stream << FLATDATA(Params().MessageStart()) << data;
+ hasher << FLATDATA(Params().MessageStart()) << data;
+ stream << hasher.GetHash();
+ } catch (const std::exception& e) {
+ return error("%s: Serialize or I/O error - %s", __func__, e.what());
+ }
+
+ return true;
}
-bool CBanDB::Write(const banmap_t& banSet)
+template <typename Data>
+bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
- std::string tmpfn = strprintf("banlist.dat.%04x", randv);
-
- // serialize banlist, checksum data up to that point, then append csum
- CDataStream ssBanlist(SER_DISK, CLIENT_VERSION);
- ssBanlist << FLATDATA(Params().MessageStart());
- ssBanlist << banSet;
- uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end());
- ssBanlist << hash;
+ std::string tmpfn = strprintf("%s.%04x", prefix, randv);
// open temp output file, and associate with CAutoFile
fs::path pathTmp = GetDataDir() / tmpfn;
@@ -42,69 +48,41 @@ bool CBanDB::Write(const banmap_t& banSet)
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, pathTmp.string());
- // Write and commit header, data
- try {
- fileout << ssBanlist;
- }
- catch (const std::exception& e) {
- return error("%s: Serialize or I/O error - %s", __func__, e.what());
- }
+ // Serialize
+ if (!SerializeDB(fileout, data)) return false;
FileCommit(fileout.Get());
fileout.fclose();
- // replace existing banlist.dat, if any, with new banlist.dat.XXXX
- if (!RenameOver(pathTmp, pathBanlist))
+ // replace existing file, if any, with new file
+ if (!RenameOver(pathTmp, path))
return error("%s: Rename-into-place failed", __func__);
return true;
}
-bool CBanDB::Read(banmap_t& banSet)
+template <typename Stream, typename Data>
+bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
{
- // open input file, and associate with CAutoFile
- FILE *file = fsbridge::fopen(pathBanlist, "rb");
- CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
- if (filein.IsNull())
- return error("%s: Failed to open file %s", __func__, pathBanlist.string());
-
- // use file size to size memory buffer
- uint64_t fileSize = fs::file_size(pathBanlist);
- uint64_t dataSize = 0;
- // Don't try to resize to a negative number if file is small
- if (fileSize >= sizeof(uint256))
- dataSize = fileSize - sizeof(uint256);
- std::vector<unsigned char> vchData;
- vchData.resize(dataSize);
- uint256 hashIn;
-
- // read data and checksum from file
- try {
- filein.read((char *)&vchData[0], dataSize);
- filein >> hashIn;
- }
- catch (const std::exception& e) {
- return error("%s: Deserialize or I/O error - %s", __func__, e.what());
- }
- filein.fclose();
-
- CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION);
-
- // verify stored checksum matches input data
- uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end());
- if (hashIn != hashTmp)
- return error("%s: Checksum mismatch, data corrupted", __func__);
-
- unsigned char pchMsgTmp[4];
try {
+ CHashVerifier<Stream> verifier(&stream);
// de-serialize file header (network specific magic number) and ..
- ssBanlist >> FLATDATA(pchMsgTmp);
-
+ unsigned char pchMsgTmp[4];
+ verifier >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
- // de-serialize ban data
- ssBanlist >> banSet;
+ // de-serialize data
+ verifier >> data;
+
+ // verify checksum
+ if (fCheckSum) {
+ uint256 hashTmp;
+ stream >> hashTmp;
+ if (hashTmp != verifier.GetHash()) {
+ return error("%s: Checksum mismatch, data corrupted", __func__);
+ }
+ }
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
@@ -113,106 +91,56 @@ bool CBanDB::Read(banmap_t& banSet)
return true;
}
-CAddrDB::CAddrDB()
+template <typename Data>
+bool DeserializeFileDB(const fs::path& path, Data& data)
{
- pathAddr = GetDataDir() / "peers.dat";
+ // open input file, and associate with CAutoFile
+ FILE *file = fsbridge::fopen(path, "rb");
+ CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
+ if (filein.IsNull())
+ return error("%s: Failed to open file %s", __func__, path.string());
+
+ return DeserializeDB(filein, data);
}
-bool CAddrDB::Write(const CAddrMan& addr)
-{
- // Generate random temporary filename
- unsigned short randv = 0;
- GetRandBytes((unsigned char*)&randv, sizeof(randv));
- std::string tmpfn = strprintf("peers.dat.%04x", randv);
+}
- // serialize addresses, checksum data up to that point, then append csum
- CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
- ssPeers << FLATDATA(Params().MessageStart());
- ssPeers << addr;
- uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
- ssPeers << hash;
+CBanDB::CBanDB()
+{
+ pathBanlist = GetDataDir() / "banlist.dat";
+}
- // open temp output file, and associate with CAutoFile
- fs::path pathTmp = GetDataDir() / tmpfn;
- FILE *file = fsbridge::fopen(pathTmp, "wb");
- CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
- if (fileout.IsNull())
- return error("%s: Failed to open file %s", __func__, pathTmp.string());
+bool CBanDB::Write(const banmap_t& banSet)
+{
+ return SerializeFileDB("banlist", pathBanlist, banSet);
+}
- // Write and commit header, data
- try {
- fileout << ssPeers;
- }
- catch (const std::exception& e) {
- return error("%s: Serialize or I/O error - %s", __func__, e.what());
- }
- FileCommit(fileout.Get());
- fileout.fclose();
+bool CBanDB::Read(banmap_t& banSet)
+{
+ return DeserializeFileDB(pathBanlist, banSet);
+}
- // replace existing peers.dat, if any, with new peers.dat.XXXX
- if (!RenameOver(pathTmp, pathAddr))
- return error("%s: Rename-into-place failed", __func__);
+CAddrDB::CAddrDB()
+{
+ pathAddr = GetDataDir() / "peers.dat";
+}
- return true;
+bool CAddrDB::Write(const CAddrMan& addr)
+{
+ return SerializeFileDB("peers", pathAddr, addr);
}
bool CAddrDB::Read(CAddrMan& addr)
{
- // open input file, and associate with CAutoFile
- FILE *file = fsbridge::fopen(pathAddr, "rb");
- CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
- if (filein.IsNull())
- return error("%s: Failed to open file %s", __func__, pathAddr.string());
-
- // use file size to size memory buffer
- uint64_t fileSize = fs::file_size(pathAddr);
- uint64_t dataSize = 0;
- // Don't try to resize to a negative number if file is small
- if (fileSize >= sizeof(uint256))
- dataSize = fileSize - sizeof(uint256);
- std::vector<unsigned char> vchData;
- vchData.resize(dataSize);
- uint256 hashIn;
-
- // read data and checksum from file
- try {
- filein.read((char *)&vchData[0], dataSize);
- filein >> hashIn;
- }
- catch (const std::exception& e) {
- return error("%s: Deserialize or I/O error - %s", __func__, e.what());
- }
- filein.fclose();
-
- CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
-
- // verify stored checksum matches input data
- uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
- if (hashIn != hashTmp)
- return error("%s: Checksum mismatch, data corrupted", __func__);
-
- return Read(addr, ssPeers);
+ return DeserializeFileDB(pathAddr, addr);
}
bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
{
- unsigned char pchMsgTmp[4];
- try {
- // de-serialize file header (network specific magic number) and ..
- ssPeers >> FLATDATA(pchMsgTmp);
-
- // ... verify the network matches ours
- if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
- return error("%s: Invalid network magic number", __func__);
-
- // de-serialize address data into one CAddrMan object
- ssPeers >> addr;
- }
- catch (const std::exception& e) {
- // de-serialization has failed, ensure addrman is left in a clean state
+ bool ret = DeserializeDB(ssPeers, addr, false);
+ if (!ret) {
+ // Ensure addrman is left in a clean state
addr.Clear();
- return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
-
- return true;
+ return ret;
}
diff --git a/src/addrdb.h b/src/addrdb.h
index c3d509bd3a..6cb36dfac4 100644
--- a/src/addrdb.h
+++ b/src/addrdb.h
@@ -85,7 +85,7 @@ public:
CAddrDB();
bool Write(const CAddrMan& addr);
bool Read(CAddrMan& addr);
- bool Read(CAddrMan& addr, CDataStream& ssPeers);
+ static bool Read(CAddrMan& addr, CDataStream& ssPeers);
};
/** Access to the banlist database (banlist.dat) */
diff --git a/src/arith_uint256.cpp b/src/arith_uint256.cpp
index dd34a313b7..b4952af6f4 100644
--- a/src/arith_uint256.cpp
+++ b/src/arith_uint256.cpp
@@ -15,6 +15,8 @@
template <unsigned int BITS>
base_uint<BITS>::base_uint(const std::string& str)
{
+ static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
+
SetHex(str);
}
diff --git a/src/arith_uint256.h b/src/arith_uint256.h
index 0f6b3d4fba..c7734035df 100644
--- a/src/arith_uint256.h
+++ b/src/arith_uint256.h
@@ -31,12 +31,16 @@ public:
base_uint()
{
+ static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
+
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
base_uint(const base_uint& b)
{
+ static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
+
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
@@ -50,6 +54,8 @@ public:
base_uint(uint64_t b)
{
+ static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
+
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
@@ -174,7 +180,7 @@ public:
{
// prefix operator
int i = 0;
- while (++pn[i] == 0 && i < WIDTH-1)
+ while (i < WIDTH && ++pn[i] == 0)
i++;
return *this;
}
@@ -191,7 +197,7 @@ public:
{
// prefix operator
int i = 0;
- while (--pn[i] == (uint32_t)-1 && i < WIDTH-1)
+ while (i < WIDTH && --pn[i] == (uint32_t)-1)
i++;
return *this;
}
diff --git a/src/bench/bench_bitcoin.cpp b/src/bench/bench_bitcoin.cpp
index 61a0b31aed..226861aa7f 100644
--- a/src/bench/bench_bitcoin.cpp
+++ b/src/bench/bench_bitcoin.cpp
@@ -7,10 +7,12 @@
#include "key.h"
#include "validation.h"
#include "util.h"
+#include "random.h"
int
main(int argc, char** argv)
{
+ RandomInit();
ECC_Start();
SetupEnvironment();
fPrintToDebugLog = false; // don't want to write to debug.log file
diff --git a/src/bench/coin_selection.cpp b/src/bench/coin_selection.cpp
index 42891f345b..942942c299 100644
--- a/src/bench/coin_selection.cpp
+++ b/src/bench/coin_selection.cpp
@@ -39,7 +39,7 @@ static void CoinSelection(benchmark::State& state)
while (state.KeepRunning()) {
// Empty wallet.
- BOOST_FOREACH (COutput output, vCoins)
+ for (COutput output : vCoins)
delete output.tx;
vCoins.clear();
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index 499e7ea926..6093f78fb1 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -299,7 +299,6 @@ static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& str
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
- CBitcoinAddress addr(scriptPubKey);
// Extract and validate FLAGS
bool bSegWit = false;
@@ -636,7 +635,7 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
// ... and merge in other signatures:
- BOOST_FOREACH(const CTransaction& txv, txVariants)
+ for (const CTransaction& txv : txVariants)
sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
UpdateTransaction(mergedTx, i, sigdata);
diff --git a/src/bloom.cpp b/src/bloom.cpp
index 7ed982c984..cc3baa9185 100644
--- a/src/bloom.cpp
+++ b/src/bloom.cpp
@@ -179,7 +179,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
if (fFound)
return true;
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
{
// Match if the filter contains an outpoint tx spends
if (contains(txin.prevout))
diff --git a/src/chain.cpp b/src/chain.cpp
index a5b369c4fc..8d4c4e7dea 100644
--- a/src/chain.cpp
+++ b/src/chain.cpp
@@ -126,7 +126,7 @@ arith_uint256 GetBlockProof(const CBlockIndex& block)
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
- // as it's too large for a arith_uint256. However, as 2**256 is at least as large
+ // as it's too large for an arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
diff --git a/src/checkqueue.h b/src/checkqueue.h
index 08017ff799..d7b7b836dc 100644
--- a/src/checkqueue.h
+++ b/src/checkqueue.h
@@ -120,7 +120,7 @@ private:
fOk = fAllOk;
}
// execute work
- BOOST_FOREACH (T& check, vChecks)
+ for (T& check : vChecks)
if (fOk)
fOk = check();
vChecks.clear();
@@ -150,7 +150,7 @@ public:
void Add(std::vector<T>& vChecks)
{
boost::unique_lock<boost::mutex> lock(mutex);
- BOOST_FOREACH (T& check, vChecks) {
+ for (T& check : vChecks) {
queue.push_back(T());
check.swap(queue.back());
}
diff --git a/src/coins.cpp b/src/coins.cpp
index b45fc76338..2dceaf09b6 100644
--- a/src/coins.cpp
+++ b/src/coins.cpp
@@ -91,9 +91,9 @@ void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) {
}
}
-void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
+bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
CCoinsMap::iterator it = FetchCoin(outpoint);
- if (it == cacheCoins.end()) return;
+ if (it == cacheCoins.end()) return false;
cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
if (moveout) {
*moveout = std::move(it->second.coin);
@@ -104,6 +104,7 @@ void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
it->second.flags |= CCoinsCacheEntry::DIRTY;
it->second.coin.Clear();
}
+ return true;
}
static const Coin coinEmpty;
diff --git a/src/coins.h b/src/coins.h
index dc3210b8ac..4774c9f6a6 100644
--- a/src/coins.h
+++ b/src/coins.h
@@ -224,8 +224,13 @@ public:
/**
* Return a reference to Coin in the cache, or a pruned one if not found. This is
- * more efficient than GetCoin. Modifications to other cache entries are
- * allowed while accessing the returned pointer.
+ * more efficient than GetCoin.
+ *
+ * Generally, do not hold the reference returned for more than a short scope.
+ * While the current implementation allows for modifications to the contents
+ * of the cache while holding the reference, this behavior should not be relied
+ * on! To be safe, best to not hold the returned reference through any other
+ * calls to this cache.
*/
const Coin& AccessCoin(const COutPoint &output) const;
@@ -240,7 +245,7 @@ public:
* If no unspent output exists for the passed outpoint, this call
* has no effect.
*/
- void SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
+ bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
/**
* Push the modifications applied to this cache to its base.
diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp
index bf68f8754b..0671cbc132 100644
--- a/src/consensus/tx_verify.cpp
+++ b/src/consensus/tx_verify.cpp
@@ -126,7 +126,9 @@ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& in
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
- const CTxOut &prevout = inputs.AccessCoin(tx.vin[i].prevout).out;
+ const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
+ assert(!coin.IsSpent());
+ const CTxOut &prevout = coin.out;
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
@@ -146,7 +148,9 @@ int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& i
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
- const CTxOut &prevout = inputs.AccessCoin(tx.vin[i].prevout).out;
+ const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
+ assert(!coin.IsSpent());
+ const CTxOut &prevout = coin.out;
nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
}
return nSigOps;
diff --git a/src/core_write.cpp b/src/core_write.cpp
index 178519daf1..553ef44874 100644
--- a/src/core_write.cpp
+++ b/src/core_write.cpp
@@ -139,7 +139,7 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey,
out.pushKV("type", GetTxnOutputType(type));
UniValue a(UniValue::VARR);
- BOOST_FOREACH(const CTxDestination& addr, addresses)
+ for (const CTxDestination& addr : addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.pushKV("addresses", a);
}
diff --git a/src/cuckoocache.h b/src/cuckoocache.h
index 5837549455..fd24d05ee7 100644
--- a/src/cuckoocache.h
+++ b/src/cuckoocache.h
@@ -176,7 +176,7 @@ private:
*/
mutable std::vector<bool> epoch_flags;
- /** epoch_heuristic_counter is used to determine when a epoch might be aged
+ /** epoch_heuristic_counter is used to determine when an epoch might be aged
* & an expensive scan should be done. epoch_heuristic_counter is
* decremented on insert and reset to the new number of inserts which would
* cause the epoch to reach epoch_size when it reaches zero.
@@ -184,7 +184,7 @@ private:
uint32_t epoch_heuristic_counter;
/** epoch_size is set to be the number of elements supposed to be in a
- * epoch. When the number of non-erased elements in a epoch
+ * epoch. When the number of non-erased elements in an epoch
* exceeds epoch_size, a new epoch should be started and all
* current entries demoted. epoch_size is set to be 45% of size because
* we want to keep load around 90%, and we support 3 epochs at once --
@@ -206,6 +206,37 @@ private:
/** compute_hashes is convenience for not having to write out this
* expression everywhere we use the hash values of an Element.
*
+ * We need to map the 32-bit input hash onto a hash bucket in a range [0, size) in a
+ * manner which preserves as much of the hash's uniformity as possible. Ideally
+ * this would be done by bitmasking but the size is usually not a power of two.
+ *
+ * The naive approach would be to use a mod -- which isn't perfectly uniform but so
+ * long as the hash is much larger than size it is not that bad. Unfortunately,
+ * mod/division is fairly slow on ordinary microprocessors (e.g. 90-ish cycles on
+ * haswell, ARM doesn't even have an instruction for it.); when the divisor is a
+ * constant the compiler will do clever tricks to turn it into a multiply+add+shift,
+ * but size is a run-time value so the compiler can't do that here.
+ *
+ * One option would be to implement the same trick the compiler uses and compute the
+ * constants for exact division based on the size, as described in "{N}-bit Unsigned
+ * Division via {N}-bit Multiply-Add" by Arch D. Robison in 2005. But that code is
+ * somewhat complicated and the result is still slower than other options:
+ *
+ * Instead we treat the 32-bit random number as a Q32 fixed-point number in the range
+ * [0,1) and simply multiply it by the size. Then we just shift the result down by
+ * 32-bits to get our bucket number. The results has non-uniformity the same as a
+ * mod, but it is much faster to compute. More about this technique can be found at
+ * http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
+ *
+ * The resulting non-uniformity is also more equally distributed which would be
+ * advantageous for something like linear probing, though it shouldn't matter
+ * one way or the other for a cuckoo table.
+ *
+ * The primary disadvantage of this approach is increased intermediate precision is
+ * required but for a 32-bit random number we only need the high 32 bits of a
+ * 32*32->64 multiply, which means the operation is reasonably fast even on a
+ * typical 32-bit processor.
+ *
* @param e the element whose hashes will be returned
* @returns std::array<uint32_t, 8> of deterministic hashes derived from e
*/
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index 3d2098c059..4ad8a2c1ac 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -108,7 +108,7 @@ CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bo
leveldb::Status result = leveldb::DestroyDB(path.string(), options);
dbwrapper_private::HandleError(result);
}
- TryCreateDirectory(path);
+ TryCreateDirectories(path);
LogPrintf("Opening LevelDB in %s\n", path.string());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
diff --git a/src/httprpc.cpp b/src/httprpc.cpp
index 9e0bcd7a00..053702f843 100644
--- a/src/httprpc.cpp
+++ b/src/httprpc.cpp
@@ -18,7 +18,7 @@
#include <stdio.h>
#include <boost/algorithm/string.hpp> // boost::trim
-#include <boost/foreach.hpp> //BOOST_FOREACH
+#include <boost/foreach.hpp>
/** WWW-Authenticate to present with 401 Unauthorized response */
static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
@@ -94,7 +94,7 @@ static bool multiUserAuthorized(std::string strUserPass)
if (gArgs.IsArgSet("-rpcauth")) {
//Search for multi-user login/pass "rpcauth" from config
- BOOST_FOREACH(std::string strRPCAuth, gArgs.GetArgs("-rpcauth"))
+ for (std::string strRPCAuth : gArgs.GetArgs("-rpcauth"))
{
std::vector<std::string> vFields;
boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
index 0d1cba3fd2..1557cf98f8 100644
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -21,13 +21,13 @@
#include <signal.h>
#include <future>
-#include <event2/event.h>
-#include <event2/http.h>
#include <event2/thread.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
+#include "support/events.h"
+
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef _XOPEN_SOURCE_EXTENDED
@@ -367,9 +367,6 @@ static void libevent_log_cb(int severity, const char *msg)
bool InitHTTPServer()
{
- struct evhttp* http = 0;
- struct event_base* base = 0;
-
if (!InitHTTPAllowList())
return false;
@@ -395,17 +392,13 @@ bool InitHTTPServer()
evthread_use_pthreads();
#endif
- base = event_base_new(); // XXX RAII
- if (!base) {
- LogPrintf("Couldn't create an event_base: exiting\n");
- return false;
- }
+ raii_event_base base_ctr = obtain_event_base();
/* Create a new evhttp object to handle requests. */
- http = evhttp_new(base); // XXX RAII
+ raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
+ struct evhttp* http = http_ctr.get();
if (!http) {
LogPrintf("couldn't create evhttp. Exiting.\n");
- event_base_free(base);
return false;
}
@@ -416,8 +409,6 @@ bool InitHTTPServer()
if (!HTTPBindAddresses(http)) {
LogPrintf("Unable to bind any endpoint for RPC server\n");
- evhttp_free(http);
- event_base_free(base);
return false;
}
@@ -426,8 +417,9 @@ bool InitHTTPServer()
LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
- eventBase = base;
- eventHTTP = http;
+ // tranfer ownership to eventBase/HTTP via .release()
+ eventBase = base_ctr.release();
+ eventHTTP = http_ctr.release();
return true;
}
diff --git a/src/httpserver.h b/src/httpserver.h
index 6be9950682..9df56e5fc5 100644
--- a/src/httpserver.h
+++ b/src/httpserver.h
@@ -86,7 +86,7 @@ public:
/**
* Get the request header specified by hdr, or an empty string.
- * Return an pair (isPresent,string).
+ * Return a pair (isPresent,string).
*/
std::pair<bool, std::string> GetHeader(const std::string& hdr);
@@ -125,7 +125,7 @@ public:
virtual ~HTTPClosure() {}
};
-/** Event class. This can be used either as an cross-thread trigger or as a timer.
+/** Event class. This can be used either as a cross-thread trigger or as a timer.
*/
class HTTPEvent
{
diff --git a/src/init.cpp b/src/init.cpp
index 56d0bd9b0e..686a31b0f4 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -613,7 +613,7 @@ void CleanupBlockRevFiles()
// keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
// start removing block files.
int nContigCounter = 0;
- BOOST_FOREACH(const PAIRTYPE(std::string, fs::path)& item, mapBlockFiles) {
+ for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
if (atoi(item.first) == nContigCounter) {
nContigCounter++;
continue;
@@ -666,7 +666,7 @@ void ThreadImport(std::vector<fs::path> vImportFiles)
}
// -loadblock=
- BOOST_FOREACH(const fs::path& path, vImportFiles) {
+ for (const fs::path& path : vImportFiles) {
FILE *file = fsbridge::fopen(path, "rb");
if (file) {
LogPrintf("Importing blocks file %s...\n", path.string());
@@ -844,8 +844,6 @@ bool AppInitBasicSetup()
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
-#endif
-#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
@@ -1030,14 +1028,7 @@ bool AppInitParameterInteraction()
if (nConnectTimeout <= 0)
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
- // Fee-per-kilobyte amount required for mempool acceptance and relay
- // If you are mining, be careful setting this:
- // if you set it to zero then
- // a transaction spammer can cheaply fill blocks using
- // 0-fee transactions. It should be set above the real
- // cost to you of processing a transaction.
- if (IsArgSet("-minrelaytxfee"))
- {
+ if (IsArgSet("-minrelaytxfee")) {
CAmount n = 0;
if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
@@ -1170,6 +1161,7 @@ bool AppInitSanityChecks()
// ********************************************************* Step 4: sanity checks
// Initialize elliptic curve code
+ RandomInit();
ECC_Start();
globalVerifyHandle.reset(new ECCVerifyHandle());
@@ -1260,7 +1252,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// sanitize comments per BIP-0014, format user agent and check total size
std::vector<std::string> uacomments;
if (gArgs.IsArgSet("-uacomment")) {
- BOOST_FOREACH(std::string cmt, gArgs.GetArgs("-uacomment"))
+ for (std::string cmt : gArgs.GetArgs("-uacomment"))
{
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
@@ -1275,7 +1267,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
if (gArgs.IsArgSet("-onlynet")) {
std::set<enum Network> nets;
- BOOST_FOREACH(const std::string& snet, gArgs.GetArgs("-onlynet")) {
+ for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
@@ -1289,7 +1281,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
if (gArgs.IsArgSet("-whitelist")) {
- BOOST_FOREACH(const std::string& net, gArgs.GetArgs("-whitelist")) {
+ for (const std::string& net : gArgs.GetArgs("-whitelist")) {
CSubNet subnet;
LookupSubNet(net.c_str(), subnet);
if (!subnet.IsValid())
@@ -1351,7 +1343,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
if (fListen) {
bool fBound = false;
if (gArgs.IsArgSet("-bind")) {
- BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-bind")) {
+ for (const std::string& strBind : gArgs.GetArgs("-bind")) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(ResolveErrMsg("bind", strBind));
@@ -1359,7 +1351,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
}
if (gArgs.IsArgSet("-whitebind")) {
- BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-whitebind")) {
+ for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, 0, false))
return InitError(ResolveErrMsg("whitebind", strBind));
@@ -1379,7 +1371,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
if (gArgs.IsArgSet("-externalip")) {
- BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-externalip")) {
+ for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
CService addrLocal;
if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
AddLocal(addrLocal, LOCAL_MANUAL);
@@ -1407,8 +1399,6 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fReindex = GetBoolArg("-reindex", false);
bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
- fs::create_directories(GetDataDir() / "blocks");
-
// cache size calculations
int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
@@ -1618,7 +1608,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
std::vector<fs::path> vImportFiles;
if (gArgs.IsArgSet("-loadblock"))
{
- BOOST_FOREACH(const std::string& strFile, gArgs.GetArgs("-loadblock"))
+ for (const std::string& strFile : gArgs.GetArgs("-loadblock"))
vImportFiles.push_back(strFile);
}
diff --git a/src/leveldb/db/version_set.h b/src/leveldb/db/version_set.h
index c4e7ac360b..7935a965a7 100644
--- a/src/leveldb/db/version_set.h
+++ b/src/leveldb/db/version_set.h
@@ -376,7 +376,7 @@ class Compaction {
// Each compaction reads inputs from "level_" and "level_+1"
std::vector<FileMetaData*> inputs_[2]; // The two sets of inputs
- // State used to check for number of of overlapping grandparent files
+ // State used to check for number of overlapping grandparent files
// (parent == level_ + 1, grandparent == level_ + 2)
std::vector<FileMetaData*> grandparents_;
size_t grandparent_index_; // Index in grandparent_starts_
diff --git a/src/miner.cpp b/src/miner.cpp
index 28b6f23d56..79016bfd3e 100644
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -242,7 +242,7 @@ bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
- BOOST_FOREACH (const CTxMemPool::txiter it, package) {
+ for (const CTxMemPool::txiter it : package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && it->GetTx().HasWitness())
@@ -284,11 +284,11 @@ int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& already
indexed_modified_transaction_set &mapModifiedTx)
{
int nDescendantsUpdated = 0;
- BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
+ for (const CTxMemPool::txiter it : alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
- BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
+ for (CTxMemPool::txiter desc : descendants) {
if (alreadyAdded.count(desc))
continue;
++nDescendantsUpdated;
diff --git a/src/net.cpp b/src/net.cpp
index cd9e0d05d9..43bd0eb0d5 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -295,7 +295,7 @@ bool IsReachable(const CNetAddr& addr)
CNode* CConnman::FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes)
+ for (CNode* pnode : vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
@@ -304,7 +304,7 @@ CNode* CConnman::FindNode(const CNetAddr& ip)
CNode* CConnman::FindNode(const CSubNet& subNet)
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes)
+ for (CNode* pnode : vNodes)
if (subNet.Match((CNetAddr)pnode->addr))
return (pnode);
return NULL;
@@ -313,7 +313,7 @@ CNode* CConnman::FindNode(const CSubNet& subNet)
CNode* CConnman::FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes) {
+ for (CNode* pnode : vNodes) {
if (pnode->GetAddrName() == addrName) {
return (pnode);
}
@@ -324,7 +324,7 @@ CNode* CConnman::FindNode(const std::string& addrName)
CNode* CConnman::FindNode(const CService& addr)
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes)
+ for (CNode* pnode : vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
return NULL;
@@ -333,7 +333,7 @@ CNode* CConnman::FindNode(const CService& addr)
bool CConnman::CheckIncomingNonce(uint64_t nonce)
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes) {
+ for (CNode* pnode : vNodes) {
if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
return false;
}
@@ -524,7 +524,7 @@ void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t ba
clientInterface->BannedListChanged();
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes) {
+ for (CNode* pnode : vNodes) {
if (subNet.Match((CNetAddr)pnode->addr))
pnode->fDisconnect = true;
}
@@ -602,7 +602,7 @@ void CConnman::SetBannedSetDirty(bool dirty)
bool CConnman::IsWhitelistedRange(const CNetAddr &addr) {
LOCK(cs_vWhitelistedRange);
- BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
+ for (const CSubNet& subnet : vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
@@ -955,7 +955,7 @@ bool CConnman::AttemptToEvictConnection()
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode *node, vNodes) {
+ for (CNode *node : vNodes) {
if (node->fWhitelisted)
continue;
if (!node->fInbound)
@@ -1015,7 +1015,7 @@ bool CConnman::AttemptToEvictConnection()
unsigned int nMostConnections = 0;
int64_t nMostConnectionsTime = 0;
std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
- BOOST_FOREACH(const NodeEvictionCandidate &node, vEvictionCandidates) {
+ for (const NodeEvictionCandidate &node : vEvictionCandidates) {
mapNetGroupNodes[node.nKeyedNetGroup].push_back(node);
int64_t grouptime = mapNetGroupNodes[node.nKeyedNetGroup][0].nTimeConnected;
size_t groupsize = mapNetGroupNodes[node.nKeyedNetGroup].size();
@@ -1059,7 +1059,7 @@ void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes)
+ for (CNode* pnode : vNodes)
if (pnode->fInbound)
nInbound++;
}
@@ -1135,7 +1135,7 @@ void CConnman::ThreadSocketHandler()
LOCK(cs_vNodes);
// Disconnect unused nodes
std::vector<CNode*> vNodesCopy = vNodes;
- BOOST_FOREACH(CNode* pnode, vNodesCopy)
+ for (CNode* pnode : vNodesCopy)
{
if (pnode->fDisconnect)
{
@@ -1157,7 +1157,7 @@ void CConnman::ThreadSocketHandler()
{
// Delete disconnected nodes
std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
- BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
+ for (CNode* pnode : vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
@@ -1205,7 +1205,7 @@ void CConnman::ThreadSocketHandler()
SOCKET hSocketMax = 0;
bool have_fds = false;
- BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
+ for (const ListenSocket& hListenSocket : vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = std::max(hSocketMax, hListenSocket.socket);
have_fds = true;
@@ -1213,7 +1213,7 @@ void CConnman::ThreadSocketHandler()
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes)
+ for (CNode* pnode : vNodes)
{
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
@@ -1274,7 +1274,7 @@ void CConnman::ThreadSocketHandler()
//
// Accept new connections
//
- BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
+ for (const ListenSocket& hListenSocket : vhListenSocket)
{
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
{
@@ -1289,10 +1289,10 @@ void CConnman::ThreadSocketHandler()
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
- BOOST_FOREACH(CNode* pnode, vNodesCopy)
+ for (CNode* pnode : vNodesCopy)
pnode->AddRef();
}
- BOOST_FOREACH(CNode* pnode, vNodesCopy)
+ for (CNode* pnode : vNodesCopy)
{
if (interruptNet)
return;
@@ -1413,7 +1413,7 @@ void CConnman::ThreadSocketHandler()
}
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodesCopy)
+ for (CNode* pnode : vNodesCopy)
pnode->Release();
}
}
@@ -1594,7 +1594,7 @@ void CConnman::ThreadDNSAddressSeed()
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
- BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
+ for (const CDNSSeedData &seed : vSeeds) {
if (interruptNet) {
return;
}
@@ -1611,7 +1611,7 @@ void CConnman::ThreadDNSAddressSeed()
}
if (LookupHost(host.c_str(), vIPs, 0, true))
{
- BOOST_FOREACH(const CNetAddr& ip, vIPs)
+ for (const CNetAddr& ip : vIPs)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
@@ -1681,7 +1681,7 @@ void CConnman::ThreadOpenConnections()
for (int64_t nLoop = 0;; nLoop++)
{
ProcessOneShot();
- BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-connect"))
+ for (const std::string& strAddr : gArgs.GetArgs("-connect"))
{
CAddress addr(CService(), NODE_NONE);
OpenNetworkConnection(addr, false, NULL, strAddr.c_str());
@@ -1736,7 +1736,7 @@ void CConnman::ThreadOpenConnections()
std::set<std::vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodes) {
+ for (CNode* pnode : vNodes) {
if (!pnode->fInbound && !pnode->fAddnode) {
// Count the peers that have all relevant services
@@ -1853,7 +1853,7 @@ std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
{
LOCK(cs_vAddedNodes);
ret.reserve(vAddedNodes.size());
- BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
+ for (const std::string& strAddNode : vAddedNodes)
lAddresses.push_back(strAddNode);
}
@@ -1874,7 +1874,7 @@ std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
}
}
- BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
+ for (const std::string& strAddNode : lAddresses) {
CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
if (service.IsValid()) {
// strAddNode is an IP:port
@@ -1983,14 +1983,14 @@ void CConnman::ThreadMessageHandler()
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
- BOOST_FOREACH(CNode* pnode, vNodesCopy) {
+ for (CNode* pnode : vNodesCopy) {
pnode->AddRef();
}
}
bool fMoreWork = false;
- BOOST_FOREACH(CNode* pnode, vNodesCopy)
+ for (CNode* pnode : vNodesCopy)
{
if (pnode->fDisconnect)
continue;
@@ -2012,7 +2012,7 @@ void CConnman::ThreadMessageHandler()
{
LOCK(cs_vNodes);
- BOOST_FOREACH(CNode* pnode, vNodesCopy)
+ for (CNode* pnode : vNodesCopy)
pnode->Release();
}
@@ -2140,7 +2140,7 @@ void Discover(boost::thread_group& threadGroup)
std::vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr, 0, true))
{
- BOOST_FOREACH (const CNetAddr &addr, vaddr)
+ for (const CNetAddr &addr : vaddr)
{
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
@@ -2187,7 +2187,7 @@ void CConnman::SetNetworkActive(bool active)
LOCK(cs_vNodes);
// Close sockets to all nodes
- BOOST_FOREACH(CNode* pnode, vNodes) {
+ for (CNode* pnode : vNodes) {
pnode->CloseSocketDisconnect();
}
} else {
@@ -2389,18 +2389,18 @@ void CConnman::Stop()
}
// Close sockets
- BOOST_FOREACH(CNode* pnode, vNodes)
+ for (CNode* pnode : vNodes)
pnode->CloseSocketDisconnect();
- BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
+ for (ListenSocket& hListenSocket : vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
- BOOST_FOREACH(CNode *pnode, vNodes) {
+ for (CNode *pnode : vNodes) {
DeleteNode(pnode);
}
- BOOST_FOREACH(CNode *pnode, vNodesDisconnected) {
+ for (CNode *pnode : vNodesDisconnected) {
DeleteNode(pnode);
}
vNodes.clear();
@@ -2712,7 +2712,7 @@ CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn
fPauseSend = false;
nProcessQueueSize = 0;
- BOOST_FOREACH(const std::string &msg, getAllNetMessageTypes())
+ for (const std::string &msg : getAllNetMessageTypes())
mapRecvBytesPerMsgCmd[msg] = 0;
mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 3d38350d9b..91681265b1 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -288,7 +288,7 @@ void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
fUpdateConnectionTime = true;
}
- BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
+ for (const QueuedBlock& entry : state->vBlocksInFlight) {
mapBlocksInFlight.erase(entry.hash);
}
EraseOrphansFor(nodeid);
@@ -342,7 +342,9 @@ bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex*
// Short-circuit most stuff in case its from the same node
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
- *pit = &itInFlight->second.second;
+ if (pit) {
+ *pit = &itInFlight->second.second;
+ }
return false;
}
@@ -523,7 +525,7 @@ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<con
// are not yet downloaded and not in flight to vBlocks. In the mean time, update
// pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
// already part of our chain (and therefore don't need it even if pruned).
- BOOST_FOREACH(const CBlockIndex* pindex, vToFetch) {
+ for (const CBlockIndex* pindex : vToFetch) {
if (!pindex->IsValid(BLOCK_VALID_TREE)) {
// We consider the chain that this peer is on invalid.
return;
@@ -567,7 +569,7 @@ bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
- BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
+ for (const QueuedBlock& queue : state->vBlocksInFlight) {
if (queue.pindex)
stats.vHeightInFlight.push_back(queue.pindex->nHeight);
}
@@ -628,7 +630,7 @@ bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRE
auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
assert(ret.second);
- BOOST_FOREACH(const CTxIn& txin, tx->vin) {
+ for (const CTxIn& txin : tx->vin) {
mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
}
@@ -644,7 +646,7 @@ int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return 0;
- BOOST_FOREACH(const CTxIn& txin, it->second.tx->vin)
+ for (const CTxIn& txin : it->second.tx->vin)
{
auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
if (itPrev == mapOrphanTransactionsByPrev.end())
@@ -769,7 +771,7 @@ void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pb
// Erase orphan transactions include or precluded by this block
if (vOrphanErase.size()) {
int nErased = 0;
- BOOST_FOREACH(uint256 &orphanHash, vOrphanErase) {
+ for (uint256 &orphanHash : vOrphanErase) {
nErased += EraseOrphanTx(orphanHash);
}
LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
@@ -1079,7 +1081,7 @@ void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParam
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
- BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
+ for (PairType& pair : merkleBlock.vMatchedTxn)
connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
}
// else
@@ -1474,7 +1476,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
std::vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
- BOOST_FOREACH(CAddress& addr, vAddr)
+ for (CAddress& addr : vAddr)
{
if (interruptMsgProc)
return true;
@@ -1884,13 +1886,13 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
}
}
- BOOST_FOREACH(uint256 hash, vEraseQueue)
+ for (uint256 hash : vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
- BOOST_FOREACH(const CTxIn& txin, tx.vin) {
+ for (const CTxIn& txin : tx.vin) {
if (recentRejects->contains(txin.prevout.hash)) {
fRejectedParents = true;
break;
@@ -1898,7 +1900,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
}
if (!fRejectedParents) {
uint32_t nFetchFlags = GetFetchFlags(pfrom);
- BOOST_FOREACH(const CTxIn& txin, tx.vin) {
+ for (const CTxIn& txin : tx.vin) {
CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
pfrom->AddInventoryKnown(_inv);
if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
@@ -2434,7 +2436,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
pfrom->vAddrToSend.clear();
std::vector<CAddress> vAddr = connman.GetAddresses();
FastRandomContext insecure_rand;
- BOOST_FOREACH(const CAddress &addr, vAddr)
+ for (const CAddress &addr : vAddr)
pfrom->PushAddress(addr, insecure_rand);
}
@@ -2628,7 +2630,7 @@ static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman& connman)
AssertLockHeld(cs_main);
CNodeState &state = *State(pnode->GetId());
- BOOST_FOREACH(const CBlockReject& reject, state.rejects) {
+ for (const CBlockReject& reject : state.rejects) {
connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
}
state.rejects.clear();
@@ -2852,7 +2854,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
std::vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
- BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
+ for (const CAddress& addr : pto->vAddrToSend)
{
if (!pto->addrKnown.contains(addr.GetKey()))
{
@@ -2931,7 +2933,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
// Try to find first header that our peer doesn't have, and
// then send all headers past that one. If we come across any
// headers that aren't on chainActive, give up.
- BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) {
+ for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
assert(mi != mapBlockIndex.end());
const CBlockIndex *pindex = mi->second;
@@ -3057,7 +3059,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
// Add blocks
- BOOST_FOREACH(const uint256& hash, pto->vInventoryBlockToSend) {
+ for (const uint256& hash : pto->vInventoryBlockToSend) {
vInv.push_back(CInv(MSG_BLOCK, hash));
if (vInv.size() == MAX_INV_SZ) {
connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
@@ -3248,7 +3250,7 @@ bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interr
std::vector<const CBlockIndex*> vToDownload;
NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
- BOOST_FOREACH(const CBlockIndex *pindex, vToDownload) {
+ for (const CBlockIndex *pindex : vToDownload) {
uint32_t nFetchFlags = GetFetchFlags(pto);
vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
diff --git a/src/policy/fees.cpp b/src/policy/fees.cpp
index 3c3a2fb651..771491770e 100644
--- a/src/policy/fees.cpp
+++ b/src/policy/fees.cpp
@@ -16,6 +16,26 @@
static constexpr double INF_FEERATE = 1e99;
+std::string StringForFeeReason(FeeReason reason) {
+ static const std::map<FeeReason, std::string> fee_reason_strings = {
+ {FeeReason::NONE, "None"},
+ {FeeReason::HALF_ESTIMATE, "Half Target 60% Threshold"},
+ {FeeReason::FULL_ESTIMATE, "Target 85% Threshold"},
+ {FeeReason::DOUBLE_ESTIMATE, "Double Target 95% Threshold"},
+ {FeeReason::CONSERVATIVE, "Conservative Double Target longer horizon"},
+ {FeeReason::MEMPOOL_MIN, "Mempool Min Fee"},
+ {FeeReason::PAYTXFEE, "PayTxFee set"},
+ {FeeReason::FALLBACK, "Fallback fee"},
+ {FeeReason::REQUIRED, "Minimum Required Fee"},
+ {FeeReason::MAXTXFEE, "MaxTxFee limit"}
+ };
+ auto reason_string = fee_reason_strings.find(reason);
+
+ if (reason_string == fee_reason_strings.end()) return "Unknown";
+
+ return reason_string->second;
+}
+
/**
* We will instantiate an instance of this class to track transactions that were
* included in a block. We will lump transactions into a bucket according to their
@@ -698,31 +718,36 @@ unsigned int CBlockPolicyEstimator::MaxUsableEstimate() const
* time horizon which tracks confirmations up to the desired target. If
* checkShorterHorizon is requested, also allow short time horizon estimates
* for a lower target to reduce the given answer */
-double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon) const
+double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const
{
double estimate = -1;
if (confTarget >= 1 && confTarget <= longStats->GetMaxConfirms()) {
// Find estimate from shortest time horizon possible
if (confTarget <= shortStats->GetMaxConfirms()) { // short horizon
- estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight);
+ estimate = shortStats->EstimateMedianVal(confTarget, SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, result);
}
else if (confTarget <= feeStats->GetMaxConfirms()) { // medium horizon
- estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight);
+ estimate = feeStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
}
else { // long horizon
- estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight);
+ estimate = longStats->EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, result);
}
if (checkShorterHorizon) {
+ EstimationResult tempResult;
// If a lower confTarget from a more recent horizon returns a lower answer use it.
if (confTarget > feeStats->GetMaxConfirms()) {
- double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight);
- if (medMax > 0 && (estimate == -1 || medMax < estimate))
+ double medMax = feeStats->EstimateMedianVal(feeStats->GetMaxConfirms(), SUFFICIENT_FEETXS, successThreshold, true, nBestSeenHeight, &tempResult);
+ if (medMax > 0 && (estimate == -1 || medMax < estimate)) {
estimate = medMax;
+ if (result) *result = tempResult;
+ }
}
if (confTarget > shortStats->GetMaxConfirms()) {
- double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight);
- if (shortMax > 0 && (estimate == -1 || shortMax < estimate))
+ double shortMax = shortStats->EstimateMedianVal(shortStats->GetMaxConfirms(), SUFFICIENT_TXS_SHORT, successThreshold, true, nBestSeenHeight, &tempResult);
+ if (shortMax > 0 && (estimate == -1 || shortMax < estimate)) {
estimate = shortMax;
+ if (result) *result = tempResult;
+ }
}
}
}
@@ -732,16 +757,18 @@ double CBlockPolicyEstimator::estimateCombinedFee(unsigned int confTarget, doubl
/** Ensure that for a conservative estimate, the DOUBLE_SUCCESS_PCT is also met
* at 2 * target for any longer time horizons.
*/
-double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget) const
+double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const
{
double estimate = -1;
+ EstimationResult tempResult;
if (doubleTarget <= shortStats->GetMaxConfirms()) {
- estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight);
+ estimate = feeStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, result);
}
if (doubleTarget <= feeStats->GetMaxConfirms()) {
- double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight);
+ double longEstimate = longStats->EstimateMedianVal(doubleTarget, SUFFICIENT_FEETXS, DOUBLE_SUCCESS_PCT, true, nBestSeenHeight, &tempResult);
if (longEstimate > estimate) {
estimate = longEstimate;
+ if (result) *result = tempResult;
}
}
return estimate;
@@ -754,12 +781,15 @@ double CBlockPolicyEstimator::estimateConservativeFee(unsigned int doubleTarget)
* estimates, however, required the 95% threshold at 2 * target be met for any
* longer time horizons also.
*/
-CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool& pool, bool conservative) const
+CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, FeeCalculation *feeCalc, const CTxMemPool& pool, bool conservative) const
{
- if (answerFoundAtTarget)
- *answerFoundAtTarget = confTarget;
+ if (feeCalc) {
+ feeCalc->desiredTarget = confTarget;
+ feeCalc->returnedTarget = confTarget;
+ }
double median = -1;
+ EstimationResult tempResult;
{
LOCK(cs_feeEstimator);
@@ -780,7 +810,6 @@ CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, int *answerFoun
}
assert(confTarget > 0); //estimateCombinedFee and estimateConservativeFee take unsigned ints
-
/** true is passed to estimateCombined fee for target/2 and target so
* that we check the max confirms for shorter time horizons as well.
* This is necessary to preserve monotonically increasing estimates.
@@ -791,32 +820,49 @@ CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, int *answerFoun
* the purpose of conservative estimates is not to let short term
* fluctuations lower our estimates by too much.
*/
- double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true);
- double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true);
- double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative);
+ double halfEst = estimateCombinedFee(confTarget/2, HALF_SUCCESS_PCT, true, &tempResult);
+ if (feeCalc) {
+ feeCalc->est = tempResult;
+ feeCalc->reason = FeeReason::HALF_ESTIMATE;
+ }
median = halfEst;
+ double actualEst = estimateCombinedFee(confTarget, SUCCESS_PCT, true, &tempResult);
if (actualEst > median) {
median = actualEst;
+ if (feeCalc) {
+ feeCalc->est = tempResult;
+ feeCalc->reason = FeeReason::FULL_ESTIMATE;
+ }
}
+ double doubleEst = estimateCombinedFee(2 * confTarget, DOUBLE_SUCCESS_PCT, !conservative, &tempResult);
if (doubleEst > median) {
median = doubleEst;
+ if (feeCalc) {
+ feeCalc->est = tempResult;
+ feeCalc->reason = FeeReason::DOUBLE_ESTIMATE;
+ }
}
if (conservative || median == -1) {
- double consEst = estimateConservativeFee(2 * confTarget);
+ double consEst = estimateConservativeFee(2 * confTarget, &tempResult);
if (consEst > median) {
median = consEst;
+ if (feeCalc) {
+ feeCalc->est = tempResult;
+ feeCalc->reason = FeeReason::CONSERVATIVE;
+ }
}
}
} // Must unlock cs_feeEstimator before taking mempool locks
- if (answerFoundAtTarget)
- *answerFoundAtTarget = confTarget;
+ if (feeCalc) feeCalc->returnedTarget = confTarget;
// If mempool is limiting txs , return at least the min feerate from the mempool
CAmount minPoolFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
- if (minPoolFee > 0 && minPoolFee > median)
+ if (minPoolFee > 0 && minPoolFee > median) {
+ if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
return CFeeRate(minPoolFee);
+ }
if (median < 0)
return CFeeRate(0);
diff --git a/src/policy/fees.h b/src/policy/fees.h
index e99fec2c39..2029ce3744 100644
--- a/src/policy/fees.h
+++ b/src/policy/fees.h
@@ -48,7 +48,7 @@ class TxConfirmStats;
* in each bucket and the total amount of feerate paid in each bucket. Then we
* calculate how many blocks Y it took each transaction to be mined. We convert
* from a number of blocks to a number of periods Y' each encompassing "scale"
- * blocks. This is is tracked in 3 different data sets each up to a maximum
+ * blocks. This is tracked in 3 different data sets each up to a maximum
* number of periods. Within each data set we have an array of counters in each
* feerate bucket and we increment all the counters from Y' up to max periods
* representing that a tx was successfully confirmed in less than or equal to
@@ -74,6 +74,22 @@ enum FeeEstimateHorizon {
LONG_HALFLIFE = 2
};
+/* Enumeration of reason for returned fee estimate */
+enum class FeeReason {
+ NONE,
+ HALF_ESTIMATE,
+ FULL_ESTIMATE,
+ DOUBLE_ESTIMATE,
+ CONSERVATIVE,
+ MEMPOOL_MIN,
+ PAYTXFEE,
+ FALLBACK,
+ REQUIRED,
+ MAXTXFEE,
+};
+
+std::string StringForFeeReason(FeeReason reason);
+
/* Used to return detailed information about a feerate bucket */
struct EstimatorBucket
{
@@ -90,8 +106,16 @@ struct EstimationResult
{
EstimatorBucket pass;
EstimatorBucket fail;
- double decay;
- unsigned int scale;
+ double decay = 0;
+ unsigned int scale = 0;
+};
+
+struct FeeCalculation
+{
+ EstimationResult est;
+ FeeReason reason = FeeReason::NONE;
+ int desiredTarget = 0;
+ int returnedTarget = 0;
};
/**
@@ -173,7 +197,7 @@ public:
* the closest target where one can be given. 'conservative' estimates are
* valid over longer time horizons also.
*/
- CFeeRate estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool& pool, bool conservative = true) const;
+ CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, const CTxMemPool& pool, bool conservative = true) const;
/** Return a specific fee estimate calculation with a given success
* threshold and time horizon, and optionally return detailed data about
@@ -223,9 +247,9 @@ private:
bool processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry* entry);
/** Helper for estimateSmartFee */
- double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon) const;
+ double estimateCombinedFee(unsigned int confTarget, double successThreshold, bool checkShorterHorizon, EstimationResult *result) const;
/** Helper for estimateSmartFee */
- double estimateConservativeFee(unsigned int doubleTarget) const;
+ double estimateConservativeFee(unsigned int doubleTarget, EstimationResult *result) const;
/** Number of blocks of data recorded while fee estimates have been running */
unsigned int BlockSpan() const;
/** Number of blocks of recorded fee estimate data represented in saved data file */
diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp
index 14d58e7442..5f68c09a86 100644
--- a/src/policy/policy.cpp
+++ b/src/policy/policy.cpp
@@ -111,7 +111,7 @@ bool IsStandardTx(const CTransaction& tx, std::string& reason, const bool witnes
return false;
}
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
{
// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
// keys (remember the 520 byte limit on redeemScript size). That works
@@ -132,7 +132,7 @@ bool IsStandardTx(const CTransaction& tx, std::string& reason, const bool witnes
unsigned int nDataOut = 0;
txnouttype whichType;
- BOOST_FOREACH(const CTxOut& txout, tx.vout) {
+ for (const CTxOut& txout : tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType, witnessEnabled)) {
reason = "scriptpubkey";
return false;
diff --git a/src/policy/rbf.cpp b/src/policy/rbf.cpp
index d9b47e71bb..755ef83c9a 100644
--- a/src/policy/rbf.cpp
+++ b/src/policy/rbf.cpp
@@ -6,7 +6,7 @@
bool SignalsOptInRBF(const CTransaction &tx)
{
- BOOST_FOREACH(const CTxIn &txin, tx.vin) {
+ for (const CTxIn &txin : tx.vin) {
if (txin.nSequence < std::numeric_limits<unsigned int>::max()-1) {
return true;
}
@@ -38,7 +38,7 @@ RBFTransactionState IsRBFOptIn(const CTransaction &tx, CTxMemPool &pool)
CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
pool.CalculateMemPoolAncestors(entry, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
- BOOST_FOREACH(CTxMemPool::txiter it, setAncestors) {
+ for (CTxMemPool::txiter it : setAncestors) {
if (SignalsOptInRBF(it->GetTx())) {
return RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125;
}
diff --git a/src/qt/addressbookpage.cpp b/src/qt/addressbookpage.cpp
index b1253a9f17..cebac46b95 100644
--- a/src/qt/addressbookpage.cpp
+++ b/src/qt/addressbookpage.cpp
@@ -254,7 +254,7 @@ void AddressBookPage::done(int retval)
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
- Q_FOREACH (const QModelIndex& index, indexes) {
+ for (const QModelIndex& index : indexes) {
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp
index 93120de1ea..d3ad24da01 100644
--- a/src/qt/addresstablemodel.cpp
+++ b/src/qt/addresstablemodel.cpp
@@ -81,7 +81,7 @@ public:
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
- BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook)
+ for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp
index 5c26baef9e..429c18cba8 100644
--- a/src/qt/bitcoingui.cpp
+++ b/src/qt/bitcoingui.cpp
@@ -1006,7 +1006,7 @@ void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
- Q_FOREACH(const QUrl &uri, event->mimeData()->urls())
+ for (const QUrl &uri : event->mimeData()->urls())
{
Q_EMIT receivedURI(uri.toString());
}
@@ -1202,7 +1202,7 @@ UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *pl
QList<BitcoinUnits::Unit> units = BitcoinUnits::availableUnits();
int max_width = 0;
const QFontMetrics fm(font());
- Q_FOREACH (const BitcoinUnits::Unit unit, units)
+ for (const BitcoinUnits::Unit unit : units)
{
max_width = qMax(max_width, fm.width(BitcoinUnits::name(unit)));
}
@@ -1221,7 +1221,7 @@ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu(this);
- Q_FOREACH(BitcoinUnits::Unit u, BitcoinUnits::availableUnits())
+ for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
QAction *menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp
index de00eacdb9..3dfb51ccfa 100644
--- a/src/qt/clientmodel.cpp
+++ b/src/qt/clientmodel.cpp
@@ -303,7 +303,7 @@ static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CB
}
// if we are in-sync, update the UI regardless of last update time
if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) {
- //pass a async signal to the UI thread
+ //pass an async signal to the UI thread
QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
Q_ARG(int, pIndex->nHeight),
Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())),
diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp
index 1f14abf2c9..af9a888d94 100644
--- a/src/qt/coincontroldialog.cpp
+++ b/src/qt/coincontroldialog.cpp
@@ -424,7 +424,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
- Q_FOREACH(const CAmount &amount, CoinControlDialog::payAmounts)
+ for (const CAmount &amount : CoinControlDialog::payAmounts)
{
nPayAmount += amount;
@@ -450,7 +450,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
- BOOST_FOREACH(const COutput& out, vOutputs) {
+ for (const COutput& out : vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
@@ -499,7 +499,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
// there is some fudging in these numbers related to the actual virtual transaction size calculation that will keep this estimate from being exact.
// usually, the result will be an overestimate within a couple of satoshis so that the confirmation dialog ends up displaying a slightly smaller fee.
- // also, the witness stack size value value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit.
+ // also, the witness stack size value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit.
nBytes += 2; // account for the serialized marker and flag bytes
nBytes += nQuantity; // account for the witness byte that holds the number of stack items for each input.
}
@@ -510,7 +510,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
nBytes -= 34;
// Fee
- nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, ::mempool, ::feeEstimator);
+ nPayFee = CWallet::GetMinimumFee(nBytes, coinControl->nConfirmTarget, ::mempool, ::feeEstimator);
if (nPayAmount > 0)
{
@@ -524,13 +524,10 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0));
if (IsDust(txout, ::dustRelayFee))
{
- if (CoinControlDialog::fSubtractFeeFromAmount) // dust-change will be raised until no dust
- nChange = GetDustThreshold(txout, ::dustRelayFee);
- else
- {
- nPayFee += nChange;
- nChange = 0;
- }
+ nPayFee += nChange;
+ nChange = 0;
+ if (CoinControlDialog::fSubtractFeeFromAmount)
+ nBytes -= 34; // we didn't detect lack of change above
}
}
@@ -588,7 +585,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
if (payTxFee.GetFeePerK() > 0)
dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), payTxFee.GetFeePerK()) / 1000;
else {
- dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), ::feeEstimator.estimateSmartFee(nTxConfirmTarget, NULL, ::mempool).GetFeePerK()) / 1000;
+ dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), ::feeEstimator.estimateSmartFee(coinControl->nConfirmTarget, NULL, ::mempool).GetFeePerK()) / 1000;
}
QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary);
@@ -626,7 +623,7 @@ void CoinControlDialog::updateView()
std::map<QString, std::vector<COutput> > mapCoins;
model->listCoins(mapCoins);
- BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) {
+ for (const std::pair<QString, std::vector<COutput>>& coins : mapCoins) {
CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
@@ -651,7 +648,7 @@ void CoinControlDialog::updateView()
CAmount nSum = 0;
int nChildren = 0;
- BOOST_FOREACH(const COutput& out, coins.second) {
+ for (const COutput& out : coins.second) {
nSum += out.tx->tx->vout[out.i].nValue;
nChildren++;
diff --git a/src/qt/forms/optionsdialog.ui b/src/qt/forms/optionsdialog.ui
index 0f1b3f4a73..14078b9ee8 100644
--- a/src/qt/forms/optionsdialog.ui
+++ b/src/qt/forms/optionsdialog.ui
@@ -315,7 +315,7 @@
<bool>false</bool>
</property>
<property name="toolTip">
- <string>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</string>
+ <string>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</string>
</property>
<property name="text">
<string/>
@@ -338,7 +338,7 @@
<bool>false</bool>
</property>
<property name="toolTip">
- <string>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</string>
+ <string>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</string>
</property>
<property name="text">
<string/>
@@ -361,7 +361,7 @@
<bool>false</bool>
</property>
<property name="toolTip">
- <string>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</string>
+ <string>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</string>
</property>
<property name="text">
<string/>
diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp
index 2460a59109..1e0d472b6a 100644
--- a/src/qt/intro.cpp
+++ b/src/qt/intro.cpp
@@ -214,7 +214,7 @@ bool Intro::pickDataDirectory()
}
dataDir = intro.getDataDirectory();
try {
- TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
+ TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(0, tr(PACKAGE_NAME),
diff --git a/src/qt/modaloverlay.cpp b/src/qt/modaloverlay.cpp
index 4779ffa43f..a83f285034 100644
--- a/src/qt/modaloverlay.cpp
+++ b/src/qt/modaloverlay.cpp
@@ -126,7 +126,7 @@ void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVeri
return;
// estimate the number of headers left based on nPowTargetSpacing
- // and check if the gui is not aware of the the best header (happens rarely)
+ // and check if the gui is not aware of the best header (happens rarely)
int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) / Params().GetConsensus().nPowTargetSpacing;
bool hasBestHeader = bestHeaderHeight >= count;
diff --git a/src/qt/optionsdialog.cpp b/src/qt/optionsdialog.cpp
index 9cdd02e1f0..b80b6541dd 100644
--- a/src/qt/optionsdialog.cpp
+++ b/src/qt/optionsdialog.cpp
@@ -82,7 +82,7 @@ OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) :
ui->lang->setToolTip(ui->lang->toolTip().arg(tr(PACKAGE_NAME)));
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
- Q_FOREACH(const QString &langStr, translations.entryList())
+ for (const QString &langStr : translations.entryList())
{
QLocale locale(langStr);
diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp
index c31a7a478d..132ee32748 100644
--- a/src/qt/paymentserver.cpp
+++ b/src/qt/paymentserver.cpp
@@ -144,7 +144,7 @@ void PaymentServer::LoadRootCAs(X509_STORE* _store)
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
- Q_FOREACH (const QSslCertificate& cert, certList) {
+ for (const QSslCertificate& cert : certList) {
// Don't log NULL certificates
if (cert.isNull())
continue;
@@ -267,7 +267,7 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
- Q_FOREACH (const QString& r, savedPaymentRequests)
+ for (const QString& r : savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
@@ -392,7 +392,7 @@ void PaymentServer::uiReady()
initNetManager();
saveURIs = false;
- Q_FOREACH (const QString& s, savedPaymentRequests)
+ for (const QString& s : savedPaymentRequests)
{
handleURIOrFile(s);
}
@@ -555,7 +555,7 @@ bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, Sen
QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();
QStringList addresses;
- Q_FOREACH(const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {
+ for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
@@ -742,7 +742,7 @@ void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError>
Q_UNUSED(reply);
QString errString;
- Q_FOREACH (const QSslError& err, errs) {
+ for (const QSslError& err : errs) {
qWarning() << "PaymentServer::reportSslErrors: " << err;
errString += err.errorString() + "\n";
}
diff --git a/src/qt/peertablemodel.cpp b/src/qt/peertablemodel.cpp
index fff072fd4c..42934f8055 100644
--- a/src/qt/peertablemodel.cpp
+++ b/src/qt/peertablemodel.cpp
@@ -62,7 +62,7 @@ public:
#if QT_VERSION >= 0x040700
cachedNodeStats.reserve(vstats.size());
#endif
- Q_FOREACH (const CNodeStats& nodestats, vstats)
+ for (const CNodeStats& nodestats : vstats)
{
CNodeCombinedStats stats;
stats.nodeStateStats.nMisbehavior = 0;
@@ -79,7 +79,7 @@ public:
TRY_LOCK(cs_main, lockMain);
if (lockMain)
{
- BOOST_FOREACH(CNodeCombinedStats &stats, cachedNodeStats)
+ for (CNodeCombinedStats &stats : cachedNodeStats)
stats.fNodeStateStatsAvailable = GetNodeStateStats(stats.nodeStats.nodeid, stats.nodeStateStats);
}
}
@@ -91,7 +91,7 @@ public:
// build index map
mapNodeRows.clear();
int row = 0;
- Q_FOREACH (const CNodeCombinedStats& stats, cachedNodeStats)
+ for (const CNodeCombinedStats& stats : cachedNodeStats)
mapNodeRows.insert(std::pair<NodeId, int>(stats.nodeStats.nodeid, row++));
}
diff --git a/src/qt/platformstyle.cpp b/src/qt/platformstyle.cpp
index 90bd619c04..1f4e1a442f 100644
--- a/src/qt/platformstyle.cpp
+++ b/src/qt/platformstyle.cpp
@@ -48,8 +48,7 @@ void MakeSingleColorImage(QImage& img, const QColor& colorbase)
QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase)
{
QIcon new_ico;
- QSize sz;
- Q_FOREACH(sz, ico.availableSizes())
+ for (const QSize sz : ico.availableSizes())
{
QImage img(ico.pixmap(sz).toImage());
MakeSingleColorImage(img, colorbase);
diff --git a/src/qt/receivecoinsdialog.cpp b/src/qt/receivecoinsdialog.cpp
index e98f4d3347..84f43266e1 100644
--- a/src/qt/receivecoinsdialog.cpp
+++ b/src/qt/receivecoinsdialog.cpp
@@ -191,7 +191,7 @@ void ReceiveCoinsDialog::on_showRequestButton_clicked()
return;
QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();
- Q_FOREACH (const QModelIndex& index, selection) {
+ for (const QModelIndex& index : selection) {
on_recentRequestsView_doubleClicked(index);
}
}
diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp
index e4c857e40b..470fb6b377 100644
--- a/src/qt/recentrequeststablemodel.cpp
+++ b/src/qt/recentrequeststablemodel.cpp
@@ -22,7 +22,7 @@ RecentRequestsTableModel::RecentRequestsTableModel(CWallet *wallet, WalletModel
// Load entries from wallet
std::vector<std::string> vReceiveRequests;
parent->loadReceiveRequests(vReceiveRequests);
- BOOST_FOREACH(const std::string& request, vReceiveRequests)
+ for (const std::string& request : vReceiveRequests)
addNewRequest(request);
/* These columns must match the indices in the ColumnIndex enumeration */
diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp
index b17693e1ca..ec0580b81c 100644
--- a/src/qt/rpcconsole.cpp
+++ b/src/qt/rpcconsole.cpp
@@ -672,7 +672,7 @@ void RPCConsole::setFontSize(int newSize)
{
QSettings settings;
- //don't allow a insane font size
+ //don't allow an insane font size
if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
return;
@@ -738,7 +738,7 @@ void RPCConsole::clear(bool clearHistory)
tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")) +
"<br><span class=\"secwarning\">" +
- tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramification of a command.") +
+ tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
"</span>",
true);
}
diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp
index 272ab9486a..12d2d0f31c 100644
--- a/src/qt/sendcoinsdialog.cpp
+++ b/src/qt/sendcoinsdialog.cpp
@@ -265,7 +265,7 @@ void SendCoinsDialog::on_sendButton_clicked()
// Format confirmation message
QStringList formatted;
- Q_FOREACH(const SendCoinsRecipient &rcp, currentTransaction.getRecipients())
+ for (const SendCoinsRecipient &rcp : currentTransaction.getRecipients())
{
// generate bold amount string
QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
@@ -319,7 +319,7 @@ void SendCoinsDialog::on_sendButton_clicked()
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
- Q_FOREACH(BitcoinUnits::Unit u, BitcoinUnits::availableUnits())
+ for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
if(u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
@@ -651,8 +651,8 @@ void SendCoinsDialog::updateSmartFeeLabel()
return;
int nBlocksToConfirm = ui->sliderSmartFee->maximum() - ui->sliderSmartFee->value() + 2;
- int estimateFoundAtBlocks = nBlocksToConfirm;
- CFeeRate feeRate = ::feeEstimator.estimateSmartFee(nBlocksToConfirm, &estimateFoundAtBlocks, ::mempool);
+ FeeCalculation feeCalc;
+ CFeeRate feeRate = ::feeEstimator.estimateSmartFee(nBlocksToConfirm, &feeCalc, ::mempool);
if (feeRate <= CFeeRate(0)) // not enough data => minfee
{
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(),
@@ -670,7 +670,7 @@ void SendCoinsDialog::updateSmartFeeLabel()
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(),
std::max(feeRate.GetFeePerK(), CWallet::GetRequiredFee(1000))) + "/kB");
ui->labelSmartFee2->hide();
- ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", estimateFoundAtBlocks));
+ ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", feeCalc.returnedTarget));
ui->fallbackFeeWarningLabel->setVisible(false);
}
@@ -822,6 +822,12 @@ void SendCoinsDialog::coinControlUpdateLabels()
// set pay amounts
CoinControlDialog::payAmounts.clear();
CoinControlDialog::fSubtractFeeFromAmount = false;
+ if (ui->radioSmartFee->isChecked()) {
+ CoinControlDialog::coinControl->nConfirmTarget = ui->sliderSmartFee->maximum() - ui->sliderSmartFee->value() + 2;
+ } else {
+ CoinControlDialog::coinControl->nConfirmTarget = model->getDefaultConfirmTarget();
+ }
+
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp
index f4377247e1..10966e42eb 100644
--- a/src/qt/splashscreen.cpp
+++ b/src/qt/splashscreen.cpp
@@ -188,7 +188,7 @@ void SplashScreen::unsubscribeFromCoreSignals()
uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
#ifdef ENABLE_WALLET
- Q_FOREACH(CWallet* const & pwallet, connectedWallets) {
+ for (CWallet* const & pwallet : connectedWallets) {
pwallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
}
#endif
diff --git a/src/qt/test/paymentservertests.cpp b/src/qt/test/paymentservertests.cpp
index 08a76c7d49..b9a8ad6e28 100644
--- a/src/qt/test/paymentservertests.cpp
+++ b/src/qt/test/paymentservertests.cpp
@@ -196,7 +196,7 @@ void PaymentServerTests::paymentServerTests()
QVERIFY(r.paymentRequest.IsInitialized());
// Extract address and amount from the request
QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo();
- Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {
+ for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest))
QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);
diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp
index dada689731..26dec3c610 100644
--- a/src/qt/test/rpcnestedtests.cpp
+++ b/src/qt/test/rpcnestedtests.cpp
@@ -33,8 +33,6 @@ static const CRPCCommand vRPCCommands[] =
void RPCNestedTests::rpcNestedTests()
{
- UniValue jsonRPCError;
-
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
const CChainParams& chainparams = Params();
diff --git a/src/qt/trafficgraphwidget.cpp b/src/qt/trafficgraphwidget.cpp
index 06f9c5134a..5bb863451f 100644
--- a/src/qt/trafficgraphwidget.cpp
+++ b/src/qt/trafficgraphwidget.cpp
@@ -140,10 +140,10 @@ void TrafficGraphWidget::updateRates()
}
float tmax = 0.0f;
- Q_FOREACH(float f, vSamplesIn) {
+ for (float f : vSamplesIn) {
if(f > tmax) tmax = f;
}
- Q_FOREACH(float f, vSamplesOut) {
+ for (float f : vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp
index 233fc08772..bcacc47ef3 100644
--- a/src/qt/transactiondesc.cpp
+++ b/src/qt/transactiondesc.cpp
@@ -133,7 +133,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
// Coinbase
//
CAmount nUnmatured = 0;
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
@@ -152,14 +152,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
else
{
isminetype fAllFromMe = ISMINE_SPENDABLE;
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
isminetype mine = wallet->IsMine(txin);
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
{
isminetype mine = wallet->IsMine(txout);
if(fAllToMe > mine) fAllToMe = mine;
@@ -173,7 +173,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// Debit
//
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
{
// Ignore change
isminetype toSelf = wallet->IsMine(txout);
@@ -221,10 +221,10 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
//
// Mixed debit transaction
//
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
}
@@ -245,14 +245,14 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>";
// Message from normal bitcoin:URI (bitcoin:123...?message=example)
- Q_FOREACH (const PAIRTYPE(std::string, std::string)& r, wtx.vOrderForm)
+ for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
- Q_FOREACH (const PAIRTYPE(std::string, std::string)& r, wtx.vOrderForm)
+ for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
{
if (r.first == "PaymentRequest")
{
@@ -276,10 +276,10 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
if (logCategories != BCLog::NONE)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
if(wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
if(wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
@@ -289,7 +289,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
COutPoint prevout = txin.prevout;
diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp
index 0090b0c74b..da070da084 100644
--- a/src/qt/transactionrecord.cpp
+++ b/src/qt/transactionrecord.cpp
@@ -78,7 +78,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
{
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
isminetype mine = wallet->IsMine(txin);
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
@@ -86,7 +86,7 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *
}
isminetype fAllToMe = ISMINE_SPENDABLE;
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
{
isminetype mine = wallet->IsMine(txout);
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp
index ae51eba902..59cef555b1 100644
--- a/src/qt/transactiontablemodel.cpp
+++ b/src/qt/transactiontablemodel.cpp
@@ -143,7 +143,7 @@ public:
{
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);
int insert_idx = lowerIndex;
- Q_FOREACH(const TransactionRecord &rec, toInsert)
+ for (const TransactionRecord &rec : toInsert)
{
cachedWallet.insert(insert_idx, rec);
insert_idx += 1;
diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp
index 7ab4125284..c9b344fbd8 100644
--- a/src/qt/utilitydialog.cpp
+++ b/src/qt/utilitydialog.cpp
@@ -106,7 +106,7 @@ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
- Q_FOREACH (const QString &line, coreOptions.split("\n")) {
+ for (const QString &line : coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp
index 8df0e481bd..6538a80233 100644
--- a/src/qt/walletmodel.cpp
+++ b/src/qt/walletmodel.cpp
@@ -207,7 +207,7 @@ WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransact
int nAddresses = 0;
// Pre-check input data for validity
- Q_FOREACH(const SendCoinsRecipient &rcp, recipients)
+ for (const SendCoinsRecipient &rcp : recipients)
{
if (rcp.fSubtractFeeFromAmount)
fSubtractFeeFromAmount = true;
@@ -310,7 +310,7 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran
LOCK2(cs_main, wallet->cs_wallet);
CWalletTx *newTx = transaction.getTransaction();
- Q_FOREACH(const SendCoinsRecipient &rcp, transaction.getRecipients())
+ for (const SendCoinsRecipient &rcp : transaction.getRecipients())
{
if (rcp.paymentRequest.IsInitialized())
{
@@ -339,9 +339,9 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran
transaction_array.append(&(ssTx[0]), ssTx.size());
}
- // Add addresses / update labels that we've sent to to the address book,
+ // Add addresses / update labels that we've sent to the address book,
// and emit coinsSent signal for each recipient
- Q_FOREACH(const SendCoinsRecipient &rcp, transaction.getRecipients())
+ for (const SendCoinsRecipient &rcp : transaction.getRecipients())
{
// Don't touch the address book when we have a payment request
if (!rcp.paymentRequest.IsInitialized())
@@ -574,7 +574,7 @@ bool WalletModel::getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const
void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
{
LOCK2(cs_main, wallet->cs_wallet);
- BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
+ for (const COutPoint& outpoint : vOutpoints)
{
if (!wallet->mapWallet.count(outpoint.hash)) continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
diff --git a/src/qt/walletmodeltransaction.cpp b/src/qt/walletmodeltransaction.cpp
index b4445c8166..8bc9ef725e 100644
--- a/src/qt/walletmodeltransaction.cpp
+++ b/src/qt/walletmodeltransaction.cpp
@@ -82,7 +82,7 @@ void WalletModelTransaction::reassignAmounts(int nChangePosRet)
CAmount WalletModelTransaction::getTotalTransactionAmount()
{
CAmount totalTransactionAmount = 0;
- Q_FOREACH(const SendCoinsRecipient &rcp, recipients)
+ for (const SendCoinsRecipient &rcp : recipients)
{
totalTransactionAmount += rcp.amount;
}
diff --git a/src/random.cpp b/src/random.cpp
index e1ccfa5f24..67efc7d945 100644
--- a/src/random.cpp
+++ b/src/random.cpp
@@ -65,6 +65,70 @@ static inline int64_t GetPerformanceCounter()
#endif
}
+
+#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
+static std::atomic<bool> hwrand_initialized{false};
+static bool rdrand_supported = false;
+static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
+static void RDRandInit()
+{
+ uint32_t eax, ecx, edx;
+#if defined(__i386__) && ( defined(__PIC__) || defined(__PIE__))
+ // Avoid clobbering ebx, as that is used for PIC on x86.
+ uint32_t tmp;
+ __asm__ ("mov %%ebx, %1; cpuid; mov %1, %%ebx": "=a"(eax), "=g"(tmp), "=c"(ecx), "=d"(edx) : "a"(1));
+#else
+ uint32_t ebx;
+ __asm__ ("cpuid": "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(1));
+#endif
+ //! When calling cpuid function #1, ecx register will have this set if RDRAND is available.
+ if (ecx & CPUID_F1_ECX_RDRAND) {
+ LogPrintf("Using RdRand as entropy source\n");
+ rdrand_supported = true;
+ }
+ hwrand_initialized.store(true);
+}
+#else
+static void RDRandInit() {}
+#endif
+
+static bool GetHWRand(unsigned char* ent32) {
+#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
+ assert(hwrand_initialized.load(std::memory_order_relaxed));
+ if (rdrand_supported) {
+ uint8_t ok;
+ // Not all assemblers support the rdrand instruction, write it in hex.
+#ifdef __i386__
+ for (int iter = 0; iter < 4; ++iter) {
+ uint32_t r1, r2;
+ __asm__ volatile (".byte 0x0f, 0xc7, 0xf0;" // rdrand %eax
+ ".byte 0x0f, 0xc7, 0xf2;" // rdrand %edx
+ "setc %2" :
+ "=a"(r1), "=d"(r2), "=q"(ok) :: "cc");
+ if (!ok) return false;
+ WriteLE32(ent32 + 8 * iter, r1);
+ WriteLE32(ent32 + 8 * iter + 4, r2);
+ }
+#else
+ uint64_t r1, r2, r3, r4;
+ __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf0, " // rdrand %rax
+ "0x48, 0x0f, 0xc7, 0xf3, " // rdrand %rbx
+ "0x48, 0x0f, 0xc7, 0xf1, " // rdrand %rcx
+ "0x48, 0x0f, 0xc7, 0xf2; " // rdrand %rdx
+ "setc %4" :
+ "=a"(r1), "=b"(r2), "=c"(r3), "=d"(r4), "=q"(ok) :: "cc");
+ if (!ok) return false;
+ WriteLE64(ent32, r1);
+ WriteLE64(ent32 + 8, r2);
+ WriteLE64(ent32 + 16, r3);
+ WriteLE64(ent32 + 24, r4);
+#endif
+ return true;
+ }
+#endif
+ return false;
+}
+
void RandAddSeed()
{
// Seed with CPU performance counter
@@ -255,6 +319,11 @@ void GetStrongRandBytes(unsigned char* out, int num)
GetOSRand(buf);
hasher.Write(buf, 32);
+ // Third source: HW RNG, if available.
+ if (GetHWRand(buf)) {
+ hasher.Write(buf, 32);
+ }
+
// Combine with and update state
{
std::unique_lock<std::mutex> lock(cs_rng_state);
@@ -381,3 +450,8 @@ FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDete
uint256 seed;
rng.SetKey(seed.begin(), 32);
}
+
+void RandomInit()
+{
+ RDRandInit();
+}
diff --git a/src/random.h b/src/random.h
index dcb74eadb5..c60ab36179 100644
--- a/src/random.h
+++ b/src/random.h
@@ -140,4 +140,7 @@ void GetOSRand(unsigned char *ent32);
*/
bool Random_SanityCheck();
+/** Initialize the RNG. */
+void RandomInit();
+
#endif // BITCOIN_RANDOM_H
diff --git a/src/rest.cpp b/src/rest.cpp
index b08d7153b1..33e3fb4529 100644
--- a/src/rest.cpp
+++ b/src/rest.cpp
@@ -158,7 +158,7 @@ static bool rest_headers(HTTPRequest* req,
}
CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION);
- BOOST_FOREACH(const CBlockIndex *pindex, headers) {
+ for (const CBlockIndex *pindex : headers) {
ssHeader << pindex->GetBlockHeader();
}
@@ -178,7 +178,7 @@ static bool rest_headers(HTTPRequest* req,
}
case RF_JSON: {
UniValue jsonHeaders(UniValue::VARR);
- BOOST_FOREACH(const CBlockIndex *pindex, headers) {
+ for (const CBlockIndex *pindex : headers) {
jsonHeaders.push_back(blockheaderToJSON(pindex));
}
std::string strJSON = jsonHeaders.write() + "\n";
@@ -413,7 +413,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
boost::split(uriParts, strUriParams, boost::is_any_of("/"));
}
- // throw exception in case of a empty request
+ // throw exception in case of an empty request
std::string strRequestMutable = req->ReadBody();
if (strRequestMutable.length() == 0 && uriParts.size() == 0)
return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
@@ -558,7 +558,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
UniValue utxos(UniValue::VARR);
- BOOST_FOREACH (const CCoin& coin, outs) {
+ for (const CCoin& coin : outs) {
UniValue utxo(UniValue::VOBJ);
utxo.push_back(Pair("height", (int32_t)coin.nHeight));
utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index 388472f076..8f7f76841d 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -365,14 +365,14 @@ void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
const CTransaction& tx = e.GetTx();
std::set<std::string> setDepends;
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
{
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
- BOOST_FOREACH(const std::string& dep, setDepends)
+ for (const std::string& dep : setDepends)
{
depends.push_back(dep);
}
@@ -386,7 +386,7 @@ UniValue mempoolToJSON(bool fVerbose)
{
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
- BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx)
+ for (const CTxMemPoolEntry& e : mempool.mapTx)
{
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
@@ -401,7 +401,7 @@ UniValue mempoolToJSON(bool fVerbose)
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
- BOOST_FOREACH(const uint256& hash, vtxid)
+ for (const uint256& hash : vtxid)
a.push_back(hash.ToString());
return a;
@@ -486,14 +486,14 @@ UniValue getmempoolancestors(const JSONRPCRequest& request)
if (!fVerbose) {
UniValue o(UniValue::VARR);
- BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
+ for (CTxMemPool::txiter ancestorIt : setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
- BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
+ for (CTxMemPool::txiter ancestorIt : setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
@@ -550,14 +550,14 @@ UniValue getmempooldescendants(const JSONRPCRequest& request)
if (!fVerbose) {
UniValue o(UniValue::VARR);
- BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
+ for (CTxMemPool::txiter descendantIt : setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
- BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
+ for (CTxMemPool::txiter descendantIt : setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
@@ -1262,7 +1262,7 @@ UniValue getchaintips(const JSONRPCRequest& request)
std::set<const CBlockIndex*> setOrphans;
std::set<const CBlockIndex*> setPrevs;
- BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
+ for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
{
if (!chainActive.Contains(item.second)) {
setOrphans.insert(item.second);
@@ -1282,7 +1282,7 @@ UniValue getchaintips(const JSONRPCRequest& request)
/* Construct the output array. */
UniValue res(UniValue::VARR);
- BOOST_FOREACH(const CBlockIndex* block, setTips)
+ for (const CBlockIndex* block : setTips)
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("height", block->nHeight));
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index ab9f40d466..3b212dc0e4 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -582,7 +582,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request)
entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
UniValue deps(UniValue::VARR);
- BOOST_FOREACH (const CTxIn &in, tx.vin)
+ for (const CTxIn &in : tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
@@ -867,10 +867,10 @@ UniValue estimatesmartfee(const JSONRPCRequest& request)
}
UniValue result(UniValue::VOBJ);
- int answerFound;
- CFeeRate feeRate = ::feeEstimator.estimateSmartFee(nBlocks, &answerFound, ::mempool, conservative);
+ FeeCalculation feeCalc;
+ CFeeRate feeRate = ::feeEstimator.estimateSmartFee(nBlocks, &feeCalc, ::mempool, conservative);
result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
- result.push_back(Pair("blocks", answerFound));
+ result.push_back(Pair("blocks", feeCalc.returnedTarget));
return result;
}
diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp
index 5af6bbef33..ef19e481c2 100644
--- a/src/rpc/misc.cpp
+++ b/src/rpc/misc.cpp
@@ -147,7 +147,7 @@ public:
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
UniValue a(UniValue::VARR);
- BOOST_FOREACH(const CTxDestination& addr, addresses)
+ for (const CTxDestination& addr : addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp
index ab4ecbcf17..5cab0ad5bd 100644
--- a/src/rpc/net.cpp
+++ b/src/rpc/net.cpp
@@ -75,7 +75,7 @@ UniValue getpeerinfo(const JSONRPCRequest& request)
"[\n"
" {\n"
" \"id\": n, (numeric) Peer index\n"
- " \"addr\":\"host:port\", (string) The ip address and port of the peer\n"
+ " \"addr\":\"host:port\", (string) The IP address and port of the peer\n"
" \"addrbind\":\"ip:port\", (string) Bind address of the connection to the peer\n"
" \"addrlocal\":\"ip:port\", (string) Local address as reported by the peer\n"
" \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
@@ -126,7 +126,7 @@ UniValue getpeerinfo(const JSONRPCRequest& request)
UniValue ret(UniValue::VARR);
- BOOST_FOREACH(const CNodeStats& stats, vstats) {
+ for (const CNodeStats& stats : vstats) {
UniValue obj(UniValue::VOBJ);
CNodeStateStats statestats;
bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
@@ -163,7 +163,7 @@ UniValue getpeerinfo(const JSONRPCRequest& request)
obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
UniValue heights(UniValue::VARR);
- BOOST_FOREACH(int height, statestats.vHeightInFlight) {
+ for (int height : statestats.vHeightInFlight) {
heights.push_back(height);
}
obj.push_back(Pair("inflight", heights));
@@ -171,14 +171,14 @@ UniValue getpeerinfo(const JSONRPCRequest& request)
obj.push_back(Pair("whitelisted", stats.fWhitelisted));
UniValue sendPerMsgCmd(UniValue::VOBJ);
- BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapSendBytesPerMsgCmd) {
+ for (const mapMsgCmdSize::value_type &i : stats.mapSendBytesPerMsgCmd) {
if (i.second > 0)
sendPerMsgCmd.push_back(Pair(i.first, i.second));
}
obj.push_back(Pair("bytessent_per_msg", sendPerMsgCmd));
UniValue recvPerMsgCmd(UniValue::VOBJ);
- BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapRecvBytesPerMsgCmd) {
+ for (const mapMsgCmdSize::value_type &i : stats.mapRecvBytesPerMsgCmd) {
if (i.second > 0)
recvPerMsgCmd.push_back(Pair(i.first, i.second));
}
@@ -199,7 +199,7 @@ UniValue addnode(const JSONRPCRequest& request)
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw std::runtime_error(
"addnode \"node\" \"add|remove|onetry\"\n"
- "\nAttempts add or remove a node from the addnode list.\n"
+ "\nAttempts to add or remove a node from the addnode list.\n"
"Or try a connection to a node once.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
@@ -290,7 +290,7 @@ UniValue getaddednodeinfo(const JSONRPCRequest& request)
"\nResult:\n"
"[\n"
" {\n"
- " \"addednode\" : \"192.168.0.201\", (string) The node ip address or name (as provided to addnode)\n"
+ " \"addednode\" : \"192.168.0.201\", (string) The node IP address or name (as provided to addnode)\n"
" \"connected\" : true|false, (boolean) If connected\n"
" \"addresses\" : [ (list of objects) Only when connected = true\n"
" {\n"
@@ -474,7 +474,7 @@ UniValue getnetworkinfo(const JSONRPCRequest& request)
UniValue localAddresses(UniValue::VARR);
{
LOCK(cs_mapLocalHost);
- BOOST_FOREACH(const PAIRTYPE(CNetAddr, LocalServiceInfo) &item, mapLocalHost)
+ for (const std::pair<CNetAddr, LocalServiceInfo> &item : mapLocalHost)
{
UniValue rec(UniValue::VOBJ);
rec.push_back(Pair("address", item.first.ToString()));
@@ -497,12 +497,12 @@ UniValue setban(const JSONRPCRequest& request)
(strCommand != "add" && strCommand != "remove"))
throw std::runtime_error(
"setban \"subnet\" \"add|remove\" (bantime) (absolute)\n"
- "\nAttempts add or remove a IP/Subnet from the banned list.\n"
+ "\nAttempts to add or remove an IP/Subnet from the banned list.\n"
"\nArguments:\n"
- "1. \"subnet\" (string, required) The IP/Subnet (see getpeerinfo for nodes ip) with a optional netmask (default is /32 = single ip)\n"
- "2. \"command\" (string, required) 'add' to add a IP/Subnet to the list, 'remove' to remove a IP/Subnet from the list\n"
- "3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the ip is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n"
- "4. \"absolute\" (boolean, optional) If set, the bantime must be a absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
+ "1. \"subnet\" (string, required) The IP/Subnet (see getpeerinfo for nodes IP) with an optional netmask (default is /32 = single IP)\n"
+ "2. \"command\" (string, required) 'add' to add an IP/Subnet to the list, 'remove' to remove an IP/Subnet from the list\n"
+ "3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the IP is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n"
+ "4. \"absolute\" (boolean, optional) If set, the bantime must be an absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
"\nExamples:\n"
+ HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
+ HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp
index 63fd197a6b..527a4d6974 100644
--- a/src/rpc/rawtransaction.cpp
+++ b/src/rpc/rawtransaction.cpp
@@ -218,9 +218,13 @@ UniValue gettxoutproof(const JSONRPCRequest& request)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
- const Coin& coin = AccessByTxid(*pcoinsTip, oneTxid);
- if (!coin.IsSpent() && coin.nHeight > 0 && coin.nHeight <= chainActive.Height()) {
- pblockindex = chainActive[coin.nHeight];
+ // Loop through txids and try to find which block they're in. Exit loop once a block is found.
+ for (const auto& tx : setTxids) {
+ const Coin& coin = AccessByTxid(*pcoinsTip, tx);
+ if (!coin.IsSpent()) {
+ pblockindex = chainActive[coin.nHeight];
+ break;
+ }
}
}
@@ -243,7 +247,7 @@ UniValue gettxoutproof(const JSONRPCRequest& request)
if (setTxids.count(tx->GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
- throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
+ throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
CMerkleBlock mb(block, setTxids);
@@ -281,7 +285,7 @@ UniValue verifytxoutproof(const JSONRPCRequest& request)
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
- BOOST_FOREACH(const uint256& hash, vMatch)
+ for (const uint256& hash : vMatch)
res.push_back(hash.GetHex());
return res;
}
@@ -383,7 +387,7 @@ UniValue createrawtransaction(const JSONRPCRequest& request)
std::set<CBitcoinAddress> setAddress;
std::vector<std::string> addrList = sendTo.getKeys();
- BOOST_FOREACH(const std::string& name_, addrList) {
+ for (const std::string& name_ : addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
@@ -651,7 +655,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
- BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
+ for (const CTxIn& txin : mergedTx.vin) {
view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
}
@@ -794,7 +798,7 @@ UniValue signrawtransaction(const JSONRPCRequest& request)
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
// ... and merge in other signatures:
- BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
+ for (const CMutableTransaction& txv : txVariants) {
if (txv.vin.size() > i) {
sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
}
diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp
index 31771dffb8..1a04ce2b47 100644
--- a/src/rpc/server.cpp
+++ b/src/rpc/server.cpp
@@ -62,7 +62,7 @@ void RPCTypeCheck(const UniValue& params,
bool fAllowNull)
{
unsigned int i = 0;
- BOOST_FOREACH(UniValue::VType t, typesExpected)
+ for (UniValue::VType t : typesExpected)
{
if (params.size() <= i)
break;
@@ -101,7 +101,7 @@ void RPCTypeCheckObj(const UniValue& o,
if (fStrict)
{
- BOOST_FOREACH(const std::string& k, o.getKeys())
+ for (const std::string& k : o.getKeys())
{
if (typesExpected.count(k) == 0)
{
@@ -184,7 +184,7 @@ std::string CRPCTable::help(const std::string& strCommand, const JSONRPCRequest&
jreq.fHelp = true;
jreq.params = UniValue();
- BOOST_FOREACH(const PAIRTYPE(std::string, const CRPCCommand*)& command, vCommands)
+ for (const std::pair<std::string, const CRPCCommand*>& command : vCommands)
{
const CRPCCommand *pcmd = command.second;
std::string strMethod = pcmd->name;
diff --git a/src/script/ismine.cpp b/src/script/ismine.cpp
index a4743281b1..35b534344e 100644
--- a/src/script/ismine.cpp
+++ b/src/script/ismine.cpp
@@ -18,7 +18,7 @@ typedef std::vector<unsigned char> valtype;
unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
{
unsigned int nResult = 0;
- BOOST_FOREACH(const valtype& pubkey, pubkeys)
+ for (const valtype& pubkey : pubkeys)
{
CKeyID keyID = CPubKey(pubkey).GetID();
if (keystore.HaveKey(keyID))
diff --git a/src/script/sign.cpp b/src/script/sign.cpp
index 123f88bd6f..f4a32472b0 100644
--- a/src/script/sign.cpp
+++ b/src/script/sign.cpp
@@ -126,7 +126,7 @@ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptP
static CScript PushAll(const std::vector<valtype>& values)
{
CScript result;
- BOOST_FOREACH(const valtype& v, values) {
+ for (const valtype& v : values) {
if (v.size() == 0) {
result << OP_0;
} else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
@@ -231,12 +231,12 @@ static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const B
{
// Combine all the signatures we've got:
std::set<valtype> allsigs;
- BOOST_FOREACH(const valtype& v, sigs1)
+ for (const valtype& v : sigs1)
{
if (!v.empty())
allsigs.insert(v);
}
- BOOST_FOREACH(const valtype& v, sigs2)
+ for (const valtype& v : sigs2)
{
if (!v.empty())
allsigs.insert(v);
@@ -247,7 +247,7 @@ static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const B
unsigned int nSigsRequired = vSolutions.front()[0];
unsigned int nPubKeys = vSolutions.size()-2;
std::map<valtype, valtype> sigs;
- BOOST_FOREACH(const valtype& sig, allsigs)
+ for (const valtype& sig : allsigs)
{
for (unsigned int i = 0; i < nPubKeys; i++)
{
diff --git a/src/script/standard.cpp b/src/script/standard.cpp
index 63f20b0993..7efcad7b0f 100644
--- a/src/script/standard.cpp
+++ b/src/script/standard.cpp
@@ -94,7 +94,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::v
// Scan templates
const CScript& script1 = scriptPubKey;
- BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
+ for (const std::pair<txnouttype, CScript>& tplate : mTemplates)
{
const CScript& script2 = tplate.second;
vSolutionsRet.clear();
@@ -293,7 +293,7 @@ CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
CScript script;
script << CScript::EncodeOP_N(nRequired);
- BOOST_FOREACH(const CPubKey& key, keys)
+ for (const CPubKey& key : keys)
script << ToByteVector(key);
script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
return script;
diff --git a/src/secp256k1/sage/group_prover.sage b/src/secp256k1/sage/group_prover.sage
index ab580c5b23..5198724bea 100644
--- a/src/secp256k1/sage/group_prover.sage
+++ b/src/secp256k1/sage/group_prover.sage
@@ -3,7 +3,7 @@
# to independently set assumptions on input or intermediary variables.
#
# The general approach is:
-# * A constraint is a tuple of two sets of of symbolic expressions:
+# * A constraint is a tuple of two sets of symbolic expressions:
# the first of which are required to evaluate to zero, the second of which
# are required to evaluate to nonzero.
# - A constraint is said to be conflicting if any of its nonzero expressions
diff --git a/src/secp256k1/src/asm/field_10x26_arm.s b/src/secp256k1/src/asm/field_10x26_arm.s
index 5df561f2fc..bd2b629e1c 100644
--- a/src/secp256k1/src/asm/field_10x26_arm.s
+++ b/src/secp256k1/src/asm/field_10x26_arm.s
@@ -11,7 +11,7 @@ Note:
- To avoid unnecessary loads and make use of available registers, two
'passes' have every time been interleaved, with the odd passes accumulating c' and d'
- which will be added to c and d respectively in the the even passes
+ which will be added to c and d respectively in the even passes
*/
diff --git a/src/support/events.h b/src/support/events.h
index 4f2f3cf9ef..90690876ee 100644
--- a/src/support/events.h
+++ b/src/support/events.h
@@ -27,26 +27,26 @@ MAKE_RAII(evhttp);
MAKE_RAII(evhttp_request);
MAKE_RAII(evhttp_connection);
-raii_event_base obtain_event_base() {
+inline raii_event_base obtain_event_base() {
auto result = raii_event_base(event_base_new());
if (!result.get())
throw std::runtime_error("cannot create event_base");
return result;
}
-raii_event obtain_event(struct event_base* base, evutil_socket_t s, short events, event_callback_fn cb, void* arg) {
+inline raii_event obtain_event(struct event_base* base, evutil_socket_t s, short events, event_callback_fn cb, void* arg) {
return raii_event(event_new(base, s, events, cb, arg));
}
-raii_evhttp obtain_evhttp(struct event_base* base) {
+inline raii_evhttp obtain_evhttp(struct event_base* base) {
return raii_evhttp(evhttp_new(base));
}
-raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg) {
+inline raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg) {
return raii_evhttp_request(evhttp_request_new(cb, arg));
}
-raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) {
+inline raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) {
auto result = raii_evhttp_connection(evhttp_connection_base_new(base, NULL, host.c_str(), port));
if (!result.get())
throw std::runtime_error("create connection failed");
diff --git a/src/sync.cpp b/src/sync.cpp
index 552682ab67..94f2cafa98 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -77,7 +77,7 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch,
{
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
- BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {
+ for (const std::pair<void*, CLockLocation> & i : s2) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
}
@@ -87,7 +87,7 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch,
LogPrintf(" %s\n", i.second.ToString());
}
LogPrintf("Current lock order is:\n");
- BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {
+ for (const std::pair<void*, CLockLocation> & i : s1) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
}
@@ -108,7 +108,7 @@ static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
(*lockstack).push_back(std::make_pair(c, locklocation));
- BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {
+ for (const std::pair<void*, CLockLocation> & i : (*lockstack)) {
if (i.first == c)
break;
@@ -142,14 +142,14 @@ void LeaveCritical()
std::string LocksHeld()
{
std::string result;
- BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
+ for (const std::pair<void*, CLockLocation> & i : *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
- BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
+ for (const std::pair<void*, CLockLocation> & i : *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
diff --git a/src/test/arith_uint256_tests.cpp b/src/test/arith_uint256_tests.cpp
index 45ae7d4636..2c98fbcfd6 100644
--- a/src/test/arith_uint256_tests.cpp
+++ b/src/test/arith_uint256_tests.cpp
@@ -219,7 +219,7 @@ BOOST_AUTO_TEST_CASE( unaryOperators ) // ! ~ -
// Check if doing _A_ _OP_ _B_ results in the same as applying _OP_ onto each
-// element of Aarray and Barray, and then converting the result into a arith_uint256.
+// element of Aarray and Barray, and then converting the result into an arith_uint256.
#define CHECKBITWISEOPERATOR(_A_,_B_,_OP_) \
for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = _A_##Array[i] _OP_ _B_##Array[i]; } \
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (_A_##L _OP_ _B_##L));
diff --git a/src/test/bip32_tests.cpp b/src/test/bip32_tests.cpp
index c148ad6d82..6bcd550d7b 100644
--- a/src/test/bip32_tests.cpp
+++ b/src/test/bip32_tests.cpp
@@ -93,7 +93,7 @@ void RunTest(const TestVector &test) {
CExtPubKey pubkey;
key.SetMaster(&seed[0], seed.size());
pubkey = key.Neuter();
- BOOST_FOREACH(const TestDerivation &derive, test.vDerive) {
+ for (const TestDerivation &derive : test.vDerive) {
unsigned char data[74];
key.Encode(data);
pubkey.Encode(data);
diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
index 4fd3ff9cf1..33abfabe6b 100644
--- a/src/test/coins_tests.cpp
+++ b/src/test/coins_tests.cpp
@@ -193,7 +193,7 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
found_an_entry = true;
}
}
- BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) {
+ for (const CCoinsViewCacheTest *test : stack) {
test->SelfTest();
}
}
diff --git a/src/test/data/script_tests.json b/src/test/data/script_tests.json
index e35a7ce569..0390d6806d 100644
--- a/src/test/data/script_tests.json
+++ b/src/test/data/script_tests.json
@@ -2506,7 +2506,7 @@
],
["CHECKSEQUENCEVERIFY tests"],
-["", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "INVALID_STACK_OPERATION", "CSV automatically fails on a empty stack"],
+["", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "INVALID_STACK_OPERATION", "CSV automatically fails on an empty stack"],
["-1", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "NEGATIVE_LOCKTIME", "CSV automatically fails if stack top is negative"],
["0x0100", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY,MINIMALDATA", "UNKNOWN_ERROR", "CSV fails if stack top is not minimally encoded"],
["0", "CHECKSEQUENCEVERIFY", "CHECKSEQUENCEVERIFY", "UNSATISFIED_LOCKTIME", "CSV fails if stack top bit 1 << 31 is set and the tx version < 2"],
diff --git a/src/test/data/tx_valid.json b/src/test/data/tx_valid.json
index d70fa54333..e6b382af13 100644
--- a/src/test/data/tx_valid.json
+++ b/src/test/data/tx_valid.json
@@ -174,7 +174,7 @@
[[["5a6b0021a6042a686b6b94abc36b387bef9109847774e8b1e51eb8cc55c53921", 1, "DUP HASH160 0x14 0xee5a6aa40facefb2655ac23c0c28c57c65c41f9b EQUALVERIFY CHECKSIG"]],
"01000000012139c555ccb81ee5b1e87477840991ef7b386bc3ab946b6b682a04a621006b5a01000000fdb40148304502201723e692e5f409a7151db386291b63524c5eb2030df652b1f53022fd8207349f022100b90d9bbf2f3366ce176e5e780a00433da67d9e5c79312c6388312a296a5800390148304502201723e692e5f409a7151db386291b63524c5eb2030df652b1f53022fd8207349f022100b90d9bbf2f3366ce176e5e780a00433da67d9e5c79312c6388312a296a5800390121038479a0fa998cd35259a2ef0a7a5c68662c1474f88ccb6d08a7677bbec7f2204148304502201723e692e5f409a7151db386291b63524c5eb2030df652b1f53022fd8207349f022100b90d9bbf2f3366ce176e5e780a00433da67d9e5c79312c6388312a296a5800390175ac4830450220646b72c35beeec51f4d5bc1cbae01863825750d7f490864af354e6ea4f625e9c022100f04b98432df3a9641719dbced53393022e7249fb59db993af1118539830aab870148304502201723e692e5f409a7151db386291b63524c5eb2030df652b1f53022fd8207349f022100b90d9bbf2f3366ce176e5e780a00433da67d9e5c79312c6388312a296a580039017521038479a0fa998cd35259a2ef0a7a5c68662c1474f88ccb6d08a7677bbec7f22041ffffffff010000000000000000016a00000000", "P2SH"],
-["Finally CHECKMULTISIG removes all signatures prior to hashing the script containing those signatures. In conjunction with the SIGHASH_SINGLE bug this lets us test whether or not FindAndDelete() is actually present in scriptPubKey/redeemScript evaluation by including a signature of the digest 0x01 We can compute in advance for our pubkey, embed it it in the scriptPubKey, and then also using a normal SIGHASH_ALL signature. If FindAndDelete() wasn't run, the 'bugged' signature would still be in the hashed script, and the normal signature would fail."],
+["Finally CHECKMULTISIG removes all signatures prior to hashing the script containing those signatures. In conjunction with the SIGHASH_SINGLE bug this lets us test whether or not FindAndDelete() is actually present in scriptPubKey/redeemScript evaluation by including a signature of the digest 0x01 We can compute in advance for our pubkey, embed it in the scriptPubKey, and then also using a normal SIGHASH_ALL signature. If FindAndDelete() wasn't run, the 'bugged' signature would still be in the hashed script, and the normal signature would fail."],
["Here's an example on mainnet within a P2SH redeemScript. Remarkably it's a standard transaction in <0.9"],
[[["b5b598de91787439afd5938116654e0b16b7a0d0f82742ba37564219c5afcbf9", 0, "DUP HASH160 0x14 0xf6f365c40f0739b61de827a44751e5e99032ed8f EQUALVERIFY CHECKSIG"],
diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp
index 9f59de3ef5..01cc5ed831 100644
--- a/src/test/getarg_tests.cpp
+++ b/src/test/getarg_tests.cpp
@@ -25,7 +25,7 @@ static void ResetArgs(const std::string& strArg)
// Convert to char*:
std::vector<const char*> vecChar;
- BOOST_FOREACH(std::string& s, vecArg)
+ for (std::string& s : vecArg)
vecChar.push_back(s.c_str());
ParseParameters(vecChar.size(), &vecChar[0]);
diff --git a/src/test/multisig_tests.cpp b/src/test/multisig_tests.cpp
index dd5678ea6e..6d8aab887b 100644
--- a/src/test/multisig_tests.cpp
+++ b/src/test/multisig_tests.cpp
@@ -28,7 +28,7 @@ sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transac
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
- BOOST_FOREACH(const CKey &key, keys)
+ for (const CKey &key : keys)
{
std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
diff --git a/src/test/prevector_tests.cpp b/src/test/prevector_tests.cpp
index 354fed1c1d..11bb11d1e9 100644
--- a/src/test/prevector_tests.cpp
+++ b/src/test/prevector_tests.cpp
@@ -53,13 +53,13 @@ class prevector_tester {
local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
size_t pos = 0;
- BOOST_FOREACH(const T& v, pre_vector) {
+ for (const T& v : pre_vector) {
local_check(v == real_vector[pos++]);
}
BOOST_REVERSE_FOREACH(const T& v, pre_vector) {
local_check(v == real_vector[--pos]);
}
- BOOST_FOREACH(const T& v, const_pre_vector) {
+ for (const T& v : const_pre_vector) {
local_check(v == real_vector[pos++]);
}
BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) {
diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp
index 70544cacd6..2ff4f4227e 100644
--- a/src/test/script_tests.cpp
+++ b/src/test/script_tests.cpp
@@ -927,7 +927,7 @@ BOOST_AUTO_TEST_CASE(script_build)
std::string strGen;
- BOOST_FOREACH(TestBuilder& test, tests) {
+ for (TestBuilder& test : tests) {
test.Test();
std::string str = JSONPrettyPrint(test.GetJSON());
#ifndef UPDATE_JSON_TESTS
@@ -1033,7 +1033,7 @@ sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transac
// and vice-versa)
//
result << OP_0;
- BOOST_FOREACH(const CKey &key, keys)
+ for (const CKey &key : keys)
{
std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp
index 11e3df92e1..c60379982e 100644
--- a/src/test/test_bitcoin.cpp
+++ b/src/test/test_bitcoin.cpp
@@ -33,6 +33,7 @@ extern void noui_connect();
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
{
+ RandomInit();
ECC_Start();
SetupEnvironment();
SetupNetworking();
@@ -119,7 +120,7 @@ TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>&
// Replace mempool-selected txns with just coinbase plus passed-in txns:
block.vtx.resize(1);
- BOOST_FOREACH(const CMutableTransaction& tx, txns)
+ for (const CMutableTransaction& tx : txns)
block.vtx.push_back(MakeTransactionRef(tx));
// IncrementExtraNonce creates a valid coinbase and merkleRoot
unsigned int extraNonce = 0;
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index e146bb238c..778d2fd742 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -65,7 +65,7 @@ unsigned int ParseScriptFlags(std::string strFlags)
std::vector<std::string> words;
boost::algorithm::split(words, strFlags, boost::algorithm::is_any_of(","));
- BOOST_FOREACH(std::string word, words)
+ for (std::string word : words)
{
if (!mapFlagNames.count(word))
BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
@@ -393,7 +393,7 @@ void CheckWithFlag(const CTransactionRef& output, const CMutableTransaction& inp
static CScript PushAll(const std::vector<valtype>& values)
{
CScript result;
- BOOST_FOREACH(const valtype& v, values) {
+ for (const valtype& v : values) {
if (v.size() == 0) {
result << OP_0;
} else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
diff --git a/src/timedata.cpp b/src/timedata.cpp
index ec74912703..d736baa213 100644
--- a/src/timedata.cpp
+++ b/src/timedata.cpp
@@ -95,7 +95,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
- BOOST_FOREACH(int64_t nOffset, vSorted)
+ for (int64_t nOffset : vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
@@ -110,7 +110,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
}
if (LogAcceptCategory(BCLog::NET)) {
- BOOST_FOREACH(int64_t n, vSorted) {
+ for (int64_t n : vSorted) {
LogPrint(BCLog::NET, "%+d ", n);
}
LogPrint(BCLog::NET, "| ");
diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
index e3baa0556a..4cd64bf028 100644
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -376,8 +376,10 @@ static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size
while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
// Check for reading errors so we don't return any data if we couldn't
// read the entire file (or up to maxsize)
- if (ferror(f))
+ if (ferror(f)) {
+ fclose(f);
return std::make_pair(false,"");
+ }
retval.append(buffer, buffer+n);
if (retval.size() > maxsize)
break;
@@ -405,7 +407,7 @@ static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
/****** Bitcoin specific TorController implementation ********/
/** Controller that connects to Tor control socket, authenticate, then create
- * and maintain a ephemeral hidden service.
+ * and maintain an ephemeral hidden service.
*/
class TorController
{
@@ -486,7 +488,7 @@ void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlRe
{
if (reply.code == 250) {
LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
- BOOST_FOREACH(const std::string &s, reply.lines) {
+ for (const std::string &s : reply.lines) {
std::map<std::string,std::string> m = ParseTorReplyMapping(s);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("ServiceID")) != m.end())
@@ -616,7 +618,7 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro
* 250-AUTH METHODS=NULL
* 250-AUTH METHODS=HASHEDPASSWORD
*/
- BOOST_FOREACH(const std::string &s, reply.lines) {
+ for (const std::string &s : reply.lines) {
std::pair<std::string,std::string> l = SplitTorReplyLine(s);
if (l.first == "AUTH") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
@@ -633,7 +635,7 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro
}
}
}
- BOOST_FOREACH(const std::string &s, methods) {
+ for (const std::string &s : methods) {
LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
}
// Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
diff --git a/src/txmempool.cpp b/src/txmempool.cpp
index 17389db9f0..f49fd391da 100644
--- a/src/txmempool.cpp
+++ b/src/txmempool.cpp
@@ -73,12 +73,12 @@ void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendan
setAllDescendants.insert(cit);
stageEntries.erase(cit);
const setEntries &setChildren = GetMemPoolChildren(cit);
- BOOST_FOREACH(const txiter childEntry, setChildren) {
+ for (const txiter childEntry : setChildren) {
cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
if (cacheIt != cachedDescendants.end()) {
// We've already calculated this one, just add the entries for this set
// but don't traverse again.
- BOOST_FOREACH(const txiter cacheEntry, cacheIt->second) {
+ for (const txiter cacheEntry : cacheIt->second) {
setAllDescendants.insert(cacheEntry);
}
} else if (!setAllDescendants.count(childEntry)) {
@@ -92,7 +92,7 @@ void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendan
int64_t modifySize = 0;
CAmount modifyFee = 0;
int64_t modifyCount = 0;
- BOOST_FOREACH(txiter cit, setAllDescendants) {
+ for (txiter cit : setAllDescendants) {
if (!setExclude.count(cit->GetTx().GetHash())) {
modifySize += cit->GetTxSize();
modifyFee += cit->GetModifiedFee();
@@ -122,7 +122,7 @@ void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashes
// accounted for in the state of their ancestors)
std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
- // Iterate in reverse, so that whenever we are looking at at a transaction
+ // Iterate in reverse, so that whenever we are looking at a transaction
// we are sure that all in-mempool descendants have already been processed.
// This maximizes the benefit of the descendant cache and guarantees that
// setMemPoolChildren will be updated, an assumption made in
@@ -202,7 +202,7 @@ bool CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntr
}
const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
- BOOST_FOREACH(const txiter &phash, setMemPoolParents) {
+ for (const txiter &phash : setMemPoolParents) {
// If this is a new ancestor, add it.
if (setAncestors.count(phash) == 0) {
parentHashes.insert(phash);
@@ -221,13 +221,13 @@ void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors
{
setEntries parentIters = GetMemPoolParents(it);
// add or remove this tx as a child of each parent
- BOOST_FOREACH(txiter piter, parentIters) {
+ for (txiter piter : parentIters) {
UpdateChild(piter, it, add);
}
const int64_t updateCount = (add ? 1 : -1);
const int64_t updateSize = updateCount * it->GetTxSize();
const CAmount updateFee = updateCount * it->GetModifiedFee();
- BOOST_FOREACH(txiter ancestorIt, setAncestors) {
+ for (txiter ancestorIt : setAncestors) {
mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
}
}
@@ -238,7 +238,7 @@ void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncesto
int64_t updateSize = 0;
CAmount updateFee = 0;
int64_t updateSigOpsCost = 0;
- BOOST_FOREACH(txiter ancestorIt, setAncestors) {
+ for (txiter ancestorIt : setAncestors) {
updateSize += ancestorIt->GetTxSize();
updateFee += ancestorIt->GetModifiedFee();
updateSigOpsCost += ancestorIt->GetSigOpCost();
@@ -249,7 +249,7 @@ void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncesto
void CTxMemPool::UpdateChildrenForRemoval(txiter it)
{
const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
- BOOST_FOREACH(txiter updateIt, setMemPoolChildren) {
+ for (txiter updateIt : setMemPoolChildren) {
UpdateParent(updateIt, it, false);
}
}
@@ -266,19 +266,19 @@ void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, b
// Here we only update statistics and not data in mapLinks (which
// we need to preserve until we're finished with all operations that
// need to traverse the mempool).
- BOOST_FOREACH(txiter removeIt, entriesToRemove) {
+ for (txiter removeIt : entriesToRemove) {
setEntries setDescendants;
CalculateDescendants(removeIt, setDescendants);
setDescendants.erase(removeIt); // don't update state for self
int64_t modifySize = -((int64_t)removeIt->GetTxSize());
CAmount modifyFee = -removeIt->GetModifiedFee();
int modifySigOps = -removeIt->GetSigOpCost();
- BOOST_FOREACH(txiter dit, setDescendants) {
+ for (txiter dit : setDescendants) {
mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
}
}
}
- BOOST_FOREACH(txiter removeIt, entriesToRemove) {
+ for (txiter removeIt : entriesToRemove) {
setEntries setAncestors;
const CTxMemPoolEntry &entry = *removeIt;
std::string dummy;
@@ -307,7 +307,7 @@ void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, b
// After updating all the ancestor sizes, we can now sever the link between each
// transaction being removed and any mempool children (ie, update setMemPoolParents
// for each direct child of a transaction being removed).
- BOOST_FOREACH(txiter removeIt, entriesToRemove) {
+ for (txiter removeIt : entriesToRemove) {
UpdateChildrenForRemoval(removeIt);
}
}
@@ -401,7 +401,7 @@ bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry,
// to clean up the mess we're leaving here.
// Update ancestors with information about this tx
- BOOST_FOREACH (const uint256 &phash, setParentTransactions) {
+ for (const uint256 &phash : setParentTransactions) {
txiter pit = mapTx.find(phash);
if (pit != mapTx.end()) {
UpdateParent(newit, pit, true);
@@ -424,7 +424,7 @@ void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
{
NotifyEntryRemoved(it->GetSharedTx(), reason);
const uint256 hash = it->GetTx().GetHash();
- BOOST_FOREACH(const CTxIn& txin, it->GetTx().vin)
+ for (const CTxIn& txin : it->GetTx().vin)
mapNextTx.erase(txin.prevout);
if (vTxHashes.size() > 1) {
@@ -466,7 +466,7 @@ void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants
stage.erase(it);
const setEntries &setChildren = GetMemPoolChildren(it);
- BOOST_FOREACH(const txiter &childiter, setChildren) {
+ for (const txiter &childiter : setChildren) {
if (!setDescendants.count(childiter)) {
stage.insert(childiter);
}
@@ -498,7 +498,7 @@ void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReaso
}
}
setEntries setAllRemoves;
- BOOST_FOREACH(txiter it, txToRemove) {
+ for (txiter it : txToRemove) {
CalculateDescendants(it, setAllRemoves);
}
@@ -520,7 +520,7 @@ void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMem
// So it's critical that we remove the tx and not depend on the LockPoints.
txToRemove.insert(it);
} else if (it->GetSpendsCoinbase()) {
- BOOST_FOREACH(const CTxIn& txin, tx.vin) {
+ for (const CTxIn& txin : tx.vin) {
indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end())
continue;
@@ -547,7 +547,7 @@ void CTxMemPool::removeConflicts(const CTransaction &tx)
{
// Remove transactions which depend on inputs of tx, recursively
LOCK(cs);
- BOOST_FOREACH(const CTxIn &txin, tx.vin) {
+ for (const CTxIn &txin : tx.vin) {
auto it = mapNextTx.find(txin.prevout);
if (it != mapNextTx.end()) {
const CTransaction &txConflict = *it->second;
@@ -642,7 +642,7 @@ void CTxMemPool::check(const CCoinsViewCache *pcoins) const
setEntries setParentCheck;
int64_t parentSizes = 0;
int64_t parentSigOpCost = 0;
- BOOST_FOREACH(const CTxIn &txin, tx.vin) {
+ for (const CTxIn &txin : tx.vin) {
// Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end()) {
@@ -674,7 +674,7 @@ void CTxMemPool::check(const CCoinsViewCache *pcoins) const
CAmount nFeesCheck = it->GetModifiedFee();
int64_t nSigOpCheck = it->GetSigOpCost();
- BOOST_FOREACH(txiter ancestorIt, setAncestors) {
+ for (txiter ancestorIt : setAncestors) {
nSizeCheck += ancestorIt->GetTxSize();
nFeesCheck += ancestorIt->GetModifiedFee();
nSigOpCheck += ancestorIt->GetSigOpCost();
@@ -848,14 +848,14 @@ void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeD
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
- BOOST_FOREACH(txiter ancestorIt, setAncestors) {
+ for (txiter ancestorIt : setAncestors) {
mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
}
// Now update all descendants' modified fees with ancestors
setEntries setDescendants;
CalculateDescendants(it, setDescendants);
setDescendants.erase(it);
- BOOST_FOREACH(txiter descendantIt, setDescendants) {
+ for (txiter descendantIt : setDescendants) {
mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
}
++nTransactionsUpdated;
@@ -919,7 +919,7 @@ size_t CTxMemPool::DynamicMemoryUsage() const {
void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
AssertLockHeld(cs);
UpdateForRemoveFromMempool(stage, updateDescendants);
- BOOST_FOREACH(const txiter& it, stage) {
+ for (const txiter& it : stage) {
removeUnchecked(it, reason);
}
}
@@ -933,7 +933,7 @@ int CTxMemPool::Expire(int64_t time) {
it++;
}
setEntries stage;
- BOOST_FOREACH(txiter removeit, toremove) {
+ for (txiter removeit : toremove) {
CalculateDescendants(removeit, stage);
}
RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
@@ -1042,17 +1042,15 @@ void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpends
std::vector<CTransaction> txn;
if (pvNoSpendsRemaining) {
txn.reserve(stage.size());
- BOOST_FOREACH(txiter iter, stage)
+ for (txiter iter : stage)
txn.push_back(iter->GetTx());
}
RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
if (pvNoSpendsRemaining) {
- BOOST_FOREACH(const CTransaction& tx, txn) {
- BOOST_FOREACH(const CTxIn& txin, tx.vin) {
+ for (const CTransaction& tx : txn) {
+ for (const CTxIn& txin : tx.vin) {
if (exists(txin.prevout.hash)) continue;
- if (!mapNextTx.count(txin.prevout)) {
- pvNoSpendsRemaining->push_back(txin.prevout);
- }
+ pvNoSpendsRemaining->push_back(txin.prevout);
}
}
}
diff --git a/src/util.cpp b/src/util.cpp
index 0a14e8bb9e..20a8082017 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -651,21 +651,21 @@ bool RenameOver(fs::path src, fs::path dest)
}
/**
- * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
+ * Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
* Specifically handles case where path p exists, but it wasn't possible for the user to
* write to the parent directory.
*/
-bool TryCreateDirectory(const fs::path& p)
+bool TryCreateDirectories(const fs::path& p)
{
try
{
- return fs::create_directory(p);
+ return fs::create_directories(p);
} catch (const fs::filesystem_error&) {
if (!fs::exists(p) || !fs::is_directory(p))
throw;
}
- // create_directory didn't create the directory, it had to have existed already
+ // create_directories didn't create the directory, it had to have existed already
return false;
}
diff --git a/src/util.h b/src/util.h
index 8f8b249749..a4d7aa4db8 100644
--- a/src/util.h
+++ b/src/util.h
@@ -122,6 +122,17 @@ int LogPrintStr(const std::string &str);
/** Get format string from VA_ARGS for error reporting */
template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
+static inline void MarkUsed() {}
+template<typename T, typename... Args> static inline void MarkUsed(const T& t, const Args&... args)
+{
+ (void)t;
+ MarkUsed(args...);
+}
+
+#ifdef USE_COVERAGE
+#define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
+#define LogPrint(category, ...) do { MarkUsed(__VA_ARGS__); } while(0)
+#else
#define LogPrintf(...) do { \
std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
try { \
@@ -138,6 +149,7 @@ template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt,
LogPrintf(__VA_ARGS__); \
} \
} while(0)
+#endif
template<typename... Args>
bool error(const char* fmt, const Args&... args)
@@ -152,7 +164,7 @@ bool TruncateFile(FILE *file, unsigned int length);
int RaiseFileDescriptorLimit(int nMinFD);
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
bool RenameOver(fs::path src, fs::path dest);
-bool TryCreateDirectory(const fs::path& p);
+bool TryCreateDirectories(const fs::path& p);
fs::path GetDefaultDataDir();
const fs::path &GetDataDir(bool fNetSpecific = true);
void ClearDatadirCache();
@@ -187,62 +199,63 @@ public:
void ParseParameters(int argc, const char*const argv[]);
void ReadConfigFile(const std::string& confPath);
std::vector<std::string> GetArgs(const std::string& strArg);
-/**
- * Return true if the given argument has been manually set
- *
- * @param strArg Argument to get (e.g. "-foo")
- * @return true if the argument has been set
- */
-bool IsArgSet(const std::string& strArg);
-
-/**
- * Return string argument or default value
- *
- * @param strArg Argument to get (e.g. "-foo")
- * @param default (e.g. "1")
- * @return command-line argument or default value
- */
-std::string GetArg(const std::string& strArg, const std::string& strDefault);
-
-/**
- * Return integer argument or default value
- *
- * @param strArg Argument to get (e.g. "-foo")
- * @param default (e.g. 1)
- * @return command-line argument (0 if invalid number) or default value
- */
-int64_t GetArg(const std::string& strArg, int64_t nDefault);
-
-/**
- * Return boolean argument or default value
- *
- * @param strArg Argument to get (e.g. "-foo")
- * @param default (true or false)
- * @return command-line argument or default value
- */
-bool GetBoolArg(const std::string& strArg, bool fDefault);
-
-/**
- * Set an argument if it doesn't already have a value
- *
- * @param strArg Argument to set (e.g. "-foo")
- * @param strValue Value (e.g. "1")
- * @return true if argument gets set, false if it already had a value
- */
-bool SoftSetArg(const std::string& strArg, const std::string& strValue);
-
-/**
- * Set a boolean argument if it doesn't already have a value
- *
- * @param strArg Argument to set (e.g. "-foo")
- * @param fValue Value (e.g. false)
- * @return true if argument gets set, false if it already had a value
- */
-bool SoftSetBoolArg(const std::string& strArg, bool fValue);
-// Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
-// been set. Also called directly in testing.
-void ForceSetArg(const std::string& strArg, const std::string& strValue);
+ /**
+ * Return true if the given argument has been manually set
+ *
+ * @param strArg Argument to get (e.g. "-foo")
+ * @return true if the argument has been set
+ */
+ bool IsArgSet(const std::string& strArg);
+
+ /**
+ * Return string argument or default value
+ *
+ * @param strArg Argument to get (e.g. "-foo")
+ * @param default (e.g. "1")
+ * @return command-line argument or default value
+ */
+ std::string GetArg(const std::string& strArg, const std::string& strDefault);
+
+ /**
+ * Return integer argument or default value
+ *
+ * @param strArg Argument to get (e.g. "-foo")
+ * @param default (e.g. 1)
+ * @return command-line argument (0 if invalid number) or default value
+ */
+ int64_t GetArg(const std::string& strArg, int64_t nDefault);
+
+ /**
+ * Return boolean argument or default value
+ *
+ * @param strArg Argument to get (e.g. "-foo")
+ * @param default (true or false)
+ * @return command-line argument or default value
+ */
+ bool GetBoolArg(const std::string& strArg, bool fDefault);
+
+ /**
+ * Set an argument if it doesn't already have a value
+ *
+ * @param strArg Argument to set (e.g. "-foo")
+ * @param strValue Value (e.g. "1")
+ * @return true if argument gets set, false if it already had a value
+ */
+ bool SoftSetArg(const std::string& strArg, const std::string& strValue);
+
+ /**
+ * Set a boolean argument if it doesn't already have a value
+ *
+ * @param strArg Argument to set (e.g. "-foo")
+ * @param fValue Value (e.g. false)
+ * @return true if argument gets set, false if it already had a value
+ */
+ bool SoftSetBoolArg(const std::string& strArg, bool fValue);
+
+ // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
+ // been set. Also called directly in testing.
+ void ForceSetArg(const std::string& strArg, const std::string& strValue);
};
extern ArgsManager gArgs;
diff --git a/src/utilstrencodings.cpp b/src/utilstrencodings.cpp
index 74bf66fbf6..93abaec04b 100644
--- a/src/utilstrencodings.cpp
+++ b/src/utilstrencodings.cpp
@@ -437,7 +437,7 @@ bool ParseInt32(const std::string& str, int32_t *out)
errno = 0; // strtol will not set errno if valid
long int n = strtol(str.c_str(), &endp, 10);
if(out) *out = (int32_t)n;
- // Note that strtol returns a *long int*, so even if strtol doesn't report a over/underflow
+ // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
// platforms the size of these types may be different.
return endp && *endp == 0 && !errno &&
@@ -453,7 +453,7 @@ bool ParseInt64(const std::string& str, int64_t *out)
errno = 0; // strtoll will not set errno if valid
long long int n = strtoll(str.c_str(), &endp, 10);
if(out) *out = (int64_t)n;
- // Note that strtoll returns a *long long int*, so even if strtol doesn't report a over/underflow
+ // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *int64_t*.
return endp && *endp == 0 && !errno &&
n >= std::numeric_limits<int64_t>::min() &&
@@ -470,7 +470,7 @@ bool ParseUInt32(const std::string& str, uint32_t *out)
errno = 0; // strtoul will not set errno if valid
unsigned long int n = strtoul(str.c_str(), &endp, 10);
if(out) *out = (uint32_t)n;
- // Note that strtoul returns a *unsigned long int*, so even if it doesn't report a over/underflow
+ // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
// platforms the size of these types may be different.
return endp && *endp == 0 && !errno &&
@@ -487,7 +487,7 @@ bool ParseUInt64(const std::string& str, uint64_t *out)
errno = 0; // strtoull will not set errno if valid
unsigned long long int n = strtoull(str.c_str(), &endp, 10);
if(out) *out = (uint64_t)n;
- // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report a over/underflow
+ // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *uint64_t*.
return endp && *endp == 0 && !errno &&
n <= std::numeric_limits<uint64_t>::max();
diff --git a/src/utilstrencodings.h b/src/utilstrencodings.h
index e2a1b9bef9..8b37fe12e0 100644
--- a/src/utilstrencodings.h
+++ b/src/utilstrencodings.h
@@ -19,9 +19,6 @@
#define UEND(a) ((unsigned char*)&((&(a))[1]))
#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
-/** This is needed because the foreach macro can't get over the comma in pair<t1, t2> */
-#define PAIRTYPE(t1, t2) std::pair<t1, t2>
-
/** Used by SanitizeString() */
enum SafeChars
{
diff --git a/src/validation.cpp b/src/validation.cpp
index 9350735bab..59542e8f98 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -159,7 +159,7 @@ namespace {
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
// Find the first block the caller has in the main chain
- BOOST_FOREACH(const uint256& hash, locator.vHave) {
+ for (const uint256& hash : locator.vHave) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
@@ -300,7 +300,7 @@ bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool
// lock on a mempool input, so we can use the return value of
// CheckSequenceLocks to indicate the LockPoints validity
int maxInputHeight = 0;
- BOOST_FOREACH(int height, prevheights) {
+ for (int height : prevheights) {
// Can ignore mempool inputs since we'll fail if they had non-zero locks
if (height != tip->nHeight+1) {
maxInputHeight = std::max(maxInputHeight, height);
@@ -320,7 +320,7 @@ static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age)
std::vector<COutPoint> vNoSpendsRemaining;
pool.TrimToSize(limit, &vNoSpendsRemaining);
- BOOST_FOREACH(const COutPoint& removed, vNoSpendsRemaining)
+ for (const COutPoint& removed : vNoSpendsRemaining)
pcoinsTip->Uncache(removed);
}
@@ -430,14 +430,15 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
// is it already in the memory pool?
- if (pool.exists(hash))
- return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
+ if (pool.exists(hash)) {
+ return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
+ }
// Check for conflicts with in-memory transactions
std::set<uint256> setConflicts;
{
LOCK(pool.cs); // protect pool.mapNextTx
- BOOST_FOREACH(const CTxIn &txin, tx.vin)
+ for (const CTxIn &txin : tx.vin)
{
auto itConflicting = pool.mapNextTx.find(txin.prevout);
if (itConflicting != pool.mapNextTx.end())
@@ -460,7 +461,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
bool fReplacementOptOut = true;
if (fEnableReplacement)
{
- BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
+ for (const CTxIn &_txin : ptxConflicting->vin)
{
if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
{
@@ -469,8 +470,9 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
}
}
}
- if (fReplacementOptOut)
- return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
+ if (fReplacementOptOut) {
+ return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
+ }
setConflicts.insert(ptxConflicting->GetHash());
}
@@ -497,12 +499,12 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
if (!had_coin_in_cache) {
coins_to_uncache.push_back(outpoint);
}
- return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
+ return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
}
}
// do all inputs exist?
- BOOST_FOREACH(const CTxIn txin, tx.vin) {
+ for (const CTxIn txin : tx.vin) {
if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
coins_to_uncache.push_back(txin.prevout);
}
@@ -550,7 +552,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// Keep track of transactions that spend a coinbase, which we re-scan
// during reorgs to ensure COINBASE_MATURITY is still met.
bool fSpendsCoinbase = false;
- BOOST_FOREACH(const CTxIn &txin, tx.vin) {
+ for (const CTxIn &txin : tx.vin) {
const Coin &coin = view.AccessCoin(txin.prevout);
if (coin.IsCoinBase()) {
fSpendsCoinbase = true;
@@ -601,7 +603,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
// that we have the set of all ancestors we can detect this
// pathological case by making sure setConflicts and setAncestors don't
// intersect.
- BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
+ for (CTxMemPool::txiter ancestorIt : setAncestors)
{
const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
if (setConflicts.count(hashAncestor))
@@ -632,7 +634,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
std::set<uint256> setConflictsParents;
const int maxDescendantsToVisit = 100;
CTxMemPool::setEntries setIterConflicting;
- BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
+ for (const uint256 &hashConflicting : setConflicts)
{
CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
if (mi == pool.mapTx.end())
@@ -668,7 +670,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
oldFeeRate.ToString()));
}
- BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
+ for (const CTxIn &txin : mi->GetTx().vin)
{
setConflictsParents.insert(txin.prevout.hash);
}
@@ -681,10 +683,10 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
if (nConflictingCount <= maxDescendantsToVisit) {
// If not too many to replace, then calculate the set of
// transactions that would have to be evicted
- BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
+ for (CTxMemPool::txiter it : setIterConflicting) {
pool.CalculateDescendants(it, allConflicting);
}
- BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
+ for (CTxMemPool::txiter it : allConflicting) {
nConflictingFees += it->GetModifiedFee();
nConflictingSize += it->GetTxSize();
}
@@ -778,7 +780,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool
}
// Remove conflicting transactions from the mempool
- BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
+ for (const CTxMemPool::txiter it : allConflicting)
{
LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
it->GetTx().GetHash().ToString(),
@@ -820,7 +822,7 @@ static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPo
std::vector<COutPoint> coins_to_uncache;
bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache);
if (!res) {
- BOOST_FOREACH(const COutPoint& hashTx, coins_to_uncache)
+ for (const COutPoint& hashTx : coins_to_uncache)
pcoinsTip->Uncache(hashTx);
}
// After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
@@ -1121,9 +1123,10 @@ void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txund
// mark inputs spent
if (!tx.IsCoinBase()) {
txundo.vprevout.reserve(tx.vin.size());
- BOOST_FOREACH(const CTxIn &txin, tx.vin) {
+ for (const CTxIn &txin : tx.vin) {
txundo.vprevout.emplace_back();
- inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
+ bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
+ assert(is_spent);
}
}
// add outputs
@@ -1206,7 +1209,7 @@ static bool CheckInputs(const CTransaction& tx, CValidationState &state, const C
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// Failures of other flags indicate a transaction that is
- // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
+ // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
@@ -1368,8 +1371,8 @@ static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex*
if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
COutPoint out(hash, o);
Coin coin;
- view.SpendCoin(out, &coin);
- if (tx.vout[o] != coin.out) {
+ bool is_spent = view.SpendCoin(out, &coin);
+ if (!is_spent || tx.vout[o] != coin.out) {
fClean = false; // transaction output mismatch
}
}
@@ -3111,7 +3114,7 @@ bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams,
static uint64_t CalculateCurrentUsage()
{
uint64_t retval = 0;
- BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
+ for (const CBlockFileInfo &file : vinfoBlockFile) {
retval += file.nSize + file.nUndoSize;
}
return retval;
@@ -3330,13 +3333,13 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams)
// Calculate nChainWork
std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
- BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
+ for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
- BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
+ for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
@@ -3385,7 +3388,7 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams)
// Check presence of blk files
LogPrintf("Checking all blk files are present...\n");
std::set<int> setBlkDataFiles;
- BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
+ for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
{
CBlockIndex* pindex = item.second;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
@@ -3641,7 +3644,7 @@ void UnloadBlockIndex()
warningcache[b].clear();
}
- BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
+ for (BlockMap::value_type& entry : mapBlockIndex) {
delete entry.second;
}
mapBlockIndex.clear();
diff --git a/src/validation.h b/src/validation.h
index 15e19bc511..82df4cb170 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -469,10 +469,6 @@ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Para
static const unsigned int REJECT_INTERNAL = 0x100;
/** Too high fee. Can not be triggered by P2P transactions */
static const unsigned int REJECT_HIGHFEE = 0x100;
-/** Transaction is already known (either in mempool or blockchain) */
-static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
-/** Transaction conflicts with a transaction already known */
-static const unsigned int REJECT_CONFLICT = 0x102;
/** Get block file info entry for one block file */
CBlockFileInfo* GetBlockFileInfo(size_t n);
diff --git a/src/wallet/crypter.cpp b/src/wallet/crypter.cpp
index fc318c1612..6fa685628f 100644
--- a/src/wallet/crypter.cpp
+++ b/src/wallet/crypter.cpp
@@ -274,7 +274,6 @@ bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) co
// Check for watch-only pubkeys
return CBasicKeyStore::GetPubKey(address, vchPubKeyOut);
}
- return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
@@ -285,7 +284,7 @@ bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
return false;
fUseCrypto = true;
- BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
+ for (KeyMap::value_type& mKey : mapKeys)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp
index 74b82a8616..c8928a3b66 100644
--- a/src/wallet/db.cpp
+++ b/src/wallet/db.cpp
@@ -74,7 +74,7 @@ bool CDBEnv::Open(const fs::path& pathIn)
strPath = pathIn.string();
fs::path pathLogDir = pathIn / "database";
- TryCreateDirectory(pathLogDir);
+ TryCreateDirectories(pathLogDir);
fs::path pathErrorFile = pathIn / "db.log";
LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
@@ -204,7 +204,7 @@ bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*reco
}
DbTxn* ptxn = bitdb.TxnBegin();
- BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
+ for (CDBEnv::KeyValPair& row : salvagedData)
{
if (recoverKVcallback)
{
diff --git a/src/wallet/feebumper.cpp b/src/wallet/feebumper.cpp
index 46ef87b7b1..6a9e6cf9ff 100644
--- a/src/wallet/feebumper.cpp
+++ b/src/wallet/feebumper.cpp
@@ -165,7 +165,7 @@ CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, int newConf
nNewFee = totalFee;
nNewFeeRate = CFeeRate(totalFee, maxNewTxSize);
} else {
- nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, ::feeEstimator, ignoreGlobalPayTxFee);
+ nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, ::feeEstimator, nullptr, ignoreGlobalPayTxFee);
nNewFeeRate = CFeeRate(nNewFee, maxNewTxSize);
// New fee rate must be at least old rate + minimum incremental relay rate
diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp
index e771ce9bb3..09aaf4f747 100644
--- a/src/wallet/rpcdump.cpp
+++ b/src/wallet/rpcdump.cpp
@@ -47,7 +47,7 @@ int64_t static DecodeDumpTime(const std::string &str) {
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
- BOOST_FOREACH(unsigned char c, str) {
+ for (unsigned char c : str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
@@ -1049,7 +1049,7 @@ UniValue importmulti(const JSONRPCRequest& mainRequest)
" \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
" \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
" \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
- " \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be be treated as not incoming payments\n"
+ " \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be treated as not incoming payments\n"
" \"watchonly\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be considered watched even when they're not spendable, only allowed if keys are empty\n"
" \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
" }\n"
@@ -1105,7 +1105,7 @@ UniValue importmulti(const JSONRPCRequest& mainRequest)
UniValue response(UniValue::VARR);
- BOOST_FOREACH (const UniValue& data, requests.getValues()) {
+ for (const UniValue& data : requests.getValues()) {
const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
const UniValue result = ProcessImport(pwallet, data, timestamp);
response.push_back(result);
diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp
index 4b8a8b81e4..5bbb5088e2 100644
--- a/src/wallet/rpcwallet.cpp
+++ b/src/wallet/rpcwallet.cpp
@@ -77,7 +77,7 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
- BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
+ for (const uint256& conflict : wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
@@ -95,7 +95,7 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
}
entry.push_back(Pair("bip125-replaceable", rbfStatus));
- BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, wtx.mapValue)
+ for (const std::pair<std::string, std::string>& item : wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
@@ -489,7 +489,7 @@ UniValue listaddressgroupings(const JSONRPCRequest& request)
std::map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances();
for (std::set<CTxDestination> grouping : pwallet->GetAddressGroupings()) {
UniValue jsonGrouping(UniValue::VARR);
- BOOST_FOREACH(CTxDestination address, grouping)
+ for (CTxDestination address : grouping)
{
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CBitcoinAddress(address).ToString());
@@ -615,7 +615,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request)
if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
continue;
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
@@ -670,7 +670,7 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request)
if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
continue;
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwallet, address) && setAddress.count(address)) {
@@ -949,7 +949,7 @@ UniValue sendmany(const JSONRPCRequest& request)
CAmount totalAmount = 0;
std::vector<std::string> keys = sendTo.getKeys();
- BOOST_FOREACH(const std::string& name_, keys)
+ for (const std::string& name_ : keys)
{
CBitcoinAddress address(name_);
if (!address.IsValid())
@@ -1064,7 +1064,6 @@ public:
bool operator()(const CNoDestination &dest) const { return false; }
bool operator()(const CKeyID &keyID) {
- CPubKey pubkey;
if (pwallet) {
CScript basescript = GetScriptForDestination(keyID);
isminetype typ;
@@ -1190,7 +1189,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
if (nDepth < nMinDepth)
continue;
- BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout)
+ for (const CTxOut& txout : wtx.tx->vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
@@ -1250,7 +1249,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
- BOOST_FOREACH(const uint256& _item, (*it).second.txids)
+ for (const uint256& _item : (*it).second.txids)
{
transactions.push_back(_item.GetHex());
}
@@ -1384,7 +1383,7 @@ void ListTransactions(CWallet* const pwallet, const CWalletTx& wtx, const std::s
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
- BOOST_FOREACH(const COutputEntry& s, listSent)
+ for (const COutputEntry& s : listSent)
{
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwallet, s.destination) & ISMINE_WATCH_ONLY)) {
@@ -1409,7 +1408,7 @@ void ListTransactions(CWallet* const pwallet, const CWalletTx& wtx, const std::s
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
- BOOST_FOREACH(const COutputEntry& r, listReceived)
+ for (const COutputEntry& r : listReceived)
{
std::string account;
if (pwallet->mapAddressBook.count(r.destination)) {
@@ -1654,11 +1653,11 @@ UniValue listaccounts(const JSONRPCRequest& request)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
- BOOST_FOREACH(const COutputEntry& s, listSent)
+ for (const COutputEntry& s : listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth)
{
- BOOST_FOREACH(const COutputEntry& r, listReceived)
+ for (const COutputEntry& r : listReceived)
if (pwallet->mapAddressBook.count(r.destination)) {
mapAccountBalances[pwallet->mapAddressBook[r.destination].name] += r.amount;
}
@@ -1668,11 +1667,11 @@ UniValue listaccounts(const JSONRPCRequest& request)
}
const std::list<CAccountingEntry>& acentries = pwallet->laccentries;
- BOOST_FOREACH(const CAccountingEntry& entry, acentries)
+ for (const CAccountingEntry& entry : acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
- BOOST_FOREACH(const PAIRTYPE(std::string, CAmount)& accountBalance, mapAccountBalances) {
+ for (const std::pair<std::string, CAmount>& accountBalance : mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
@@ -2337,7 +2336,7 @@ UniValue listlockunspent(const JSONRPCRequest& request)
UniValue ret(UniValue::VARR);
- BOOST_FOREACH(COutPoint &outpt, vOutpts) {
+ for (COutPoint &outpt : vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
@@ -2455,7 +2454,7 @@ UniValue resendwallettransactions(const JSONRPCRequest& request)
std::vector<uint256> txids = pwallet->ResendWalletTransactionsBefore(GetTime(), g_connman.get());
UniValue result(UniValue::VARR);
- BOOST_FOREACH(const uint256& txid, txids)
+ for (const uint256& txid : txids)
{
result.push_back(txid.ToString());
}
@@ -2580,7 +2579,7 @@ UniValue listunspent(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet);
pwallet->AvailableCoins(vecOutputs, !include_unsafe, NULL, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
- BOOST_FOREACH(const COutput& out, vecOutputs) {
+ for (const COutput& out : vecOutputs) {
CTxDestination address;
const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, address);
diff --git a/src/wallet/test/accounting_tests.cpp b/src/wallet/test/accounting_tests.cpp
index 1fe633f2e5..12d9f2e995 100644
--- a/src/wallet/test/accounting_tests.cpp
+++ b/src/wallet/test/accounting_tests.cpp
@@ -23,7 +23,7 @@ GetResults(std::map<CAmount, CAccountingEntry>& results)
results.clear();
BOOST_CHECK(pwalletMain->ReorderTransactions() == DB_LOAD_OK);
pwalletMain->ListAccountCreditDebit("", aes);
- BOOST_FOREACH(CAccountingEntry& ae, aes)
+ for (CAccountingEntry& ae : aes)
{
results[ae.nOrderPos] = ae;
}
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index eb6de4870f..f07a6cb5a5 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -205,7 +205,6 @@ bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
- return false;
}
bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
@@ -297,7 +296,7 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
LOCK(cs_wallet);
- BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
+ for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
@@ -320,7 +319,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase,
CCrypter crypter;
CKeyingMaterial _vMasterKey;
- BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
+ for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
@@ -412,7 +411,7 @@ std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
@@ -554,7 +553,7 @@ void CWallet::AddToSpends(const uint256& wtxid)
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
- BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
+ for (const CTxIn& txin : thisTx.tx->vin)
AddToSpends(txin.prevout, wtxid);
}
@@ -669,7 +668,7 @@ DBErrors CWallet::ReorderTransactions()
}
std::list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit("", acentries);
- BOOST_FOREACH(CAccountingEntry& entry, acentries)
+ for (CAccountingEntry& entry : acentries)
{
txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
@@ -699,7 +698,7 @@ DBErrors CWallet::ReorderTransactions()
else
{
int64_t nOrderPosOff = 0;
- BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
+ for (const int64_t& nOffsetStart : nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
@@ -788,7 +787,7 @@ bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bFo
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && account.vchPubKey.IsValid();
++it)
- BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
+ for (const CTxOut& txout : (*it).second.tx->vout)
if (txout.scriptPubKey == scriptPubKey) {
bForceNew = true;
break;
@@ -814,7 +813,7 @@ void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
- BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
+ for (std::pair<const uint256, CWalletTx>& item : mapWallet)
item.second.MarkDirty();
}
}
@@ -932,7 +931,7 @@ bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
wtx.BindWallet(this);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
AddToSpends(hash);
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
+ for (const CTxIn& txin : wtx.tx->vin) {
if (mapWallet.count(txin.prevout.hash)) {
CWalletTx& prevtx = mapWallet[txin.prevout.hash];
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
@@ -964,7 +963,7 @@ bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockI
AssertLockHeld(cs_wallet);
if (pIndex != NULL) {
- BOOST_FOREACH(const CTxIn& txin, tx.vin) {
+ for (const CTxIn& txin : tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
@@ -1045,7 +1044,7 @@ bool CWallet::AbandonTransaction(const uint256& hashTx)
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
@@ -1106,7 +1105,7 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
@@ -1124,7 +1123,7 @@ void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pin
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
@@ -1240,7 +1239,7 @@ CAmount CWallet::GetChange(const CTxOut& txout) const
bool CWallet::IsMine(const CTransaction& tx) const
{
- BOOST_FOREACH(const CTxOut& txout, tx.vout)
+ for (const CTxOut& txout : tx.vout)
if (IsMine(txout))
return true;
return false;
@@ -1254,7 +1253,7 @@ bool CWallet::IsFromMe(const CTransaction& tx) const
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
@@ -1267,7 +1266,7 @@ bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) co
{
LOCK(cs_wallet);
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
@@ -1287,7 +1286,7 @@ bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) co
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
- BOOST_FOREACH(const CTxOut& txout, tx.vout)
+ for (const CTxOut& txout : tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
@@ -1299,7 +1298,7 @@ CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) c
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
- BOOST_FOREACH(const CTxOut& txout, tx.vout)
+ for (const CTxOut& txout : tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
@@ -1535,7 +1534,7 @@ void CWallet::ReacceptWalletTransactions()
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
- BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
+ for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
@@ -1549,7 +1548,7 @@ void CWallet::ReacceptWalletTransactions()
}
// Try to add wallet transactions to memory pool
- BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
+ for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *(item.second);
@@ -1777,7 +1776,7 @@ bool CWalletTx::IsTrusted() const
return false;
// Trusted if all inputs are from us and are in the mempool:
- BOOST_FOREACH(const CTxIn& txin, tx->vin)
+ for (const CTxIn& txin : tx->vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
@@ -1806,7 +1805,7 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CCon
LOCK(cs_wallet);
// Sort them in chronological order
std::multimap<unsigned int, CWalletTx*> mapSorted;
- BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
+ for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
@@ -1814,7 +1813,7 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CCon
continue;
mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
}
- BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
+ for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.RelayWalletTransaction(connman))
@@ -2238,7 +2237,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMin
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
- BOOST_FOREACH(const COutput &output, vCoins)
+ for (const COutput &output : vCoins)
{
if (!output.fSpendable)
continue;
@@ -2338,7 +2337,7 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
{
- BOOST_FOREACH(const COutput& out, vCoins)
+ for (const COutput& out : vCoins)
{
if (!out.fSpendable)
continue;
@@ -2355,7 +2354,7 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
std::vector<COutPoint> vPresetInputs;
if (coinControl)
coinControl->ListSelected(vPresetInputs);
- BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
+ for (const COutPoint& outpoint : vPresetInputs)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
@@ -2438,7 +2437,7 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
coinControl.fAllowOtherInputs = true;
- BOOST_FOREACH(const CTxIn& txin, tx.vin)
+ for (const CTxIn& txin : tx.vin)
coinControl.Select(txin.prevout);
CReserveKey reservekey(this);
@@ -2454,7 +2453,7 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nC
tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
// Add new txins (keeping original txin scriptSig/order)
- BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
+ for (const CTxIn& txin : wtx.tx->vin)
{
if (!coinControl.IsSelected(txin.prevout))
{
@@ -2534,7 +2533,8 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
-
+ FeeCalculation feeCalc;
+ unsigned int nBytes;
{
std::set<CInputCoin> setCoins;
LOCK2(cs_main, cs_wallet);
@@ -2633,28 +2633,6 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
CTxOut newTxOut(nChange, scriptChange);
- // We do not move dust-change to fees, because the sender would end up paying more than requested.
- // This would be against the purpose of the all-inclusive feature.
- // So instead we raise the change and deduct from the recipient.
- if (nSubtractFeeFromAmount > 0 && IsDust(newTxOut, ::dustRelayFee))
- {
- CAmount nDust = GetDustThreshold(newTxOut, ::dustRelayFee) - newTxOut.nValue;
- newTxOut.nValue += nDust; // raise change until no more dust
- for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
- {
- if (vecSend[i].fSubtractFeeFromAmount)
- {
- txNew.vout[i].nValue -= nDust;
- if (IsDust(txNew.vout[i], ::dustRelayFee))
- {
- strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
- return false;
- }
- break;
- }
- }
- }
-
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (IsDust(newTxOut, ::dustRelayFee))
@@ -2706,9 +2684,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
return false;
}
- unsigned int nBytes = GetVirtualTransactionSize(txNew);
-
- CTransaction txNewConst(txNew);
+ nBytes = GetVirtualTransactionSize(txNew);
// Remove scriptSigs to eliminate the fee calculation dummy signatures
for (auto& vin : txNew.vin) {
@@ -2721,7 +2697,7 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
if (coinControl && coinControl->nConfirmTarget > 0)
currentConfirmationTarget = coinControl->nConfirmTarget;
- CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator);
+ CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator, &feeCalc);
if (coinControl && coinControl->fOverrideFeeRate)
nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
@@ -2818,6 +2794,15 @@ bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletT
return false;
}
}
+
+ LogPrintf("Fee Calculation: Fee:%d Bytes:%u Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
+ nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
+ feeCalc.est.pass.start, feeCalc.est.pass.end,
+ 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
+ feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
+ feeCalc.est.fail.start, feeCalc.est.fail.end,
+ 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
+ feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
return true;
}
@@ -2838,7 +2823,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CCon
AddToWallet(wtxNew);
// Notify that old coins are spent
- BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
+ for (const CTxIn& txin : wtxNew.tx->vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
@@ -2893,23 +2878,32 @@ CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
}
-CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee)
+CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc, bool ignoreGlobalPayTxFee)
{
// payTxFee is the user-set global for desired feerate
CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
// User didn't set: use -txconfirmtarget to estimate...
if (nFeeNeeded == 0 || ignoreGlobalPayTxFee) {
- int estimateFoundTarget = nConfirmTarget;
- nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, &estimateFoundTarget, pool).GetFee(nTxBytes);
+ nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, feeCalc, pool, true).GetFee(nTxBytes);
// ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
- if (nFeeNeeded == 0)
+ if (nFeeNeeded == 0) {
nFeeNeeded = fallbackFee.GetFee(nTxBytes);
+ if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
+ }
+ } else {
+ if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
}
// prevent user from paying a fee below minRelayTxFee or minTxFee
- nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
+ CAmount requiredFee = GetRequiredFee(nTxBytes);
+ if (requiredFee > nFeeNeeded) {
+ nFeeNeeded = requiredFee;
+ if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
+ }
// But always obey the maximum
- if (nFeeNeeded > maxTxFee)
+ if (nFeeNeeded > maxTxFee) {
nFeeNeeded = maxTxFee;
+ if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
+ }
return nFeeNeeded;
}
@@ -3017,7 +3011,7 @@ bool CWallet::DelAddressBook(const CTxDestination& address)
// Delete destdata tuples associated with address
std::string strAddress = CBitcoinAddress(address).ToString();
- BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
+ for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
{
CWalletDB(*dbw).EraseDestData(strAddress, item.first);
}
@@ -3062,7 +3056,7 @@ bool CWallet::NewKeyPool()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
- BOOST_FOREACH(int64_t nIndex, setKeyPool)
+ for (int64_t nIndex : setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
@@ -3312,7 +3306,7 @@ std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
{
bool any_mine = false;
// group all input addresses with each other
- BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
+ for (CTxIn txin : pcoin->tx->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
@@ -3326,7 +3320,7 @@ std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
// group change with input addresses
if (any_mine)
{
- BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
+ for (CTxOut txout : pcoin->tx->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
@@ -3357,18 +3351,18 @@ std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
- BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
+ for (std::set<CTxDestination> _grouping : groupings)
{
// make a set of all the groups hit by this new group
std::set< std::set<CTxDestination>* > hits;
std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
- BOOST_FOREACH(CTxDestination address, _grouping)
+ for (CTxDestination address : _grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
- BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
+ for (std::set<CTxDestination>* hit : hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
@@ -3377,12 +3371,12 @@ std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
uniqueGroupings.insert(merged);
// update setmap
- BOOST_FOREACH(CTxDestination element, *merged)
+ for (CTxDestination element : *merged)
setmap[element] = merged;
}
std::set< std::set<CTxDestination> > ret;
- BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
+ for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
@@ -3395,7 +3389,7 @@ std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAcco
{
LOCK(cs_wallet);
std::set<CTxDestination> result;
- BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
+ for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
{
const CTxDestination& address = item.first;
const std::string& strName = item.second.name;
@@ -3445,7 +3439,7 @@ void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
CWalletDB walletdb(*dbw);
LOCK2(cs_main, cs_wallet);
- BOOST_FOREACH(const int64_t& id, setKeyPool)
+ for (const int64_t& id : setKeyPool)
{
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
@@ -3520,7 +3514,7 @@ public:
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
- BOOST_FOREACH(const CTxDestination &dest, vDest)
+ for (const CTxDestination &dest : vDest)
boost::apply_visitor(*this, dest);
}
}
@@ -3555,7 +3549,7 @@ void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) c
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys;
GetKeys(setKeys);
- BOOST_FOREACH(const CKeyID &keyid, setKeys) {
+ for (const CKeyID &keyid : setKeys) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
@@ -3574,10 +3568,10 @@ void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) c
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
- BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
+ for (const CTxOut &txout : wtx.tx->vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
- BOOST_FOREACH(const CKeyID &keyid, vAffected) {
+ for (const CKeyID &keyid : vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
@@ -3847,11 +3841,11 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
else if (IsArgSet("-usehd")) {
bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
if (walletInstance->IsHDEnabled() && !useHD) {
- InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
+ InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
return NULL;
}
if (!walletInstance->IsHDEnabled() && useHD) {
- InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
+ InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
return NULL;
}
}
@@ -3871,7 +3865,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
//We can't rescan beyond non-pruned blocks, stop and throw an error
- //this might happen if a user uses a old wallet within a pruned node
+ //this might happen if a user uses an old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fPruneMode)
{
@@ -3898,7 +3892,7 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
{
CWalletDB walletdb(*walletInstance->dbw);
- BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
+ for (const CWalletTx& wtxOld : vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h
index 6c6eb69180..ad606b8535 100644
--- a/src/wallet/wallet.h
+++ b/src/wallet/wallet.h
@@ -77,6 +77,7 @@ class CScheduler;
class CTxMemPool;
class CBlockPolicyEstimator;
class CWalletTx;
+struct FeeCalculation;
/** (client) version numbers for particular wallet features */
enum WalletFeature
@@ -959,7 +960,7 @@ public:
* Estimate the minimum fee considering user set parameters
* and the required fee
*/
- static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee = false);
+ static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc = nullptr, bool ignoreGlobalPayTxFee = false);
/**
* Return the minimum required fee taking into account the
* floating relay fee and user set minimum transaction fee
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
index 7731fa5631..8321719b56 100644
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -76,8 +76,6 @@ bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
- const bool fEraseUnencryptedKey = true;
-
if (!WriteIC(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta)) {
return false;
}
@@ -85,12 +83,8 @@ bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
if (!WriteIC(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false)) {
return false;
}
- if (fEraseUnencryptedKey)
- {
- EraseIC(std::make_pair(std::string("key"), vchPubKey));
- EraseIC(std::make_pair(std::string("wkey"), vchPubKey));
- }
-
+ EraseIC(std::make_pair(std::string("key"), vchPubKey));
+ EraseIC(std::make_pair(std::string("wkey"), vchPubKey));
return true;
}
@@ -184,7 +178,7 @@ CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount)
ListAccountCreditDebit(strAccount, entries);
CAmount nCreditDebit = 0;
- BOOST_FOREACH (const CAccountingEntry& entry, entries)
+ for (const CAccountingEntry& entry : entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
@@ -612,7 +606,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
if ((wss.nKeys + wss.nCKeys + wss.nWatchKeys) != wss.nKeyMeta)
pwallet->UpdateTimeFirstKey(1);
- BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
+ for (uint256 hash : wss.vWalletUpgrade)
WriteTx(pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
@@ -627,7 +621,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
pwallet->laccentries.clear();
ListAccountCreditDebit("*", pwallet->laccentries);
- BOOST_FOREACH(CAccountingEntry& entry, pwallet->laccentries) {
+ for (CAccountingEntry& entry : pwallet->laccentries) {
pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry)));
}
@@ -713,7 +707,7 @@ DBErrors CWalletDB::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uin
// erase each matching wallet TX
bool delerror = false;
std::vector<uint256>::iterator it = vTxHashIn.begin();
- BOOST_FOREACH (uint256 hash, vTxHash) {
+ for (uint256 hash : vTxHash) {
while (it < vTxHashIn.end() && (*it) < hash) {
it++;
}
@@ -744,7 +738,7 @@ DBErrors CWalletDB::ZapWalletTx(std::vector<CWalletTx>& vWtx)
return err;
// erase each wallet TX
- BOOST_FOREACH (uint256& hash, vTxHash) {
+ for (uint256& hash : vTxHash) {
if (!EraseTx(hash))
return DB_CORRUPT;
}