Refactor: Remove using namespace <xxx> from src/*.cpp.

This commit is contained in:
Karl-Johan Alm 2017-01-27 17:43:41 +09:00
parent 9b4d2673b7
commit b7b48c8bbd
13 changed files with 179 additions and 206 deletions

View file

@ -19,15 +19,13 @@
#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
#define LN2 0.6931471805599453094172321214581765680755001343602552 #define LN2 0.6931471805599453094172321214581765680755001343602552
using namespace std;
CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) : CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :
/** /**
* The ideal size for a bloom filter with a given number of elements and false positive rate is: * The ideal size for a bloom filter with a given number of elements and false positive rate is:
* - nElements * log(fp rate) / ln(2)^2 * - nElements * log(fp rate) / ln(2)^2
* We ignore filter parameters which will create a bloom filter larger than the protocol limits * We ignore filter parameters which will create a bloom filter larger than the protocol limits
*/ */
vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8), vData(std::min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
/** /**
* The ideal number of hash functions is filter size * ln(2) / number of elements * The ideal number of hash functions is filter size * ln(2) / number of elements
* Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
@ -35,7 +33,7 @@ CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int
*/ */
isFull(false), isFull(false),
isEmpty(true), isEmpty(true),
nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
nTweak(nTweakIn), nTweak(nTweakIn),
nFlags(nFlagsIn) nFlags(nFlagsIn)
{ {
@ -58,7 +56,7 @@ inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<
return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8); return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
} }
void CBloomFilter::insert(const vector<unsigned char>& vKey) void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
{ {
if (isFull) if (isFull)
return; return;
@ -75,17 +73,17 @@ void CBloomFilter::insert(const COutPoint& outpoint)
{ {
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint; stream << outpoint;
vector<unsigned char> data(stream.begin(), stream.end()); std::vector<unsigned char> data(stream.begin(), stream.end());
insert(data); insert(data);
} }
void CBloomFilter::insert(const uint256& hash) void CBloomFilter::insert(const uint256& hash)
{ {
vector<unsigned char> data(hash.begin(), hash.end()); std::vector<unsigned char> data(hash.begin(), hash.end());
insert(data); insert(data);
} }
bool CBloomFilter::contains(const vector<unsigned char>& vKey) const bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{ {
if (isFull) if (isFull)
return true; return true;
@ -105,13 +103,13 @@ bool CBloomFilter::contains(const COutPoint& outpoint) const
{ {
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << outpoint; stream << outpoint;
vector<unsigned char> data(stream.begin(), stream.end()); std::vector<unsigned char> data(stream.begin(), stream.end());
return contains(data); return contains(data);
} }
bool CBloomFilter::contains(const uint256& hash) const bool CBloomFilter::contains(const uint256& hash) const
{ {
vector<unsigned char> data(hash.begin(), hash.end()); std::vector<unsigned char> data(hash.begin(), hash.end());
return contains(data); return contains(data);
} }
@ -154,7 +152,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
// This means clients don't have to update the filter themselves when a new relevant tx // This means clients don't have to update the filter themselves when a new relevant tx
// is discovered in order to find spending transactions, which avoids round-tripping and race conditions. // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
CScript::const_iterator pc = txout.scriptPubKey.begin(); CScript::const_iterator pc = txout.scriptPubKey.begin();
vector<unsigned char> data; std::vector<unsigned char> data;
while (pc < txout.scriptPubKey.end()) while (pc < txout.scriptPubKey.end())
{ {
opcodetype opcode; opcodetype opcode;
@ -168,7 +166,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
{ {
txnouttype type; txnouttype type;
vector<vector<unsigned char> > vSolutions; std::vector<std::vector<unsigned char> > vSolutions;
if (Solver(txout.scriptPubKey, type, vSolutions) && if (Solver(txout.scriptPubKey, type, vSolutions) &&
(type == TX_PUBKEY || type == TX_MULTISIG)) (type == TX_PUBKEY || type == TX_MULTISIG))
insert(COutPoint(hash, i)); insert(COutPoint(hash, i));
@ -189,7 +187,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
// Match if the filter contains any arbitrary script data element in any scriptSig in tx // Match if the filter contains any arbitrary script data element in any scriptSig in tx
CScript::const_iterator pc = txin.scriptSig.begin(); CScript::const_iterator pc = txin.scriptSig.begin();
vector<unsigned char> data; std::vector<unsigned char> data;
while (pc < txin.scriptSig.end()) while (pc < txin.scriptSig.end())
{ {
opcodetype opcode; opcodetype opcode;
@ -280,7 +278,7 @@ void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
void CRollingBloomFilter::insert(const uint256& hash) void CRollingBloomFilter::insert(const uint256& hash)
{ {
vector<unsigned char> vData(hash.begin(), hash.end()); std::vector<unsigned char> vData(hash.begin(), hash.end());
insert(vData); insert(vData);
} }
@ -300,7 +298,7 @@ bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
bool CRollingBloomFilter::contains(const uint256& hash) const bool CRollingBloomFilter::contains(const uint256& hash) const
{ {
vector<unsigned char> vData(hash.begin(), hash.end()); std::vector<unsigned char> vData(hash.begin(), hash.end());
return contains(vData); return contains(vData);
} }

View file

@ -5,8 +5,6 @@
#include "chain.h" #include "chain.h"
using namespace std;
/** /**
* CChain implementation * CChain implementation
*/ */

View file

@ -20,13 +20,11 @@
#include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/split.hpp>
#include <boost/assign/list_of.hpp> #include <boost/assign/list_of.hpp>
using namespace std;
CScript ParseScript(const std::string& s) CScript ParseScript(const std::string& s)
{ {
CScript result; CScript result;
static map<string, opcodetype> mapOpNames; static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty()) if (mapOpNames.empty())
{ {
@ -39,7 +37,7 @@ CScript ParseScript(const std::string& s)
const char* name = GetOpName((opcodetype)op); const char* name = GetOpName((opcodetype)op);
if (strcmp(name, "OP_UNKNOWN") == 0) if (strcmp(name, "OP_UNKNOWN") == 0)
continue; continue;
string strName(name); std::string strName(name);
mapOpNames[strName] = (opcodetype)op; mapOpNames[strName] = (opcodetype)op;
// Convenience: OP_ADD and just ADD are both recognized: // Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", ""); boost::algorithm::replace_first(strName, "OP_", "");
@ -47,7 +45,7 @@ CScript ParseScript(const std::string& s)
} }
} }
vector<string> words; std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on); boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w) for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
@ -57,16 +55,16 @@ CScript ParseScript(const std::string& s)
// Empty string, ignore. (boost::split given '' will return one word) // Empty string, ignore. (boost::split given '' will return one word)
} }
else if (all(*w, boost::algorithm::is_digit()) || else if (all(*w, boost::algorithm::is_digit()) ||
(boost::algorithm::starts_with(*w, "-") && all(string(w->begin()+1, w->end()), boost::algorithm::is_digit()))) (boost::algorithm::starts_with(*w, "-") && all(std::string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
{ {
// Number // Number
int64_t n = atoi64(*w); int64_t n = atoi64(*w);
result << n; result << n;
} }
else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(string(w->begin()+2, w->end()))) else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(std::string(w->begin()+2, w->end())))
{ {
// Raw hex data, inserted NOT pushed onto stack: // Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(string(w->begin()+2, w->end())); std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
result.insert(result.end(), raw.begin(), raw.end()); result.insert(result.end(), raw.begin(), raw.end());
} }
else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'")) else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
@ -83,7 +81,7 @@ CScript ParseScript(const std::string& s)
} }
else else
{ {
throw runtime_error("script parse error"); throw std::runtime_error("script parse error");
} }
} }
@ -95,7 +93,7 @@ bool DecodeHexTx(CMutableTransaction& tx, const std::string& strHexTx, bool fTry
if (!IsHex(strHexTx)) if (!IsHex(strHexTx))
return false; return false;
vector<unsigned char> txData(ParseHex(strHexTx)); std::vector<unsigned char> txData(ParseHex(strHexTx));
if (fTryNoWitness) { if (fTryNoWitness) {
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
@ -138,9 +136,9 @@ bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
return true; return true;
} }
uint256 ParseHashUV(const UniValue& v, const string& strName) uint256 ParseHashUV(const UniValue& v, const std::string& strName)
{ {
string strHex; std::string strHex;
if (v.isStr()) if (v.isStr())
strHex = v.getValStr(); strHex = v.getValStr();
return ParseHashStr(strHex, strName); // Note: ParseHashStr("") throws a runtime_error return ParseHashStr(strHex, strName); // Note: ParseHashStr("") throws a runtime_error
@ -149,19 +147,19 @@ uint256 ParseHashUV(const UniValue& v, const string& strName)
uint256 ParseHashStr(const std::string& strHex, const std::string& strName) uint256 ParseHashStr(const std::string& strHex, const std::string& strName)
{ {
if (!IsHex(strHex)) // Note: IsHex("") is false if (!IsHex(strHex)) // Note: IsHex("") is false
throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')"); throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
uint256 result; uint256 result;
result.SetHex(strHex); result.SetHex(strHex);
return result; return result;
} }
vector<unsigned char> ParseHexUV(const UniValue& v, const string& strName) std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{ {
string strHex; std::string strHex;
if (v.isStr()) if (v.isStr())
strHex = v.getValStr(); strHex = v.getValStr();
if (!IsHex(strHex)) if (!IsHex(strHex))
throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')"); throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
return ParseHex(strHex); return ParseHex(strHex);
} }

View file

@ -18,16 +18,14 @@
#include <boost/assign/list_of.hpp> #include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
using namespace std; std::string FormatScript(const CScript& script)
string FormatScript(const CScript& script)
{ {
string ret; std::string ret;
CScript::const_iterator it = script.begin(); CScript::const_iterator it = script.begin();
opcodetype op; opcodetype op;
while (it != script.end()) { while (it != script.end()) {
CScript::const_iterator it2 = it; CScript::const_iterator it2 = it;
vector<unsigned char> vch; std::vector<unsigned char> vch;
if (script.GetOp2(it, op, &vch)) { if (script.GetOp2(it, op, &vch)) {
if (op == OP_0) { if (op == OP_0) {
ret += "0 "; ret += "0 ";
@ -36,9 +34,9 @@ string FormatScript(const CScript& script)
ret += strprintf("%i ", op - OP_1NEGATE - 1); ret += strprintf("%i ", op - OP_1NEGATE - 1);
continue; continue;
} else if (op >= OP_NOP && op <= OP_NOP10) { } else if (op >= OP_NOP && op <= OP_NOP10) {
string str(GetOpName(op)); std::string str(GetOpName(op));
if (str.substr(0, 3) == string("OP_")) { if (str.substr(0, 3) == std::string("OP_")) {
ret += str.substr(3, string::npos) + " "; ret += str.substr(3, std::string::npos) + " ";
continue; continue;
} }
} }
@ -55,14 +53,14 @@ string FormatScript(const CScript& script)
return ret.substr(0, ret.size() - 1); return ret.substr(0, ret.size() - 1);
} }
const map<unsigned char, string> mapSigHashTypes = const std::map<unsigned char, std::string> mapSigHashTypes =
boost::assign::map_list_of boost::assign::map_list_of
(static_cast<unsigned char>(SIGHASH_ALL), string("ALL")) (static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL"))
(static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), string("ALL|ANYONECANPAY")) (static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY"))
(static_cast<unsigned char>(SIGHASH_NONE), string("NONE")) (static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE"))
(static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), string("NONE|ANYONECANPAY")) (static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY"))
(static_cast<unsigned char>(SIGHASH_SINGLE), string("SINGLE")) (static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE"))
(static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), string("SINGLE|ANYONECANPAY")) (static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY"))
; ;
/** /**
@ -72,11 +70,11 @@ const map<unsigned char, string> mapSigHashTypes =
* of a signature. Only pass true for scripts you believe could contain signatures. For example, * of a signature. Only pass true for scripts you believe could contain signatures. For example,
* pass false, or omit the this argument (defaults to false), for scriptPubKeys. * pass false, or omit the this argument (defaults to false), for scriptPubKeys.
*/ */
string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
{ {
string str; std::string str;
opcodetype opcode; opcodetype opcode;
vector<unsigned char> vch; std::vector<unsigned char> vch;
CScript::const_iterator pc = script.begin(); CScript::const_iterator pc = script.begin();
while (pc < script.end()) { while (pc < script.end()) {
if (!str.empty()) { if (!str.empty()) {
@ -87,12 +85,12 @@ string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
return str; return str;
} }
if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (0 <= opcode && opcode <= OP_PUSHDATA4) {
if (vch.size() <= static_cast<vector<unsigned char>::size_type>(4)) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) {
str += strprintf("%d", CScriptNum(vch, false).getint()); str += strprintf("%d", CScriptNum(vch, false).getint());
} else { } else {
// the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
if (fAttemptSighashDecode && !script.IsUnspendable()) { if (fAttemptSighashDecode && !script.IsUnspendable()) {
string strSigHashDecode; std::string strSigHashDecode;
// goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
// this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
// the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
@ -116,7 +114,7 @@ string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
return str; return str;
} }
string EncodeHexTx(const CTransaction& tx, const int serialFlags) std::string EncodeHexTx(const CTransaction& tx, const int serialFlags)
{ {
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serialFlags); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serialFlags);
ssTx << tx; ssTx << tx;
@ -127,7 +125,7 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey,
UniValue& out, bool fIncludeHex) UniValue& out, bool fIncludeHex)
{ {
txnouttype type; txnouttype type;
vector<CTxDestination> addresses; std::vector<CTxDestination> addresses;
int nRequired; int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); out.pushKV("asm", ScriptToAsmStr(scriptPubKey));

View file

@ -65,8 +65,6 @@
#include "zmq/zmqnotificationinterface.h" #include "zmq/zmqnotificationinterface.h"
#endif #endif
using namespace std;
bool fFeeEstimatesInitialized = false; bool fFeeEstimatesInitialized = false;
static const bool DEFAULT_PROXYRANDOMIZE = true; static const bool DEFAULT_PROXYRANDOMIZE = true;
static const bool DEFAULT_REST_ENABLE = false; static const bool DEFAULT_REST_ENABLE = false;
@ -310,10 +308,10 @@ void OnRPCStopped()
void OnRPCPreCommand(const CRPCCommand& cmd) void OnRPCPreCommand(const CRPCCommand& cmd)
{ {
// Observe safe mode // Observe safe mode
string strWarning = GetWarnings("rpc"); std::string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) && if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
!cmd.okSafeMode) !cmd.okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
} }
std::string HelpMessage(HelpMessageMode mode) std::string HelpMessage(HelpMessageMode mode)
@ -322,7 +320,7 @@ std::string HelpMessage(HelpMessageMode mode)
// When adding new options to the categories, please keep and ensure alphabetical ordering. // When adding new options to the categories, please keep and ensure alphabetical ordering.
// Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators. // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
string strUsage = HelpMessageGroup(_("Options:")); std::string strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("Print this help message and exit")); strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
strUsage += HelpMessageOpt("-version", _("Print version and exit")); strUsage += HelpMessageOpt("-version", _("Print version and exit"));
strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)")); strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
@ -436,7 +434,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT)); strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)"); strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
} }
string debugCategories = "addrman, alert, bench, cmpctblock, coindb, db, http, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below std::string debugCategories = "addrman, alert, bench, cmpctblock, coindb, db, http, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below
if (mode == HMM_BITCOIN_QT) if (mode == HMM_BITCOIN_QT)
debugCategories += ", qt"; debugCategories += ", qt";
strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " + strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
@ -576,15 +574,14 @@ struct CImportingNow
// works correctly. // works correctly.
void CleanupBlockRevFiles() void CleanupBlockRevFiles()
{ {
using namespace boost::filesystem; std::map<std::string, boost::filesystem::path> mapBlockFiles;
map<string, path> mapBlockFiles;
// Glob all blk?????.dat and rev?????.dat files from the blocks directory. // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
// Remove the rev files immediately and insert the blk file paths into an // Remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index. // ordered map keyed by block file index.
LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n"); LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
path blocksdir = GetDataDir() / "blocks"; boost::filesystem::path blocksdir = GetDataDir() / "blocks";
for (directory_iterator it(blocksdir); it != directory_iterator(); it++) { for (boost::filesystem::directory_iterator it(blocksdir); it != boost::filesystem::directory_iterator(); it++) {
if (is_regular_file(*it) && if (is_regular_file(*it) &&
it->path().filename().string().length() == 12 && it->path().filename().string().length() == 12 &&
it->path().filename().string().substr(8,4) == ".dat") it->path().filename().string().substr(8,4) == ".dat")
@ -601,7 +598,7 @@ void CleanupBlockRevFiles()
// keeping a separate counter. Once we hit a gap (or if 0 doesn't exist) // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
// start removing block files. // start removing block files.
int nContigCounter = 0; int nContigCounter = 0;
BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) { BOOST_FOREACH(const PAIRTYPE(std::string, boost::filesystem::path)& item, mapBlockFiles) {
if (atoi(item.first) == nContigCounter) { if (atoi(item.first) == nContigCounter) {
nContigCounter++; nContigCounter++;
continue; continue;
@ -894,8 +891,8 @@ bool AppInitParameterInteraction()
fDebug = mapMultiArgs.count("-debug"); fDebug = mapMultiArgs.count("-debug");
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
if (fDebug) { if (fDebug) {
const vector<string>& categories = mapMultiArgs.at("-debug"); const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end())
fDebug = false; fDebug = false;
} }
@ -1063,7 +1060,7 @@ bool AppInitParameterInteraction()
if (!chainparams.MineBlocksOnDemand()) { if (!chainparams.MineBlocksOnDemand()) {
return InitError("BIP9 parameters may only be overridden on regtest."); return InitError("BIP9 parameters may only be overridden on regtest.");
} }
const vector<string>& deployments = mapMultiArgs.at("-bip9params"); const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params");
for (auto i : deployments) { for (auto i : deployments) {
std::vector<std::string> vDeploymentParams; std::vector<std::string> vDeploymentParams;
boost::split(vDeploymentParams, i, boost::is_any_of(":")); boost::split(vDeploymentParams, i, boost::is_any_of(":"));
@ -1208,9 +1205,9 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
RegisterNodeSignals(GetNodeSignals()); RegisterNodeSignals(GetNodeSignals());
// sanitize comments per BIP-0014, format user agent and check total size // sanitize comments per BIP-0014, format user agent and check total size
std::vector<string> uacomments; std::vector<std::string> uacomments;
if (mapMultiArgs.count("-uacomment")) { if (mapMultiArgs.count("-uacomment")) {
BOOST_FOREACH(string cmt, mapMultiArgs.at("-uacomment")) BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment"))
{ {
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));

View file

@ -9,14 +9,12 @@
#include "consensus/consensus.h" #include "consensus/consensus.h"
#include "utilstrencodings.h" #include "utilstrencodings.h"
using namespace std;
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter) CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{ {
header = block.GetBlockHeader(); header = block.GetBlockHeader();
vector<bool> vMatch; std::vector<bool> vMatch;
vector<uint256> vHashes; std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size()); vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size());
@ -27,7 +25,7 @@ CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
if (filter.IsRelevantAndUpdate(*block.vtx[i])) if (filter.IsRelevantAndUpdate(*block.vtx[i]))
{ {
vMatch.push_back(true); vMatch.push_back(true);
vMatchedTxn.push_back(make_pair(i, hash)); vMatchedTxn.push_back(std::make_pair(i, hash));
} }
else else
vMatch.push_back(false); vMatch.push_back(false);
@ -41,8 +39,8 @@ CMerkleBlock::CMerkleBlock(const CBlock& block, const std::set<uint256>& txids)
{ {
header = block.GetBlockHeader(); header = block.GetBlockHeader();
vector<bool> vMatch; std::vector<bool> vMatch;
vector<uint256> vHashes; std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size()); vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size());

View file

@ -31,8 +31,6 @@
#include <queue> #include <queue>
#include <utility> #include <utility>
using namespace std;
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// //
// BitcoinMiner // BitcoinMiner
@ -500,7 +498,7 @@ void BlockAssembler::addPackageTxs()
} }
// Package can be added. Sort the entries in a valid order. // Package can be added. Sort the entries in a valid order.
vector<CTxMemPool::txiter> sortedEntries; std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, iter, sortedEntries); SortForBlock(ancestors, iter, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) { for (size_t i=0; i<sortedEntries.size(); ++i) {
@ -529,7 +527,7 @@ void BlockAssembler::addPriorityTxs()
fNeedSizeAccounting = true; fNeedSizeAccounting = true;
// This vector will be sorted into a priority queue: // This vector will be sorted into a priority queue:
vector<TxCoinAgePriority> vecPriority; std::vector<TxCoinAgePriority> vecPriority;
TxCoinAgePriorityCompare pricomparer; TxCoinAgePriorityCompare pricomparer;
std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap; std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter; typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;

View file

@ -32,8 +32,6 @@
#include <boost/thread.hpp> #include <boost/thread.hpp>
using namespace std;
#if defined(NDEBUG) #if defined(NDEBUG)
# error "Bitcoin cannot be compiled without assertions." # error "Bitcoin cannot be compiled without assertions."
#endif #endif
@ -55,8 +53,8 @@ struct COrphanTx {
NodeId fromPeer; NodeId fromPeer;
int64_t nTimeExpire; int64_t nTimeExpire;
}; };
map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main); std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
map<COutPoint, set<map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main); std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main); void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
static size_t vExtraTxnForCompactIt = 0; static size_t vExtraTxnForCompactIt = 0;
@ -76,7 +74,7 @@ namespace {
* Set mapBlockSource[hash].second to false if the node should not be * Set mapBlockSource[hash].second to false if the node should not be
* punished if the block is invalid. * punished if the block is invalid.
*/ */
map<uint256, std::pair<NodeId, bool>> mapBlockSource; std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
/** /**
* Filter for transactions that were recently rejected by * Filter for transactions that were recently rejected by
@ -108,10 +106,10 @@ namespace {
bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request. bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
}; };
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight; std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
/** Stack of nodes which we have set to announce using compact blocks */ /** Stack of nodes which we have set to announce using compact blocks */
list<NodeId> lNodesAnnouncingHeaderAndIDs; std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
/** Number of preferable block download peers. */ /** Number of preferable block download peers. */
int nPreferredDownload = 0; int nPreferredDownload = 0;
@ -135,7 +133,7 @@ namespace {
struct CBlockReject { struct CBlockReject {
unsigned char chRejectCode; unsigned char chRejectCode;
string strRejectReason; std::string strRejectReason;
uint256 hashBlock; uint256 hashBlock;
}; };
@ -172,7 +170,7 @@ struct CNodeState {
bool fSyncStarted; bool fSyncStarted;
//! Since when we're stalling block download progress (in microseconds), or 0. //! Since when we're stalling block download progress (in microseconds), or 0.
int64_t nStallingSince; int64_t nStallingSince;
list<QueuedBlock> vBlocksInFlight; std::list<QueuedBlock> vBlocksInFlight;
//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
int64_t nDownloadingSince; int64_t nDownloadingSince;
int nBlocksInFlight; int nBlocksInFlight;
@ -224,11 +222,11 @@ struct CNodeState {
}; };
/** Map maintaining per-node state. Requires cs_main. */ /** Map maintaining per-node state. Requires cs_main. */
map<NodeId, CNodeState> mapNodeState; std::map<NodeId, CNodeState> mapNodeState;
// Requires cs_main. // Requires cs_main.
CNodeState *State(NodeId pnode) { CNodeState *State(NodeId pnode) {
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode); std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end()) if (it == mapNodeState.end())
return NULL; return NULL;
return &it->second; return &it->second;
@ -310,7 +308,7 @@ void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
// Returns a bool indicating whether we requested this block. // Returns a bool indicating whether we requested this block.
// Also used if a block was /not/ received and timed out or started with another peer // Also used if a block was /not/ received and timed out or started with another peer
bool MarkBlockAsReceived(const uint256& hash) { bool MarkBlockAsReceived(const uint256& hash) {
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) { if (itInFlight != mapBlocksInFlight.end()) {
CNodeState *state = State(itInFlight->second.first); CNodeState *state = State(itInFlight->second.first);
state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
@ -334,12 +332,12 @@ bool MarkBlockAsReceived(const uint256& hash) {
// Requires cs_main. // Requires cs_main.
// returns false, still setting pit, if the block was already in flight from the same peer // returns false, still setting pit, if the block was already in flight from the same peer
// pit will only be valid as long as the same cs_main lock is being held // pit will only be valid as long as the same cs_main lock is being held
bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, const CBlockIndex *pindex = NULL, list<QueuedBlock>::iterator **pit = NULL) { bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, const CBlockIndex* pindex = NULL, std::list<QueuedBlock>::iterator** pit = NULL) {
CNodeState *state = State(nodeid); CNodeState *state = State(nodeid);
assert(state != NULL); assert(state != NULL);
// Short-circuit most stuff in case its from the same node // Short-circuit most stuff in case its from the same node
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) { if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
*pit = &itInFlight->second.second; *pit = &itInFlight->second.second;
return false; return false;
@ -348,7 +346,7 @@ bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Pa
// Make sure it's not listed somewhere already. // Make sure it's not listed somewhere already.
MarkBlockAsReceived(hash); MarkBlockAsReceived(hash);
list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
{hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)}); {hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)});
state->nBlocksInFlight++; state->nBlocksInFlight++;
state->nBlocksInFlightValidHeaders += it->fValidatedHeaders; state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
@ -640,7 +638,7 @@ bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRE
int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{ {
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash); std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end()) if (it == mapOrphanTransactions.end())
return 0; return 0;
BOOST_FOREACH(const CTxIn& txin, it->second.tx->vin) BOOST_FOREACH(const CTxIn& txin, it->second.tx->vin)
@ -659,10 +657,10 @@ int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void EraseOrphansFor(NodeId peer) void EraseOrphansFor(NodeId peer)
{ {
int nErased = 0; int nErased = 0;
map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin(); std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end()) while (iter != mapOrphanTransactions.end())
{ {
map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
if (maybeErase->second.fromPeer == peer) if (maybeErase->second.fromPeer == peer)
{ {
nErased += EraseOrphanTx(maybeErase->second.tx->GetHash()); nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
@ -681,10 +679,10 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRE
// Sweep out expired orphan pool entries: // Sweep out expired orphan pool entries:
int nErased = 0; int nErased = 0;
int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL; int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin(); std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end()) while (iter != mapOrphanTransactions.end())
{ {
map<uint256, COrphanTx>::iterator maybeErase = iter++; std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
if (maybeErase->second.nTimeExpire <= nNow) { if (maybeErase->second.nTimeExpire <= nNow) {
nErased += EraseOrphanTx(maybeErase->second.tx->GetHash()); nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
} else { } else {
@ -699,7 +697,7 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRE
{ {
// Evict a random orphan: // Evict a random orphan:
uint256 randomhash = GetRandHash(); uint256 randomhash = GetRandHash();
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash); std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end()) if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin(); it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first); EraseOrphanTx(it->first);
@ -961,7 +959,7 @@ static void RelayAddress(const CAddress& addr, bool fReachable, CConnman& connma
void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman& connman, std::atomic<bool>& interruptMsgProc) void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman& connman, std::atomic<bool>& interruptMsgProc)
{ {
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin(); std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound; std::vector<CInv> vNotFound;
CNetMsgMaker msgMaker(pfrom->GetSendVersion()); CNetMsgMaker msgMaker(pfrom->GetSendVersion());
LOCK(cs_main); LOCK(cs_main);
@ -1083,7 +1081,7 @@ void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParam
// Bypass PushInventory, this must send even if redundant, // Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't // and we want it right after the last block so they don't
// wait for other stuff first. // wait for other stuff first.
vector<CInv> vInv; std::vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv)); connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
pfrom->hashContinue.SetNull(); pfrom->hashContinue.SetNull();
@ -1160,7 +1158,7 @@ inline void static SendBlockTransactions(const CBlock& block, const BlockTransac
connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp)); connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
} }
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman, std::atomic<bool>& interruptMsgProc) bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman, std::atomic<bool>& interruptMsgProc)
{ {
LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0) if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
@ -1190,7 +1188,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
// Each connection can only send one version message // Each connection can only send one version message
if (pfrom->nVersion != 0) if (pfrom->nVersion != 0)
{ {
connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, string("Duplicate version message"))); connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
LOCK(cs_main); LOCK(cs_main);
Misbehaving(pfrom->GetId(), 1); Misbehaving(pfrom->GetId(), 1);
return false; return false;
@ -1311,7 +1309,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
pfrom->fSuccessfullyConnected = true; pfrom->fSuccessfullyConnected = true;
string remoteAddr; std::string remoteAddr;
if (fLogIPs) if (fLogIPs)
remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
@ -1352,7 +1350,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
if (strCommand == NetMsgType::VERACK) if (strCommand == NetMsgType::VERACK)
{ {
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); pfrom->SetRecvVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound) { if (!pfrom->fInbound) {
// Mark this node as currently connected, so we update its timestamp later. // Mark this node as currently connected, so we update its timestamp later.
@ -1385,7 +1383,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
else if (strCommand == NetMsgType::ADDR) else if (strCommand == NetMsgType::ADDR)
{ {
vector<CAddress> vAddr; std::vector<CAddress> vAddr;
vRecv >> vAddr; vRecv >> vAddr;
// Don't want addr from older versions unless seeding // Don't want addr from older versions unless seeding
@ -1399,7 +1397,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
} }
// Store the new addresses // Store the new addresses
vector<CAddress> vAddrOk; std::vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime(); int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60; int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr) BOOST_FOREACH(CAddress& addr, vAddr)
@ -1462,7 +1460,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
else if (strCommand == NetMsgType::INV) else if (strCommand == NetMsgType::INV)
{ {
vector<CInv> vInv; std::vector<CInv> vInv;
vRecv >> vInv; vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ) if (vInv.size() > MAX_INV_SZ)
{ {
@ -1529,7 +1527,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
else if (strCommand == NetMsgType::GETDATA) else if (strCommand == NetMsgType::GETDATA)
{ {
vector<CInv> vInv; std::vector<CInv> vInv;
vRecv >> vInv; vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ) if (vInv.size() > MAX_INV_SZ)
{ {
@ -1691,7 +1689,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
} }
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
vector<CBlock> vHeaders; std::vector<CBlock> vHeaders;
int nLimit = MAX_HEADERS_RESULTS; int nLimit = MAX_HEADERS_RESULTS;
LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->id); LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex)) for (; pindex; pindex = chainActive.Next(pindex))
@ -1727,8 +1725,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
return true; return true;
} }
deque<COutPoint> vWorkQueue; std::deque<COutPoint> vWorkQueue;
vector<uint256> vEraseQueue; std::vector<uint256> vEraseQueue;
CTransactionRef ptx; CTransactionRef ptx;
vRecv >> ptx; vRecv >> ptx;
const CTransaction& tx = *ptx; const CTransaction& tx = *ptx;
@ -1761,7 +1759,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
mempool.size(), mempool.DynamicMemoryUsage() / 1000); mempool.size(), mempool.DynamicMemoryUsage() / 1000);
// Recursively process any orphan transactions that depended on this one // Recursively process any orphan transactions that depended on this one
set<NodeId> setMisbehaving; std::set<NodeId> setMisbehaving;
while (!vWorkQueue.empty()) { while (!vWorkQueue.empty()) {
auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front()); auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
vWorkQueue.pop_front(); vWorkQueue.pop_front();
@ -1955,7 +1953,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
assert(pindex); assert(pindex);
UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash()); UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
std::map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash()); std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end(); bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
@ -1990,7 +1988,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
if (pindex->nHeight <= chainActive.Height() + 2) { if (pindex->nHeight <= chainActive.Height() + 2) {
if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
(fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) { (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
list<QueuedBlock>::iterator *queuedBlockIt = NULL; std::list<QueuedBlock>::iterator* queuedBlockIt = NULL;
if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex, &queuedBlockIt)) { if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex, &queuedBlockIt)) {
if (!(*queuedBlockIt)->partialBlock) if (!(*queuedBlockIt)->partialBlock)
(*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool)); (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
@ -2108,7 +2106,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
{ {
LOCK(cs_main); LOCK(cs_main);
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash); std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock || if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
it->second.first != pfrom->GetId()) { it->second.first != pfrom->GetId()) {
LogPrint("net", "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->id); LogPrint("net", "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->id);
@ -2265,7 +2263,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
// If this set of headers is valid and ends in a block with at least as // If this set of headers is valid and ends in a block with at least as
// much work as our tip, download as much as possible. // much work as our tip, download as much as possible.
if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) { if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
vector<const CBlockIndex *> vToFetch; std::vector<const CBlockIndex*> vToFetch;
const CBlockIndex *pindexWalk = pindexLast; const CBlockIndex *pindexWalk = pindexLast;
// Calculate all the blocks we'd need to switch to pindexLast, up to a limit. // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
@ -2286,7 +2284,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
pindexLast->GetBlockHash().ToString(), pindexLast->GetBlockHash().ToString(),
pindexLast->nHeight); pindexLast->nHeight);
} else { } else {
vector<CInv> vGetData; std::vector<CInv> vGetData;
// Download as much as possible, from earliest to latest. // Download as much as possible, from earliest to latest.
BOOST_REVERSE_FOREACH(const CBlockIndex *pindex, vToFetch) { BOOST_REVERSE_FOREACH(const CBlockIndex *pindex, vToFetch) {
if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
@ -2365,7 +2363,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
pfrom->fSentAddr = true; pfrom->fSentAddr = true;
pfrom->vAddrToSend.clear(); pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = connman.GetAddresses(); std::vector<CAddress> vAddr = connman.GetAddresses();
FastRandomContext insecure_rand; FastRandomContext insecure_rand;
BOOST_FOREACH(const CAddress &addr, vAddr) BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr, insecure_rand); pfrom->PushAddress(addr, insecure_rand);
@ -2496,7 +2494,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
else if (strCommand == NetMsgType::FILTERADD) else if (strCommand == NetMsgType::FILTERADD)
{ {
vector<unsigned char> vData; std::vector<unsigned char> vData;
vRecv >> vData; vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
@ -2534,10 +2532,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
{ {
if (fDebug) { if (fDebug) {
try { try {
string strMsg; unsigned char ccode; string strReason; std::string strMsg; unsigned char ccode; std::string strReason;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH); vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
ostringstream ss; std::ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason; ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX) if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
@ -2635,7 +2633,7 @@ bool ProcessMessages(CNode* pfrom, CConnman& connman, std::atomic<bool>& interru
LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id); LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
return fMoreWork; return fMoreWork;
} }
string strCommand = hdr.GetCommand(); std::string strCommand = hdr.GetCommand();
// Message size // Message size
unsigned int nMessageSize = hdr.nMessageSize; unsigned int nMessageSize = hdr.nMessageSize;
@ -2664,7 +2662,7 @@ bool ProcessMessages(CNode* pfrom, CConnman& connman, std::atomic<bool>& interru
} }
catch (const std::ios_base::failure& e) catch (const std::ios_base::failure& e)
{ {
connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, string("error parsing message"))); connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
if (strstr(e.what(), "end of data")) if (strstr(e.what(), "end of data"))
{ {
// Allow exceptions from under-length message on vRecv // Allow exceptions from under-length message on vRecv
@ -2761,7 +2759,7 @@ bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interruptMsg
CNodeState &state = *State(pto->GetId()); CNodeState &state = *State(pto->GetId());
BOOST_FOREACH(const CBlockReject& reject, state.rejects) BOOST_FOREACH(const CBlockReject& reject, state.rejects)
connman.PushMessage(pto, msgMaker.Make(NetMsgType::REJECT, (string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock)); connman.PushMessage(pto, msgMaker.Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
state.rejects.clear(); state.rejects.clear();
if (state.fShouldBan) { if (state.fShouldBan) {
@ -2794,7 +2792,7 @@ bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interruptMsg
// //
if (pto->nNextAddrSend < nNow) { if (pto->nNextAddrSend < nNow) {
pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL); pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
vector<CAddress> vAddr; std::vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size()); vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{ {
@ -2862,7 +2860,7 @@ bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interruptMsg
// blocks, or if the peer doesn't want headers, just // blocks, or if the peer doesn't want headers, just
// add all to the inv queue. // add all to the inv queue.
LOCK(pto->cs_inventory); LOCK(pto->cs_inventory);
vector<CBlock> vHeaders; std::vector<CBlock> vHeaders;
bool fRevertToInv = ((!state.fPreferHeaders && bool fRevertToInv = ((!state.fPreferHeaders &&
(!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) || (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE); pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
@ -2994,7 +2992,7 @@ bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interruptMsg
// //
// Message: inventory // Message: inventory
// //
vector<CInv> vInv; std::vector<CInv> vInv;
{ {
LOCK(pto->cs_inventory); LOCK(pto->cs_inventory);
vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX)); vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
@ -3059,7 +3057,7 @@ bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interruptMsg
// Determine transactions to relay // Determine transactions to relay
if (fSendTrickle) { if (fSendTrickle) {
// Produce a vector with all candidates for sending // Produce a vector with all candidates for sending
vector<std::set<uint256>::iterator> vInvTx; std::vector<std::set<uint256>::iterator> vInvTx;
vInvTx.reserve(pto->setInventoryTxToSend.size()); vInvTx.reserve(pto->setInventoryTxToSend.size());
for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) { for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
vInvTx.push_back(it); vInvTx.push_back(it);
@ -3153,9 +3151,9 @@ bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interruptMsg
// //
// Message: getdata (blocks) // Message: getdata (blocks)
// //
vector<CInv> vGetData; std::vector<CInv> vGetData;
if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
vector<const CBlockIndex*> vToDownload; std::vector<const CBlockIndex*> vToDownload;
NodeId staller = -1; NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams); FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
BOOST_FOREACH(const CBlockIndex *pindex, vToDownload) { BOOST_FOREACH(const CBlockIndex *pindex, vToDownload) {

View file

@ -20,8 +20,6 @@
#include <univalue.h> #include <univalue.h>
using namespace std;
static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
enum RetFormat { enum RetFormat {
@ -64,7 +62,7 @@ extern UniValue mempoolToJSON(bool fVerbose = false);
extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
extern UniValue blockheaderToJSON(const CBlockIndex* blockindex); extern UniValue blockheaderToJSON(const CBlockIndex* blockindex);
static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, string message) static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, std::string message)
{ {
req->WriteHeader("Content-Type", "text/plain"); req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(status, message + "\r\n"); req->WriteReply(status, message + "\r\n");
@ -92,9 +90,9 @@ static enum RetFormat ParseDataFormat(std::string& param, const std::string& str
return rf_names[0].rf; return rf_names[0].rf;
} }
static string AvailableDataFormatsString() static std::string AvailableDataFormatsString()
{ {
string formats = ""; std::string formats = "";
for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++) for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
if (strlen(rf_names[i].name) > 0) { if (strlen(rf_names[i].name) > 0) {
formats.append("."); formats.append(".");
@ -108,7 +106,7 @@ static string AvailableDataFormatsString()
return formats; return formats;
} }
static bool ParseHashStr(const string& strReq, uint256& v) static bool ParseHashStr(const std::string& strReq, uint256& v)
{ {
if (!IsHex(strReq) || (strReq.size() != 64)) if (!IsHex(strReq) || (strReq.size() != 64))
return false; return false;
@ -132,7 +130,7 @@ static bool rest_headers(HTTPRequest* req,
return false; return false;
std::string param; std::string param;
const RetFormat rf = ParseDataFormat(param, strURIPart); const RetFormat rf = ParseDataFormat(param, strURIPart);
vector<string> path; std::vector<std::string> path;
boost::split(path, param, boost::is_any_of("/")); boost::split(path, param, boost::is_any_of("/"));
if (path.size() != 2) if (path.size() != 2)
@ -142,7 +140,7 @@ static bool rest_headers(HTTPRequest* req,
if (count < 1 || count > 2000) if (count < 1 || count > 2000)
return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]); return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
string hashStr = path[1]; std::string hashStr = path[1];
uint256 hash; uint256 hash;
if (!ParseHashStr(hashStr, hash)) if (!ParseHashStr(hashStr, hash))
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
@ -168,14 +166,14 @@ static bool rest_headers(HTTPRequest* req,
switch (rf) { switch (rf) {
case RF_BINARY: { case RF_BINARY: {
string binaryHeader = ssHeader.str(); std::string binaryHeader = ssHeader.str();
req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, binaryHeader); req->WriteReply(HTTP_OK, binaryHeader);
return true; return true;
} }
case RF_HEX: { case RF_HEX: {
string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n"; std::string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain"); req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex); req->WriteReply(HTTP_OK, strHex);
return true; return true;
@ -185,7 +183,7 @@ static bool rest_headers(HTTPRequest* req,
BOOST_FOREACH(const CBlockIndex *pindex, headers) { BOOST_FOREACH(const CBlockIndex *pindex, headers) {
jsonHeaders.push_back(blockheaderToJSON(pindex)); jsonHeaders.push_back(blockheaderToJSON(pindex));
} }
string strJSON = jsonHeaders.write() + "\n"; std::string strJSON = jsonHeaders.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;
@ -232,14 +230,14 @@ static bool rest_block(HTTPRequest* req,
switch (rf) { switch (rf) {
case RF_BINARY: { case RF_BINARY: {
string binaryBlock = ssBlock.str(); std::string binaryBlock = ssBlock.str();
req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, binaryBlock); req->WriteReply(HTTP_OK, binaryBlock);
return true; return true;
} }
case RF_HEX: { case RF_HEX: {
string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n"; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain"); req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex); req->WriteReply(HTTP_OK, strHex);
return true; return true;
@ -247,7 +245,7 @@ static bool rest_block(HTTPRequest* req,
case RF_JSON: { case RF_JSON: {
UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails); UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails);
string strJSON = objBlock.write() + "\n"; std::string strJSON = objBlock.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;
@ -287,7 +285,7 @@ static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
JSONRPCRequest jsonRequest; JSONRPCRequest jsonRequest;
jsonRequest.params = UniValue(UniValue::VARR); jsonRequest.params = UniValue(UniValue::VARR);
UniValue chainInfoObject = getblockchaininfo(jsonRequest); UniValue chainInfoObject = getblockchaininfo(jsonRequest);
string strJSON = chainInfoObject.write() + "\n"; std::string strJSON = chainInfoObject.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;
@ -312,7 +310,7 @@ static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
case RF_JSON: { case RF_JSON: {
UniValue mempoolInfoObject = mempoolInfoToJSON(); UniValue mempoolInfoObject = mempoolInfoToJSON();
string strJSON = mempoolInfoObject.write() + "\n"; std::string strJSON = mempoolInfoObject.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;
@ -337,7 +335,7 @@ static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPar
case RF_JSON: { case RF_JSON: {
UniValue mempoolObject = mempoolToJSON(true); UniValue mempoolObject = mempoolToJSON(true);
string strJSON = mempoolObject.write() + "\n"; std::string strJSON = mempoolObject.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;
@ -372,14 +370,14 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
switch (rf) { switch (rf) {
case RF_BINARY: { case RF_BINARY: {
string binaryTx = ssTx.str(); std::string binaryTx = ssTx.str();
req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, binaryTx); req->WriteReply(HTTP_OK, binaryTx);
return true; return true;
} }
case RF_HEX: { case RF_HEX: {
string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n"; std::string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain"); req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex); req->WriteReply(HTTP_OK, strHex);
return true; return true;
@ -388,7 +386,7 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
case RF_JSON: { case RF_JSON: {
UniValue objTx(UniValue::VOBJ); UniValue objTx(UniValue::VOBJ);
TxToJSON(*tx, hashBlock, objTx); TxToJSON(*tx, hashBlock, objTx);
string strJSON = objTx.write() + "\n"; std::string strJSON = objTx.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;
@ -410,7 +408,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
std::string param; std::string param;
const RetFormat rf = ParseDataFormat(param, strURIPart); const RetFormat rf = ParseDataFormat(param, strURIPart);
vector<string> uriParts; std::vector<std::string> uriParts;
if (param.length() > 1) if (param.length() > 1)
{ {
std::string strUriParams = param.substr(1); std::string strUriParams = param.substr(1);
@ -424,7 +422,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
bool fInputParsed = false; bool fInputParsed = false;
bool fCheckMemPool = false; bool fCheckMemPool = false;
vector<COutPoint> vOutPoints; std::vector<COutPoint> vOutPoints;
// parse/deserialize input // parse/deserialize input
// input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ... // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
@ -498,8 +496,8 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size())); return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
// check spentness and form a bitmap (as well as a JSON capable human-readable string representation) // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
vector<unsigned char> bitmap; std::vector<unsigned char> bitmap;
vector<CCoin> outs; std::vector<CCoin> outs;
std::string bitmapStringRepresentation; std::string bitmapStringRepresentation;
std::vector<bool> hits; std::vector<bool> hits;
bitmap.resize((vOutPoints.size() + 7) / 8); bitmap.resize((vOutPoints.size() + 7) / 8);
@ -546,7 +544,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
// use exact same output as mentioned in Bip64 // use exact same output as mentioned in Bip64
CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs; ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
string ssGetUTXOResponseString = ssGetUTXOResponse.str(); std::string ssGetUTXOResponseString = ssGetUTXOResponse.str();
req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteHeader("Content-Type", "application/octet-stream");
req->WriteReply(HTTP_OK, ssGetUTXOResponseString); req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
@ -556,7 +554,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
case RF_HEX: { case RF_HEX: {
CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs; ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n"; std::string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain"); req->WriteHeader("Content-Type", "text/plain");
req->WriteReply(HTTP_OK, strHex); req->WriteReply(HTTP_OK, strHex);
@ -588,7 +586,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
objGetUTXOResponse.push_back(Pair("utxos", utxos)); objGetUTXOResponse.push_back(Pair("utxos", utxos));
// return json string // return json string
string strJSON = objGetUTXOResponse.write() + "\n"; std::string strJSON = objGetUTXOResponse.write() + "\n";
req->WriteHeader("Content-Type", "application/json"); req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strJSON); req->WriteReply(HTTP_OK, strJSON);
return true; return true;

View file

@ -17,8 +17,6 @@
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
using namespace std;
static CCriticalSection cs_nTimeOffset; static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0; static int64_t nTimeOffset = 0;
@ -51,7 +49,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{ {
LOCK(cs_nTimeOffset); LOCK(cs_nTimeOffset);
// Ignore duplicates // Ignore duplicates
static set<CNetAddr> setKnown; static std::set<CNetAddr> setKnown;
if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES) if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)
return; return;
if (!setKnown.insert(ip).second) if (!setKnown.insert(ip).second)

View file

@ -14,8 +14,6 @@
#include <boost/thread.hpp> #include <boost/thread.hpp>
using namespace std;
static const char DB_COINS = 'c'; static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f'; static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't'; static const char DB_TXINDEX = 't';
@ -32,11 +30,11 @@ CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(Get
} }
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const { bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair(DB_COINS, txid), coins); return db.Read(std::make_pair(DB_COINS, txid), coins);
} }
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const { bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair(DB_COINS, txid)); return db.Exists(std::make_pair(DB_COINS, txid));
} }
uint256 CCoinsViewDB::GetBestBlock() const { uint256 CCoinsViewDB::GetBestBlock() const {
@ -53,9 +51,9 @@ bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) { if (it->second.flags & CCoinsCacheEntry::DIRTY) {
if (it->second.coins.IsPruned()) if (it->second.coins.IsPruned())
batch.Erase(make_pair(DB_COINS, it->first)); batch.Erase(std::make_pair(DB_COINS, it->first));
else else
batch.Write(make_pair(DB_COINS, it->first), it->second.coins); batch.Write(std::make_pair(DB_COINS, it->first), it->second.coins);
changed++; changed++;
} }
count++; count++;
@ -73,7 +71,7 @@ CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWra
} }
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info); return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
} }
bool CBlockTreeDB::WriteReindexing(bool fReindexing) { bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
@ -139,23 +137,23 @@ void CCoinsViewDBCursor::Next()
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch(*this); CDBBatch batch(*this);
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) { for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second); batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second);
} }
batch.Write(DB_LAST_BLOCK, nLastFile); batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) { for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it)); batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
} }
return WriteBatch(batch, true); return WriteBatch(batch, true);
} }
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos); return Read(std::make_pair(DB_TXINDEX, txid), pos);
} }
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CDBBatch batch(*this); CDBBatch batch(*this);
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second); batch.Write(std::make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch); return WriteBatch(batch);
} }
@ -175,7 +173,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts(boost::function<CBlockIndex*(const uint256
{ {
std::unique_ptr<CDBIterator> pcursor(NewIterator()); std::unique_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256())); pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
// Load mapBlockIndex // Load mapBlockIndex
while (pcursor->Valid()) { while (pcursor->Valid()) {

View file

@ -18,8 +18,6 @@
#include "utiltime.h" #include "utiltime.h"
#include "version.h" #include "version.h"
using namespace std;
CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee, CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
int64_t _nTime, double _entryPriority, unsigned int _entryHeight, int64_t _nTime, double _entryPriority, unsigned int _entryHeight,
CAmount _inChainInputValue, CAmount _inChainInputValue,
@ -658,7 +656,7 @@ void CTxMemPool::check(const CCoinsViewCache *pcoins) const
const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate); const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
LOCK(cs); LOCK(cs);
list<const CTxMemPoolEntry*> waitingOnDependants; std::list<const CTxMemPoolEntry*> waitingOnDependants;
for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
unsigned int i = 0; unsigned int i = 0;
checkTotal += it->GetTxSize(); checkTotal += it->GetTxSize();
@ -816,7 +814,7 @@ std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::Get
return iters; return iters;
} }
void CTxMemPool::queryHashes(vector<uint256>& vtxid) void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{ {
LOCK(cs); LOCK(cs);
auto iters = GetSortedDepthAndScore(); auto iters = GetSortedDepthAndScore();
@ -920,7 +918,7 @@ CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
return true; return true;
} }
void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta) void CTxMemPool::PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
{ {
{ {
LOCK(cs); LOCK(cs);

View file

@ -46,8 +46,6 @@
#include <boost/math/distributions/poisson.hpp> #include <boost/math/distributions/poisson.hpp>
#include <boost/thread.hpp> #include <boost/thread.hpp>
using namespace std;
#if defined(NDEBUG) #if defined(NDEBUG)
# error "Bitcoin cannot be compiled without assertions." # error "Bitcoin cannot be compiled without assertions."
#endif #endif
@ -90,7 +88,7 @@ static void CheckBlockIndex(const Consensus::Params& consensusParams);
/** Constant stuff for coinbase transactions we create: */ /** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS; CScript COINBASE_FLAGS;
const string strMessageMagic = "Bitcoin Signed Message:\n"; const std::string strMessageMagic = "Bitcoin Signed Message:\n";
// Internal stuff // Internal stuff
namespace { namespace {
@ -123,11 +121,11 @@ namespace {
* as good as our current tip or better. Entries may be failed, though, and pruning nodes may be * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
* missing the data for the block. * missing the data for the block.
*/ */
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates; std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
/** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions. /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
* Pruned nodes may have entries where B is missing data. * Pruned nodes may have entries where B is missing data.
*/ */
multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked; std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
CCriticalSection cs_LastBlockFile; CCriticalSection cs_LastBlockFile;
std::vector<CBlockFileInfo> vinfoBlockFile; std::vector<CBlockFileInfo> vinfoBlockFile;
@ -151,10 +149,10 @@ namespace {
arith_uint256 nLastPreciousChainwork = 0; arith_uint256 nLastPreciousChainwork = 0;
/** Dirty block index entries. */ /** Dirty block index entries. */
set<CBlockIndex*> setDirtyBlockIndex; std::set<CBlockIndex*> setDirtyBlockIndex;
/** Dirty block file entries. */ /** Dirty block file entries. */
set<int> setDirtyFileInfo; std::set<int> setDirtyFileInfo;
} // anon namespace } // anon namespace
/* Use this class to start tracking transactions that are removed from the /* Use this class to start tracking transactions that are removed from the
@ -517,7 +515,7 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fChe
// Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
if (fCheckDuplicateInputs) { if (fCheckDuplicateInputs) {
set<COutPoint> vInOutPoints; std::set<COutPoint> vInOutPoints;
for (const auto& txin : tx.vin) for (const auto& txin : tx.vin)
{ {
if (!vInOutPoints.insert(txin.prevout).second) if (!vInOutPoints.insert(txin.prevout).second)
@ -596,7 +594,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
} }
// Rather not work on nonstandard transactions (unless -testnet/-regtest) // Rather not work on nonstandard transactions (unless -testnet/-regtest)
string reason; std::string reason;
if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled)) if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
return state.DoS(0, false, REJECT_NONSTANDARD, reason); return state.DoS(0, false, REJECT_NONSTANDARD, reason);
@ -611,7 +609,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool"); return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
// Check for conflicts with in-memory transactions // Check for conflicts with in-memory transactions
set<uint256> setConflicts; std::set<uint256> setConflicts;
{ {
LOCK(pool.cs); // protect pool.mapNextTx LOCK(pool.cs); // protect pool.mapNextTx
BOOST_FOREACH(const CTxIn &txin, tx.vin) BOOST_FOREACH(const CTxIn &txin, tx.vin)
@ -831,7 +829,7 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
if (fReplacementTransaction) if (fReplacementTransaction)
{ {
CFeeRate newFeeRate(nModifiedFees, nSize); CFeeRate newFeeRate(nModifiedFees, nSize);
set<uint256> setConflictsParents; std::set<uint256> setConflictsParents;
const int maxDescendantsToVisit = 100; const int maxDescendantsToVisit = 100;
CTxMemPool::setEntries setIterConflicting; CTxMemPool::setEntries setIterConflicting;
BOOST_FOREACH(const uint256 &hashConflicting, setConflicts) BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
@ -2052,13 +2050,13 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int n
{ {
std::vector<std::pair<int, const CBlockFileInfo*> > vFiles; std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
vFiles.reserve(setDirtyFileInfo.size()); vFiles.reserve(setDirtyFileInfo.size());
for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
setDirtyFileInfo.erase(it++); setDirtyFileInfo.erase(it++);
} }
std::vector<const CBlockIndex*> vBlocks; std::vector<const CBlockIndex*> vBlocks;
vBlocks.reserve(setDirtyBlockIndex.size()); vBlocks.reserve(setDirtyBlockIndex.size());
for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
vBlocks.push_back(*it); vBlocks.push_back(*it);
setDirtyBlockIndex.erase(it++); setDirtyBlockIndex.erase(it++);
} }
@ -2670,7 +2668,7 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
// to avoid miners withholding blocks but broadcasting headers, to get a // to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage. // competitive advantage.
pindexNew->nSequenceId = 0; pindexNew->nSequenceId = 0;
BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first); pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock); BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
if (miPrev != mapBlockIndex.end()) if (miPrev != mapBlockIndex.end())
@ -2707,7 +2705,7 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl
if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
deque<CBlockIndex*> queue; std::deque<CBlockIndex*> queue;
queue.push_back(pindexNew); queue.push_back(pindexNew);
// Recursively process any descendant blocks that now may be eligible to be connected. // Recursively process any descendant blocks that now may be eligible to be connected.
@ -3329,7 +3327,7 @@ void PruneOneBlockFile(const int fileNumber)
void UnlinkPrunedFiles(std::set<int>& setFilesToPrune) void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
{ {
for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) { for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
CDiskBlockPos pos(*it, 0); CDiskBlockPos pos(*it, 0);
boost::filesystem::remove(GetBlockPosFilename(pos, "blk")); boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
boost::filesystem::remove(GetBlockPosFilename(pos, "rev")); boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
@ -3347,7 +3345,7 @@ void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeig
return; return;
// last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip) // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
unsigned int nLastBlockWeCanPrune = min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP); unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
int count=0; int count=0;
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
@ -3474,8 +3472,8 @@ CBlockIndex * InsertBlockIndex(uint256 hash)
// Create new // Create new
CBlockIndex* pindexNew = new CBlockIndex(); CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew) if (!pindexNew)
throw runtime_error(std::string(__func__) + ": new CBlockIndex failed"); throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first); pindexNew->phashBlock = &((*mi).first);
return pindexNew; return pindexNew;
@ -3489,12 +3487,12 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams)
boost::this_thread::interruption_point(); boost::this_thread::interruption_point();
// Calculate nChainWork // Calculate nChainWork
vector<pair<int, CBlockIndex*> > vSortedByHeight; std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size()); vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{ {
CBlockIndex* pindex = item.second; CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
} }
sort(vSortedByHeight.begin(), vSortedByHeight.end()); sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
@ -3545,7 +3543,7 @@ bool static LoadBlockIndexDB(const CChainParams& chainparams)
// Check presence of blk files // Check presence of blk files
LogPrintf("Checking all blk files are present...\n"); LogPrintf("Checking all blk files are present...\n");
set<int> setBlkDataFiles; std::set<int> setBlkDataFiles;
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{ {
CBlockIndex* pindex = item.second; CBlockIndex* pindex = item.second;
@ -3932,7 +3930,7 @@ bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskB
NotifyHeaderTip(); NotifyHeaderTip();
// Recursively process earlier encountered successors of this block // Recursively process earlier encountered successors of this block
deque<uint256> queue; std::deque<uint256> queue;
queue.push_back(hash); queue.push_back(hash);
while (!queue.empty()) { while (!queue.empty()) {
uint256 head = queue.front(); uint256 head = queue.front();