diff --git a/src/activemasternode.cpp b/src/activemasternode.cpp index 3a71bc5f3a52..106b7bfac73b 100644 --- a/src/activemasternode.cpp +++ b/src/activemasternode.cpp @@ -184,7 +184,7 @@ bool CActiveMasternode::SendMasternodePing(std::string& errorMessage) } pmn->lastPing = mnp; - mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp)); + mnodeman.mapSeenMasternodePing.insert(std::make_pair(mnp.GetHash(), mnp)); //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); @@ -350,7 +350,7 @@ bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secr TRY_LOCK(pwalletMain->cs_wallet, fWallet); if (!fWallet) return false; - vector possibleCoins = SelectCoinsMasternode(); + std::vector possibleCoins = SelectCoinsMasternode(); COutput* selectedOutput; // Find the vin @@ -423,11 +423,11 @@ bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubke } // get all possible outputs for running Masternode -vector CActiveMasternode::SelectCoinsMasternode() +std::vector CActiveMasternode::SelectCoinsMasternode() { - vector vCoins; - vector filteredCoins; - vector confLockedCoins; + std::vector vCoins; + std::vector filteredCoins; + std::vector confLockedCoins; // Temporary unlock MN coins from masternode.conf if (GetBoolArg("-mnconflock", true)) { diff --git a/src/activemasternode.h b/src/activemasternode.h index d4e742fb62db..03ac09acf03f 100644 --- a/src/activemasternode.h +++ b/src/activemasternode.h @@ -63,7 +63,7 @@ class CActiveMasternode /// Get 10000 PIV input that can be used for the Masternode bool GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey); - vector SelectCoinsMasternode(); + std::vector SelectCoinsMasternode(); /// Enable cold wallet mode (run a Masternode with no funds) bool EnableHotColdMasterNode(CTxIn& vin, CService& addr); diff --git a/src/addrman.cpp b/src/addrman.cpp index 5718fc28fecb..8993e077cd4f 100644 --- a/src/addrman.cpp +++ b/src/addrman.cpp @@ -10,7 +10,6 @@ #include "serialize.h" #include "streams.h" -using namespace std; int CAddrInfo::GetTriedBucket(const uint256& nKey) const { @@ -70,7 +69,7 @@ double CAddrInfo::GetChance(int64_t nNow) const fChance *= 0.01; // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. - fChance *= pow(0.66, min(nAttempts, 8)); + fChance *= pow(0.66, std::min(nAttempts, 8)); return fChance; } @@ -260,7 +259,7 @@ bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimeP bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty)) - pinfo->nTime = max((int64_t)0, addr.nTime - nTimePenalty); + pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty); // add services pinfo->nServices |= addr.nServices; @@ -285,7 +284,7 @@ bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimeP return false; } else { pinfo = Create(addr, source, &nId); - pinfo->nTime = max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); + pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); nNew++; fNew = true; } diff --git a/src/alert.cpp b/src/alert.cpp index 5c5d8e8664a2..12803ad1ed15 100644 --- a/src/alert.cpp +++ b/src/alert.cpp @@ -22,9 +22,8 @@ #include #include -using namespace std; -map mapAlerts; +std::map mapAlerts; CCriticalSection cs_mapAlerts; void CUnsignedAlert::SetNull() @@ -160,7 +159,7 @@ CAlert CAlert::getAlertByHash(const uint256& hash) CAlert retval; { LOCK(cs_mapAlerts); - map::iterator mi = mapAlerts.find(hash); + std::map::iterator mi = mapAlerts.find(hash); if (mi != mapAlerts.end()) retval = mi->second; } @@ -197,7 +196,7 @@ bool CAlert::ProcessAlert(bool fThread) { LOCK(cs_mapAlerts); // Cancel previous alerts - for (map::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { + for (std::map::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { LogPrint("alert", "cancelling alert %d\n", alert.nID); @@ -221,7 +220,7 @@ bool CAlert::ProcessAlert(bool fThread) } // Add to mapAlerts - mapAlerts.insert(make_pair(GetHash(), *this)); + mapAlerts.insert(std::make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if (AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); diff --git a/src/base58.cpp b/src/base58.cpp index 996baf40eef9..da669fc73773 100644 --- a/src/base58.cpp +++ b/src/base58.cpp @@ -75,7 +75,7 @@ std::string DecodeBase58(const char* psz) for (unsigned int i = 0; i < vch.size(); i++) { unsigned char* c = &vch[i]; - ss << setw(2) << setfill('0') << (int)c[0]; + ss << std::setw(2) << std::setfill('0') << (int)c[0]; } return ss.str(); diff --git a/src/bip38.cpp b/src/bip38.cpp index 55c8eb790440..34748be29b1b 100644 --- a/src/bip38.cpp +++ b/src/bip38.cpp @@ -82,7 +82,7 @@ bool ComputePasspoint(uint256 passfactor, CPubKey& passpoint) void ComputeSeedBPass(CPubKey passpoint, std::string strAddressHash, std::string strOwnerSalt, uint512& seedBPass) { // Derive decryption key for seedb using scrypt with passpoint, addresshash, and ownerentropy - string salt = ReverseEndianString(strAddressHash + strOwnerSalt); + std::string salt = ReverseEndianString(strAddressHash + strOwnerSalt); uint256 s2(salt); scrypt_hash(BEGIN(passpoint), HexStr(passpoint).size() / 2, BEGIN(s2), salt.size() / 2, BEGIN(seedBPass), 1024, 1, 1, 64); } @@ -105,7 +105,7 @@ std::string AddressToBip38Hash(std::string address) std::string BIP38_Encrypt(std::string strAddress, std::string strPassphrase, uint256 privKey, bool fCompressed) { - string strAddressHash = AddressToBip38Hash(strAddress); + std::string strAddressHash = AddressToBip38Hash(strAddress); uint512 hashed; uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); @@ -132,7 +132,7 @@ std::string BIP38_Encrypt(std::string strAddress, std::string strPassphrase, uin uint512 encrypted2; AES_encrypt(block2.begin(), encrypted2.begin(), &key); - string strPrefix = "0142"; + std::string strPrefix = "0142"; strPrefix += (fCompressed ? "E0" : "C0"); uint512 encryptedKey(ReverseEndianString(strPrefix + strAddressHash)); @@ -273,7 +273,7 @@ bool BIP38_Decrypt(std::string strPassphrase, std::string strEncryptedKey, uint2 CKey k; k.Set(privKey.begin(), privKey.end(), fCompressed); CPubKey pubkey = k.GetPubKey(); - string address = CBitcoinAddress(pubkey.GetID()).ToString(); + std::string address = CBitcoinAddress(pubkey.GetID()).ToString(); return strAddressHash == AddressToBip38Hash(address); } diff --git a/src/bloom.cpp b/src/bloom.cpp index ba8e6b969594..b2f7f1171a6c 100644 --- a/src/bloom.cpp +++ b/src/bloom.cpp @@ -22,23 +22,22 @@ #define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 #define LN2 0.6931471805599453094172321214581765680755001343602552 -using namespace std; 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: * - nElements * log(fp rate) / ln(2)^2 * 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 * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas */ - isFull(false), - isEmpty(false), - nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), + isFull(false), + isEmpty(false), + nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), nTweak(nTweakIn), nFlags(nFlagsIn) { @@ -55,7 +54,7 @@ void CBloomFilter::setNotFull() isFull = false; } -void CBloomFilter::insert(const vector& vKey) +void CBloomFilter::insert(const std::vector& vKey) { if (isFull) return; @@ -71,17 +70,17 @@ void CBloomFilter::insert(const COutPoint& outpoint) { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; - vector data(stream.begin(), stream.end()); + std::vector data(stream.begin(), stream.end()); insert(data); } void CBloomFilter::insert(const uint256& hash) { - vector data(hash.begin(), hash.end()); + std::vector data(hash.begin(), hash.end()); insert(data); } -bool CBloomFilter::contains(const vector& vKey) const +bool CBloomFilter::contains(const std::vector& vKey) const { if (isFull) { return true; @@ -102,13 +101,13 @@ bool CBloomFilter::contains(const COutPoint& outpoint) const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << outpoint; - vector data(stream.begin(), stream.end()); + std::vector data(stream.begin(), stream.end()); return contains(data); } bool CBloomFilter::contains(const uint256& hash) const { - vector data(hash.begin(), hash.end()); + std::vector data(hash.begin(), hash.end()); return contains(data); } @@ -176,7 +175,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& 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. CScript::const_iterator pc = txout.scriptPubKey.begin(); - vector data; + std::vector data; while (pc < txout.scriptPubKey.end()) { opcodetype opcode; if (!txout.scriptPubKey.GetOp(pc, opcode, data)){ @@ -184,7 +183,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx) } if (txout.IsZerocoinMint()){ - data = vector(txout.scriptPubKey.begin() + 6, txout.scriptPubKey.begin() + txout.scriptPubKey.size()); + data = std::vector(txout.scriptPubKey.begin() + 6, txout.scriptPubKey.begin() + txout.scriptPubKey.size()); } if (data.size() != 0 && contains(data)) { @@ -193,7 +192,7 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx) insert(COutPoint(hash, i)); else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) { txnouttype type; - vector > vSolutions; + std::vector > vSolutions; if (Solver(txout.scriptPubKey, type, vSolutions) && (type == TX_PUBKEY || type == TX_MULTISIG)) insert(COutPoint(hash, i)); @@ -213,13 +212,13 @@ bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx) // Match if the filter contains any arbitrary script data element in any scriptSig in tx CScript::const_iterator pc = txin.scriptSig.begin(); - vector data; + std::vector data; while (pc < txin.scriptSig.end()) { opcodetype opcode; if (!txin.scriptSig.GetOp(pc, opcode, data)) break; if (txin.IsZerocoinSpend()) { - CDataStream s(vector(txin.scriptSig.begin() + 44, txin.scriptSig.end()), + CDataStream s(std::vector(txin.scriptSig.begin() + 44, txin.scriptSig.end()), SER_NETWORK, PROTOCOL_VERSION); data = libzerocoin::CoinSpend::ParseSerial(s); diff --git a/src/chain.cpp b/src/chain.cpp index 4d9c47a37a0a..8a19cbc6dd20 100644 --- a/src/chain.cpp +++ b/src/chain.cpp @@ -6,7 +6,6 @@ #include "chain.h" -using namespace std; /** * CChain implementation diff --git a/src/chain.h b/src/chain.h index b418f0589472..eeefa6074aa1 100644 --- a/src/chain.h +++ b/src/chain.h @@ -211,7 +211,7 @@ class CBlockIndex nAccumulatorCheckpoint = 0; // Start supply of each denomination with 0s for (auto& denom : libzerocoin::zerocoinDenomList) { - mapZerocoinSupply.insert(make_pair(denom, 0)); + mapZerocoinSupply.insert(std::make_pair(denom, 0)); } vMintDenominationsInBlock.clear(); } diff --git a/src/chainparams.cpp b/src/chainparams.cpp index b46080c38a65..19d6baa128e4 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -15,8 +15,6 @@ #include -using namespace std; -using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; @@ -186,7 +184,7 @@ class CMainParams : public CChainParams CMutableTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); - txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); + txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 250 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9") << OP_CHECKSIG; genesis.vtx.push_back(txNew); diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp index 702d5224561a..3a6e2f1e76a7 100644 --- a/src/chainparamsbase.cpp +++ b/src/chainparamsbase.cpp @@ -12,7 +12,6 @@ #include -using namespace boost::assign; /** * Main network diff --git a/src/core_read.cpp b/src/core_read.cpp index c2e8c447f07b..971347005712 100644 --- a/src/core_read.cpp +++ b/src/core_read.cpp @@ -21,15 +21,12 @@ #include #include -using namespace boost; -using namespace boost::algorithm; -using namespace std; CScript ParseScript(std::string s) { CScript result; - static map mapOpNames; + static std::map mapOpNames; if (mapOpNames.empty()) { for (int op = 0; op <= OP_ZEROCOINSPEND; op++) { @@ -40,30 +37,30 @@ CScript ParseScript(std::string s) const char* name = GetOpName((opcodetype)op); if (strcmp(name, "OP_UNKNOWN") == 0) continue; - string strName(name); + std::string strName(name); mapOpNames[strName] = (opcodetype)op; // Convenience: OP_ADD and just ADD are both recognized: - replace_first(strName, "OP_", ""); + boost::algorithm::replace_first(strName, "OP_", ""); mapOpNames[strName] = (opcodetype)op; } } - vector words; - split(words, s, is_any_of(" \t\n"), token_compress_on); + std::vector words; + boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on); for (std::vector::const_iterator w = words.begin(); w != words.end(); ++w) { if (w->empty()) { // Empty string, ignore. (boost::split given '' will return one word) - } else if (all(*w, is_digit()) || - (starts_with(*w, "-") && all(string(w->begin() + 1, w->end()), is_digit()))) { + } else if (all(*w, boost::algorithm::is_digit()) || + (boost::algorithm::starts_with(*w, "-") && all(std::string(w->begin() + 1, w->end()), boost::algorithm::is_digit()))) { // Number int64_t n = atoi64(*w); result << n; - } else if (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: - std::vector raw = ParseHex(string(w->begin() + 2, w->end())); + std::vector raw = ParseHex(std::string(w->begin() + 2, w->end())); result.insert(result.end(), raw.begin(), raw.end()); - } else if (w->size() >= 2 && starts_with(*w, "'") && ends_with(*w, "'")) { + } else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'")) { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. std::vector value(w->begin() + 1, w->end() - 1); @@ -72,7 +69,7 @@ CScript ParseScript(std::string s) // opcode, e.g. OP_ADD or ADD: result << mapOpNames[*w]; } else { - throw runtime_error("script parse error"); + throw std::runtime_error("script parse error"); } } @@ -84,7 +81,7 @@ bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx) if (!IsHex(strHexTx)) return false; - vector txData(ParseHex(strHexTx)); + std::vector txData(ParseHex(strHexTx)); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); try { ssData >> tx; @@ -111,30 +108,30 @@ bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk) 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()) strHex = v.getValStr(); - return ParseHashStr(strHex, strName); // Note: ParseHashStr("") throws a runtime_error + return ParseHashStr(strHex, strName); // Note: ParseHashStr("") throws a std::runtime_error } uint256 ParseHashStr(const std::string& strHex, const std::string& strName) { 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; result.SetHex(strHex); return result; } -vector ParseHexUV(const UniValue& v, const string& strName) +std::vector ParseHexUV(const UniValue& v, const std::string& strName) { - string strHex; + std::string strHex; if (v.isStr()) strHex = v.getValStr(); 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); } diff --git a/src/core_write.cpp b/src/core_write.cpp index c6de70eb52a8..cc91b232489e 100644 --- a/src/core_write.cpp +++ b/src/core_write.cpp @@ -17,16 +17,15 @@ #include "utilstrencodings.h" -using namespace std; -string FormatScript(const CScript& script) +std::string FormatScript(const CScript& script) { - string ret; + std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; - vector vch; + std::vector vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; @@ -35,9 +34,9 @@ string FormatScript(const CScript& script) ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_CHECKMULTISIGVERIFY) { - string str(GetOpName(op)); - if (str.substr(0, 3) == string("OP_")) { - ret += str.substr(3, string::npos) + " "; + std::string str(GetOpName(op)); + if (str.substr(0, 3) == std::string("OP_")) { + ret += str.substr(3, std::string::npos) + " "; continue; } } @@ -54,7 +53,7 @@ string FormatScript(const CScript& script) return ret.substr(0, ret.size() - 1); } -string EncodeHexTx(const CTransaction& tx) +std::string EncodeHexTx(const CTransaction& tx) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; @@ -66,7 +65,7 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey, bool fIncludeHex) { txnouttype type; - vector addresses; + std::vector addresses; int nRequired; out.pushKV("asm", scriptPubKey.ToString()); diff --git a/src/crypter.cpp b/src/crypter.cpp index 3ef7e83ae411..5f4c80c33e26 100644 --- a/src/crypter.cpp +++ b/src/crypter.cpp @@ -375,14 +375,14 @@ bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) bool CCryptoKeyStore::AddDeterministicSeed(const uint256& seed) { CWalletDB db(pwalletMain->strWalletFile); - string strErr; + std::string strErr; uint256 hashSeed = Hash(seed.begin(), seed.end()); if(IsCrypted()) { if (!IsLocked()) { //if we have password CKeyingMaterial kmSeed(seed.begin(), seed.end()); - vector vchSeedSecret; + std::vector vchSeedSecret; //attempt encrypt @@ -410,11 +410,11 @@ bool CCryptoKeyStore::GetDeterministicSeed(const uint256& hashSeed, uint256& see { CWalletDB db(pwalletMain->strWalletFile); - string strErr; + std::string strErr; if (IsCrypted()) { if(!IsLocked()) { //if we have password - vector vchCryptedSeed; + std::vector vchCryptedSeed; //read encrypted seed if (db.ReadZPIVSeed(hashSeed, vchCryptedSeed)) { uint256 seedRetrieved = uint256(ReverseEndianString(HexStr(vchCryptedSeed))); @@ -435,7 +435,7 @@ bool CCryptoKeyStore::GetDeterministicSeed(const uint256& hashSeed, uint256& see } else { strErr = "read seed from wallet"; } } else { strErr = "read seed; wallet is locked"; } } else { - vector vchSeed; + std::vector vchSeed; // wallet not crypted if (db.ReadZPIVSeed(hashSeed, vchSeed)) { seedOut = uint256(ReverseEndianString(HexStr(vchSeed))); diff --git a/src/denomination_functions.cpp b/src/denomination_functions.cpp index ed4aed6e51f2..ac22520ab17b 100644 --- a/src/denomination_functions.cpp +++ b/src/denomination_functions.cpp @@ -4,16 +4,15 @@ #include "denomination_functions.h" -using namespace libzerocoin; // ------------------------------------------------------------------------------------------------------- // Number of coins used for either change or a spend given a map of coins used // ------------------------------------------------------------------------------------------------------- int getNumberOfCoinsUsed( - const std::map& mapChange) + const std::map& mapChange) { int nChangeCount = 0; - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { nChangeCount += mapChange.at(denom); } return nChangeCount; @@ -22,11 +21,11 @@ int getNumberOfCoinsUsed( // ------------------------------------------------------------------------------------------------------- // Find the max CoinDenomination amongst held coins // ------------------------------------------------------------------------------------------------------- -CoinDenomination getMaxDenomHeld( - const std::map& mapCoinsHeld) +libzerocoin::CoinDenomination getMaxDenomHeld( + const std::map& mapCoinsHeld) { - CoinDenomination maxDenom = ZQ_ERROR; - for (auto& coin : reverse_iterate(zerocoinDenomList)) { + libzerocoin::CoinDenomination maxDenom = libzerocoin::ZQ_ERROR; + for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) { if (mapCoinsHeld.at(coin)) { maxDenom = coin; break; @@ -37,19 +36,19 @@ CoinDenomination getMaxDenomHeld( // ------------------------------------------------------------------------------------------------------- // Get Exact Amount with CoinsHeld // ------------------------------------------------------------------------------------------------------- -std::map getSpendCoins(const CAmount nValueTarget, - const std::map mapOfDenomsHeld) +std::map getSpendCoins(const CAmount nValueTarget, + const std::map mapOfDenomsHeld) { - std::map mapUsed; + std::map mapUsed; CAmount nRemainingValue = nValueTarget; // Initialize - for (const auto& denom : zerocoinDenomList) - mapUsed.insert(std::pair(denom, 0)); + for (const auto& denom : libzerocoin::zerocoinDenomList) + mapUsed.insert(std::pair(denom, 0)); // Start with the Highest Denomination coin and grab coins as long as the remaining amount is greater than the // current denomination value and we have the denom - for (auto& coin : reverse_iterate(zerocoinDenomList)) { + for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) { CAmount nValue = ZerocoinDenominationToAmount(coin); do { if ((nRemainingValue >= nValue) && (mapUsed.at(coin) < mapOfDenomsHeld.at(coin))) { @@ -64,17 +63,17 @@ std::map getSpendCoins(const CAmount nValueTarget, // ------------------------------------------------------------------------------------------------------- // Get change (no limits) // ------------------------------------------------------------------------------------------------------- -std::map getChange(const CAmount nValueTarget) +std::map getChange(const CAmount nValueTarget) { - std::map mapChange; + std::map mapChange; CAmount nRemainingValue = nValueTarget; // Initialize - for (const auto& denom : zerocoinDenomList) - mapChange.insert(std::pair(denom, 0)); + for (const auto& denom : libzerocoin::zerocoinDenomList) + mapChange.insert(std::pair(denom, 0)); // Start with the Highest Denomination coin and grab coins as long as the remaining amount is greater than the // current denomination value - for (auto& coin : reverse_iterate(zerocoinDenomList)) { + for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) { CAmount nValue = ZerocoinDenominationToAmount(coin); do { if (nRemainingValue >= nValue) { @@ -93,17 +92,17 @@ std::map getChange(const CAmount nValueTarget) bool getIdealSpends( const CAmount nValueTarget, const std::list& listMints, - const std::map mapOfDenomsHeld, - std::map& mapOfDenomsUsed) + const std::map mapOfDenomsHeld, + std::map& mapOfDenomsUsed) { CAmount nRemainingValue = nValueTarget; // Initialize - for (const auto& denom : zerocoinDenomList) - mapOfDenomsUsed.insert(std::pair(denom, 0)); + for (const auto& denom : libzerocoin::zerocoinDenomList) + mapOfDenomsUsed.insert(std::pair(denom, 0)); // Start with the Highest Denomination coin and grab coins as long as the remaining amount is greater than the // current denomination value - for (auto& coin : reverse_iterate(zerocoinDenomList)) { + for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) { for (const CMintMeta& mint : listMints) { if (mint.isUsed) continue; if (nRemainingValue >= ZerocoinDenominationToAmount(coin) && coin == mint.denom) { @@ -121,12 +120,12 @@ bool getIdealSpends( // ------------------------------------------------------------------------------------------------------- std::vector getSpends( const std::list& listMints, - std::map& mapOfDenomsUsed, + std::map& mapOfDenomsUsed, CAmount& nCoinsSpentValue) { std::vector vSelectedMints; nCoinsSpentValue = 0; - for (auto& coin : reverse_iterate(zerocoinDenomList)) { + for (auto& coin : reverse_iterate(libzerocoin::zerocoinDenomList)) { do { for (const CMintMeta& mint : listMints) { if (mint.isUsed) continue; @@ -165,12 +164,12 @@ void listSpends(const std::vector& vSelectedMints) // ------------------------------------------------------------------------------------------------------- // Find the CoinDenomination with the most number for a given amount // ------------------------------------------------------------------------------------------------------- -CoinDenomination getDenomWithMostCoins( - const std::map& mapOfDenomsUsed) +libzerocoin::CoinDenomination getDenomWithMostCoins( + const std::map& mapOfDenomsUsed) { - CoinDenomination maxCoins = ZQ_ERROR; + libzerocoin::CoinDenomination maxCoins = libzerocoin::ZQ_ERROR; CAmount nMaxNumber = 0; - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { CAmount amount = mapOfDenomsUsed.at(denom); if (amount > nMaxNumber) { nMaxNumber = amount; @@ -182,10 +181,10 @@ CoinDenomination getDenomWithMostCoins( // ------------------------------------------------------------------------------------------------------- // Get the next denomination above the current one. Return ZQ_ERROR if already at the highest // ------------------------------------------------------------------------------------------------------- -CoinDenomination getNextHighestDenom(const CoinDenomination& this_denom) +libzerocoin::CoinDenomination getNextHighestDenom(const libzerocoin::CoinDenomination& this_denom) { - CoinDenomination nextValue = ZQ_ERROR; - for (const auto& denom : zerocoinDenomList) { + libzerocoin::CoinDenomination nextValue = libzerocoin::ZQ_ERROR; + for (const auto& denom : libzerocoin::zerocoinDenomList) { if (ZerocoinDenominationToAmount(denom) > ZerocoinDenominationToAmount(this_denom)) { nextValue = denom; break; @@ -197,11 +196,11 @@ CoinDenomination getNextHighestDenom(const CoinDenomination& this_denom) // Get the next denomination below the current one that is also amongst those held. // Return ZQ_ERROR if none found // ------------------------------------------------------------------------------------------------------- -CoinDenomination getNextLowerDenomHeld(const CoinDenomination& this_denom, - const std::map& mapCoinsHeld) +libzerocoin::CoinDenomination getNextLowerDenomHeld(const libzerocoin::CoinDenomination& this_denom, + const std::map& mapCoinsHeld) { - CoinDenomination nextValue = ZQ_ERROR; - for (auto& denom : reverse_iterate(zerocoinDenomList)) { + libzerocoin::CoinDenomination nextValue = libzerocoin::ZQ_ERROR; + for (auto& denom : reverse_iterate(libzerocoin::zerocoinDenomList)) { if ((denom < this_denom) && (mapCoinsHeld.at(denom) != 0)) { nextValue = denom; break; @@ -213,10 +212,10 @@ CoinDenomination getNextLowerDenomHeld(const CoinDenomination& this_denom, int minimizeChange( int nMaxNumberOfSpends, int nChangeCount, - const CoinDenomination nextToMaxDenom, + const libzerocoin::CoinDenomination nextToMaxDenom, const CAmount nValueTarget, - const std::map& mapOfDenomsHeld, - std::map& mapOfDenomsUsed) + const std::map& mapOfDenomsHeld, + std::map& mapOfDenomsUsed) { // Now find out if possible without using 1 coin such that we have more spends but less change // First get set of coins close to value but still less than value (since not exact) @@ -225,13 +224,13 @@ int minimizeChange( int nCoinCount = 0; // Re-clear this - std::map savedMapOfDenomsUsed = mapOfDenomsUsed; - for (const auto& denom : zerocoinDenomList) + std::map savedMapOfDenomsUsed = mapOfDenomsUsed; + for (const auto& denom : libzerocoin::zerocoinDenomList) mapOfDenomsUsed.at(denom) = 0; // Find the amount this is less than total but uses up higher denoms first, // starting at the denom that is not greater than the overall total - for (const auto& denom : reverse_iterate(zerocoinDenomList)) { + for (const auto& denom : reverse_iterate(libzerocoin::zerocoinDenomList)) { if (denom <= nextToMaxDenom) { CAmount nValue = ZerocoinDenominationToAmount(denom); do { @@ -248,7 +247,7 @@ int minimizeChange( // Now work way back up from the bottom filling in with the denom that we have that is just // bigger than the remaining amount // Shouldn't need more than one coin here? - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { CAmount nValue = ZerocoinDenominationToAmount(denom); if ((nValue > nRemainingValue) && (mapOfDenomsUsed.at(denom) < mapOfDenomsHeld.at(denom))) { mapOfDenomsUsed.at(denom)++; @@ -266,11 +265,11 @@ int minimizeChange( // So 5 is no longer needed and will become change also CAmount nAltChangeAmount = AmountUsed - nValueTarget; - std::map mapAltChange = getChange(nAltChangeAmount); + std::map mapAltChange = getChange(nAltChangeAmount); // Check if there is overlap between change and spend denominations // And if so, remove those that overlap - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { do { if (mapAltChange.at(denom) && mapOfDenomsUsed.at(denom)) { mapOfDenomsUsed.at(denom)--; @@ -311,32 +310,32 @@ int calculateChange( int nMaxNumberOfSpends, bool fMinimizeChange, const CAmount nValueTarget, - const std::map& mapOfDenomsHeld, - std::map& mapOfDenomsUsed) + const std::map& mapOfDenomsHeld, + std::map& mapOfDenomsUsed) { - CoinDenomination minDenomOverTarget = ZQ_ERROR; + libzerocoin::CoinDenomination minDenomOverTarget = libzerocoin::ZQ_ERROR; // Initialize mapOfDenomsUsed.clear(); - for (const auto& denom : zerocoinDenomList) - mapOfDenomsUsed.insert(std::pair(denom, 0)); + for (const auto& denom : libzerocoin::zerocoinDenomList) + mapOfDenomsUsed.insert(std::pair(denom, 0)); - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { if (nValueTarget < ZerocoinDenominationToAmount(denom) && mapOfDenomsHeld.at(denom)) { minDenomOverTarget = denom; break; } } // OK so if != ZQ_ERROR we have a solution using 1 coin - if (minDenomOverTarget != ZQ_ERROR) { + if (minDenomOverTarget != libzerocoin::ZQ_ERROR) { mapOfDenomsUsed.at(minDenomOverTarget) = 1; // Now find out # of coins in change CAmount nChangeAmount = ZerocoinDenominationToAmount(minDenomOverTarget) - nValueTarget; - std::map mapChange = getChange(nChangeAmount); + std::map mapChange = getChange(nChangeAmount); int nChangeCount = getNumberOfCoinsUsed(mapChange); if (fMinimizeChange) { - CoinDenomination nextToMaxDenom = getNextLowerDenomHeld(minDenomOverTarget, mapOfDenomsHeld); + libzerocoin::CoinDenomination nextToMaxDenom = getNextLowerDenomHeld(minDenomOverTarget, mapOfDenomsHeld); int newChangeCount = minimizeChange(nMaxNumberOfSpends, nChangeCount, nextToMaxDenom, nValueTarget, mapOfDenomsHeld, mapOfDenomsUsed); @@ -345,7 +344,7 @@ int calculateChange( if (newChangeCount < nChangeCount) return newChangeCount; // Reclear - for (const auto& denom : zerocoinDenomList) + for (const auto& denom : libzerocoin::zerocoinDenomList) mapOfDenomsUsed.at(denom) = 0; // Then reset as before previous clearing mapOfDenomsUsed.at(minDenomOverTarget) = 1; @@ -355,12 +354,12 @@ int calculateChange( } else { // Try to meet a different way - for (const auto& denom : zerocoinDenomList) + for (const auto& denom : libzerocoin::zerocoinDenomList) mapOfDenomsUsed.at(denom) = 0; CAmount nRemainingValue = nValueTarget; int nCoinCount = 0; CAmount AmountUsed = 0; - for (const auto& denom : reverse_iterate(zerocoinDenomList)) { + for (const auto& denom : reverse_iterate(libzerocoin::zerocoinDenomList)) { CAmount nValue = ZerocoinDenominationToAmount(denom); do { if (mapOfDenomsHeld.at(denom) && nRemainingValue > 0) { @@ -374,14 +373,14 @@ int calculateChange( } CAmount nChangeAmount = AmountUsed - nValueTarget; - std::map mapChange = getChange(nChangeAmount); + std::map mapChange = getChange(nChangeAmount); int nMaxChangeCount = getNumberOfCoinsUsed(mapChange); // Instead get max Denom held - CoinDenomination maxDenomHeld = getMaxDenomHeld(mapOfDenomsHeld); + libzerocoin::CoinDenomination maxDenomHeld = getMaxDenomHeld(mapOfDenomsHeld); // Assign for size (only) - std::map mapOfMinDenomsUsed = mapOfDenomsUsed; + std::map mapOfMinDenomsUsed = mapOfDenomsUsed; int nChangeCount = minimizeChange(nMaxNumberOfSpends, nMaxChangeCount, maxDenomHeld, nValueTarget, @@ -404,10 +403,10 @@ int calculateChange( // ------------------------------------------------------------------------------------------------------- std::vector SelectMintsFromList(const CAmount nValueTarget, CAmount& nSelectedValue, int nMaxNumberOfSpends, bool fMinimizeChange, int& nCoinsReturned, const std::list& listMints, - const std::map mapOfDenomsHeld, int& nNeededSpends) + const std::map mapOfDenomsHeld, int& nNeededSpends) { std::vector vSelectedMints; - std::map mapOfDenomsUsed; + std::map mapOfDenomsUsed; nNeededSpends = 0; bool fCanMeetExactly = getIdealSpends(nValueTarget, listMints, mapOfDenomsHeld, mapOfDenomsUsed); diff --git a/src/hash.h b/src/hash.h index 3bc8486391cf..0e5ae5f6e8b4 100644 --- a/src/hash.h +++ b/src/hash.h @@ -27,7 +27,6 @@ #include #include -using namespace std; typedef uint256 ChainCode; @@ -156,9 +155,9 @@ inline std::string Hash(std::string input) SHA256_Init(&sha256); SHA256_Update(&sha256, input.c_str(), input.size()); SHA256_Final(hash, &sha256); - stringstream ss; + std::stringstream ss; for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { - ss << hex << setw(2) << setfill('0') << (int)hash[i]; + ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i]; } return ss.str(); } diff --git a/src/httpserver.h b/src/httpserver.h index 0e30e666a6b4..e320026b256a 100644 --- a/src/httpserver.h +++ b/src/httpserver.h @@ -82,7 +82,7 @@ class HTTPRequest /** * Get the request header specified by hdr, or an empty string. - * Return an pair (isPresent,string). + * Return an pair (isPresent,std::string). */ std::pair GetHeader(const std::string& hdr); diff --git a/src/init.cpp b/src/init.cpp index ac3184315b76..0dccae49f273 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -69,8 +69,6 @@ #include "zmq/zmqnotificationinterface.h" #endif -using namespace boost; -using namespace std; #ifdef ENABLE_WALLET CWallet* pwalletMain = NULL; @@ -364,17 +362,17 @@ void OnRPCPreCommand(const CRPCCommand& cmd) #endif // Observe safe mode - string strWarning = GetWarnings("rpc"); + std::string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !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) { // When adding new options to the categories, please keep and ensure alphabetical ordering. - string strUsage = HelpMessageGroup(_("Options:")); + std::string strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-version", _("Print version and exit")); strUsage += HelpMessageOpt("-alertnotify=", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)")); @@ -501,7 +499,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-stopafterblockimport", strprintf(_("Stop running after importing blocks from disk (default: %u)"), 0)); strUsage += HelpMessageOpt("-sporkkey=", _("Enable spork administration functionality with the appropriate private key.")); } - string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, tor, mempool, net, proxy, http, libevent, pivx, (obfuscation, swiftx, masternode, mnpayments, mnbudget, zero, precompute, staking)"; // Don't translate these and qt below + std::string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, tor, mempool, net, proxy, http, libevent, pivx, (obfuscation, swiftx, masternode, mnpayments, mnbudget, zero, precompute, staking)"; // Don't translate these and qt below if (mode == HMM_BITCOIN_QT) debugCategories += ", qt"; strUsage += HelpMessageOpt("-debug=", strprintf(_("Output debugging information (default: %u, supplying is optional)"), 0) + ". " + @@ -679,12 +677,12 @@ void ThreadImport(std::vector vImportFiles) } // hardcoded $DATADIR/bootstrap.dat - filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; - if (filesystem::exists(pathBootstrap)) { + boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; + if (boost::filesystem::exists(pathBootstrap)) { FILE* file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { CImportingNow imp; - filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; + boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LogPrintf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); @@ -895,8 +893,8 @@ bool AppInit2() fDebug = !mapMultiArgs["-debug"].empty(); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages - const vector& categories = mapMultiArgs["-debug"]; - if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) + const std::vector& categories = mapMultiArgs["-debug"]; + if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end()) fDebug = false; // Check for -debugnet @@ -1096,15 +1094,15 @@ bool AppInit2() // ********************************************************* Step 5: Backup wallet and verify wallet database integrity #ifdef ENABLE_WALLET if (!fDisableWallet) { - filesystem::path backupDir = GetDataDir() / "backups"; - if (!filesystem::exists(backupDir)) { + boost::filesystem::path backupDir = GetDataDir() / "backups"; + if (!boost::filesystem::exists(backupDir)) { // Always create backup folder to not confuse the operating system's file browser - filesystem::create_directories(backupDir); + boost::filesystem::create_directories(backupDir); } nWalletBackups = GetArg("-createwalletbackups", 10); nWalletBackups = std::max(0, std::min(10, nWalletBackups)); if (nWalletBackups > 0) { - if (filesystem::exists(backupDir)) { + if (boost::filesystem::exists(backupDir)) { // Create backup of the wallet std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime()); std::string backupPathStr = backupDir.string(); @@ -1167,30 +1165,30 @@ bool AppInit2() if (GetBoolArg("-resync", false)) { uiInterface.InitMessage(_("Preparing for resync...")); // Delete the local blockchain folders to force a resync from scratch to get a consitent blockchain-state - filesystem::path blocksDir = GetDataDir() / "blocks"; - filesystem::path chainstateDir = GetDataDir() / "chainstate"; - filesystem::path sporksDir = GetDataDir() / "sporks"; - filesystem::path zerocoinDir = GetDataDir() / "zerocoin"; + boost::filesystem::path blocksDir = GetDataDir() / "blocks"; + boost::filesystem::path chainstateDir = GetDataDir() / "chainstate"; + boost::filesystem::path sporksDir = GetDataDir() / "sporks"; + boost::filesystem::path zerocoinDir = GetDataDir() / "zerocoin"; LogPrintf("Deleting blockchain folders blocks, chainstate, sporks and zerocoin\n"); // We delete in 4 individual steps in case one of the folder is missing already try { - if (filesystem::exists(blocksDir)){ + if (boost::filesystem::exists(blocksDir)){ boost::filesystem::remove_all(blocksDir); LogPrintf("-resync: folder deleted: %s\n", blocksDir.string().c_str()); } - if (filesystem::exists(chainstateDir)){ + if (boost::filesystem::exists(chainstateDir)){ boost::filesystem::remove_all(chainstateDir); LogPrintf("-resync: folder deleted: %s\n", chainstateDir.string().c_str()); } - if (filesystem::exists(sporksDir)){ + if (boost::filesystem::exists(sporksDir)){ boost::filesystem::remove_all(sporksDir); LogPrintf("-resync: folder deleted: %s\n", sporksDir.string().c_str()); } - if (filesystem::exists(zerocoinDir)){ + if (boost::filesystem::exists(zerocoinDir)){ boost::filesystem::remove_all(zerocoinDir); LogPrintf("-resync: folder deleted: %s\n", zerocoinDir.string().c_str()); } @@ -1216,7 +1214,7 @@ bool AppInit2() // try again if (!bitdb.Open(GetDataDir())) { // if it still fails, it probably means we can't even create the database env - string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir); + std::string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir); return InitError(msg); } } @@ -1227,10 +1225,10 @@ bool AppInit2() return false; } - if (filesystem::exists(GetDataDir() / strWalletFile)) { + if (boost::filesystem::exists(GetDataDir() / strWalletFile)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { - string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" + std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), @@ -1364,7 +1362,7 @@ bool AppInit2() } if (mapArgs.count("-externalip")) { - for (string strAddr : mapMultiArgs["-externalip"]) { + for (std::string strAddr : mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr)); @@ -1372,7 +1370,7 @@ bool AppInit2() } } - for (string strDest : mapMultiArgs["-seednode"]) + for (std::string strDest : mapMultiArgs["-seednode"]) AddOneShot(strDest); #if ENABLE_ZMQ @@ -1391,19 +1389,19 @@ bool AppInit2() fReindex = GetBoolArg("-reindex", false); // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ - filesystem::path blocksDir = GetDataDir() / "blocks"; - if (!filesystem::exists(blocksDir)) { - filesystem::create_directories(blocksDir); + boost::filesystem::path blocksDir = GetDataDir() / "blocks"; + if (!boost::filesystem::exists(blocksDir)) { + boost::filesystem::create_directories(blocksDir); bool linked = false; for (unsigned int i = 1; i < 10000; i++) { - filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); - if (!filesystem::exists(source)) break; - filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i - 1); + boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); + if (!boost::filesystem::exists(source)) break; + boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i - 1); try { - filesystem::create_hard_link(source, dest); + boost::filesystem::create_hard_link(source, dest); LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string()); linked = true; - } catch (filesystem::filesystem_error& e) { + } catch (boost::filesystem::filesystem_error& e) { // Note: hardlink creation failing is not a disaster, it just means // blocks will get re-downloaded from peers. LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); @@ -1464,7 +1462,7 @@ bool AppInit2() LoadSporksFromDB(); uiInterface.InitMessage(_("Loading block index...")); - string strBlockIndexError = ""; + std::string strBlockIndexError = ""; if (!LoadBlockIndex(strBlockIndexError)) { strLoadError = _("Error loading block database"); strLoadError = strprintf("%s : %s", strLoadError, strBlockIndexError); @@ -1563,7 +1561,7 @@ bool AppInit2() uiInterface.InitMessage(_("Calculating missing accumulators...")); LogPrintf("%s : finding missing checkpoints\n", __func__); - string strError; + std::string strError; if (!ReindexAccumulators(listAccCheckpointsNoDB, strError)) return InitError(strError); } @@ -1676,7 +1674,7 @@ bool AppInit2() if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { - string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" + std::string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); InitWarning(msg); } else if (nLoadWalletRet == DB_TOO_NEW) @@ -1797,7 +1795,7 @@ bool AppInit2() std::vector vImportFiles; if (mapArgs.count("-loadblock")) { - for (string strFile : mapMultiArgs["-loadblock"]) + for (std::string strFile : mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); diff --git a/src/kernel.cpp b/src/kernel.cpp index 549b58fdfb26..3e846c4a519e 100644 --- a/src/kernel.cpp +++ b/src/kernel.cpp @@ -14,7 +14,6 @@ #include "utilmoneystr.h" #include "zpivchain.h" -using namespace std; bool fTestNet = false; //Params().NetworkID() == CBaseChainParams::TESTNET; @@ -76,8 +75,8 @@ static int64_t GetStakeModifierSelectionInterval() // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates( - vector >& vSortedByTimestamp, - map& mapSelectedBlocks, + std::vector >& vSortedByTimestamp, + std::map& mapSelectedBlocks, int64_t nSelectionIntervalStop, uint64_t nStakeModifierPrev, const CBlockIndex** pindexSelected) @@ -176,26 +175,26 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeMod return true; // Sort candidate blocks by timestamp - vector > vSortedByTimestamp; + std::vector > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * getIntervalVersion(fTestNet) / nStakeTargetSpacing); int64_t nSelectionInterval = GetStakeModifierSelectionInterval(); int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet)) * getIntervalVersion(fTestNet) - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { - vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); + vSortedByTimestamp.push_back(std::make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; - reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); - sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); + std::reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); + std::sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64_t nStakeModifierNew = 0; int64_t nSelectionIntervalStop = nSelectionIntervalStart; - map mapSelectedBlocks; - for (int nRound = 0; nRound < min(64, (int)vSortedByTimestamp.size()); nRound++) { + std::map mapSelectedBlocks; + for (int nRound = 0; nRound < std::min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); @@ -207,7 +206,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeMod nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list - mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); + mapSelectedBlocks.insert(std::make_pair(pindex->GetBlockHash(), pindex)); if (GetBoolArg("-printstakemodifier", false)) LogPrintf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit()); @@ -215,7 +214,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeMod // Print selection map for visualization of the selected blocks if (GetBoolArg("-printstakemodifier", false)) { - string strSelectionMap = ""; + std::string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; diff --git a/src/libzerocoin/Coin.cpp b/src/libzerocoin/Coin.cpp index 6a460a06f30a..73ff70e3d2df 100644 --- a/src/libzerocoin/Coin.cpp +++ b/src/libzerocoin/Coin.cpp @@ -104,7 +104,7 @@ PrivateCoin::PrivateCoin(const ZerocoinParams* p, const CoinDenomination denomin bool PrivateCoin::IsValid() { if (!IsValidSerial(params, serialNumber)) { - cout << "Serial not valid\n"; + std::cout << "Serial not valid\n"; return false; } @@ -150,7 +150,7 @@ const CPubKey PrivateCoin::getPubKey() const return key.GetPubKey(); } -bool PrivateCoin::sign(const uint256& hash, vector& vchSig) const +bool PrivateCoin::sign(const uint256& hash, std::vector& vchSig) const { CKey key; key.SetPrivKey(privkey, true); diff --git a/src/libzerocoin/Coin.h b/src/libzerocoin/Coin.h index b96ca6ddd574..3c77f812ba40 100644 --- a/src/libzerocoin/Coin.h +++ b/src/libzerocoin/Coin.h @@ -26,7 +26,7 @@ namespace libzerocoin class InvalidSerialException : public std::exception { public: std::string message; - InvalidSerialException(const string &message) : message(message) {} + InvalidSerialException(const std::string &message) : message(message) {} }; int ExtractVersionFromSerial(const CBigNum& bnSerial); @@ -53,11 +53,11 @@ class PublicCoin PublicCoin(const ZerocoinParams* p); /**Generates a public coin - * - * @param p cryptographic paramters - * @param coin the value of the commitment. - * @param denomination The denomination of the coin. - */ + * + * @param p cryptographic paramters + * @param coin the value of the commitment. + * @param denomination The denomination of the coin. + */ PublicCoin(const ZerocoinParams* p, const CBigNum& coin, const CoinDenomination d); const CBigNum& getValue() const { return this->value; } @@ -149,31 +149,31 @@ class PrivateCoin CPrivKey privkey; /** - * @brief Mint a new coin. - * @param denomination the denomination of the coin to mint - * @throws ZerocoinException if the process takes too long - * - * Generates a new Zerocoin by (a) selecting a random serial - * number, (b) committing to this serial number and repeating until - * the resulting commitment is prime. Stores the - * resulting commitment (coin) and randomness (trapdoor). - **/ + * @brief Mint a new coin. + * @param denomination the denomination of the coin to mint + * @throws ZerocoinException if the process takes too long + * + * Generates a new Zerocoin by (a) selecting a random serial + * number, (b) committing to this serial number and repeating until + * the resulting commitment is prime. Stores the + * resulting commitment (coin) and randomness (trapdoor). + **/ void mintCoin(const CoinDenomination denomination); /** - * @brief Mint a new coin using a faster process. - * @param denomination the denomination of the coin to mint - * @throws ZerocoinException if the process takes too long - * - * Generates a new Zerocoin by (a) selecting a random serial - * number, (b) committing to this serial number and repeating until - * the resulting commitment is prime. Stores the - * resulting commitment (coin) and randomness (trapdoor). - * This routine is substantially faster than the - * mintCoin() routine, but could be more vulnerable - * to timing attacks. Don't use it if you think someone - * could be timing your coin minting. - **/ + * @brief Mint a new coin using a faster process. + * @param denomination the denomination of the coin to mint + * @throws ZerocoinException if the process takes too long + * + * Generates a new Zerocoin by (a) selecting a random serial + * number, (b) committing to this serial number and repeating until + * the resulting commitment is prime. Stores the + * resulting commitment (coin) and randomness (trapdoor). + * This routine is substantially faster than the + * mintCoin() routine, but could be more vulnerable + * to timing attacks. Don't use it if you think someone + * could be timing your coin minting. + **/ void mintCoinFast(const CoinDenomination denomination); }; diff --git a/src/libzerocoin/ParamGeneration.cpp b/src/libzerocoin/ParamGeneration.cpp index 08757b7bd85c..8c67802a7f1a 100644 --- a/src/libzerocoin/ParamGeneration.cpp +++ b/src/libzerocoin/ParamGeneration.cpp @@ -16,7 +16,6 @@ #include "hash.h" #include "uint256.h" -using namespace std; namespace libzerocoin { @@ -39,80 +38,80 @@ namespace libzerocoin { /// void -CalculateParams(ZerocoinParams ¶ms, CBigNum N, string aux, uint32_t securityLevel) +CalculateParams(ZerocoinParams ¶ms, CBigNum N, std::string aux, uint32_t securityLevel) { - params.initialized = false; - params.accumulatorParams.initialized = false; - - // Verify that |N| is > 1023 bits. - uint32_t NLen = N.bitSize(); - if (NLen < 1023) { - throw std::runtime_error("Modulus must be at least 1023 bits"); - } - - // Verify that "securityLevel" is at least 80 bits (minimum). - if (securityLevel < 80) { - throw std::runtime_error("Security level must be at least 80 bits."); - } - - // Set the accumulator modulus to "N". - params.accumulatorParams.accumulatorModulus = N; - - // Calculate the required size of the field "F_p" into which - // we're embedding the coin commitment group. This may throw an - // exception if the securityLevel is too large to be supported - // by the current modulus. - uint32_t pLen = 0; - uint32_t qLen = 0; - calculateGroupParamLengths(NLen - 2, securityLevel, &pLen, &qLen); - - // Calculate candidate parameters ("p", "q") for the coin commitment group - // using a deterministic process based on "N", the "aux" string, and - // the dedicated string "COMMITMENTGROUP". - params.coinCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_COMMIT_GROUP), - pLen, qLen); - - // Next, we derive parameters for a second Accumulated Value commitment group. - // This is a Schnorr group with the specific property that the order of the group - // must be exactly equal to "q" from the commitment group. We set - // the modulus of the new group equal to "2q+1" and test to see if this is prime. - params.serialNumberSoKCommitmentGroup = deriveIntegerGroupFromOrder(params.coinCommitmentGroup.modulus); - - // Calculate the parameters for the internal commitment - // using the same process. - params.accumulatorParams.accumulatorPoKCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_AIC_GROUP), - qLen + 300, qLen + 1); - - // Calculate the parameters for the accumulator QRN commitment generators. This isn't really - // a whole group, just a pair of random generators in QR_N. - uint32_t resultCtr; - params.accumulatorParams.accumulatorQRNCommitmentGroup.g = generateIntegerFromSeed(NLen - 1, - calculateSeed(N, aux, securityLevel, STRING_QRNCOMMIT_GROUPG), - &resultCtr).pow_mod(CBigNum(2),N); - params.accumulatorParams.accumulatorQRNCommitmentGroup.h = generateIntegerFromSeed(NLen - 1, - calculateSeed(N, aux, securityLevel, STRING_QRNCOMMIT_GROUPH), - &resultCtr).pow_mod(CBigNum(2), N); - - // Calculate the accumulator base, which we calculate as "u = C**2 mod N" - // where C is an arbitrary value. In the unlikely case that "u = 1" we increment - // "C" and repeat. - CBigNum constant(ACCUMULATOR_BASE_CONSTANT); - params.accumulatorParams.accumulatorBase = CBigNum(1); - for (uint32_t count = 0; count < MAX_ACCUMGEN_ATTEMPTS && params.accumulatorParams.accumulatorBase.isOne(); count++) { - params.accumulatorParams.accumulatorBase = constant.pow_mod(CBigNum(2), params.accumulatorParams.accumulatorModulus); - } - - // Compute the accumulator range. The upper range is the largest possible coin commitment value. - // The lower range is sqrt(upper range) + 1. Since OpenSSL doesn't have - // a square root function we use a slightly higher approximation. - params.accumulatorParams.maxCoinValue = params.coinCommitmentGroup.modulus; - params.accumulatorParams.minCoinValue = CBigNum(2).pow((params.coinCommitmentGroup.modulus.bitSize() / 2) + 3); - - // If all went well, mark params as successfully initialized. - params.accumulatorParams.initialized = true; - - // If all went well, mark params as successfully initialized. - params.initialized = true; + params.initialized = false; + params.accumulatorParams.initialized = false; + + // Verify that |N| is > 1023 bits. + uint32_t NLen = N.bitSize(); + if (NLen < 1023) { + throw std::runtime_error("Modulus must be at least 1023 bits"); + } + + // Verify that "securityLevel" is at least 80 bits (minimum). + if (securityLevel < 80) { + throw std::runtime_error("Security level must be at least 80 bits."); + } + + // Set the accumulator modulus to "N". + params.accumulatorParams.accumulatorModulus = N; + + // Calculate the required size of the field "F_p" into which + // we're embedding the coin commitment group. This may throw an + // exception if the securityLevel is too large to be supported + // by the current modulus. + uint32_t pLen = 0; + uint32_t qLen = 0; + calculateGroupParamLengths(NLen - 2, securityLevel, &pLen, &qLen); + + // Calculate candidate parameters ("p", "q") for the coin commitment group + // using a deterministic process based on "N", the "aux" string, and + // the dedicated string "COMMITMENTGROUP". + params.coinCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_COMMIT_GROUP), + pLen, qLen); + + // Next, we derive parameters for a second Accumulated Value commitment group. + // This is a Schnorr group with the specific property that the order of the group + // must be exactly equal to "q" from the commitment group. We set + // the modulus of the new group equal to "2q+1" and test to see if this is prime. + params.serialNumberSoKCommitmentGroup = deriveIntegerGroupFromOrder(params.coinCommitmentGroup.modulus); + + // Calculate the parameters for the internal commitment + // using the same process. + params.accumulatorParams.accumulatorPoKCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_AIC_GROUP), + qLen + 300, qLen + 1); + + // Calculate the parameters for the accumulator QRN commitment generators. This isn't really + // a whole group, just a pair of random generators in QR_N. + uint32_t resultCtr; + params.accumulatorParams.accumulatorQRNCommitmentGroup.g = generateIntegerFromSeed(NLen - 1, + calculateSeed(N, aux, securityLevel, STRING_QRNCOMMIT_GROUPG), + &resultCtr).pow_mod(CBigNum(2),N); + params.accumulatorParams.accumulatorQRNCommitmentGroup.h = generateIntegerFromSeed(NLen - 1, + calculateSeed(N, aux, securityLevel, STRING_QRNCOMMIT_GROUPH), + &resultCtr).pow_mod(CBigNum(2), N); + + // Calculate the accumulator base, which we calculate as "u = C**2 mod N" + // where C is an arbitrary value. In the unlikely case that "u = 1" we increment + // "C" and repeat. + CBigNum constant(ACCUMULATOR_BASE_CONSTANT); + params.accumulatorParams.accumulatorBase = CBigNum(1); + for (uint32_t count = 0; count < MAX_ACCUMGEN_ATTEMPTS && params.accumulatorParams.accumulatorBase.isOne(); count++) { + params.accumulatorParams.accumulatorBase = constant.pow_mod(CBigNum(2), params.accumulatorParams.accumulatorModulus); + } + + // Compute the accumulator range. The upper range is the largest possible coin commitment value. + // The lower range is sqrt(upper range) + 1. Since OpenSSL doesn't have + // a square root function we use a slightly higher approximation. + params.accumulatorParams.maxCoinValue = params.coinCommitmentGroup.modulus; + params.accumulatorParams.minCoinValue = CBigNum(2).pow((params.coinCommitmentGroup.modulus.bitSize() / 2) + 3); + + // If all went well, mark params as successfully initialized. + params.accumulatorParams.initialized = true; + + // If all went well, mark params as successfully initialized. + params.initialized = true; } /// \brief Format a seed string by hashing several values. @@ -125,26 +124,26 @@ CalculateParams(ZerocoinParams ¶ms, CBigNum N, string aux, uint32_t security /// Returns the hash of the value. uint256 -calculateGeneratorSeed(uint256 seed, uint256 pSeed, uint256 qSeed, string label, uint32_t index, uint32_t count) +calculateGeneratorSeed(uint256 seed, uint256 pSeed, uint256 qSeed, std::string label, uint32_t index, uint32_t count) { - CHashWriter hasher(0,0); - uint256 hash; - - // Compute the hash of: - // ||||||groupName - hasher << seed; - hasher << string("||"); - hasher << pSeed; - hasher << string("||"); - hasher << qSeed; - hasher << string("||"); - hasher << label; - hasher << string("||"); - hasher << index; - hasher << string("||"); - hasher << count; - - return hasher.GetHash(); + CHashWriter hasher(0,0); + uint256 hash; + + // Compute the hash of: + // ||||||groupName + hasher << seed; + hasher << std::string("||"); + hasher << pSeed; + hasher << std::string("||"); + hasher << qSeed; + hasher << std::string("||"); + hasher << label; + hasher << std::string("||"); + hasher << index; + hasher << std::string("||"); + hasher << count; + + return hasher.GetHash(); } /// \brief Format a seed string by hashing several values. @@ -157,33 +156,33 @@ calculateGeneratorSeed(uint256 seed, uint256 pSeed, uint256 qSeed, string label, /// Returns the hash of the value. uint256 -calculateSeed(CBigNum modulus, string auxString, uint32_t securityLevel, string groupName) +calculateSeed(CBigNum modulus, std::string auxString, uint32_t securityLevel, std::string groupName) { - CHashWriter hasher(0,0); - uint256 hash; - - // Compute the hash of: - // ||||||groupName - hasher << modulus; - hasher << string("||"); - hasher << securityLevel; - hasher << string("||"); - hasher << auxString; - hasher << string("||"); - hasher << groupName; - - return hasher.GetHash(); + CHashWriter hasher(0,0); + uint256 hash; + + // Compute the hash of: + // ||||||groupName + hasher << modulus; + hasher << std::string("||"); + hasher << securityLevel; + hasher << std::string("||"); + hasher << auxString; + hasher << std::string("||"); + hasher << groupName; + + return hasher.GetHash(); } uint256 calculateHash(uint256 input) { - CHashWriter hasher(0,0); + CHashWriter hasher(0,0); - // Compute the hash of "input" - hasher << input; + // Compute the hash of "input" + hasher << input; - return hasher.GetHash(); + return hasher.GetHash(); } /// \brief Calculate field/group parameter sizes based on a security level. @@ -209,26 +208,26 @@ void calculateGroupParamLengths(uint32_t maxPLen, uint32_t securityLevel, uint32_t *pLen, uint32_t *qLen) { - *pLen = *qLen = 0; - - if (securityLevel < 80) { - throw std::runtime_error("Security level must be at least 80 bits."); - } else if (securityLevel == 80) { - *qLen = 256; - *pLen = 1024; - } else if (securityLevel <= 112) { - *qLen = 256; - *pLen = 2048; - } else if (securityLevel <= 128) { - *qLen = 320; - *pLen = 3072; - } else { - throw std::runtime_error("Security level not supported."); - } - - if (*pLen > maxPLen) { - throw std::runtime_error("Modulus size is too small for this security level."); - } + *pLen = *qLen = 0; + + if (securityLevel < 80) { + throw std::runtime_error("Security level must be at least 80 bits."); + } else if (securityLevel == 80) { + *qLen = 256; + *pLen = 1024; + } else if (securityLevel <= 112) { + *qLen = 256; + *pLen = 2048; + } else if (securityLevel <= 128) { + *qLen = 320; + *pLen = 3072; + } else { + throw std::runtime_error("Security level not supported."); + } + + if (*pLen > maxPLen) { + throw std::runtime_error("Modulus size is too small for this security level."); + } } /// \brief Deterministically compute a set of group parameters using NIST procedures. @@ -246,40 +245,40 @@ calculateGroupParamLengths(uint32_t maxPLen, uint32_t securityLevel, IntegerGroupParams deriveIntegerGroupParams(uint256 seed, uint32_t pLen, uint32_t qLen) { - IntegerGroupParams result; - CBigNum p; - CBigNum q; - uint256 pSeed, qSeed; - - // Calculate "p" and "q" and "domain_parameter_seed" from the - // "seed" buffer above, using the procedure described in NIST - // FIPS 186-3, Appendix A.1.2. - calculateGroupModulusAndOrder(seed, pLen, qLen, &(result.modulus), - &(result.groupOrder), &pSeed, &qSeed); - - // Calculate the generators "g", "h" using the process described in - // NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q", - // "domain_parameter_seed", "index"). We use "index" value 1 - // to generate "g" and "index" value 2 to generate "h". - result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1); - result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2); - - // Perform some basic tests to make sure we have good parameters - if ((uint32_t)(result.modulus.bitSize()) < pLen || // modulus is pLen bits long - (uint32_t)(result.groupOrder.bitSize()) < qLen || // order is qLen bits long - !(result.modulus.isPrime()) || // modulus is prime - !(result.groupOrder.isPrime()) || // order is prime - !((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1 - !((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1 - ((result.g.pow_mod(CBigNum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1 - ((result.h.pow_mod(CBigNum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1 - result.g == result.h || // g != h - result.g.isOne()) { // g != 1 - // If any of the above tests fail, throw an exception - throw std::runtime_error("Group parameters are not valid"); - } - - return result; + IntegerGroupParams result; + CBigNum p; + CBigNum q; + uint256 pSeed, qSeed; + + // Calculate "p" and "q" and "domain_parameter_seed" from the + // "seed" buffer above, using the procedure described in NIST + // FIPS 186-3, Appendix A.1.2. + calculateGroupModulusAndOrder(seed, pLen, qLen, &(result.modulus), + &(result.groupOrder), &pSeed, &qSeed); + + // Calculate the generators "g", "h" using the process described in + // NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q", + // "domain_parameter_seed", "index"). We use "index" value 1 + // to generate "g" and "index" value 2 to generate "h". + result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1); + result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2); + + // Perform some basic tests to make sure we have good parameters + if ((uint32_t)(result.modulus.bitSize()) < pLen || // modulus is pLen bits long + (uint32_t)(result.groupOrder.bitSize()) < qLen || // order is qLen bits long + !(result.modulus.isPrime()) || // modulus is prime + !(result.groupOrder.isPrime()) || // order is prime + !((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1 + !((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1 + ((result.g.pow_mod(CBigNum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1 + ((result.h.pow_mod(CBigNum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1 + result.g == result.h || // g != h + result.g.isOne()) { // g != 1 + // If any of the above tests fail, throw an exception + throw std::runtime_error("Group parameters are not valid"); + } + + return result; } /// \brief Deterministically compute a set of group parameters with a specified order. @@ -292,52 +291,52 @@ deriveIntegerGroupParams(uint256 seed, uint32_t pLen, uint32_t qLen) IntegerGroupParams deriveIntegerGroupFromOrder(CBigNum &groupOrder) { - IntegerGroupParams result; - - // Set the order to "groupOrder" - result.groupOrder = groupOrder; - - // Try possible values for "modulus" of the form "groupOrder * 2 * i" where - // "p" is prime and i is a counter starting at 1. - for (uint32_t i = 1; i < NUM_SCHNORRGEN_ATTEMPTS; i++) { - // Set modulus equal to "groupOrder * 2 * i" - result.modulus = (result.groupOrder * CBigNum(i*2)) + CBigNum(1); - - // Test the result for primality - // TODO: This is a probabilistic routine and thus not the right choice - if (result.modulus.isPrime(256)) { - - // Success. - // - // Calculate the generators "g", "h" using the process described in - // NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q", - // "domain_parameter_seed", "index"). We use "index" value 1 - // to generate "g" and "index" value 2 to generate "h". - uint256 seed = calculateSeed(groupOrder, "", 128, ""); - uint256 pSeed = calculateHash(seed); - uint256 qSeed = calculateHash(pSeed); - result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1); - result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2); - - // Perform some basic tests to make sure we have good parameters - if (!(result.modulus.isPrime()) || // modulus is prime - !(result.groupOrder.isPrime()) || // order is prime - !((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1 - !((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1 - ((result.g.pow_mod(CBigNum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1 - ((result.h.pow_mod(CBigNum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1 - result.g == result.h || // g != h - result.g.isOne()) { // g != 1 - // If any of the above tests fail, throw an exception - throw std::runtime_error("Group parameters are not valid"); - } - - return result; - } - } - - // If we reached this point group generation has failed. Throw an exception. - throw std::runtime_error("Too many attempts to generate Schnorr group."); + IntegerGroupParams result; + + // Set the order to "groupOrder" + result.groupOrder = groupOrder; + + // Try possible values for "modulus" of the form "groupOrder * 2 * i" where + // "p" is prime and i is a counter starting at 1. + for (uint32_t i = 1; i < NUM_SCHNORRGEN_ATTEMPTS; i++) { + // Set modulus equal to "groupOrder * 2 * i" + result.modulus = (result.groupOrder * CBigNum(i*2)) + CBigNum(1); + + // Test the result for primality + // TODO: This is a probabilistic routine and thus not the right choice + if (result.modulus.isPrime(256)) { + + // Success. + // + // Calculate the generators "g", "h" using the process described in + // NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q", + // "domain_parameter_seed", "index"). We use "index" value 1 + // to generate "g" and "index" value 2 to generate "h". + uint256 seed = calculateSeed(groupOrder, "", 128, ""); + uint256 pSeed = calculateHash(seed); + uint256 qSeed = calculateHash(pSeed); + result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1); + result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2); + + // Perform some basic tests to make sure we have good parameters + if (!(result.modulus.isPrime()) || // modulus is prime + !(result.groupOrder.isPrime()) || // order is prime + !((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1 + !((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1 + ((result.g.pow_mod(CBigNum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1 + ((result.h.pow_mod(CBigNum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1 + result.g == result.h || // g != h + result.g.isOne()) { // g != 1 + // If any of the above tests fail, throw an exception + throw std::runtime_error("Group parameters are not valid"); + } + + return result; + } + } + + // If we reached this point group generation has failed. Throw an exception. + throw std::runtime_error("Too many attempts to generate Schnorr group."); } /// \brief Deterministically compute a group description using NIST procedures. @@ -358,88 +357,88 @@ calculateGroupModulusAndOrder(uint256 seed, uint32_t pLen, uint32_t qLen, CBigNum *resultModulus, CBigNum *resultGroupOrder, uint256 *resultPseed, uint256 *resultQseed) { - // Verify that the seed length is >= qLen - if (qLen > (sizeof(seed)) * 8) { - // TODO: The use of 256-bit seeds limits us to 256-bit group orders. We should probably change this. - // throw std::runtime_error("Seed is too short to support the required security level."); - } + // Verify that the seed length is >= qLen + if (qLen > (sizeof(seed)) * 8) { + // TODO: The use of 256-bit seeds limits us to 256-bit group orders. We should probably change this. + // throw std::runtime_error("Seed is too short to support the required security level."); + } #ifdef ZEROCOIN_DEBUG - cout << "calculateGroupModulusAndOrder: pLen = " << pLen << endl; + cout << "calculateGroupModulusAndOrder: pLen = " << pLen << endl; #endif - // Generate a random prime for the group order. - // This may throw an exception, which we'll pass upwards. - // Result is the value "resultGroupOrder", "qseed" and "qgen_counter". - uint256 qseed; - uint32_t qgen_counter; - *resultGroupOrder = generateRandomPrime(qLen, seed, &qseed, &qgen_counter); - - // Using ⎡pLen / 2 + 1⎤ as the length and qseed as the input_seed, use the random prime - // routine to obtain p0 , pseed, and pgen_counter. We pass exceptions upward. - uint32_t p0len = ceil((pLen / 2.0) + 1); - uint256 pseed; - uint32_t pgen_counter; - CBigNum p0 = generateRandomPrime(p0len, qseed, &pseed, &pgen_counter); - - // Set x = 0, old_counter = pgen_counter - uint32_t old_counter = pgen_counter; - - // Generate a random integer "x" of pLen bits - uint32_t iterations; - CBigNum x = generateIntegerFromSeed(pLen, pseed, &iterations); - pseed += (iterations + 1); - - // Set x = 2^{pLen−1} + (x mod 2^{pLen–1}). - CBigNum powerOfTwo = CBigNum(2).pow(pLen-1); - x = powerOfTwo + (x % powerOfTwo); - - // t = ⎡x / (2 * resultGroupOrder * p0)⎤. - // TODO: we don't have a ceiling function - CBigNum t = x / (CBigNum(2) * (*resultGroupOrder) * p0); - - // Now loop until we find a valid prime "p" or we fail due to - // pgen_counter exceeding ((4*pLen) + old_counter). - for ( ; pgen_counter <= ((4*pLen) + old_counter) ; pgen_counter++) { - // If (2 * t * resultGroupOrder * p0 + 1) > 2^{pLen}, then - // t = ⎡2^{pLen−1} / (2 * resultGroupOrder * p0)⎤. - powerOfTwo = CBigNum(2).pow(pLen); - CBigNum prod = (CBigNum(2) * t * (*resultGroupOrder) * p0) + CBigNum(1); - if (prod > powerOfTwo) { - // TODO: implement a ceil function - t = CBigNum(2).pow(pLen-1) / (CBigNum(2) * (*resultGroupOrder) * p0); - } - - // Compute a candidate prime resultModulus = 2tqp0 + 1. - *resultModulus = (CBigNum(2) * t * (*resultGroupOrder) * p0) + CBigNum(1); - - // Verify that resultModulus is prime. First generate a pseudorandom integer "a". - CBigNum a = generateIntegerFromSeed(pLen, pseed, &iterations); - pseed += iterations + 1; - - // Set a = 2 + (a mod (resultModulus–3)). - a = CBigNum(2) + (a % ((*resultModulus) - CBigNum(3))); - - // Set z = a^{2 * t * resultGroupOrder} mod resultModulus - CBigNum z = a.pow_mod(CBigNum(2) * t * (*resultGroupOrder), (*resultModulus)); - - // If GCD(z–1, resultModulus) == 1 AND (z^{p0} mod resultModulus == 1) - // then we have found our result. Return. - if ((resultModulus->gcd(z - CBigNum(1))).isOne() && - (z.pow_mod(p0, (*resultModulus))).isOne()) { - // Success! Return the seeds and primes. - *resultPseed = pseed; - *resultQseed = qseed; - return; - } - - // This prime did not work out. Increment "t" and try again. - t = t + CBigNum(1); - } // loop continues until pgen_counter exceeds a limit - - // We reach this point only if we exceeded our maximum iteration count. - // Throw an exception. - throw std::runtime_error("Unable to generate a prime modulus for the group"); + // Generate a random prime for the group order. + // This may throw an exception, which we'll pass upwards. + // Result is the value "resultGroupOrder", "qseed" and "qgen_counter". + uint256 qseed; + uint32_t qgen_counter; + *resultGroupOrder = generateRandomPrime(qLen, seed, &qseed, &qgen_counter); + + // Using ⎡pLen / 2 + 1⎤ as the length and qseed as the input_seed, use the random prime + // routine to obtain p0 , pseed, and pgen_counter. We pass exceptions upward. + uint32_t p0len = ceil((pLen / 2.0) + 1); + uint256 pseed; + uint32_t pgen_counter; + CBigNum p0 = generateRandomPrime(p0len, qseed, &pseed, &pgen_counter); + + // Set x = 0, old_counter = pgen_counter + uint32_t old_counter = pgen_counter; + + // Generate a random integer "x" of pLen bits + uint32_t iterations; + CBigNum x = generateIntegerFromSeed(pLen, pseed, &iterations); + pseed += (iterations + 1); + + // Set x = 2^{pLen−1} + (x mod 2^{pLen–1}). + CBigNum powerOfTwo = CBigNum(2).pow(pLen-1); + x = powerOfTwo + (x % powerOfTwo); + + // t = ⎡x / (2 * resultGroupOrder * p0)⎤. + // TODO: we don't have a ceiling function + CBigNum t = x / (CBigNum(2) * (*resultGroupOrder) * p0); + + // Now loop until we find a valid prime "p" or we fail due to + // pgen_counter exceeding ((4*pLen) + old_counter). + for ( ; pgen_counter <= ((4*pLen) + old_counter) ; pgen_counter++) { + // If (2 * t * resultGroupOrder * p0 + 1) > 2^{pLen}, then + // t = ⎡2^{pLen−1} / (2 * resultGroupOrder * p0)⎤. + powerOfTwo = CBigNum(2).pow(pLen); + CBigNum prod = (CBigNum(2) * t * (*resultGroupOrder) * p0) + CBigNum(1); + if (prod > powerOfTwo) { + // TODO: implement a ceil function + t = CBigNum(2).pow(pLen-1) / (CBigNum(2) * (*resultGroupOrder) * p0); + } + + // Compute a candidate prime resultModulus = 2tqp0 + 1. + *resultModulus = (CBigNum(2) * t * (*resultGroupOrder) * p0) + CBigNum(1); + + // Verify that resultModulus is prime. First generate a pseudorandom integer "a". + CBigNum a = generateIntegerFromSeed(pLen, pseed, &iterations); + pseed += iterations + 1; + + // Set a = 2 + (a mod (resultModulus–3)). + a = CBigNum(2) + (a % ((*resultModulus) - CBigNum(3))); + + // Set z = a^{2 * t * resultGroupOrder} mod resultModulus + CBigNum z = a.pow_mod(CBigNum(2) * t * (*resultGroupOrder), (*resultModulus)); + + // If GCD(z–1, resultModulus) == 1 AND (z^{p0} mod resultModulus == 1) + // then we have found our result. Return. + if ((resultModulus->gcd(z - CBigNum(1))).isOne() && + (z.pow_mod(p0, (*resultModulus))).isOne()) { + // Success! Return the seeds and primes. + *resultPseed = pseed; + *resultQseed = qseed; + return; + } + + // This prime did not work out. Increment "t" and try again. + t = t + CBigNum(1); + } // loop continues until pgen_counter exceeds a limit + + // We reach this point only if we exceeded our maximum iteration count. + // Throw an exception. + throw std::runtime_error("Unable to generate a prime modulus for the group"); } /// \brief Deterministically compute a generator for a given group. @@ -458,33 +457,33 @@ calculateGroupModulusAndOrder(uint256 seed, uint32_t pLen, uint32_t qLen, CBigNum calculateGroupGenerator(uint256 seed, uint256 pSeed, uint256 qSeed, CBigNum modulus, CBigNum groupOrder, uint32_t index) { - CBigNum result; + CBigNum result; - // Verify that 0 <= index < 256 - if (index > 255) { - throw std::runtime_error("Invalid index for group generation"); - } + // Verify that 0 <= index < 256 + if (index > 255) { + throw std::runtime_error("Invalid index for group generation"); + } - // Compute e = (modulus - 1) / groupOrder - CBigNum e = (modulus - CBigNum(1)) / groupOrder; + // Compute e = (modulus - 1) / groupOrder + CBigNum e = (modulus - CBigNum(1)) / groupOrder; - // Loop until we find a generator - for (uint32_t count = 1; count < MAX_GENERATOR_ATTEMPTS; count++) { - // hash = Hash(seed || pSeed || qSeed || “ggen” || index || count - uint256 hash = calculateGeneratorSeed(seed, pSeed, qSeed, "ggen", index, count); - CBigNum W(hash); + // Loop until we find a generator + for (uint32_t count = 1; count < MAX_GENERATOR_ATTEMPTS; count++) { + // hash = Hash(seed || pSeed || qSeed || “ggen” || index || count + uint256 hash = calculateGeneratorSeed(seed, pSeed, qSeed, "ggen", index, count); + CBigNum W(hash); - // Compute result = W^e mod p - result = W.pow_mod(e, modulus); + // Compute result = W^e mod p + result = W.pow_mod(e, modulus); - // If result > 1, we have a generator - if (result > 1) { - return result; - } - } + // If result > 1, we have a generator + if (result > 1) { + return result; + } + } - // We only get here if we failed to find a generator - throw std::runtime_error("Unable to find a generator, too many attempts"); + // We only get here if we failed to find a generator + throw std::runtime_error("Unable to find a generator, too many attempts"); } /// \brief Deterministically compute a random prime number. @@ -503,141 +502,141 @@ CBigNum generateRandomPrime(uint32_t primeBitLen, uint256 in_seed, uint256 *out_seed, uint32_t *prime_gen_counter) { - // Verify that primeBitLen is not too small - if (primeBitLen < 2) { - throw std::runtime_error("Prime length is too short"); - } + // Verify that primeBitLen is not too small + if (primeBitLen < 2) { + throw std::runtime_error("Prime length is too short"); + } - // If primeBitLen < 33 bits, perform the base case. - if (primeBitLen < 33) { - CBigNum result(0); + // If primeBitLen < 33 bits, perform the base case. + if (primeBitLen < 33) { + CBigNum result(0); - // Set prime_seed = in_seed, prime_gen_counter = 0. - uint256 prime_seed = in_seed; - (*prime_gen_counter) = 0; + // Set prime_seed = in_seed, prime_gen_counter = 0. + uint256 prime_seed = in_seed; + (*prime_gen_counter) = 0; - // Loop up to "4 * primeBitLen" iterations. - while ((*prime_gen_counter) < (4 * primeBitLen)) { + // Loop up to "4 * primeBitLen" iterations. + while ((*prime_gen_counter) < (4 * primeBitLen)) { - // Generate a pseudorandom integer "c" of length primeBitLength bits - uint32_t iteration_count; - CBigNum c = generateIntegerFromSeed(primeBitLen, prime_seed, &iteration_count); + // Generate a pseudorandom integer "c" of length primeBitLength bits + uint32_t iteration_count; + CBigNum c = generateIntegerFromSeed(primeBitLen, prime_seed, &iteration_count); #ifdef ZEROCOIN_DEBUG - cout << "generateRandomPrime: primeBitLen = " << primeBitLen << endl; - cout << "Generated c = " << c << endl; + cout << "generateRandomPrime: primeBitLen = " << primeBitLen << endl; + cout << "Generated c = " << c << endl; #endif - prime_seed += (iteration_count + 1); - (*prime_gen_counter)++; + prime_seed += (iteration_count + 1); + (*prime_gen_counter)++; - // Set "intc" to be the least odd integer >= "c" we just generated - uint32_t intc = c.getulong(); - intc = (2 * floor(intc / 2.0)) + 1; + // Set "intc" to be the least odd integer >= "c" we just generated + uint32_t intc = c.getulong(); + intc = (2 * floor(intc / 2.0)) + 1; #ifdef ZEROCOIN_DEBUG - cout << "Should be odd. c = " << intc << endl; - cout << "The big num is: c = " << c << endl; + cout << "Should be odd. c = " << intc << endl; + cout << "The big num is: c = " << c << endl; #endif - // Perform trial division on this (relatively small) integer to determine if "intc" - // is prime. If so, return success. - if (primalityTestByTrialDivision(intc)) { - // Return "intc" converted back into a CBigNum and "prime_seed". We also updated - // the variable "prime_gen_counter" in previous statements. - result = intc; - *out_seed = prime_seed; - - // Success - return result; - } - } // while() - - // If we reached this point there was an error finding a candidate prime - // so throw an exception. - throw std::runtime_error("Unable to find prime in Shawe-Taylor algorithm"); - - // END OF BASE CASE - } - // If primeBitLen >= 33 bits, perform the recursive case. - else { - // Recurse to find a new random prime of roughly half the size - uint32_t newLength = ceil((double)primeBitLen / 2.0) + 1; - CBigNum c0 = generateRandomPrime(newLength, in_seed, out_seed, prime_gen_counter); - - // Generate a random integer "x" of primeBitLen bits using the output - // of the previous call. - uint32_t numIterations; - CBigNum x = generateIntegerFromSeed(primeBitLen, *out_seed, &numIterations); - (*out_seed) += numIterations + 1; - - // Compute "t" = ⎡x / (2 * c0⎤ - // TODO no Ceiling call - CBigNum t = x / (CBigNum(2) * c0); - - // Repeat the following procedure until we find a prime (or time out) - for (uint32_t testNum = 0; testNum < MAX_PRIMEGEN_ATTEMPTS; testNum++) { - - // If ((2 * t * c0) + 1 > 2^{primeBitLen}), - // then t = ⎡2^{primeBitLen} – 1 / (2 * c0)⎤. - if ((CBigNum(2) * t * c0) > (CBigNum(2).pow(CBigNum(primeBitLen)))) { - t = ((CBigNum(2).pow(CBigNum(primeBitLen))) - CBigNum(1)) / (CBigNum(2) * c0); - } - - // Set c = (2 * t * c0) + 1 - CBigNum c = (CBigNum(2) * t * c0) + CBigNum(1); - - // Increment prime_gen_counter - (*prime_gen_counter)++; - - // Test "c" for primality as follows: - // 1. First pick an integer "a" in between 2 and (c - 2) - CBigNum a = generateIntegerFromSeed(c.bitSize(), (*out_seed), &numIterations); - a = CBigNum(2) + (a % (c - CBigNum(3))); - (*out_seed) += (numIterations + 1); - - // 2. Compute "z" = a^{2*t} mod c - CBigNum z = a.pow_mod(CBigNum(2) * t, c); - - // 3. Check if "c" is prime. - // Specifically, verify that gcd((z-1), c) == 1 AND (z^c0 mod c) == 1 - // If so we return "c" as our result. - if (c.gcd(z - CBigNum(1)).isOne() && z.pow_mod(c0, c).isOne()) { - // Return "c", out_seed and prime_gen_counter - // (the latter two of which were already updated) - return c; - } - - // 4. If the test did not succeed, increment "t" and loop - t = t + CBigNum(1); - } // end of test loop - } - - // We only reach this point if the test loop has iterated MAX_PRIMEGEN_ATTEMPTS - // and failed to identify a valid prime. Throw an exception. - throw std::runtime_error("Unable to generate random prime (too many tests)"); + // Perform trial division on this (relatively small) integer to determine if "intc" + // is prime. If so, return success. + if (primalityTestByTrialDivision(intc)) { + // Return "intc" converted back into a CBigNum and "prime_seed". We also updated + // the variable "prime_gen_counter" in previous statements. + result = intc; + *out_seed = prime_seed; + + // Success + return result; + } + } // while() + + // If we reached this point there was an error finding a candidate prime + // so throw an exception. + throw std::runtime_error("Unable to find prime in Shawe-Taylor algorithm"); + + // END OF BASE CASE + } + // If primeBitLen >= 33 bits, perform the recursive case. + else { + // Recurse to find a new random prime of roughly half the size + uint32_t newLength = ceil((double)primeBitLen / 2.0) + 1; + CBigNum c0 = generateRandomPrime(newLength, in_seed, out_seed, prime_gen_counter); + + // Generate a random integer "x" of primeBitLen bits using the output + // of the previous call. + uint32_t numIterations; + CBigNum x = generateIntegerFromSeed(primeBitLen, *out_seed, &numIterations); + (*out_seed) += numIterations + 1; + + // Compute "t" = ⎡x / (2 * c0⎤ + // TODO no Ceiling call + CBigNum t = x / (CBigNum(2) * c0); + + // Repeat the following procedure until we find a prime (or time out) + for (uint32_t testNum = 0; testNum < MAX_PRIMEGEN_ATTEMPTS; testNum++) { + + // If ((2 * t * c0) + 1 > 2^{primeBitLen}), + // then t = ⎡2^{primeBitLen} – 1 / (2 * c0)⎤. + if ((CBigNum(2) * t * c0) > (CBigNum(2).pow(CBigNum(primeBitLen)))) { + t = ((CBigNum(2).pow(CBigNum(primeBitLen))) - CBigNum(1)) / (CBigNum(2) * c0); + } + + // Set c = (2 * t * c0) + 1 + CBigNum c = (CBigNum(2) * t * c0) + CBigNum(1); + + // Increment prime_gen_counter + (*prime_gen_counter)++; + + // Test "c" for primality as follows: + // 1. First pick an integer "a" in between 2 and (c - 2) + CBigNum a = generateIntegerFromSeed(c.bitSize(), (*out_seed), &numIterations); + a = CBigNum(2) + (a % (c - CBigNum(3))); + (*out_seed) += (numIterations + 1); + + // 2. Compute "z" = a^{2*t} mod c + CBigNum z = a.pow_mod(CBigNum(2) * t, c); + + // 3. Check if "c" is prime. + // Specifically, verify that gcd((z-1), c) == 1 AND (z^c0 mod c) == 1 + // If so we return "c" as our result. + if (c.gcd(z - CBigNum(1)).isOne() && z.pow_mod(c0, c).isOne()) { + // Return "c", out_seed and prime_gen_counter + // (the latter two of which were already updated) + return c; + } + + // 4. If the test did not succeed, increment "t" and loop + t = t + CBigNum(1); + } // end of test loop + } + + // We only reach this point if the test loop has iterated MAX_PRIMEGEN_ATTEMPTS + // and failed to identify a valid prime. Throw an exception. + throw std::runtime_error("Unable to generate random prime (too many tests)"); } CBigNum generateIntegerFromSeed(uint32_t numBits, uint256 seed, uint32_t *numIterations) { - CBigNum result(0); - uint32_t iterations = ceil((double)numBits / (double)HASH_OUTPUT_BITS); + CBigNum result(0); + uint32_t iterations = ceil((double)numBits / (double)HASH_OUTPUT_BITS); #ifdef ZEROCOIN_DEBUG - cout << "numBits = " << numBits << endl; - cout << "iterations = " << iterations << endl; + cout << "numBits = " << numBits << endl; + cout << "iterations = " << iterations << endl; #endif - // Loop "iterations" times filling up the value "result" with random bits - for (uint32_t count = 0; count < iterations; count++) { - // result += ( H(pseed + count) * 2^{count * p0len} ) - result += CBigNum(calculateHash(seed + count)) * CBigNum(2).pow(count * HASH_OUTPUT_BITS); - } + // Loop "iterations" times filling up the value "result" with random bits + for (uint32_t count = 0; count < iterations; count++) { + // result += ( H(pseed + count) * 2^{count * p0len} ) + result += CBigNum(calculateHash(seed + count)) * CBigNum(2).pow(count * HASH_OUTPUT_BITS); + } - result = CBigNum(2).pow(numBits - 1) + (result % (CBigNum(2).pow(numBits - 1))); + result = CBigNum(2).pow(numBits - 1) + (result % (CBigNum(2).pow(numBits - 1))); - // Return the number of iterations and the result - *numIterations = iterations; - return result; + // Return the number of iterations and the result + *numIterations = iterations; + return result; } /// \brief Determines whether a uint32_t is a prime through trial division. @@ -649,10 +648,10 @@ generateIntegerFromSeed(uint32_t numBits, uint256 seed, uint32_t *numIterations) bool primalityTestByTrialDivision(uint32_t candidate) { - // TODO: HACK HACK WRONG WRONG - CBigNum canBignum(candidate); + // TODO: HACK HACK WRONG WRONG + CBigNum canBignum(candidate); - return canBignum.isPrime(); + return canBignum.isPrime(); } } // namespace libzerocoin diff --git a/src/libzerocoin/SerialNumberSignatureOfKnowledge.cpp b/src/libzerocoin/SerialNumberSignatureOfKnowledge.cpp index e635827a5e4e..c99c965561b0 100644 --- a/src/libzerocoin/SerialNumberSignatureOfKnowledge.cpp +++ b/src/libzerocoin/SerialNumberSignatureOfKnowledge.cpp @@ -23,8 +23,8 @@ CBigNum SeedTo1024(uint256 hashSeed) { CHashWriter hasher(0,0); hasher << hashSeed; - vector vResult; - vector vHash = CBigNum(hasher.GetHash()).getvch(); + std::vector vResult; + std::vector vHash = CBigNum(hasher.GetHash()).getvch(); vResult.insert(vResult.end(), vHash.begin(), vHash.end()); for (int i = 0; i < 3; i ++) { hasher << vResult; @@ -56,10 +56,10 @@ SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const CHashWriter hasher(0,0); hasher << *params << commitmentToCoin.getCommitmentValue() << coin.getSerialNumber() << msghash; - vector r(params->zkp_iterations); - vector v_seed(params->zkp_iterations); - vector v_expanded(params->zkp_iterations); - vector c(params->zkp_iterations); + std::vector r(params->zkp_iterations); + std::vector v_seed(params->zkp_iterations); + std::vector v_expanded(params->zkp_iterations); + std::vector c(params->zkp_iterations); for(uint32_t i=0; i < params->zkp_iterations; i++) { r[i] = CBigNum::randBignum(params->coinCommitmentGroup.groupOrder); @@ -144,7 +144,7 @@ bool SerialNumberSignatureOfKnowledge::Verify(const CBigNum& coinSerialNumber, c CHashWriter hasher(0,0); hasher << *params << valueOfCommitmentToCoin << coinSerialNumber << msghash; - vector tprime(params->zkp_iterations); + std::vector tprime(params->zkp_iterations); unsigned char *hashbytes = (unsigned char*) &this->hash; try { diff --git a/src/libzerocoin/SerialNumberSignatureOfKnowledge.h b/src/libzerocoin/SerialNumberSignatureOfKnowledge.h index 5fc2bd69c745..bb572bc0528a 100644 --- a/src/libzerocoin/SerialNumberSignatureOfKnowledge.h +++ b/src/libzerocoin/SerialNumberSignatureOfKnowledge.h @@ -25,7 +25,6 @@ #include "Accumulator.h" #include "hash.h" -using namespace std; namespace libzerocoin { /**A Signature of knowledge on the hash of metadata attesting that the signer knows the values @@ -35,41 +34,41 @@ namespace libzerocoin { class SerialNumberSignatureOfKnowledge { public: SerialNumberSignatureOfKnowledge(){}; - SerialNumberSignatureOfKnowledge(const ZerocoinParams* p); - /** Creates a Signature of knowledge object that a commitment to a coin contains a coin with serial number x - * - * @param p params - * @param coin the coin we are going to prove the serial number of. - * @param commitmentToCoin the commitment to the coin - * @param msghash hash of meta data to create a signature of knowledge on. - */ - SerialNumberSignatureOfKnowledge(const ZerocoinParams* p, const PrivateCoin& coin, const Commitment& commitmentToCoin, uint256 msghash); + SerialNumberSignatureOfKnowledge(const ZerocoinParams* p); + /** Creates a Signature of knowledge object that a commitment to a coin contains a coin with serial number x + * + * @param p params + * @param coin the coin we are going to prove the serial number of. + * @param commitmentToCoin the commitment to the coin + * @param msghash hash of meta data to create a signature of knowledge on. + */ + SerialNumberSignatureOfKnowledge(const ZerocoinParams* p, const PrivateCoin& coin, const Commitment& commitmentToCoin, uint256 msghash); - /** Verifies the Signature of knowledge. - * - * @param msghash hash of meta data to create a signature of knowledge on. - * @return - */ + /** Verifies the Signature of knowledge. + * + * @param msghash hash of meta data to create a signature of knowledge on. + * @return + */ bool Verify(const CBigNum& coinSerialNumber, const CBigNum& valueOfCommitmentToCoin,const uint256 msghash, bool isInParamsValidationRange = true) const; - ADD_SERIALIZE_METHODS; + ADD_SERIALIZE_METHODS; template inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { - READWRITE(s_notprime); - READWRITE(sprime); - READWRITE(hash); - } + READWRITE(s_notprime); + READWRITE(sprime); + READWRITE(hash); + } private: - const ZerocoinParams* params; - // challenge hash - uint256 hash; //TODO For efficiency, should this be a bitset where Templates define params? + const ZerocoinParams* params; + // challenge hash + uint256 hash; //TODO For efficiency, should this be a bitset where Templates define params? - // challenge response values - // this is s_notprime instead of s - // because the serialization macros - // define something named s and it conflicts - vector s_notprime; - vector sprime; - inline CBigNum challengeCalculation(const CBigNum& a_exp, const CBigNum& b_exp, - const CBigNum& h_exp) const; + // challenge response values + // this is s_notprime instead of s + // because the serialization macros + // define something named s and it conflicts + std::vector s_notprime; + std::vector sprime; + inline CBigNum challengeCalculation(const CBigNum& a_exp, const CBigNum& b_exp, + const CBigNum& h_exp) const; }; } /* namespace libzerocoin */ diff --git a/src/libzerocoin/paramgen.cpp b/src/libzerocoin/paramgen.cpp index 05bf4cd7be33..09989fc08328 100644 --- a/src/libzerocoin/paramgen.cpp +++ b/src/libzerocoin/paramgen.cpp @@ -21,8 +21,6 @@ #define DEFAULT_MODULUS_SIZE 3072 #define MIN_MODULUS_SIZE 1026 -using namespace std; -using namespace libzerocoin; void PrintWarning() diff --git a/src/lightzpivthread.cpp b/src/lightzpivthread.cpp index 49ce7829a082..63088431e2f5 100644 --- a/src/lightzpivthread.cpp +++ b/src/lightzpivthread.cpp @@ -35,11 +35,11 @@ void CLightWorker::ThreadLightZPIVSimplified() { libzerocoin::Accumulator accumulator(params, genWit.getDen(), genWit.getAccWitValue()); libzerocoin::PublicCoin temp(params); libzerocoin::AccumulatorWitness witness(params, accumulator, temp); - string strFailReason = ""; + std::string strFailReason = ""; int nMintsAdded = 0; CZerocoinSpendReceipt receipt; - list ret; + std::list ret; int heightStop; bool res; diff --git a/src/limitedmap.h b/src/limitedmap.h index 03727d7c4256..dda9287f1695 100644 --- a/src/limitedmap.h +++ b/src/limitedmap.h @@ -42,7 +42,7 @@ class limitedmap map.erase(rmap.begin()->second); rmap.erase(rmap.begin()); } - rmap.insert(make_pair(x.second, ret.first)); + rmap.insert(std::make_pair(x.second, ret.first)); } return; } @@ -72,7 +72,7 @@ class limitedmap if (it->second == itTarget) { rmap.erase(it); itTarget->second = v; - rmap.insert(make_pair(v, itTarget)); + rmap.insert(std::make_pair(v, itTarget)); return; } // Shouldn't ever get here diff --git a/src/main.cpp b/src/main.cpp index 2387835b2901..e8ff44ade5af 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -48,9 +48,6 @@ #include #include -using namespace boost; -using namespace std; -using namespace libzerocoin; #if defined(NDEBUG) #error "PIVX cannot be compiled without assertions." @@ -63,8 +60,8 @@ using namespace libzerocoin; CCriticalSection cs_main; BlockMap mapBlockIndex; -map mapProofOfStake; -map mapHashedBlocks; +std::map mapProofOfStake; +std::map mapHashedBlocks; CChain chainActive; CBlockIndex* pindexBestHeader = NULL; int64_t nTimeBestReceived = 0; @@ -99,10 +96,10 @@ struct COrphanTx { CTransaction tx; NodeId fromPeer; }; -map mapOrphanTransactions; -map > mapOrphanTransactionsByPrev; -map mapRejectedBlocks; -map mapZerocoinspends; //txid, time received +std::map mapOrphanTransactions; +std::map > mapOrphanTransactionsByPrev; +std::map mapRejectedBlocks; +std::map mapZerocoinspends; //txid, time received /***/ CLightWorker lightWorker; @@ -114,7 +111,7 @@ static void CheckBlockIndex(); /** Constant stuff for coinbase transactions we create: */ CScript COINBASE_FLAGS; -const string strMessageMagic = "DarkNet Signed Message:\n"; +const std::string strMessageMagic = "DarkNet Signed Message:\n"; // Internal stuff namespace @@ -146,11 +143,11 @@ CBlockIndex* pindexBestInvalid; * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though. */ -set setBlockIndexCandidates; +std::set setBlockIndexCandidates; /** Number of nodes with fSyncStarted. */ int nSyncStarted = 0; /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */ -multimap mapBlocksUnlinked; +std::multimap mapBlocksUnlinked; CCriticalSection cs_LastBlockFile; std::vector vinfoBlockFile; @@ -168,7 +165,7 @@ uint32_t nBlockSequenceId = 1; * Sources of received blocks, to be able to send them reject messages or ban * them, if processing happens afterwards. Protected by cs_main. */ -map mapBlockSource; +std::map mapBlockSource; /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */ struct QueuedBlock { @@ -178,7 +175,7 @@ struct QueuedBlock { int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested. bool fValidatedHeaders; //! Whether this block has validated headers at the time of request. }; -map::iterator> > mapBlocksInFlight; +std::map::iterator> > mapBlocksInFlight; /** Number of blocks in flight with validated headers. */ int nQueuedValidatedHeaders = 0; @@ -187,10 +184,10 @@ int nQueuedValidatedHeaders = 0; int nPreferredDownload = 0; /** Dirty block index entries. */ -set setDirtyBlockIndex; +std::set setDirtyBlockIndex; /** Dirty block file entries. */ -set setDirtyFileInfo; +std::set setDirtyFileInfo; } // anon namespace ////////////////////////////////////////////////////////////////////////////// @@ -202,7 +199,7 @@ namespace { struct CBlockReject { unsigned char chRejectCode; - string strRejectReason; + std::string strRejectReason; uint256 hashBlock; }; @@ -312,7 +309,7 @@ struct CNodeState { bool fSyncStarted; //! Since when we're stalling block download progress (in microseconds), or 0. int64_t nStallingSince; - list vBlocksInFlight; + std::list vBlocksInFlight; int nBlocksInFlight; //! Whether we consider this a preferred download peer. bool fPreferredDownload; @@ -335,12 +332,12 @@ struct CNodeState { }; /** Map maintaining per-node state. Requires cs_main. */ -map mapNodeState; +std::map mapNodeState; // Requires cs_main. CNodeState* State(NodeId pnode) { - map::iterator it = mapNodeState.find(pnode); + std::map::iterator it = mapNodeState.find(pnode); if (it == mapNodeState.end()) return NULL; return &it->second; @@ -399,7 +396,7 @@ void FinalizeNode(NodeId nodeid) // Requires cs_main. void MarkBlockAsReceived(const uint256& hash) { - map::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); + std::map::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); if (itInFlight != mapBlocksInFlight.end()) { CNodeState* state = State(itInFlight->second.first); nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; @@ -421,7 +418,7 @@ void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex* pindex QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL}; nQueuedValidatedHeaders += newentry.fValidatedHeaders; - list::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); + std::list::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); state->nBlocksInFlight++; mapBlocksInFlight[hash] = std::make_pair(nodeid, it); } @@ -656,11 +653,11 @@ bool AddOrphanTx(const CTransaction& tx, NodeId peer) void static EraseOrphanTx(uint256 hash) { - map::iterator it = mapOrphanTransactions.find(hash); + std::map::iterator it = mapOrphanTransactions.find(hash); if (it == mapOrphanTransactions.end()) return; for (const CTxIn& txin : it->second.tx.vin) { - map >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash); + std::map >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash); if (itPrev == mapOrphanTransactionsByPrev.end()) continue; itPrev->second.erase(hash); @@ -673,9 +670,9 @@ void static EraseOrphanTx(uint256 hash) void EraseOrphansFor(NodeId peer) { int nErased = 0; - map::iterator iter = mapOrphanTransactions.begin(); + std::map::iterator iter = mapOrphanTransactions.begin(); while (iter != mapOrphanTransactions.end()) { - map::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid + std::map::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid if (maybeErase->second.fromPeer == peer) { EraseOrphanTx(maybeErase->second.tx.GetHash()); ++nErased; @@ -691,7 +688,7 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); - map::iterator it = mapOrphanTransactions.lower_bound(randomhash); + std::map::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); @@ -700,7 +697,7 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) return nEvicted; } -bool IsStandardTx(const CTransaction& tx, string& reason) +bool IsStandardTx(const CTransaction& tx, std::string& reason) { AssertLockHeld(cs_main); if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) { @@ -825,7 +822,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]); - vector > vSolutions; + std::vector > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; @@ -841,7 +838,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) // beside "push data" in the scriptSig // IsStandard() will have already returned false // and this method isn't called. - vector > stack; + std::vector > stack; if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker())) return false; @@ -849,7 +846,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); - vector > vSolutions2; + std::vector > vSolutions2; txnouttype whichType2; if (Solver(subscript, whichType2, vSolutions2)) { int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); @@ -958,7 +955,7 @@ bool MoneyRange(CAmount nValueOut) bool CheckZerocoinMint(const uint256& txHash, const CTxOut& txout, CValidationState& state, bool fCheckOnly) { - PublicCoin pubCoin(Params().Zerocoin_Params(false)); + libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false)); if(!TxOutToPublicCoin(txout, pubCoin, state)) return state.DoS(100, error("CheckZerocoinMint(): TxOutToPublicCoin() failed")); @@ -968,7 +965,7 @@ bool CheckZerocoinMint(const uint256& txHash, const CTxOut& txout, CValidationSt return true; } -bool ContextualCheckZerocoinMint(const CTransaction& tx, const PublicCoin& coin, const CBlockIndex* pindex) +bool ContextualCheckZerocoinMint(const CTransaction& tx, const libzerocoin::PublicCoin& coin, const CBlockIndex* pindex) { if (pindex->nHeight >= Params().Zerocoin_Block_Public_Spend_Enabled()) { // Zerocoin MINTs have been disabled @@ -1011,7 +1008,7 @@ bool CheckPublicCoinSpendEnforced(int blockHeight, bool isPublicSpend) { return true; } -bool ContextualCheckZerocoinSpend(const CTransaction& tx, const CoinSpend* spend, CBlockIndex* pindex, const uint256& hashBlock) +bool ContextualCheckZerocoinSpend(const CTransaction& tx, const libzerocoin::CoinSpend* spend, CBlockIndex* pindex, const uint256& hashBlock) { if(!ContextualCheckZerocoinSpendNoSerialCheck(tx, spend, pindex, hashBlock)){ return false; @@ -1026,7 +1023,7 @@ bool ContextualCheckZerocoinSpend(const CTransaction& tx, const CoinSpend* spend return true; } -bool ContextualCheckZerocoinSpendNoSerialCheck(const CTransaction& tx, const CoinSpend* spend, CBlockIndex* pindex, const uint256& hashBlock) +bool ContextualCheckZerocoinSpendNoSerialCheck(const CTransaction& tx, const libzerocoin::CoinSpend* spend, CBlockIndex* pindex, const uint256& hashBlock) { //Check to see if the zPIV is properly signed if (pindex->nHeight >= Params().Zerocoin_Block_V2_Start()) { @@ -1096,7 +1093,7 @@ bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidati uint256 hashTxOut = txTemp.GetHash(); bool fValidated = false; - set serials; + std::set serials; CAmount nTotalRedeemed = 0; for (const CTxIn& txin : tx.vin) { @@ -1105,7 +1102,7 @@ bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidati if (!txin.IsZerocoinSpend() && !isPublicSpend) continue; - CoinSpend newSpend; + libzerocoin::CoinSpend newSpend; CTxOut prevOut; if (isPublicSpend) { if(!GetOutput(txin.prevout.hash, txin.prevout.n, state, prevOut)){ @@ -1122,7 +1119,7 @@ bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidati } //check that the denomination is valid - if (newSpend.getDenomination() == ZQ_ERROR) + if (newSpend.getDenomination() == libzerocoin::ZQ_ERROR) return state.DoS(100, error("Zerocoinspend does not have the correct denomination")); //check that denomination is what it claims to be in nSequence @@ -1149,7 +1146,7 @@ bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidati return state.DoS(100, error("%s: Zerocoinspend could not find accumulator associated with checksum %s", __func__, HexStr(BEGIN(nChecksum), END(nChecksum)))); } - Accumulator accumulator(Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()), + libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()), newSpend.getDenomination(), bnAccumulatorValue); //Check that the coin has been accumulated @@ -1162,7 +1159,7 @@ bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidati serials.insert(newSpend.getCoinSerialNumber()); //make sure that there is no over redemption of coins - nTotalRedeemed += ZerocoinDenominationToAmount(newSpend.getDenomination()); + nTotalRedeemed += libzerocoin::ZerocoinDenominationToAmount(newSpend.getDenomination()); fValidated = true; } @@ -1213,8 +1210,8 @@ bool CheckTransaction(const CTransaction& tx, bool fZerocoinActive, bool fReject } } - set vInOutPoints; - set vZerocoinSpendSerials; + std::set vInOutPoints; + std::set vZerocoinSpendSerials; int nZCSpendCount = 0; for (const CTxIn& txin : tx.vin) { // Check for duplicate inputs @@ -1366,7 +1363,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransa return state.DoS(0, false, REJECT_NONSTANDARD, "non-final"); // Rather not work on nonstandard transactions (unless -testnet/-regtest) - string reason; + std::string reason; if (Params().RequireStandard() && !IsStandardTx(tx, reason)) return state.DoS(0, error("AcceptToMemoryPool : nonstandard transaction: %s", reason), @@ -1443,7 +1440,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransa return state.Invalid(error("%s: ContextualCheckZerocoinSpend failed for tx %s", __func__, tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); } else { - CoinSpend spend = TxInToZerocoinSpend(txIn); + libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txIn); if (!ContextualCheckZerocoinSpend(tx, &spend, chainActive.Tip(), 0)) return state.Invalid(error("%s: ContextualCheckZerocoinSpend failed for tx %s", __func__, tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); @@ -1481,7 +1478,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransa if (!out.IsZerocoinMint()) continue; - PublicCoin coin(Params().Zerocoin_Params(false)); + libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(out, coin, state)) return state.Invalid(error("%s: failed final check of zerocoinmint for tx %s", __func__, tx.GetHash().GetHex())); @@ -1637,7 +1634,7 @@ bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransact REJECT_INVALID, "coinbase"); // Rather not work on nonstandard transactions (unless -testnet/-regtest) - string reason; + std::string reason; // for any real tx this will be checked on AcceptToMemoryPool anyway // if (Params().RequireStandard() && !IsStandardTx(tx, reason)) // return state.DoS(0, @@ -2468,8 +2465,8 @@ bool CScriptCheck::operator()() CBitcoinAddress addressExp1("DQZzqnSR6PXxagep1byLiRg9ZurCZ5KieQ"); CBitcoinAddress addressExp2("DTQYdnNqKuEHXyNeeYhPQGGGdqHbXYwjpj"); -map mapInvalidOutPoints; -map mapInvalidSerials; +std::map mapInvalidOutPoints; +std::map mapInvalidSerials; void AddInvalidSpendsToMap(const CBlock& block) { for (const CTransaction& tx : block.vtx) { @@ -2481,17 +2478,17 @@ void AddInvalidSpendsToMap(const CBlock& block) bool isPublicSpend = in.IsZerocoinPublicSpend(); if (in.IsZerocoinSpend() || isPublicSpend) { - CoinSpend* spend; + libzerocoin::CoinSpend* spend; if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); CValidationState state; if (!ZPIVModule::ParseZerocoinPublicSpend(in, tx, state, publicSpend)){ - throw runtime_error("Failed to parse public spend"); + throw std::runtime_error("Failed to parse public spend"); } spend = &publicSpend; } else { - CoinSpend spendObj = TxInToZerocoinSpend(in); + libzerocoin::CoinSpend spendObj = TxInToZerocoinSpend(in); spend = &spendObj; } @@ -2697,7 +2694,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex } serial = publicSpend.getCoinSerialNumber(); } else { - CoinSpend spend = TxInToZerocoinSpend(txin); + libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin); serial = spend.getCoinSerialNumber(); } @@ -2722,7 +2719,7 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex if (txout.scriptPubKey.empty() || !txout.IsZerocoinMint()) continue; - PublicCoin pubCoin(Params().Zerocoin_Params(false)); + libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(txout, pubCoin, state)) return error("DisconnectBlock(): TxOutToPublicCoin() failed"); @@ -2887,7 +2884,7 @@ void RecalculateZPIVMinted() std::list listMints; BlockToZerocoinMintList(block, listMints, true); - vector vDenomsBefore = pindex->vMintDenominationsInBlock; + std::vector vDenomsBefore = pindex->vMintDenominationsInBlock; pindex->vMintDenominationsInBlock.clear(); for (auto mint : listMints) pindex->vMintDenominationsInBlock.emplace_back(mint.GetDenomination()); @@ -2915,7 +2912,7 @@ void RecalculateZPIVSpent() CBlock block; assert(ReadBlockFromDisk(block, pindex)); - list listDenomsSpent = ZerocoinSpendListFromBlock(block, true); + std::list listDenomsSpent = ZerocoinSpendListFromBlock(block, true); //Reset the supply to previous block pindex->mapZerocoinSupply = pindex->pprev->mapZerocoinSupply; @@ -3022,7 +3019,7 @@ bool RecalculatePIVSupply(int nHeightStart) return true; } -bool ReindexAccumulators(list& listMissingCheckpoints, string& strError) +bool ReindexAccumulators(std::list& listMissingCheckpoints, std::string& strError) { // PIVX: recalculate Accumulator Checkpoints that failed to database properly if (!listMissingCheckpoints.empty()) { @@ -3081,7 +3078,7 @@ bool UpdateZPIVSupply(const CBlock& block, CBlockIndex* pindex, bool fJustCheck) // Initialize zerocoin supply to the supply from previous block if (pindex->pprev && pindex->pprev->GetBlockHeader().nVersion > 3) { - for (auto& denom : zerocoinDenomList) { + for (auto& denom : libzerocoin::zerocoinDenomList) { pindex->mapZerocoinSupply.at(denom) = pindex->pprev->GetZcMints(denom); } } @@ -3128,7 +3125,7 @@ bool UpdateZPIVSupply(const CBlock& block, CBlockIndex* pindex, bool fJustCheck) } } - for (auto& denom : zerocoinDenomList) + for (auto& denom : libzerocoin::zerocoinDenomList) LogPrint("zero", "%s coins for denomination %d pubcoin %s\n", __func__, denom, pindex->mapZerocoinSupply.at(denom)); // Update Wrapped Serials amount @@ -3216,15 +3213,15 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin unsigned int nSigOps = 0; CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size())); std::vector > vPos; - std::vector > vSpends; - std::vector > vMints; + std::vector > vSpends; + std::vector > vMints; vPos.reserve(block.vtx.size()); CBlockUndo blockundo; blockundo.vtxundo.reserve(block.vtx.size() - 1); CAmount nValueOut = 0; CAmount nValueIn = 0; unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_CURRENT; - vector vSpendsInBlock; + std::vector vSpendsInBlock; uint256 hashBlock = block.GetHash(); for (unsigned int i = 0; i < block.vtx.size(); i++) { const CTransaction& tx = block.vtx[i]; @@ -3252,7 +3249,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } //Check for double spending of serial #'s - set setSerials; + std::set setSerials; for (const CTxIn& txIn : tx.vin) { bool isPublicSpend = txIn.IsZerocoinPublicSpend(); bool isPrivZerocoinSpend = txIn.IsZerocoinSpend(); @@ -3272,14 +3269,14 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } nValueIn += publicSpend.getDenomination() * COIN; //queue for db write after the 'justcheck' section has concluded - vSpends.emplace_back(make_pair(publicSpend, tx.GetHash())); + vSpends.emplace_back(std::make_pair(publicSpend, tx.GetHash())); if (!ContextualCheckZerocoinSpend(tx, &publicSpend, pindex, hashBlock)) return state.DoS(100, error("%s: failed to add block %s with invalid public zc spend", __func__, tx.GetHash().GetHex()), REJECT_INVALID); } else { - CoinSpend spend = TxInToZerocoinSpend(txIn); + libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txIn); nValueIn += spend.getDenomination() * COIN; //queue for db write after the 'justcheck' section has concluded - vSpends.emplace_back(make_pair(spend, tx.GetHash())); + vSpends.emplace_back(std::make_pair(spend, tx.GetHash())); if (!ContextualCheckZerocoinSpend(tx, &spend, pindex, hashBlock)) return state.DoS(100, error("%s: failed to add block %s with invalid zerocoinspend", __func__, tx.GetHash().GetHex()), REJECT_INVALID); } @@ -3291,14 +3288,14 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!out.IsZerocoinMint()) continue; - PublicCoin coin(Params().Zerocoin_Params(false)); + libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(out, coin, state)) return state.DoS(100, error("%s: failed final check of zerocoinmint for tx %s", __func__, tx.GetHash().GetHex())); if (!ContextualCheckZerocoinMint(tx, coin, pindex)) return state.DoS(100, error("%s: zerocoin mint failed contextual check", __func__)); - vMints.emplace_back(make_pair(coin, tx.GetHash())); + vMints.emplace_back(std::make_pair(coin, tx.GetHash())); } } } else if (!tx.IsCoinBase()) { @@ -3320,14 +3317,14 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!out.IsZerocoinMint()) continue; - PublicCoin coin(Params().Zerocoin_Params(false)); + libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(out, coin, state)) return state.DoS(100, error("%s: failed final check of zerocoinmint for tx %s", __func__, tx.GetHash().GetHex())); if (!ContextualCheckZerocoinMint(tx, coin, pindex)) return state.DoS(100, error("%s: zerocoin mint failed contextual check", __func__)); - vMints.emplace_back(make_pair(coin, tx.GetHash())); + vMints.emplace_back(std::make_pair(coin, tx.GetHash())); } } @@ -3442,7 +3439,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin //Record zPIV serials if (pwalletMain) { std::set setAddedTx; - for (std::pair pSpend : vSpends) { + for (std::pair pSpend : vSpends) { // Send signal to wallet if this is ours if (pwalletMain->IsMyZerocoinSpend(pSpend.first.getCoinSerialNumber())) { LogPrintf("%s: %s detected zerocoinspend in transaction %s \n", __func__, @@ -3541,13 +3538,13 @@ bool static FlushStateToDisk(CValidationState& state, FlushStateMode mode) { std::vector > vFiles; vFiles.reserve(setDirtyFileInfo.size()); - for (set::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { - vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); + for (std::set::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { + vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it])); setDirtyFileInfo.erase(it++); } std::vector vBlocks; vBlocks.reserve(setDirtyBlockIndex.size()); - for (set::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { + for (std::set::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { vBlocks.push_back(*it); setDirtyBlockIndex.erase(it++); } @@ -3648,7 +3645,7 @@ bool static DisconnectTip(CValidationState& state) // Resurrect mempool transactions from the disconnected block. for (const CTransaction& tx : block.vtx) { // ignore validation errors in resurrected transactions - list removed; + std::list removed; CValidationState stateDummy; if (tx.IsCoinBase() || tx.IsCoinStake() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL)) mempool.remove(tx, removed, true); @@ -3727,7 +3724,7 @@ bool static ConnectTip(CValidationState& state, CBlockIndex* pindexNew, CBlock* LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001); // Remove conflicting transactions from the mempool. - list txConflicted; + std::list txConflicted; mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted); mempool.check(pcoinsTip); // Update chainActive & related variables. @@ -3782,12 +3779,12 @@ bool DisconnectBlockAndInputs(CValidationState& state, CTransaction txLock) bool foundConflictingTx = false; //remove anything conflicting in the memory pool - list txConflicted; + std::list txConflicted; mempool.removeConflicts(txLock, txConflicted); // List of what to disconnect (typically nothing) - vector vDisconnect; + std::vector vDisconnect; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0 && !foundConflictingTx && i < 6; i++) { vDisconnect.push_back(BlockReading); @@ -4131,7 +4128,7 @@ CBlockIndex* AddToBlockIndex(const CBlock& block) // to avoid miners withholding blocks but broadcasting headers, to get a // competitive advantage. 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); BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock); @@ -4197,7 +4194,7 @@ bool ReceivedBlockTransactions(const CBlock& block, CValidationState& state, CBl if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. - deque queue; + std::deque queue; queue.push_back(pindexNew); // Recursively process any descendant blocks that now may be eligible to be connected. @@ -4399,7 +4396,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { - mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime())); + mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime())); LogPrintf("CheckBlock() : found conflicting transaction with transaction lock %s %s\n", mapLockedInputs[in.prevout].ToString(), tx.GetHash().ToString()); return state.DoS(0, error("CheckBlock() : found conflicting transaction with transaction lock"), REJECT_INVALID, "conflicting-tx-ix"); @@ -4432,7 +4429,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo // that this block is invalid, so don't issue an outright ban. if (nHeight != 0 && !IsInitialBlockDownload()) { if (!IsBlockPayeeValid(block, nHeight)) { - mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime())); + mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime())); return state.DoS(0, error("CheckBlock() : Couldn't find masternode/budget payment"), REJECT_INVALID, "bad-cb-payee"); } @@ -4444,7 +4441,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo // Check transactions bool fZerocoinActive = block.GetBlockTime() > Params().Zerocoin_StartTime(); - vector vBlockSerials; + std::vector vBlockSerials; // TODO: Check if this is ok... blockHeight is always the tip or should we look for the prevHash and get the height? int blockHeight = chainActive.Height() + 1; for (const CTransaction& tx : block.vtx) { @@ -4473,7 +4470,7 @@ bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bo } else { spend = TxInToZerocoinSpend(txIn); } - if (count(vBlockSerials.begin(), vBlockSerials.end(), spend.getCoinSerialNumber())) + if (std::count(vBlockSerials.begin(), vBlockSerials.end(), spend.getCoinSerialNumber())) return state.DoS(100, error("%s : Double spending of zPIV serial %s in block\n Block: %s", __func__, spend.getCoinSerialNumber().GetHex(), block.ToString())); vBlockSerials.emplace_back(spend.getCoinSerialNumber()); @@ -4506,8 +4503,8 @@ bool CheckWork(const CBlock block, CBlockIndex* const pindexPrev) double n1 = ConvertBitsToDouble(block.nBits); double n2 = ConvertBitsToDouble(nBitsRequired); - if (abs(n1 - n2) > n1 * 0.5) - return error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, abs(n1 - n2), n1, n2, pindexPrev->nHeight + 1); + if (std::abs(n1 - n2) > n1 * 0.5) + return error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, std::abs(n1 - n2), n1, n2, pindexPrev->nHeight + 1); return true; } @@ -4725,7 +4722,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, if (block.IsProofOfStake()) { isPoS = true; uint256 hashProofOfStake = 0; - unique_ptr stake; + std::unique_ptr stake; if (!CheckProofOfStake(block, hashProofOfStake, stake, pindexPrev->nHeight)) return state.DoS(100, error("%s: proof of stake check failed", __func__)); @@ -4735,7 +4732,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, uint256 hash = block.GetHash(); if(!mapProofOfStake.count(hash)) // add to mapProofOfStake - mapProofOfStake.insert(make_pair(hash, hashProofOfStake)); + mapProofOfStake.insert(std::make_pair(hash, hashProofOfStake)); } if (!AcceptBlockHeader(block, state, &pindex)) @@ -4786,7 +4783,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, // ZC started after PoS. // Check for serial double spent on the same block, TODO: Move this to the proper method.. - vector inBlockSerials; + std::vector inBlockSerials; for (const CTransaction& tx : block.vtx) { for (const CTxIn& in: tx.vin) { if(nHeight >= Params().Zerocoin_StartHeight()) { @@ -4842,7 +4839,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, if (!ReadBlockFromDisk(bl, prev)) return error("%s: previous block %s not on disk", __func__, prev->GetBlockHash().GetHex()); - vector vBlockSerials; + std::vector vBlockSerials; int readBlock = 0; // Go backwards on the forked chain up to the split while (!chainActive.Contains(prev)) { @@ -4892,7 +4889,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, // Now that this loop if completed. Check if we have zPIV inputs. if(hasZPIVInputs){ for (const CTxIn& zPivInput : zPIVInputs) { - CoinSpend spend = TxInToZerocoinSpend(zPivInput); + libzerocoin::CoinSpend spend = TxInToZerocoinSpend(zPivInput); // First check if the serials were not already spent on the forked blocks. CBigNum coinSerial = spend.getCoinSerialNumber(); @@ -4921,7 +4918,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, return state.DoS(100, error("%s: stake zerocoinspend not ready to be spent", __func__)); } - Accumulator accumulator(Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()), + libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()), spend.getDenomination(), bnAccumulatorValue); //Check that the coinspend is valid @@ -4955,7 +4952,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } else { if(!isBlockFromFork) for (const CTxIn& zPivInput : zPIVInputs) { - CoinSpend spend = TxInToZerocoinSpend(zPivInput); + libzerocoin::CoinSpend spend = TxInToZerocoinSpend(zPivInput); if (!ContextualCheckZerocoinSpend(stakeTxIn, &spend, pindex, 0)) return state.DoS(100,error("%s: main chain ContextualCheckZerocoinSpend failed for tx %s", __func__, stakeTxIn.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); @@ -5188,7 +5185,7 @@ bool AbortNode(const std::string& strMessage, const std::string& userMessage) bool CheckDiskSpace(uint64_t nAdditionalBytes) { - uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available; + uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) @@ -5248,15 +5245,15 @@ CBlockIndex* InsertBlockIndex(uint256 hash) // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) - throw runtime_error("LoadBlockIndex() : new CBlockIndex failed"); - mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; + throw std::runtime_error("LoadBlockIndex() : new CBlockIndex failed"); + mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); return pindexNew; } -bool static LoadBlockIndexDB(string& strError) +bool static LoadBlockIndexDB(std::string& strError) { if (!pblocktree->LoadBlockIndexGuts()) return false; @@ -5264,13 +5261,13 @@ bool static LoadBlockIndexDB(string& strError) boost::this_thread::interruption_point(); // Calculate nChainWork - vector > vSortedByHeight; + std::vector > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); for (const std::pair& item : mapBlockIndex) { 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()); + std::sort(vSortedByHeight.begin(), vSortedByHeight.end()); for (const PAIRTYPE(int, CBlockIndex*) & item : vSortedByHeight) { CBlockIndex* pindex = item.second; pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex); @@ -5315,7 +5312,7 @@ bool static LoadBlockIndexDB(string& strError) // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); - set setBlkDataFiles; + std::set setBlkDataFiles; for (const std::pair& item : mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex->nStatus & BLOCK_HAVE_DATA) { @@ -5478,7 +5475,7 @@ void UnloadBlockIndex() mapBlockIndex.clear(); } -bool LoadBlockIndex(string& strError) +bool LoadBlockIndex(std::string& strError) { // Load block index from databases if (!fReindex && !LoadBlockIndexDB(strError)) @@ -5594,7 +5591,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos* dbp) } // Recursively process earlier encountered successors of this block - deque queue; + std::deque queue; queue.push_back(hash); while (!queue.empty()) { uint256 head = queue.front(); @@ -5775,11 +5772,11 @@ void static CheckBlockIndex() // CAlert // -string GetWarnings(string strFor) +std::string GetWarnings(std::string strFor) { int nPriority = 0; - string strStatusBar; - string strRPC; + std::string strStatusBar; + std::string strRPC; if (!CLIENT_VERSION_IS_RELEASE) strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for staking or merchant applications!"); @@ -5897,7 +5894,7 @@ void static ProcessGetData(CNode* pfrom) { std::deque::iterator it = pfrom->vRecvGetData.begin(); - vector vNotFound; + std::vector vNotFound; LOCK(cs_main); @@ -5962,7 +5959,7 @@ void static ProcessGetData(CNode* pfrom) // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. - vector vInv; + std::vector vInv; vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; @@ -5973,7 +5970,7 @@ void static ProcessGetData(CNode* pfrom) bool pushed = false; { LOCK(cs_mapRelay); - map::iterator mi = mapRelay.find(inv); + std::map::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) { pfrom->PushMessage(inv.GetCommand(), (*mi).second); pushed = true; @@ -6016,7 +6013,7 @@ void static ProcessGetData(CNode* pfrom) // Don't send not-validated blocks if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) { try { - list pubcoins = GetPubcoinFromBlock((*mi).second); + std::list pubcoins = GetPubcoinFromBlock((*mi).second); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(2000); ss << inv.hash.Get32(); @@ -6169,7 +6166,7 @@ void static ProcessGetData(CNode* pfrom) } bool fRequestedSporksIDB = false; -bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived) +bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv, int64_t nTimeReceived) { RandAddSeedPerfmon(); LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); @@ -6181,7 +6178,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { - pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message")); + pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")); LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); return false; @@ -6245,7 +6242,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // Change version pfrom->PushMessage("verack"); - pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); + pfrom->ssSend.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address @@ -6283,7 +6280,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->fSuccessfullyConnected = true; - string remoteAddr; + std::string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); @@ -6307,7 +6304,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "verack") { - pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); + pfrom->SetRecvVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION)); // Mark this node as currently connected, so we update its timestamp later. if (pfrom->fNetworkNode) { @@ -6318,7 +6315,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "addr") { - vector vAddr; + std::vector vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding @@ -6331,7 +6328,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } // Store the new addresses - vector vAddrOk; + std::vector vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; for (CAddress& addr : vAddr) { @@ -6353,7 +6350,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, uint64_t hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); - multimap mapMix; + std::multimap mapMix; for (CNode* pnode : vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; @@ -6361,10 +6358,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); - mapMix.insert(make_pair(hashKey, pnode)); + mapMix.insert(std::make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) - for (multimap::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) + for (std::multimap::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } @@ -6381,7 +6378,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "inv") { - vector vInv; + std::vector vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { LOCK(cs_main); @@ -6430,7 +6427,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "getdata") { - vector vInv; + std::vector vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { LOCK(cs_main); @@ -6506,7 +6503,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 - vector vHeaders; + std::vector vHeaders; int nLimit = MAX_HEADERS_RESULTS; if (fDebug) LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id); @@ -6520,14 +6517,14 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "tx" || strCommand == "dstx") { - vector vWorkQueue; - vector vEraseQueue; + std::vector vWorkQueue; + std::vector vEraseQueue; CTransaction tx; //masternode signed transaction bool ignoreFees = false; CTxIn vin; - vector vchSig; + std::vector vchSig; int64_t sigTime; if (strCommand == "tx") { @@ -6565,7 +6562,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, dstx.vchSig = vchSig; dstx.sigTime = sigTime; - mapObfuscationBroadcastTxes.insert(make_pair(tx.GetHash(), dstx)); + mapObfuscationBroadcastTxes.insert(std::make_pair(tx.GetHash(), dstx)); } } } @@ -6592,12 +6589,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, mempool.mapTx.size()); // Recursively process any orphan transactions that depended on this one - set setMisbehaving; + std::set setMisbehaving; for(unsigned int i = 0; i < vWorkQueue.size(); i++) { - map >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]); + std::map >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]); if(itByPrev == mapOrphanTransactionsByPrev.end()) continue; - for(set::iterator mi = itByPrev->second.begin(); + for(std::set::iterator mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) { const uint256 &orphanHash = *mi; @@ -6840,7 +6837,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // getaddr message mitigates the attack. else if ((strCommand == "getaddr") && (pfrom->fInbound)) { pfrom->vAddrToSend.clear(); - vector vAddr = addrman.GetAddr(); + std::vector vAddr = addrman.GetAddr(); for (const CAddress& addr : vAddr) pfrom->PushAddress(addr); } @@ -6851,7 +6848,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, std::vector vtxid; mempool.queryHashes(vtxid); - vector vInv; + std::vector vInv; for (uint256& hash : vtxid) { CInv inv(MSG_TX, hash); CTransaction tx; @@ -7001,7 +6998,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "filteradd") { - vector vData; + std::vector vData; vRecv >> vData; // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, @@ -7032,12 +7029,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else if (strCommand == "reject") { if (fDebug) { try { - string strMsg; + std::string strMsg; unsigned char ccode; - string strReason; + std::string strReason; 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; if (strMsg == "block" || strMsg == "tx") { @@ -7138,7 +7135,7 @@ bool ProcessMessages(CNode* pfrom) LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id); continue; } - string strCommand = hdr.GetCommand(); + std::string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; @@ -7160,7 +7157,7 @@ bool ProcessMessages(CNode* pfrom) fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime); boost::this_thread::interruption_point(); } catch (std::ios_base::failure& e) { - pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message")); + pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, std::string("error parsing message")); if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what()); @@ -7252,7 +7249,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // Message: addr // if (fSendTrickle) { - vector vAddr; + std::vector vAddr; vAddr.reserve(pto->vAddrToSend.size()); for (const CAddress& addr : pto->vAddrToSend) { // returns true if wasn't already contained in the set @@ -7286,7 +7283,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } for (const CBlockReject& reject : state.rejects) - pto->PushMessage("reject", (string) "block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); + pto->PushMessage("reject", (std::string) "block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); state.rejects.clear(); // Start block sync @@ -7315,8 +7312,8 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // // Message: inventory // - vector vInv; - vector vInvWait; + std::vector vInv; + std::vector vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); @@ -7377,9 +7374,9 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // // Message: getdata (blocks) // - vector vGetData; + std::vector vGetData; if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { - vector vToDownload; + std::vector vToDownload; NodeId staller = -1; FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller); for (CBlockIndex* pindex : vToDownload) { diff --git a/src/main.h b/src/main.h index f69844e23f01..29a267df33cd 100644 --- a/src/main.h +++ b/src/main.h @@ -371,7 +371,7 @@ void AddWrappedSerialsInflation(); void RecalculateZPIVSpent(); void RecalculateZPIVMinted(); bool RecalculatePIVSupply(int nHeightStart); -bool ReindexAccumulators(list& listMissingCheckpoints, string& strError); +bool ReindexAccumulators(std::list& listMissingCheckpoints, std::string& strError); // Fake Serial attack Range bool isBlockBetweenFakeSerialAttackRange(int nHeight); diff --git a/src/masternode-budget.cpp b/src/masternode-budget.cpp index 090d72269b06..1525f7c26dcd 100644 --- a/src/masternode-budget.cpp +++ b/src/masternode-budget.cpp @@ -214,7 +214,7 @@ void CBudgetManager::SubmitFinalBudget() pwalletMain->CommitTransaction(wtx, reservekey, "NO-ix"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); - mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); + mapCollateralTxids.insert(std::make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } @@ -257,7 +257,7 @@ void CBudgetManager::SubmitFinalBudget() } LOCK(cs); - mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); + mapSeenFinalizedBudgets.insert(std::make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; @@ -326,7 +326,7 @@ CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; - vector vchData; + std::vector vchData; vchData.resize(dataSize); uint256 hashIn; @@ -428,7 +428,7 @@ bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) return false; } - mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); + mapFinalizedBudgets.insert(std::make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } @@ -445,7 +445,7 @@ bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) return false; } - mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); + mapProposals.insert(std::make_pair(budgetProposal.GetHash(), budgetProposal)); LogPrint("mnbudget","CBudgetManager::AddProposal - proposal %s added\n", budgetProposal.GetName ().c_str ()); return true; } @@ -467,8 +467,8 @@ void CBudgetManager::CheckAndRemove() LogPrint("mnbudget", "CBudgetManager::CheckAndRemove at Height=%d\n", nHeight); - map tmpMapFinalizedBudgets; - map tmpMapProposals; + std::map tmpMapFinalizedBudgets; + std::map tmpMapProposals; std::string strError = ""; @@ -488,7 +488,7 @@ void CBudgetManager::CheckAndRemove() if (pfinalizedBudget->fValid) { pfinalizedBudget->CheckAndVote(); - tmpMapFinalizedBudgets.insert(make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget)); + tmpMapFinalizedBudgets.insert(std::make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget)); } ++it; @@ -508,7 +508,7 @@ void CBudgetManager::CheckAndRemove() pbudgetProposal->strProposalName.c_str(), pbudgetProposal->nFeeTXHash.ToString().c_str()); } if (pbudgetProposal->fValid) { - tmpMapProposals.insert(make_pair(pbudgetProposal->GetHash(), *pbudgetProposal)); + tmpMapProposals.insert(std::make_pair(pbudgetProposal->GetHash(), *pbudgetProposal)); } ++it2; @@ -777,7 +777,7 @@ std::vector CBudgetManager::GetBudget() std::map::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); - vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays())); + vBudgetPorposalsSort.push_back(std::make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays())); ++it; } @@ -859,7 +859,7 @@ std::vector CBudgetManager::GetFinalizedBudgets() while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); - vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); + vFinalizedBudgetsSort.push_back(std::make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); @@ -1103,7 +1103,7 @@ void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CData return; } - mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); + mapSeenMasternodeBudgetProposals.insert(std::make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if (!budgetProposalBroadcast.IsValid(strError)) { LogPrint("mnbudget","mprop - invalid budget proposal - %s\n", strError); @@ -1140,7 +1140,7 @@ void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CData } - mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + mapSeenMasternodeBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { if (masternodeSync.IsSynced()) { LogPrintf("CBudgetManager::ProcessMessage() : mvote - signature invalid\n"); @@ -1178,7 +1178,7 @@ void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CData return; } - mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); + mapSeenFinalizedBudgets.insert(std::make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","fbs - invalid finalized budget - %s\n", strError); @@ -1214,7 +1214,7 @@ void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CData return; } - mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + mapSeenFinalizedBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { if (masternodeSync.IsSynced()) { LogPrintf("CBudgetManager::ProcessMessage() : fbvote - signature from masternode %s invalid\n", HexStr(pmn->pubKeyMasternode)); @@ -2139,7 +2139,7 @@ bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) bool CFinalizedBudget::IsPaidAlready(uint256 nProposalHash, int nBlockHeight) { // Remove budget-payments from former/future payment cycles - map::iterator it = mapPayment_History.begin(); + std::map::iterator it = mapPayment_History.begin(); int nPaidBlockHeight = 0; uint256 nOldProposalHash; @@ -2241,7 +2241,7 @@ void CFinalizedBudget::SubmitVote() if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); - budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenFinalizedBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); } else { LogPrint("mnbudget","CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); diff --git a/src/masternode-budget.h b/src/masternode-budget.h index 5bc8ecf5aaf9..ffa5eb570f84 100644 --- a/src/masternode-budget.h +++ b/src/masternode-budget.h @@ -15,7 +15,6 @@ #include "sync.h" #include "util.h" -using namespace std; extern CCriticalSection cs_budget; @@ -41,7 +40,7 @@ static const CAmount PROPOSAL_FEE_TX = (50 * COIN); static const CAmount BUDGET_FEE_TX_OLD = (50 * COIN); static const CAmount BUDGET_FEE_TX = (5 * COIN); static const int64_t BUDGET_VOTE_UPDATE_MIN = 60 * 60; -static map mapPayment_History; +static std::map mapPayment_History; extern std::vector vecImmatureBudgetProposals; extern std::vector vecImmatureFinalizedBudgets; @@ -179,16 +178,16 @@ class CBudgetManager { private: //hold txes until they mature enough to use - // XX42 map mapCollateral; - map mapCollateralTxids; + // XX42 std::map mapCollateral; + std::map mapCollateralTxids; public: // critical section to protect the inner data structures mutable CCriticalSection cs; // keep track of the scanning errors I've seen - map mapProposals; - map mapFinalizedBudgets; + std::map mapProposals; + std::map mapFinalizedBudgets; std::map mapSeenMasternodeBudgetProposals; std::map mapSeenMasternodeBudgetVotes; @@ -321,7 +320,7 @@ class CFinalizedBudget std::string strBudgetName; int nBlockStart; std::vector vecBudgetPayments; - map mapVotes; + std::map mapVotes; uint256 nFeeTXHash; int64_t nTime; @@ -372,7 +371,7 @@ class CFinalizedBudget void SubmitVote(); //checks the hashes to make sure we know about them - string GetStatus(); + std::string GetStatus(); uint256 GetHash() { @@ -478,7 +477,7 @@ class CBudgetProposal int64_t nTime; uint256 nFeeTXHash; - map mapVotes; + std::map mapVotes; //cache object CBudgetProposal(); diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 30f4a217a1d2..cb6be6bbf84e 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -81,7 +81,7 @@ CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; - vector vchData; + std::vector vchData; vchData.resize(dataSize); uint256 hashIn; diff --git a/src/masternode-payments.h b/src/masternode-payments.h index bf54b8a3e7b4..c55087666bbc 100644 --- a/src/masternode-payments.h +++ b/src/masternode-payments.h @@ -10,7 +10,6 @@ #include "main.h" #include "masternode.h" -using namespace std; extern CCriticalSection cs_vecPayments; extern CCriticalSection cs_mapMasternodeBlocks; diff --git a/src/masternode-sync.cpp b/src/masternode-sync.cpp index a368c384ee02..d23f1bd46be2 100644 --- a/src/masternode-sync.cpp +++ b/src/masternode-sync.cpp @@ -92,7 +92,7 @@ void CMasternodeSync::AddedMasternodeList(uint256 hash) } } else { lastMasternodeList = GetTime(); - mapSeenSyncMNB.insert(make_pair(hash, 1)); + mapSeenSyncMNB.insert(std::make_pair(hash, 1)); } } @@ -105,7 +105,7 @@ void CMasternodeSync::AddedMasternodeWinner(uint256 hash) } } else { lastMasternodeWinner = GetTime(); - mapSeenSyncMNW.insert(make_pair(hash, 1)); + mapSeenSyncMNW.insert(std::make_pair(hash, 1)); } } @@ -119,7 +119,7 @@ void CMasternodeSync::AddedBudgetItem(uint256 hash) } } else { lastBudgetItem = GetTime(); - mapSeenSyncBudget.insert(make_pair(hash, 1)); + mapSeenSyncBudget.insert(std::make_pair(hash, 1)); } } diff --git a/src/masternode.cpp b/src/masternode.cpp index 1cc7a28a3d7a..984d93d2d37e 100644 --- a/src/masternode.cpp +++ b/src/masternode.cpp @@ -11,7 +11,7 @@ #include "util.h" // keep track of the scanning errors I've seen -map mapSeenMasternodeScanningErrors; +std::map mapSeenMasternodeScanningErrors; // cache block hashes as we calculate them std::map mapCacheBlockHashes; @@ -147,7 +147,7 @@ bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb) int nDoS = 0; if (mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(nDoS, false))) { lastPing = mnb.lastPing; - mnodeman.mapSeenMasternodePing.insert(make_pair(lastPing.GetHash(), lastPing)); + mnodeman.mapSeenMasternodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } return true; } diff --git a/src/masternode.h b/src/masternode.h index 9dbe87e7e0ff..b5acbd05b036 100644 --- a/src/masternode.h +++ b/src/masternode.h @@ -22,12 +22,11 @@ #define MASTERNODE_REMOVAL_SECONDS (130 * 60) #define MASTERNODE_CHECK_SECONDS 5 -using namespace std; class CMasternode; class CMasternodeBroadcast; class CMasternodePing; -extern map mapCacheBlockHashes; +extern std::map mapCacheBlockHashes; bool GetBlockHash(uint256& hash, int nBlockHeight); diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index c6f43c793670..70734a197784 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -18,24 +18,24 @@ CMasternodeMan mnodeman; struct CompareLastPaid { - bool operator()(const pair& t1, - const pair& t2) const + bool operator()(const std::pair& t1, + const std::pair& t2) const { return t1.first < t2.first; } }; struct CompareScoreTxIn { - bool operator()(const pair& t1, - const pair& t2) const + bool operator()(const std::pair& t1, + const std::pair& t2) const { return t1.first < t2.first; } }; struct CompareScoreMN { - bool operator()(const pair& t1, - const pair& t2) const + bool operator()(const std::pair& t1, + const std::pair& t2) const { return t1.first < t2.first; } @@ -101,7 +101,7 @@ CMasternodeDB::ReadResult CMasternodeDB::Read(CMasternodeMan& mnodemanToLoad, bo // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; - vector vchData; + std::vector vchData; vchData.resize(dataSize); uint256 hashIn; @@ -246,7 +246,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) LOCK(cs); //remove inactive and outdated - vector::iterator it = vMasternodes.begin(); + std::vector::iterator it = vMasternodes.begin(); while (it != vMasternodes.end()) { if ((*it).activeState == CMasternode::MASTERNODE_REMOVE || (*it).activeState == CMasternode::MASTERNODE_VIN_SPENT || @@ -257,7 +257,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) //erase all of the broadcasts we've seen from this vin // -- if we missed a few pings and the node was removed, this will allow is to get it back without them // sending a brand new mnb - map::iterator it3 = mapSeenMasternodeBroadcast.begin(); + std::map::iterator it3 = mapSeenMasternodeBroadcast.begin(); while (it3 != mapSeenMasternodeBroadcast.end()) { if ((*it3).second.vin == (*it).vin) { masternodeSync.mapSeenSyncMNB.erase((*it3).first); @@ -268,7 +268,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) } // allow us to ask for this masternode again if we see another ping - map::iterator it2 = mWeAskedForMasternodeListEntry.begin(); + std::map::iterator it2 = mWeAskedForMasternodeListEntry.begin(); while (it2 != mWeAskedForMasternodeListEntry.end()) { if ((*it2).first == (*it).vin.prevout) { mWeAskedForMasternodeListEntry.erase(it2++); @@ -284,7 +284,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) } // check who's asked for the Masternode list - map::iterator it1 = mAskedUsForMasternodeList.begin(); + std::map::iterator it1 = mAskedUsForMasternodeList.begin(); while (it1 != mAskedUsForMasternodeList.end()) { if ((*it1).second < GetTime()) { mAskedUsForMasternodeList.erase(it1++); @@ -304,7 +304,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) } // check which Masternodes we've asked for - map::iterator it2 = mWeAskedForMasternodeListEntry.begin(); + std::map::iterator it2 = mWeAskedForMasternodeListEntry.begin(); while (it2 != mWeAskedForMasternodeListEntry.end()) { if ((*it2).second < GetTime()) { mWeAskedForMasternodeListEntry.erase(it2++); @@ -314,7 +314,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) } // remove expired mapSeenMasternodeBroadcast - map::iterator it3 = mapSeenMasternodeBroadcast.begin(); + std::map::iterator it3 = mapSeenMasternodeBroadcast.begin(); while (it3 != mapSeenMasternodeBroadcast.end()) { if ((*it3).second.lastPing.sigTime < GetTime() - (MASTERNODE_REMOVAL_SECONDS * 2)) { mapSeenMasternodeBroadcast.erase(it3++); @@ -325,7 +325,7 @@ void CMasternodeMan::CheckAndRemove(bool forceExpiredRemoval) } // remove expired mapSeenMasternodePing - map::iterator it4 = mapSeenMasternodePing.begin(); + std::map::iterator it4 = mapSeenMasternodePing.begin(); while (it4 != mapSeenMasternodePing.end()) { if ((*it4).second.sigTime < GetTime() - (MASTERNODE_REMOVAL_SECONDS * 2)) { mapSeenMasternodePing.erase(it4++); @@ -478,7 +478,7 @@ CMasternode* CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight LOCK(cs); CMasternode* pBestMasternode = NULL; - std::vector > vecMasternodeLastPaid; + std::vector > vecMasternodeLastPaid; /* Make a vector with all of the last paid times @@ -501,7 +501,7 @@ CMasternode* CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight //make sure it has as many confirmations as there are masternodes if (mn.GetMasternodeInputAge() < nMnCount) continue; - vecMasternodeLastPaid.push_back(make_pair(mn.SecondsSincePayment(), mn.vin)); + vecMasternodeLastPaid.push_back(std::make_pair(mn.SecondsSincePayment(), mn.vin)); } nCount = (int)vecMasternodeLastPaid.size(); @@ -592,7 +592,7 @@ CMasternode* CMasternodeMan::GetCurrentMasterNode(int mod, int64_t nBlockHeight, int CMasternodeMan::GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, int minProtocol, bool fOnlyActive) { - std::vector > vecMasternodeScores; + std::vector > vecMasternodeScores; int64_t nMasternode_Min_Age = MN_WINNER_MINIMUM_AGE; int64_t nMasternode_Age = 0; @@ -621,7 +621,7 @@ int CMasternodeMan::GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, in uint256 n = mn.CalculateScore(1, nBlockHeight); int64_t n2 = n.GetCompact(false); - vecMasternodeScores.push_back(make_pair(n2, mn.vin)); + vecMasternodeScores.push_back(std::make_pair(n2, mn.vin)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreTxIn()); @@ -637,10 +637,10 @@ int CMasternodeMan::GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, in return -1; } -std::vector > CMasternodeMan::GetMasternodeRanks(int64_t nBlockHeight, int minProtocol) +std::vector > CMasternodeMan::GetMasternodeRanks(int64_t nBlockHeight, int minProtocol) { - std::vector > vecMasternodeScores; - std::vector > vecMasternodeRanks; + std::vector > vecMasternodeScores; + std::vector > vecMasternodeRanks; //make sure we know about this block uint256 hash = 0; @@ -653,14 +653,14 @@ std::vector > CMasternodeMan::GetMasternodeRanks(int64_t if (mn.protocolVersion < minProtocol) continue; if (!mn.IsEnabled()) { - vecMasternodeScores.push_back(make_pair(9999, mn)); + vecMasternodeScores.push_back(std::make_pair(9999, mn)); continue; } uint256 n = mn.CalculateScore(1, nBlockHeight); int64_t n2 = n.GetCompact(false); - vecMasternodeScores.push_back(make_pair(n2, mn)); + vecMasternodeScores.push_back(std::make_pair(n2, mn)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreMN()); @@ -668,7 +668,7 @@ std::vector > CMasternodeMan::GetMasternodeRanks(int64_t int rank = 0; for (PAIRTYPE(int64_t, CMasternode) & s : vecMasternodeScores) { rank++; - vecMasternodeRanks.push_back(make_pair(rank, s.second)); + vecMasternodeRanks.push_back(std::make_pair(rank, s.second)); } return vecMasternodeRanks; @@ -676,7 +676,7 @@ std::vector > CMasternodeMan::GetMasternodeRanks(int64_t CMasternode* CMasternodeMan::GetMasternodeByRank(int nRank, int64_t nBlockHeight, int minProtocol, bool fOnlyActive) { - std::vector > vecMasternodeScores; + std::vector > vecMasternodeScores; // scan for winner for (CMasternode& mn : vMasternodes) { @@ -689,7 +689,7 @@ CMasternode* CMasternodeMan::GetMasternodeByRank(int nRank, int64_t nBlockHeight uint256 n = mn.CalculateScore(1, nBlockHeight); int64_t n2 = n.GetCompact(false); - vecMasternodeScores.push_back(make_pair(n2, mn.vin)); + vecMasternodeScores.push_back(std::make_pair(n2, mn.vin)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreTxIn()); @@ -736,7 +736,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CData masternodeSync.AddedMasternodeList(mnb.GetHash()); return; } - mapSeenMasternodeBroadcast.insert(make_pair(mnb.GetHash(), mnb)); + mapSeenMasternodeBroadcast.insert(std::make_pair(mnb.GetHash(), mnb)); int nDoS = 0; if (!mnb.CheckAndUpdate(nDoS)) { @@ -776,7 +776,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CData LogPrint("masternode", "mnp - Masternode ping, vin: %s\n", mnp.vin.prevout.hash.ToString()); if (mapSeenMasternodePing.count(mnp.GetHash())) return; //seen - mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp)); + mapSeenMasternodePing.insert(std::make_pair(mnp.GetHash(), mnp)); int nDoS = 0; if (mnp.CheckAndUpdate(nDoS)) return; @@ -833,7 +833,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CData pfrom->PushInventory(CInv(MSG_MASTERNODE_ANNOUNCE, hash)); nInvCount++; - if (!mapSeenMasternodeBroadcast.count(hash)) mapSeenMasternodeBroadcast.insert(make_pair(hash, mnb)); + if (!mapSeenMasternodeBroadcast.count(hash)) mapSeenMasternodeBroadcast.insert(std::make_pair(hash, mnb)); if (vin == mn.vin) { LogPrint("masternode", "dseg - Sent 1 Masternode entry to peer %i\n", pfrom->GetId()); @@ -862,7 +862,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CData CService addr; CPubKey pubkey; CPubKey pubkey2; - vector vchSig; + std::vector vchSig; int64_t sigTime; int count; int current; @@ -968,7 +968,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CData LogPrint("masternode", "dsee - already seen this vin %s\n", vin.prevout.ToString()); return; } - mapSeenDsee.insert(make_pair(vin.prevout, pubkey)); + mapSeenDsee.insert(std::make_pair(vin.prevout, pubkey)); // make sure the vout that was signed is related to the transaction that spawned the Masternode // - this is expensive, so it's only done once per Masternode if (!obfuScationSigner.IsVinAssociatedWithPubkey(vin, pubkey)) { @@ -1064,7 +1064,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CData if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return; CTxIn vin; - vector vchSig; + std::vector vchSig; int64_t sigTime; bool stop; vRecv >> vin >> vchSig >> sigTime >> stop; @@ -1134,7 +1134,7 @@ void CMasternodeMan::Remove(CTxIn vin) { LOCK(cs); - vector::iterator it = vMasternodes.begin(); + std::vector::iterator it = vMasternodes.begin(); while (it != vMasternodes.end()) { if ((*it).vin == vin) { LogPrint("masternode", "CMasternodeMan: Removing Masternode %s - %i now\n", (*it).vin.prevout.hash.ToString(), size() - 1); @@ -1147,9 +1147,9 @@ void CMasternodeMan::Remove(CTxIn vin) void CMasternodeMan::UpdateMasternodeList(CMasternodeBroadcast mnb) { - mapSeenMasternodePing.insert(make_pair(mnb.lastPing.GetHash(), mnb.lastPing)); - mapSeenMasternodeBroadcast.insert(make_pair(mnb.GetHash(), mnb)); - masternodeSync.AddedMasternodeList(mnb.GetHash()); + mapSeenMasternodePing.insert(std::make_pair(mnb.lastPing.GetHash(), mnb.lastPing)); + mapSeenMasternodeBroadcast.insert(std::make_pair(mnb.GetHash(), mnb)); + masternodeSync.AddedMasternodeList(mnb.GetHash()); LogPrint("masternode","CMasternodeMan::UpdateMasternodeList() -- masternode=%s\n", mnb.vin.prevout.ToString()); @@ -1158,7 +1158,7 @@ void CMasternodeMan::UpdateMasternodeList(CMasternodeBroadcast mnb) CMasternode mn(mnb); Add(mn); } else { - pmn->UpdateFromNewBroadcast(mnb); + pmn->UpdateFromNewBroadcast(mnb); } } diff --git a/src/masternodeman.h b/src/masternodeman.h index ec78f94cdc32..b73ea7b4a893 100644 --- a/src/masternodeman.h +++ b/src/masternodeman.h @@ -17,7 +17,6 @@ #define MASTERNODES_DUMP_SECONDS (15 * 60) #define MASTERNODES_DSEG_SECONDS (3 * 60 * 60) -using namespace std; class CMasternodeMan; @@ -68,9 +67,9 @@ class CMasternodeMan public: // Keep track of all broadcasts I've seen - map mapSeenMasternodeBroadcast; + std::map mapSeenMasternodeBroadcast; // Keep track of all pings I've seen - map mapSeenMasternodePing; + std::map mapSeenMasternodePing; // keep track of dsq count to prevent masternodes from gaming obfuscation queue int64_t nDsqCount; @@ -135,7 +134,7 @@ class CMasternodeMan return vMasternodes; } - std::vector > GetMasternodeRanks(int64_t nBlockHeight, int minProtocol = 0); + std::vector > GetMasternodeRanks(int64_t nBlockHeight, int minProtocol = 0); int GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, int minProtocol = 0, bool fOnlyActive = true); CMasternode* GetMasternodeByRank(int nRank, int64_t nBlockHeight, int minProtocol = 0, bool fOnlyActive = true); diff --git a/src/merkleblock.cpp b/src/merkleblock.cpp index 04ec867237b2..798ccba11a12 100644 --- a/src/merkleblock.cpp +++ b/src/merkleblock.cpp @@ -10,14 +10,13 @@ #include "primitives/block.h" // for MAX_BLOCK_SIZE #include "utilstrencodings.h" -using namespace std; CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter) { header = block.GetBlockHeader(); - vector vMatch; - vector vHashes; + std::vector vMatch; + std::vector vHashes; vMatch.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size()); @@ -26,7 +25,7 @@ CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter) const uint256& hash = block.vtx[i].GetHash(); if (filter.IsRelevantAndUpdate(block.vtx[i])) { vMatch.push_back(true); - vMatchedTxn.push_back(make_pair(i, hash)); + vMatchedTxn.push_back(std::make_pair(i, hash)); } else vMatch.push_back(false); vHashes.push_back(hash); diff --git a/src/miner.cpp b/src/miner.cpp index 74cbf74fecdf..00e362bff349 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -33,7 +33,6 @@ #include #include -using namespace std; ////////////////////////////////////////////////////////////////////////////// // @@ -52,7 +51,7 @@ class COrphan { public: const CTransaction* ptx; - set setDependsOn; + std::set setDependsOn; CFeeRate feeRate; double dPriority; @@ -103,7 +102,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CWallet* pwallet, CReserveKey reservekey(pwallet); // Create new block - unique_ptr pblocktemplate(new CBlockTemplate()); + std::unique_ptr pblocktemplate(new CBlockTemplate()); if (!pblocktemplate.get()) return NULL; CBlock* pblock = &pblocktemplate->block; // pointer for convenience @@ -197,14 +196,14 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CWallet* pwallet, CCoinsViewCache view(pcoinsTip); // Priority order to process transactions - list vOrphan; // list memory doesn't move - map > mapDependers; + std::list vOrphan; // list memory doesn't move + std::map > mapDependers; bool fPrintPriority = GetBoolArg("-printpriority", false); // This vector will be sorted into a priority queue: - vector vecPriority; + std::vector vecPriority; vecPriority.reserve(mempool.mapTx.size()); - for (map::iterator mi = mempool.mapTx.begin(); + for (std::map::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { const CTransaction& tx = mi->second.GetTx(); if (tx.IsCoinBase() || tx.IsCoinStake() || !IsFinalTx(tx, nHeight)){ @@ -321,8 +320,8 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CWallet* pwallet, TxPriorityCompare comparer(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); - vector vBlockSerials; - vector vTxSerials; + std::vector vBlockSerials; + std::vector vTxSerials; while (!vecPriority.empty()) { // Take highest priority transaction off the priority queue: double dPriority = vecPriority.front().get<0>(); @@ -390,9 +389,9 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, CWallet* pwallet, bool fUseV1Params = libzerocoin::ExtractVersionFromSerial(spend->getCoinSerialNumber()) < libzerocoin::PrivateCoin::PUBKEY_VERSION; if (!spend->HasValidSerial(Params().Zerocoin_Params(fUseV1Params))) fDoubleSerial = true; - if (count(vBlockSerials.begin(), vBlockSerials.end(), spend->getCoinSerialNumber())) + if (std::count(vBlockSerials.begin(), vBlockSerials.end(), spend->getCoinSerialNumber())) fDoubleSerial = true; - if (count(vTxSerials.begin(), vTxSerials.end(), spend->getCoinSerialNumber())) + if (std::count(vTxSerials.begin(), vTxSerials.end(), spend->getCoinSerialNumber())) fDoubleSerial = true; if (fDoubleSerial) break; @@ -675,7 +674,7 @@ void BitcoinMiner(CWallet* pwallet, bool fProofOfStake) if (mapHashedBlocks.count(chainActive.Tip()->nHeight) && !fLastLoopOrphan) //search our map of hashed blocks, see if bestblock has been hashed yet { - if (GetTime() - mapHashedBlocks[chainActive.Tip()->nHeight] < max(pwallet->nHashInterval, (unsigned int)1)) // wait half of the nHashDrift with max wait of 3 minutes + if (GetTime() - mapHashedBlocks[chainActive.Tip()->nHeight] < std::max(pwallet->nHashInterval, (unsigned int)1)) // wait half of the nHashDrift with max wait of 3 minutes { MilliSleep(5000); continue; @@ -691,7 +690,7 @@ void BitcoinMiner(CWallet* pwallet, bool fProofOfStake) if (!pindexPrev) continue; - unique_ptr pblocktemplate(CreateNewBlockWithKey(reservekey, pwallet, fProofOfStake)); + std::unique_ptr pblocktemplate(CreateNewBlockWithKey(reservekey, pwallet, fProofOfStake)); if (!pblocktemplate.get()) continue; diff --git a/src/net.cpp b/src/net.cpp index 5fd0794516d7..6d0f809a8291 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -57,8 +57,6 @@ #endif #endif -using namespace boost; -using namespace std; namespace { @@ -79,7 +77,7 @@ bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK; CCriticalSection cs_mapLocalHost; -map mapLocalHost; +std::map mapLocalHost; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64_t nLocalHostNonce = 0; @@ -89,20 +87,20 @@ int nMaxConnections = 125; bool fAddressesInitialized = false; std::string strSubVersion; -vector vNodes; +std::vector vNodes; CCriticalSection cs_vNodes; -map mapRelay; -deque > vRelayExpiration; +std::map mapRelay; +std::deque > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap mapAlreadyAskedFor(MAX_INV_SZ); -static deque vOneShots; +static std::deque vOneShots; CCriticalSection cs_vOneShots; -set setservAddNodeAddresses; +std::set setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; -vector vAddedNodes; +std::vector vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; @@ -115,7 +113,7 @@ boost::condition_variable messageHandlerCondition; static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } -void AddOneShot(string strDest) +void AddOneShot(std::string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); @@ -136,7 +134,7 @@ bool GetLocal(CService& addr, const CNetAddr* paddrPeer) int nBestReachability = -1; { LOCK(cs_mapLocalHost); - for (map::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { + for (std::map::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { @@ -165,7 +163,7 @@ CAddress GetLocalAddress(const CNetAddr* paddrPeer) return ret; } -bool RecvLine(SOCKET hSocket, string& strLine) +bool RecvLine(SOCKET hSocket, std::string& strLine) { strLine = ""; while (true) { @@ -460,7 +458,7 @@ void CNode::CloseSocketDisconnect() vRecvMsg.clear(); } -bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand) +bool CNode::DisconnectOldProtocol(int nVersionRequired, std::string strLastCommand) { fDisconnect = false; if (nVersion < nVersionRequired) { @@ -835,7 +833,7 @@ void SocketSendData(CNode* pnode) pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } -static list vNodesDisconnected; +static std::list vNodesDisconnected; void ThreadSocketHandler() { @@ -847,7 +845,7 @@ void ThreadSocketHandler() { LOCK(cs_vNodes); // Disconnect unused nodes - vector vNodesCopy = vNodes; + std::vector vNodesCopy = vNodes; for (CNode* pnode : vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { @@ -869,7 +867,7 @@ void ThreadSocketHandler() } { // Delete disconnected nodes - list vNodesDisconnectedCopy = vNodesDisconnected; + std::list vNodesDisconnectedCopy = vNodesDisconnected; for (CNode* pnode : vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { @@ -920,7 +918,7 @@ void ThreadSocketHandler() for (const ListenSocket& hListenSocket : vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); - hSocketMax = max(hSocketMax, hListenSocket.socket); + hSocketMax = std::max(hSocketMax, hListenSocket.socket); have_fds = true; } @@ -930,7 +928,7 @@ void ThreadSocketHandler() if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); - hSocketMax = max(hSocketMax, pnode->hSocket); + hSocketMax = std::max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: @@ -1032,7 +1030,7 @@ void ThreadSocketHandler() // // Service each socket // - vector vNodesCopy; + std::vector vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; @@ -1160,7 +1158,7 @@ void ThreadMapPort() } } - string strDesc = "PIVX " + FormatFullVersion(); + std::string strDesc = "PIVX " + FormatFullVersion(); try { while (true) { @@ -1241,7 +1239,7 @@ void ThreadDNSAddressSeed() } } - const vector& vSeeds = Params().DNSSeeds(); + const std::vector& vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); @@ -1250,8 +1248,8 @@ void ThreadDNSAddressSeed() if (HaveNameProxy()) { AddOneShot(seed.host); } else { - vector vIPs; - vector vAdd; + std::vector vIPs; + std::vector vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { for (CNetAddr& ip : vIPs) { int nOneDay = 24 * 3600; @@ -1288,7 +1286,7 @@ void DumpData() void static ProcessOneShot() { - string strDest; + std::string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) @@ -1310,7 +1308,7 @@ void ThreadOpenConnections() if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); - for (string strAddr : mapMultiArgs["-connect"]) { + for (std::string strAddr : mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { @@ -1349,7 +1347,7 @@ void ThreadOpenConnections() // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; - set > setConnected; + std::set > setConnected; { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { @@ -1406,13 +1404,13 @@ void ThreadOpenAddedConnections() if (HaveNameProxy()) { while (true) { - list lAddresses(0); + std::list lAddresses(0); { LOCK(cs_vAddedNodes); - for (string& strAddNode : vAddedNodes) + for (std::string& strAddNode : vAddedNodes) lAddresses.push_back(strAddNode); } - for (string& strAddNode : lAddresses) { + for (std::string& strAddNode : lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); @@ -1423,16 +1421,16 @@ void ThreadOpenAddedConnections() } for (unsigned int i = 0; true; i++) { - list lAddresses(0); + std::list lAddresses(0); { LOCK(cs_vAddedNodes); - for (string& strAddNode : vAddedNodes) + for (std::string& strAddNode : vAddedNodes) lAddresses.push_back(strAddNode); } - list > lservAddressesToAdd(0); - for (string& strAddNode : lAddresses) { - vector vservNode(0); + std::list > lservAddressesToAdd(0); + for (std::string& strAddNode : lAddresses) { + std::vector vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { @@ -1447,7 +1445,7 @@ void ThreadOpenAddedConnections() { LOCK(cs_vNodes); for (CNode* pnode : vNodes) - for (list >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) + for (std::list >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) for (CService& addrNode : *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); @@ -1455,7 +1453,7 @@ void ThreadOpenAddedConnections() break; } } - for (vector& vserv : lservAddressesToAdd) { + for (std::vector& vserv : lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); @@ -1501,7 +1499,7 @@ void ThreadMessageHandler() SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { - vector vNodesCopy; + std::vector vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; @@ -1577,7 +1575,7 @@ void static ThreadStakeMinter() } #endif // ENABLE_WALLET -bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted) +bool BindListenPort(const CService& addrBind, std::string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; @@ -1674,7 +1672,7 @@ void static Discover(boost::thread_group& threadGroup) // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { - vector vaddr; + std::vector vaddr; if (LookupHost(pszHostName, vaddr)) { for (const CNetAddr& addr : vaddr) { if (AddLocal(addr, LOCAL_IF)) @@ -1739,7 +1737,7 @@ void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler) if (semOutbound == NULL) { // initialize semaphore - int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); + int nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } @@ -2016,7 +2014,7 @@ bool CAddrDB::Read(CAddrMan& addr) // Don't try to resize to a negative number if file is small if (fileSize >= sizeof(uint256)) dataSize = fileSize - sizeof(uint256); - vector vchData; + std::vector vchData; vchData.resize(dataSize); uint256 hashIn; @@ -2271,7 +2269,7 @@ bool CBanDB::Read(banmap_t& banSet) // Don't try to resize to a negative number if file is small if (fileSize >= sizeof(uint256)) dataSize = fileSize - sizeof(uint256); - vector vchData; + std::vector vchData; vchData.resize(dataSize); uint256 hashIn; diff --git a/src/netbase.cpp b/src/netbase.cpp index 50429bc2f3ab..15c55bd18472 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -36,7 +36,6 @@ #define MSG_NOSIGNAL 0 #endif -using namespace std; // Settings static proxyType proxyInfo[NET_MAX]; @@ -296,7 +295,7 @@ struct ProxyCredentials }; /** Connect using SOCKS5 (as described in RFC1928) */ -bool static Socks5(string strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket) +bool static Socks5(std::string strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket) { LogPrintf("SOCKS5 connecting %s\n", strDest); if (strDest.size() > 255) { @@ -613,13 +612,13 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, b bool ConnectSocketByName(CService& addr, SOCKET& hSocketRet, const char* pszDest, int portDefault, int nTimeout, bool* outProxyConnectionFailed) { - string strDest; + std::string strDest; int port = portDefault; if (outProxyConnectionFailed) *outProxyConnectionFailed = false; - SplitHostPort(string(pszDest), port, strDest); + SplitHostPort(std::string(pszDest), port, strDest); proxyType nameProxy; GetNameProxy(nameProxy); diff --git a/src/obfuscation-relay.cpp b/src/obfuscation-relay.cpp index e020d815f9ff..6e5d91b29ec5 100644 --- a/src/obfuscation-relay.cpp +++ b/src/obfuscation-relay.cpp @@ -14,7 +14,7 @@ CObfuScationRelay::CObfuScationRelay() out = CTxOut(); } -CObfuScationRelay::CObfuScationRelay(CTxIn& vinMasternodeIn, vector& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2) +CObfuScationRelay::CObfuScationRelay(CTxIn& vinMasternodeIn, std::vector& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2) { vinMasternode = vinMasternodeIn; vchSig = vchSigIn; diff --git a/src/obfuscation-relay.h b/src/obfuscation-relay.h index 07438a7d8015..c00106f9c391 100644 --- a/src/obfuscation-relay.h +++ b/src/obfuscation-relay.h @@ -15,15 +15,15 @@ class CObfuScationRelay { public: CTxIn vinMasternode; - vector vchSig; - vector vchSig2; + std::vector vchSig; + std::vector vchSig2; int nBlockHeight; int nRelayType; CTxIn in; CTxOut out; CObfuScationRelay(); - CObfuScationRelay(CTxIn& vinMasternodeIn, vector& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2); + CObfuScationRelay(CTxIn& vinMasternodeIn, std::vector& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2); ADD_SERIALIZE_METHODS; diff --git a/src/obfuscation.cpp b/src/obfuscation.cpp index 3245026e6d33..fd07a2e710fb 100644 --- a/src/obfuscation.cpp +++ b/src/obfuscation.cpp @@ -21,8 +21,6 @@ #include #include -using namespace std; -using namespace boost; // The main object for accessing Obfuscation CObfuscationPool obfuScationPool; @@ -33,7 +31,7 @@ std::vector vecObfuscationQueue; // Keep track of the used Masternodes std::vector vecMasternodesUsed; // Keep track of the scanning errors I've seen -map mapObfuscationBroadcastTxes; +std::map mapObfuscationBroadcastTxes; // Keep track of the active Masternode CActiveMasternode activeMasternode; @@ -226,7 +224,7 @@ void CObfuscationPool::CheckFinalTransaction() dstx.vchSig = vchSig; dstx.sigTime = sigTime; - mapObfuscationBroadcastTxes.insert(make_pair(txNew.GetHash(), dstx)); + mapObfuscationBroadcastTxes.insert(std::make_pair(txNew.GetHash(), dstx)); } CInv inv(MSG_DSTX, txNew.GetHash()); @@ -420,7 +418,7 @@ void CObfuscationPool::CheckTimeout() // check Obfuscation queue objects for timeouts int c = 0; - vector::iterator it = vecObfuscationQueue.begin(); + std::vector::iterator it = vecObfuscationQueue.begin(); while (it != vecObfuscationQueue.end()) { if ((*it).IsExpired()) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() : Removing expired queue entry - %d\n", c); @@ -437,7 +435,7 @@ void CObfuscationPool::CheckTimeout() c = 0; // check for a timeout and reset if needed - vector::iterator it2 = entries.begin(); + std::vector::iterator it2 = entries.begin(); while (it2 != entries.end()) { if ((*it2).IsExpired()) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() : Removing expired entry - %d\n", c); @@ -572,7 +570,7 @@ bool CObfuScationSigner::GetKeysFromSecret(std::string strSecret, CKey& keyRet, return true; } -bool CObfuScationSigner::SignMessage(std::string strMessage, std::string& errorMessage, vector& vchSig, CKey key) +bool CObfuScationSigner::SignMessage(std::string strMessage, std::string& errorMessage, std::vector& vchSig, CKey key) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; @@ -586,7 +584,7 @@ bool CObfuScationSigner::SignMessage(std::string strMessage, std::string& errorM return true; } -bool CObfuScationSigner::VerifyMessage(CPubKey pubkey, vector& vchSig, std::string strMessage, std::string& errorMessage) +bool CObfuScationSigner::VerifyMessage(CPubKey pubkey, std::vector& vchSig, std::string strMessage, std::string& errorMessage) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; diff --git a/src/obfuscation.h b/src/obfuscation.h index 463f2d14a3c0..322a0331e179 100644 --- a/src/obfuscation.h +++ b/src/obfuscation.h @@ -53,7 +53,7 @@ extern CObfuscationPool obfuScationPool; extern CObfuScationSigner obfuScationSigner; extern std::vector vecObfuscationQueue; extern std::string strMasterNodePrivKey; -extern map mapObfuscationBroadcastTxes; +extern std::map mapObfuscationBroadcastTxes; extern CActiveMasternode activeMasternode; /** Holds an Obfuscation input @@ -194,7 +194,7 @@ class CObfuscationBroadcastTx public: CTransaction tx; CTxIn vin; - vector vchSig; + std::vector vchSig; int64_t sigTime; }; diff --git a/src/pivx-cli.cpp b/src/pivx-cli.cpp index f7f61bcc46b2..2c32a3684d92 100644 --- a/src/pivx-cli.cpp +++ b/src/pivx-cli.cpp @@ -24,13 +24,12 @@ #define _(x) std::string(x) /* Keep the _() around in case gettext or such will be used later to translate non-UI */ -using namespace std; static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900; std::string HelpMessageCli() { - string strUsage; + std::string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-conf=", strprintf(_("Specify configuration file (default: %s)"), "pivx.conf")); @@ -141,7 +140,7 @@ static void http_request_done(struct evhttp_request *req, void *ctx) } } -UniValue CallRPC(const string& strMethod, const UniValue& params) +UniValue CallRPC(const std::string& strMethod, const UniValue& params) { std::string host = GetArg("-rpcconnect", "127.0.0.1"); int port = GetArg("-rpcport", BaseParams().RPCPort()); @@ -149,25 +148,25 @@ UniValue CallRPC(const string& strMethod, const UniValue& params) // Create event base struct event_base *base = event_base_new(); // TODO RAII if (!base) - throw runtime_error("cannot create event_base"); + throw std::runtime_error("cannot create event_base"); // Synchronously look up hostname struct evhttp_connection *evcon = evhttp_connection_base_new(base, NULL, host.c_str(), port); // TODO RAII if (evcon == NULL) - throw runtime_error("create connection failed"); + throw std::runtime_error("create connection failed"); evhttp_connection_set_timeout(evcon, GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; struct evhttp_request *req = evhttp_request_new(http_request_done, (void*)&response); // TODO RAII if (req == NULL) - throw runtime_error("create http request failed"); + throw std::runtime_error("create http request failed"); // Get credentials std::string strRPCUserColonPass; if (mapArgs["-rpcpassword"] == "") { // Try fall back to cookie-based authentication if no password is provided if (!GetAuthCookie(&strRPCUserColonPass)) { - throw runtime_error(strprintf( + throw std::runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile().string().c_str())); @@ -202,26 +201,26 @@ UniValue CallRPC(const string& strMethod, const UniValue& params) if (response.status == 0) throw CConnectionFailed("couldn't connect to server"); else if (response.status == HTTP_UNAUTHORIZED) - throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); + throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) - throw runtime_error(strprintf("server returned HTTP error %d", response.status)); + throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) - throw runtime_error("no response from server"); + throw std::runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) - throw runtime_error("couldn't parse reply from server"); + throw std::runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) - throw runtime_error("expected reply to have result, error and id properties"); + throw std::runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char* argv[]) { - string strPrint; + std::string strPrint; int nRet = 0; try { // Skip switches @@ -232,8 +231,8 @@ int CommandLineRPC(int argc, char* argv[]) // Method if (argc < 2) - throw runtime_error("too few parameters"); - string strMethod = argv[1]; + throw std::runtime_error("too few parameters"); + std::string strMethod = argv[1]; // Parameters default to strings std::vector strParams(&argv[2], &argv[argc]); @@ -277,7 +276,7 @@ int CommandLineRPC(int argc, char* argv[]) } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { - strPrint = string("error: ") + e.what(); + strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); diff --git a/src/pivx-tx.cpp b/src/pivx-tx.cpp index d888765b004a..1595541e0d94 100644 --- a/src/pivx-tx.cpp +++ b/src/pivx-tx.cpp @@ -23,11 +23,9 @@ #include #include -using namespace boost::assign; -using namespace std; static bool fCreateBlank; -static map registers; +static std::map registers; CClientUIInterface uiInterface; static bool AppInitRawTx(int argc, char* argv[]) @@ -91,52 +89,52 @@ static bool AppInitRawTx(int argc, char* argv[]) return true; } -static void RegisterSetJson(const string& key, const string& rawJson) +static void RegisterSetJson(const std::string& key, const std::string& rawJson) { UniValue val; if (!val.read(rawJson)) { - string strErr = "Cannot parse JSON for key " + key; - throw runtime_error(strErr); + std::string strErr = "Cannot parse JSON for key " + key; + throw std::runtime_error(strErr); } registers[key] = val; } -static void RegisterSet(const string& strInput) +static void RegisterSet(const std::string& strInput) { // separate NAME:VALUE in string size_t pos = strInput.find(':'); - if ((pos == string::npos) || + if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) - throw runtime_error("Register input requires NAME:VALUE"); + throw std::runtime_error("Register input requires NAME:VALUE"); - string key = strInput.substr(0, pos); - string valStr = strInput.substr(pos + 1, string::npos); + std::string key = strInput.substr(0, pos); + std::string valStr = strInput.substr(pos + 1, std::string::npos); RegisterSetJson(key, valStr); } -static void RegisterLoad(const string& strInput) +static void RegisterLoad(const std::string& strInput) { // separate NAME:FILENAME in string size_t pos = strInput.find(':'); - if ((pos == string::npos) || + if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) - throw runtime_error("Register load requires NAME:FILENAME"); + throw std::runtime_error("Register load requires NAME:FILENAME"); - string key = strInput.substr(0, pos); - string filename = strInput.substr(pos + 1, string::npos); + std::string key = strInput.substr(0, pos); + std::string filename = strInput.substr(pos + 1, std::string::npos); FILE* f = fopen(filename.c_str(), "r"); if (!f) { - string strErr = "Cannot open file " + filename; - throw runtime_error(strErr); + std::string strErr = "Cannot open file " + filename; + throw std::runtime_error(strErr); } // load file chunks into one big buffer - string valStr; + std::string valStr; while ((!feof(f)) && (!ferror(f))) { char buf[4096]; int bread = fread(buf, 1, sizeof(buf), f); @@ -147,8 +145,8 @@ static void RegisterLoad(const string& strInput) } if (ferror(f)) { - string strErr = "Error reading file " + filename; - throw runtime_error(strErr); + std::string strErr = "Error reading file " + filename; + throw std::runtime_error(strErr); } fclose(f); @@ -157,37 +155,37 @@ static void RegisterLoad(const string& strInput) RegisterSetJson(key, valStr); } -static void MutateTxVersion(CMutableTransaction& tx, const string& cmdVal) +static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newVersion = atoi64(cmdVal); if (newVersion < 1 || newVersion > CTransaction::CURRENT_VERSION) - throw runtime_error("Invalid TX version requested"); + throw std::runtime_error("Invalid TX version requested"); tx.nVersion = (int)newVersion; } -static void MutateTxLocktime(CMutableTransaction& tx, const string& cmdVal) +static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newLocktime = atoi64(cmdVal); if (newLocktime < 0LL || newLocktime > 0xffffffffLL) - throw runtime_error("Invalid TX locktime requested"); + throw std::runtime_error("Invalid TX locktime requested"); tx.nLockTime = (unsigned int)newLocktime; } -static void MutateTxAddInput(CMutableTransaction& tx, const string& strInput) +static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput) { // separate TXID:VOUT in string size_t pos = strInput.find(':'); - if ((pos == string::npos) || + if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) - throw runtime_error("TX input missing separator"); + throw std::runtime_error("TX input missing separator"); // extract and validate TXID - string strTxid = strInput.substr(0, pos); + std::string strTxid = strInput.substr(0, pos); if ((strTxid.size() != 64) || !IsHex(strTxid)) - throw runtime_error("invalid TX input txid"); + throw std::runtime_error("invalid TX input txid"); uint256 txid(strTxid); static const unsigned int minTxOutSz = 9; @@ -195,36 +193,36 @@ static void MutateTxAddInput(CMutableTransaction& tx, const string& strInput) static const unsigned int maxVout = nMaxSize / minTxOutSz; // extract and validate vout - string strVout = strInput.substr(pos + 1, string::npos); + std::string strVout = strInput.substr(pos + 1, std::string::npos); int vout = atoi(strVout); if ((vout < 0) || (vout > (int)maxVout)) - throw runtime_error("invalid TX input vout"); + throw std::runtime_error("invalid TX input vout"); // append to transaction input list CTxIn txin(txid, vout); tx.vin.push_back(txin); } -static void MutateTxAddOutAddr(CMutableTransaction& tx, const string& strInput) +static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput) { // separate VALUE:ADDRESS in string size_t pos = strInput.find(':'); - if ((pos == string::npos) || + if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) - throw runtime_error("TX output missing separator"); + throw std::runtime_error("TX output missing separator"); // extract and validate VALUE - string strValue = strInput.substr(0, pos); + std::string strValue = strInput.substr(0, pos); CAmount value; if (!ParseMoney(strValue, value)) - throw runtime_error("invalid TX output value"); + throw std::runtime_error("invalid TX output value"); // extract and validate ADDRESS - string strAddr = strInput.substr(pos + 1, string::npos); + std::string strAddr = strInput.substr(pos + 1, std::string::npos); CBitcoinAddress addr(strAddr); if (!addr.IsValid()) - throw runtime_error("invalid TX output address"); + throw std::runtime_error("invalid TX output address"); // build standard output script via GetScriptForDestination() CScript scriptPubKey = GetScriptForDestination(addr.Get()); @@ -234,22 +232,22 @@ static void MutateTxAddOutAddr(CMutableTransaction& tx, const string& strInput) tx.vout.push_back(txout); } -static void MutateTxAddOutScript(CMutableTransaction& tx, const string& strInput) +static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput) { // separate VALUE:SCRIPT in string size_t pos = strInput.find(':'); - if ((pos == string::npos) || + if ((pos == std::string::npos) || (pos == 0)) - throw runtime_error("TX output missing separator"); + throw std::runtime_error("TX output missing separator"); // extract and validate VALUE - string strValue = strInput.substr(0, pos); + std::string strValue = strInput.substr(0, pos); CAmount value; if (!ParseMoney(strValue, value)) - throw runtime_error("invalid TX output value"); + throw std::runtime_error("invalid TX output value"); // extract and validate script - string strScript = strInput.substr(pos + 1, string::npos); + std::string strScript = strInput.substr(pos + 1, std::string::npos); CScript scriptPubKey = ParseScript(strScript); // throws on err // construct TxOut, append to transaction output list @@ -257,26 +255,26 @@ static void MutateTxAddOutScript(CMutableTransaction& tx, const string& strInput tx.vout.push_back(txout); } -static void MutateTxDelInput(CMutableTransaction& tx, const string& strInIdx) +static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested deletion index int inIdx = atoi(strInIdx); if (inIdx < 0 || inIdx >= (int)tx.vin.size()) { - string strErr = "Invalid TX input index '" + strInIdx + "'"; - throw runtime_error(strErr.c_str()); + std::string strErr = "Invalid TX input index '" + strInIdx + "'"; + throw std::runtime_error(strErr.c_str()); } // delete input from transaction tx.vin.erase(tx.vin.begin() + inIdx); } -static void MutateTxDelOutput(CMutableTransaction& tx, const string& strOutIdx) +static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx) { // parse requested deletion index int outIdx = atoi(strOutIdx); if (outIdx < 0 || outIdx >= (int)tx.vout.size()) { - string strErr = "Invalid TX output index '" + strOutIdx + "'"; - throw runtime_error(strErr.c_str()); + std::string strErr = "Invalid TX output index '" + strOutIdx + "'"; + throw std::runtime_error(strErr.c_str()); } // delete output from transaction @@ -296,7 +294,7 @@ static const struct { {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY}, }; -static bool findSighashFlags(int& flags, const string& flagStr) +static bool findSighashFlags(int& flags, const std::string& flagStr) { flags = 0; @@ -310,31 +308,31 @@ static bool findSighashFlags(int& flags, const string& flagStr) return false; } -uint256 ParseHashUO(map& o, string strKey) +uint256 ParseHashUO(std::map& o, std::string strKey) { if (!o.count(strKey)) return 0; return ParseHashUV(o[strKey], strKey); } -vector ParseHexUO(map& o, string strKey) +std::vector ParseHexUO(std::map& o, std::string strKey) { if (!o.count(strKey)) { - vector emptyVec; + std::vector emptyVec; return emptyVec; } return ParseHexUV(o[strKey], strKey); } -static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) +static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr) { int nHashType = SIGHASH_ALL; if (flagStr.size() > 0) if (!findSighashFlags(nHashType, flagStr)) - throw runtime_error("unknown sighash flag/sign option"); + throw std::runtime_error("unknown sighash flag/sign option"); - vector txVariants; + std::vector txVariants; txVariants.push_back(tx); // mergedTx will end up with all the signatures; it @@ -345,7 +343,7 @@ static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) CCoinsViewCache view(&viewDummy); if (!registers.count("privatekeys")) - throw runtime_error("privatekeys register variable must be set."); + throw std::runtime_error("privatekeys register variable must be set."); bool fGivenKeys = false; CBasicKeyStore tempKeystore; UniValue keysObj = registers["privatekeys"]; @@ -353,11 +351,11 @@ static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) { if (!keysObj[kidx].isStr()) - throw runtime_error("privatekey not a string"); + throw std::runtime_error("privatekey not a string"); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(keysObj[kidx].getValStr()); if (!fGood) - throw runtime_error("privatekey not valid"); + throw std::runtime_error("privatekey not valid"); CKey key = vchSecret.GetKey(); tempKeystore.AddKey(key); @@ -365,34 +363,34 @@ static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) // Add previous txouts given in the RPC call: if (!registers.count("prevtxs")) - throw runtime_error("prevtxs register variable must be set."); + throw std::runtime_error("prevtxs register variable must be set."); UniValue prevtxsObj = registers["prevtxs"]; { for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) { UniValue prevOut = prevtxsObj[previdx]; if (!prevOut.isObject()) - throw runtime_error("expected prevtxs internal object"); + throw std::runtime_error("expected prevtxs internal object"); - map types = map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR); + std::map types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR); if (!prevOut.checkObject(types)) - throw runtime_error("prevtxs internal object typecheck fail"); + throw std::runtime_error("prevtxs internal object typecheck fail"); uint256 txid = ParseHashUV(prevOut["txid"], "txid"); int nOut = atoi(prevOut["vout"].getValStr()); if (nOut < 0) - throw runtime_error("vout must be positive"); + throw std::runtime_error("vout must be positive"); - vector pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); + std::vector pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { CCoinsModifier coins = view.ModifyCoins(txid); if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) { - string err("Previous output scriptPubKey mismatch:\n"); + std::string err("Previous output scriptPubKey mismatch:\n"); err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" + scriptPubKey.ToString(); - throw runtime_error(err); + throw std::runtime_error(err); } if ((unsigned int)nOut >= coins->vout.size()) coins->vout.resize(nOut + 1); @@ -405,7 +403,7 @@ static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) if (fGivenKeys && scriptPubKey.IsPayToScriptHash() && prevOut.exists("redeemScript")) { UniValue v = prevOut["redeemScript"]; - vector rsData(ParseHexUV(v, "redeemScript")); + std::vector rsData(ParseHexUV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } @@ -460,7 +458,7 @@ class Secp256k1Init } }; -static void MutateTx(CMutableTransaction& tx, const string& command, const string& commandVal) +static void MutateTx(CMutableTransaction& tx, const std::string& command, const std::string& commandVal) { boost::scoped_ptr ecc; if (command == "nversion") @@ -492,7 +490,7 @@ static void MutateTx(CMutableTransaction& tx, const string& command, const strin RegisterSet(commandVal); else - throw runtime_error("unknown command"); + throw std::runtime_error("unknown command"); } static void OutputTxJSON(const CTransaction& tx) @@ -500,20 +498,20 @@ static void OutputTxJSON(const CTransaction& tx) UniValue entry(UniValue::VOBJ); TxToUniv(tx, 0, entry); - string jsonOutput = entry.write(4); + std::string jsonOutput = entry.write(4); fprintf(stdout, "%s\n", jsonOutput.c_str()); } static void OutputTxHash(const CTransaction& tx) { - string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) + std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) fprintf(stdout, "%s\n", strHexHash.c_str()); } static void OutputTxHex(const CTransaction& tx) { - string strHex = EncodeHexTx(tx); + std::string strHex = EncodeHexTx(tx); fprintf(stdout, "%s\n", strHex.c_str()); } @@ -528,10 +526,10 @@ static void OutputTx(const CTransaction& tx) OutputTxHex(tx); } -static string readStdin() +static std::string readStdin() { char buf[4096]; - string ret; + std::string ret; while (!feof(stdin)) { size_t bread = fread(buf, 1, sizeof(buf), stdin); @@ -541,7 +539,7 @@ static string readStdin() } if (ferror(stdin)) - throw runtime_error("error reading stdin"); + throw std::runtime_error("error reading stdin"); boost::algorithm::trim_right(ret); @@ -550,7 +548,7 @@ static string readStdin() static int CommandLineRawTx(int argc, char* argv[]) { - string strPrint; + std::string strPrint; int nRet = 0; try { // Skip switches; Permit common stdin convention "-" @@ -566,15 +564,15 @@ static int CommandLineRawTx(int argc, char* argv[]) if (!fCreateBlank) { // require at least one param if (argc < 2) - throw runtime_error("too few parameters"); + throw std::runtime_error("too few parameters"); // param: hex-encoded pivx transaction - string strHexTx(argv[1]); + std::string strHexTx(argv[1]); if (strHexTx == "-") // "-" implies standard input strHexTx = readStdin(); if (!DecodeHexTx(txDecodeTmp, strHexTx)) - throw runtime_error("invalid transaction encoding"); + throw std::runtime_error("invalid transaction encoding"); startArg = 2; } else @@ -583,10 +581,10 @@ static int CommandLineRawTx(int argc, char* argv[]) CMutableTransaction tx(txDecodeTmp); for (int i = startArg; i < argc; i++) { - string arg = argv[i]; - string key, value; + std::string arg = argv[i]; + std::string key, value; size_t eqpos = arg.find('='); - if (eqpos == string::npos) + if (eqpos == std::string::npos) key = arg; else { key = arg.substr(0, eqpos); @@ -602,7 +600,7 @@ static int CommandLineRawTx(int argc, char* argv[]) catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { - strPrint = string("error: ") + e.what(); + strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRawTx()"); diff --git a/src/qt/bip38tooldialog.cpp b/src/qt/bip38tooldialog.cpp index 858702d2486f..1f511699b783 100644 --- a/src/qt/bip38tooldialog.cpp +++ b/src/qt/bip38tooldialog.cpp @@ -176,8 +176,8 @@ void Bip38ToolDialog::on_pasteButton_DEC_clicked() void Bip38ToolDialog::on_decryptKeyButton_DEC_clicked() { - string strPassphrase = ui->passphraseIn_DEC->text().toStdString(); - string strKey = ui->encryptedKeyIn_DEC->text().toStdString(); + std::string strPassphrase = ui->passphraseIn_DEC->text().toStdString(); + std::string strKey = ui->encryptedKeyIn_DEC->text().toStdString(); uint256 privKey; bool fCompressed; diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index 3aab20e57506..9fc60ac9aae1 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -32,7 +32,6 @@ #include #include -using namespace std; QList CoinControlDialog::payAmounts; int CoinControlDialog::nSplitBlockDummy; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); @@ -476,7 +475,7 @@ QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEsti // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { - vector vOutpts; + std::vector vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); @@ -493,8 +492,8 @@ void CoinControlDialog::updateDialogLabels() return; } - vector vCoinControl; - vector vOutputs; + std::vector vCoinControl; + std::vector vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); @@ -534,7 +533,7 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) nPayAmount += amount; if (amount > 0) { - CTxOut txout(amount, (CScript)vector(24, 0)); + CTxOut txout(amount, (CScript)std::vector(24, 0)); txDummy.vout.push_back(txout); if (txout.IsDust(::minRelayTxFee)) fDust = true; @@ -554,8 +553,8 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) int nQuantityUncompressed = 0; bool fAllowFree = false; - vector vCoinControl; - vector vOutputs; + std::vector vCoinControl; + std::vector vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); @@ -596,7 +595,7 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) // calculation if (nQuantity > 0) { // Bytes - nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + max(1, CoinControlDialog::nSplitBlockDummy) : 2) * 34) + 10; // always assume +1 output for change here + nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + std::max(1, CoinControlDialog::nSplitBlockDummy) : 2) * 34) + 10; // always assume +1 output for change here // Priority double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget); @@ -607,7 +606,7 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); // IX Fee - if (coinControl->useSwiftTX) nPayFee = max(nPayFee, CENT); + if (coinControl->useSwiftTX) nPayFee = std::max(nPayFee, CENT); // Allow free? double dPriorityNeeded = mempoolEstimatePriority; if (dPriorityNeeded <= 0) @@ -623,7 +622,7 @@ void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < CENT) { - CTxOut txout(nChange, (CScript)vector(24, 0)); + CTxOut txout(nChange, (CScript)std::vector(24, 0)); if (txout.IsDust(::minRelayTxFee)) { nPayFee += nChange; nChange = 0; @@ -735,10 +734,10 @@ void CoinControlDialog::updateView() int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget); - map> mapCoins; + std::map> mapCoins; model->listCoins(mapCoins); - for (PAIRTYPE(QString, vector) coins : mapCoins) { + for (PAIRTYPE(QString, std::vector) coins : mapCoins) { CCoinControlWidgetItem* itemWalletAddress = new CCoinControlWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; diff --git a/src/qt/multisigdialog.cpp b/src/qt/multisigdialog.cpp index f819263223f5..54db2cbe9bac 100644 --- a/src/qt/multisigdialog.cpp +++ b/src/qt/multisigdialog.cpp @@ -193,7 +193,7 @@ void MultisigDialog::on_addMultisigButton_clicked() int m = ui->enterMSpinbox->value(); - vector keys; + std::vector keys; for (int i = 0; i < ui->addressList->count(); i++) { QWidget* address = qobject_cast(ui->addressList->itemAt(i)->widget()); @@ -211,7 +211,7 @@ void MultisigDialog::on_importAddressButton_clicked(){ if(!model) return; - string sRedeem = ui->importRedeem->text().toStdString(); + std::string sRedeem = ui->importRedeem->text().toStdString(); if(sRedeem.empty()){ ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); @@ -219,7 +219,7 @@ void MultisigDialog::on_importAddressButton_clicked(){ return; } - vector vRedeem; + std::vector vRedeem; size_t pos = 0; //search redeem input delimited by space @@ -228,7 +228,7 @@ void MultisigDialog::on_importAddressButton_clicked(){ sRedeem.erase(0, pos + 1); } - vector keys(vRedeem.begin()+1, vRedeem.end()-1); + std::vector keys(vRedeem.begin()+1, vRedeem.end()-1); addMultisig(stoi(vRedeem[0]), keys); @@ -237,28 +237,28 @@ void MultisigDialog::on_importAddressButton_clicked(){ pwalletMain->ReacceptWalletTransactions(); } -bool MultisigDialog::addMultisig(int m, vector keys){ +bool MultisigDialog::addMultisig(int m, std::vector keys){ try{ - string error; + std::string error; CScript redeem; if(!createRedeemScript(m, keys, redeem, error)){ - throw runtime_error(error.data()); + throw std::runtime_error(error.data()); } if (::IsMine(*pwalletMain, redeem) == ISMINE_SPENDABLE){ - throw runtime_error("The wallet already contains this script"); + throw std::runtime_error("The wallet already contains this script"); } if(!pwalletMain->AddCScript(redeem)){ - throw runtime_error("Failure: address invalid or already exists"); + throw std::runtime_error("Failure: address invalid or already exists"); } CScriptID innerID(redeem); - string label = ui->multisigAddressLabel->text().toStdString(); + std::string label = ui->multisigAddressLabel->text().toStdString(); pwalletMain->SetAddressBook(innerID, label, "receive"); if (!pwalletMain->AddMultiSig(redeem)){ - throw runtime_error("Failure: unable to add address as watch only"); + throw std::runtime_error("Failure: unable to add address as watch only"); } ui->addMultisigStatus->setStyleSheet("QLabel { color: black; }"); @@ -266,7 +266,7 @@ bool MultisigDialog::addMultisig(int m, vector keys){ QString::fromStdString(CBitcoinAddress(innerID).ToString()) + " has been added to the wallet.\nSend the redeem below for other owners to import:\n" + QString::fromStdString(redeem.ToString())); - }catch(const runtime_error& e) { + }catch(const std::runtime_error& e) { ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText(tr(e.what())); return false; @@ -281,12 +281,12 @@ void MultisigDialog::on_createButton_clicked() if(!model) return; - vector vUserIn; - vector vUserOut; + std::vector vUserIn; + std::vector vUserOut; try{ //Add inputs from Coin Control if any are selected if (CoinControlDialog::coinControl->HasSelected()) { - vector vSelected; + std::vector vSelected; CoinControlDialog::coinControl->ListSelected(vSelected); for (auto outpoint : vSelected) vUserIn.emplace_back(CTxIn(outpoint)); @@ -352,10 +352,10 @@ void MultisigDialog::on_createButton_clicked() //clear member variable multisigTx = CMutableTransaction(); - string error; - string fee; + std::string error; + std::string fee; if(!createMultisigTransaction(vUserIn, vUserOut, fee, error)){ - throw runtime_error(error); + throw std::runtime_error(error); } //display status string @@ -369,13 +369,13 @@ void MultisigDialog::on_createButton_clicked() ui->transactionHex->setText(QString::fromStdString(EncodeHexTx(multisigTx))); } - }catch(const runtime_error& e){ + }catch(const std::runtime_error& e){ ui->createButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->createButtonStatus->setText(tr(e.what())); } } -bool MultisigDialog::createMultisigTransaction(vector vUserIn, vector vUserOut, string& feeStringRet, string& errorRet) +bool MultisigDialog::createMultisigTransaction(std::vector vUserIn, std::vector vUserOut, std::string& feeStringRet, std::string& errorRet) { try{ //attempt to access the given inputs @@ -383,7 +383,7 @@ bool MultisigDialog::createMultisigTransaction(vector vUserIn, vector vInputVals; + std::vector vInputVals; CScript changePubKey; bool fFirst = true; @@ -400,7 +400,7 @@ bool MultisigDialog::createMultisigTransaction(vector vUserIn, vector vUserIn, vector vUserIn, vectorIsAvailable(tx.vin[0].prevout.n)){ - throw runtime_error("Coins unavailable (unconfirmed/spent)"); + throw std::runtime_error("Coins unavailable (unconfirmed/spent)"); } CScript prevPubKey = coins->vout[tx.vin[0].prevout.n].scriptPubKey; @@ -449,20 +449,20 @@ bool MultisigDialog::createMultisigTransaction(vector vUserIn, vector(address); CScript redeemScript; if (!pwalletMain->GetCScript(hash, redeemScript)){ - throw runtime_error("could not redeem"); + throw std::runtime_error("could not redeem"); } txnouttype type; - vector addresses; + std::vector addresses; int nReq; if(!ExtractDestinations(redeemScript, type, addresses, nReq)){ - throw runtime_error("Could not extract destinations from redeem script."); + throw std::runtime_error("Could not extract destinations from redeem script."); } for(CTxIn& in : tx.vin){ @@ -481,7 +481,7 @@ bool MultisigDialog::createMultisigTransaction(vector vUserIn, vector vUserIn, vectortransactionHex->text().toStdString())){ - throw runtime_error("Failed to decode transaction hex!"); + throw std::runtime_error("Failed to decode transaction hex!"); } CMutableTransaction tx(txRead); @@ -518,11 +518,11 @@ void MultisigDialog::on_signButton_clicked() return; } - string errorOut = string(); + std::string errorOut = std::string(); bool fComplete = signMultisigTx(tx, errorOut, ui->keyList); if(!errorOut.empty()){ - throw runtime_error(errorOut.data()); + throw std::runtime_error(errorOut.data()); }else{ this->multisigTx = tx; } @@ -530,7 +530,7 @@ void MultisigDialog::on_signButton_clicked() ui->signButtonStatus->setStyleSheet("QTextEdit{ color: black }"); ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx)); - }catch(const runtime_error& e){ + }catch(const std::runtime_error& e){ ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->signButtonStatus->setText(tr(e.what())); } @@ -541,19 +541,19 @@ void MultisigDialog::on_signButton_clicked() */ QString MultisigDialog::buildMultisigTxStatusString(bool fComplete, const CMutableTransaction& tx) { - string sTxHex = EncodeHexTx(tx); + std::string sTxHex = EncodeHexTx(tx); if(fComplete){ ui->commitButton->setEnabled(true); - string sTxId = tx.GetHash().GetHex(); - string sTxComplete = "Complete: true!\n" + std::string sTxId = tx.GetHash().GetHex(); + std::string sTxComplete = "Complete: true!\n" "The commit button has now been enabled for you to finalize the transaction.\n" "Once the commit button is clicked, the transaction will be published and coins transferred " "to their destinations.\nWARNING: THE ACTIONS OF THE COMMIT BUTTON ARE FINAL AND CANNOT BE REVERSED."; return QString(strprintf("%s\nTx Id:\n%s\nTx Hex:\n%s",sTxComplete, sTxId, sTxHex).c_str()); } else { - string sTxIncomplete = "Complete: false.\n" + std::string sTxIncomplete = "Complete: false.\n" "You may now send the hex below to another owner to sign.\n" "Keep in mind the transaction must be passed from one owner to the next for signing.\n" "Ensure all owners have imported the redeem before trying to sign. (besides creator)"; @@ -563,7 +563,7 @@ QString MultisigDialog::buildMultisigTxStatusString(bool fComplete, const CMutab } -CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const vector& vin) +CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const std::vector& vin) { CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); @@ -585,7 +585,7 @@ CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const vector& vin } -bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, QVBoxLayout* keyList) +bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, std::string& errorOut, QVBoxLayout* keyList) { //will be set false if all inputs are not fully signed(valid) bool fComplete = true; @@ -596,7 +596,7 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q try{ //copy of vin for reference before vin is mutated - vector oldVin(tx.vin); + std::vector oldVin(tx.vin); CBasicKeyStore privKeystore; //if keys were given, attempt to collect redeem and scriptpubkey @@ -606,10 +606,10 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q QLineEdit* key = keyFrame->findChild("key"); CBitcoinSecret vchSecret; if (!vchSecret.SetString(key->text().toStdString())) - throw runtime_error("Invalid private key"); + throw std::runtime_error("Invalid private key"); CKey cKey = vchSecret.GetKey(); if (!cKey.IsValid()) - throw runtime_error("Private key outside allowed range"); + throw std::runtime_error("Private key outside allowed range"); privKeystore.AddKey(cKey); } @@ -618,10 +618,10 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)) - throw runtime_error("txin could not be found"); + throw std::runtime_error("txin could not be found"); if (hashBlock == 0) - throw runtime_error("txin is unconfirmed"); + throw std::runtime_error("txin is unconfirmed"); //get pubkey from input CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; @@ -629,7 +629,7 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q //get payment destination CTxDestination address; if(!ExtractDestination(prevPubKey, address)){ - throw runtime_error("Could not find address for destination."); + throw std::runtime_error("Could not find address for destination."); } //get redeem script related to destination @@ -645,7 +645,7 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q if (model->getEncryptionStatus() == model->Locked) { if (!model->requestUnlock(AskPassphraseDialog::Context::Multi_Sig, true).isValid()) { // Unlock wallet was cancelled - throw runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first."); + throw std::runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first."); } } } @@ -660,10 +660,10 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)) - throw runtime_error("txin could not be found"); + throw std::runtime_error("txin could not be found"); if (hashBlock == 0) - throw runtime_error("txin is unconfirmed"); + throw std::runtime_error("txin is unconfirmed"); txin.scriptSig.clear(); CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; @@ -682,8 +682,8 @@ bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, Q ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx)); - }catch(const runtime_error& e){ - errorOut = string(e.what()); + }catch(const std::runtime_error& e){ + errorOut = std::string(e.what()); fComplete = false; } return fComplete; @@ -697,10 +697,10 @@ bool MultisigDialog::isFullyVerified(CMutableTransaction& tx){ CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)){ - throw runtime_error("txin could not be found"); + throw std::runtime_error("txin could not be found"); } if (hashBlock == 0){ - throw runtime_error("txin is unconfirmed"); + throw std::runtime_error("txin is unconfirmed"); } //get pubkey from this input as output in last tx @@ -712,7 +712,7 @@ bool MultisigDialog::isFullyVerified(CMutableTransaction& tx){ nIn++; } - }catch(const runtime_error& e){ + }catch(const std::runtime_error& e){ return false; } @@ -727,7 +727,7 @@ void MultisigDialog::commitMultisigTx() CWalletTx wtx(pwalletMain, tx); CReserveKey keyChange(pwalletMain); if (!pwalletMain->CommitTransaction(wtx, keyChange)) - throw runtime_error(string("Transaction rejected - Failed to commit")); + throw std::runtime_error(std::string("Transaction rejected - Failed to commit")); #else uint256 hashTx = tx.GetHash(); CCoinsViewCache& view = *pcoinsTip; @@ -741,60 +741,60 @@ void MultisigDialog::commitMultisigTx() CValidationState state; if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) { if (state.IsInvalid()) - throw runtime_error(strprintf("Transaction rejected - %i: %s", state.GetRejectCode(), state.GetRejectReason())); + throw std::runtime_error(strprintf("Transaction rejected - %i: %s", state.GetRejectCode(), state.GetRejectReason())); else - throw runtime_error(string("Transaction rejected - ") + state.GetRejectReason()); + throw std::runtime_error(std::string("Transaction rejected - ") + state.GetRejectReason()); } } else if (fHaveChain) { - throw runtime_error("transaction already in block chain"); + throw std::runtime_error("transaction already in block chain"); } RelayTransaction(tx); #endif //disable commit if successfully committed ui->commitButton->setEnabled(false); ui->signButtonStatus->setText(strprintf("Transaction has been successfully published with transaction ID:\n %s", tx.GetHash().GetHex()).c_str()); - }catch(const runtime_error& e){ + }catch(const std::runtime_error& e){ ui->signButtonStatus->setText(e.what()); } } -bool MultisigDialog::createRedeemScript(int m, vector vKeys, CScript& redeemRet, string& errorRet) +bool MultisigDialog::createRedeemScript(int m, std::vector vKeys, CScript& redeemRet, std::string& errorRet) { try{ int n = vKeys.size(); //gather pub keys if (n < 1) - throw runtime_error("a Multisignature address must require at least one key to redeem"); + throw std::runtime_error("a Multisignature address must require at least one key to redeem"); if (n < m) - throw runtime_error( + throw std::runtime_error( strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", m, n)); if (n > 15) - throw runtime_error("Number of addresses involved in the Multisignature address creation > 15\nReduce the number"); + throw std::runtime_error("Number of addresses involved in the Multisignature address creation > 15\nReduce the number"); - vector pubkeys; + std::vector pubkeys; pubkeys.resize(n); int i = 0; - for(vector::iterator it = vKeys.begin(); it != vKeys.end(); ++it) { - string keyString = *it; + for(std::vector::iterator it = vKeys.begin(); it != vKeys.end(); ++it) { + std::string keyString = *it; #ifdef ENABLE_WALLET // Case 1: PIVX address and we have full public key: CBitcoinAddress address(keyString); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) { - throw runtime_error( + throw std::runtime_error( strprintf("%s does not refer to a key", keyString)); } CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) - throw runtime_error( + throw std::runtime_error( strprintf("no full public key for address %s", keyString)); if (!vchPubKey.IsFullyValid()){ - string sKey = keyString.empty()?"(empty)":keyString; - throw runtime_error(" Invalid public key: " + sKey ); + std::string sKey = keyString.empty()?"(empty)":keyString; + throw std::runtime_error(" Invalid public key: " + sKey ); } pubkeys[i++] = vchPubKey; } @@ -805,11 +805,11 @@ bool MultisigDialog::createRedeemScript(int m, vector vKeys, CScript& re if (IsHex(keyString)) { CPubKey vchPubKey(ParseHex(keyString)); if (!vchPubKey.IsFullyValid()){ - throw runtime_error(" Invalid public key: " + keyString); + throw std::runtime_error(" Invalid public key: " + keyString); } pubkeys[i++] = vchPubKey; } else { - throw runtime_error(" Invalid public key: " + keyString); + throw std::runtime_error(" Invalid public key: " + keyString); } } //populate redeem script @@ -817,15 +817,15 @@ bool MultisigDialog::createRedeemScript(int m, vector vKeys, CScript& re redeemRet << redeemRet.EncodeOP_N(m); //public keys for(CPubKey& key : pubkeys){ - vector vKey= ToByteVector(key); + std::vector vKey= ToByteVector(key); redeemRet << vKey; } //OP_N for total pubkeys redeemRet << redeemRet.EncodeOP_N(pubkeys.size()); redeemRet << OP_CHECKMULTISIG; return true; - }catch(const runtime_error& e){ - errorRet = string(e.what()); + }catch(const std::runtime_error& e){ + errorRet = std::string(e.what()); return false; } } diff --git a/src/qt/multisigdialog.h b/src/qt/multisigdialog.h index 152f2c2752b9..48bb3429b3e1 100644 --- a/src/qt/multisigdialog.h +++ b/src/qt/multisigdialog.h @@ -47,7 +47,7 @@ public slots: CCoinsViewCache getInputsCoinsViewCache(const std::vector& vin); QString buildMultisigTxStatusString(bool fComplete, const CMutableTransaction& tx); bool createRedeemScript(int m, std::vector keys, CScript& redeemRet, std::string& errorRet); - bool createMultisigTransaction(std::vector vUserIn, std::vector vUserOut, string& feeStringRet, string& errorRet); + bool createMultisigTransaction(std::vector vUserIn, std::vector vUserOut, std::string& feeStringRet, std::string& errorRet); bool signMultisigTx(CMutableTransaction& txToSign, std::string& errorMessageRet, QVBoxLayout* keyList = nullptr); bool addMultisig(int m, std::vector keys); bool isFullyVerified(CMutableTransaction& txToVerify); diff --git a/src/qt/paymentrequestplus.cpp b/src/qt/paymentrequestplus.cpp index d3555035c924..748a799da718 100644 --- a/src/qt/paymentrequestplus.cpp +++ b/src/qt/paymentrequestplus.cpp @@ -18,7 +18,6 @@ #include #include -using namespace std; class SSLVerifyError : public std::runtime_error { @@ -47,7 +46,7 @@ bool PaymentRequestPlus::parse(const QByteArray& data) return true; } -bool PaymentRequestPlus::SerializeToString(string* output) const +bool PaymentRequestPlus::SerializeToString(std::string* output) const { return paymentRequest.SerializeToString(output); } @@ -201,7 +200,7 @@ QList > PaymentRequestPlus::getPayTo() const const unsigned char* scriptStr = (const unsigned char*)details.outputs(i).script().data(); CScript s(scriptStr, scriptStr + details.outputs(i).script().size()); - result.append(make_pair(s, details.outputs(i).amount())); + result.append(std::make_pair(s, details.outputs(i).amount())); } return result; } diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp index 9613f1cfba86..c0c1340a6531 100644 --- a/src/qt/paymentserver.cpp +++ b/src/qt/paymentserver.cpp @@ -42,8 +42,6 @@ #include #include -using namespace boost; -using namespace std; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("pivx:"); @@ -576,7 +574,7 @@ void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipien // Create a new refund address, or re-use: QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant); std::string strAccount = account.toStdString(); - set refundAddresses = wallet->GetAccountAddresses(strAccount); + std::set refundAddresses = wallet->GetAccountAddresses(strAccount); if (!refundAddresses.empty()) { CScript s = GetScriptForDestination(*refundAddresses.begin()); payments::Output* refund_to = payment.add_refund_to(); diff --git a/src/qt/pivx.cpp b/src/qt/pivx.cpp index 70ebafb69e20..830e8941e0ec 100644 --- a/src/qt/pivx.cpp +++ b/src/qt/pivx.cpp @@ -587,7 +587,7 @@ int main(int argc, char* argv[]) #ifdef ENABLE_WALLET /// 7a. parse masternode.conf - string strErr; + std::string strErr; if (!masternodeConfig.read(strErr)) { QMessageBox::critical(0, QObject::tr("PIVX Core"), QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str())); diff --git a/src/qt/pivxstrings.cpp b/src/qt/pivxstrings.cpp index 12bd878a7d4f..328aa6e1f29b 100644 --- a/src/qt/pivxstrings.cpp +++ b/src/qt/pivxstrings.cpp @@ -36,7 +36,7 @@ QT_TRANSLATE_NOOP("pivx-core", "" "running."), QT_TRANSLATE_NOOP("pivx-core", "" "Change automatic finalized budget voting behavior. mode=auto: Vote for only " -"exact finalized budget match to my generated budget. (string, default: auto)"), +"exact finalized budget match to my generated budget. (std::string, default: auto)"), QT_TRANSLATE_NOOP("pivx-core", "" "Continuously rate-limit free transactions to *1000 bytes per minute " "(default:%u)"), diff --git a/src/qt/privacydialog.cpp b/src/qt/privacydialog.cpp index 433cd261a46e..0ccb721bc55c 100644 --- a/src/qt/privacydialog.cpp +++ b/src/qt/privacydialog.cpp @@ -200,8 +200,8 @@ void PrivacyDialog::on_pushButtonMintzPIV_clicked() int64_t nTime = GetTimeMillis(); CWalletTx wtx; - vector vMints; - string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); + std::vector vMints; + std::string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); // Return if something went wrong during minting if (strError != ""){ @@ -246,7 +246,7 @@ void PrivacyDialog::on_pushButtonMintReset_clicked() ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); - string strResetMintResult = pwalletMain->ResetMintZerocoin(); + std::string strResetMintResult = pwalletMain->ResetMintZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); @@ -261,7 +261,7 @@ void PrivacyDialog::on_pushButtonSpentReset_clicked() ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: ")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); - string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); + std::string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); @@ -412,8 +412,8 @@ void PrivacyDialog::sendzPIV() ui->TEMintStatus->repaint(); // use mints from zPIV selector if applicable - vector vMintsToFetch; - vector vMintsSelected; + std::vector vMintsToFetch; + std::vector vMintsSelected; if (!ZPivControlDialog::setSelectedMints.empty()) { vMintsToFetch = ZPivControlDialog::GetSelectedMints(); @@ -625,13 +625,13 @@ void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirme std::map mapUnconfirmed; std::map mapImmature; for (const auto& denom : libzerocoin::zerocoinDenomList){ - mapDenomBalances.insert(make_pair(denom, 0)); - mapUnconfirmed.insert(make_pair(denom, 0)); - mapImmature.insert(make_pair(denom, 0)); + mapDenomBalances.insert(std::make_pair(denom, 0)); + mapUnconfirmed.insert(std::make_pair(denom, 0)); + mapImmature.insert(std::make_pair(denom, 0)); } std::vector vMints = pwalletMain->zpivTracker->GetMints(false); - map mapMaturityHeights = GetMintMaturityHeight(); + std::map mapMaturityHeights = GetMintMaturityHeight(); for (auto& meta : vMints){ // All denominations mapDenomBalances.at(meta.denom)++; diff --git a/src/qt/proposalframe.cpp b/src/qt/proposalframe.cpp index 9f5df1369424..8b84fbd36567 100644 --- a/src/qt/proposalframe.cpp +++ b/src/qt/proposalframe.cpp @@ -298,7 +298,7 @@ void ProposalFrame::SendVote(std::string strHash, int nVote) std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { - budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenMasternodeBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); mnresult += mne.getAlias() + ": " + "Success!" + "
"; success++; diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp index 6eef1a083635..908c8df9127d 100644 --- a/src/qt/transactiondesc.cpp +++ b/src/qt/transactiondesc.cpp @@ -23,7 +23,6 @@ #include #include -using namespace std; QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) { @@ -254,14 +253,14 @@ QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionReco strHTML += "" + tr("Output index") + ": " + QString::number(rec->getOutputIndex()) + "
"; // Message from normal pivx:URI (pivx:XyZ...?message=example) - foreach (const PAIRTYPE(string, string) & r, wtx.vOrderForm) + foreach (const PAIRTYPE(std::string, std::string) & r, wtx.vOrderForm) if (r.first == "Message") strHTML += "
" + tr("Message") + ":
" + GUIUtil::HtmlEscape(r.second, true) + "
"; // // PaymentRequest info: // - foreach (const PAIRTYPE(string, string) & r, wtx.vOrderForm) { + foreach (const PAIRTYPE(std::string, std::string) & r, wtx.vOrderForm) { if (r.first == "PaymentRequest") { PaymentRequestPlus req; req.parse(QByteArray::fromRawData(r.second.data(), r.second.size())); diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp index aa8eb1f08ac3..9d57816239bf 100644 --- a/src/qt/transactionrecord.cpp +++ b/src/qt/transactionrecord.cpp @@ -121,7 +121,7 @@ QList TransactionRecord::decomposeTransaction(const CWallet* continue; } - string strAddress = ""; + std::string strAddress = ""; CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) strAddress = CBitcoinAddress(address).ToString(); diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 297127bdc8c8..360f19637955 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -26,7 +26,6 @@ #include #include -using namespace std; WalletModel::WalletModel(CWallet* wallet, OptionsModel* optionsModel, QObject* parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), @@ -245,7 +244,7 @@ bool WalletModel::validateAddress(const QString& address) return addressParsed.IsValid(); } -void WalletModel::updateAddressBookLabels(const CTxDestination& dest, const string& strName, const string& strPurpose) +void WalletModel::updateAddressBookLabels(const CTxDestination& dest, const std::string& strName, const std::string& strPurpose) { LOCK(wallet->cs_wallet); @@ -381,10 +380,10 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction& tran std::string key("PaymentRequest"); std::string value; rcp.paymentRequest.SerializeToString(&value); - newTx->vOrderForm.push_back(make_pair(key, value)); + newTx->vOrderForm.push_back(std::make_pair(key, value)); } else if (!rcp.message.isEmpty()) // Message from normal pivx:URI (pivx:XyZ...?message=example) { - newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString())); + newTx->vOrderForm.push_back(std::make_pair("Message", rcp.message.toStdString())); } } @@ -532,7 +531,7 @@ static std::vector > vQueueNotifications; static void NotifyTransactionChanged(WalletModel* walletmodel, CWallet* wallet, const uint256& hash, ChangeType status) { if (fQueueNotifications) { - vQueueNotifications.push_back(make_pair(hash, status)); + vQueueNotifications.push_back(std::make_pair(hash, status)); return; } @@ -582,10 +581,10 @@ static void NotifyzPIVReset(WalletModel* walletmodel) QMetaObject::invokeMethod(walletmodel, "checkBalanceChanged", Qt::QueuedConnection); } -static void NotifyWalletBacked(WalletModel* model, const bool& fSuccess, const string& filename) +static void NotifyWalletBacked(WalletModel* model, const bool& fSuccess, const std::string& filename) { - string message; - string title = "Backup "; + std::string message; + std::string title = "Backup "; CClientUIInterface::MessageBoxFlags method; if (fSuccess) { diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index 655901de34bc..73e464bd87d2 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -146,7 +146,7 @@ class WalletModel : public QObject CAmount getWatchImmatureBalance() const; EncryptionStatus getEncryptionStatus() const; CKey generateNewKey() const; //for temporary paper wallet key generation - bool setAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose); + bool setAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose); void encryptKey(const CKey key, const std::string& pwd, const std::string& slt, std::vector& crypted); void decryptKey(const std::vector& crypted, const std::string& slt, const std::string& pwd, CKey& key); void emitBalanceChanged(); // Force update of UI-elements even when no values have changed @@ -216,7 +216,7 @@ class WalletModel : public QObject void listZerocoinMints(std::set& setMints, bool fUnusedOnly = false, bool fMaturedOnly = false, bool fUpdateStatus = false, bool fWrongSeed = false); - string GetUniqueWalletBackupName(); + std::string GetUniqueWalletBackupName(); void loadReceiveRequests(std::vector& vReceiveRequests); bool saveReceiveRequest(const std::string& sAddress, const int64_t nId, const std::string& sRequest); @@ -303,7 +303,7 @@ public slots: /* Current, immature or unconfirmed balance might have changed - emit 'balanceChanged' if so */ void pollBalanceChanged(); /* Update address book labels in the database */ - void updateAddressBookLabels(const CTxDestination& address, const string& strName, const string& strPurpose); + void updateAddressBookLabels(const CTxDestination& address, const std::string& strName, const std::string& strPurpose); }; #endif // BITCOIN_QT_WALLETMODEL_H diff --git a/src/qt/zpivcontroldialog.cpp b/src/qt/zpivcontroldialog.cpp index cfc5d7cd41ab..a2d8f6c39909 100644 --- a/src/qt/zpivcontroldialog.cpp +++ b/src/qt/zpivcontroldialog.cpp @@ -9,8 +9,6 @@ #include "main.h" #include "walletmodel.h" -using namespace std; -using namespace libzerocoin; std::set ZPivControlDialog::setSelectedMints; std::set ZPivControlDialog::setMints; @@ -60,7 +58,7 @@ void ZPivControlDialog::updateList() // add a top level item for each denomination QFlags flgTristate = Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; - map mapDenomPosition; + std::map mapDenomPosition; for (auto denom : libzerocoin::zerocoinDenomList) { CZPivControlWidgetItem* itemDenom(new CZPivControlWidgetItem); ui->treeWidget->addTopLevelItem(itemDenom); @@ -138,7 +136,7 @@ void ZPivControlDialog::updateList() if (setSelectedMints.count(strPubCoinHash)) setSelectedMints.erase(strPubCoinHash); - string strReason = ""; + std::string strReason = ""; if(nConfirmations < Params().Zerocoin_MintRequiredConfirmations()) strReason = strprintf("Needs %d more confirmations", Params().Zerocoin_MintRequiredConfirmations() - nConfirmations); else if (model->getEncryptionStatus() == WalletModel::EncryptionStatus::Locked) diff --git a/src/rest.cpp b/src/rest.cpp index cfff2f12a5fe..c61ef0e8d9b8 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -21,7 +21,6 @@ #include -using namespace std; static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once @@ -65,14 +64,14 @@ extern UniValue mempoolToJSON(bool fVerbose = false); extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); 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->WriteReply(status, message + "\r\n"); return false; } -static enum RetFormat ParseDataFormat(vector& params, const string& strReq) +static enum RetFormat ParseDataFormat(std::vector& params, const std::string& strReq) { boost::split(params, strReq, boost::is_any_of(".")); if (params.size() > 1) { @@ -84,9 +83,9 @@ static enum RetFormat ParseDataFormat(vector& params, const string& strR 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++) if (strlen(rf_names[i].name) > 0) { formats.append("."); @@ -100,7 +99,7 @@ static string AvailableDataFormatsString() 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)) return false; @@ -122,9 +121,9 @@ static bool rest_headers(HTTPRequest* req, { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; const RetFormat rf = ParseDataFormat(params, strURIPart); - vector path; + std::vector path; boost::split(path, params[0], boost::is_any_of("/")); if (path.size() != 2) @@ -134,7 +133,7 @@ static bool rest_headers(HTTPRequest* req, if (count < 1 || count > 2000) return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]); - string hashStr = path[1]; + std::string hashStr = path[1]; uint256 hash; if (!ParseHashStr(hashStr, hash)) return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); @@ -160,14 +159,14 @@ static bool rest_headers(HTTPRequest* req, switch (rf) { case RF_BINARY: { - string binaryHeader = ssHeader.str(); + std::string binaryHeader = ssHeader.str(); req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteReply(HTTP_OK, binaryHeader); return true; } 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->WriteReply(HTTP_OK, strHex); return true; @@ -177,7 +176,7 @@ static bool rest_headers(HTTPRequest* req, for (const CBlockIndex *pindex : headers) { jsonHeaders.push_back(blockheaderToJSON(pindex)); } - string strJSON = jsonHeaders.write() + "\n"; + std::string strJSON = jsonHeaders.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; @@ -197,10 +196,10 @@ static bool rest_block(HTTPRequest* req, { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; const RetFormat rf = ParseDataFormat(params, strURIPart); - string hashStr = params[0]; + std::string hashStr = params[0]; uint256 hash; if (!ParseHashStr(hashStr, hash)) return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); @@ -225,14 +224,14 @@ static bool rest_block(HTTPRequest* req, switch (rf) { case RF_BINARY: { - string binaryBlock = ssBlock.str(); + std::string binaryBlock = ssBlock.str(); req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteReply(HTTP_OK, binaryBlock); return true; } 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->WriteReply(HTTP_OK, strHex); return true; @@ -240,7 +239,7 @@ static bool rest_block(HTTPRequest* req, case RF_JSON: { UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails); - string strJSON = objBlock.write() + "\n"; + std::string strJSON = objBlock.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; @@ -269,14 +268,14 @@ static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart) { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; const RetFormat rf = ParseDataFormat(params, strURIPart); switch (rf) { case RF_JSON: { UniValue rpcParams(UniValue::VARR); UniValue chainInfoObject = getblockchaininfo(rpcParams, false); - string strJSON = chainInfoObject.write() + "\n"; + std::string strJSON = chainInfoObject.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; @@ -294,14 +293,14 @@ static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart) { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; const RetFormat rf = ParseDataFormat(params, strURIPart); switch (rf) { case RF_JSON: { UniValue mempoolInfoObject = mempoolInfoToJSON(); - string strJSON = mempoolInfoObject.write() + "\n"; + std::string strJSON = mempoolInfoObject.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; @@ -319,14 +318,14 @@ static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPar { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; const RetFormat rf = ParseDataFormat(params, strURIPart); switch (rf) { case RF_JSON: { UniValue mempoolObject = mempoolToJSON(true); - string strJSON = mempoolObject.write() + "\n"; + std::string strJSON = mempoolObject.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; @@ -344,10 +343,10 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart) { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; const RetFormat rf = ParseDataFormat(params, strURIPart); - string hashStr = params[0]; + std::string hashStr = params[0]; uint256 hash; if (!ParseHashStr(hashStr, hash)) return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); @@ -362,14 +361,14 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart) switch (rf) { case RF_BINARY: { - string binaryTx = ssTx.str(); + std::string binaryTx = ssTx.str(); req->WriteHeader("Content-Type", "application/octet-stream"); req->WriteReply(HTTP_OK, binaryTx); return true; } 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->WriteReply(HTTP_OK, strHex); return true; @@ -378,7 +377,7 @@ static bool rest_tx(HTTPRequest* req, const std::string& strURIPart) case RF_JSON: { UniValue objTx(UniValue::VOBJ); TxToJSON(tx, hashBlock, objTx); - string strJSON = objTx.write() + "\n"; + std::string strJSON = objTx.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; @@ -397,10 +396,10 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) { if (!CheckWarmup(req)) return false; - vector params; + std::vector params; enum RetFormat rf = ParseDataFormat(params, strURIPart); - vector uriParts; + std::vector uriParts; if (params.size() > 0 && params[0].length() > 1) { std::string strUriParams = params[0].substr(1); @@ -414,7 +413,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) bool fInputParsed = false; bool fCheckMemPool = false; - vector vOutPoints; + std::vector vOutPoints; // parse/deserialize input // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ... @@ -488,8 +487,8 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, 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-readble string representation) - vector bitmap; - vector outs; + std::vector bitmap; + std::vector outs; std::string bitmapStringRepresentation; boost::dynamic_bitset hits(vOutPoints.size()); { @@ -533,7 +532,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) // use exact same output as mentioned in Bip64 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); 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->WriteReply(HTTP_OK, ssGetUTXOResponseString); @@ -543,7 +542,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) case RF_HEX: { CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); 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->WriteReply(HTTP_OK, strHex); @@ -575,7 +574,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) objGetUTXOResponse.push_back(Pair("utxos", utxos)); // return json string - string strJSON = objGetUTXOResponse.write() + "\n"; + std::string strJSON = objGetUTXOResponse.write() + "\n"; req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strJSON); return true; diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 88ffb9368e32..25d29c1c4ea2 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -28,7 +28,6 @@ #include #include -using namespace std; struct CUpdatedBlock { @@ -141,7 +140,7 @@ UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool tx UniValue zpivObj(UniValue::VOBJ); for (auto denom : libzerocoin::zerocoinDenomList) { - zpivObj.push_back(Pair(to_string(denom), ValueFromAmount(blockindex->mapZerocoinSupply.at(denom) * (denom*COIN)))); + zpivObj.push_back(Pair(std::to_string(denom), ValueFromAmount(blockindex->mapZerocoinSupply.at(denom) * (denom*COIN)))); } zpivObj.push_back(Pair("total", ValueFromAmount(blockindex->GetZerocoinSupply()))); result.push_back(Pair("zPIVsupply", zpivObj)); @@ -152,7 +151,7 @@ UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool tx UniValue getchecksumblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "getchecksumblock\n" "\nFinds the first occurrence of a certain accumulator checksum." "\nReturns the block hash or, if fVerbose=true, the JSON block object\n" @@ -238,7 +237,7 @@ UniValue getchecksumblock(const UniValue& params, bool fHelp) UniValue getblockcount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest block chain.\n" @@ -255,7 +254,7 @@ UniValue getblockcount(const UniValue& params, bool fHelp) UniValue getbestblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest block chain.\n" @@ -330,7 +329,7 @@ UniValue waitforblock(const UniValue& params, bool fHelp) "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" - "1. \"blockhash\" (required, string) Block hash to wait for.\n" + "1. \"blockhash\" (required, std::string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" @@ -414,7 +413,7 @@ UniValue waitforblockheight(const UniValue& params, bool fHelp) UniValue getdifficulty(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" @@ -445,14 +444,14 @@ UniValue mempoolToJSON(bool fVerbose = false) info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); const CTransaction& tx = e.GetTx(); - set setDepends; + std::set setDepends; for (const CTxIn& txin : tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); - for (const string& dep : setDepends) { + for (const std::string& dep : setDepends) { depends.push_back(dep); } @@ -461,7 +460,7 @@ UniValue mempoolToJSON(bool fVerbose = false) } return o; } else { - vector vtxid; + std::vector vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); @@ -475,7 +474,7 @@ UniValue mempoolToJSON(bool fVerbose = false) UniValue getrawmempool(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" @@ -518,7 +517,7 @@ UniValue getrawmempool(const UniValue& params, bool fHelp) UniValue getblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getblockhash index\n" "\nReturns hash of block in best-block-chain at index provided.\n" @@ -544,7 +543,7 @@ UniValue getblockhash(const UniValue& params, bool fHelp) UniValue getblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "getblock \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block .\n" @@ -625,7 +624,7 @@ UniValue getblock(const UniValue& params, bool fHelp) UniValue getblockheader(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n" "If verbose is true, returns an Object with information about block header.\n" @@ -677,7 +676,7 @@ UniValue getblockheader(const UniValue& params, bool fHelp) UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" @@ -717,7 +716,7 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) UniValue gettxout(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "gettxout \"txid\" n ( includemempool )\n" "\nReturns details about an unspent transaction output.\n" @@ -798,7 +797,7 @@ UniValue gettxout(const UniValue& params, bool fHelp) UniValue verifychain(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "verifychain ( numblocks )\n" "\nVerifies blockchain database.\n" @@ -856,7 +855,7 @@ static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* UniValue getblockchaininfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding block chain processing.\n" @@ -921,7 +920,7 @@ struct CompareBlocksByHeight { UniValue getchaintips(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" @@ -979,7 +978,7 @@ UniValue getchaintips(const UniValue& params, bool fHelp) const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); - string status; + std::string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; @@ -1010,7 +1009,7 @@ UniValue getchaintips(const UniValue& params, bool fHelp) UniValue getfeeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getfeeinfo blocks\n" "\nReturns details of transaction fees over the last n blocks.\n" @@ -1060,7 +1059,7 @@ UniValue mempoolInfoToJSON() UniValue getmempoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" @@ -1079,7 +1078,7 @@ UniValue getmempoolinfo(const UniValue& params, bool fHelp) UniValue invalidateblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "invalidateblock \"hash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" @@ -1116,7 +1115,7 @@ UniValue invalidateblock(const UniValue& params, bool fHelp) UniValue reconsiderblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "reconsiderblock \"hash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" @@ -1154,7 +1153,7 @@ UniValue reconsiderblock(const UniValue& params, bool fHelp) UniValue findserial(const UniValue& params, bool fHelp) { if(fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "findserial \"serial\"\n" "\nSearches the zerocoin database for a zerocoin spend transaction that contains the specified serial\n" @@ -1188,7 +1187,7 @@ UniValue findserial(const UniValue& params, bool fHelp) UniValue getaccumulatorvalues(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getaccumulatorvalues \"height\"\n" "\nReturns the accumulator values associated with a block height\n" @@ -1222,7 +1221,7 @@ UniValue getaccumulatorvalues(const UniValue& params, bool fHelp) UniValue getaccumulatorwitness(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "getaccumulatorwitness \"commitmentCoinValue, coinDenomination\"\n" "\nReturns the accumulator witness value associated with the coin\n" @@ -1255,7 +1254,7 @@ UniValue getaccumulatorwitness(const UniValue& params, bool fHelp) //Compute Accumulator and Witness libzerocoin::Accumulator accumulator(zcparams, pubCoin.getDenomination()); libzerocoin::AccumulatorWitness witness(zcparams, accumulator, pubCoin); - string strFailReason = ""; + std::string strFailReason = ""; int nMintsAdded = 0; CZerocoinSpendReceipt receipt; @@ -1308,7 +1307,7 @@ void validaterange(const UniValue& params, int& heightStart, int& heightEnd, int UniValue getmintsinblocks(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 3) - throw runtime_error( + throw std::runtime_error( "getmintsinblocks height range coinDenomination\n" "\nReturns the number of mints of a certain denomination" "\noccurred in blocks [height, height+1, height+2, ..., height+range-1]\n" @@ -1363,7 +1362,7 @@ UniValue getmintsinblocks(const UniValue& params, bool fHelp) { UniValue getserials(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "getserials height range ( fVerbose )\n" "\nLook the inputs of any tx in a range of blocks and returns the serial numbers for any coinspend.\n" @@ -1413,7 +1412,7 @@ UniValue getserials(const UniValue& params, bool fHelp) { spentTo = "Zerocoin Stake"; } else { txnouttype type; - vector addresses; + std::vector addresses; int nRequired; if (!ExtractDestinations(tx.vout[0].scriptPubKey, type, addresses, nRequired)) { spentTo = strprintf("type: %d", GetTxnOutputType(type)); @@ -1479,7 +1478,7 @@ UniValue getserials(const UniValue& params, bool fHelp) { UniValue getblockindexstats(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "getblockindexstats height range ( fFeeOnly )\n" "\nReturns aggregated BlockIndex data for blocks " "\n[height, height+1, height+2, ..., height+range-1]\n" @@ -1542,9 +1541,9 @@ UniValue getblockindexstats(const UniValue& params, bool fHelp) { std::map mapSpendCount; std::map mapPublicSpendCount; for (auto& denom : libzerocoin::zerocoinDenomList) { - mapMintCount.insert(make_pair(denom, 0)); - mapSpendCount.insert(make_pair(denom, 0)); - mapPublicSpendCount.insert(make_pair(denom, 0)); + mapMintCount.insert(std::make_pair(denom, 0)); + mapSpendCount.insert(std::make_pair(denom, 0)); + mapPublicSpendCount.insert(std::make_pair(denom, 0)); } CBlockIndex* pindex = nullptr; diff --git a/src/rpc/budget.cpp b/src/rpc/budget.cpp index 0bcd6524349c..cec1531996f4 100644 --- a/src/rpc/budget.cpp +++ b/src/rpc/budget.cpp @@ -18,7 +18,6 @@ #include #include -using namespace std; void budgetToJSON(CBudgetProposal* pbudgetProposal, UniValue& bObj) { @@ -55,7 +54,7 @@ UniValue preparebudget(const UniValue& params, bool fHelp) CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 6) - throw runtime_error( + throw std::runtime_error( "preparebudget \"proposal-name\" \"url\" payment-count block-start \"pivx-address\" monthy-payment\n" "\nPrepare proposal for network by signing and creating tx\n" @@ -80,15 +79,15 @@ UniValue preparebudget(const UniValue& params, bool fHelp) std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) - throw runtime_error("Invalid proposal name, limit of 20 characters."); + throw std::runtime_error("Invalid proposal name, limit of 20 characters."); std::string strURL = SanitizeString(params[1].get_str()); if (strURL.size() > 64) - throw runtime_error("Invalid url, limit of 64 characters."); + throw std::runtime_error("Invalid url, limit of 64 characters."); int nPaymentCount = params[2].get_int(); if (nPaymentCount < 1) - throw runtime_error("Invalid payment count, must be more than zero."); + throw std::runtime_error("Invalid payment count, must be more than zero."); // Start must be in the next budget cycle if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - pindexPrev->nHeight % Params().GetBudgetCycleBlocks() + Params().GetBudgetCycleBlocks(); @@ -96,16 +95,16 @@ UniValue preparebudget(const UniValue& params, bool fHelp) int nBlockStart = params[3].get_int(); if (nBlockStart % Params().GetBudgetCycleBlocks() != 0) { int nNext = pindexPrev->nHeight - pindexPrev->nHeight % Params().GetBudgetCycleBlocks() + Params().GetBudgetCycleBlocks(); - throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); + throw std::runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); } int nBlockEnd = nBlockStart + Params().GetBudgetCycleBlocks() * nPaymentCount; // End must be AFTER current cycle if (nBlockStart < nBlockMin) - throw runtime_error("Invalid block start, must be more than current height."); + throw std::runtime_error("Invalid block start, must be more than current height."); if (nBlockEnd < pindexPrev->nHeight) - throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); + throw std::runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); CBitcoinAddress address(params[4].get_str()); if (!address.IsValid()) @@ -122,7 +121,7 @@ UniValue preparebudget(const UniValue& params, bool fHelp) std::string strError = ""; if (!budgetProposalBroadcast.IsValid(strError, false)) - throw runtime_error("Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError); + throw std::runtime_error("Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError); bool useIX = false; //true; // if (params.size() > 7) { @@ -133,7 +132,7 @@ UniValue preparebudget(const UniValue& params, bool fHelp) CWalletTx wtx; if (!pwalletMain->GetBudgetSystemCollateralTX(wtx, budgetProposalBroadcast.GetHash(), useIX)) { // 50 PIV collateral for proposal - throw runtime_error("Error making collateral transaction for proposal. Please check your wallet balance."); + throw std::runtime_error("Error making collateral transaction for proposal. Please check your wallet balance."); } // make our change address @@ -150,7 +149,7 @@ UniValue submitbudget(const UniValue& params, bool fHelp) CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 7) - throw runtime_error( + throw std::runtime_error( "submitbudget \"proposal-name\" \"url\" payment-count block-start \"pivx-address\" monthy-payment \"fee-tx\"\n" "\nSubmit proposal to the network\n" @@ -175,15 +174,15 @@ UniValue submitbudget(const UniValue& params, bool fHelp) std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) - throw runtime_error("Invalid proposal name, limit of 20 characters."); + throw std::runtime_error("Invalid proposal name, limit of 20 characters."); std::string strURL = SanitizeString(params[1].get_str()); if (strURL.size() > 64) - throw runtime_error("Invalid url, limit of 64 characters."); + throw std::runtime_error("Invalid url, limit of 64 characters."); int nPaymentCount = params[2].get_int(); if (nPaymentCount < 1) - throw runtime_error("Invalid payment count, must be more than zero."); + throw std::runtime_error("Invalid payment count, must be more than zero."); // Start must be in the next budget cycle if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - pindexPrev->nHeight % Params().GetBudgetCycleBlocks() + Params().GetBudgetCycleBlocks(); @@ -191,16 +190,16 @@ UniValue submitbudget(const UniValue& params, bool fHelp) int nBlockStart = params[3].get_int(); if (nBlockStart % Params().GetBudgetCycleBlocks() != 0) { int nNext = pindexPrev->nHeight - pindexPrev->nHeight % Params().GetBudgetCycleBlocks() + Params().GetBudgetCycleBlocks(); - throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); + throw std::runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); } int nBlockEnd = nBlockStart + (Params().GetBudgetCycleBlocks() * nPaymentCount); // End must be AFTER current cycle if (nBlockStart < nBlockMin) - throw runtime_error("Invalid block start, must be more than current height."); + throw std::runtime_error("Invalid block start, must be more than current height."); if (nBlockEnd < pindexPrev->nHeight) - throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); + throw std::runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); CBitcoinAddress address(params[4].get_str()); if (!address.IsValid()) @@ -217,23 +216,23 @@ UniValue submitbudget(const UniValue& params, bool fHelp) std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(hash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { - throw runtime_error("Proposal FeeTX is not valid - " + hash.ToString() + " - " + strError); + throw std::runtime_error("Proposal FeeTX is not valid - " + hash.ToString() + " - " + strError); } if (!masternodeSync.IsBlockchainSynced()) { - throw runtime_error("Must wait for client to sync with masternode network. Try again in a minute or so."); + throw std::runtime_error("Must wait for client to sync with masternode network. Try again in a minute or so."); } // if(!budgetProposalBroadcast.IsValid(strError)){ // return "Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError; // } - budget.mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); + budget.mapSeenMasternodeBudgetProposals.insert(std::make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); budgetProposalBroadcast.Relay(); if(budget.AddProposal(budgetProposalBroadcast)) { return budgetProposalBroadcast.GetHash().ToString(); } - throw runtime_error("Invalid proposal, see debug.log for details."); + throw std::runtime_error("Invalid proposal, see debug.log for details."); } UniValue mnbudgetvote(const UniValue& params, bool fHelp) @@ -250,7 +249,7 @@ UniValue mnbudgetvote(const UniValue& params, bool fHelp) if (fHelp || (params.size() == 3 && (strCommand != "local" && strCommand != "many")) || (params.size() == 4 && strCommand != "alias") || params.size() > 4 || params.size() < 3) - throw runtime_error( + throw std::runtime_error( "mnbudgetvote \"local|many|alias\" \"votehash\" \"yes|no\" ( \"alias\" )\n" "\nVote on a budget proposal\n" @@ -330,7 +329,7 @@ UniValue mnbudgetvote(const UniValue& params, bool fHelp) std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { success++; - budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenMasternodeBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "success")); @@ -396,7 +395,7 @@ UniValue mnbudgetvote(const UniValue& params, bool fHelp) std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { - budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenMasternodeBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); @@ -471,7 +470,7 @@ UniValue mnbudgetvote(const UniValue& params, bool fHelp) std::string strError = ""; if(budget.UpdateProposal(vote, NULL, strError)) { - budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenMasternodeBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); @@ -500,7 +499,7 @@ UniValue mnbudgetvote(const UniValue& params, bool fHelp) UniValue getbudgetvotes(const UniValue& params, bool fHelp) { if (params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getbudgetvotes \"proposal-name\"\n" "\nPrint vote information for a budget proposal\n" @@ -528,7 +527,7 @@ UniValue getbudgetvotes(const UniValue& params, bool fHelp) CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName); - if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name"); + if (pbudgetProposal == NULL) throw std::runtime_error("Unknown proposal name"); std::map::iterator it = pbudgetProposal->mapVotes.begin(); while (it != pbudgetProposal->mapVotes.end()) { @@ -550,7 +549,7 @@ UniValue getbudgetvotes(const UniValue& params, bool fHelp) UniValue getnextsuperblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getnextsuperblock\n" "\nPrint the next super block height\n" @@ -570,7 +569,7 @@ UniValue getnextsuperblock(const UniValue& params, bool fHelp) UniValue getbudgetprojection(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getbudgetprojection\n" "\nShow the projection of which proposals will be paid the next cycle\n" @@ -631,7 +630,7 @@ UniValue getbudgetprojection(const UniValue& params, bool fHelp) UniValue getbudgetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "getbudgetinfo ( \"proposal\" )\n" "\nShow current masternode budgets\n" @@ -673,7 +672,7 @@ UniValue getbudgetinfo(const UniValue& params, bool fHelp) if (params.size() == 1) { std::string strProposalName = SanitizeString(params[0].get_str()); CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName); - if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name"); + if (pbudgetProposal == NULL) throw std::runtime_error("Unknown proposal name"); UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); ret.push_back(bObj); @@ -696,7 +695,7 @@ UniValue getbudgetinfo(const UniValue& params, bool fHelp) UniValue mnbudgetrawvote(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 6) - throw runtime_error( + throw std::runtime_error( "mnbudgetrawvote \"masternode-tx-hash\" masternode-tx-index \"proposal-hash\" yes|no time \"vote-sig\"\n" "\nCompile and relay a proposal vote with provided external signature instead of signing vote internally\n" @@ -729,7 +728,7 @@ UniValue mnbudgetrawvote(const UniValue& params, bool fHelp) int64_t nTime = params[4].get_int64(); std::string strSig = params[5].get_str(); bool fInvalid = false; - vector vchSig = DecodeBase64(strSig.c_str(), &fInvalid); + std::vector vchSig = DecodeBase64(strSig.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); @@ -749,7 +748,7 @@ UniValue mnbudgetrawvote(const UniValue& params, bool fHelp) std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { - budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenMasternodeBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); return "Voted successfully"; } else { @@ -759,13 +758,13 @@ UniValue mnbudgetrawvote(const UniValue& params, bool fHelp) UniValue mnfinalbudget(const UniValue& params, bool fHelp) { - string strCommand; + std::string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "suggest" && strCommand != "vote-many" && strCommand != "vote" && strCommand != "show" && strCommand != "getvotes")) - throw runtime_error( + throw std::runtime_error( "mnfinalbudget \"command\"... ( \"passphrase\" )\n" "\nVote or show current budgets\n" @@ -777,7 +776,7 @@ UniValue mnfinalbudget(const UniValue& params, bool fHelp) if (strCommand == "vote-many") { if (params.size() != 2) - throw runtime_error("Correct usage is 'mnfinalbudget vote-many BUDGET_HASH'"); + throw std::runtime_error("Correct usage is 'mnfinalbudget vote-many BUDGET_HASH'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); @@ -828,7 +827,7 @@ UniValue mnfinalbudget(const UniValue& params, bool fHelp) std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { - budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenFinalizedBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("result", "success")); @@ -849,7 +848,7 @@ UniValue mnfinalbudget(const UniValue& params, bool fHelp) if (strCommand == "vote") { if (params.size() != 2) - throw runtime_error("Correct usage is 'mnfinalbudget vote BUDGET_HASH'"); + throw std::runtime_error("Correct usage is 'mnfinalbudget vote BUDGET_HASH'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); @@ -873,7 +872,7 @@ UniValue mnfinalbudget(const UniValue& params, bool fHelp) std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { - budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); + budget.mapSeenFinalizedBudgetVotes.insert(std::make_pair(vote.GetHash(), vote)); vote.Relay(); return "success"; } else { @@ -907,7 +906,7 @@ UniValue mnfinalbudget(const UniValue& params, bool fHelp) if (strCommand == "getvotes") { if (params.size() != 2) - throw runtime_error("Correct usage is 'mnbudget getvotes budget-hash'"); + throw std::runtime_error("Correct usage is 'mnbudget getvotes budget-hash'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); @@ -939,7 +938,7 @@ UniValue mnfinalbudget(const UniValue& params, bool fHelp) UniValue checkbudgets(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "checkbudgets\n" "\nInitiates a buddget check cycle manually\n" diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index db61de9edb2e..8122438ed9aa 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -17,7 +17,6 @@ #include // for to_lower() #include -using namespace std; class CRPCConvertParam { @@ -199,7 +198,7 @@ UniValue ParseNonRFCJSONValue(const std::string& strVal) UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) - throw runtime_error(string("Error parsing JSON:")+strVal); + throw std::runtime_error(std::string("Error parsing JSON:")+strVal); return jVal[0]; } diff --git a/src/rpc/masternode.cpp b/src/rpc/masternode.cpp index 77035cd97575..0b3d894d1573 100644 --- a/src/rpc/masternode.cpp +++ b/src/rpc/masternode.cpp @@ -22,7 +22,7 @@ UniValue getpoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getpoolinfo\n" "\nReturns anonymous pool-related information\n" @@ -52,7 +52,7 @@ UniValue listmasternodes(const UniValue& params, bool fHelp) if (params.size() == 1) strFilter = params[0].get_str(); if (fHelp || (params.size() > 1)) - throw runtime_error( + throw std::runtime_error( "listmasternodes ( \"filter\" )\n" "\nGet a ranked list of masternodes\n" @@ -87,7 +87,7 @@ UniValue listmasternodes(const UniValue& params, bool fHelp) if(!pindex) return 0; nHeight = pindex->nHeight; } - std::vector > vMasternodeRanks = mnodeman.GetMasternodeRanks(nHeight); + std::vector > vMasternodeRanks = mnodeman.GetMasternodeRanks(nHeight); for (PAIRTYPE(int, CMasternode) & s : vMasternodeRanks) { UniValue obj(UniValue::VOBJ); std::string strVin = s.second.vin.prevout.ToStringShort(); @@ -97,9 +97,9 @@ UniValue listmasternodes(const UniValue& params, bool fHelp) CMasternode* mn = mnodeman.Find(s.second.vin); if (mn != NULL) { - if (strFilter != "" && strTxHash.find(strFilter) == string::npos && - mn->Status().find(strFilter) == string::npos && - CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString().find(strFilter) == string::npos) continue; + if (strFilter != "" && strTxHash.find(strFilter) == std::string::npos && + mn->Status().find(strFilter) == std::string::npos && + CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString().find(strFilter) == std::string::npos) continue; std::string strStatus = mn->Status(); std::string strHost; @@ -130,7 +130,7 @@ UniValue listmasternodes(const UniValue& params, bool fHelp) UniValue masternodeconnect(const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 1)) - throw runtime_error( + throw std::runtime_error( "masternodeconnect \"address\"\n" "\nAttempts to connect to specified masternode address\n" @@ -149,14 +149,14 @@ UniValue masternodeconnect(const UniValue& params, bool fHelp) pnode->Release(); return NullUniValue; } else { - throw runtime_error("error connecting\n"); + throw std::runtime_error("error connecting\n"); } } UniValue getmasternodecount (const UniValue& params, bool fHelp) { if (fHelp || (params.size() > 0)) - throw runtime_error( + throw std::runtime_error( "getmasternodecount\n" "\nGet masternode count values\n" @@ -196,7 +196,7 @@ UniValue getmasternodecount (const UniValue& params, bool fHelp) UniValue masternodecurrent (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) - throw runtime_error( + throw std::runtime_error( "masternodecurrent\n" "\nGet current masternode winner\n" @@ -224,13 +224,13 @@ UniValue masternodecurrent (const UniValue& params, bool fHelp) return obj; } - throw runtime_error("unknown"); + throw std::runtime_error("unknown"); } UniValue masternodedebug (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) - throw runtime_error( + throw std::runtime_error( "masternodedebug\n" "\nPrint masternode status\n" @@ -247,7 +247,7 @@ UniValue masternodedebug (const UniValue& params, bool fHelp) CPubKey pubkey; CKey key; if (!activeMasternode.GetMasterNodeVin(vin, pubkey, key)) - throw runtime_error("Missing masternode input, please look at the documentation for instructions on masternode creation\n"); + throw std::runtime_error("Missing masternode input, please look at the documentation for instructions on masternode creation\n"); else return activeMasternode.GetStatus(); } @@ -270,7 +270,7 @@ UniValue startmasternode (const UniValue& params, bool fHelp) if (fHelp || params.size() < 2 || params.size() > 3 || (params.size() == 2 && (strCommand != "local" && strCommand != "all" && strCommand != "many" && strCommand != "missing" && strCommand != "disabled")) || (params.size() == 3 && strCommand != "alias")) - throw runtime_error( + throw std::runtime_error( "startmasternode \"local|all|many|missing|disabled|alias\" lockwallet ( \"alias\" )\n" "\nAttempts to start one or more masternode(s)\n" @@ -303,7 +303,7 @@ UniValue startmasternode (const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); if (strCommand == "local") { - if (!fMasterNode) throw runtime_error("you must set masternode=1 in the configuration\n"); + if (!fMasterNode) throw std::runtime_error("you must set masternode=1 in the configuration\n"); if (activeMasternode.status != ACTIVE_MASTERNODE_STARTED) { activeMasternode.status = ACTIVE_MASTERNODE_INITIAL; // TODO: consider better way @@ -319,7 +319,7 @@ UniValue startmasternode (const UniValue& params, bool fHelp) if ((strCommand == "missing" || strCommand == "disabled") && (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_LIST || masternodeSync.RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED)) { - throw runtime_error("You can't use this command until masternode list is synced\n"); + throw std::runtime_error("You can't use this command until masternode list is synced\n"); } std::vector mnEntries; @@ -426,7 +426,7 @@ UniValue startmasternode (const UniValue& params, bool fHelp) UniValue createmasternodekey (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) - throw runtime_error( + throw std::runtime_error( "createmasternodekey\n" "\nCreate a new masternode private key\n" @@ -445,7 +445,7 @@ UniValue createmasternodekey (const UniValue& params, bool fHelp) UniValue getmasternodeoutputs (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) - throw runtime_error( + throw std::runtime_error( "getmasternodeoutputs\n" "\nPrint all masternode transaction outputs\n" @@ -462,7 +462,7 @@ UniValue getmasternodeoutputs (const UniValue& params, bool fHelp) HelpExampleCli("getmasternodeoutputs", "") + HelpExampleRpc("getmasternodeoutputs", "")); // Find possible candidates - vector possibleCoins = activeMasternode.SelectCoinsMasternode(); + std::vector possibleCoins = activeMasternode.SelectCoinsMasternode(); UniValue ret(UniValue::VARR); for (COutput& out : possibleCoins) { @@ -482,7 +482,7 @@ UniValue listmasternodeconf (const UniValue& params, bool fHelp) if (params.size() == 1) strFilter = params[0].get_str(); if (fHelp || (params.size() > 1)) - throw runtime_error( + throw std::runtime_error( "listmasternodeconf ( \"filter\" )\n" "\nPrint masternode.conf in JSON format\n" @@ -519,10 +519,10 @@ UniValue listmasternodeconf (const UniValue& params, bool fHelp) std::string strStatus = pmn ? pmn->Status() : "MISSING"; - if (strFilter != "" && mne.getAlias().find(strFilter) == string::npos && - mne.getIp().find(strFilter) == string::npos && - mne.getTxHash().find(strFilter) == string::npos && - strStatus.find(strFilter) == string::npos) continue; + if (strFilter != "" && mne.getAlias().find(strFilter) == std::string::npos && + mne.getIp().find(strFilter) == std::string::npos && + mne.getTxHash().find(strFilter) == std::string::npos && + strStatus.find(strFilter) == std::string::npos) continue; UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("alias", mne.getAlias())); @@ -540,7 +540,7 @@ UniValue listmasternodeconf (const UniValue& params, bool fHelp) UniValue getmasternodestatus (const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 0)) - throw runtime_error( + throw std::runtime_error( "getmasternodestatus\n" "\nPrint masternode status\n" @@ -557,7 +557,7 @@ UniValue getmasternodestatus (const UniValue& params, bool fHelp) "\nExamples:\n" + HelpExampleCli("getmasternodestatus", "") + HelpExampleRpc("getmasternodestatus", "")); - if (!fMasterNode) throw runtime_error("This is not a masternode"); + if (!fMasterNode) throw std::runtime_error("This is not a masternode"); CMasternode* pmn = mnodeman.Find(activeMasternode.vin); @@ -571,14 +571,14 @@ UniValue getmasternodestatus (const UniValue& params, bool fHelp) mnObj.push_back(Pair("message", activeMasternode.GetStatus())); return mnObj; } - throw runtime_error("Masternode not found in the list of available masternodes. Current status: " + throw std::runtime_error("Masternode not found in the list of available masternodes. Current status: " + activeMasternode.GetStatus()); } UniValue getmasternodewinners (const UniValue& params, bool fHelp) { if (fHelp || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "getmasternodewinners ( blocks \"filter\" )\n" "\nPrint the masternode winners for the last n blocks\n" @@ -646,7 +646,7 @@ UniValue getmasternodewinners (const UniValue& params, bool fHelp) UniValue winner(UniValue::VARR); boost::char_separator sep(","); boost::tokenizer< boost::char_separator > tokens(strPayment, sep); - for (const string& t : tokens) { + for (const std::string& t : tokens) { UniValue addr(UniValue::VOBJ); std::size_t pos = t.find(":"); std::string strAddress = t.substr(0,pos); @@ -680,7 +680,7 @@ UniValue getmasternodewinners (const UniValue& params, bool fHelp) UniValue getmasternodescores (const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "getmasternodescores ( blocks )\n" "\nPrint list of winning masternode by score\n" @@ -702,7 +702,7 @@ UniValue getmasternodescores (const UniValue& params, bool fHelp) try { nLast = std::stoi(params[0].get_str()); } catch (const std::invalid_argument&) { - throw runtime_error("Exception on param 2"); + throw std::runtime_error("Exception on param 2"); } } UniValue obj(UniValue::VOBJ); @@ -730,7 +730,7 @@ bool DecodeHexMnb(CMasternodeBroadcast& mnb, std::string strHexMnb) { if (!IsHex(strHexMnb)) return false; - vector mnbData(ParseHex(strHexMnb)); + std::vector mnbData(ParseHex(strHexMnb)); CDataStream ssData(mnbData, SER_NETWORK, PROTOCOL_VERSION); try { ssData >> mnb; @@ -743,11 +743,11 @@ bool DecodeHexMnb(CMasternodeBroadcast& mnb, std::string strHexMnb) { } UniValue createmasternodebroadcast(const UniValue& params, bool fHelp) { - string strCommand; + std::string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "alias" && strCommand != "all") || (strCommand == "alias" && params.size() < 2)) - throw runtime_error( + throw std::runtime_error( "createmasternodebroadcast \"command\" ( \"alias\")\n" "\nCreates a masternode broadcast message for one or all masternodes configured in masternode.conf\n" + HelpRequiringPassphrase() + "\n" @@ -875,7 +875,7 @@ UniValue createmasternodebroadcast(const UniValue& params, bool fHelp) UniValue decodemasternodebroadcast(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "decodemasternodebroadcast \"hexstring\"\n" "\nCommand to decode masternode broadcast messages\n" @@ -935,7 +935,7 @@ UniValue decodemasternodebroadcast(const UniValue& params, bool fHelp) UniValue relaymasternodebroadcast(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "relaymasternodebroadcast \"hexstring\"\n" "\nCommand to relay masternode broadcast messages\n" diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index e625bc4c0fc3..c7a449cc33d7 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -28,7 +28,6 @@ #include -using namespace std; /** * Return average network hashes per second based on the last 'lookup' blocks, @@ -76,7 +75,7 @@ UniValue GetNetworkHashPS(int lookup, int height) UniValue getnetworkhashps(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "getnetworkhashps ( blocks height )\n" "\nReturns the estimated network hashes per second based on the last n blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" @@ -99,7 +98,7 @@ UniValue getnetworkhashps(const UniValue& params, bool fHelp) UniValue getgenerate(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getgenerate\n" "\nReturn if the server is set to generate coins or not. The default is false.\n" "It is set with the command line argument -gen (or pivx.conf setting gen)\n" @@ -118,7 +117,7 @@ UniValue getgenerate(const UniValue& params, bool fHelp) UniValue generate(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "generate numblocks\n" "\nMine blocks immediately (before the RPC call returns)\n" "\nNote: this function can only be used on the regtest network\n" @@ -155,7 +154,7 @@ UniValue generate(const UniValue& params, bool fHelp) while (nHeight < nHeightEnd) { - unique_ptr pblocktemplate(CreateNewBlockWithKey(reservekey, pwalletMain, fPoS)); + std::unique_ptr pblocktemplate(CreateNewBlockWithKey(reservekey, pwalletMain, fPoS)); if (!pblocktemplate.get()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); CBlock *pblock = &pblocktemplate->block; @@ -184,7 +183,7 @@ UniValue generate(const UniValue& params, bool fHelp) UniValue setgenerate(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "setgenerate generate ( genproclimit )\n" "\nSet 'generate' true or false to turn generation on or off.\n" "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n" @@ -228,7 +227,7 @@ UniValue setgenerate(const UniValue& params, bool fHelp) UniValue gethashespersec(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "gethashespersec\n" "\nReturns a recent hashes per second performance measurement while generating.\n" "See the getgenerate and setgenerate calls to turn generation on and off.\n" @@ -249,7 +248,7 @@ UniValue gethashespersec(const UniValue& params, bool fHelp) UniValue getmininginfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getmininginfo\n" "\nReturns a json object containing mining-related information." @@ -296,7 +295,7 @@ UniValue getmininginfo(const UniValue& params, bool fHelp) UniValue prioritisetransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 3) - throw runtime_error( + throw std::runtime_error( "prioritisetransaction \n" "Accepts the transaction into mined blocks at a higher (or lower) priority\n" @@ -346,7 +345,7 @@ static UniValue BIP22ValidationResult(const CValidationState& state) UniValue getblocktemplate(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "getblocktemplate ( \"jsonrequestobject\" )\n" "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n" "It returns data needed to construct a block to work on.\n" @@ -544,7 +543,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp) UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal"); UniValue transactions(UniValue::VARR); - map setTxIndex; + std::map setTxIndex; int i = 0; for (CTransaction& tx : pblock->vtx) { uint256 txHash = tx.GetHash(); @@ -646,7 +645,7 @@ class submitblock_StateCatcher : public CValidationInterface UniValue submitblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n" "\nAttempts to submit new block to network.\n" "The 'jsonparametersobject' parameter is currently ignored.\n" @@ -709,7 +708,7 @@ UniValue submitblock(const UniValue& params, bool fHelp) UniValue estimatefee(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "estimatefee nblocks\n" "\nEstimates the approximate fee per kilobyte\n" "needed for a transaction to begin confirmation\n" @@ -743,7 +742,7 @@ UniValue estimatefee(const UniValue& params, bool fHelp) UniValue estimatepriority(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "estimatepriority nblocks\n" "\nEstimates the approximate priority\n" "a zero-fee transaction needs to begin confirmation\n" diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index af2cf2cbd482..4f419c21958a 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -27,9 +27,6 @@ #include -using namespace boost; -using namespace boost::assign; -using namespace std; /** * @note Do not add or change anything in the information returned by this @@ -47,7 +44,7 @@ using namespace std; UniValue getinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getinfo\n" "\nReturns an object containing various state info.\n" @@ -133,7 +130,7 @@ UniValue getinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("timeoffset", GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); - obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string()))); + obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC())); @@ -146,7 +143,7 @@ UniValue getinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("moneysupply",ValueFromAmount(chainActive.Tip()->nMoneySupply))); UniValue zpivObj(UniValue::VOBJ); for (auto denom : libzerocoin::zerocoinDenomList) { - zpivObj.push_back(Pair(to_string(denom), ValueFromAmount(chainActive.Tip()->mapZerocoinSupply.at(denom) * (denom*COIN)))); + zpivObj.push_back(Pair(std::to_string(denom), ValueFromAmount(chainActive.Tip()->mapZerocoinSupply.at(denom) * (denom*COIN)))); } zpivObj.push_back(Pair("total", ValueFromAmount(chainActive.Tip()->GetZerocoinSupply()))); obj.push_back(Pair("zPIVsupply", zpivObj)); @@ -178,7 +175,7 @@ UniValue mnsync(const UniValue& params, bool fHelp) strMode = params[0].get_str(); if (fHelp || params.size() != 1 || (strMode != "status" && strMode != "reset")) { - throw runtime_error( + throw std::runtime_error( "mnsync \"status|reset\"\n" "\nReturns the sync status or resets sync.\n" @@ -323,7 +320,7 @@ UniValue spork(const UniValue& params, bool fHelp) } } - throw runtime_error( + throw std::runtime_error( "spork \"name\" ( value )\n" "\nReturn spork values or their active state.\n" @@ -354,7 +351,7 @@ UniValue spork(const UniValue& params, bool fHelp) UniValue validateaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "validateaddress \"pivxaddress\"\n" "\nReturn information about the given pivx address.\n" @@ -391,7 +388,7 @@ UniValue validateaddress(const UniValue& params, bool fHelp) ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); - string currentAddress = address.ToString(); + std::string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); CScript scriptPubKey = GetScriptForDestination(dest); ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); @@ -419,14 +416,14 @@ CScript _createmultisig_redeemScript(const UniValue& params) // Gather public keys if (nRequired < 1) - throw runtime_error("a multisignature address must require at least one key to redeem"); + throw std::runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) - throw runtime_error( + throw std::runtime_error( strprintf("not enough keys supplied " "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired)); if (keys.size() > 16) - throw runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number"); + throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number"); std::vector pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { @@ -437,14 +434,14 @@ CScript _createmultisig_redeemScript(const UniValue& params) if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) - throw runtime_error( + throw std::runtime_error( strprintf("%s does not refer to a key", ks)); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) - throw runtime_error( + throw std::runtime_error( strprintf("no full public key for address %s", ks)); if (!vchPubKey.IsFullyValid()) - throw runtime_error(" Invalid public key: " + ks); + throw std::runtime_error(" Invalid public key: " + ks); pubkeys[i] = vchPubKey; } @@ -454,16 +451,16 @@ CScript _createmultisig_redeemScript(const UniValue& params) if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) - throw runtime_error(" Invalid public key: " + ks); + throw std::runtime_error(" Invalid public key: " + ks); pubkeys[i] = vchPubKey; } else { - throw runtime_error(" Invalid public key: " + ks); + throw std::runtime_error(" Invalid public key: " + ks); } } CScript result = GetScriptForMultisig(nRequired, pubkeys); if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) - throw runtime_error( + throw std::runtime_error( strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE)); return result; @@ -472,7 +469,7 @@ CScript _createmultisig_redeemScript(const UniValue& params) UniValue createmultisig(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "createmultisig nrequired [\"key\",...]\n" "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n" @@ -512,7 +509,7 @@ UniValue createmultisig(const UniValue& params, bool fHelp) UniValue verifymessage(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 3) - throw runtime_error( + throw std::runtime_error( "verifymessage \"pivxaddress\" \"signature\" \"message\"\n" "\nVerify a signed message\n" @@ -536,9 +533,9 @@ UniValue verifymessage(const UniValue& params, bool fHelp) LOCK(cs_main); - string strAddress = params[0].get_str(); - string strSign = params[1].get_str(); - string strMessage = params[2].get_str(); + std::string strAddress = params[0].get_str(); + std::string strSign = params[1].get_str(); + std::string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) @@ -549,7 +546,7 @@ UniValue verifymessage(const UniValue& params, bool fHelp) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; - vector vchSig = DecodeBase64(strSign.c_str(), &fInvalid); + std::vector vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); @@ -568,7 +565,7 @@ UniValue verifymessage(const UniValue& params, bool fHelp) UniValue setmocktime(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "setmocktime timestamp\n" "\nSet the local time to given timestamp (-regtest only)\n" @@ -577,7 +574,7 @@ UniValue setmocktime(const UniValue& params, bool fHelp) " Pass 0 to go back to using the system time."); if (!Params().MineBlocksOnDemand()) - throw runtime_error("setmocktime for regression testing (-regtest mode) only"); + throw std::runtime_error("setmocktime for regression testing (-regtest mode) only"); LOCK(cs_main); @@ -591,7 +588,7 @@ UniValue setmocktime(const UniValue& params, bool fHelp) UniValue getstakingstatus(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getstakingstatus\n" "\nReturns an object containing various staking information.\n" diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp index b17b9e63a2cc..59cb0232be5a 100644 --- a/src/rpc/net.cpp +++ b/src/rpc/net.cpp @@ -20,12 +20,11 @@ #include -using namespace std; UniValue getconnectioncount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getconnectioncount\n" "\nReturns the number of connections to other nodes.\n" @@ -43,7 +42,7 @@ UniValue getconnectioncount(const UniValue& params, bool fHelp) UniValue ping(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "ping\n" "\nRequests that a ping be sent to all other nodes, to measure ping time.\n" "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n" @@ -78,7 +77,7 @@ static void CopyNodeStats(std::vector& vstats) UniValue getpeerinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" @@ -117,7 +116,7 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp) LOCK(cs_main); - vector vstats; + std::vector vstats; CopyNodeStats(vstats); UniValue ret(UniValue::VARR); @@ -167,12 +166,12 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp) UniValue addnode(const UniValue& params, bool fHelp) { - string strCommand; + std::string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) - throw runtime_error( + throw std::runtime_error( "addnode \"node\" \"add|remove|onetry\"\n" "\nAttempts add or remove a node from the addnode list.\n" "Or try a connection to a node once.\n" @@ -184,7 +183,7 @@ UniValue addnode(const UniValue& params, bool fHelp) "\nExamples:\n" + HelpExampleCli("addnode", "\"192.168.0.6:51472\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:51472\", \"onetry\"")); - string strNode = params[0].get_str(); + std::string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; @@ -193,7 +192,7 @@ UniValue addnode(const UniValue& params, bool fHelp) } LOCK(cs_vAddedNodes); - vector::iterator it = vAddedNodes.begin(); + std::vector::iterator it = vAddedNodes.begin(); for (; it != vAddedNodes.end(); it++) if (strNode == *it) break; @@ -214,7 +213,7 @@ UniValue addnode(const UniValue& params, bool fHelp) UniValue disconnectnode(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "disconnectnode \"node\" \n" "\nImmediately disconnects from the specified node.\n" @@ -238,7 +237,7 @@ UniValue disconnectnode(const UniValue& params, bool fHelp) UniValue getaddednodeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "getaddednodeinfo dns ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" @@ -270,15 +269,15 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) bool fDns = params[0].get_bool(); - list laddedNodes(0); + std::list laddedNodes(0); if (params.size() == 1) { LOCK(cs_vAddedNodes); - for (string& strAddNode : vAddedNodes) + for (std::string& strAddNode : vAddedNodes) laddedNodes.push_back(strAddNode); } else { - string strNode = params[1].get_str(); + std::string strNode = params[1].get_str(); LOCK(cs_vAddedNodes); - for (string& strAddNode : vAddedNodes) + for (std::string& strAddNode : vAddedNodes) if (strAddNode == strNode) { laddedNodes.push_back(strAddNode); break; @@ -289,7 +288,7 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) UniValue ret(UniValue::VARR); if (!fDns) { - for (string& strAddNode : laddedNodes) { + for (std::string& strAddNode : laddedNodes) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", strAddNode)); ret.push_back(obj); @@ -297,11 +296,11 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) return ret; } - list > > laddedAddreses(0); - for (string& strAddNode : laddedNodes) { - vector vservNode(0); + std::list > > laddedAddreses(0); + for (std::string& strAddNode : laddedNodes) { + std::vector vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) - laddedAddreses.push_back(make_pair(strAddNode, vservNode)); + laddedAddreses.push_back(std::make_pair(strAddNode, vservNode)); else { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", strAddNode)); @@ -312,7 +311,7 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) } LOCK(cs_vNodes); - for (list > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) { + for (std::list > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", it->first)); @@ -344,7 +343,7 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp) UniValue getnettotals(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 0) - throw runtime_error( + throw std::runtime_error( "getnettotals\n" "\nReturns information about network traffic, including bytes in, bytes out,\n" "and current time.\n" @@ -379,7 +378,7 @@ static UniValue GetNetworksInfo() obj.push_back(Pair("name", GetNetworkName(network))); obj.push_back(Pair("limited", IsLimited(network))); obj.push_back(Pair("reachable", IsReachable(network))); - obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())); + obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())); obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials)); networks.push_back(obj); } @@ -389,7 +388,7 @@ static UniValue GetNetworksInfo() UniValue getnetworkinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getnetworkinfo\n" "\nReturns an object containing various state info regarding P2P networking.\n" @@ -452,12 +451,12 @@ UniValue getnetworkinfo(const UniValue& params, bool fHelp) UniValue setban(const UniValue& params, bool fHelp) { - string strCommand; + std::string strCommand; if (params.size() >= 2) strCommand = params[1].get_str(); if (fHelp || params.size() < 2 || (strCommand != "add" && strCommand != "remove")) - throw runtime_error( + throw std::runtime_error( "setban \"ip(/netmask)\" \"add|remove\" (bantime) (absolute)\n" "\nAttempts add or remove a IP/Subnet from the banned list.\n" @@ -476,7 +475,7 @@ UniValue setban(const UniValue& params, bool fHelp) CNetAddr netAddr; bool isSubnet = false; - if (params[0].get_str().find("/") != string::npos) + if (params[0].get_str().find("/") != std::string::npos) isSubnet = true; if (!isSubnet) @@ -521,7 +520,7 @@ UniValue setban(const UniValue& params, bool fHelp) UniValue listbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "listbanned\n" "\nList all banned IPs/Subnets.\n" @@ -562,7 +561,7 @@ UniValue listbanned(const UniValue& params, bool fHelp) UniValue clearbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "clearbanned\n" "\nClear all banned IPs.\n" diff --git a/src/rpc/protocol.cpp b/src/rpc/protocol.cpp index 25ef1a6d27e7..a023f0666b1b 100644 --- a/src/rpc/protocol.cpp +++ b/src/rpc/protocol.cpp @@ -17,7 +17,6 @@ #include #include -using namespace std; /** * JSON-RPC protocol. PIVX speaks version 1.0 for maximum compatibility, @@ -29,7 +28,7 @@ using namespace std; * http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx */ -string JSONRPCRequest(const string& strMethod, const UniValue& params, const UniValue& id) +std::string JSONRPCRequest(const std::string& strMethod, const UniValue& params, const UniValue& id) { UniValue request(UniValue::VOBJ); request.push_back(Pair("method", strMethod)); @@ -50,13 +49,13 @@ UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const Un return reply; } -string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id) +std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id) { UniValue reply = JSONRPCReplyObj(result, error, id); return reply.write() + "\n"; } -UniValue JSONRPCError(int code, const string& message) +UniValue JSONRPCError(int code, const std::string& message) { UniValue error(UniValue::VOBJ); error.push_back(Pair("code", code)); diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 74ff162720fd..4df04be63791 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -32,14 +32,11 @@ #include -using namespace boost; -using namespace boost::assign; -using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; - vector addresses; + std::vector addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); @@ -88,7 +85,7 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) UniValue getrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "getrawtransaction \"txid\" ( verbose \"blockhash\" )\n" "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n" @@ -210,7 +207,7 @@ UniValue getrawtransaction(const UniValue& params, bool fHelp) UniValue listunspent(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 4) - throw runtime_error( + throw std::runtime_error( "listunspent ( minconf maxconf [\"address\",...] watchonlyconfig )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" @@ -257,16 +254,16 @@ UniValue listunspent(const UniValue& params, bool fHelp) if (params.size() > 1) nMaxDepth = params[1].get_int(); - set setAddress; + std::set setAddress; if (params.size() > 2) { UniValue inputs = params[2].get_array(); for (unsigned int inx = 0; inx < inputs.size(); inx++) { const UniValue& input = inputs[inx]; CBitcoinAddress address(input.get_str()); if (!address.IsValid()) - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid PIVX address: ") + input.get_str()); + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid PIVX address: ") + input.get_str()); if (setAddress.count(address)) - throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + input.get_str()); + throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str()); setAddress.insert(address); } } @@ -279,7 +276,7 @@ UniValue listunspent(const UniValue& params, bool fHelp) } UniValue results(UniValue::VARR); - vector vecOutputs; + std::vector vecOutputs; assert(pwalletMain != NULL); LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->AvailableCoins(vecOutputs, false, NULL, false, ALL_COINS, false, nWatchonlyConfig); @@ -330,7 +327,7 @@ UniValue listunspent(const UniValue& params, bool fHelp) UniValue createrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...} ( locktime )\n" "\nCreate a transaction spending the given inputs and sending to the given addresses.\n" "Returns hex-encoded raw transaction.\n" @@ -407,15 +404,15 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp) rawTx.vin.push_back(in); } - set setAddress; - vector addrList = sendTo.getKeys(); - for (const string& name_ : addrList) { + std::set setAddress; + std::vector addrList = sendTo.getKeys(); + for (const std::string& name_ : addrList) { CBitcoinAddress address(name_); if (!address.IsValid()) - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid PIVX address: ")+name_); + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid PIVX address: ")+name_); if (setAddress.count(address)) - throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); + throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); @@ -431,7 +428,7 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp) UniValue decoderawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "decoderawtransaction \"hexstring\"\n" "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n" @@ -495,7 +492,7 @@ UniValue decoderawtransaction(const UniValue& params, bool fHelp) UniValue decodescript(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "decodescript \"hex\"\n" "\nDecode a hex-encoded script.\n" @@ -524,7 +521,7 @@ UniValue decodescript(const UniValue& params, bool fHelp) UniValue r(UniValue::VOBJ); CScript script; if (params[0].get_str().size() > 0) { - vector scriptData(ParseHexV(params[0], "argument")); + std::vector scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid @@ -550,7 +547,7 @@ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std:: UniValue signrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) - throw runtime_error( + throw std::runtime_error( "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n" "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" @@ -612,9 +609,9 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) #endif RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true); - vector txData(ParseHexV(params[0], "argument 1")); + std::vector txData(ParseHexV(params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); - vector txVariants; + std::vector txVariants; while (!ssData.empty()) { try { CMutableTransaction tx; @@ -702,13 +699,13 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); - vector pkData(ParseHexO(prevOut, "scriptPubKey")); + std::vector pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { CCoinsModifier coins = view.ModifyCoins(txid); if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) { - string err("Previous output scriptPubKey mismatch:\n"); + std::string err("Previous output scriptPubKey mismatch:\n"); err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" + scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); @@ -725,7 +722,7 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR)); UniValue v = find_value(prevOut, "redeemScript"); if (!v.isNull()) { - vector rsData(ParseHexV(v, "redeemScript")); + std::vector rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } @@ -741,9 +738,9 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) int nHashType = SIGHASH_ALL; if (params.size() > 3 && !params[3].isNull()) { - static map mapSigHashValues = - boost::assign::map_list_of(string("ALL"), int(SIGHASH_ALL))(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(string("NONE"), int(SIGHASH_NONE))(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(string("SINGLE"), int(SIGHASH_SINGLE))(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY)); - string strHashType = params[3].get_str(); + static std::map mapSigHashValues = + boost::assign::map_list_of(std::string("ALL"), int(SIGHASH_ALL))(std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(std::string("NONE"), int(SIGHASH_NONE))(std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(std::string("SINGLE"), int(SIGHASH_SINGLE))(std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY)); + std::string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else @@ -802,7 +799,7 @@ UniValue signrawtransaction(const UniValue& params, bool fHelp) UniValue sendrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "sendrawtransaction \"hexstring\" ( allowhighfees )\n" "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n" "\nAlso see createrawtransaction and signrawtransaction calls.\n" @@ -846,7 +843,7 @@ UniValue sendrawtransaction(const UniValue& params, bool fHelp) if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets if (fSwiftX) { - mapTxLockReq.insert(make_pair(tx.GetHash(), tx)); + mapTxLockReq.insert(std::make_pair(tx.GetHash(), tx)); CreateNewLock(tx); RelayTransactionLockReq(tx, true); } @@ -873,7 +870,7 @@ UniValue sendrawtransaction(const UniValue& params, bool fHelp) UniValue getspentzerocoinamount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "getspentzerocoinamount hexstring index\n" "\nReturns value of spent zerocoin output designated by transaction hash and input index.\n" @@ -915,7 +912,7 @@ UniValue getspentzerocoinamount(const UniValue& params, bool fHelp) UniValue createrawzerocoinstake(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "createrawzerocoinstake mint_input \n" "\nCreates raw zPIV coinstakes (without MN output).\n" + HelpRequiringPassphrase() + "\n" @@ -997,7 +994,7 @@ UniValue createrawzerocoinstake(const UniValue& params, bool fHelp) UniValue createrawzerocoinpublicspend(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "createrawzerocoinpublicspend mint_input \n" "\nCreates raw zPIV public spend.\n" + HelpRequiringPassphrase() + "\n" @@ -1043,13 +1040,13 @@ UniValue createrawzerocoinpublicspend(const UniValue& params, bool fHelp) throw JSONRPCError(RPC_WALLET_ERROR, strErr); } CAmount nAmount = input_mint.GetDenominationAsAmount(); - vector vMintsSelected = vector(1,input_mint); + std::vector vMintsSelected = std::vector(1,input_mint); // create the spend CWalletTx rawTx; CZerocoinSpendReceipt receipt; CReserveKey reserveKey(pwalletMain); - vector vNewMints; + std::vector vNewMints; if (!pwalletMain->CreateZerocoinSpendTransaction(nAmount, rawTx, reserveKey, receipt, vMintsSelected, vNewMints, false, true, addr_ptr, true)) throw JSONRPCError(RPC_WALLET_ERROR, receipt.GetStatusMessage()); diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 25853a70ad83..e2010dc02923 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -27,8 +27,6 @@ #include -using namespace RPCServer; -using namespace std; static bool fRPCRunning = false; static bool fRPCInWarmup = true; @@ -70,7 +68,7 @@ void RPCServer::OnPostCommand(boost::function slot) } void RPCTypeCheck(const UniValue& params, - const list& typesExpected, + const std::list& typesExpected, bool fAllowNull) { unsigned int i = 0; @@ -80,7 +78,7 @@ void RPCTypeCheck(const UniValue& params, const UniValue& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.isNull())))) { - string err = strprintf("Expected type %s, got %s", + std::string err = strprintf("Expected type %s, got %s", uvTypeName(t), uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } @@ -89,16 +87,16 @@ void RPCTypeCheck(const UniValue& params, } void RPCTypeCheckObj(const UniValue& o, - const map& typesExpected, + const std::map& typesExpected, bool fAllowNull) { - for (const PAIRTYPE(string, UniValue::VType)& t : typesExpected) { + for (const PAIRTYPE(std::string, UniValue::VType)& t : typesExpected) { const UniValue& v = find_value(o, t.first); if (!fAllowNull && v.isNull()) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.isNull())))) { - string err = strprintf("Expected type %s for %s, got %s", + std::string err = strprintf("Expected type %s for %s, got %s", uvTypeName(t.second), t.first, uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } @@ -147,25 +145,25 @@ uint256 ParseHashV(const UniValue& v, std::string strName) result.SetHex(strHex); return result; } -uint256 ParseHashO(const UniValue& o, string strKey) +uint256 ParseHashO(const UniValue& o, std::string strKey) { return ParseHashV(find_value(o, strKey), strKey); } -vector ParseHexV(const UniValue& v, string strName) +std::vector ParseHexV(const UniValue& v, std::string strName) { - string strHex; + std::string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } -vector ParseHexO(const UniValue& o, string strKey) +std::vector ParseHexO(const UniValue& o, std::string strKey) { return ParseHexV(find_value(o, strKey), strKey); } -int ParseInt(const UniValue& o, string strKey) +int ParseInt(const UniValue& o, std::string strKey) { const UniValue& v = find_value(o, strKey); if (v.isNum()) @@ -174,7 +172,7 @@ int ParseInt(const UniValue& o, string strKey) return v.get_int(); } -bool ParseBool(const UniValue& o, string strKey) +bool ParseBool(const UniValue& o, std::string strKey) { const UniValue& v = find_value(o, strKey); if (v.isBool()) @@ -188,22 +186,22 @@ bool ParseBool(const UniValue& o, string strKey) * Note: This interface may still be subject to change. */ -string CRPCTable::help(string strCommand) const +std::string CRPCTable::help(std::string strCommand) const { - string strRet; - string category; - set setDone; - vector > vCommands; + std::string strRet; + std::string category; + std::set setDone; + std::vector > vCommands; - for (map::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) - vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); - sort(vCommands.begin(), vCommands.end()); + for (std::map::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) + vCommands.push_back(std::make_pair(mi->second->category + mi->first, mi->second)); + std::sort(vCommands.begin(), vCommands.end()); - for (const PAIRTYPE(string, const CRPCCommand*) & command : vCommands) { + for (const PAIRTYPE(std::string, const CRPCCommand*) & command : vCommands) { const CRPCCommand* pcmd = command.second; - string strMethod = pcmd->name; + std::string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order - if (strMethod.find("label") != string::npos) + if (strMethod.find("label") != std::string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; @@ -219,16 +217,16 @@ string CRPCTable::help(string strCommand) const (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception - string strHelp = string(e.what()); + std::string strHelp = std::string(e.what()); if (strCommand == "") { - if (strHelp.find('\n') != string::npos) + if (strHelp.find('\n') != std::string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; - string firstLetter = category.substr(0, 1); + std::string firstLetter = category.substr(0, 1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } @@ -245,7 +243,7 @@ string CRPCTable::help(string strCommand) const UniValue help(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" @@ -253,7 +251,7 @@ UniValue help(const UniValue& params, bool fHelp) "\nResult:\n" "\"text\" (string) The help text\n"); - string strCommand; + std::string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); @@ -265,7 +263,7 @@ UniValue stop(const UniValue& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "stop\n" "\nStop PIVX server."); // Event loop will exit after current HTTP requests have been handled, so @@ -486,7 +484,7 @@ CRPCTable::CRPCTable() const CRPCCommand *CRPCTable::operator[](const std::string &name) const { - map::const_iterator it = mapCommands.find(name); + std::map::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; @@ -630,12 +628,12 @@ std::vector CRPCTable::listCommands() const return commandList; } -std::string HelpExampleCli(string methodname, string args) +std::string HelpExampleCli(std::string methodname, std::string args) { return "> pivx-cli " + methodname + " " + args + "\n"; } -std::string HelpExampleRpc(string methodname, string args) +std::string HelpExampleRpc(std::string methodname, std::string args) { return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + diff --git a/src/rpc/server.h b/src/rpc/server.h index 5797abefa8d5..5d365f788e25 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -179,7 +179,7 @@ extern std::string HelpExampleCli(std::string methodname, std::string args); extern std::string HelpExampleRpc(std::string methodname, std::string args); extern void EnsureWalletIsUnlocked(bool fAllowAnonOnly = false); -extern UniValue DoZpivSpend(const CAmount nAmount, bool fMintChange, bool fMinimizeChange, vector& vMintsSelected, std::string address_str, bool isPublicSpend = true); +extern UniValue DoZpivSpend(const CAmount nAmount, bool fMintChange, bool fMinimizeChange, std::vector& vMintsSelected, std::string address_str, bool isPublicSpend = true); extern UniValue getconnectioncount(const UniValue& params, bool fHelp); // in rpc/net.cpp extern UniValue getpeerinfo(const UniValue& params, bool fHelp); diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 47d6d3129b51..6459fd55d2a4 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -14,9 +14,8 @@ #include "script/script.h" #include "uint256.h" -using namespace std; -typedef vector valtype; +typedef std::vector valtype; namespace { @@ -57,10 +56,10 @@ bool CastToBool(const valtype& vch) */ #define stacktop(i) (stack.at(stack.size()+(i))) #define altstacktop(i) (altstack.at(altstack.size()+(i))) -static inline void popstack(vector& stack) +static inline void popstack(std::vector& stack) { if (stack.empty()) - throw runtime_error("popstack() : stack empty"); + throw std::runtime_error("popstack() : stack empty"); stack.pop_back(); } @@ -236,7 +235,7 @@ bool static CheckMinimalPush(const valtype& data, opcodetype opcode) { return true; } -bool EvalScript(vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) +bool EvalScript(std::vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) { static const CScriptNum bnZero(0); static const CScriptNum bnOne(1); @@ -251,8 +250,8 @@ bool EvalScript(vector >& stack, const CScript& script, un CScript::const_iterator pbegincodehash = script.begin(); opcodetype opcode; valtype vchPushValue; - vector vfExec; - vector altstack; + std::vector vfExec; + std::vector altstack; set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); if (script.size() > 10000) return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE); @@ -1108,14 +1107,14 @@ bool TransactionSignatureChecker::VerifySignature(const std::vector& vchSigIn, const vector& vchPubKey, const CScript& scriptCode) const +bool TransactionSignatureChecker::CheckSig(const std::vector& vchSigIn, const std::vector& vchPubKey, const CScript& scriptCode) const { CPubKey pubkey(vchPubKey); if (!pubkey.IsValid()) return false; // Hash type is one byte tacked on to the end of the signature - vector vchSig(vchSigIn); + std::vector vchSig(vchSigIn); if (vchSig.empty()) return false; int nHashType = vchSig.back(); @@ -1174,7 +1173,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigne return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); } - vector > stack, stackCopy; + std::vector > stack, stackCopy; if (!EvalScript(stack, scriptSig, flags, checker, serror)) // serror is set return false; diff --git a/src/script/script.cpp b/src/script/script.cpp index ce6e7bd9808c..0fc8178ca0ce 100644 --- a/src/script/script.cpp +++ b/src/script/script.cpp @@ -18,7 +18,6 @@ inline std::string ValueString(const std::vector& vch) } } // anon namespace -using namespace std; const char* GetOpName(opcodetype opcode) { @@ -201,7 +200,7 @@ unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const // get the last item that the scriptSig // pushes onto the stack: const_iterator pc = scriptSig.begin(); - vector data; + std::vector data; while (pc < scriptSig.end()) { opcodetype opcode; diff --git a/src/script/sign.cpp b/src/script/sign.cpp index 6e2e069b3ddf..1f9ecc7564f7 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -14,9 +14,8 @@ #include "util.h" -using namespace std; -typedef vector valtype; +typedef std::vector valtype; bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet) { @@ -24,7 +23,7 @@ bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int n if (!keystore.GetKey(address, key)) return false; - vector vchSig; + std::vector vchSig; if (!key.Sign(hash, vchSig)) return false; vchSig.push_back((unsigned char)nHashType); @@ -33,7 +32,7 @@ bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int n return true; } -bool SignN(const vector& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet) +bool SignN(const std::vector& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet) { int nSigned = 0; int nRequired = multisigdata.front()[0]; @@ -58,7 +57,7 @@ bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash { scriptSigRet.clear(); - vector vSolutions; + std::vector vSolutions; if (!Solver(scriptPubKey, whichTypeRet, vSolutions)) { LogPrintf("*** solver solver failed \n"); @@ -154,7 +153,7 @@ bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutab return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType); } -static CScript PushAll(const vector& values) +static CScript PushAll(const std::vector& values) { CScript result; for (const valtype& v : values) @@ -163,11 +162,11 @@ static CScript PushAll(const vector& values) } static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, - const vector& vSolutions, - const vector& sigs1, const vector& sigs2) + const std::vector& vSolutions, + const std::vector& sigs1, const std::vector& sigs2) { // Combine all the signatures we've got: - set allsigs; + std::set allsigs; for (const valtype& v : sigs1) { if (!v.empty()) @@ -183,7 +182,7 @@ static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& assert(vSolutions.size() > 1); unsigned int nSigsRequired = vSolutions.front()[0]; unsigned int nPubKeys = vSolutions.size()-2; - map sigs; + std::map sigs; for (const valtype& sig : allsigs) { for (unsigned int i = 0; i < nPubKeys; i++) @@ -218,8 +217,8 @@ static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& } static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, - const txnouttype txType, const vector& vSolutions, - vector& sigs1, vector& sigs2) + const txnouttype txType, const std::vector& vSolutions, + std::vector& sigs1, std::vector& sigs2) { switch (txType) { @@ -248,7 +247,7 @@ static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction CScript pubKey2(spk.begin(), spk.end()); txnouttype txType2; - vector > vSolutions2; + std::vector > vSolutions2; Solver(pubKey2, txType2, vSolutions2); sigs1.pop_back(); sigs2.pop_back(); @@ -267,12 +266,12 @@ CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, const CScript& scriptSig1, const CScript& scriptSig2) { txnouttype txType; - vector > vSolutions; + std::vector > vSolutions; Solver(scriptPubKey, txType, vSolutions); - vector stack1; + std::vector stack1; EvalScript(stack1, scriptSig1, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker()); - vector stack2; + std::vector stack2; EvalScript(stack2, scriptSig2, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker()); return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2); diff --git a/src/script/standard.cpp b/src/script/standard.cpp index 06f757e6b90e..4b4239696af2 100644 --- a/src/script/standard.cpp +++ b/src/script/standard.cpp @@ -12,9 +12,8 @@ #include "utilstrencodings.h" -using namespace std; -typedef vector valtype; +typedef std::vector valtype; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; @@ -38,20 +37,20 @@ const char* GetTxnOutputType(txnouttype t) /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ -bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector >& vSolutionsRet) +bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector >& vSolutionsRet) { // Templates - static multimap mTemplates; + static std::multimap mTemplates; if (mTemplates.empty()) { // Standard tx, sender provides pubkey, receiver adds signature - mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG)); + mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG)); // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey - mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG)); + mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG)); // Sender provides N pubkeys, receivers provides M signatures - mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG)); + mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG)); } // Shortcut for pay-to-script-hash, which are more constrained than the other types: @@ -59,7 +58,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); + std::vector hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } @@ -68,7 +67,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector 150) return false; - vector hashBytes(scriptPubKey.begin()+2, scriptPubKey.end()); + std::vector hashBytes(scriptPubKey.begin()+2, scriptPubKey.end()); vSolutionsRet.push_back(hashBytes); return true; } @@ -91,7 +90,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector vch1, vch2; + std::vector vch1, vch2; // Compare CScript::const_iterator pc1 = script1.begin(); @@ -192,7 +191,7 @@ int ScriptSigArgsExpected(txnouttype t, const std::vector vSolutions; + std::vector vSolutions; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; @@ -214,7 +213,7 @@ bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType) bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { - vector vSolutions; + std::vector vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; @@ -242,11 +241,11 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) return false; } -bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector& addressRet, int& nRequiredRet) +bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; - vector vSolutions; + std::vector vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ diff --git a/src/serialize.h b/src/serialize.h index 52e47550aabe..f492fccccd26 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -60,11 +60,11 @@ enum { #define READWRITE(obj) (::SerReadWrite(s, (obj), nType, nVersion, ser_action)) -/** +/** * Implement three methods for serializable objects. These are actually wrappers over * "SerializationOp" template, which implements the body of each class' serialization * code. Adding "ADD_SERIALIZE_METHODS" in the body of the class causes these wrappers to be - * added as members. + * added as members. */ #define ADD_SERIALIZE_METHODS \ size_t GetSerializeSize(int nType, int nVersion) const \ @@ -373,16 +373,16 @@ uint64_t ReadCompactSize(Stream& is) * sure the encoding is one-to-one, one is subtracted from all but the last digit. * Thus, the byte sequence a[] with length len, where all but the last byte * has bit 128 set, encodes the number: - * + * * (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1)) - * + * * Properties: * * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes) * * Every integer has exactly one encoding * * Encoding does not depend on size of original integer type * * No redundancy: every (infinite) byte sequence corresponds to a list * of encoded integers. - * + * * 0: [0x00] 256: [0x81 0x00] * 1: [0x01] 16383: [0xFE 0x7F] * 127: [0x7F] 16384: [0xFF 0x00] @@ -440,7 +440,7 @@ I ReadVarInt(Stream& is) #define VARINT(obj) REF(WrapVarInt(REF(obj))) #define LIMITED_STRING(obj, n) REF(LimitedString(REF(obj))) -/** +/** * Wrapper for serializing arrays and POD. */ class CFlatData @@ -553,7 +553,7 @@ CVarInt WrapVarInt(I& n) */ /** - * string + * std::string */ template unsigned int GetSerializeSize(const std::basic_string& str, int, int = 0); diff --git a/src/spork.cpp b/src/spork.cpp index da2808834e3b..70760d2228f5 100644 --- a/src/spork.cpp +++ b/src/spork.cpp @@ -14,8 +14,6 @@ #include "sporkdb.h" #include "util.h" -using namespace std; -using namespace boost; class CSporkMessage; class CSporkManager; diff --git a/src/spork.h b/src/spork.h index 8d8a4ae8905f..e9fcaa3a0539 100644 --- a/src/spork.h +++ b/src/spork.h @@ -16,8 +16,6 @@ #include "obfuscation.h" #include "protocol.h" -using namespace std; -using namespace boost; /* Don't ever reuse these IDs for other sporks diff --git a/src/stakeinput.cpp b/src/stakeinput.cpp index a1ef4e4dfae4..adf37c636dc6 100644 --- a/src/stakeinput.cpp +++ b/src/stakeinput.cpp @@ -126,7 +126,7 @@ bool CZPivStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut) return true; } -bool CZPivStake::CreateTxOuts(CWallet* pwallet, vector& vout, CAmount nTotal) +bool CZPivStake::CreateTxOuts(CWallet* pwallet, std::vector& vout, CAmount nTotal) { //Create an output returning the zPIV that was staked CTxOut outReward; @@ -195,9 +195,9 @@ CAmount CPivStake::GetValue() return txFrom.vout[nPosition].nValue; } -bool CPivStake::CreateTxOuts(CWallet* pwallet, vector& vout, CAmount nTotal) +bool CPivStake::CreateTxOuts(CWallet* pwallet, std::vector& vout, CAmount nTotal) { - vector vSolutions; + std::vector vSolutions; txnouttype whichType; CScript scriptPubKeyKernel = txFrom.vout[nPosition].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { diff --git a/src/stakeinput.h b/src/stakeinput.h index a8ed267bfa99..887b18db3ce2 100644 --- a/src/stakeinput.h +++ b/src/stakeinput.h @@ -24,7 +24,7 @@ class CStakeInput virtual bool CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut = 0) = 0; virtual bool GetTxFrom(CTransaction& tx) = 0; virtual CAmount GetValue() = 0; - virtual bool CreateTxOuts(CWallet* pwallet, vector& vout, CAmount nTotal) = 0; + virtual bool CreateTxOuts(CWallet* pwallet, std::vector& vout, CAmount nTotal) = 0; virtual bool GetModifier(uint64_t& nStakeModifier) = 0; virtual bool IsZPIV() = 0; virtual CDataStream GetUniqueness() = 0; @@ -60,7 +60,7 @@ class CZPivStake : public CStakeInput bool GetModifier(uint64_t& nStakeModifier) override; CDataStream GetUniqueness() override; bool CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut = 0) override; - bool CreateTxOuts(CWallet* pwallet, vector& vout, CAmount nTotal) override; + bool CreateTxOuts(CWallet* pwallet, std::vector& vout, CAmount nTotal) override; bool MarkSpent(CWallet* pwallet, const uint256& txid); bool IsZPIV() override { return true; } uint256 GetSerialHash() const override { return hashSerial; } @@ -88,7 +88,7 @@ class CPivStake : public CStakeInput bool GetModifier(uint64_t& nStakeModifier) override; CDataStream GetUniqueness() override; bool CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut = 0) override; - bool CreateTxOuts(CWallet* pwallet, vector& vout, CAmount nTotal) override; + bool CreateTxOuts(CWallet* pwallet, std::vector& vout, CAmount nTotal) override; bool IsZPIV() override { return false; } uint256 GetSerialHash() const override { return uint256(0); } }; diff --git a/src/swifttx.cpp b/src/swifttx.cpp index 49282c41d9de..1d7f4ca306a2 100644 --- a/src/swifttx.cpp +++ b/src/swifttx.cpp @@ -18,8 +18,6 @@ #include "validationinterface.h" #include -using namespace std; -using namespace boost; std::map mapTxLockReq; std::map mapTxLockReqRejected; @@ -84,7 +82,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v DoConsensusVote(tx, nBlockHeight); - mapTxLockReq.insert(make_pair(tx.GetHash(), tx)); + mapTxLockReq.insert(std::make_pair(tx.GetHash(), tx)); LogPrintf("ProcessMessageSwiftTX::ix - Transaction Lock Request: %s %s : accepted %s\n", pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(), @@ -97,7 +95,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v return; } else { - mapTxLockReqRejected.insert(make_pair(tx.GetHash(), tx)); + mapTxLockReqRejected.insert(std::make_pair(tx.GetHash(), tx)); // can we get the conflicting transaction as proof? @@ -107,7 +105,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v for (const CTxIn& in : tx.vin) { if (!mapLockedInputs.count(in.prevout)) { - mapLockedInputs.insert(make_pair(in.prevout, tx.GetHash())); + mapLockedInputs.insert(std::make_pair(in.prevout, tx.GetHash())); } } @@ -121,7 +119,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v //reprocess the last 15 blocks ReprocessBlocks(15); - mapTxLockReq.insert(make_pair(tx.GetHash(), tx)); + mapTxLockReq.insert(std::make_pair(tx.GetHash(), tx)); } } } @@ -140,7 +138,7 @@ void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& v return; } - mapTxLockVote.insert(make_pair(ctx.GetHash(), ctx)); + mapTxLockVote.insert(std::make_pair(ctx.GetHash(), ctx)); if (ProcessConsensusVote(pfrom, ctx)) { //Spam/Dos protection @@ -249,7 +247,7 @@ int64_t CreateNewLock(CTransaction tx) newLock.nExpiration = GetTime() + (60 * 60); //locks expire after 60 minutes (24 confirmations) newLock.nTimeout = GetTime() + (60 * 5); newLock.txHash = tx.GetHash(); - mapTxLocks.insert(make_pair(tx.GetHash(), newLock)); + mapTxLocks.insert(std::make_pair(tx.GetHash(), newLock)); } else { mapTxLocks[tx.GetHash()].nBlockHeight = nBlockHeight; LogPrint("swiftx", "CreateNewLock - Transaction Lock Exists %s !\n", tx.GetHash().ToString().c_str()); @@ -336,7 +334,7 @@ bool ProcessConsensusVote(CNode* pnode, CConsensusVote& ctx) newLock.nExpiration = GetTime() + (60 * 60); newLock.nTimeout = GetTime() + (60 * 5); newLock.txHash = ctx.txHash; - mapTxLocks.insert(make_pair(ctx.txHash, newLock)); + mapTxLocks.insert(std::make_pair(ctx.txHash, newLock)); } else LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Transaction Lock Exists %s !\n", ctx.txHash.ToString().c_str()); @@ -371,7 +369,7 @@ bool ProcessConsensusVote(CNode* pnode, CConsensusVote& ctx) if (mapTxLockReq.count(ctx.txHash)) { for (const CTxIn& in : tx.vin) { if (!mapLockedInputs.count(in.prevout)) { - mapLockedInputs.insert(make_pair(in.prevout, ctx.txHash)); + mapLockedInputs.insert(std::make_pair(in.prevout, ctx.txHash)); } } } diff --git a/src/swifttx.h b/src/swifttx.h index bf971f72aa5a..6d918f5e05b0 100644 --- a/src/swifttx.h +++ b/src/swifttx.h @@ -26,8 +26,6 @@ #define SWIFTTX_SIGNATURES_REQUIRED 6 #define SWIFTTX_SIGNATURES_TOTAL 10 -using namespace std; -using namespace boost; class CConsensusVote; class CTransaction; @@ -35,10 +33,10 @@ class CTransactionLock; static const int MIN_SWIFTTX_PROTO_VERSION = 70103; -extern map mapTxLockReq; -extern map mapTxLockReqRejected; -extern map mapTxLockVote; -extern map mapTxLocks; +extern std::map mapTxLockReq; +extern std::map mapTxLockReqRejected; +extern std::map mapTxLockVote; +extern std::map mapTxLocks; extern std::map mapLockedInputs; extern int nCompleteTXLocks; diff --git a/src/test/Checkpoints_tests.cpp b/src/test/Checkpoints_tests.cpp index 2967edadd161..29c010872575 100644 --- a/src/test/Checkpoints_tests.cpp +++ b/src/test/Checkpoints_tests.cpp @@ -14,7 +14,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(Checkpoints_tests, BasicTestingSetup) diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp index 203887ad0eb4..f2aaa78a5bd4 100644 --- a/src/test/addrman_tests.cpp +++ b/src/test/addrman_tests.cpp @@ -340,7 +340,7 @@ BOOST_AUTO_TEST_CASE(addrman_getaddr) // Test 22: Sanity check, GetAddr should never return anything if addrman // is empty. BOOST_CHECK(addrman.size() == 0); - vector vAddr1 = addrman.GetAddr(); + std::vector vAddr1 = addrman.GetAddr(); BOOST_CHECK(vAddr1.size() == 0); CAddress addr1 = CAddress(CService("250.250.2.1", 8333)); diff --git a/src/test/arith_uint256_tests.cpp b/src/test/arith_uint256_tests.cpp index 6b05b59e92b7..5263fab40091 100644 --- a/src/test/arith_uint256_tests.cpp +++ b/src/test/arith_uint256_tests.cpp @@ -68,7 +68,7 @@ std::string ArrayToString(const unsigned char A[], unsigned int width) BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality { BOOST_CHECK(1 == 0+1); - // constructor arith_uint256(vector): + // constructor arith_uint256(std::vector): BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32)); BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32)); BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32)); diff --git a/src/test/benchmark_zerocoin.cpp b/src/test/benchmark_zerocoin.cpp index 785fcc80ec79..f1ddb743f297 100644 --- a/src/test/benchmark_zerocoin.cpp +++ b/src/test/benchmark_zerocoin.cpp @@ -27,8 +27,6 @@ #include "libzerocoin/Accumulator.h" #include "test_pivx.h" -using namespace std; -using namespace libzerocoin; #define COLOR_STR_GREEN "\033[32m" #define COLOR_STR_NORMAL "\033[0m" @@ -41,10 +39,10 @@ uint32_t ggNumTests = 0; uint32_t ggSuccessfulTests = 0; // Global coin array -PrivateCoin *ggCoins[TESTS_COINS_TO_ACCUMULATE]; +libzerocoin::PrivateCoin *ggCoins[TESTS_COINS_TO_ACCUMULATE]; // Global params -ZerocoinParams *gg_Params; +libzerocoin::ZerocoinParams *gg_Params; ////////// // Utility routines @@ -52,75 +50,75 @@ ZerocoinParams *gg_Params; class Timer { - timeval timer[2]; + timeval timer[2]; public: - timeval start() - { - gettimeofday(&this->timer[0], NULL); - return this->timer[0]; - } - - timeval stop() - { - gettimeofday(&this->timer[1], NULL); - return this->timer[1]; - } - - int duration() const - { - int secs(this->timer[1].tv_sec - this->timer[0].tv_sec); - int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec); - - if(usecs < 0) - { - --secs; - usecs += 1000000; - } - - return static_cast(secs * 1000 + usecs / 1000.0 + 0.5); - } + timeval start() + { + gettimeofday(&this->timer[0], NULL); + return this->timer[0]; + } + + timeval stop() + { + gettimeofday(&this->timer[1], NULL); + return this->timer[1]; + } + + int duration() const + { + int secs(this->timer[1].tv_sec - this->timer[0].tv_sec); + int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec); + + if(usecs < 0) + { + --secs; + usecs += 1000000; + } + + return static_cast(secs * 1000 + usecs / 1000.0 + 0.5); + } }; // Global timer Timer timer; void -gLogTestResult(string testName, bool (*testPtr)()) +gLogTestResult(std::string testName, bool (*testPtr)()) { - string colorGreen(COLOR_STR_GREEN); - string colorNormal(COLOR_STR_NORMAL); - string colorRed(COLOR_STR_RED); + std::string colorGreen(COLOR_STR_GREEN); + std::string colorNormal(COLOR_STR_NORMAL); + std::string colorRed(COLOR_STR_RED); - cout << "Testing if " << testName << "..." << endl; + std::cout << "Testing if " << testName << "..." << std::endl; - bool testResult = testPtr(); + bool testResult = testPtr(); - if (testResult == true) { - cout << "\t" << colorGreen << "[PASS]" << colorNormal << endl; - ggSuccessfulTests++; - } else { - cout << colorRed << "\t[FAIL]" << colorNormal << endl; - } + if (testResult == true) { + std::cout << "\t" << colorGreen << "[PASS]" << colorNormal << std::endl; + ggSuccessfulTests++; + } else { + std::cout << colorRed << "\t[FAIL]" << colorNormal << std::endl; + } - ggNumTests++; + ggNumTests++; } CBigNum gGetTestModulus() { - static CBigNum testModulus(0); + static CBigNum testModulus(0); - // TODO: should use a hard-coded RSA modulus for testing - if (!testModulus) { - CBigNum p, q; - p = CBigNum::generatePrime(1024, false); - q = CBigNum::generatePrime(1024, false); - testModulus = p * q; - } + // TODO: should use a hard-coded RSA modulus for testing + if (!testModulus) { + CBigNum p, q; + p = CBigNum::generatePrime(1024, false); + q = CBigNum::generatePrime(1024, false); + testModulus = p * q; + } - return testModulus; + return testModulus; } ////////// @@ -131,286 +129,286 @@ gGetTestModulus() bool Testb_GenRSAModulus() { - CBigNum result = gGetTestModulus(); - - if (!result) { - return false; - } - else { - return true; - } + CBigNum result = gGetTestModulus(); + + if (!result) { + return false; + } + else { + return true; + } } bool Testb_CalcParamSizes() { - bool result = true; + bool result = true; #if 0 - uint32_t pLen, qLen; - - try { - calculateGroupParamLengths(4000, 80, &pLen, &qLen); - if (pLen < 1024 || qLen < 256) { - result = false; - } - calculateGroupParamLengths(4000, 96, &pLen, &qLen); - if (pLen < 2048 || qLen < 256) { - result = false; - } - calculateGroupParamLengths(4000, 112, &pLen, &qLen); - if (pLen < 3072 || qLen < 320) { - result = false; - } - calculateGroupParamLengths(4000, 120, &pLen, &qLen); - if (pLen < 3072 || qLen < 320) { - result = false; - } - calculateGroupParamLengths(4000, 128, &pLen, &qLen); - if (pLen < 3072 || qLen < 320) { - result = false; - } - } catch (exception &e) { - result = false; - } + uint32_t pLen, qLen; + + try { + calculateGroupParamLengths(4000, 80, &pLen, &qLen); + if (pLen < 1024 || qLen < 256) { + result = false; + } + calculateGroupParamLengths(4000, 96, &pLen, &qLen); + if (pLen < 2048 || qLen < 256) { + result = false; + } + calculateGroupParamLengths(4000, 112, &pLen, &qLen); + if (pLen < 3072 || qLen < 320) { + result = false; + } + calculateGroupParamLengths(4000, 120, &pLen, &qLen); + if (pLen < 3072 || qLen < 320) { + result = false; + } + calculateGroupParamLengths(4000, 128, &pLen, &qLen); + if (pLen < 3072 || qLen < 320) { + result = false; + } + } catch (exception &e) { + result = false; + } #endif - return result; + return result; } bool Testb_GenerateGroupParams() { - uint32_t pLen = 1024, qLen = 256, count; - IntegerGroupParams group; + uint32_t pLen = 1024, qLen = 256, count; + libzerocoin::IntegerGroupParams group; - for (count = 0; count < 1; count++) { + for (count = 0; count < 1; count++) { - try { - group = deriveIntegerGroupParams(calculateSeed(gGetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen); - } catch (std::runtime_error e) { - cout << "Caught exception " << e.what() << endl; - return false; - } + try { + group = libzerocoin::deriveIntegerGroupParams(libzerocoin::calculateSeed(gGetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen); + } catch (std::runtime_error e) { + std::cout << "Caught exception " << e.what() << std::endl; + return false; + } - // Now perform some simple tests on the resulting parameters - if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) { - return false; - } + // Now perform some simple tests on the resulting parameters + if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) { + return false; + } - CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus); - //cout << "g^q mod p = " << c << endl; - if (!(c.isOne())) return false; + CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus); + //cout << "g^q mod p = " << c << std::endl; + if (!(c.isOne())) return false; - // Try at multiple parameter sizes - pLen = pLen * 1.5; - qLen = qLen * 1.5; - } + // Try at multiple parameter sizes + pLen = pLen * 1.5; + qLen = qLen * 1.5; + } - return true; + return true; } bool Testb_ParamGen() { - bool result = true; + bool result = true; - try { - timer.start(); - // Instantiating testParams runs the parameter generation code - ZerocoinParams testParams(gGetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL); - timer.stop(); + try { + timer.start(); + // Instantiating testParams runs the parameter generation code + libzerocoin::ZerocoinParams testParams(gGetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL); + timer.stop(); - cout << "\tPARAMGEN ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl; - } catch (runtime_error e) { - cout << e.what() << endl; - result = false; - } + std::cout << "\tPARAMGEN ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; + } catch (std::runtime_error e) { + std::cout << e.what() << std::endl; + result = false; + } - return result; + return result; } bool Testb_Accumulator() { - // This test assumes a list of coins were generated during - // the Testb_MintCoin() test. - if (ggCoins[0] == NULL) { - return false; - } - try { - // Accumulate the coin list from first to last into one accumulator - Accumulator accOne(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); - Accumulator accTwo(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); - Accumulator accThree(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); - Accumulator accFour(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); - AccumulatorWitness wThree(gg_Params, accThree, ggCoins[0]->getPublicCoin()); - - for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - accOne += ggCoins[i]->getPublicCoin(); - accTwo += ggCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin(); - accThree += ggCoins[i]->getPublicCoin(); - wThree += ggCoins[i]->getPublicCoin(); - if(i != 0) { - accFour += ggCoins[i]->getPublicCoin(); - } - } - - // Compare the accumulated results - if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) { - cout << "Accumulators don't match" << endl; - return false; - } - - if(accFour.getValue() != wThree.getValue()) { - cout << "Witness math not working," << endl; - return false; - } - - // Verify that the witness is correct - if (!wThree.VerifyWitness(accThree, ggCoins[0]->getPublicCoin()) ) { - cout << "Witness not valid" << endl; - return false; - } - - } catch (runtime_error e) { - cout << e.what() << endl; + // This test assumes a list of coins were generated during + // the Testb_MintCoin() test. + if (ggCoins[0] == NULL) { return false; - } + } + try { + // Accumulate the coin list from first to last into one accumulator + libzerocoin::Accumulator accOne(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::Accumulator accTwo(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::Accumulator accThree(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::Accumulator accFour(&gg_Params->accumulatorParams,libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::AccumulatorWitness wThree(gg_Params, accThree, ggCoins[0]->getPublicCoin()); + + for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { + accOne += ggCoins[i]->getPublicCoin(); + accTwo += ggCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin(); + accThree += ggCoins[i]->getPublicCoin(); + wThree += ggCoins[i]->getPublicCoin(); + if(i != 0) { + accFour += ggCoins[i]->getPublicCoin(); + } + } + + // Compare the accumulated results + if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) { + std::cout << "Accumulators don't match" << std::endl; + return false; + } + + if(accFour.getValue() != wThree.getValue()) { + std::cout << "Witness math not working," << std::endl; + return false; + } + + // Verify that the witness is correct + if (!wThree.VerifyWitness(accThree, ggCoins[0]->getPublicCoin()) ) { + std::cout << "Witness not valid" << std::endl; + return false; + } + + } catch (std::runtime_error e) { + std::cout << e.what() << std::endl; + return false; + } - return true; + return true; } bool Testb_MintCoin() { - try { - // Generate a list of coins - timer.start(); - for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - ggCoins[i] = new PrivateCoin(gg_Params,CoinDenomination::ZQ_ONE); - } - timer.stop(); - } catch (exception &e) { - return false; - } - - cout << "\tMINT ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Coin: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << endl; - - return true; + try { + // Generate a list of coins + timer.start(); + for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { + ggCoins[i] = new libzerocoin::PrivateCoin(gg_Params, libzerocoin::CoinDenomination::ZQ_ONE); + } + timer.stop(); + } catch (std::exception &e) { + return false; + } + + std::cout << "\tMINT ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Coin: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << std::endl; + + return true; } bool Testb_MintAndSpend() { - try { - // This test assumes a list of coins were generated in Testb_MintCoin() - if (ggCoins[0] == NULL) - { - // No coins: mint some. - Testb_MintCoin(); - if (ggCoins[0] == NULL) { - return false; - } - } - - // Accumulate the list of generated coins into a fresh accumulator. - // The first one gets marked as accumulated for a witness, the - // others just get accumulated normally. - Accumulator acc(&gg_Params->accumulatorParams,CoinDenomination::ZQ_ONE); - AccumulatorWitness wAcc(gg_Params, acc, ggCoins[0]->getPublicCoin()); - - timer.start(); - for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - acc += ggCoins[i]->getPublicCoin(); - } - timer.stop(); - - cout << "\tACCUMULATOR ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << endl; - - timer.start(); - for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - wAcc +=ggCoins[i]->getPublicCoin(); - } - timer.stop(); - - cout << "\tWITNESS ELAPSED TIME: \n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << endl; - - // Now spend the coin - timer.start(); - CoinSpend spend(gg_Params, gg_Params, *(ggCoins[0]), acc, 0, wAcc, 0, SpendType::SPEND); //(0) presstab - timer.stop(); - - cout << "\tSPEND ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl; - - // Serialize the proof and deserialize into newSpend - CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); - - timer.start(); - ss << spend; - timer.stop(); - - CoinSpend newSpend(gg_Params, gg_Params, ss); - - cout << "\tSERIALIZE ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl; - - // Finally, see if we can verify the deserialized proof (return our result) - timer.start(); - bool ret = newSpend.Verify(acc); - timer.stop(); - - cout << "\tSPEND VERIFY ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << endl; - - return ret; - } catch (runtime_error &e) { - cout << e.what() << endl; - return false; - } - - return false; + try { + // This test assumes a list of coins were generated in Testb_MintCoin() + if (ggCoins[0] == NULL) + { + // No coins: mint some. + Testb_MintCoin(); + if (ggCoins[0] == NULL) { + return false; + } + } + + // Accumulate the list of generated coins into a fresh accumulator. + // The first one gets marked as accumulated for a witness, the + // others just get accumulated normally. + libzerocoin::Accumulator acc(&gg_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::AccumulatorWitness wAcc(gg_Params, acc, ggCoins[0]->getPublicCoin()); + + timer.start(); + for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { + acc += ggCoins[i]->getPublicCoin(); + } + timer.stop(); + + std::cout << "\tACCUMULATOR ELAPSED TIME:\n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << std::endl; + + timer.start(); + for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { + wAcc +=ggCoins[i]->getPublicCoin(); + } + timer.stop(); + + std::cout << "\tWITNESS ELAPSED TIME: \n\t\tTotal: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s\n\t\tPer Element: " << timer.duration()/TESTS_COINS_TO_ACCUMULATE << " ms\t" << (timer.duration()/TESTS_COINS_TO_ACCUMULATE)*0.001 << " s" << std::endl; + + // Now spend the coin + timer.start(); + libzerocoin::CoinSpend spend(gg_Params, gg_Params, *(ggCoins[0]), acc, 0, wAcc, 0, libzerocoin::SpendType::SPEND); //(0) presstab + timer.stop(); + + std::cout << "\tSPEND ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; + + // Serialize the proof and deserialize into newSpend + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + + timer.start(); + ss << spend; + timer.stop(); + + libzerocoin::CoinSpend newSpend(gg_Params, gg_Params, ss); + + std::cout << "\tSERIALIZE ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; + + // Finally, see if we can verify the deserialized proof (return our result) + timer.start(); + bool ret = newSpend.Verify(acc); + timer.stop(); + + std::cout << "\tSPEND VERIFY ELAPSED TIME: " << timer.duration() << " ms\t" << timer.duration()*0.001 << " s" << std::endl; + + return ret; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + return false; + } + + return false; } void Testb_RunAllTests() { - // Make a new set of parameters from a random RSA modulus - gg_Params = new ZerocoinParams(gGetTestModulus()); - - ggNumTests = ggSuccessfulTests = 0; - for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - ggCoins[i] = NULL; - } - - // Run through all of the Zerocoin tests - gLogTestResult("an RSA modulus can be generated", Testb_GenRSAModulus); - gLogTestResult("parameter sizes are correct", Testb_CalcParamSizes); - gLogTestResult("group/field parameters can be generated", Testb_GenerateGroupParams); - gLogTestResult("parameter generation is correct", Testb_ParamGen); - gLogTestResult("coins can be minted", Testb_MintCoin); - gLogTestResult("the accumulator works", Testb_Accumulator); - gLogTestResult("a minted coin can be spent", Testb_MintAndSpend); - - // Summarize test results - if (ggSuccessfulTests < ggNumTests) { - cout << endl << "ERROR: SOME TESTS FAILED" << endl; - } - - // Clear any generated coins - for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - delete ggCoins[i]; - } - - cout << ggSuccessfulTests << " out of " << ggNumTests << " tests passed." << endl << endl; - delete gg_Params; + // Make a new set of parameters from a random RSA modulus + gg_Params = new libzerocoin::ZerocoinParams(gGetTestModulus()); + + ggNumTests = ggSuccessfulTests = 0; + for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { + ggCoins[i] = NULL; + } + + // Run through all of the Zerocoin tests + gLogTestResult("an RSA modulus can be generated", Testb_GenRSAModulus); + gLogTestResult("parameter sizes are correct", Testb_CalcParamSizes); + gLogTestResult("group/field parameters can be generated", Testb_GenerateGroupParams); + gLogTestResult("parameter generation is correct", Testb_ParamGen); + gLogTestResult("coins can be minted", Testb_MintCoin); + gLogTestResult("the accumulator works", Testb_Accumulator); + gLogTestResult("a minted coin can be spent", Testb_MintAndSpend); + + // Summarize test results + if (ggSuccessfulTests < ggNumTests) { + std::cout << std::endl << "ERROR: SOME TESTS FAILED" << std::endl; + } + + // Clear any generated coins + for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { + delete ggCoins[i]; + } + + std::cout << ggSuccessfulTests << " out of " << ggNumTests << " tests passed." << std::endl << std::endl; + delete gg_Params; } BOOST_FIXTURE_TEST_SUITE(benchmark_zerocoin, TestingSetup) BOOST_AUTO_TEST_CASE(benchmark_test) { - cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " benchmark utility." << endl << endl; + std::cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " benchmark utility." << std::endl << std::endl; - Testb_RunAllTests(); + Testb_RunAllTests(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/bloom_tests.cpp b/src/test/bloom_tests.cpp index bb8083afa531..d71977a28f7f 100644 --- a/src/test/bloom_tests.cpp +++ b/src/test/bloom_tests.cpp @@ -21,8 +21,6 @@ #include #include -using namespace std; -using namespace boost::tuples; BOOST_FIXTURE_TEST_SUITE(bloom_tests, BasicTestingSetup) @@ -44,8 +42,8 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize) CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION); - vector vch = ParseHex("03614e9b050000000000000001"); - vector expected(vch.size()); + std::vector vch = ParseHex("03614e9b050000000000000001"); + std::vector expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; @@ -76,8 +74,8 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak) CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION); - vector vch = ParseHex("03ce4299050000000100008001"); - vector expected(vch.size()); + std::vector vch = ParseHex("03ce4299050000000100008001"); + std::vector expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; @@ -87,24 +85,24 @@ BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak) BOOST_AUTO_TEST_CASE(bloom_create_insert_key) { - string strSecret = string("5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"); + std::string strSecret = std::string("5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"); CBitcoinSecret vchSecret; BOOST_CHECK(vchSecret.SetString(strSecret)); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); - vector vchPubKey(pubkey.begin(), pubkey.end()); + std::vector vchPubKey(pubkey.begin(), pubkey.end()); CBloomFilter filter(2, 0.001, 0, BLOOM_UPDATE_ALL); filter.insert(vchPubKey); uint160 hash = pubkey.GetID(); - filter.insert(vector(hash.begin(), hash.end())); + filter.insert(std::vector(hash.begin(), hash.end())); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION); - vector vch = ParseHex("038fc16b080000000000000001"); - vector expected(vch.size()); + std::vector vch = ParseHex("038fc16b080000000000000001"); + std::vector expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; @@ -121,7 +119,7 @@ BOOST_AUTO_TEST_CASE(bloom_match) // and one which spends it (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436) unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00}; - vector vch(ch, ch + sizeof(ch) -1); + std::vector vch(ch, ch + sizeof(ch) -1); CDataStream spendStream(vch, SER_DISK, CLIENT_VERSION); CTransaction spendingTx; spendStream >> spendingTx; @@ -159,7 +157,7 @@ BOOST_AUTO_TEST_CASE(bloom_match) filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); COutPoint prevOutPoint(uint256("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0); { - vector data(32 + sizeof(unsigned int)); + std::vector data(32 + sizeof(unsigned int)); memcpy(&data[0], prevOutPoint.hash.begin(), 32); memcpy(&data[32], &prevOutPoint.n, sizeof(unsigned int)); filter.insert(data); @@ -204,7 +202,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_1) BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8); - vector vMatched; + std::vector vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) @@ -249,7 +247,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_2) BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); - vector vMatched; + std::vector vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) @@ -303,7 +301,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none) BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); - vector vMatched; + std::vector vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) @@ -353,7 +351,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize) BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); - vector vMatched; + std::vector vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) @@ -362,8 +360,8 @@ BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize) CDataStream merkleStream(SER_NETWORK, PROTOCOL_VERSION); merkleStream << merkleBlock; - vector vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101"); - vector expected(vch.size()); + std::vector vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101"); + std::vector expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; @@ -392,7 +390,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_4) BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6); - vector vMatched; + std::vector vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) diff --git a/src/test/hash_tests.cpp b/src/test/hash_tests.cpp index 31815f31fedf..974583c3f869 100644 --- a/src/test/hash_tests.cpp +++ b/src/test/hash_tests.cpp @@ -10,7 +10,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(hash_tests, BasicTestingSetup) diff --git a/src/test/key_tests.cpp b/src/test/key_tests.cpp index f1960ec2e71b..4d3864a7b045 100644 --- a/src/test/key_tests.cpp +++ b/src/test/key_tests.cpp @@ -17,19 +17,18 @@ #include -using namespace std; -static const string strSecret1 ("87vK7Vayi3QLsuiva5yWSuVwSMhMcRM9dBsaD6JXMD1P5vnjRFn"); -static const string strSecret2 ("87FGYGFDg5SYfdD4XL593hr7do6f52czPecVsYSAXi8N4RGeS9i"); -static const string strSecret1C ("YRYJwfAyJ9c2jhi3T2xQyLijGvM7yLTw4izDaNQLxBzgUYrQiPmJ"); -static const string strSecret2C ("YNZyazHkwUbkmUpEYsBGWwHnHQTy2n9rJy1gS5k54YXVx3pE8n6N"); +static const std::string strSecret1 ("87vK7Vayi3QLsuiva5yWSuVwSMhMcRM9dBsaD6JXMD1P5vnjRFn"); +static const std::string strSecret2 ("87FGYGFDg5SYfdD4XL593hr7do6f52czPecVsYSAXi8N4RGeS9i"); +static const std::string strSecret1C ("YRYJwfAyJ9c2jhi3T2xQyLijGvM7yLTw4izDaNQLxBzgUYrQiPmJ"); +static const std::string strSecret2C ("YNZyazHkwUbkmUpEYsBGWwHnHQTy2n9rJy1gS5k54YXVx3pE8n6N"); static const CBitcoinAddress addr1 ("DBFi8XAE1rcdCQfkv9w22n8Y9RxgaJnrDD"); static const CBitcoinAddress addr2 ("DPvKfv1FVp69yZMDzeuugvfZ9pzYiMv1bs"); static const CBitcoinAddress addr1C("DNPrHK9ezAAUVExFDpZ7EE1xWpPskgp1gP"); static const CBitcoinAddress addr2C("DNBVSAoc2whPFjZVAZ1pQbXPJk1LRrDC8Q"); -static const string strAddressBad("Xta1praZQjyELweyMByXyiREw1ZRsjXzVP"); +static const std::string strAddressBad("Xta1praZQjyELweyMByXyiREw1ZRsjXzVP"); #ifdef KEY_TESTS_DUMPINFO @@ -38,7 +37,7 @@ void dumpKeyInfo(uint256 privkey) CKey key; key.resize(32); memcpy(&secret[0], &privkey, 32); - vector sec; + std::vector sec; sec.resize(32); memcpy(&sec[0], &secret[0], 32); printf(" * secret (hex): %s\n", HexStr(sec).c_str()); @@ -52,7 +51,7 @@ void dumpKeyInfo(uint256 privkey) printf(" * secret (base58): %s\n", bsecret.ToString().c_str()); CKey key; key.SetSecret(secret, fCompressed); - vector vchPubKey = key.GetPubKey(); + std::vector vchPubKey = key.GetPubKey(); printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str()); printf(" * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str()); } @@ -111,12 +110,12 @@ BOOST_AUTO_TEST_CASE(key_test1) for (int n=0; n<16; n++) { - string strMsg = strprintf("Very secret message %i: 11", n); + std::string strMsg = strprintf("Very secret message %i: 11", n); uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); // normal signatures - vector sign1, sign2, sign1C, sign2C; + std::vector sign1, sign2, sign1C, sign2C; BOOST_CHECK(key1.Sign (hashMsg, sign1)); BOOST_CHECK(key2.Sign (hashMsg, sign2)); @@ -145,7 +144,7 @@ BOOST_AUTO_TEST_CASE(key_test1) // compact signatures (with key recovery) - vector csign1, csign2, csign1C, csign2C; + std::vector csign1, csign2, csign1C, csign2C; BOOST_CHECK(key1.SignCompact (hashMsg, csign1)); BOOST_CHECK(key2.SignCompact (hashMsg, csign2)); @@ -168,7 +167,7 @@ BOOST_AUTO_TEST_CASE(key_test1) // test deterministic signing std::vector detsig, detsigc; - string strMsg = "Very deterministic message"; + std::string strMsg = "Very deterministic message"; uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); BOOST_CHECK(key1.Sign(hashMsg, detsig)); BOOST_CHECK(key1C.Sign(hashMsg, detsigc)); diff --git a/src/test/libzerocoin_tests.cpp b/src/test/libzerocoin_tests.cpp index fb1fb547b9dc..a0452c0654c8 100644 --- a/src/test/libzerocoin_tests.cpp +++ b/src/test/libzerocoin_tests.cpp @@ -26,8 +26,6 @@ #include "libzerocoin/Accumulator.h" #include "test_pivx.h" -using namespace std; -using namespace libzerocoin; #define COLOR_STR_GREEN "\033[32m" #define COLOR_STR_NORMAL "\033[0m" @@ -46,31 +44,31 @@ uint32_t gCoinSize = 0; uint32_t gSerialNumberSize = 0; // Global coin array -PrivateCoin *gCoins[TESTS_COINS_TO_ACCUMULATE]; +libzerocoin::PrivateCoin *gCoins[TESTS_COINS_TO_ACCUMULATE]; // Global params -ZerocoinParams *g_Params; +libzerocoin::ZerocoinParams *g_Params; ////////// // Utility routines ////////// void -LogTestResult(string testName, bool (*testPtr)()) +LogTestResult(std::string testName, bool (*testPtr)()) { - string colorGreen(COLOR_STR_GREEN); - string colorNormal(COLOR_STR_NORMAL); - string colorRed(COLOR_STR_RED); + std::string colorGreen(COLOR_STR_GREEN); + std::string colorNormal(COLOR_STR_NORMAL); + std::string colorRed(COLOR_STR_RED); - cout << "Testing if " << testName << "..." << endl; + std::cout << "Testing if " << testName << "..." << std::endl; bool testResult = testPtr(); if (testResult == true) { - cout << "\t" << colorGreen << "[PASS]" << colorNormal << endl; + std::cout << "\t" << colorGreen << "[PASS]" << colorNormal << std::endl; gSuccessfulTests++; } else { - cout << colorRed << "\t[FAIL]" << colorNormal << endl; + std::cout << colorRed << "\t[FAIL]" << colorNormal << std::endl; } gNumTests++; @@ -154,14 +152,14 @@ bool Test_GenerateGroupParams() { uint32_t pLen = 1024, qLen = 256, count; - IntegerGroupParams group; + libzerocoin::IntegerGroupParams group; for (count = 0; count < 1; count++) { try { - group = deriveIntegerGroupParams(calculateSeed(GetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen); + group = libzerocoin::deriveIntegerGroupParams(libzerocoin::calculateSeed(GetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen); } catch (std::runtime_error e) { - cout << "Caught exception " << e.what() << endl; + std::cout << "Caught exception " << e.what() << std::endl; return false; } @@ -171,7 +169,7 @@ Test_GenerateGroupParams() } CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus); - //cout << "g^q mod p = " << c << endl; + //cout << "g^q mod p = " << c << std::endl; if (!(c.isOne())) return false; // Try at multiple parameter sizes @@ -189,9 +187,9 @@ Test_ParamGen() try { // Instantiating testParams runs the parameter generation code - ZerocoinParams testParams(GetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL); - } catch (runtime_error e) { - cout << e.what() << endl; + libzerocoin::ZerocoinParams testParams(GetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL); + } catch (std::runtime_error e) { + std::cout << e.what() << std::endl; result = false; } @@ -208,11 +206,11 @@ Test_Accumulator() } try { // Accumulate the coin list from first to last into one accumulator - Accumulator accOne(&g_Params->accumulatorParams, CoinDenomination::ZQ_ONE); - Accumulator accTwo(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE); - Accumulator accThree(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE); - Accumulator accFour(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE); - AccumulatorWitness wThree(g_Params, accThree, gCoins[0]->getPublicCoin()); + libzerocoin::Accumulator accOne(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::Accumulator accTwo(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::Accumulator accThree(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::Accumulator accFour(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::AccumulatorWitness wThree(g_Params, accThree, gCoins[0]->getPublicCoin()); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { accOne += gCoins[i]->getPublicCoin(); @@ -226,18 +224,18 @@ Test_Accumulator() // Compare the accumulated results if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) { - cout << "Accumulators don't match" << endl; + std::cout << "Accumulators don't match" << std::endl; return false; } if(accFour.getValue() != wThree.getValue()) { - cout << "Witness math not working," << endl; + std::cout << "Witness math not working," << std::endl; return false; } // Verify that the witness is correct if (!wThree.VerifyWitness(accThree, gCoins[0]->getPublicCoin()) ) { - cout << "Witness not valid" << endl; + std::cout << "Witness not valid" << std::endl; return false; } @@ -246,14 +244,14 @@ Test_Accumulator() ss << accOne; // Deserialize it into a new object - Accumulator newAcc(g_Params, ss); + libzerocoin::Accumulator newAcc(g_Params, ss); // Compare the results if (accOne.getValue() != newAcc.getValue()) { return false; } - } catch (runtime_error e) { + } catch (std::runtime_error e) { return false; } @@ -271,13 +269,13 @@ Test_EqualityPoK() // Manufacture two commitments to "val", both // under different sets of parameters - Commitment one(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, val); + libzerocoin::Commitment one(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, val); - Commitment two(&g_Params->serialNumberSoKCommitmentGroup, val); + libzerocoin::Commitment two(&g_Params->serialNumberSoKCommitmentGroup, val); // Now generate a proof of knowledge that "one" and "two" are // both commitments to the same value - CommitmentProofOfKnowledge pok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, + libzerocoin::CommitmentProofOfKnowledge pok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, &g_Params->serialNumberSoKCommitmentGroup, one, two); @@ -286,7 +284,7 @@ Test_EqualityPoK() ss << pok; // Deserialize back into a PoK object - CommitmentProofOfKnowledge newPok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, + libzerocoin::CommitmentProofOfKnowledge newPok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, &g_Params->serialNumberSoKCommitmentGroup, ss); @@ -300,7 +298,7 @@ Test_EqualityPoK() // This time tamper with it, then deserialize it back into a PoK ss2[15] = 0; - CommitmentProofOfKnowledge newPok2(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, + libzerocoin::CommitmentProofOfKnowledge newPok2(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, &g_Params->serialNumberSoKCommitmentGroup, ss2); @@ -309,7 +307,7 @@ Test_EqualityPoK() return false; } - } catch (runtime_error &e) { + } catch (std::runtime_error &e) { return false; } } @@ -325,9 +323,9 @@ Test_MintCoin() try { // Generate a list of coins for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - gCoins[i] = new PrivateCoin(g_Params,libzerocoin::CoinDenomination::ZQ_ONE); + gCoins[i] = new libzerocoin::PrivateCoin(g_Params,libzerocoin::CoinDenomination::ZQ_ONE); - PublicCoin pc = gCoins[i]->getPublicCoin(); + libzerocoin::PublicCoin pc = gCoins[i]->getPublicCoin(); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pc; gCoinSize += ss.size(); @@ -335,7 +333,7 @@ Test_MintCoin() gCoinSize /= TESTS_COINS_TO_ACCUMULATE; - } catch (exception &e) { + } catch (std::exception &e) { return false; } @@ -354,19 +352,19 @@ bool Test_InvalidCoin() if (!coinValue.isPrime()) break; } - PublicCoin pubCoin(g_Params); + libzerocoin::PublicCoin pubCoin(g_Params); if (pubCoin.validate()) { // A blank coin should not be valid! return false; } - PublicCoin pubCoin2(g_Params, coinValue, ZQ_ONE); + libzerocoin::PublicCoin pubCoin2(g_Params, coinValue, libzerocoin::ZQ_ONE); if (pubCoin2.validate()) { // A non-prime coin should not be valid! return false; } - PublicCoin pubCoin3 = pubCoin2; + libzerocoin::PublicCoin pubCoin3 = pubCoin2; if (pubCoin2.validate()) { // A copy of a non-prime coin should not be valid! return false; @@ -375,14 +373,14 @@ bool Test_InvalidCoin() // Serialize and deserialize the coin CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pubCoin; - PublicCoin pubCoin4(g_Params, ss); + libzerocoin::PublicCoin pubCoin4(g_Params, ss); if (pubCoin4.validate()) { // A deserialized copy of a non-prime coin should not be valid! return false; } - } catch (runtime_error &e) { - cout << "Caught exception: " << e.what() << endl; + } catch (std::runtime_error &e) { + std::cout << "Caught exception: " << e.what() << std::endl; return false; } @@ -406,8 +404,8 @@ Test_MintAndSpend() // Accumulate the list of generated coins into a fresh accumulator. // The first one gets marked as accumulated for a witness, the // others just get accumulated normally. - Accumulator acc(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE); - AccumulatorWitness wAcc(g_Params, acc, gCoins[0]->getPublicCoin()); + libzerocoin::Accumulator acc(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::AccumulatorWitness wAcc(g_Params, acc, gCoins[0]->getPublicCoin()); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { acc += gCoins[i]->getPublicCoin(); @@ -418,16 +416,16 @@ Test_MintAndSpend() //SpendMetaData m(1,1); CDataStream cc(SER_NETWORK, PROTOCOL_VERSION); cc << *gCoins[0]; - PrivateCoin myCoin(g_Params,cc); + libzerocoin::PrivateCoin myCoin(g_Params,cc); - CoinSpend spend(g_Params, g_Params, myCoin, acc, 0, wAcc, 0, SpendType::SPEND); + libzerocoin::CoinSpend spend(g_Params, g_Params, myCoin, acc, 0, wAcc, 0, libzerocoin::SpendType::SPEND); spend.Verify(acc); // Serialize the proof and deserialize into newSpend CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << spend; gProofSize = ss.size(); - CoinSpend newSpend(g_Params, g_Params, ss); + libzerocoin::CoinSpend newSpend(g_Params, g_Params, ss); // See if we can verify the deserialized proof (return our result) bool ret = newSpend.Verify(acc); @@ -437,8 +435,8 @@ Test_MintAndSpend() gSerialNumberSize = ceil((double)serialNumber.bitSize() / 8.0); return ret; - } catch (runtime_error &e) { - cout << e.what() << endl; + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; return false; } @@ -449,7 +447,7 @@ void Test_RunAllTests() { // Make a new set of parameters from a random RSA modulus - g_Params = new ZerocoinParams(GetTestModulus()); + g_Params = new libzerocoin::ZerocoinParams(GetTestModulus()); gNumTests = gSuccessfulTests = gProofSize = 0; for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { @@ -467,13 +465,13 @@ Test_RunAllTests() LogTestResult("the commitment equality PoK works", Test_EqualityPoK); LogTestResult("a minted coin can be spent", Test_MintAndSpend); - cout << endl << "Average coin size is " << gCoinSize << " bytes." << endl; - cout << "Serial number size is " << gSerialNumberSize << " bytes." << endl; - cout << "Spend proof size is " << gProofSize << " bytes." << endl; + std::cout << std::endl << "Average coin size is " << gCoinSize << " bytes." << std::endl; + std::cout << "Serial number size is " << gSerialNumberSize << " bytes." << std::endl; + std::cout << "Spend proof size is " << gProofSize << " bytes." << std::endl; // Summarize test results if (gSuccessfulTests < gNumTests) { - cout << endl << "ERROR: SOME TESTS FAILED" << endl; + std::cout << std::endl << "ERROR: SOME TESTS FAILED" << std::endl; } // Clear any generated coins @@ -481,14 +479,14 @@ Test_RunAllTests() delete gCoins[i]; } - cout << endl << gSuccessfulTests << " out of " << gNumTests << " tests passed." << endl << endl; + std::cout << std::endl << gSuccessfulTests << " out of " << gNumTests << " tests passed." << std::endl << std::endl; delete g_Params; } BOOST_FIXTURE_TEST_SUITE(libzerocoin, TestingSetup) BOOST_AUTO_TEST_CASE(libzerocoin_tests) { - cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " test utility." << endl << endl; + std::cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " test utility." << std::endl << std::endl; Test_RunAllTests(); } diff --git a/src/test/mruset_tests.cpp b/src/test/mruset_tests.cpp index c25f42ce906e..e54a0f2ffeac 100644 --- a/src/test/mruset_tests.cpp +++ b/src/test/mruset_tests.cpp @@ -15,7 +15,6 @@ #define NUM_TESTS 16 #define MAX_SIZE 100 -using namespace std; class mrutester { @@ -88,8 +87,8 @@ BOOST_AUTO_TEST_CASE(mruset_window) { mru.insert(permute(n)); - set tester; - for (int m=max(0,n-MAX_SIZE+1); m<=n; m++) + std::set tester; + for (int m=std::max(0,n-MAX_SIZE+1); m<=n; m++) tester.insert(permute(m)); BOOST_CHECK(mru == tester); diff --git a/src/test/multisig_tests.cpp b/src/test/multisig_tests.cpp index 19c1919237c0..70c1b3b69378 100644 --- a/src/test/multisig_tests.cpp +++ b/src/test/multisig_tests.cpp @@ -16,18 +16,15 @@ #include "wallet/wallet_ismine.h" #endif -#include #include -using namespace std; -using namespace boost::assign; -typedef vector valtype; +typedef std::vector valtype; BOOST_FIXTURE_TEST_SUITE(multisig_tests, TestingSetup) CScript -sign_multisig(CScript scriptPubKey, vector keys, CTransaction transaction, int whichIn) +sign_multisig(CScript scriptPubKey, std::vector keys, CTransaction transaction, int whichIn) { uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL); @@ -35,7 +32,7 @@ sign_multisig(CScript scriptPubKey, vector keys, CTransaction transaction, result << OP_0; // CHECKMULTISIG bug workaround for (const CKey &key : keys) { - vector vchSig; + std::vector vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; @@ -77,12 +74,13 @@ BOOST_AUTO_TEST_CASE(multisig_verify) txTo[i].vout[0].nValue = 1; } - vector keys; + std::vector keys; CScript s; // Test a AND b: keys.clear(); - keys += key[0],key[1]; // magic operator+= from boost.assign + keys.push_back(key[0]); + keys.push_back(key[1]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK(VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); @@ -90,13 +88,14 @@ BOOST_AUTO_TEST_CASE(multisig_verify) for (int i = 0; i < 4; i++) { keys.clear(); - keys += key[i]; + keys.push_back(key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err), strprintf("a&b 1: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); keys.clear(); - keys += key[1],key[i]; + keys.push_back(key[1]); + keys.push_back(key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err), strprintf("a&b 2: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); @@ -106,7 +105,7 @@ BOOST_AUTO_TEST_CASE(multisig_verify) for (int i = 0; i < 4; i++) { keys.clear(); - keys += key[i]; + keys.push_back(key[i]); s = sign_multisig(a_or_b, keys, txTo[1], 0); if (i == 0 || i == 1) { @@ -129,7 +128,8 @@ BOOST_AUTO_TEST_CASE(multisig_verify) for (int j = 0; j < 4; j++) { keys.clear(); - keys += key[i],key[j]; + keys.push_back(key[i]); + keys.push_back(key[j]); s = sign_multisig(escrow, keys, txTo[2], 0); if (i < j && i < 3 && j < 3) { @@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) partialkeystore.AddKey(key[0]); { - vector solutions; + std::vector solutions; txnouttype whichType; CScript s; s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; @@ -219,7 +219,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) #endif } { - vector solutions; + std::vector solutions; txnouttype whichType; CScript s; s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; @@ -234,7 +234,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) #endif } { - vector solutions; + std::vector solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; @@ -249,13 +249,13 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) #endif } { - vector solutions; + std::vector solutions; txnouttype whichType; CScript s; s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); - vector addrs; + std::vector addrs; int nRequired; BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired)); BOOST_CHECK(addrs[0] == keyaddr[0]); @@ -268,7 +268,7 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) #endif } { - vector solutions; + std::vector solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; diff --git a/src/test/netbase_tests.cpp b/src/test/netbase_tests.cpp index 77947fd9ce5a..715e734657dc 100644 --- a/src/test/netbase_tests.cpp +++ b/src/test/netbase_tests.cpp @@ -11,7 +11,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup) @@ -48,9 +47,9 @@ BOOST_AUTO_TEST_CASE(netbase_properties) BOOST_CHECK(CNetAddr("127.0.0.1").IsValid()); } -bool static TestSplitHost(string test, string host, int port) +bool static TestSplitHost(std::string test, std::string host, int port) { - string hostOut; + std::string hostOut; int portOut = -1; SplitHostPort(test, portOut, hostOut); return hostOut == host && port == portOut; @@ -75,7 +74,7 @@ BOOST_AUTO_TEST_CASE(netbase_splithost) BOOST_CHECK(TestSplitHost("", "", -1)); } -bool static TestParse(string src, string canon) +bool static TestParse(std::string src, std::string canon) { CService addr; if (!LookupNumeric(src.c_str(), addr, 65535)) diff --git a/src/test/pmt_tests.cpp b/src/test/pmt_tests.cpp index 9946736caa0f..b11dbb2d9d52 100644 --- a/src/test/pmt_tests.cpp +++ b/src/test/pmt_tests.cpp @@ -15,7 +15,6 @@ #include -using namespace std; class CPartialMerkleTreeTester : public CPartialMerkleTree { diff --git a/src/test/rpc_tests.cpp b/src/test/rpc_tests.cpp index 05bddca3f2ce..c9369e398ec8 100644 --- a/src/test/rpc_tests.cpp +++ b/src/test/rpc_tests.cpp @@ -17,7 +17,6 @@ #include -using namespace std; UniValue createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL) @@ -31,11 +30,11 @@ createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL) return result; } -UniValue CallRPC(string args) +UniValue CallRPC(std::string args) { - vector vArgs; + std::vector vArgs; boost::split(vArgs, args, boost::is_any_of(" \t")); - string strMethod = vArgs[0]; + std::string strMethod = vArgs[0]; vArgs.erase(vArgs.begin()); UniValue params = RPCConvertValues(strMethod, vArgs); @@ -45,7 +44,7 @@ UniValue CallRPC(string args) return result; } catch (const UniValue& objError) { - throw runtime_error(find_value(objError, "message").get_str()); + throw std::runtime_error(find_value(objError, "message").get_str()); } } @@ -57,58 +56,58 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams) // Test raw transaction API argument handling UniValue r; - BOOST_CHECK_THROW(CallRPC("getrawtransaction"), runtime_error); - BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), runtime_error); - BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), runtime_error); + BOOST_CHECK_THROW(CallRPC("getrawtransaction"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), std::runtime_error); - BOOST_CHECK_THROW(CallRPC("createrawtransaction"), runtime_error); - BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), runtime_error); - BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), runtime_error); - BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), runtime_error); - BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), runtime_error); + BOOST_CHECK_THROW(CallRPC("createrawtransaction"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}")); - BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), runtime_error); + BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), std::runtime_error); - BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), runtime_error); - BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), runtime_error); - BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), runtime_error); - string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000"; - BOOST_CHECK_NO_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx)); + BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), std::runtime_error); + std::string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000"; + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0); - BOOST_CHECK_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx+" extra"), runtime_error); + BOOST_CHECK_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" extra"), std::runtime_error); - BOOST_CHECK_THROW(CallRPC("signrawtransaction"), runtime_error); - BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), runtime_error); - BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), runtime_error); - BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx)); - BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY")); - BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY")); - BOOST_CHECK_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null badenum"), runtime_error); + BOOST_CHECK_THROW(CallRPC("signrawtransaction"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), std::runtime_error); + BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx)); + BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY")); + BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY")); + BOOST_CHECK_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" null null badenum"), std::runtime_error); // Only check failure cases for sendrawtransaction, there's no network to send to... - BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), runtime_error); - BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), runtime_error); - BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), runtime_error); - BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error); + BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC(std::string("sendrawtransaction ")+rawtx+" extra"), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_rawsign) { UniValue r; // input is a 1-of-2 multisig (so is output): - string prevout = + std::string prevout = "[{\"txid\":\"dd2888870cdc3f6e92661f6b0829667ee4bb07ed086c44205e726bbf3338f726\"," "\"vout\":1,\"scriptPubKey\":\"a914f5404a39a4799d8710e15db4c4512c5e06f97fed87\"," "\"redeemScript\":\"5121021431a18c7039660cd9e3612a2a47dc53b69cb38ea4ad743b7df8245fd0438f8e21029bbeff390ce736bd396af43b52a1c14ed52c086b1e5585c15931f68725772bac52ae\"}]"; - r = CallRPC(string("createrawtransaction ")+prevout+" "+ + r = CallRPC(std::string("createrawtransaction ")+prevout+" "+ "{\"6ckcNMWRYgTnPcrTXCdwhDnMLwj3zwseej\":1}"); - string notsigned = r.get_str(); - string privkey1 = "\"YVobcS47fr6kceZy9LzLJR8WQ6YRpUwYKoJhrnEXepebMxaSpbnn\""; - string privkey2 = "\"YRyMjG8hbm8jHeDMAfrzSeHq5GgAj7kuHFvJtMudCUH3sCkq1WtA\""; - r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]"); + std::string notsigned = r.get_str(); + std::string privkey1 = "\"YVobcS47fr6kceZy9LzLJR8WQ6YRpUwYKoJhrnEXepebMxaSpbnn\""; + std::string privkey2 = "\"YRyMjG8hbm8jHeDMAfrzSeHq5GgAj7kuHFvJtMudCUH3sCkq1WtA\""; + r = CallRPC(std::string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false); - r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); + r = CallRPC(std::string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true); } @@ -186,23 +185,23 @@ BOOST_AUTO_TEST_CASE(json_parse_errors) BOOST_AUTO_TEST_CASE(rpc_ban) { - BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); UniValue r; - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0 add"))); - BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.0.0:8334")), runtime_error); //portnumber for setban not allowed - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0 add"))); + BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.0:8334")), std::runtime_error); //portnumber for setban not allowed + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); UniValue ar = r.get_array(); UniValue o1 = ar[0].get_obj(); UniValue adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/32"); - BOOST_CHECK_NO_THROW(CallRPC(string("setban 127.0.0.0 remove")));; - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0 remove")));; + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/24 add 1607731200 true"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 1607731200 true"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); @@ -210,10 +209,10 @@ BOOST_AUTO_TEST_CASE(rpc_ban) BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24"); BOOST_CHECK_EQUAL(banned_until.get_int64(), 1607731200); // absolute time check - BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/24 add 200"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 200"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); @@ -224,42 +223,42 @@ BOOST_AUTO_TEST_CASE(rpc_ban) BOOST_CHECK(banned_until.get_int64()-now <= 200); // must throw an exception because 127.0.0.1 is in already banned suubnet range - BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.0.1 add")), runtime_error); + BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.1 add")), std::runtime_error); - BOOST_CHECK_NO_THROW(CallRPC(string("setban 127.0.0.0/24 remove")));; - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0/24 remove")));; + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 127.0.0.0/255.255.0.0 add"))); - BOOST_CHECK_THROW(r = CallRPC(string("setban 127.0.1.1 add")), runtime_error); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/255.255.0.0 add"))); + BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.1.1 add")), std::runtime_error); - BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); - BOOST_CHECK_THROW(r = CallRPC(string("setban test add")), runtime_error); //invalid IP + BOOST_CHECK_THROW(r = CallRPC(std::string("setban test add")), std::runtime_error); //invalid IP //IPv6 tests - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "fe80::202:b3ff:fe1e:8329/128"); - BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "2001:db8::/30"); - BOOST_CHECK_NO_THROW(CallRPC(string("clearbanned"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add"))); - BOOST_CHECK_NO_THROW(r = CallRPC(string("listbanned"))); + BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add"))); + BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); diff --git a/src/test/rpc_wallet_tests.cpp b/src/test/rpc_wallet_tests.cpp index bb66b50d0666..6c23d320b52a 100644 --- a/src/test/rpc_wallet_tests.cpp +++ b/src/test/rpc_wallet_tests.cpp @@ -16,10 +16,9 @@ #include -using namespace std; extern UniValue createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL); -extern UniValue CallRPC(string args); +extern UniValue CallRPC(std::string args); extern CWallet* pwalletMain; @@ -50,18 +49,18 @@ BOOST_AUTO_TEST_CASE(rpc_addmultisig) address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); - BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error); - BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error); - BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(0), false), std::runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(1), false), std::runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), std::runtime_error); - BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error); - BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), std::runtime_error); + BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), std::runtime_error); - string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing - BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error); + std::string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing + BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), std::runtime_error); - string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing - BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error); + std::string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing + BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet) @@ -74,8 +73,8 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) CPubKey demoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); UniValue retValue; - string strAccount = "walletDemoAccount"; - string strPurpose = "receive"; + std::string strAccount = "walletDemoAccount"; + std::string strPurpose = "receive"; BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */ CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; @@ -92,19 +91,19 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) *********************************/ BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount")); /* D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R is not owned by the test wallet. */ - BOOST_CHECK_THROW(CallRPC("setaccount D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R nullaccount"), runtime_error); - BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error); + BOOST_CHECK_THROW(CallRPC("setaccount D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R nullaccount"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("setaccount"), std::runtime_error); /* D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 (33 chars) is an illegal address (should be 34 chars) */ - BOOST_CHECK_THROW(CallRPC("setaccount D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 nullaccount"), runtime_error); + BOOST_CHECK_THROW(CallRPC("setaccount D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 nullaccount"), std::runtime_error); /********************************* * listunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listunspent")); - BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error); - BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error); - BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error); - BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent string"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), std::runtime_error); BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []")); BOOST_CHECK(r.get_array().empty()); @@ -113,20 +112,20 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0")); - BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error); - BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true")); - BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), std::runtime_error); /********************************* * listreceivedbyaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0")); - BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error); - BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true")); - BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error); + BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), std::runtime_error); /********************************* * getrawchangeaddress @@ -150,22 +149,22 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) /********************************* * getaccount *********************************/ - BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error); + BOOST_CHECK_THROW(CallRPC("getaccount"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString())); /********************************* * signmessage + verifymessage *********************************/ BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage")); - BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error); + BOOST_CHECK_THROW(CallRPC("signmessage"), std::runtime_error); /* Should throw error because this address is not loaded in the wallet */ - BOOST_CHECK_THROW(CallRPC("signmessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R mymessage"), runtime_error); + BOOST_CHECK_THROW(CallRPC("signmessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R mymessage"), std::runtime_error); /* missing arguments */ - BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error); - BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error); + BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), std::runtime_error); + BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), std::runtime_error); /* Illegal address */ - BOOST_CHECK_THROW(CallRPC("verifymessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 " + retValue.get_str() + " mymessage"), runtime_error); + BOOST_CHECK_THROW(CallRPC("verifymessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5 " + retValue.get_str() + " mymessage"), std::runtime_error); /* wrong address */ BOOST_CHECK(CallRPC("verifymessage D8w12Vu3WVhn543dgrUUf9uYu6HLwnPm5R " + retValue.get_str() + " mymessage").get_bool() == false); /* Correct address and signature but wrong message */ @@ -176,7 +175,7 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) /********************************* * getaddressesbyaccount *********************************/ - BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error); + BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), std::runtime_error); BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount)); UniValue arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); diff --git a/src/test/script_P2SH_tests.cpp b/src/test/script_P2SH_tests.cpp index 15cd22fda869..48907af0bf14 100644 --- a/src/test/script_P2SH_tests.cpp +++ b/src/test/script_P2SH_tests.cpp @@ -18,7 +18,6 @@ #include -using namespace std; // Helpers: static std::vector @@ -80,7 +79,7 @@ BOOST_AUTO_TEST_CASE(sign) } CMutableTransaction txFrom; // Funding transaction: - string reason; + std::string reason; txFrom.vout.resize(8); for (int i = 0; i < 4; i++) { @@ -178,7 +177,7 @@ BOOST_AUTO_TEST_CASE(set) } CMutableTransaction txFrom; // Funding transaction: - string reason; + std::string reason; txFrom.vout.resize(4); for (int i = 0; i < 4; i++) { @@ -265,7 +264,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard) CCoinsViewCache coins(&coinsDummy); CBasicKeyStore keystore; CKey key[6]; - vector keys; + std::vector keys; for (int i = 0; i < 6; i++) { key[i].MakeNewKey(true); @@ -337,8 +336,8 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard) // SignSignature doesn't know how to sign these. We're // not testing validating signatures, so just create // dummy signatures that DO include the correct P2SH scripts: - txTo.vin[3].scriptSig << OP_11 << OP_11 << static_cast >(oneAndTwo); - txTo.vin[4].scriptSig << static_cast >(fifteenSigops); + txTo.vin[3].scriptSig << OP_11 << OP_11 << static_cast >(oneAndTwo); + txTo.vin[4].scriptSig << static_cast >(fifteenSigops); BOOST_CHECK(::AreInputsStandard(txTo, coins)); // 22 P2SH sigops for all inputs (1 for vin[0], 6 for vin[3], 15 for vin[4] @@ -360,7 +359,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard) txToNonStd1.vin.resize(1); txToNonStd1.vin[0].prevout.n = 5; txToNonStd1.vin[0].prevout.hash = txFrom.GetHash(); - txToNonStd1.vin[0].scriptSig << static_cast >(sixteenSigops); + txToNonStd1.vin[0].scriptSig << static_cast >(sixteenSigops); BOOST_CHECK(!::AreInputsStandard(txToNonStd1, coins)); BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd1, coins), 16U); @@ -372,7 +371,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard) txToNonStd2.vin.resize(1); txToNonStd2.vin[0].prevout.n = 6; txToNonStd2.vin[0].prevout.hash = txFrom.GetHash(); - txToNonStd2.vin[0].scriptSig << static_cast >(twentySigops); + txToNonStd2.vin[0].scriptSig << static_cast >(twentySigops); BOOST_CHECK(!::AreInputsStandard(txToNonStd2, coins)); BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd2, coins), 20U); diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index feb10837dc6d..1c2d7b1c05f0 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -35,16 +35,14 @@ #include -using namespace std; -using namespace boost::algorithm; // Uncomment if you want to output updated JSON tests. // #define UPDATE_JSON_TESTS static const unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; -unsigned int ParseScriptFlags(string strFlags); -string FormatScriptFlags(unsigned int flags); +unsigned int ParseScriptFlags(std::string strFlags); +std::string FormatScriptFlags(unsigned int flags); UniValue read_json(const std::string& jsondata) @@ -625,7 +623,7 @@ BOOST_AUTO_TEST_CASE(script_valid) for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; - string strTest = test.write(); + std::string strTest = test.write(); if (test.size() < 3) // Allow size > 3; extra stuff ignored (useful for comments) { if (test.size() != 1) { @@ -633,9 +631,9 @@ BOOST_AUTO_TEST_CASE(script_valid) } continue; } - string scriptSigString = test[0].get_str(); + std::string scriptSigString = test[0].get_str(); CScript scriptSig = ParseScript(scriptSigString); - string scriptPubKeyString = test[1].get_str(); + std::string scriptPubKeyString = test[1].get_str(); CScript scriptPubKey = ParseScript(scriptPubKeyString); unsigned int scriptflags = ParseScriptFlags(test[2].get_str()); @@ -650,7 +648,7 @@ BOOST_AUTO_TEST_CASE(script_invalid) for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; - string strTest = test.write(); + std::string strTest = test.write(); if (test.size() < 3) // Allow size > 3; extra stuff ignored (useful for comments) { if (test.size() != 1) { @@ -658,9 +656,9 @@ BOOST_AUTO_TEST_CASE(script_invalid) } continue; } - string scriptSigString = test[0].get_str(); + std::string scriptSigString = test[0].get_str(); CScript scriptSig = ParseScript(scriptSigString); - string scriptPubKeyString = test[1].get_str(); + std::string scriptPubKeyString = test[1].get_str(); CScript scriptPubKey = ParseScript(scriptPubKeyString); unsigned int scriptflags = ParseScriptFlags(test[2].get_str()); @@ -678,21 +676,21 @@ BOOST_AUTO_TEST_CASE(script_PushData) static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a }; ScriptError err; - vector > directStack; + std::vector > directStack; BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), true, BaseSignatureChecker(), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); - vector > pushdata1Stack; + std::vector > pushdata1Stack; BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), true, BaseSignatureChecker(), &err)); BOOST_CHECK(pushdata1Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); - vector > pushdata2Stack; + std::vector > pushdata2Stack; BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), true, BaseSignatureChecker(), &err)); BOOST_CHECK(pushdata2Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); - vector > pushdata4Stack; + std::vector > pushdata4Stack; BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), true, BaseSignatureChecker(), &err)); BOOST_CHECK(pushdata4Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); @@ -715,7 +713,7 @@ sign_multisig(CScript scriptPubKey, std::vector keys, CTransaction transac result << OP_0; for (const CKey &key : keys) { - vector vchSig; + std::vector vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; @@ -833,8 +831,8 @@ BOOST_AUTO_TEST_CASE(script_combineSigs) { // Test the CombineSignatures function CBasicKeyStore keystore; - vector keys; - vector pubkeys; + std::vector keys; + std::vector pubkeys; for (int i = 0; i < 3; i++) { CKey key; @@ -879,7 +877,7 @@ BOOST_AUTO_TEST_CASE(script_combineSigs) combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig); // dummy scriptSigCopy with placeholder, should always choose non-placeholder: - scriptSigCopy = CScript() << OP_0 << static_cast >(pkSingle); + scriptSigCopy = CScript() << OP_0 << static_cast >(pkSingle); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig); BOOST_CHECK(combined == scriptSig); combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy); @@ -895,15 +893,15 @@ BOOST_AUTO_TEST_CASE(script_combineSigs) BOOST_CHECK(combined == scriptSig); // A couple of partially-signed versions: - vector sig1; + std::vector sig1; uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL); BOOST_CHECK(keys[0].Sign(hash1, sig1)); sig1.push_back(SIGHASH_ALL); - vector sig2; + std::vector sig2; uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE); BOOST_CHECK(keys[1].Sign(hash2, sig2)); sig2.push_back(SIGHASH_NONE); - vector sig3; + std::vector sig3; uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE); BOOST_CHECK(keys[2].Sign(hash3, sig3)); sig3.push_back(SIGHASH_SINGLE); diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp index c97f43c93420..554d394d9413 100644 --- a/src/test/serialize_tests.cpp +++ b/src/test/serialize_tests.cpp @@ -11,7 +11,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(serialize_tests, BasicTestingSetup) @@ -50,7 +49,7 @@ BOOST_AUTO_TEST_CASE(varints) BOOST_AUTO_TEST_CASE(compactsize) { CDataStream ss(SER_DISK, 0); - vector::size_type i, j; + std::vector::size_type i, j; for (i = 1; i <= MAX_SIZE; i *= 2) { @@ -83,7 +82,7 @@ BOOST_AUTO_TEST_CASE(noncanonical) // Write some non-canonical CompactSize encodings, and // make sure an exception is thrown when read back. CDataStream ss(SER_DISK, 0); - vector::size_type n; + std::vector::size_type n; // zero encoded with three bytes: ss.write("\xfd\x00\x00", 3); diff --git a/src/test/sigopcount_tests.cpp b/src/test/sigopcount_tests.cpp index 22886f9ad2a3..dce3ca9f7f5c 100644 --- a/src/test/sigopcount_tests.cpp +++ b/src/test/sigopcount_tests.cpp @@ -14,7 +14,6 @@ #include -using namespace std; // Helpers: static std::vector diff --git a/src/test/timedata_tests.cpp b/src/test/timedata_tests.cpp index 29d8da894ced..844c2b4f6ded 100644 --- a/src/test/timedata_tests.cpp +++ b/src/test/timedata_tests.cpp @@ -7,7 +7,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(timedata_tests, BasicTestingSetup) diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index ace04ffa3cfb..fad229023944 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -27,35 +27,33 @@ #include -using namespace std; -using namespace boost::algorithm; // In script_tests.cpp extern UniValue read_json(const std::string& jsondata); -static std::map mapFlagNames = boost::assign::map_list_of - (string("NONE"), (unsigned int)SCRIPT_VERIFY_NONE) - (string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH) - (string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC) - (string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG) - (string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S) - (string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY) - (string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA) - (string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY) - (string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) - (string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK) - (string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY); - -unsigned int ParseScriptFlags(string strFlags) +static std::map mapFlagNames = boost::assign::map_list_of + (std::string("NONE"), (unsigned int)SCRIPT_VERIFY_NONE) + (std::string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH) + (std::string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC) + (std::string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG) + (std::string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S) + (std::string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY) + (std::string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA) + (std::string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY) + (std::string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) + (std::string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK) + (std::string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY); + +unsigned int ParseScriptFlags(std::string strFlags) { if (strFlags.empty()) { return 0; } unsigned int flags = 0; - vector words; - split(words, strFlags, is_any_of(",")); + std::vector words; + boost::algorithm::split(words, strFlags, boost::algorithm::is_any_of(",")); - for (string word : words) + for (std::string word : words) { if (!mapFlagNames.count(word)) BOOST_ERROR("Bad test: unknown verification flag '" << word << "'"); @@ -65,13 +63,13 @@ unsigned int ParseScriptFlags(string strFlags) return flags; } -string FormatScriptFlags(unsigned int flags) +std::string FormatScriptFlags(unsigned int flags) { if (flags == 0) { return ""; } - string ret; - std::map::const_iterator it = mapFlagNames.begin(); + std::string ret; + std::map::const_iterator it = mapFlagNames.begin(); while (it != mapFlagNames.end()) { if (flags & it->second) { ret += it->first + ","; @@ -97,7 +95,7 @@ BOOST_AUTO_TEST_CASE(tx_valid) ScriptError err; for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; - string strTest = test.write(); + std::string strTest = test.write(); if (test[0].isArray()) { if (test.size() != 3 || !test[1].isStr() || !test[2].isStr()) @@ -106,7 +104,7 @@ BOOST_AUTO_TEST_CASE(tx_valid) continue; } - map mapprevOutScriptPubKeys; + std::map mapprevOutScriptPubKeys; UniValue inputs = test[0].get_array(); bool fValid = true; for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) { @@ -131,7 +129,7 @@ BOOST_AUTO_TEST_CASE(tx_valid) continue; } - string transaction = test[1].get_str(); + std::string transaction = test[1].get_str(); CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; @@ -172,7 +170,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) ScriptError err; for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; - string strTest = test.write(); + std::string strTest = test.write(); if (test[0].isArray()) { if (test.size() != 3 || !test[1].isStr() || !test[2].isStr()) @@ -181,7 +179,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) continue; } - map mapprevOutScriptPubKeys; + std::map mapprevOutScriptPubKeys; UniValue inputs = test[0].get_array(); bool fValid = true; for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) { @@ -206,7 +204,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) continue; } - string transaction = test[1].get_str(); + std::string transaction = test[1].get_str(); CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; @@ -236,7 +234,7 @@ BOOST_AUTO_TEST_CASE(basic_transaction_tests) { // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436) unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00}; - vector vch(ch, ch + sizeof(ch) -1); + std::vector vch(ch, ch + sizeof(ch) -1); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); CMutableTransaction tx; stream >> tx; @@ -339,7 +337,7 @@ BOOST_AUTO_TEST_CASE(test_IsStandard) key.MakeNewKey(true); t.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); - string reason; + std::string reason; BOOST_CHECK(IsStandardTx(t, reason)); t.vout[0].nValue = 5011; // dust diff --git a/src/test/tutorial_zerocoin.cpp b/src/test/tutorial_zerocoin.cpp index 3433d6cc5ff9..ace7bd60c6ec 100644 --- a/src/test/tutorial_zerocoin.cpp +++ b/src/test/tutorial_zerocoin.cpp @@ -26,7 +26,6 @@ #include "libzerocoin/Accumulator.h" #include "test_pivx.h" -using namespace std; #define COINS_TO_ACCUMULATE 5 #define DUMMY_TRANSACTION_HASH 0 // in real life these would be uint256 hashes @@ -49,236 +48,236 @@ using namespace std; bool ZerocoinTutorial() { - // The following simple code illustrates the call flow for Zerocoin - // applications. In a real currency network these operations would - // be split between individual payers/payees, network nodes and miners. - // - // For each call we specify the participant who would use it. - - // Zerocoin uses exceptions (based on the runtime_error class) - // to indicate all sorts of problems. Always remember to catch them! - - try { - - /********************************************************************/ - // What is it: Parameter loading - // Who does it: ALL ZEROCOIN PARTICIPANTS - // What it does: Loads a trusted Zerocoin modulus "N" and - // generates all associated parameters from it. - // We use a hardcoded "N" that we generated using - // the included 'paramgen' utility. - /********************************************************************/ - - // Load a test modulus from our hardcoded string (above) - CBigNum testModulus; - testModulus.SetHex(std::string(TUTORIAL_TEST_MODULUS)); - - // Set up the Zerocoin Params object - libzerocoin::ZerocoinParams* params = new libzerocoin::ZerocoinParams(testModulus); - - cout << "Successfully loaded parameters." << endl; - - /********************************************************************/ - // What is it: Coin generation - // Who does it: ZEROCOIN CLIENTS - // What it does: Generates a new 'zerocoin' coin using the - // public parameters. Once generated, the client - // will transmit the public portion of this coin - // in a ZEROCOIN_MINT transaction. The inputs - // to this transaction must add up to the zerocoin - // denomination plus any transaction fees. - /********************************************************************/ - - // The following constructor does all the work of minting a brand - // new zerocoin. It stores all the private values inside the - // PrivateCoin object. This includes the coin secrets, which must be - // stored in a secure location (wallet) at the client. + // The following simple code illustrates the call flow for Zerocoin + // applications. In a real currency network these operations would + // be split between individual payers/payees, network nodes and miners. + // + // For each call we specify the participant who would use it. + + // Zerocoin uses exceptions (based on the std::runtime_error class) + // to indicate all sorts of problems. Always remember to catch them! + + try { + + /********************************************************************/ + // What is it: Parameter loading + // Who does it: ALL ZEROCOIN PARTICIPANTS + // What it does: Loads a trusted Zerocoin modulus "N" and + // generates all associated parameters from it. + // We use a hardcoded "N" that we generated using + // the included 'paramgen' utility. + /********************************************************************/ + + // Load a test modulus from our hardcoded string (above) + CBigNum testModulus; + testModulus.SetHex(std::string(TUTORIAL_TEST_MODULUS)); + + // Set up the Zerocoin Params object + libzerocoin::ZerocoinParams* params = new libzerocoin::ZerocoinParams(testModulus); + + std::cout << "Successfully loaded parameters." << std::endl; + + /********************************************************************/ + // What is it: Coin generation + // Who does it: ZEROCOIN CLIENTS + // What it does: Generates a new 'zerocoin' coin using the + // public parameters. Once generated, the client + // will transmit the public portion of this coin + // in a ZEROCOIN_MINT transaction. The inputs + // to this transaction must add up to the zerocoin + // denomination plus any transaction fees. + /********************************************************************/ + + // The following constructor does all the work of minting a brand + // new zerocoin. It stores all the private values inside the + // PrivateCoin object. This includes the coin secrets, which must be + // stored in a secure location (wallet) at the client. libzerocoin::PrivateCoin newCoin(params, libzerocoin::CoinDenomination::ZQ_ONE); - // Get a copy of the 'public' portion of the coin. You should - // embed this into a Zerocoin 'MINT' transaction along with a series - // of currency inputs totaling the assigned value of one zerocoin. - libzerocoin::PublicCoin pubCoin = newCoin.getPublicCoin(); - - cout << "Successfully minted a zerocoin." << endl; - - // Serialize the public coin to a CDataStream object. - CDataStream serializedCoin(SER_NETWORK, PROTOCOL_VERSION); - serializedCoin << pubCoin; - - /********************************************************************/ - // What is it: Coin verification - // Who does it: TRANSACTION VERIFIERS - // What it does: Verifies the structure of a zerocoin obtained from - // a ZEROCOIN_MINT transaction. All coins must be - // verified before you operate on them. - // Note that this is only part of the transaction - // verification process! The client must also check - // that (1) the inputs to the transaction are valid - // and add up to the value of one zerocoin, (2) that - // this particular zerocoin has not been minted before. - /********************************************************************/ - - // Deserialize the public coin into a fresh object. - libzerocoin::PublicCoin pubCoinNew(params, serializedCoin); - - // Now make sure the coin is valid. - if (!pubCoinNew.validate()) { - // If this returns false, don't accept the coin for any purpose! - // Any ZEROCOIN_MINT with an invalid coin should NOT be - // accepted as a valid transaction in the block chain. - cout << "Error: coin is not valid!"; - } - - cout << "Deserialized and verified the coin." << endl; - - /********************************************************************/ - // What is it: Accumulator computation - // Who does it: ZEROCOIN CLIENTS & TRANSACTION VERIFIERS - // What it does: Collects a number of PublicCoin values drawn from - // the block chain and calculates an accumulator. - // This accumulator is incrementally computable; - // you can stop and serialize it at any point - // then continue accumulating new transactions. - // The accumulator is also order-independent, so - // the same coins can be accumulated in any order - // to give the same result. - // WARNING: do not accumulate the same coin twice! - /********************************************************************/ - - // Create an empty accumulator object + // Get a copy of the 'public' portion of the coin. You should + // embed this into a Zerocoin 'MINT' transaction along with a series + // of currency inputs totaling the assigned value of one zerocoin. + libzerocoin::PublicCoin pubCoin = newCoin.getPublicCoin(); + + std::cout << "Successfully minted a zerocoin." << std::endl; + + // Serialize the public coin to a CDataStream object. + CDataStream serializedCoin(SER_NETWORK, PROTOCOL_VERSION); + serializedCoin << pubCoin; + + /********************************************************************/ + // What is it: Coin verification + // Who does it: TRANSACTION VERIFIERS + // What it does: Verifies the structure of a zerocoin obtained from + // a ZEROCOIN_MINT transaction. All coins must be + // verified before you operate on them. + // Note that this is only part of the transaction + // verification process! The client must also check + // that (1) the inputs to the transaction are valid + // and add up to the value of one zerocoin, (2) that + // this particular zerocoin has not been minted before. + /********************************************************************/ + + // Deserialize the public coin into a fresh object. + libzerocoin::PublicCoin pubCoinNew(params, serializedCoin); + + // Now make sure the coin is valid. + if (!pubCoinNew.validate()) { + // If this returns false, don't accept the coin for any purpose! + // Any ZEROCOIN_MINT with an invalid coin should NOT be + // accepted as a valid transaction in the block chain. + std::cout << "Error: coin is not valid!"; + } + + std::cout << "Deserialized and verified the coin." << std::endl; + + /********************************************************************/ + // What is it: libzerocoin::Accumulator computation + // Who does it: ZEROCOIN CLIENTS & TRANSACTION VERIFIERS + // What it does: Collects a number of PublicCoin values drawn from + // the block chain and calculates an accumulator. + // This accumulator is incrementally computable; + // you can stop and serialize it at any point + // then continue accumulating new transactions. + // The accumulator is also order-independent, so + // the same coins can be accumulated in any order + // to give the same result. + // WARNING: do not accumulate the same coin twice! + /********************************************************************/ + + // Create an empty accumulator object libzerocoin::Accumulator accumulator(params,libzerocoin::CoinDenomination::ZQ_ONE); - // Add several coins to it (we'll generate them here on the fly). - for (uint32_t i = 0; i < COINS_TO_ACCUMULATE; i++) { + // Add several coins to it (we'll generate them here on the fly). + for (uint32_t i = 0; i < COINS_TO_ACCUMULATE; i++) { libzerocoin::PrivateCoin testCoin(params, libzerocoin::CoinDenomination::ZQ_ONE); - accumulator += testCoin.getPublicCoin(); - } - - // Serialize the accumulator object. - // - // If you're using Accumulator Checkpoints, each miner would - // start by deserializing the accumulator checkpoint from the - // previous block (or creating a new Accumulator if no previous - // block exists). It will then add all the coins in the new block, - // then serialize the resulting Accumulator object to obtain the - // new checkpoint. All block verifiers should do the same thing - // to check their work. - CDataStream serializedAccumulator(SER_NETWORK, PROTOCOL_VERSION); - serializedAccumulator << accumulator; - - // Deserialize the accumulator object - libzerocoin::Accumulator newAccumulator(params, serializedAccumulator); - - // We can now continue accumulating things into the accumulator - // we just deserialized. For example, let's put in the coin - // we generated up above. - newAccumulator += pubCoinNew; - - cout << "Successfully accumulated coins." << endl; - - /********************************************************************/ - // What is it: Coin spend - // Who does it: ZEROCOIN CLIENTS - // What it does: Create a new transaction that spends a Zerocoin. - // The user first authors a transaction specifying - // a set of destination addresses (outputs). They - // next compute an Accumulator over all coins in the - // block chain (see above) and a Witness based on the - // coin to be spent. Finally they instantiate a CoinSpend - // object that 'signs' the transaction with a special - // zero knowledge signature of knowledge over the coin - // data, Witness and Accumulator. - /********************************************************************/ - - // We are going to spend the coin "newCoin" that we generated at the - // top of this function. - // - // We'll use the accumulator we constructed above. This contains - // a set of coins, but does NOT include the coin "newCoin". - // - // To generate the witness, we start with this accumulator and - // add the public half of the coin we want to spend. - libzerocoin::AccumulatorWitness witness(params, accumulator, newCoin.getPublicCoin()); - - // Add the public half of "newCoin" to the Accumulator itself. - accumulator += newCoin.getPublicCoin(); - - // At this point we should generate a ZEROCOIN_SPEND transaction to - // send to the network. This network should include a set of outputs - // totalling to the value of one zerocoin (minus transaction fees). - - // Construct the CoinSpend object. This acts like a signature on the - // transaction. + accumulator += testCoin.getPublicCoin(); + } + + // Serialize the accumulator object. + // + // If you're using Accumulator Checkpoints, each miner would + // start by deserializing the accumulator checkpoint from the + // previous block (or creating a new Accumulator if no previous + // block exists). It will then add all the coins in the new block, + // then serialize the resulting Accumulator object to obtain the + // new checkpoint. All block verifiers should do the same thing + // to check their work. + CDataStream serializedAccumulator(SER_NETWORK, PROTOCOL_VERSION); + serializedAccumulator << accumulator; + + // Deserialize the accumulator object + libzerocoin::Accumulator newAccumulator(params, serializedAccumulator); + + // We can now continue accumulating things into the accumulator + // we just deserialized. For example, let's put in the coin + // we generated up above. + newAccumulator += pubCoinNew; + + std::cout << "Successfully accumulated coins." << std::endl; + + /********************************************************************/ + // What is it: Coin spend + // Who does it: ZEROCOIN CLIENTS + // What it does: Create a new transaction that spends a Zerocoin. + // The user first authors a transaction specifying + // a set of destination addresses (outputs). They + // next compute an Accumulator over all coins in the + // block chain (see above) and a Witness based on the + // coin to be spent. Finally they instantiate a CoinSpend + // object that 'signs' the transaction with a special + // zero knowledge signature of knowledge over the coin + // data, Witness and Accumulator. + /********************************************************************/ + + // We are going to spend the coin "newCoin" that we generated at the + // top of this function. + // + // We'll use the accumulator we constructed above. This contains + // a set of coins, but does NOT include the coin "newCoin". + // + // To generate the witness, we start with this accumulator and + // add the public half of the coin we want to spend. + libzerocoin::AccumulatorWitness witness(params, accumulator, newCoin.getPublicCoin()); + + // Add the public half of "newCoin" to the Accumulator itself. + accumulator += newCoin.getPublicCoin(); + + // At this point we should generate a ZEROCOIN_SPEND transaction to + // send to the network. This network should include a set of outputs + // totalling to the value of one zerocoin (minus transaction fees). + + // Construct the CoinSpend object. This acts like a signature on the + // transaction. libzerocoin::CoinSpend spend(params, params, newCoin, accumulator, 0, witness, 0, libzerocoin::SpendType::SPEND);//(0) - Presstab - // This is a sanity check. The CoinSpend object should always verify, - // but why not check before we put it onto the wire? - if (!spend.Verify(accumulator)) { - cout << "ERROR: Our new CoinSpend transaction did not verify!" << endl; - return false; - } - - // Serialize the CoinSpend object into a buffer. - CDataStream serializedCoinSpend(SER_NETWORK, PROTOCOL_VERSION); - serializedCoinSpend << spend; - - cout << "Successfully generated a coin spend transaction." << endl; - - /********************************************************************/ - // What is it: Coin spend verification - // Who does it: ALL PARTIES - // What it does: Verifies that a CoinSpend signature is correct - // with respect to a ZEROCOIN_SPEND transaction hash. - // The client must also extract the serial number from - // the CoinSpend and verify that this serial number has - // not previously appeared in another ZEROCOIN_SPEND - // transaction. - /********************************************************************/ - - // Deserialize the CoinSpend intro a fresh object - libzerocoin::CoinSpend newSpend(params, params, serializedCoinSpend); - - // Create a new metadata object to contain the hash of the received - // ZEROCOIN_SPEND transaction. If we were a real client we'd actually - // compute the hash of the received transaction here. - - // If we were a real client we would now re-compute the Accumulator - // from the information given in the ZEROCOIN_SPEND transaction. - // For our purposes we'll just use the one we calculated above. - // - // Verify that the spend is valid with respect to the Accumulator - // and the Metadata - if (!newSpend.Verify(accumulator)) { - cout << "ERROR: The CoinSpend transaction did not verify!" << endl; - return false; - } - - // Pull the serial number out of the CoinSpend object. If we - // were a real Zerocoin client we would now check that the serial number - // has not been spent before (in another ZEROCOIN_SPEND) transaction. - // The serial number is stored as a CBigNum. - CBigNum serialNumber = newSpend.getCoinSerialNumber(); - - cout << "Successfully verified a coin spend transaction." << endl; - cout << endl << "Coin serial number is:" << endl << serialNumber << endl; - - // We're done - return true; - - } catch (runtime_error &e) { - cout << e.what() << endl; - return false; - } - - return false; + // This is a sanity check. The CoinSpend object should always verify, + // but why not check before we put it onto the wire? + if (!spend.Verify(accumulator)) { + std::cout << "ERROR: Our new CoinSpend transaction did not verify!" << std::endl; + return false; + } + + // Serialize the CoinSpend object into a buffer. + CDataStream serializedCoinSpend(SER_NETWORK, PROTOCOL_VERSION); + serializedCoinSpend << spend; + + std::cout << "Successfully generated a coin spend transaction." << std::endl; + + /********************************************************************/ + // What is it: Coin spend verification + // Who does it: ALL PARTIES + // What it does: Verifies that a CoinSpend signature is correct + // with respect to a ZEROCOIN_SPEND transaction hash. + // The client must also extract the serial number from + // the CoinSpend and verify that this serial number has + // not previously appeared in another ZEROCOIN_SPEND + // transaction. + /********************************************************************/ + + // Deserialize the CoinSpend intro a fresh object + libzerocoin::CoinSpend newSpend(params, params, serializedCoinSpend); + + // Create a new metadata object to contain the hash of the received + // ZEROCOIN_SPEND transaction. If we were a real client we'd actually + // compute the hash of the received transaction here. + + // If we were a real client we would now re-compute the Accumulator + // from the information given in the ZEROCOIN_SPEND transaction. + // For our purposes we'll just use the one we calculated above. + // + // Verify that the spend is valid with respect to the Accumulator + // and the Metadata + if (!newSpend.Verify(accumulator)) { + std::cout << "ERROR: The CoinSpend transaction did not verify!" << std::endl; + return false; + } + + // Pull the serial number out of the CoinSpend object. If we + // were a real Zerocoin client we would now check that the serial number + // has not been spent before (in another ZEROCOIN_SPEND) transaction. + // The serial number is stored as a CBigNum. + CBigNum serialNumber = newSpend.getCoinSerialNumber(); + + std::cout << "Successfully verified a coin spend transaction." << std::endl; + std::cout << std::endl << "Coin serial number is:" << std::endl << serialNumber << std::endl; + + // We're done + return true; + + } catch (std::runtime_error &e) { + std::cout << e.what() << std::endl; + return false; + } + + return false; } BOOST_FIXTURE_TEST_SUITE(tutorial_libzerocoin, TestingSetup) BOOST_AUTO_TEST_CASE(tutorial_libzerocoin_tests) { - cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " tutorial." << endl << endl; + std::cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " tutorial." << std::endl << std::endl; - ZerocoinTutorial(); + ZerocoinTutorial(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/uint256_tests.cpp b/src/test/uint256_tests.cpp index b29281a7fd44..9e64607c9bd6 100644 --- a/src/test/uint256_tests.cpp +++ b/src/test/uint256_tests.cpp @@ -66,7 +66,7 @@ std::string ArrayToString(const unsigned char A[], unsigned int width) BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality { BOOST_CHECK(1 == 0+1); - // constructor uint256(vector): + // constructor uint256(std::vector): BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32)); BOOST_CHECK(R1S.ToString() == ArrayToString(R1Array,20)); BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32)); diff --git a/src/test/univalue_tests.cpp b/src/test/univalue_tests.cpp index 0417cb2f8bcd..204a7dc1e8e9 100644 --- a/src/test/univalue_tests.cpp +++ b/src/test/univalue_tests.cpp @@ -12,7 +12,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup) @@ -53,7 +52,7 @@ BOOST_AUTO_TEST_CASE(univalue_constructor) BOOST_CHECK(v7.isNum()); BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21"); - string vs("yawn"); + std::string vs("yawn"); UniValue v8(vs); BOOST_CHECK(v8.isStr()); BOOST_CHECK_EQUAL(v8.getValStr(), "yawn"); @@ -69,41 +68,41 @@ BOOST_AUTO_TEST_CASE(univalue_typecheck) UniValue v1; BOOST_CHECK(v1.setNumStr("1")); BOOST_CHECK(v1.isNum()); - BOOST_CHECK_THROW(v1.get_bool(), runtime_error); + BOOST_CHECK_THROW(v1.get_bool(), std::runtime_error); UniValue v2; BOOST_CHECK(v2.setBool(true)); BOOST_CHECK_EQUAL(v2.get_bool(), true); - BOOST_CHECK_THROW(v2.get_int(), runtime_error); + BOOST_CHECK_THROW(v2.get_int(), std::runtime_error); UniValue v3; BOOST_CHECK(v3.setNumStr("32482348723847471234")); - BOOST_CHECK_THROW(v3.get_int64(), runtime_error); + BOOST_CHECK_THROW(v3.get_int64(), std::runtime_error); BOOST_CHECK(v3.setNumStr("1000")); BOOST_CHECK_EQUAL(v3.get_int64(), 1000); UniValue v4; BOOST_CHECK(v4.setNumStr("2147483648")); BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648); - BOOST_CHECK_THROW(v4.get_int(), runtime_error); + BOOST_CHECK_THROW(v4.get_int(), std::runtime_error); BOOST_CHECK(v4.setNumStr("1000")); BOOST_CHECK_EQUAL(v4.get_int(), 1000); - BOOST_CHECK_THROW(v4.get_str(), runtime_error); + BOOST_CHECK_THROW(v4.get_str(), std::runtime_error); BOOST_CHECK_EQUAL(v4.get_real(), 1000); - BOOST_CHECK_THROW(v4.get_array(), runtime_error); - BOOST_CHECK_THROW(v4.getKeys(), runtime_error); - BOOST_CHECK_THROW(v4.getValues(), runtime_error); - BOOST_CHECK_THROW(v4.get_obj(), runtime_error); + BOOST_CHECK_THROW(v4.get_array(), std::runtime_error); + BOOST_CHECK_THROW(v4.getKeys(), std::runtime_error); + BOOST_CHECK_THROW(v4.getValues(), std::runtime_error); + BOOST_CHECK_THROW(v4.get_obj(), std::runtime_error); UniValue v5; BOOST_CHECK(v5.read("[true, 10]")); BOOST_CHECK_NO_THROW(v5.get_array()); std::vector vals = v5.getValues(); - BOOST_CHECK_THROW(vals[0].get_int(), runtime_error); + BOOST_CHECK_THROW(vals[0].get_int(), std::runtime_error); BOOST_CHECK_EQUAL(vals[0].get_bool(), true); BOOST_CHECK_EQUAL(vals[1].get_int(), 10); - BOOST_CHECK_THROW(vals[1].get_bool(), runtime_error); + BOOST_CHECK_THROW(vals[1].get_bool(), std::runtime_error); } BOOST_AUTO_TEST_CASE(univalue_set) @@ -172,13 +171,13 @@ BOOST_AUTO_TEST_CASE(univalue_array) UniValue v((int64_t)1023LL); BOOST_CHECK(arr.push_back(v)); - string vStr("zippy"); + std::string vStr("zippy"); BOOST_CHECK(arr.push_back(vStr)); const char *s = "pippy"; BOOST_CHECK(arr.push_back(s)); - vector vec; + std::vector vec; v.setStr("boing"); vec.push_back(v); @@ -206,7 +205,7 @@ BOOST_AUTO_TEST_CASE(univalue_array) BOOST_AUTO_TEST_CASE(univalue_object) { UniValue obj(UniValue::VOBJ); - string strKey, strVal; + std::string strKey, strVal; UniValue v; strKey = "age"; @@ -266,7 +265,7 @@ BOOST_AUTO_TEST_CASE(univalue_object) BOOST_CHECK(!obj.exists("nyuknyuknyuk")); - map objTypes; + std::map objTypes; objTypes["age"] = UniValue::VNUM; objTypes["first"] = UniValue::VSTR; objTypes["last"] = UniValue::VSTR; @@ -294,7 +293,7 @@ BOOST_AUTO_TEST_CASE(univalue_readwrite) UniValue v; BOOST_CHECK(v.read(json1)); - string strJson1(json1); + std::string strJson1(json1); BOOST_CHECK(v.read(strJson1)); BOOST_CHECK(v.isArray()); diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 285b1ee03afe..39898f0b45dd 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -18,7 +18,6 @@ #include -using namespace std; BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup) diff --git a/src/test/zerocoin_bignum_tests.cpp b/src/test/zerocoin_bignum_tests.cpp index fbbf41b75c1e..00932de583f8 100644 --- a/src/test/zerocoin_bignum_tests.cpp +++ b/src/test/zerocoin_bignum_tests.cpp @@ -11,7 +11,6 @@ #include "libzerocoin/Accumulator.h" #include "zpiv/zerocoin.h" -using namespace libzerocoin; bool testRandKBitBignum(int k_bits) { diff --git a/src/test/zerocoin_coinspend_tests.cpp b/src/test/zerocoin_coinspend_tests.cpp index 9c547e1db89d..7df848131cca 100644 --- a/src/test/zerocoin_coinspend_tests.cpp +++ b/src/test/zerocoin_coinspend_tests.cpp @@ -20,7 +20,6 @@ #include #include -using namespace libzerocoin; class CDeterministicMint; @@ -34,20 +33,20 @@ BOOST_AUTO_TEST_CASE(zerocoin_wrapped_serial_spend_test) unsigned int TESTS_COINS_TO_ACCUMULATE = 5; SelectParams(CBaseChainParams::MAIN); - ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); + libzerocoin::ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); (void)ZCParams; // Seed + Mints - string strWalletFile = "unittestwallet.dat"; + std::string strWalletFile = "unittestwallet.dat"; CWalletDB walletdb(strWalletFile, "cr+"); CWallet wallet(strWalletFile); CzPIVWallet *czPIVWallet = new CzPIVWallet(wallet.strWalletFile); // Get the 5 created mints. - CoinDenomination denom = CoinDenomination::ZQ_FIFTY; - std::vector vCoins; + libzerocoin::CoinDenomination denom = libzerocoin::CoinDenomination::ZQ_FIFTY; + std::vector vCoins; for (unsigned int i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { - PrivateCoin coin(ZCParams, denom, false); + libzerocoin::PrivateCoin coin(ZCParams, denom, false); CDeterministicMint dMint; czPIVWallet->GenerateDeterministicZPIV(denom, coin, dMint, true); czPIVWallet->UpdateCount(); @@ -55,11 +54,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_wrapped_serial_spend_test) } // Selected coin - PrivateCoin coinToSpend = vCoins[0]; + libzerocoin::PrivateCoin coinToSpend = vCoins[0]; // Accumulate coins - Accumulator acc(&ZCParams->accumulatorParams, denom); - AccumulatorWitness accWitness(ZCParams, acc, coinToSpend.getPublicCoin()); + libzerocoin::Accumulator acc(&ZCParams->accumulatorParams, denom); + libzerocoin::AccumulatorWitness accWitness(ZCParams, acc, coinToSpend.getPublicCoin()); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { acc += vCoins[i].getPublicCoin(); @@ -72,7 +71,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_wrapped_serial_spend_test) Bignum wrappedSerial = coinToSpend.getSerialNumber() + ZCParams->coinCommitmentGroup.groupOrder * CBigNum(2).pow(256) * 2; coinToSpend.setSerialNumber(wrappedSerial); - CoinSpend wrappedSerialSpend( + libzerocoin::CoinSpend wrappedSerialSpend( ZCParams, ZCParams, coinToSpend, @@ -80,7 +79,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_wrapped_serial_spend_test) 0, accWitness, 0, - SpendType::SPEND + libzerocoin::SpendType::SPEND ); // first check that the Verify pass without do the invalid range check diff --git a/src/test/zerocoin_denomination_tests.cpp b/src/test/zerocoin_denomination_tests.cpp index 13a5c8dbe083..c73b9e1443d3 100644 --- a/src/test/zerocoin_denomination_tests.cpp +++ b/src/test/zerocoin_denomination_tests.cpp @@ -14,59 +14,58 @@ #include #include -using namespace libzerocoin; BOOST_FIXTURE_TEST_SUITE(zerocoin_denom_tests, BasicTestingSetup) //translation from pivx quantity to zerocoin denomination BOOST_AUTO_TEST_CASE(amount_to_denomination_test) { - cout << "Running amount_to_denomination_test...\n"; + std::cout << "Running amount_to_denomination_test...\n"; //valid amount (min edge) CAmount amount = 1 * COIN; - BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount) == ZQ_ONE, "For COIN denomination should be ZQ_ONE"); + BOOST_CHECK_MESSAGE(libzerocoin::AmountToZerocoinDenomination(amount) == libzerocoin::ZQ_ONE, "For COIN denomination should be ZQ_ONE"); //valid amount (max edge) CAmount amount1 = 5000 * COIN; - BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount1) == ZQ_FIVE_THOUSAND, "For 5000*COIN denomination should be ZQ_ONE"); + BOOST_CHECK_MESSAGE(libzerocoin::AmountToZerocoinDenomination(amount1) == libzerocoin::ZQ_FIVE_THOUSAND, "For 5000*COIN denomination should be ZQ_ONE"); //invalid amount (too much) CAmount amount2 = 7000 * COIN; - BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount2) == ZQ_ERROR, "For 7000*COIN denomination should be Invalid -> ZQ_ERROR"); + BOOST_CHECK_MESSAGE(libzerocoin::AmountToZerocoinDenomination(amount2) == libzerocoin::ZQ_ERROR, "For 7000*COIN denomination should be Invalid -> ZQ_ERROR"); //invalid amount (not enough) CAmount amount3 = 1; - BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount3) == ZQ_ERROR, "For 1 denomination should be Invalid -> ZQ_ERROR"); + BOOST_CHECK_MESSAGE(libzerocoin::AmountToZerocoinDenomination(amount3) == libzerocoin::ZQ_ERROR, "For 1 denomination should be Invalid -> ZQ_ERROR"); } BOOST_AUTO_TEST_CASE(denomination_to_value_test) { - cout << "Running ZerocoinDenominationToValue_test...\n"; + std::cout << "Running ZerocoinDenominationToValue_test...\n"; int64_t Value = 1 * COIN; - CoinDenomination denomination = ZQ_ONE; - BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 1"); + libzerocoin::CoinDenomination denomination = libzerocoin::ZQ_ONE; + BOOST_CHECK_MESSAGE(libzerocoin::ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 1"); Value = 10 * COIN; - denomination = ZQ_TEN; - BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 10"); + denomination = libzerocoin::ZQ_TEN; + BOOST_CHECK_MESSAGE(libzerocoin::ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 10"); Value = 50 * COIN; - denomination = ZQ_FIFTY; - BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 50"); + denomination = libzerocoin::ZQ_FIFTY; + BOOST_CHECK_MESSAGE(libzerocoin::ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 50"); Value = 500 * COIN; - denomination = ZQ_FIVE_HUNDRED; - BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 500"); + denomination = libzerocoin::ZQ_FIVE_HUNDRED; + BOOST_CHECK_MESSAGE(libzerocoin::ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 500"); Value = 100 * COIN; - denomination = ZQ_ONE_HUNDRED; - BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 100"); + denomination = libzerocoin::ZQ_ONE_HUNDRED; + BOOST_CHECK_MESSAGE(libzerocoin::ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 100"); Value = 0 * COIN; - denomination = ZQ_ERROR; - BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 0"); + denomination = libzerocoin::ZQ_ERROR; + BOOST_CHECK_MESSAGE(libzerocoin::ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 0"); } BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) @@ -76,7 +75,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) const int DenomAmounts[] = {1, 2, 3, 4, 0, 0, 0, 0}; CAmount nSelectedValue; std::list listMints; - std::map mapDenom; + std::map mapDenom; int j = 0; CAmount nTotalAmount = 0; @@ -85,9 +84,9 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { - CAmount currentAmount = ZerocoinDenominationToAmount(denom); + CAmount currentAmount = libzerocoin::ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; @@ -101,7 +100,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) meta.nVersion = 1; listMints.push_back(meta); } - mapDenom.insert(std::pair(denom, DenomAmounts[j])); + mapDenom.insert(std::pair(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; @@ -109,14 +108,14 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) // Show what we have j = 0; - for (const auto& denom : zerocoinDenomList) - std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; + for (const auto& denom : libzerocoin::zerocoinDenomList) + std::cout << DenomAmounts[j++] << "*" << libzerocoin::ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; // For DenomAmounts[] = {1,2,3,4,0,0,0,0}; we can spend up to 200 without requiring more than 4 Spends // Amounts above this can not be met CAmount MaxLimit = 200; - CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); + CAmount OneCoinAmount = libzerocoin::ZerocoinDenominationToAmount(libzerocoin::ZQ_ONE); CAmount nValueTarget = OneCoinAmount; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed @@ -161,7 +160,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test115) const int DenomAmounts[] = {0, 1, 1, 2, 0, 0, 0, 0}; CAmount nSelectedValue; std::list listMints; - std::map mapDenom; + std::map mapDenom; int j = 0; CAmount nTotalAmount = 0; @@ -169,9 +168,9 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test115) // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { - CAmount currentAmount = ZerocoinDenominationToAmount(denom); + CAmount currentAmount = libzerocoin::ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; @@ -185,7 +184,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test115) meta.nVersion = 1; listMints.push_back(meta); } - mapDenom.insert(std::pair(denom, DenomAmounts[j])); + mapDenom.insert(std::pair(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; @@ -193,11 +192,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test115) // Show what we have j = 0; - for (const auto& denom : zerocoinDenomList) - std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; + for (const auto& denom : libzerocoin::zerocoinDenomList) + std::cout << DenomAmounts[j++] << "*" << libzerocoin::ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; - CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); + CAmount OneCoinAmount = libzerocoin::ZerocoinDenominationToAmount(libzerocoin::ZQ_ONE); CAmount nValueTarget = OneCoinAmount; //bool fDebug = 0; @@ -245,7 +244,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) const int nMaxSpendAmount = 220; CAmount nSelectedValue; std::list listMints; - std::map mapOfDenomsHeld; + std::map mapOfDenomsHeld; int j = 0; CAmount nTotalAmount = 0; @@ -253,9 +252,9 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { - CAmount currentAmount = ZerocoinDenominationToAmount(denom); + CAmount currentAmount = libzerocoin::ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; @@ -269,7 +268,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) meta.nVersion = 1; listMints.push_back(meta); } - mapOfDenomsHeld.insert(std::pair(denom, DenomAmounts[j])); + mapOfDenomsHeld.insert(std::pair(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; @@ -277,11 +276,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) // Show what we have j = 0; - for (const auto& denom : zerocoinDenomList) - std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; + for (const auto& denom : libzerocoin::zerocoinDenomList) + std::cout << DenomAmounts[j++] << "*" << libzerocoin::ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; - CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); + CAmount OneCoinAmount = libzerocoin::ZerocoinDenominationToAmount(libzerocoin::ZQ_ONE); CAmount nValueTarget = OneCoinAmount; // bool fDebug = 0; @@ -347,7 +346,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) const int DenomAmounts[] = {0, 1, 4, 2, 0, 0, 0, 0}; CAmount nSelectedValue; std::list listMints; - std::map mapOfDenomsHeld; + std::map mapOfDenomsHeld; int j = 0; CAmount nTotalAmount = 0; @@ -355,9 +354,9 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { - CAmount currentAmount = ZerocoinDenominationToAmount(denom); + CAmount currentAmount = libzerocoin::ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; @@ -371,7 +370,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) meta.nVersion = 1; listMints.push_back(meta); } - mapOfDenomsHeld.insert(std::pair(denom, DenomAmounts[j])); + mapOfDenomsHeld.insert(std::pair(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; @@ -382,11 +381,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) // Show what we have j = 0; - for (const auto& denom : zerocoinDenomList) - std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; + for (const auto& denom : libzerocoin::zerocoinDenomList) + std::cout << DenomAmounts[j++] << "*" << libzerocoin::ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; - CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); + CAmount OneCoinAmount = libzerocoin::ZerocoinDenominationToAmount(libzerocoin::ZQ_ONE); CAmount nValueTarget = OneCoinAmount; //bool fDebug = 0; @@ -453,7 +452,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test99) const int DenomAmounts[] = {0, 1, 4, 2, 1, 0, 0, 0}; CAmount nSelectedValue; std::list listMints; - std::map mapOfDenomsHeld; + std::map mapOfDenomsHeld; int j = 0; CAmount nTotalAmount = 0; @@ -461,9 +460,9 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test99) // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available - for (const auto& denom : zerocoinDenomList) { + for (const auto& denom : libzerocoin::zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { - CAmount currentAmount = ZerocoinDenominationToAmount(denom); + CAmount currentAmount = libzerocoin::ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; @@ -477,7 +476,7 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test99) meta.nVersion = 1; listMints.push_back(meta); } - mapOfDenomsHeld.insert(std::pair(denom, DenomAmounts[j])); + mapOfDenomsHeld.insert(std::pair(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; @@ -485,11 +484,11 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test99) // Show what we have j = 0; - for (const auto& denom : zerocoinDenomList) - std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; + for (const auto& denom : libzerocoin::zerocoinDenomList) + std::cout << DenomAmounts[j++] << "*" << libzerocoin::ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; - CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); + CAmount OneCoinAmount = libzerocoin::ZerocoinDenominationToAmount(libzerocoin::ZQ_ONE); CAmount nValueTarget = 99 * OneCoinAmount; // bool fDebug = 0; diff --git a/src/test/zerocoin_implementation_tests.cpp b/src/test/zerocoin_implementation_tests.cpp index 711b9143f1bf..10c99affc98d 100644 --- a/src/test/zerocoin_implementation_tests.cpp +++ b/src/test/zerocoin_implementation_tests.cpp @@ -19,7 +19,6 @@ #include "zpivchain.h" #include "test_pivx.h" -using namespace libzerocoin; extern bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx); @@ -27,12 +26,12 @@ BOOST_FIXTURE_TEST_SUITE(zerocoin_implementation_tests, TestingSetup) BOOST_AUTO_TEST_CASE(zcparams_test) { - cout << "Running zcparams_test...\n"; + std::cout << "Running zcparams_test...\n"; bool fPassed = true; try{ SelectParams(CBaseChainParams::MAIN); - ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); + libzerocoin::ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); (void)ZCParams; } catch(std::exception& e) { fPassed = false; @@ -71,7 +70,7 @@ std::vector > vecRawMints = {std::make_pair( //create a zerocoin mint from vecsend BOOST_AUTO_TEST_CASE(checkzerocoinmint_test) { - cout << "generating privkeys\n"; + std::cout << "generating privkeys\n"; //generate a privkey CKey key; @@ -92,7 +91,7 @@ BOOST_AUTO_TEST_CASE(checkzerocoinmint_test) BOOST_CHECK_MESSAGE(bnSerial == bnSerial2, "Serials do not match!"); - cout << "Running check_zerocoinmint_test...\n"; + std::cout << "Running check_zerocoinmint_test...\n"; CTransaction tx; BOOST_CHECK(DecodeHexTx(tx, rawTx1)); @@ -108,7 +107,7 @@ BOOST_AUTO_TEST_CASE(checkzerocoinmint_test) BOOST_CHECK(fFoundMint); } -bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) +bool CheckZerocoinSpendNoDB(const CTransaction tx, std::string& strError) { //max needed non-mint outputs should be 2 - one for redemption address and a possible 2nd for change if (tx.vout.size() > 2){ @@ -133,8 +132,8 @@ bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) // uint256 hashTxOut = txTemp.GetHash(); bool fValidated = false; - set serials; - list vSpends; + std::set serials; + std::list vSpends; CAmount nTotalRedeemed = 0; for (const CTxIn& txin : tx.vin) { @@ -148,12 +147,12 @@ bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) CDataStream serializedCoinSpend(dataTxIn, SER_NETWORK, PROTOCOL_VERSION); libzerocoin::ZerocoinParams* paramsAccumulator = Params().Zerocoin_Params(false); - CoinSpend newSpend(Params().Zerocoin_Params(true), paramsAccumulator, serializedCoinSpend); + libzerocoin::CoinSpend newSpend(Params().Zerocoin_Params(true), paramsAccumulator, serializedCoinSpend); vSpends.push_back(newSpend); //check that the denomination is valid - if (newSpend.getDenomination() == ZQ_ERROR) { + if (newSpend.getDenomination() == libzerocoin::ZQ_ERROR) { strError = "Zerocoinspend does not have the correct denomination"; return false; } @@ -176,7 +175,7 @@ bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) // return false; // } - // Accumulator accumulator(Params().Zerocoin_Params(true), newSpend.getDenomination(), bnAccumulatorValue); + // libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(true), newSpend.getDenomination(), bnAccumulatorValue); // //Check that the coin is on the accumulator // if (!newSpend.Verify(accumulator)) { @@ -195,7 +194,7 @@ bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) // return state.DoS(100, error("Zerocoinspend is already known")); //make sure that there is no over redemption of coins - nTotalRedeemed += ZerocoinDenominationToAmount(newSpend.getDenomination()); + nTotalRedeemed += libzerocoin::ZerocoinDenominationToAmount(newSpend.getDenomination()); fValidated = true; } @@ -214,27 +213,27 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) bnTrustedModulus.SetDec(zerocoinModulus); libzerocoin::ZerocoinParams zerocoinParams = libzerocoin::ZerocoinParams(bnTrustedModulus); - cout << "Running check_zerocoinspend_test...\n"; + std::cout << "Running check_zerocoinspend_test...\n"; //load our serialized pubcoin CBigNum bnpubcoin; BOOST_CHECK_MESSAGE(bnpubcoin.SetHexBool(rawTxpub1), "Failed to set CBigNum from hex string"); - PublicCoin pubCoin(Params().Zerocoin_Params(true), bnpubcoin, CoinDenomination::ZQ_ONE); + libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(true), bnpubcoin, libzerocoin::CoinDenomination::ZQ_ONE); BOOST_CHECK_MESSAGE(pubCoin.validate(), "Failed to validate pubCoin created from hex string"); //initialize and Accumulator and AccumulatorWitness - Accumulator accumulator(Params().Zerocoin_Params(false), CoinDenomination::ZQ_ONE); - AccumulatorWitness witness(Params().Zerocoin_Params(false), accumulator, pubCoin); + libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(false), libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::AccumulatorWitness witness(Params().Zerocoin_Params(false), accumulator, pubCoin); //populate the witness and accumulators CValidationState state; - for(pair raw : vecRawMints) { + for(std::pair raw : vecRawMints) { CTransaction tx; BOOST_CHECK_MESSAGE(DecodeHexTx(tx, raw.first), "Failed to deserialize hex transaction"); for(const CTxOut& out : tx.vout){ if(out.IsZerocoinMint()) { - PublicCoin publicCoin(Params().Zerocoin_Params(true)); + libzerocoin::PublicCoin publicCoin(Params().Zerocoin_Params(true)); BOOST_CHECK_MESSAGE(TxOutToPublicCoin(out, publicCoin, state), "Failed to convert CTxOut " << out.ToString() << " to PublicCoin"); accumulator += publicCoin; @@ -244,7 +243,7 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) } // Create a New Zerocoin with specific denomination given by pubCoin - PrivateCoin privateCoin(Params().Zerocoin_Params(true), pubCoin.getDenomination()); + libzerocoin::PrivateCoin privateCoin(Params().Zerocoin_Params(true), pubCoin.getDenomination()); privateCoin.setPublicCoin(pubCoin); CBigNum bn = 0; bn.SetHex(rawTxRand1); @@ -257,14 +256,14 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) //Get the checksum of the accumulator we use for the spend and also add it to our checksum map uint32_t nChecksum = GetChecksum(accumulator.getValue()); //AddAccumulatorChecksum(nChecksum, accumulator.getValue(), true); - CoinSpend coinSpend(Params().Zerocoin_Params(true), Params().Zerocoin_Params(false), privateCoin, accumulator, nChecksum, witness, 0, SpendType::SPEND); - cout << coinSpend.ToString() << endl; + libzerocoin::CoinSpend coinSpend(Params().Zerocoin_Params(true), Params().Zerocoin_Params(false), privateCoin, accumulator, nChecksum, witness, 0, libzerocoin::SpendType::SPEND); + std::cout << coinSpend.ToString() << std::endl; BOOST_CHECK_MESSAGE(coinSpend.Verify(accumulator), "Coinspend construction failed to create valid proof"); CBigNum serial = coinSpend.getCoinSerialNumber(); BOOST_CHECK_MESSAGE(serial, "Serial Number can't be 0"); - CoinDenomination denom = coinSpend.getDenomination(); + libzerocoin::CoinDenomination denom = coinSpend.getDenomination(); BOOST_CHECK_MESSAGE(denom == pubCoin.getDenomination(), "Spend denomination must match original pubCoin"); BOOST_CHECK_MESSAGE(coinSpend.Verify(accumulator), "CoinSpend object failed to validate"); @@ -293,7 +292,7 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) CDataStream serializedCoinSpend(dataTxIn, SER_NETWORK, PROTOCOL_VERSION); //old params for the V1 generated coin, new params for the accumulator. Emulates main-net transition. - CoinSpend spend1(Params().Zerocoin_Params(true), Params().Zerocoin_Params(false), serializedCoinSpend); + libzerocoin::CoinSpend spend1(Params().Zerocoin_Params(true), Params().Zerocoin_Params(false), serializedCoinSpend); BOOST_CHECK_MESSAGE(spend1.Verify(accumulator), "Failed deserialized check of CoinSpend"); CScript script; @@ -306,9 +305,9 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) CTransaction txMintFrom; BOOST_CHECK_MESSAGE(DecodeHexTx(txMintFrom, rawTx1), "Failed to deserialize hex transaction"); - string strError = ""; + std::string strError = ""; if (!CheckZerocoinSpendNoDB(txNew, strError)) { - cout << state.GetRejectCode() << endl; + std::cout << state.GetRejectCode() << std::endl; BOOST_CHECK_MESSAGE(false, strError); } @@ -319,11 +318,11 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) txOverSpend.vout.push_back(txOutOverSpend); strError = ""; CheckZerocoinSpendNoDB(txOverSpend, strError); - string str = "Failed to detect overspend. Error Message: " + strError; + std::string str = "Failed to detect overspend. Error Message: " + strError; BOOST_CHECK_MESSAGE(strError == "Transaction spend more than was redeemed in zerocoins", str); - cout << "checking v2 spend\n"; + std::cout << "checking v2 spend\n"; CMutableTransaction tx; uint256 txHash = 0; @@ -331,27 +330,27 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) tx.vin.emplace_back(in); // Create a New Zerocoin with specific denomination given by pubCoin - PrivateCoin privateCoin_v2(Params().Zerocoin_Params(false), CoinDenomination::ZQ_ONE); + libzerocoin::PrivateCoin privateCoin_v2(Params().Zerocoin_Params(false), libzerocoin::CoinDenomination::ZQ_ONE); CKey key; key.SetPrivKey(privateCoin.getPrivKey(), true); BOOST_CHECK_MESSAGE(key.IsValid(), "Key is not valid"); - PublicCoin pubcoin_v2 = privateCoin_v2.getPublicCoin(); + libzerocoin::PublicCoin pubcoin_v2 = privateCoin_v2.getPublicCoin(); //initialize and Accumulator and AccumulatorWitness - Accumulator accumulator_v2(Params().Zerocoin_Params(false), CoinDenomination::ZQ_ONE); - AccumulatorWitness witness_v2(Params().Zerocoin_Params(false), accumulator_v2, pubcoin_v2); + libzerocoin::Accumulator accumulator_v2(Params().Zerocoin_Params(false), libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::AccumulatorWitness witness_v2(Params().Zerocoin_Params(false), accumulator_v2, pubcoin_v2); //populate the witness and accumulators - with old v1 params int64_t nTimeStart = GetTimeMillis(); CValidationState state_v2; for(int i = 0; i < 5; i++) { - PrivateCoin privTemp(Params().Zerocoin_Params(true), CoinDenomination::ZQ_ONE); - PublicCoin pubTemp = privTemp.getPublicCoin(); + libzerocoin::PrivateCoin privTemp(Params().Zerocoin_Params(true), libzerocoin::CoinDenomination::ZQ_ONE); + libzerocoin::PublicCoin pubTemp = privTemp.getPublicCoin(); accumulator_v2 += pubTemp; witness_v2 += pubTemp; } - cout << (GetTimeMillis() - nTimeStart)/5 << "ms per mint\n"; + std::cout << (GetTimeMillis() - nTimeStart)/5 << "ms per mint\n"; accumulator_v2 += pubcoin_v2; @@ -359,7 +358,7 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) uint32_t nChecksum_v2 = GetChecksum(accumulator_v2.getValue()); //AddAccumulatorChecksum(nChecksum_v2, accumulator_v2.getValue(), true); uint256 ptxHash = CBigNum::randKBitBignum(256).getuint256(); - CoinSpend coinSpend_v2(Params().Zerocoin_Params(false), Params().Zerocoin_Params(false), privateCoin_v2, accumulator_v2, nChecksum_v2, witness_v2, ptxHash, SpendType::SPEND); + libzerocoin::CoinSpend coinSpend_v2(Params().Zerocoin_Params(false), Params().Zerocoin_Params(false), privateCoin_v2, accumulator_v2, nChecksum_v2, witness_v2, ptxHash, libzerocoin::SpendType::SPEND); BOOST_CHECK_MESSAGE(coinSpend_v2.HasValidSerial(Params().Zerocoin_Params(false)), "coinspend_v2 does not have a valid serial"); BOOST_CHECK_MESSAGE(coinSpend_v2.Verify(accumulator_v2), "coinspend_v2 failed to verify"); @@ -375,14 +374,14 @@ BOOST_AUTO_TEST_CASE(setup_exceptions_test) bnTrustedModulus.SetDec(zerocoinModulus); libzerocoin::ZerocoinParams zerocoinParams = libzerocoin::ZerocoinParams(bnTrustedModulus); - cout << "Running check_unitialized parameters,etc for setup exceptions...\n"; + std::cout << "Running check_unitialized parameters,etc for setup exceptions...\n"; CBigNum bnpubcoin; BOOST_CHECK(bnpubcoin.SetHexBool(rawTxpub1)); // Check Modulus > 1023 Exception try { - ZerocoinParams ZCParams(bnpubcoin); + libzerocoin::ZerocoinParams ZCParams(bnpubcoin); BOOST_CHECK_MESSAGE(false, "Didn't catch exception: ZerocoinException: Modulus must be at least 1023 bit"); } catch (...) { @@ -391,7 +390,7 @@ BOOST_AUTO_TEST_CASE(setup_exceptions_test) // Check Security Level < 80 Exception try { - ZerocoinParams ZCParams(bnpubcoin,1); + libzerocoin::ZerocoinParams ZCParams(bnpubcoin,1); BOOST_CHECK_MESSAGE(false, "Didn't catch exception: Security Level >= 80"); } catch (...) { @@ -401,7 +400,7 @@ BOOST_AUTO_TEST_CASE(setup_exceptions_test) // Check unitialized params Exception for PublicCoin try { zerocoinParams.initialized = false; - PublicCoin pubCoin(&zerocoinParams); + libzerocoin::PublicCoin pubCoin(&zerocoinParams); BOOST_CHECK_MESSAGE(false, "Didn't catch exception checking for uninitialized Params"); } catch (...) { @@ -411,7 +410,7 @@ BOOST_AUTO_TEST_CASE(setup_exceptions_test) // Check unitialized params Exception for PublicCoin (alternate constructor) try { zerocoinParams.initialized = false; - PublicCoin pubCoin(&zerocoinParams); + libzerocoin::PublicCoin pubCoin(&zerocoinParams); BOOST_CHECK_MESSAGE(false, "Didn't catch exception checking for uninitialized Params"); } catch (...) { @@ -421,7 +420,7 @@ BOOST_AUTO_TEST_CASE(setup_exceptions_test) // Check unitialized params Exception for PrivateCoin try { zerocoinParams.initialized = false; - PrivateCoin privCoin(&zerocoinParams, CoinDenomination::ZQ_ONE); + libzerocoin::PrivateCoin privCoin(&zerocoinParams, libzerocoin::CoinDenomination::ZQ_ONE); BOOST_CHECK_MESSAGE(false, "Didn't catch exception checking for uninitialized Params"); } catch (...) { @@ -432,7 +431,7 @@ BOOST_AUTO_TEST_CASE(setup_exceptions_test) BOOST_AUTO_TEST_CASE(checksum_tests) { - cout << "Running checksum_tests\n"; + std::cout << "Running checksum_tests\n"; uint256 checksum; uint32_t c1 = 0xa3219ef1; @@ -443,14 +442,14 @@ BOOST_AUTO_TEST_CASE(checksum_tests) uint32_t c6 = 0xbbbbbbbb; uint32_t c7 = 0x11111111; uint32_t c8 = 0xeeeeeeee; - vector vChecksums {c1,c2,c3,c4,c5,c6,c7,c8}; + std::vector vChecksums {c1,c2,c3,c4,c5,c6,c7,c8}; for(uint32_t c : vChecksums) checksum = checksum << 32 | c; BOOST_CHECK_MESSAGE(checksum == uint256("a3219ef1abcdef00101029f3aaaaaeeeffffffffbbbbbbbb11111111eeeeeeee"), "checksum not properly concatenated"); int i = 0; - for (auto& denom : zerocoinDenomList){ + for (auto& denom : libzerocoin::zerocoinDenomList){ uint32_t checksumParsed = ParseChecksum(checksum, denom); BOOST_CHECK_MESSAGE(checksumParsed == vChecksums[i], "checksum parse failed"); i++; @@ -468,10 +467,10 @@ BOOST_AUTO_TEST_CASE(test_checkpoints) BOOST_AUTO_TEST_CASE(deterministic_tests) { SelectParams(CBaseChainParams::UNITTEST); - cout << "Testing deterministic minting\n"; + std::cout << "Testing deterministic minting\n"; uint256 seedMaster("3a1947364362e2e7c073b386869c89c905c0cf462448ffd6c2021bd03ce689f6"); - string strWalletFile = "unittestwallet.dat"; + std::string strWalletFile = "unittestwallet.dat"; CWalletDB walletdb(strWalletFile, "cr+"); CWallet wallet(strWalletFile); @@ -480,30 +479,30 @@ BOOST_AUTO_TEST_CASE(deterministic_tests) wallet.setZWallet(&zWallet); int64_t nTimeStart = GetTimeMillis(); - CoinDenomination denom = CoinDenomination::ZQ_FIFTY; + libzerocoin::CoinDenomination denom = libzerocoin::CoinDenomination::ZQ_FIFTY; - std::vector vCoins; + std::vector vCoins; int nTests = 50; for (int i = 0; i < nTests; i++) { - PrivateCoin coin(Params().Zerocoin_Params(false), denom, false); + libzerocoin::PrivateCoin coin(Params().Zerocoin_Params(false), denom, false); CDeterministicMint dMint; zWallet.GenerateDeterministicZPIV(denom, coin, dMint); vCoins.emplace_back(coin); } int64_t nTotalTime = GetTimeMillis() - nTimeStart; - cout << "Total time:" << nTotalTime << "ms. Per Deterministic Mint:" << (nTotalTime/nTests) << "ms" << endl; + std::cout << "Total time:" << nTotalTime << "ms. Per Deterministic Mint:" << (nTotalTime/nTests) << "ms" << std::endl; - cout << "Checking that mints are valid" << endl; + std::cout << "Checking that mints are valid" << std::endl; CDataStream ss(SER_GETHASH, 0); - for (PrivateCoin& coin : vCoins) { + for (libzerocoin::PrivateCoin& coin : vCoins) { BOOST_CHECK_MESSAGE(coin.IsValid(), "Generated Mint is not valid"); ss << coin.getPublicCoin().getValue(); } - cout << "Checking that mints are deterministic: sha256 checksum="; + std::cout << "Checking that mints are deterministic: sha256 checksum="; uint256 hash = Hash(ss.begin(), ss.end()); - cout << hash.GetHex() << endl; + std::cout << hash.GetHex() << std::endl; BOOST_CHECK_MESSAGE(hash == uint256("c90c225f2cbdee5ef053b1f9f70053dd83724c58126d0e1b8425b88091d1f73f"), "minting determinism isn't as expected"); } diff --git a/src/test/zerocoin_transactions_tests.cpp b/src/test/zerocoin_transactions_tests.cpp index 9bd39e3353c5..b245d0451278 100644 --- a/src/test/zerocoin_transactions_tests.cpp +++ b/src/test/zerocoin_transactions_tests.cpp @@ -16,7 +16,6 @@ #include #include -using namespace libzerocoin; BOOST_FIXTURE_TEST_SUITE(zerocoin_transactions_tests, TestingSetup) @@ -26,12 +25,12 @@ static CWallet cWallet("unlocked.dat"); BOOST_AUTO_TEST_CASE(zerocoin_spend_test) { SelectParams(CBaseChainParams::MAIN); - ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); + libzerocoin::ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); (void)ZCParams; bool fFirstRun; cWallet.LoadWallet(fFirstRun); - cWallet.zpivTracker = unique_ptr(new CzPIVTracker(cWallet.strWalletFile)); + cWallet.zpivTracker = std::unique_ptr(new CzPIVTracker(cWallet.strWalletFile)); CMutableTransaction tx; CWalletTx* wtx = new CWalletTx(&cWallet, tx); bool fMintChange=true; @@ -59,10 +58,10 @@ BOOST_AUTO_TEST_CASE(zerocoin_spend_test) BOOST_AUTO_TEST_CASE(zerocoin_public_spend_test) { SelectParams(CBaseChainParams::MAIN); - ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); + libzerocoin::ZerocoinParams *ZCParams = Params().Zerocoin_Params(false); (void)ZCParams; - PrivateCoin privCoin(ZCParams, libzerocoin::CoinDenomination::ZQ_ONE, true); + libzerocoin::PrivateCoin privCoin(ZCParams, libzerocoin::CoinDenomination::ZQ_ONE, true); const CPrivKey privKey = privCoin.getPrivKey(); CZerocoinMint mint = CZerocoinMint( diff --git a/src/timedata.cpp b/src/timedata.cpp index cbf4d3b6ace4..1cce2009de6b 100644 --- a/src/timedata.cpp +++ b/src/timedata.cpp @@ -12,7 +12,6 @@ #include "utilstrencodings.h" -using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; @@ -44,7 +43,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) { LOCK(cs_nTimeOffset); // Ignore duplicates - static set setKnown; + static std::set setKnown; if (!setKnown.insert(ip).second) return; @@ -89,7 +88,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) if (!fMatch) { fDone = true; - string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong PIVX Core will not work properly."); + std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong PIVX Core will not work properly."); strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); diff --git a/src/tinyformat.h b/src/tinyformat.h index 68926d6a8e06..eee9de7e4400 100644 --- a/src/tinyformat.h +++ b/src/tinyformat.h @@ -355,7 +355,7 @@ maxParams = 16 def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1): for j in range(startInd,maxParams+1): - list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)]) + std::list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)]) cog.outl(lineTemplate % {'j':j, 'list':list}) makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s', diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp index 5ae17f3846dd..e23c3c1d212f 100644 --- a/src/torcontrol.cpp +++ b/src/torcontrol.cpp @@ -361,7 +361,7 @@ static std::map ParseTorReplyMapping(const std::string } /** Read full contents of a file and return them in a std::string. - * Returns a pair . + * Returns a pair . * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string. * * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data diff --git a/src/txdb.cpp b/src/txdb.cpp index 3ea4cc97340a..1eb12c739fdf 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -15,15 +15,13 @@ #include -using namespace std; -using namespace libzerocoin; void static BatchWriteCoins(CLevelDBBatch& batch, const uint256& hash, const CCoins& coins) { if (coins.IsPruned()) - batch.Erase(make_pair('c', hash)); + batch.Erase(std::make_pair('c', hash)); else - batch.Write(make_pair('c', hash), coins); + batch.Write(std::make_pair('c', hash), coins); } void static BatchWriteHashBestChain(CLevelDBBatch& batch, const uint256& hash) @@ -37,12 +35,12 @@ CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(Get bool CCoinsViewDB::GetCoins(const uint256& txid, CCoins& coins) const { - return db.Read(make_pair('c', txid), coins); + return db.Read(std::make_pair('c', txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256& txid) const { - return db.Exists(make_pair('c', txid)); + return db.Exists(std::make_pair('c', txid)); } uint256 CCoinsViewDB::GetBestBlock() const @@ -80,12 +78,12 @@ CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevel bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { - return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); + return Write(std::make_pair('b', blockindex.GetBlockHash()), blockindex); } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo& info) { - return Read(make_pair('f', nFile), info); + return Read(std::make_pair('f', nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) @@ -164,25 +162,25 @@ bool CCoinsViewDB::GetStats(CCoinsStats& stats) const bool CBlockTreeDB::WriteBatchSync(const std::vector >& fileInfo, int nLastFile, const std::vector& blockinfo) { CLevelDBBatch batch; for (std::vector >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) { - batch.Write(make_pair('f', it->first), *it->second); + batch.Write(std::make_pair('f', it->first), *it->second); } batch.Write('l', nLastFile); for (std::vector::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) { - batch.Write(make_pair('b', (*it)->GetBlockHash()), CDiskBlockIndex(*it)); + batch.Write(std::make_pair('b', (*it)->GetBlockHash()), CDiskBlockIndex(*it)); } return WriteBatch(batch, true); } bool CBlockTreeDB::ReadTxIndex(const uint256& txid, CDiskTxPos& pos) { - return Read(make_pair('t', txid), pos); + return Read(std::make_pair('t', txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector >& vect) { CLevelDBBatch batch; for (std::vector >::const_iterator it = vect.begin(); it != vect.end(); it++) - batch.Write(make_pair('t', it->first), it->second); + batch.Write(std::make_pair('t', it->first), it->second); return WriteBatch(batch); } @@ -215,7 +213,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() boost::scoped_ptr pcursor(NewIterator()); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); - ssKeySet << make_pair('b', uint256(0)); + ssKeySet << std::make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex @@ -298,9 +296,9 @@ bool CZerocoinDB::WriteCoinMintBatch(const std::vector >::const_iterator it=mintInfo.begin(); it != mintInfo.end(); it++) { - PublicCoin pubCoin = it->first; + libzerocoin::PublicCoin pubCoin = it->first; uint256 hash = GetPubCoinHash(pubCoin.getValue()); - batch.Write(make_pair('m', hash), it->second); + batch.Write(std::make_pair('m', hash), it->second); ++count; } @@ -315,13 +313,13 @@ bool CZerocoinDB::ReadCoinMint(const CBigNum& bnPubcoin, uint256& hashTx) bool CZerocoinDB::ReadCoinMint(const uint256& hashPubcoin, uint256& hashTx) { - return Read(make_pair('m', hashPubcoin), hashTx); + return Read(std::make_pair('m', hashPubcoin), hashTx); } bool CZerocoinDB::EraseCoinMint(const CBigNum& bnPubcoin) { uint256 hash = GetPubCoinHash(bnPubcoin); - return Erase(make_pair('m', hash)); + return Erase(std::make_pair('m', hash)); } bool CZerocoinDB::WriteCoinSpendBatch(const std::vector >& spendInfo) @@ -333,7 +331,7 @@ bool CZerocoinDB::WriteCoinSpendBatch(const std::vectorsecond); + batch.Write(std::make_pair('s', hash), it->second); ++count; } @@ -347,12 +345,12 @@ bool CZerocoinDB::ReadCoinSpend(const CBigNum& bnSerial, uint256& txHash) ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); - return Read(make_pair('s', hash), txHash); + return Read(std::make_pair('s', hash), txHash); } bool CZerocoinDB::ReadCoinSpend(const uint256& hashSerial, uint256 &txHash) { - return Read(make_pair('s', hashSerial), txHash); + return Read(std::make_pair('s', hashSerial), txHash); } bool CZerocoinDB::EraseCoinSpend(const CBigNum& bnSerial) @@ -361,7 +359,7 @@ bool CZerocoinDB::EraseCoinSpend(const CBigNum& bnSerial) ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); - return Erase(make_pair('s', hash)); + return Erase(std::make_pair('s', hash)); } bool CZerocoinDB::WipeCoins(std::string strType) @@ -373,7 +371,7 @@ bool CZerocoinDB::WipeCoins(std::string strType) char type = (strType == "spends" ? 's' : 'm'); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); - ssKeySet << make_pair(type, uint256(0)); + ssKeySet << std::make_pair(type, uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex std::set setDelete; @@ -400,7 +398,7 @@ bool CZerocoinDB::WipeCoins(std::string strType) } for (auto& hash : setDelete) { - if (!Erase(make_pair(type, hash))) + if (!Erase(std::make_pair(type, hash))) LogPrintf("%s: error failed to delete %s\n", __func__, hash.GetHex()); } @@ -410,16 +408,16 @@ bool CZerocoinDB::WipeCoins(std::string strType) bool CZerocoinDB::WriteAccumulatorValue(const uint32_t& nChecksum, const CBigNum& bnValue) { LogPrint("zero","%s : checksum:%d val:%s\n", __func__, nChecksum, bnValue.GetHex()); - return Write(make_pair('2', nChecksum), bnValue); + return Write(std::make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::ReadAccumulatorValue(const uint32_t& nChecksum, CBigNum& bnValue) { - return Read(make_pair('2', nChecksum), bnValue); + return Read(std::make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::EraseAccumulatorValue(const uint32_t& nChecksum) { LogPrint("zero", "%s : checksum:%d\n", __func__, nChecksum); - return Erase(make_pair('2', nChecksum)); + return Erase(std::make_pair('2', nChecksum)); } diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 3e6fc77d8c2a..0238b051fde9 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -15,7 +15,6 @@ #include -using namespace std; CTxMemPoolEntry::CTxMemPoolEntry() : nFee(0), nTxSize(0), nModSize(0), nTime(0), dPriority(0.0) { @@ -135,13 +134,13 @@ class CBlockAverage if (AreSane(vecFee, minRelayFee)) feeSamples.insert(feeSamples.end(), vecFee.begin(), vecFee.end()); else - throw runtime_error("Corrupt fee value in estimates file."); + throw std::runtime_error("Corrupt fee value in estimates file."); std::vector vecPriority; filein >> vecPriority; if (AreSane(vecPriority)) prioritySamples.insert(prioritySamples.end(), vecPriority.begin(), vecPriority.end()); else - throw runtime_error("Corrupt priority value in estimates file."); + throw std::runtime_error("Corrupt priority value in estimates file."); if (feeSamples.size() + prioritySamples.size() > 0) LogPrint("estimatefee", "Read %d fee samples and %d priority samples\n", feeSamples.size(), prioritySamples.size()); @@ -168,7 +167,7 @@ class CMinerPolicyEstimator void seenTxConfirm(const CFeeRate& feeRate, const CFeeRate& minRelayFee, double dPriority, int nBlocksAgo) { // Last entry records "everything else". - int nBlocksTruncated = min(nBlocksAgo, (int)history.size() - 1); + int nBlocksTruncated = std::min(nBlocksAgo, (int)history.size() - 1); assert(nBlocksTruncated >= 0); // We need to guess why the transaction was included in a block-- either @@ -287,7 +286,7 @@ class CMinerPolicyEstimator size_t nPrevSize = 0; for (int i = 0; i < nBlocksToConfirm; i++) nPrevSize += history.at(i).FeeSamples(); - size_t index = min(nPrevSize + nBucketSize / 2, sortedFeeSamples.size() - 1); + size_t index = std::min(nPrevSize + nBucketSize / 2, sortedFeeSamples.size() - 1); return sortedFeeSamples[index]; } double estimatePriority(int nBlocksToConfirm) @@ -316,7 +315,7 @@ class CMinerPolicyEstimator size_t nPrevSize = 0; for (int i = 0; i < nBlocksToConfirm; i++) nPrevSize += history.at(i).PrioritySamples(); - size_t index = min(nPrevSize + nBucketSize / 2, sortedPrioritySamples.size() - 1); + size_t index = std::min(nPrevSize + nBucketSize / 2, sortedPrioritySamples.size() - 1); return sortedPrioritySamples[index]; } @@ -336,7 +335,7 @@ class CMinerPolicyEstimator size_t numEntries; filein >> numEntries; if (numEntries <= 0 || numEntries > 10000) - throw runtime_error("Corrupt estimates file. Must have between 1 and 10k entries."); + throw std::runtime_error("Corrupt estimates file. Must have between 1 and 10k entries."); std::vector fileHistory; @@ -470,7 +469,7 @@ void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned in { // Remove transactions spending a coinbase which are now immature LOCK(cs); - list transactionsToRemove; + std::list transactionsToRemove; for (std::map::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { const CTransaction& tx = it->second.GetTx(); for (const CTxIn& txin : tx.vin) { @@ -486,7 +485,7 @@ void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned in } } for (const CTransaction& tx : transactionsToRemove) { - list removed; + std::list removed; remove(tx, removed, true); } } @@ -494,7 +493,7 @@ void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned in void CTxMemPool::removeConflicts(const CTransaction& tx, std::list& removed) { // Remove transactions which depend on inputs of tx, recursively - list result; + std::list result; LOCK(cs); for (const CTxIn& txin : tx.vin) { std::map::iterator it = mapNextTx.find(txin.prevout); @@ -550,7 +549,7 @@ void CTxMemPool::check(const CCoinsViewCache* pcoins) const CCoinsViewCache mempoolDuplicate(const_cast(pcoins)); LOCK(cs); - list waitingOnDependants; + std::list waitingOnDependants; for (std::map::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { unsigned int i = 0; checkTotal += it->second.GetTxSize(); @@ -606,7 +605,7 @@ void CTxMemPool::check(const CCoinsViewCache* pcoins) const } for (std::map::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) { uint256 hash = it->second.ptx->GetHash(); - map::const_iterator it2 = mapTx.find(hash); + std::map::const_iterator it2 = mapTx.find(hash); const CTransaction& tx = it2->second.GetTx(); assert(it2 != mapTx.end()); assert(&tx == it->second.ptx); @@ -617,13 +616,13 @@ void CTxMemPool::check(const CCoinsViewCache* pcoins) const assert(totalTxSize == checkTotal); } -void CTxMemPool::queryHashes(vector& vtxid) +void CTxMemPool::queryHashes(std::vector& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); - for (map::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) + for (std::map::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } @@ -632,14 +631,14 @@ void CTxMemPool::getTransactions(std::set& setTxid) setTxid.clear(); LOCK(cs); - for (map::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) + for (std::map::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) setTxid.insert((*mi).first); } bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const { LOCK(cs); - map::const_iterator i = mapTx.find(hash); + std::map::const_iterator i = mapTx.find(hash); if (i == mapTx.end()) return false; result = i->second.GetTx(); return true; @@ -687,7 +686,7 @@ bool CTxMemPool::ReadFeeEstimates(CAutoFile& filein) 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); diff --git a/src/util.cpp b/src/util.cpp index b2ce25e4f1ab..a88403ec3002 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -87,13 +87,12 @@ #include #include -using namespace std; // PIVX only features // Masternode bool fMasterNode = false; -string strMasterNodePrivKey = ""; -string strMasterNodeAddr = ""; +std::string strMasterNodePrivKey = ""; +std::string strMasterNodeAddr = ""; bool fLiteMode = false; // SwiftX bool fEnableSwiftTX = true; @@ -110,16 +109,16 @@ int64_t enforceMasternodePaymentsTime = 4085657524; bool fSucessfullyLoaded = false; /** All denominations used by obfuscation */ std::vector obfuScationDenominations; -string strBudgetMode = ""; +std::string strBudgetMode = ""; -map mapArgs; -map > mapMultiArgs; +std::map mapArgs; +std::map > mapMultiArgs; bool fDebug = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; bool fServer = false; -string strMiscWarning; +std::string strMiscWarning; bool fLogTimestamps = false; bool fLogIPs = false; volatile bool fReopenDebugLog = false; @@ -215,28 +214,28 @@ bool LogAcceptCategory(const char* category) // This helps prevent issues debugging global destructors, // where mapMultiArgs might be deleted before another // global destructor calls LogPrint() - static boost::thread_specific_ptr > ptrCategory; + static boost::thread_specific_ptr > ptrCategory; if (ptrCategory.get() == NULL) { - const vector& categories = mapMultiArgs["-debug"]; - ptrCategory.reset(new set(categories.begin(), categories.end())); + const std::vector& categories = mapMultiArgs["-debug"]; + ptrCategory.reset(new std::set(categories.begin(), categories.end())); // thread_specific_ptr automatically deletes the set when the thread ends. // "pivx" is a composite category enabling all PIVX-related debug output - if (ptrCategory->count(string("pivx"))) { - ptrCategory->insert(string("obfuscation")); - ptrCategory->insert(string("swiftx")); - ptrCategory->insert(string("masternode")); - ptrCategory->insert(string("mnpayments")); - ptrCategory->insert(string("zero")); - ptrCategory->insert(string("mnbudget")); - ptrCategory->insert(string("precompute")); - ptrCategory->insert(string("staking")); + if (ptrCategory->count(std::string("pivx"))) { + ptrCategory->insert(std::string("obfuscation")); + ptrCategory->insert(std::string("swiftx")); + ptrCategory->insert(std::string("masternode")); + ptrCategory->insert(std::string("mnpayments")); + ptrCategory->insert(std::string("zero")); + ptrCategory->insert(std::string("mnbudget")); + ptrCategory->insert(std::string("precompute")); + ptrCategory->insert(std::string("staking")); } } - const set& setCategories = *ptrCategory.get(); + const std::set& setCategories = *ptrCategory.get(); // if not debugging everything and not debugging specific category, LogPrint does nothing. - if (setCategories.count(string("")) == 0 && - setCategories.count(string(category)) == 0) + if (setCategories.count(std::string("")) == 0 && + setCategories.count(std::string(category)) == 0) return false; } return true; @@ -491,8 +490,8 @@ boost::filesystem::path GetMasternodeConfigFile() return pathConfigFile; } -void ReadConfigFile(map& mapSettingsRet, - map >& mapMultiSettingsRet) +void ReadConfigFile(std::map& mapSettingsRet, + std::map >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) { @@ -503,13 +502,13 @@ void ReadConfigFile(map& mapSettingsRet, return; // Nothing to read, so just return } - set setOptions; + std::set setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override pivx.conf - string strKey = string("-") + it->string_key; - string strValue = it->value[0]; + std::string strKey = std::string("-") + it->string_key; + std::string strValue = it->value[0]; InterpretNegativeSetting(strKey, strValue); if (mapSettingsRet.count(strKey) == 0) mapSettingsRet[strKey] = strValue; diff --git a/src/utilmoneystr.cpp b/src/utilmoneystr.cpp index affc8c97618f..423e37cba36d 100644 --- a/src/utilmoneystr.cpp +++ b/src/utilmoneystr.cpp @@ -10,16 +10,15 @@ #include "tinyformat.h" #include "utilstrencodings.h" -using namespace std; -string FormatMoney(const CAmount& n, bool fPlus) +std::string FormatMoney(const CAmount& n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. int64_t n_abs = (n > 0 ? n : -n); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; - string str = strprintf("%d.%08d", quotient, remainder); + std::string str = strprintf("%d.%08d", quotient, remainder); // Right-trim excess zeros before the decimal point: int nTrim = 0; @@ -36,14 +35,14 @@ string FormatMoney(const CAmount& n, bool fPlus) } -bool ParseMoney(const string& str, CAmount& nRet) +bool ParseMoney(const std::string& str, CAmount& nRet) { return ParseMoney(str.c_str(), nRet); } bool ParseMoney(const char* pszIn, CAmount& nRet) { - string strWhole; + std::string strWhole; int64_t nUnits = 0; const char* p = pszIn; while (isspace(*p)) diff --git a/src/utilstrencodings.cpp b/src/utilstrencodings.cpp index 310383a9a32a..16fd87aa4f3d 100644 --- a/src/utilstrencodings.cpp +++ b/src/utilstrencodings.cpp @@ -18,7 +18,6 @@ #include -using namespace std; static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; @@ -65,7 +64,7 @@ signed char HexDigit(char c) return p_util_hexdigit[(unsigned char)c]; } -bool IsHex(const string& str) +bool IsHex(const std::string& str) { for (std::string::const_iterator it(str.begin()); it != str.end(); ++it) { if (HexDigit(*it) < 0) @@ -74,10 +73,10 @@ bool IsHex(const string& str) return (str.size() > 0) && (str.size() % 2 == 0); } -vector ParseHex(const char* psz) +std::vector ParseHex(const char* psz) { // convert hex dump to vector - vector vch; + std::vector vch; while (true) { while (isspace(*psz)) psz++; @@ -94,16 +93,16 @@ vector ParseHex(const char* psz) return vch; } -vector ParseHex(const string& str) +std::vector ParseHex(const std::string& str) { return ParseHex(str.c_str()); } -string EncodeBase64(const unsigned char* pch, size_t len) +std::string EncodeBase64(const unsigned char* pch, size_t len) { static const char* pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - string strRet = ""; + std::string strRet = ""; strRet.reserve((len + 2) / 3 * 4); int mode = 0, left = 0; @@ -142,12 +141,12 @@ string EncodeBase64(const unsigned char* pch, size_t len) return strRet; } -string EncodeBase64(const string& str) +std::string EncodeBase64(const std::string& str) { return EncodeBase64((const unsigned char*)str.c_str(), str.size()); } -vector DecodeBase64(const char* p, bool* pfInvalid) +std::vector DecodeBase64(const char* p, bool* pfInvalid) { static const int decode64_table[256] = { @@ -168,7 +167,7 @@ vector DecodeBase64(const char* p, bool* pfInvalid) if (pfInvalid) *pfInvalid = false; - vector vchRet; + std::vector vchRet; vchRet.reserve(strlen(p) * 3 / 4); int mode = 0; @@ -226,10 +225,10 @@ vector DecodeBase64(const char* p, bool* pfInvalid) return vchRet; } -string DecodeBase64(const string& str) +std::string DecodeBase64(const std::string& str) { - vector vchRet = DecodeBase64(str.c_str()); - return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); + std::vector vchRet = DecodeBase64(str.c_str()); + return (vchRet.size() == 0) ? std::string() : std::string((const char*)&vchRet[0], vchRet.size()); } // Base64 decoding with secure memory allocation @@ -246,7 +245,7 @@ SecureString DecodeBase64Secure(const SecureString& input) // Prepare buffer to receive decoded data if (input.size() % 4 != 0) { - throw runtime_error("Input length should be a multiple of 4"); + throw std::runtime_error("Input length should be a multiple of 4"); } size_t nMaxLen = input.size() / 4 * 3; // upper bound, guaranteed divisible by 4 output.resize(nMaxLen); @@ -288,11 +287,11 @@ SecureString EncodeBase64Secure(const SecureString& input) return output; } -string EncodeBase32(const unsigned char* pch, size_t len) +std::string EncodeBase32(const unsigned char* pch, size_t len) { static const char* pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; - string strRet = ""; + std::string strRet = ""; strRet.reserve((len + 4) / 5 * 8); int mode = 0, left = 0; @@ -344,12 +343,12 @@ string EncodeBase32(const unsigned char* pch, size_t len) return strRet; } -string EncodeBase32(const string& str) +std::string EncodeBase32(const std::string& str) { return EncodeBase32((const unsigned char*)str.c_str(), str.size()); } -vector DecodeBase32(const char* p, bool* pfInvalid) +std::vector DecodeBase32(const char* p, bool* pfInvalid) { static const int decode32_table[256] = { @@ -370,7 +369,7 @@ vector DecodeBase32(const char* p, bool* pfInvalid) if (pfInvalid) *pfInvalid = false; - vector vchRet; + std::vector vchRet; vchRet.reserve((strlen(p)) * 5 / 8); int mode = 0; @@ -462,10 +461,10 @@ vector DecodeBase32(const char* p, bool* pfInvalid) return vchRet; } -string DecodeBase32(const string& str) +std::string DecodeBase32(const std::string& str) { - vector vchRet = DecodeBase32(str.c_str()); - return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); + std::vector vchRet = DecodeBase32(str.c_str()); + return (vchRet.size() == 0) ? std::string() : std::string((const char*)&vchRet[0], vchRet.size()); } static bool ParsePrechecks(const std::string& str) diff --git a/src/utiltime.cpp b/src/utiltime.cpp index 79adb4e7c20a..5c25643d316a 100644 --- a/src/utiltime.cpp +++ b/src/utiltime.cpp @@ -14,7 +14,6 @@ #include #include -using namespace std; static int64_t nMockTime = 0; //! For unit testing diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp index 418aa0e7e618..809756607eda 100644 --- a/src/wallet/db.cpp +++ b/src/wallet/db.cpp @@ -21,8 +21,6 @@ #include #include -using namespace std; -using namespace boost; unsigned int nWalletDBUpdated; @@ -120,7 +118,7 @@ bool CDBEnv::Open(const boost::filesystem::path& pathIn) void CDBEnv::MakeMock() { if (fDbEnvInit) - throw runtime_error("CDBEnv::MakeMock : Already initialized"); + throw std::runtime_error("CDBEnv::MakeMock : Already initialized"); boost::this_thread::interruption_point(); @@ -143,7 +141,7 @@ void CDBEnv::MakeMock() DB_PRIVATE, S_IRUSR | S_IWUSR); if (ret > 0) - throw runtime_error(strprintf("CDBEnv::MakeMock : Error %d opening database environment.", ret)); + throw std::runtime_error(strprintf("CDBEnv::MakeMock : Error %d opening database environment.", ret)); fDbEnvInit = true; fMockDb = true; @@ -175,7 +173,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive, std::vectorget_mpf(); ret = mpf->set_flags(DB_MPOOL_NOFILE, 1); if (ret != 0) - throw runtime_error(strprintf("CDB : Failed to configure for no temp file backing for database %s", strFile)); + throw std::runtime_error(strprintf("CDB : Failed to configure for no temp file backing for database %s", strFile)); } ret = pdb->open(NULL, // Txn pointer @@ -268,10 +266,10 @@ CDB::CDB(const std::string& strFilename, const char* pszMode) : pdb(NULL), activ pdb = NULL; --bitdb.mapFileUseCount[strFile]; strFile = ""; - throw runtime_error(strprintf("CDB : Error %d, can't open database %s", ret, strFile)); + throw std::runtime_error(strprintf("CDB : Error %d, can't open database %s", ret, strFile)); } - if (fCreate && !Exists(string("version"))) { + if (fCreate && !Exists(std::string("version"))) { bool fTmp = fReadOnly; fReadOnly = false; WriteVersion(CLIENT_VERSION); @@ -313,7 +311,7 @@ void CDB::Close() } } -void CDBEnv::CloseDb(const string& strFile) +void CDBEnv::CloseDb(const std::string& strFile) { { LOCK(cs_db); @@ -327,7 +325,7 @@ void CDBEnv::CloseDb(const string& strFile) } } -bool CDBEnv::RemoveDb(const string& strFile) +bool CDBEnv::RemoveDb(const std::string& strFile) { this->CloseDb(strFile); @@ -336,7 +334,7 @@ bool CDBEnv::RemoveDb(const string& strFile) return (rc == 0); } -bool CDB::Rewrite(const string& strFile, const char* pszSkip) +bool CDB::Rewrite(const std::string& strFile, const char* pszSkip) { while (true) { { @@ -349,7 +347,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip) bool fSuccess = true; LogPrintf("CDB::Rewrite : Rewriting %s...\n", strFile); - string strFileRes = strFile + ".rewrite"; + std::string strFileRes = strFile + ".rewrite"; { // surround usage of db with extra {} CDB db(strFile.c_str(), "r"); Db* pdbCopy = new Db(bitdb.dbenv, 0); @@ -429,9 +427,9 @@ void CDBEnv::Flush(bool fShutdown) return; { LOCK(cs_db); - map::iterator mi = mapFileUseCount.begin(); + std::map::iterator mi = mapFileUseCount.begin(); while (mi != mapFileUseCount.end()) { - string strFile = (*mi).first; + std::string strFile = (*mi).first; int nRefCount = (*mi).second; LogPrint("db", "CDBEnv::Flush : Flushing %s (refcount = %d)...\n", strFile, nRefCount); if (nRefCount == 0) { diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 0e55dcc30506..16099c27c7bd 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -27,7 +27,6 @@ #include -using namespace std; void EnsureWalletIsUnlocked(bool fAllowAnonOnly); @@ -81,7 +80,7 @@ std::string DecodeDumpString(const std::string& str) UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "importprivkey \"pivxprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" + HelpRequiringPassphrase() + "\n" @@ -107,8 +106,8 @@ UniValue importprivkey(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); - string strSecret = params[0].get_str(); - string strLabel = ""; + std::string strSecret = params[0].get_str(); + std::string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); @@ -155,7 +154,7 @@ UniValue importprivkey(const UniValue& params, bool fHelp) UniValue importaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" @@ -188,7 +187,7 @@ UniValue importaddress(const UniValue& params, bool fHelp) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address or script"); } - string strLabel = ""; + std::string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); @@ -226,7 +225,7 @@ UniValue importaddress(const UniValue& params, bool fHelp) UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" + HelpRequiringPassphrase() + "\n" @@ -246,7 +245,7 @@ UniValue importwallet(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); - ifstream file; + std::ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); @@ -329,7 +328,7 @@ UniValue importwallet(const UniValue& params, bool fHelp) UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "dumpprivkey \"pivxaddress\"\n" "\nReveals the private key corresponding to 'pivxaddress'.\n" "Then the importprivkey can be used with this output\n" + @@ -348,7 +347,7 @@ UniValue dumpprivkey(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); - string strAddress = params[0].get_str(); + std::string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address"); @@ -365,7 +364,7 @@ UniValue dumpprivkey(const UniValue& params, bool fHelp) UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" + HelpRequiringPassphrase() + "\n" @@ -383,7 +382,7 @@ UniValue dumpwallet(const UniValue& params, bool fHelp) boost::filesystem::path filepath = params[0].get_str().c_str(); filepath = boost::filesystem::absolute(filepath); - ofstream file; + std::ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); @@ -435,7 +434,7 @@ UniValue dumpwallet(const UniValue& params, bool fHelp) UniValue bip38encrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "bip38encrypt \"pivxaddress\" \"passphrase\"\n" "\nEncrypts a private key corresponding to 'pivxaddress'.\n" + HelpRequiringPassphrase() + "\n" @@ -455,8 +454,8 @@ UniValue bip38encrypt(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); - string strAddress = params[0].get_str(); - string strPassphrase = params[1].get_str(); + std::string strAddress = params[0].get_str(); + std::string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) @@ -469,7 +468,7 @@ UniValue bip38encrypt(const UniValue& params, bool fHelp) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); uint256 privKey = vchSecret.GetPrivKey_256(); - string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed()); + std::string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed()); UniValue result(UniValue::VOBJ); result.push_back(Pair("Addess", strAddress)); @@ -481,7 +480,7 @@ UniValue bip38encrypt(const UniValue& params, bool fHelp) UniValue bip38decrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "bip38decrypt \"pivxaddress\" \"passphrase\"\n" "\nDecrypts and then imports password protected private key.\n" + HelpRequiringPassphrase() + "\n" @@ -502,8 +501,8 @@ UniValue bip38decrypt(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ - string strKey = params[0].get_str(); - string strPassphrase = params[1].get_str(); + std::string strKey = params[0].get_str(); + std::string strPassphrase = params[1].get_str(); uint256 privKey; bool fCompressed; diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 236312d1bd74..dc473bd1cd73 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -29,9 +29,6 @@ #include -using namespace std; -using namespace boost; -using namespace boost::assign; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; @@ -68,13 +65,13 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) entry.push_back(Pair("walletconflicts", conflicts)); entry.push_back(Pair("time", wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); - for (const PAIRTYPE(string, string) & item : wtx.mapValue) + for (const PAIRTYPE(std::string, std::string) & item : wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } -string AccountFromValue(const UniValue& value) +std::string AccountFromValue(const UniValue& value) { - string strAccount = value.get_str(); + std::string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; @@ -83,7 +80,7 @@ string AccountFromValue(const UniValue& value) UniValue getnewaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "getnewaddress ( \"account\" )\n" "\nReturns a new PIVX address for receiving payments.\n" "If 'account' is specified (recommended), it is added to the address book \n" @@ -102,7 +99,7 @@ UniValue getnewaddress(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error - string strAccount; + std::string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); @@ -121,7 +118,7 @@ UniValue getnewaddress(const UniValue& params, bool fHelp) } -CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew = false) +CBitcoinAddress GetAccountAddress(std::string strAccount, bool bForceNew = false) { CWalletDB walletdb(pwalletMain->strWalletFile); @@ -133,7 +130,7 @@ CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew = false) // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID()); - for (map::iterator it = pwalletMain->mapWallet.begin(); + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; @@ -158,7 +155,7 @@ CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew = false) UniValue getaccountaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getaccountaddress \"account\"\n" "\nReturns the current PIVX address for receiving payments to this account.\n" @@ -175,7 +172,7 @@ UniValue getaccountaddress(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error - string strAccount = AccountFromValue(params[0]); + std::string strAccount = AccountFromValue(params[0]); UniValue ret(UniValue::VSTR); @@ -187,7 +184,7 @@ UniValue getaccountaddress(const UniValue& params, bool fHelp) UniValue getrawchangeaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "getrawchangeaddress\n" "\nReturns a new PIVX address, for receiving change.\n" "This is for use with raw transactions, NOT normal use.\n" @@ -219,7 +216,7 @@ UniValue getrawchangeaddress(const UniValue& params, bool fHelp) UniValue setaccount(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "setaccount \"pivxaddress\" \"account\"\n" "\nSets the account associated with the given address.\n" @@ -237,7 +234,7 @@ UniValue setaccount(const UniValue& params, bool fHelp) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address"); - string strAccount; + std::string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); @@ -245,7 +242,7 @@ UniValue setaccount(const UniValue& params, bool fHelp) if (IsMine(*pwalletMain, address.Get())) { // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { - string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name; + std::string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } @@ -260,7 +257,7 @@ UniValue setaccount(const UniValue& params, bool fHelp) UniValue getaccount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getaccount \"pivxaddress\"\n" "\nReturns the account associated with the given address.\n" @@ -279,8 +276,8 @@ UniValue getaccount(const UniValue& params, bool fHelp) if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address"); - string strAccount; - map::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); + std::string strAccount; + std::map::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty()) strAccount = (*mi).second.name; return strAccount; @@ -290,7 +287,7 @@ UniValue getaccount(const UniValue& params, bool fHelp) UniValue getaddressesbyaccount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "getaddressesbyaccount \"account\"\n" "\nReturns the list of addresses for the given account.\n" @@ -308,13 +305,13 @@ UniValue getaddressesbyaccount(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - string strAccount = AccountFromValue(params[0]); + std::string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account UniValue ret(UniValue::VARR); for (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item : pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; - const string& strName = item.second.name; + const std::string& strName = item.second.name; if (strName == strAccount) ret.push_back(address.ToString()); } @@ -330,7 +327,7 @@ void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, if (nValue > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); - string strError; + std::string strError; if (pwalletMain->IsLocked()) { strError = "Error: Wallet locked, unable to create transaction!"; LogPrintf("SendMoney() : %s", strError); @@ -356,7 +353,7 @@ void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, UniValue sendtoaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) - throw runtime_error( + throw std::runtime_error( "sendtoaddress \"pivxaddress\" amount ( \"comment\" \"comment-to\" )\n" "\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" + HelpRequiringPassphrase() + "\n" @@ -404,7 +401,7 @@ UniValue sendtoaddress(const UniValue& params, bool fHelp) UniValue sendtoaddressix(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) - throw runtime_error( + throw std::runtime_error( "sendtoaddressix \"pivxaddress\" amount ( \"comment\" \"comment-to\" )\n" "\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" + HelpRequiringPassphrase() + "\n" @@ -452,7 +449,7 @@ UniValue sendtoaddressix(const UniValue& params, bool fHelp) UniValue listaddressgroupings(const UniValue& params, bool fHelp) { if (fHelp) - throw runtime_error( + throw std::runtime_error( "listaddressgroupings\n" "\nLists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" @@ -477,8 +474,8 @@ UniValue listaddressgroupings(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); UniValue jsonGroupings(UniValue::VARR); - map balances = pwalletMain->GetAddressBalances(); - for (set grouping : pwalletMain->GetAddressGroupings()) { + std::map balances = pwalletMain->GetAddressBalances(); + for (std::set grouping : pwalletMain->GetAddressGroupings()) { UniValue jsonGrouping(UniValue::VARR); for (CTxDestination address : grouping) { UniValue addressInfo(UniValue::VARR); @@ -498,7 +495,7 @@ UniValue listaddressgroupings(const UniValue& params, bool fHelp) UniValue signmessage(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "signmessage \"pivxaddress\" \"message\"\n" "\nSign a message with the private key of an address" + HelpRequiringPassphrase() + "\n" @@ -524,8 +521,8 @@ UniValue signmessage(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); - string strAddress = params[0].get_str(); - string strMessage = params[1].get_str(); + std::string strAddress = params[0].get_str(); + std::string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) @@ -543,7 +540,7 @@ UniValue signmessage(const UniValue& params, bool fHelp) ss << strMessageMagic; ss << strMessage; - vector vchSig; + std::vector vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); @@ -609,7 +606,7 @@ UniValue getreceivedbyaddress(const UniValue& params, bool fHelp) UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "getreceivedbyaccount \"account\" ( minconf )\n" "\nReturns the total amount received by addresses with in transactions with at least [minconf] confirmations.\n" @@ -638,12 +635,12 @@ UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account - string strAccount = AccountFromValue(params[0]); - set setAddress = pwalletMain->GetAccountAddresses(strAccount); + std::string strAccount = AccountFromValue(params[0]); + std::set setAddress = pwalletMain->GetAccountAddresses(strAccount); // Tally CAmount nAmount = 0; - for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !IsFinalTx(wtx)) continue; @@ -660,12 +657,12 @@ UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) } -CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter) +CAmount GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter) { CAmount nBalance = 0; // Tally wallet transactions - for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; @@ -684,7 +681,7 @@ CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMi return nBalance; } -CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter) +CAmount GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth, filter); @@ -694,7 +691,7 @@ CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminef UniValue getbalance(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "getbalance ( \"account\" minconf includeWatchonly )\n" "\nIf account is not specified, returns the server's total available balance (excluding zerocoins).\n" "If account is specified, returns the balance in the account.\n" @@ -739,15 +736,15 @@ UniValue getbalance(const UniValue& params, bool fHelp) // (GetBalance() sums up all unspent TxOuts) // getbalance and "getbalance * 1 true" should return the same number CAmount nBalance = 0; - for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; CAmount allFee; - string strSentAccount; - list listReceived; - list listSent; + std::string strSentAccount; + std::list listReceived; + std::list listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (wtx.GetDepthInMainChain() >= nMinDepth) { for (const COutputEntry& r : listReceived) @@ -760,7 +757,7 @@ UniValue getbalance(const UniValue& params, bool fHelp) return ValueFromAmount(nBalance); } - string strAccount = AccountFromValue(params[0]); + std::string strAccount = AccountFromValue(params[0]); CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter); @@ -770,7 +767,7 @@ UniValue getbalance(const UniValue& params, bool fHelp) UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp) { if (fHelp || params.size() > 0) - throw runtime_error( + throw std::runtime_error( "getunconfirmedbalance\n" "Returns the server's total unconfirmed balance\n"); @@ -853,7 +850,7 @@ UniValue movecmd(const UniValue& params, bool fHelp) UniValue sendfrom(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) - throw runtime_error( + throw std::runtime_error( "sendfrom \"fromaccount\" \"topivxaddress\" amount ( minconf \"comment\" \"comment-to\" )\n" "\nSent an amount from an account to a pivx address.\n" "The amount is a real and is rounded to the nearest 0.00000001." + @@ -883,7 +880,7 @@ UniValue sendfrom(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - string strAccount = AccountFromValue(params[0]); + std::string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address"); @@ -915,7 +912,7 @@ UniValue sendfrom(const UniValue& params, bool fHelp) UniValue sendmany(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) - throw runtime_error( + throw std::runtime_error( "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" )\n" "\nSend multiple times. Amounts are double-precision floating point numbers." + HelpRequiringPassphrase() + "\n" @@ -944,7 +941,7 @@ UniValue sendmany(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - string strAccount = AccountFromValue(params[0]); + std::string strAccount = AccountFromValue(params[0]); UniValue sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) @@ -955,25 +952,25 @@ UniValue sendmany(const UniValue& params, bool fHelp) if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); - set setAddress; - vector > vecSend; + std::set setAddress; + std::vector > vecSend; CAmount totalAmount = 0; - vector keys = sendTo.getKeys(); - for (const string& name_ : keys) { + std::vector keys = sendTo.getKeys(); + for (const std::string& name_ : keys) { CBitcoinAddress address(name_); if (!address.IsValid()) - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid PIVX address: ")+name_); + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid PIVX address: ")+name_); if (setAddress.count(address)) - throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); + throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); totalAmount += nAmount; - vecSend.push_back(make_pair(scriptPubKey, nAmount)); + vecSend.push_back(std::make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); @@ -986,7 +983,7 @@ UniValue sendmany(const UniValue& params, bool fHelp) // Send CReserveKey keyChange(pwalletMain); CAmount nFeeRequired = 0; - string strFailReason; + std::string strFailReason; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); @@ -1002,7 +999,7 @@ extern CScript _createmultisig_redeemScript(const UniValue& params); UniValue addmultisigaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n" "\nAdd a nrequired-to-sign multisignature address to the wallet.\n" "Each key is a PIVX address or hex-encoded public key.\n" @@ -1028,7 +1025,7 @@ UniValue addmultisigaddress(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - string strAccount; + std::string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); @@ -1046,7 +1043,7 @@ struct tallyitem { CAmount nAmount; int nConf; int nBCConf; - vector txids; + std::vector txids; bool fIsWatchonly; tallyitem() { @@ -1075,8 +1072,8 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) filter = filter | ISMINE_WATCH_ONLY; // Tally - map mapTally; - for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { + std::map mapTally; + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !IsFinalTx(wtx)) @@ -1098,8 +1095,8 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; - item.nConf = min(item.nConf, nDepth); - item.nBCConf = min(item.nBCConf, nBCDepth); + item.nConf = std::min(item.nConf, nDepth); + item.nBCConf = std::min(item.nBCConf, nBCDepth); item.txids.push_back(wtx.GetHash()); if (mine & ISMINE_WATCH_ONLY) item.fIsWatchonly = true; @@ -1108,11 +1105,11 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) // Reply UniValue ret(UniValue::VARR); - map mapAccountTally; + std::map mapAccountTally; for (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item : pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; - const string& strAccount = item.second.name; - map::iterator it = mapTally.find(address); + const std::string& strAccount = item.second.name; + std::map::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; @@ -1130,8 +1127,8 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; - item.nConf = min(item.nConf, nConf); - item.nBCConf = min(item.nBCConf, nBCConf); + item.nConf = std::min(item.nConf, nConf); + item.nBCConf = std::min(item.nBCConf, nBCConf); item.fIsWatchonly = fIsWatchonly; } else { UniValue obj(UniValue::VOBJ); @@ -1154,7 +1151,7 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) } if (fByAccounts) { - for (map::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { + for (std::map::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { CAmount nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; int nBCConf = (*it).second.nBCConf; @@ -1175,7 +1172,7 @@ UniValue ListReceived(const UniValue& params, bool fByAccounts) UniValue listreceivedbyaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "listreceivedbyaddress ( minconf includeempty includeWatchonly)\n" "\nList balances by receiving address.\n" @@ -1208,7 +1205,7 @@ UniValue listreceivedbyaddress(const UniValue& params, bool fHelp) UniValue listreceivedbyaccount(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 3) - throw runtime_error( + throw std::runtime_error( "listreceivedbyaccount ( minconf includeempty includeWatchonly)\n" "\nList balances by account.\n" @@ -1244,16 +1241,16 @@ static void MaybePushAddress(UniValue & entry, const CTxDestination &dest) entry.push_back(Pair("address", addr.ToString())); } -void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) +void ListTransactions(const CWalletTx& wtx, const std::string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) { CAmount nFee; - string strSentAccount; - list listReceived; - list listSent; + std::string strSentAccount; + std::list listReceived; + std::list listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter); - bool fAllAccounts = (strAccount == string("*")); + bool fAllAccounts = (strAccount == std::string("*")); bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY); // Sent @@ -1278,7 +1275,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { for (const COutputEntry& r : listReceived) { - string account; + std::string account; if (pwalletMain->mapAddressBook.count(r.destination)) account = pwalletMain->mapAddressBook[r.destination].name; if (fAllAccounts || (account == strAccount)) { @@ -1307,9 +1304,9 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe } } -void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret) +void AcentryToJSON(const CAccountingEntry& acentry, const std::string& strAccount, UniValue& ret) { - bool fAllAccounts = (strAccount == string("*")); + bool fAllAccounts = (strAccount == std::string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { UniValue entry(UniValue::VOBJ); @@ -1326,7 +1323,7 @@ void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Un UniValue listtransactions(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 4) - throw runtime_error( + throw std::runtime_error( "listtransactions ( \"account\" count from includeWatchonly)\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n" @@ -1385,7 +1382,7 @@ UniValue listtransactions(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - string strAccount = "*"; + std::string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; @@ -1426,11 +1423,11 @@ UniValue listtransactions(const UniValue& params, bool fHelp) if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; - vector arrTmp = ret.getValues(); + std::vector arrTmp = ret.getValues(); - vector::iterator first = arrTmp.begin(); + std::vector::iterator first = arrTmp.begin(); std::advance(first, nFrom); - vector::iterator last = arrTmp.begin(); + std::vector::iterator last = arrTmp.begin(); std::advance(last, nFrom+nCount); if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end()); @@ -1448,7 +1445,7 @@ UniValue listtransactions(const UniValue& params, bool fHelp) UniValue listaccounts(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "listaccounts ( minconf includeWatchonly)\n" "\nReturns Object that has account names as keys, account balances as values.\n" @@ -1482,18 +1479,18 @@ UniValue listaccounts(const UniValue& params, bool fHelp) if (params[1].get_bool()) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; - map mapAccountBalances; + std::map mapAccountBalances; for (const PAIRTYPE(CTxDestination, CAddressBookData) & entry : pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me mapAccountBalances[entry.second.name] = 0; } - for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; CAmount nFee; - string strSentAccount; - list listReceived; - list listSent; + std::string strSentAccount; + std::list listReceived; + std::list listSent; int nDepth = wtx.GetDepthInMainChain(); if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) continue; @@ -1510,12 +1507,12 @@ UniValue listaccounts(const UniValue& params, bool fHelp) } } - const list & acentries = pwalletMain->laccentries; + const std::list & acentries = pwalletMain->laccentries; for (const CAccountingEntry& entry : acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; UniValue ret(UniValue::VOBJ); - for (const PAIRTYPE(string, CAmount) & accountBalance : mapAccountBalances) { + for (const PAIRTYPE(std::string, CAmount) & accountBalance : mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; @@ -1524,7 +1521,7 @@ UniValue listaccounts(const UniValue& params, bool fHelp) UniValue listsinceblock(const UniValue& params, bool fHelp) { if (fHelp) - throw runtime_error( + throw std::runtime_error( "listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n" "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n" @@ -1592,7 +1589,7 @@ UniValue listsinceblock(const UniValue& params, bool fHelp) UniValue transactions(UniValue::VARR); - for (map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { + for (std::map::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain(false) < depth) @@ -1612,7 +1609,7 @@ UniValue listsinceblock(const UniValue& params, bool fHelp) UniValue gettransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "gettransaction \"txid\" ( includeWatchonly )\n" "\nGet detailed information about in-wallet transaction \n" @@ -1679,7 +1676,7 @@ UniValue gettransaction(const UniValue& params, bool fHelp) ListTransactions(wtx, "*", 0, false, details, filter); entry.push_back(Pair("details", details)); - string strHex = EncodeHexTx(static_cast(wtx)); + std::string strHex = EncodeHexTx(static_cast(wtx)); entry.push_back(Pair("hex", strHex)); return entry; @@ -1689,7 +1686,7 @@ UniValue gettransaction(const UniValue& params, bool fHelp) UniValue backupwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "backupwallet \"destination\"\n" "\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n" @@ -1701,7 +1698,7 @@ UniValue backupwallet(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - string strDest = params[0].get_str(); + std::string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); @@ -1712,7 +1709,7 @@ UniValue backupwallet(const UniValue& params, bool fHelp) UniValue keypoolrefill(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "keypoolrefill ( newsize )\n" "\nFills the keypool." + HelpRequiringPassphrase() + "\n" @@ -1754,7 +1751,7 @@ static void LockWallet(CWallet* pWallet) UniValue walletpassphrase(const UniValue& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) - throw runtime_error( + throw std::runtime_error( "walletpassphrase \"passphrase\" timeout ( anonymizeonly )\n" "\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "This is needed prior to performing transactions related to private keys such as sending PIVs\n" @@ -1828,7 +1825,7 @@ UniValue walletpassphrase(const UniValue& params, bool fHelp) UniValue walletpassphrasechange(const UniValue& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) - throw runtime_error( + throw std::runtime_error( "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n" "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n" @@ -1857,7 +1854,7 @@ UniValue walletpassphrasechange(const UniValue& params, bool fHelp) strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) - throw runtime_error( + throw std::runtime_error( "walletpassphrasechange \n" "Changes the wallet passphrase from to ."); @@ -1871,7 +1868,7 @@ UniValue walletpassphrasechange(const UniValue& params, bool fHelp) UniValue walletlock(const UniValue& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) - throw runtime_error( + throw std::runtime_error( "walletlock\n" "\nRemoves the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" @@ -1907,7 +1904,7 @@ UniValue walletlock(const UniValue& params, bool fHelp) UniValue encryptwallet(const UniValue& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) - throw runtime_error( + throw std::runtime_error( "encryptwallet \"passphrase\"\n" "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "After this, any calls that interact with private keys such as sending or signing \n" @@ -1945,7 +1942,7 @@ UniValue encryptwallet(const UniValue& params, bool fHelp) strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) - throw runtime_error( + throw std::runtime_error( "encryptwallet \n" "Encrypts the wallet with ."); @@ -1962,7 +1959,7 @@ UniValue encryptwallet(const UniValue& params, bool fHelp) UniValue lockunspent(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n" "\nUpdates list of temporarily unspendable outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" @@ -2021,7 +2018,7 @@ UniValue lockunspent(const UniValue& params, bool fHelp) RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)); - string txid = find_value(o, "txid").get_str(); + std::string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); @@ -2043,7 +2040,7 @@ UniValue lockunspent(const UniValue& params, bool fHelp) UniValue listlockunspent(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 0) - throw runtime_error( + throw std::runtime_error( "listlockunspent\n" "\nReturns list of temporarily unspendable outputs.\n" "See the lockunspent call to lock and unlock transactions for spending.\n" @@ -2071,7 +2068,7 @@ UniValue listlockunspent(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); - vector vOutpts; + std::vector vOutpts; pwalletMain->ListLockedCoins(vOutpts); UniValue ret(UniValue::VARR); @@ -2090,7 +2087,7 @@ UniValue listlockunspent(const UniValue& params, bool fHelp) UniValue settxfee(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "settxfee amount\n" "\nSet the transaction fee per kB.\n" @@ -2116,7 +2113,7 @@ UniValue settxfee(const UniValue& params, bool fHelp) UniValue getwalletinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getwalletinfo\n" "Returns an object containing various wallet state info.\n" @@ -2158,7 +2155,7 @@ UniValue getwalletinfo(const UniValue& params, bool fHelp) UniValue reservebalance(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "reservebalance ( reserve amount )\n" "\nShow or set the reserve amount not participating in network protection\n" "If no parameters provided current setting is printed.\n" @@ -2180,15 +2177,15 @@ UniValue reservebalance(const UniValue& params, bool fHelp) bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) - throw runtime_error("must provide amount to reserve balance.\n"); + throw std::runtime_error("must provide amount to reserve balance.\n"); CAmount nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) - throw runtime_error("amount cannot be negative.\n"); + throw std::runtime_error("amount cannot be negative.\n"); nReserveBalance = nAmount; } else { if (params.size() > 1) - throw runtime_error("cannot specify amount to turn off reserve.\n"); + throw std::runtime_error("cannot specify amount to turn off reserve.\n"); nReserveBalance = 0; } } @@ -2203,7 +2200,7 @@ UniValue reservebalance(const UniValue& params, bool fHelp) UniValue setstakesplitthreshold(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "setstakesplitthreshold value\n" "\nThis will set the output size of your stakes to never be below this number\n" + HelpRequiringPassphrase() + "\n" @@ -2225,7 +2222,7 @@ UniValue setstakesplitthreshold(const UniValue& params, bool fHelp) uint64_t nStakeSplitThreshold = params[0].get_int(); if (nStakeSplitThreshold > 999999) - throw runtime_error("Value out of range, max allowed is 999999"); + throw std::runtime_error("Value out of range, max allowed is 999999"); CWalletDB walletdb(pwalletMain->strWalletFile); LOCK(pwalletMain->cs_wallet); @@ -2249,7 +2246,7 @@ UniValue setstakesplitthreshold(const UniValue& params, bool fHelp) UniValue getstakesplitthreshold(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getstakesplitthreshold\n" "Returns the threshold for stake splitting\n" @@ -2269,7 +2266,7 @@ UniValue autocombinerewards(const UniValue& params, bool fHelp) fEnable = params[0].get_bool(); if (fHelp || params.size() < 1 || (fEnable && params.size() != 2) || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "autocombinerewards enable ( threshold )\n" "\nWallet will automatically monitor for any coins with value below the threshold amount, and combine them if they reside with the same PIVX address\n" "When autocombinerewards runs it will create a transaction, and therefore will be subject to transaction fees.\n" @@ -2291,7 +2288,7 @@ UniValue autocombinerewards(const UniValue& params, bool fHelp) pwalletMain->nAutoCombineThreshold = nThreshold; if (!walletdb.WriteAutoCombineSettings(fEnable, nThreshold)) - throw runtime_error("Changed settings in wallet but failed to save to database\n"); + throw std::runtime_error("Changed settings in wallet but failed to save to database\n"); return NullUniValue; } @@ -2341,7 +2338,7 @@ UniValue printAddresses() } UniValue ret(UniValue::VARR); - for (map::const_iterator it = mapAddresses.begin(); it != mapAddresses.end(); ++it) { + for (std::map::const_iterator it = mapAddresses.begin(); it != mapAddresses.end(); ++it) { UniValue obj(UniValue::VOBJ); const std::string* strAdd = &(*it).first; const double* nBalance = &(*it).second; @@ -2367,7 +2364,7 @@ UniValue multisend(const UniValue& params, bool fHelp) bool fFileBacked; //MultiSend Commands if (params.size() == 1) { - string strCommand = params[0].get_str(); + std::string strCommand = params[0].get_str(); UniValue ret(UniValue::VOBJ); if (strCommand == "print") { return printMultiSend(); @@ -2472,7 +2469,7 @@ UniValue multisend(const UniValue& params, bool fHelp) //if no commands are used if (fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "multisend \n" "****************************************************************\n" "WHAT IS MULTISEND?\n" @@ -2496,7 +2493,7 @@ UniValue multisend(const UniValue& params, bool fHelp) "****************************************************************\n"); //if the user is entering a new MultiSend item - string strAddress = params[0].get_str(); + std::string strAddress = params[0].get_str(); CBitcoinAddress address(strAddress); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIV address"); @@ -2542,7 +2539,7 @@ UniValue getzerocoinbalance(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getzerocoinbalance\n" "\nReturn the wallet's total zPIV balance.\n" + HelpRequiringPassphrase() + "\n" @@ -2570,7 +2567,7 @@ UniValue listmintedzerocoins(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "listmintedzerocoins (fVerbose) (fMatureOnly)\n" "\nList all zPIV mints in the wallet.\n" + HelpRequiringPassphrase() + "\n" @@ -2612,7 +2609,7 @@ UniValue listmintedzerocoins(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(true); CWalletDB walletdb(pwalletMain->strWalletFile); - set setMints = pwalletMain->zpivTracker->ListMints(true, fMatureOnly, true); + std::set setMints = pwalletMain->zpivTracker->ListMints(true, fMatureOnly, true); int nBestHeight = chainActive.Height(); @@ -2655,7 +2652,7 @@ UniValue listzerocoinamounts(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "listzerocoinamounts\n" "\nGet information about your zerocoin amounts.\n" + HelpRequiringPassphrase() + "\n" @@ -2677,7 +2674,7 @@ UniValue listzerocoinamounts(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(true); CWalletDB walletdb(pwalletMain->strWalletFile); - set setMints = pwalletMain->zpivTracker->ListMints(true, true, true); + std::set setMints = pwalletMain->zpivTracker->ListMints(true, true, true); std::map spread; for (const auto& denom : libzerocoin::zerocoinDenomList) @@ -2699,7 +2696,7 @@ UniValue listspentzerocoins(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "listspentzerocoins\n" "\nList all the spent zPIV mints in the wallet.\n" + HelpRequiringPassphrase() + "\n" @@ -2718,7 +2715,7 @@ UniValue listspentzerocoins(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(true); CWalletDB walletdb(pwalletMain->strWalletFile); - list listPubCoin = walletdb.ListSpentCoinsSerial(); + std::list listPubCoin = walletdb.ListSpentCoinsSerial(); UniValue jsonList(UniValue::VARR); for (const CBigNum& pubCoinItem : listPubCoin) { @@ -2731,7 +2728,7 @@ UniValue listspentzerocoins(const UniValue& params, bool fHelp) UniValue mintzerocoin(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "mintzerocoin amount ( utxos )\n" "\nMint the specified zPIV amount\n" + HelpRequiringPassphrase() + "\n" @@ -2792,9 +2789,9 @@ UniValue mintzerocoin(const UniValue& params, bool fHelp) CAmount nAmount = params[0].get_int() * COIN; CWalletTx wtx; - vector vDMints; - string strError; - vector vOutpts; + std::vector vDMints; + std::string strError; + std::vector vOutpts; if (params.size() == 2) { @@ -2807,7 +2804,7 @@ UniValue mintzerocoin(const UniValue& params, bool fHelp) RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)); - string txid = find_value(o, "txid").get_str(); + std::string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); @@ -2846,7 +2843,7 @@ UniValue mintzerocoin(const UniValue& params, bool fHelp) UniValue spendzerocoin(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 4 || params.size() < 3) - throw runtime_error( + throw std::runtime_error( "spendzerocoin amount mintchange minimizechange ( \"address\" )\n" "\nSpend zPIV to a PIV address.\n" + HelpRequiringPassphrase() + "\n" @@ -2901,7 +2898,7 @@ UniValue spendzerocoin(const UniValue& params, bool fHelp) std::string address_str = params.size() > 3 ? params[3].get_str() : ""; bool ispublicspend = params.size() > 4 ? params[3].get_bool() : true; - vector vMintsSelected; + std::vector vMintsSelected; if (!ispublicspend && Params().NetworkID() != CBaseChainParams::REGTEST) { throw JSONRPCError(RPC_WALLET_ERROR, "zPIV old spend only available in regtest for tests purposes"); @@ -2914,7 +2911,7 @@ UniValue spendzerocoin(const UniValue& params, bool fHelp) UniValue spendzerocoinmints(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "spendzerocoinmints mints_list (\"address\") \n" "\nSpend zPIV mints to a PIV address.\n" + HelpRequiringPassphrase() + "\n" @@ -2973,7 +2970,7 @@ UniValue spendzerocoinmints(const UniValue& params, bool fHelp) CAmount nAmount(0); // Spending amount // fetch mints and update nAmount - vector vMintsSelected; + std::vector vMintsSelected; for(unsigned int i=0; i < arrMints.size(); i++) { CZerocoinMint mint; @@ -3005,7 +3002,7 @@ UniValue spendzerocoinmints(const UniValue& params, bool fHelp) } -extern UniValue DoZpivSpend(const CAmount nAmount, bool fMintChange, bool fMinimizeChange, vector& vMintsSelected, std::string address_str, bool ispublicspend) +extern UniValue DoZpivSpend(const CAmount nAmount, bool fMintChange, bool fMinimizeChange, std::vector& vMintsSelected, std::string address_str, bool ispublicspend) { // zerocoin MINT is disabled. fMintChange should be false here. Double check if (fMintChange && Params().NetworkID() != CBaseChainParams::REGTEST) @@ -3073,7 +3070,7 @@ extern UniValue DoZpivSpend(const CAmount nAmount, bool fMintChange, bool fMinim UniValue resetmintzerocoin(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) - throw runtime_error( + throw std::runtime_error( "resetmintzerocoin ( fullscan )\n" "\nScan the blockchain for all of the zerocoins that are held in the wallet.dat.\n" "Update any meta-data that is incorrect. Archive any mints that are not able to be found.\n" + @@ -3102,10 +3099,10 @@ UniValue resetmintzerocoin(const UniValue& params, bool fHelp) CWalletDB walletdb(pwalletMain->strWalletFile); CzPIVTracker* zpivTracker = pwalletMain->zpivTracker.get(); - set setMints = zpivTracker->ListMints(false, false, true); - vector vMintsToFind(setMints.begin(), setMints.end()); - vector vMintsMissing; - vector vMintsToUpdate; + std::set setMints = zpivTracker->ListMints(false, false, true); + std::vector vMintsToFind(setMints.begin(), setMints.end()); + std::vector vMintsMissing; + std::vector vMintsToUpdate; // search all of our available data for these mints FindMints(vMintsToFind, vMintsToUpdate, vMintsMissing); @@ -3133,7 +3130,7 @@ UniValue resetmintzerocoin(const UniValue& params, bool fHelp) UniValue resetspentzerocoin(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "resetspentzerocoin\n" "\nScan the blockchain for all of the zerocoins that are held in the wallet.dat.\n" "Reset mints that are considered spent that did not make it into the blockchain.\n" @@ -3155,9 +3152,9 @@ UniValue resetspentzerocoin(const UniValue& params, bool fHelp) CWalletDB walletdb(pwalletMain->strWalletFile); CzPIVTracker* zpivTracker = pwalletMain->zpivTracker.get(); - set setMints = zpivTracker->ListMints(false, false, false); - list listSpends = walletdb.ListSpentCoins(); - list listUnconfirmedSpends; + std::set setMints = zpivTracker->ListMints(false, false, false); + std::list listSpends = walletdb.ListSpentCoins(); + std::list listUnconfirmedSpends; for (CZerocoinSpend spend : listSpends) { CTransaction tx; @@ -3195,7 +3192,7 @@ UniValue resetspentzerocoin(const UniValue& params, bool fHelp) UniValue getarchivedzerocoin(const UniValue& params, bool fHelp) { if(fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "getarchivedzerocoin\n" "\nDisplay zerocoins that were archived because they were believed to be orphans.\n" "Provides enough information to recover mint if it was incorrectly archived.\n" + @@ -3221,8 +3218,8 @@ UniValue getarchivedzerocoin(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); CWalletDB walletdb(pwalletMain->strWalletFile); - list listMints = walletdb.ListArchivedZerocoins(); - list listDMints = walletdb.ListArchivedDeterministicMints(); + std::list listMints = walletdb.ListArchivedZerocoins(); + std::list listDMints = walletdb.ListArchivedDeterministicMints(); UniValue arrRet(UniValue::VARR); for (const CZerocoinMint& mint : listMints) { @@ -3252,7 +3249,7 @@ UniValue getarchivedzerocoin(const UniValue& params, bool fHelp) UniValue exportzerocoins(const UniValue& params, bool fHelp) { if(fHelp || params.empty() || params.size() > 2) - throw runtime_error( + throw std::runtime_error( "exportzerocoins include_spent ( denomination )\n" "\nExports zerocoin mints that are held by this wallet.dat\n" + HelpRequiringPassphrase() + "\n" @@ -3293,7 +3290,7 @@ UniValue exportzerocoins(const UniValue& params, bool fHelp) denomination = libzerocoin::IntToZerocoinDenomination(params[1].get_int()); CzPIVTracker* zpivTracker = pwalletMain->zpivTracker.get(); - set setMints = zpivTracker->ListMints(!fIncludeSpent, false, false); + std::set setMints = zpivTracker->ListMints(!fIncludeSpent, false, false); UniValue jsonList(UniValue::VARR); for (const CMintMeta& meta : setMints) { @@ -3330,7 +3327,7 @@ UniValue exportzerocoins(const UniValue& params, bool fHelp) UniValue importzerocoins(const UniValue& params, bool fHelp) { if(fHelp || params.size() == 0) - throw runtime_error( + throw std::runtime_error( "importzerocoins importdata \n" "\n[{\"d\":denomination,\"p\":\"pubcoin_hex\",\"s\":\"serial_hex\",\"r\":\"randomness_hex\",\"t\":\"txid\",\"h\":height, \"u\":used},{\"d\":...}]\n" "\nImport zerocoin mints.\n" @@ -3355,7 +3352,7 @@ UniValue importzerocoins(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(); - RPCTypeCheck(params, list_of(UniValue::VARR)(UniValue::VOBJ)); + RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)); UniValue arrMints = params[0].get_array(); CWalletDB walletdb(pwalletMain->strWalletFile); @@ -3422,7 +3419,7 @@ UniValue importzerocoins(const UniValue& params, bool fHelp) UniValue reconsiderzerocoins(const UniValue& params, bool fHelp) { if(fHelp || !params.empty()) - throw runtime_error( + throw std::runtime_error( "reconsiderzerocoins\n" "\nCheck archived zPIV list to see if any mints were added to the blockchain.\n" + HelpRequiringPassphrase() + "\n" @@ -3445,8 +3442,8 @@ UniValue reconsiderzerocoins(const UniValue& params, bool fHelp) EnsureWalletIsUnlocked(true); - list listMints; - list listDMints; + std::list listMints; + std::list listDMints; pwalletMain->ReconsiderZerocoins(listMints, listDMints); UniValue arrRet(UniValue::VARR); @@ -3473,7 +3470,7 @@ UniValue reconsiderzerocoins(const UniValue& params, bool fHelp) UniValue setzpivseed(const UniValue& params, bool fHelp) { if(fHelp || params.size() != 1) - throw runtime_error( + throw std::runtime_error( "setzpivseed \"seed\"\n" "\nSet the wallet's deterministic zpiv seed to a specific value.\n" + HelpRequiringPassphrase() + "\n" @@ -3507,7 +3504,7 @@ UniValue setzpivseed(const UniValue& params, bool fHelp) UniValue getzpivseed(const UniValue& params, bool fHelp) { if(fHelp || !params.empty()) - throw runtime_error( + throw std::runtime_error( "getzpivseed\n" "\nCheck archived zPIV list to see if any mints were added to the blockchain.\n" + HelpRequiringPassphrase() + "\n" @@ -3532,7 +3529,7 @@ UniValue getzpivseed(const UniValue& params, bool fHelp) UniValue generatemintlist(const UniValue& params, bool fHelp) { if(fHelp || params.size() != 2) - throw runtime_error( + throw std::runtime_error( "generatemintlist\n" "\nShow mints that are derived from the deterministic zPIV seed.\n" + HelpRequiringPassphrase() + "\n" @@ -3580,7 +3577,7 @@ UniValue generatemintlist(const UniValue& params, bool fHelp) UniValue dzpivstate(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "dzpivstate\n" "\nThe current state of the mintpool of the deterministic zPIV wallet.\n" + HelpRequiringPassphrase() + "\n" @@ -3619,7 +3616,7 @@ void static SearchThread(CzPIVWallet* zwallet, int nCountStart, int nCountEnd) zwallet->SeedToZPIV(zerocoinSeed, bnValue, bnSerial, bnRandomness, key); uint256 hashPubcoin = GetPubCoinHash(bnValue); - zwallet->AddToMintPool(make_pair(hashPubcoin, i), true); + zwallet->AddToMintPool(std::make_pair(hashPubcoin, i), true); walletDB.WriteMintPoolPair(hashSeed, hashPubcoin, i); } } catch (std::exception& e) { @@ -3632,7 +3629,7 @@ void static SearchThread(CzPIVWallet* zwallet, int nCountStart, int nCountEnd) UniValue searchdzpiv(const UniValue& params, bool fHelp) { if(fHelp || params.size() != 3) - throw runtime_error( + throw std::runtime_error( "searchdzpiv\n" "\nMake an extended search for deterministically generated zPIV that have not yet been recognized by the wallet.\n" + HelpRequiringPassphrase() + "\n" @@ -3719,7 +3716,7 @@ UniValue createautomintaddress(const UniValue& params, bool fHelp) UniValue spendrawzerocoin(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 4 || params.size() > 5) - throw runtime_error( + throw std::runtime_error( "spendrawzerocoin \"serialHex\" denom \"randomnessHex\" [\"address\"]\n" "\nCreate and broadcast a TX spending the provided zericoin.\n" @@ -3771,7 +3768,7 @@ UniValue spendrawzerocoin(const UniValue& params, bool fHelp) // Create the mint associated with this coin CZerocoinMint mint(denom, coin.getPublicCoin().getValue(), randomness, serial, false, CZerocoinMint::CURRENT_VERSION, &privkey); - vector vMintsSelected = {mint}; + std::vector vMintsSelected = {mint}; CAmount nAmount = mint.GetDenominationAsAmount(); return DoZpivSpend(nAmount, false, true, vMintsSelected, address_str); @@ -3780,7 +3777,7 @@ UniValue spendrawzerocoin(const UniValue& params, bool fHelp) UniValue clearspendcache(const UniValue& params, bool fHelp) { if(fHelp || params.size() != 0) - throw runtime_error( + throw std::runtime_error( "clearspendcache\n" "\nClear the pre-computed zPIV spend cache, and database.\n" + HelpRequiringPassphrase() + "\n" diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index 24bf30b7cc0c..a9a889bb815d 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -19,14 +19,13 @@ // we repeat those tests this many times and only complain if all iterations of the test fail #define RANDOM_REPEATS 5 -using namespace std; -typedef set > CoinSet; +typedef std::set > CoinSet; BOOST_FIXTURE_TEST_SUITE(wallet_tests, TestingSetup) static CWallet wallet; -static vector vCoins; +static std::vector vCoins; static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) { @@ -59,7 +58,7 @@ static void empty_wallet(void) static bool equal_sets(CoinSet a, CoinSet b) { - pair ret = mismatch(a.begin(), a.end(), b.begin()); + std::pair ret = mismatch(a.begin(), a.end(), b.begin()); return ret.first == a.end() && ret.second == b.end(); } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index a862ada5fde3..256a6aa3873f 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -39,7 +39,6 @@ #include #include -using namespace std; /** * Settings @@ -68,8 +67,8 @@ CFeeRate CWallet::minTxFee = CFeeRate(10000); */ struct CompareValueOnly { - bool operator()(const pair >& t1, - const pair >& t2) const + bool operator()(const std::pair >& t1, + const std::pair >& t2) const { return t1.first < t2.first; } @@ -148,7 +147,7 @@ bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey) } bool CWallet::AddCryptedKey(const CPubKey& vchPubKey, - const vector& vchCryptedSecret) + const std::vector& vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; @@ -376,9 +375,9 @@ bool CWallet::SetMaxVersion(int nVersion) return true; } -set CWallet::GetConflicts(const uint256& txid) const +std::set CWallet::GetConflicts(const uint256& txid) const { - set result; + std::set result; AssertLockHeld(cs_wallet); std::map::const_iterator it = mapWallet.find(txid); @@ -398,7 +397,7 @@ set CWallet::GetConflicts(const uint256& txid) const return result; } -void CWallet::SyncMetaData(pair range) +void CWallet::SyncMetaData(std::pair range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). @@ -438,7 +437,7 @@ void CWallet::SyncMetaData(pair range) bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); - pair range; + std::pair range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; @@ -451,8 +450,8 @@ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { - mapTxSpends.insert(make_pair(outpoint, wtxid)); - pair range; + mapTxSpends.insert(std::make_pair(outpoint, wtxid)); + std::pair range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } @@ -651,12 +650,12 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) mapWallet[hash] = wtxIn; CWalletTx& wtx = mapWallet[hash]; wtx.BindWallet(this); - wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); + wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found - pair::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); + std::pair::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; @@ -664,7 +663,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) if (!wtx.nTimeReceived) wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); - wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); + wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); wtx.nTimeSmart = ComputeTimeSmart(wtx); AddToSpends(hash); } @@ -765,7 +764,7 @@ isminetype CWallet::IsMine(const CTxIn& txin) const { { LOCK(cs_wallet); - map::const_iterator mi = mapWallet.find(txin.prevout.hash); + std::map::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) @@ -783,7 +782,7 @@ bool CWallet::IsUsed(const CBitcoinAddress address) const return false; } - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase()) { continue; @@ -805,7 +804,7 @@ CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const { { LOCK(cs_wallet); - map::const_iterator mi = mapWallet.find(txin.prevout.hash); + std::map::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) @@ -820,7 +819,7 @@ bool CWallet::IsDenominated(const CTxIn& txin) const { { LOCK(cs_wallet); - map::const_iterator mi = mapWallet.find(txin.prevout.hash); + std::map::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); @@ -885,19 +884,19 @@ int CWalletTx::GetRequestCount() const if (IsCoinBase()) { // Generated block if (hashBlock != 0) { - map::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); + std::map::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? - map::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); + std::map::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { - map::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); + std::map::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else @@ -1144,10 +1143,10 @@ CAmount CWalletTx::GetLockedWatchOnlyCredit() const return nCredit; } -void CWalletTx::GetAmounts(list& listReceived, - list& listSent, +void CWalletTx::GetAmounts(std::list& listReceived, + std::list& listSent, CAmount& nFee, - string& strSentAccount, + std::string& strSentAccount, const isminefilter& filter) const { nFee = 0; @@ -1201,14 +1200,14 @@ void CWalletTx::GetAmounts(list& listReceived, } } -void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const +void CWalletTx::GetAccountAmounts(const std::string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; - string strSentAccount; - list listReceived; - list listSent; + std::string strSentAccount; + std::list listReceived; + std::list listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { @@ -1220,7 +1219,7 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, LOCK(pwallet->cs_wallet); for (const COutputEntry& r : listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { - map::const_iterator mi = pwallet->mapAddressBook.find(r.destination); + std::map::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) nReceived += r.amount; } else if (strAccount.empty()) { @@ -1261,7 +1260,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); - set setAddedToWallet; + std::set setAddedToWallet; while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); @@ -1275,7 +1274,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) //If this is a zapwallettx, need to readd zpiv if (fCheckZPIV && pindex->nHeight >= Params().Zerocoin_StartHeight()) { - list listMints; + std::list listMints; BlockToZerocoinMintList(block, listMints, true); for (auto& m : listMints) { @@ -1366,7 +1365,7 @@ void CWalletTx::RelayWalletTransaction(std::string strCommand) LogPrintf("Relaying wtx %s\n", hash.ToString()); if (strCommand == "ix") { - mapTxLockReq.insert(make_pair(hash, (CTransaction) * this)); + mapTxLockReq.insert(std::make_pair(hash, (CTransaction) * this)); CreateNewLock(((CTransaction) * this)); RelayTransactionLockReq((CTransaction) * this, true); } else { @@ -1376,9 +1375,9 @@ void CWalletTx::RelayWalletTransaction(std::string strCommand) } } -set CWalletTx::GetConflicts() const +std::set CWalletTx::GetConflicts() const { - set result; + std::set result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); @@ -1408,13 +1407,13 @@ void CWallet::ResendWalletTransactions() { LOCK(cs_wallet); // Sort them in chronological order - multimap mapSorted; + std::multimap mapSorted; for (PAIRTYPE(const uint256, CWalletTx) & item : mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) - mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); + mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx)); } for (PAIRTYPE(const unsigned int, CWalletTx*) & item : mapSorted) { CWalletTx& wtx = *item.second; @@ -1436,7 +1435,7 @@ CAmount CWallet::GetBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) @@ -1461,7 +1460,7 @@ CAmount CWallet::GetZerocoinBalance(bool fMatureOnly) const //nLastMaturityCheck = chainActive.Height(); CAmount nBalance = 0; - vector vMints = zpivTracker->GetMints(true); + std::vector vMints = zpivTracker->GetMints(true); for (auto meta : vMints) { // Every public coin spend is now spendable, no need to mint new coins on top. //if (meta.nHeight >= mapMintMaturity.at(meta.denom) || meta.nHeight >= chainActive.Height() || meta.nHeight == 0) @@ -1491,7 +1490,7 @@ CAmount CWallet::GetUnlockedCoins() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) @@ -1509,7 +1508,7 @@ CAmount CWallet::GetLockedCoins() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) @@ -1528,7 +1527,7 @@ std::map CWallet::GetMyZerocoinDistribut spread.insert(std::pair(denom, 0)); { LOCK(cs_wallet); - set setMints = zpivTracker->ListMints(true, true, true); + std::set setMints = zpivTracker->ListMints(true, true, true); for (auto& mint : setMints) spread.at(mint.denom)++; } @@ -1541,7 +1540,7 @@ CAmount CWallet::GetUnconfirmedBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); @@ -1555,7 +1554,7 @@ CAmount CWallet::GetImmatureBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } @@ -1568,7 +1567,7 @@ CAmount CWallet::GetWatchOnlyBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); @@ -1583,7 +1582,7 @@ CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); @@ -1597,7 +1596,7 @@ CAmount CWallet::GetImmatureWatchOnlyBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } @@ -1610,7 +1609,7 @@ CAmount CWallet::GetLockedWatchOnlyBalance() const CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) nTotal += pcoin->GetLockedWatchOnlyCredit(); @@ -1623,7 +1622,7 @@ CAmount CWallet::GetLockedWatchOnlyBalance() const * populate vCoins with vector of available COutputs. */ void CWallet::AvailableCoins( - vector& vCoins, + std::vector& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, @@ -1635,7 +1634,7 @@ void CWallet::AvailableCoins( { LOCK2(cs_main, cs_wallet); - for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { + for (std::map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const uint256& wtxid = it->first; const CWalletTx* pcoin = &(*it).second; @@ -1711,12 +1710,12 @@ void CWallet::AvailableCoins( } } -map > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue) +std::map > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue) { - vector vCoins; + std::vector vCoins; AvailableCoins(vCoins, fConfirmed); - map > mapCoins; + std::map > mapCoins; for (COutput out : vCoins) { if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue) continue; @@ -1731,9 +1730,9 @@ map > CWallet::AvailableCoinsByAddress(bool fCo return mapCoins; } -static void ApproximateBestSubset(vector > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector& vfBest, CAmount& nBest, int iterations = 1000) +static void ApproximateBestSubset(std::vector > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, std::vector& vfBest, CAmount& nBest, int iterations = 1000) { - vector vfIncluded; + std::vector vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; @@ -1792,7 +1791,7 @@ bool CWallet::SelectStakeCoins(std::list >& listInp { LOCK(cs_main); //Add PIV - vector vCoins; + std::vector vCoins; AvailableCoins(vCoins, true, NULL, false, STAKABLE_COINS); CAmount nAmountSelected = 0; if (GetBoolArg("-pivstake", true) && !fPrecompute) { @@ -1837,7 +1836,7 @@ bool CWallet::SelectStakeCoins(std::list >& listInp nTimeLastUpdate = GetAdjustedTime(); } - set setMints = zpivTracker->ListMints(true, true, fUpdate); + std::set setMints = zpivTracker->ListMints(true, true, fUpdate); for (auto meta : setMints) { if (meta.hashStake == 0) { CZerocoinMint mint; @@ -1852,7 +1851,7 @@ bool CWallet::SelectStakeCoins(std::list >& listInp continue; if (meta.nHeight < chainActive.Height() - Params().Zerocoin_RequiredStakeDepth()) { std::unique_ptr input(new CZPivStake(meta.denom, meta.hashStake)); - listInputs.emplace_back(std::move(input)); + std::listInputs.emplace_back(std::move(input)); } } } @@ -1873,7 +1872,7 @@ bool CWallet::MintableCoins() if (nBalance <= nReserveBalance) return false; - vector vCoins; + std::vector vCoins; AvailableCoins(vCoins, true); for (const COutput& out : vCoins) { @@ -1891,7 +1890,7 @@ bool CWallet::MintableCoins() // zPIV if (nZpivBalance > 0) { - set setMints = zpivTracker->ListMints(true, true, true); + std::set setMints = zpivTracker->ListMints(true, true, true); for (auto mint : setMints) { if (mint.nVersion < CZerocoinMint::STAKABLE_VERSION) continue; @@ -1904,22 +1903,22 @@ bool CWallet::MintableCoins() return false; } -bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector vCoins, set >& setCoinsRet, CAmount& nValueRet) const +bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector vCoins, std::set >& setCoinsRet, CAmount& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target - pair > coinLowestLarger; + std::pair > coinLowestLarger; coinLowestLarger.first = std::numeric_limits::max(); coinLowestLarger.second.first = NULL; - vector > > vValue; + std::vector > > vValue; CAmount nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list - sort(vCoins.begin(), vCoins.end(), less_then_denom); + std::sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { @@ -1940,7 +1939,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int CAmount n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run - pair > coin = make_pair(n, make_pair(pcoin, i)); + std::pair > coin = std::make_pair(n, std::make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); @@ -1982,8 +1981,8 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int } // Solve subset sum by stochastic approximation - sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); - vector vfBest; + std::sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); + std::vector vfBest; CAmount nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); @@ -1997,7 +1996,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { - string s = "CWallet::SelectCoinsMinConf best subset: "; + std::string s = "CWallet::SelectCoinsMinConf best subset: "; for (unsigned int i = 0; i < vValue.size(); i++) { if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); @@ -2011,11 +2010,11 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int return true; } -bool CWallet::SelectCoins(const CAmount& nTargetValue, set >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const +bool CWallet::SelectCoins(const CAmount& nTargetValue, std::set >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { // Note: this function should never be used for "always free" tx types like dstx - vector vCoins; + std::vector vCoins; AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) @@ -2025,7 +2024,7 @@ bool CWallet::SelectCoins(const CAmount& nTargetValue, setvout[out.i].nValue; - setCoinsRet.insert(make_pair(out.tx, out.i)); + setCoinsRet.insert(std::make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } @@ -2050,8 +2049,8 @@ bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useI CAmount nFeeRet = 0; std::string strFail = ""; - vector > vecSend; - vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX_OLD)); // Old 50 PIV collateral + std::vector > vecSend; + vecSend.push_back(std::make_pair(scriptChange, BUDGET_FEE_TX_OLD)); // Old 50 PIV collateral CCoinControl* coinControl = NULL; bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0); @@ -2073,8 +2072,8 @@ bool CWallet::GetBudgetFinalizationCollateralTX(CWalletTx& tx, uint256 hash, boo CAmount nFeeRet = 0; std::string strFail = ""; - vector > vecSend; - vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX)); // New 5 PIV collateral + std::vector > vecSend; + vecSend.push_back(std::make_pair(scriptChange, BUDGET_FEE_TX)); // New 5 PIV collateral CCoinControl* coinControl = NULL; bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0); @@ -2086,7 +2085,7 @@ bool CWallet::GetBudgetFinalizationCollateralTX(CWalletTx& tx, uint256 hash, boo return true; } -bool CWallet::CreateTransaction(const vector >& vecSend, +bool CWallet::CreateTransaction(const std::vector >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, @@ -2160,7 +2159,7 @@ bool CWallet::CreateTransaction(const vector >& vecSend, } // Choose coins to use - set > setCoins; + std::set > setCoins; CAmount nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) { @@ -2215,7 +2214,7 @@ bool CWallet::CreateTransaction(const vector >& vecSend, if (coinControl && !boost::get(&coinControl->destChange)) { scriptChange = GetScriptForDestination(coinControl->destChange); - vector::iterator it = txNew.vout.begin(); + std::vector::iterator it = txNew.vout.begin(); while (it != txNew.vout.end()) { if (scriptChange == it->scriptPubKey) { it->nValue += nChange; @@ -2257,7 +2256,7 @@ bool CWallet::CreateTransaction(const vector >& vecSend, reservekey.ReturnKey(); } else { // Insert change txn at random position: - vector::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1); + std::vector::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1); txNew.vout.insert(position, newTxOut); } } @@ -2300,7 +2299,7 @@ bool CWallet::CreateTransaction(const vector >& vecSend, break; } - CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); + CAmount nFeeNeeded = std::max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. @@ -2323,8 +2322,8 @@ bool CWallet::CreateTransaction(const vector >& vecSend, bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { - vector > vecSend; - vecSend.push_back(make_pair(scriptPubKey, nValue)); + std::vector > vecSend; + vecSend.push_back(std::make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay); } @@ -2416,7 +2415,7 @@ bool CWallet::CreateCoinStake( nCredit += nReward; // Create the output transaction(s) - vector vout; + std::vector vout; if (!stakeInput->CreateTxOuts(this, vout, nCredit)) { LogPrintf("%s : failed to get scriptPubKey\n", __func__); continue; @@ -2533,7 +2532,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std: // Notify that old coins are spent if (!wtxNew.HasZerocoinSpendInputs()) { - set updated_hahes; + std::set updated_hahes; for (const CTxIn& txin : wtxNew.vin) { // notify only once if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue; @@ -2570,7 +2569,7 @@ bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pw laccentries.push_back(acentry); CAccountingEntry & entry = laccentries.back(); - wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); + wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); return true; } @@ -2645,7 +2644,7 @@ DBErrors CWallet::ZapWalletTx(std::vector& vWtx) return DB_LOAD_OK; } -bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) +bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose) { bool fUpdated = false; { @@ -2673,7 +2672,7 @@ bool CWallet::DelAddressBook(const CTxDestination& address) if (fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = CBitcoinAddress(address).ToString(); - for (const PAIRTYPE(string, string) & item : mapAddressBook[address].destdata) { + for (const PAIRTYPE(std::string, std::string) & item : mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } @@ -2714,7 +2713,7 @@ bool CWallet::NewKeyPool() if (IsLocked()) return false; - int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0); + int64_t nKeys = std::max(GetArg("-keypool", 1000), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i + 1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); @@ -2740,14 +2739,14 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize) if (kpSize > 0) nTargetSize = kpSize; else - nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0); + nTargetSize = std::max(GetArg("-keypool", 1000), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) - throw runtime_error("TopUpKeyPool() : writing generated key failed"); + throw std::runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); double dProgress = 100.f * nEnd / (nTargetSize + 1); @@ -2777,9 +2776,9 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) - throw runtime_error("ReserveKeyFromKeyPool() : read failed"); + throw std::runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) - throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); + throw std::runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } @@ -2836,7 +2835,7 @@ int64_t CWallet::GetOldestKeyPoolTime() std::map CWallet::GetAddressBalances() { - map balances; + std::map balances; { LOCK(cs_wallet); @@ -2872,11 +2871,11 @@ std::map CWallet::GetAddressBalances() return balances; } -set > CWallet::GetAddressGroupings() +std::set > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet - set > groupings; - set grouping; + std::set > groupings; + std::set grouping; for (PAIRTYPE(uint256, CWalletTx) walletEntry : mapWallet) { CWalletTx* pcoin = &walletEntry.second; @@ -2922,19 +2921,19 @@ set > CWallet::GetAddressGroupings() } } - set*> uniqueGroupings; // a set of pointers to groups of addresses - map*> setmap; // map addresses to the unique group containing it - for (set grouping : groupings) { + std::set*> uniqueGroupings; // a set of pointers to groups of addresses + std::map*> setmap; // map addresses to the unique group containing it + for (std::set grouping : groupings) { // make a set of all the groups hit by this new group - set*> hits; - map*>::iterator it; + std::set*> hits; + std::map*>::iterator it; 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 - set* merged = new set(grouping); - for (set* hit : hits) { + std::set* merged = new std::set(grouping); + for (std::set* hit : hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; @@ -2946,8 +2945,8 @@ set > CWallet::GetAddressGroupings() setmap[element] = merged; } - set > ret; - for (set* uniqueGrouping : uniqueGroupings) { + std::set > ret; + for (std::set* uniqueGrouping : uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } @@ -2955,13 +2954,13 @@ set > CWallet::GetAddressGroupings() return ret; } -set CWallet::GetAccountAddresses(string strAccount) const +std::set CWallet::GetAccountAddresses(std::string strAccount) const { LOCK(cs_wallet); - set result; + std::set result; for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : mapAddressBook) { const CTxDestination& address = item.first; - const string& strName = item.second.name; + const std::string& strName = item.second.name; if (strName == strAccount) result.insert(address); } @@ -3000,7 +2999,7 @@ void CReserveKey::ReturnKey() vchPubKey = CPubKey(); } -void CWallet::GetAllReserveKeys(set& setAddress) const +void CWallet::GetAllReserveKeys(std::set& setAddress) const { setAddress.clear(); @@ -3010,11 +3009,11 @@ void CWallet::GetAllReserveKeys(set& setAddress) const for (const int64_t& id : setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) - throw runtime_error("GetAllReserveKeyHashes() : read failed"); + throw std::runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) - throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); + throw std::runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } @@ -3024,7 +3023,7 @@ bool CWallet::UpdatedTransaction(const uint256& hashTx) { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet - map::const_iterator mi = mapWallet.find(hashTx); + std::map::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { NotifyTransactionChanged(this, hashTx, CT_UPDATED); return true; @@ -3237,7 +3236,7 @@ void CWallet::InitAutoConvertAddresses() void CWallet::AutoZeromintForAddress() { std::map mapBalances = GetAddressBalances(); - std::map > mapAddressCoins = AvailableCoinsByAddress(true); + std::map > mapAddressCoins = AvailableCoinsByAddress(true); for (auto address : setAutoConvertAddresses) { CTxDestination dest = address.Get(); @@ -3271,9 +3270,9 @@ void CWallet::CreateAutoMintTransaction(const CAmount& nMintAmount, CCoinControl { if (nMintAmount > 0){ CWalletTx wtx; - vector vDMints; + std::vector vDMints; LogPrintf("%s: autominting request amount %s\n", __func__, FormatMoney(nMintAmount)); - string strError = pwalletMain->MintZerocoin(nMintAmount, wtx, vDMints, coinControl); + std::string strError = pwalletMain->MintZerocoin(nMintAmount, wtx, vDMints, coinControl); // Return if something went wrong during minting if (strError != ""){ @@ -3392,11 +3391,11 @@ void CWallet::AutoCombineDust() return; } - map > mapCoinsByAddress = AvailableCoinsByAddress(true, nAutoCombineThreshold * COIN); + std::map > mapCoinsByAddress = AvailableCoinsByAddress(true, nAutoCombineThreshold * COIN); //coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address - for (map >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) { - vector vCoins, vRewardCoins; + for (std::map >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) { + std::vector vCoins, vRewardCoins; bool maxSize = false; vCoins = it->second; @@ -3439,9 +3438,9 @@ void CWallet::AutoCombineDust() if (vRewardCoins.size() <= 1) continue; - vector > vecSend; + std::vector > vecSend; CScript scriptPubKey = GetScriptForDestination(it->first.Get()); - vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue)); + vecSend.push_back(std::make_pair(scriptPubKey, nTotalRewardsValue)); //Send change to same address CTxDestination destMyAddress; @@ -3454,7 +3453,7 @@ void CWallet::AutoCombineDust() // Create the transaction and commit it to the network CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch - string strErr; + std::string strErr; CAmount nFeeRet = 0; // 10% safety margin to avoid "Insufficient funds" errors @@ -3535,7 +3534,7 @@ bool CWallet::MultiSend() CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch CAmount nFeeRet = 0; - vector > vecSend; + std::vector > vecSend; // loop through multisend vector and add amounts and addresses to the sending vector const isminefilter filter = ISMINE_SPENDABLE; @@ -3546,12 +3545,12 @@ bool CWallet::MultiSend() CBitcoinAddress strAddSend(vMultiSend[i].first); CScript scriptPubKey; scriptPubKey = GetScriptForDestination(strAddSend.Get()); - vecSend.push_back(make_pair(scriptPubKey, nAmount)); + vecSend.push_back(std::make_pair(scriptPubKey, nAmount)); } //get the fee amount CWalletTx wtxdummy; - string strErr; + std::string strErr; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, &cControl, ALL_COINS, false, CAmount(0)); CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second; if (nLastSendAmount < nFeeRet + 500) { @@ -3693,7 +3692,7 @@ int CMerkleTx::GetBlocksToMaturity() const LOCK(cs_main); if (!(IsCoinBase() || IsCoinStake())) return 0; - return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain()); + return std::max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain()); } @@ -3735,9 +3734,9 @@ bool CMerkleTx::IsTransactionLockTimedOut() const } // Given a set of inputs, find the public key that contributes the most coins to the input set -CScript GetLargestContributor(set >& setCoins) +CScript GetLargestContributor(std::set >& setCoins) { - map mapScriptsOut; + std::map mapScriptsOut; for (const std::pair& coin : setCoins) { CTxOut out = coin.first->vout[coin.second]; mapScriptsOut[out.scriptPubKey] += out.nValue; @@ -3785,7 +3784,7 @@ bool CWallet::CreateZPIVOutPut(libzerocoin::CoinDenomination denomination, CTxOu return true; } -bool CWallet::CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, vector& vDMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, const bool isZCSpendChange) +bool CWallet::CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, std::vector& vDMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, const bool isZCSpendChange) { if (IsLocked()) { strFailReason = _("Error: Wallet locked, unable to create transaction!"); @@ -3798,7 +3797,7 @@ bool CWallet::CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransa CAmount nValueRemaining = 0; while (true) { //mint a coin with the closest denomination to what is being requested - nFeeRet = max(static_cast(txNew.vout.size()), 1) * Params().Zerocoin_MintFee(); + nFeeRet = std::max(static_cast(txNew.vout.size()), 1) * Params().Zerocoin_MintFee(); nValueRemaining = nValue - nMintingValue - (isZCSpendChange ? nFeeRet : 0); // if this is change of a zerocoinspend, then we can't mint all change, at least something must be given as a fee @@ -3833,7 +3832,7 @@ bool CWallet::CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransa // check for a zerocoinspend that mints the change CAmount nValueIn = 0; - set > setCoins; + std::set > setCoins; if (isZCSpendChange) { nValueIn = nValue; } else { @@ -4116,8 +4115,8 @@ bool CWallet::CreateZerocoinSpendTransaction( CWalletTx& wtxNew, CReserveKey& reserveKey, CZerocoinSpendReceipt& receipt, - vector& vSelectedMints, - vector& vNewMints, + std::vector& vSelectedMints, + std::vector& vNewMints, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* address, @@ -4140,12 +4139,12 @@ bool CWallet::CreateZerocoinSpendTransaction( // If not already given pre-selected mints, then select mints from the wallet CWalletDB walletdb(pwalletMain->strWalletFile); - set setMints; + std::set setMints; CAmount nValueSelected = 0; int nCoinsReturned = 0; // Number of coins returned in change from function below (for debug) int nNeededSpends = 0; // Number of spends which would be needed if selection failed const int nMaxSpends = Params().Zerocoin_MaxPublicSpendsPerTransaction(); // Maximum possible spends for one zPIV public spend transaction - vector vMintsToFetch; + std::vector vMintsToFetch; if (vSelectedMints.empty()) { // All of the zPIV used in the public coin spend are mature by default (everything is public now.. no need to wait for any accumulation) setMints = zpivTracker->ListMints(true, false, true, true); // need to find mints to spend @@ -4163,7 +4162,7 @@ bool CWallet::CreateZerocoinSpendTransaction( // Select the zPIV mints to use in this spend std::map DenomMap = GetMyZerocoinDistribution(); - list listMints(setMints.begin(), setMints.end()); + std::list listMints(setMints.begin(), setMints.end()); vMintsToFetch = SelectMintsFromList(nValueToSelect, nValueSelected, nMaxSpends, fMinimizeChange, nCoinsReturned, listMints, DenomMap, nNeededSpends); for (auto& meta : vMintsToFetch) { @@ -4290,7 +4289,7 @@ bool CWallet::CreateZerocoinSpendTransaction( //mint change as zerocoins if (fMintChange) { CAmount nFeeRet = 0; - string strFailReason = ""; + std::string strFailReason = ""; if (!CreateZerocoinMintTransaction(nChange, txNew, vNewMints, &reserveKey, nFeeRet, strFailReason, NULL, true)) { receipt.SetStatus(_("Failed to create mint"), nStatus); return false; @@ -4356,16 +4355,16 @@ bool CWallet::CreateZerocoinSpendTransaction( return true; } -string CWallet::ResetMintZerocoin() +std::string CWallet::ResetMintZerocoin() { long updates = 0; long deletions = 0; CWalletDB walletdb(pwalletMain->strWalletFile); - set setMints = zpivTracker->ListMints(false, false, true); - vector vMintsToFind(setMints.begin(), setMints.end()); - vector vMintsMissing; - vector vMintsToUpdate; + std::set setMints = zpivTracker->ListMints(false, false, true); + std::vector vMintsToFind(setMints.begin(), setMints.end()); + std::vector vMintsMissing; + std::vector vMintsToUpdate; // search all of our available data for these mints FindMints(vMintsToFind, vMintsToUpdate, vMintsMissing); @@ -4385,18 +4384,18 @@ string CWallet::ResetMintZerocoin() NotifyzPIVReset(); - string strResult = _("ResetMintZerocoin finished: ") + to_string(updates) + _(" mints updated, ") + to_string(deletions) + _(" mints deleted\n"); + std::string strResult = _("ResetMintZerocoin finished: ") + std::to_string(updates) + _(" mints updated, ") + std::to_string(deletions) + _(" mints deleted\n"); return strResult; } -string CWallet::ResetSpentZerocoin() +std::string CWallet::ResetSpentZerocoin() { long removed = 0; CWalletDB walletdb(pwalletMain->strWalletFile); - set setMints = zpivTracker->ListMints(false, false, true); - list listSpends = walletdb.ListSpentCoins(); - list listUnconfirmedSpends; + std::set setMints = zpivTracker->ListMints(false, false, true); + std::list listSpends = walletdb.ListSpentCoins(); + std::list listUnconfirmedSpends; for (CZerocoinSpend spend : listSpends) { CTransaction tx; @@ -4425,7 +4424,7 @@ string CWallet::ResetSpentZerocoin() NotifyzPIVReset(); - string strResult = _("ResetSpentZerocoin finished: ") + to_string(removed) + _(" unconfirmed transactions removed\n"); + std::string strResult = _("ResetSpentZerocoin finished: ") + std::to_string(removed) + _(" unconfirmed transactions removed\n"); return strResult; } @@ -4449,8 +4448,8 @@ bool IsMintInChain(const uint256& hashPubcoin, uint256& txid, int& nHeight) void CWallet::ReconsiderZerocoins(std::list& listMintsRestored, std::list& listDMintsRestored) { CWalletDB walletdb(pwalletMain->strWalletFile); - list listMints = walletdb.ListArchivedZerocoins(); - list listDMints = walletdb.ListArchivedDeterministicMints(); + std::list listMints = walletdb.ListArchivedZerocoins(); + std::list listDMints = walletdb.ListArchivedDeterministicMints(); if (listMints.empty() && listDMints.empty()) return; @@ -4494,9 +4493,9 @@ void CWallet::ReconsiderZerocoins(std::list& listMintsRestored, s } } -string CWallet::GetUniqueWalletBackupName(bool fzpivAuto) const +std::string CWallet::GetUniqueWalletBackupName(bool fzpivAuto) const { - stringstream ssDateTime; + std::stringstream ssDateTime; std::string strWalletBackupName = strprintf("%s", DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime())); ssDateTime << strWalletBackupName; @@ -4505,22 +4504,22 @@ string CWallet::GetUniqueWalletBackupName(bool fzpivAuto) const void CWallet::ZPivBackupWallet() { - filesystem::path backupDir = GetDataDir() / "backups"; - filesystem::path backupPath; - string strNewBackupName; + boost::filesystem::path backupDir = GetDataDir() / "backups"; + boost::filesystem::path backupPath; + std::string strNewBackupName; for (int i = 0; i < 10; i++) { strNewBackupName = strprintf("wallet-autozpivbackup-%d.dat", i); backupPath = backupDir / strNewBackupName; - if (filesystem::exists(backupPath)) { + if (boost::filesystem::exists(backupPath)) { //Keep up to 10 backups if (i <= 8) { //If the next file backup exists and is newer, then iterate - filesystem::path nextBackupPath = backupDir / strprintf("wallet-autozpivbackup-%d.dat", i + 1); - if (filesystem::exists(nextBackupPath)) { - time_t timeThis = filesystem::last_write_time(backupPath); - time_t timeNext = filesystem::last_write_time(nextBackupPath); + boost::filesystem::path nextBackupPath = backupDir / strprintf("wallet-autozpivbackup-%d.dat", i + 1); + if (boost::filesystem::exists(nextBackupPath)) { + time_t timeThis = boost::filesystem::last_write_time(backupPath); + time_t timeNext = boost::filesystem::last_write_time(nextBackupPath); if (timeThis > timeNext) { //The next backup is created before this backup was //The next backup is the correct path to use @@ -4543,8 +4542,8 @@ void CWallet::ZPivBackupWallet() BackupWallet(*this, backupPath.string()); if(!GetArg("-zpivbackuppath", "").empty()) { - filesystem::path customPath(GetArg("-zpivbackuppath", "")); - filesystem::create_directories(customPath); + boost::filesystem::path customPath(GetArg("-zpivbackuppath", "")); + boost::filesystem::create_directories(customPath); if(!customPath.has_extension()) { customPath /= GetUniqueWalletBackupName(true); @@ -4555,23 +4554,23 @@ void CWallet::ZPivBackupWallet() } -string CWallet::MintZerocoinFromOutPoint(CAmount nValue, CWalletTx& wtxNew, vector& vDMints, const vector vOutpts) +std::string CWallet::MintZerocoinFromOutPoint(CAmount nValue, CWalletTx& wtxNew, std::vector& vDMints, const std::vector vOutpts) { CCoinControl* coinControl = new CCoinControl(); for (const COutPoint& outpt : vOutpts) { coinControl->Select(outpt); } if (!coinControl->HasSelected()){ - string strError = _("Error: No valid utxo!"); + std::string strError = _("Error: No valid utxo!"); LogPrintf("MintZerocoin() : %s", strError.c_str()); return strError; } - string strError = MintZerocoin(nValue, wtxNew, vDMints, coinControl); + std::string strError = MintZerocoin(nValue, wtxNew, vDMints, coinControl); delete coinControl; return strError; } -string CWallet::MintZerocoin(CAmount nValue, CWalletTx& wtxNew, vector& vDMints, const CCoinControl* coinControl) +std::string CWallet::MintZerocoin(CAmount nValue, CWalletTx& wtxNew, std::vector& vDMints, const CCoinControl* coinControl) { // Check amount if (nValue <= 0) @@ -4587,12 +4586,12 @@ string CWallet::MintZerocoin(CAmount nValue, CWalletTx& wtxNew, vector GetBalance()) @@ -4629,7 +4628,7 @@ string CWallet::MintZerocoin(CAmount nValue, CWalletTx& wtxNew, vector& vMintsSelected, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* addressTo, bool isPublicSpend) +bool CWallet::SpendZerocoin(CAmount nAmount, CWalletTx& wtxNew, CZerocoinSpendReceipt& receipt, std::vector& vMintsSelected, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* addressTo, bool isPublicSpend) { // Default: assume something goes wrong. Depending on the problem this gets more specific below int nStatus = ZPIV_SPEND_ERROR; @@ -4640,7 +4639,7 @@ bool CWallet::SpendZerocoin(CAmount nAmount, CWalletTx& wtxNew, CZerocoinSpendRe } CReserveKey reserveKey(this); - vector vNewMints; + std::vector vNewMints; if (!CreateZerocoinSpendTransaction(nAmount, wtxNew, reserveKey, receipt, vMintsSelected, vNewMints, fMintChange, fMinimizeChange, addressTo, isPublicSpend)) { return false; } @@ -4808,7 +4807,7 @@ void CWallet::PrecomputeSpends() // Create LRU Cache std::list > item_list; - std::map >::iterator> item_map; + std::map >::iterator> item_map; // Dirty cache that needs to be written to disk std::map mapDirtyWitnessData; @@ -4939,8 +4938,8 @@ void CWallet::PrecomputeSpends() nAdjustableCacheLength); // Add the serialHash found into the cache - item_list.push_front(make_pair(serialHash, tempDataHolder)); - item_map.insert(make_pair(serialHash, item_list.begin())); + item_list.push_front(std::make_pair(serialHash, tempDataHolder)); + item_map.insert(std::make_pair(serialHash, item_list.begin())); // We just added a new hash into our LRU cache, so remove it if we also have it in the dirty map mapDirtyWitnessData.erase(serialHash); @@ -4995,8 +4994,8 @@ void CWallet::PrecomputeSpends() item_list.splice(item_list.begin(), item_list, it->second); item_list.begin()->second = serialData; } else { - item_list.push_front(make_pair(serialHash, serialData)); - item_map.insert(make_pair(serialHash, item_list.begin())); + item_list.push_front(std::make_pair(serialHash, serialData)); + item_map.insert(std::make_pair(serialHash, item_list.begin())); } // We just added a new hash into our LRU cache, so remove it if we also have it in the dirty map @@ -5025,7 +5024,7 @@ void CWallet::PrecomputeSpends() // We only want to clear the cache if we have calculated new witness data if (setInputHashes.size()) { // Get a list of hashes currently in the database - set databaseHashes; + std::set databaseHashes; walletdb.LoadPrecomputes(databaseHashes); // Remove old cache data diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 189098b44a34..eb48efbb91bf 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -201,8 +201,8 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface bool IsCollateralAmount(CAmount nInputAmount) const; // Zerocoin additions - bool CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, vector& vDMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = NULL, const bool isZCSpendChange = false); - bool CreateZerocoinSpendTransaction(CAmount nValue, CWalletTx& wtxNew, CReserveKey& reserveKey, CZerocoinSpendReceipt& receipt, vector& vSelectedMints, vector& vNewMints, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* address = NULL, bool isPublicSpend = true); + bool CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, std::vector& vDMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl = NULL, const bool isZCSpendChange = false); + bool CreateZerocoinSpendTransaction(CAmount nValue, CWalletTx& wtxNew, CReserveKey& reserveKey, CZerocoinSpendReceipt& receipt, std::vector& vSelectedMints, std::vector& vNewMints, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* address = NULL, bool isPublicSpend = true); bool CheckCoinSpend(libzerocoin::CoinSpend& spend, libzerocoin::Accumulator& accumulator, CZerocoinSpendReceipt& receipt); bool MintToTxIn(CZerocoinMint mint, const uint256& hashTxOut, CTxIn& newTxIn, CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr, bool publicCoinSpend = true); bool MintsToInputVector(std::map& mapMintsSelected, const uint256& hashTxOut, std::vector& vin, @@ -212,9 +212,9 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface bool MintsToInputVectorPublicSpend(std::map& mapMintsSelected, const uint256& hashTxOut, std::vector& vin, CZerocoinSpendReceipt& receipt, libzerocoin::SpendType spendType, CBlockIndex* pindexCheckpoint = nullptr); - std::string MintZerocoinFromOutPoint(CAmount nValue, CWalletTx& wtxNew, std::vector& vDMints, const vector vOutpts); - std::string MintZerocoin(CAmount nValue, CWalletTx& wtxNew, vector& vDMints, const CCoinControl* coinControl = NULL); - bool SpendZerocoin(CAmount nValue, CWalletTx& wtxNew, CZerocoinSpendReceipt& receipt, vector& vMintsSelected, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* addressTo = NULL, bool isPublicSpend = true); + std::string MintZerocoinFromOutPoint(CAmount nValue, CWalletTx& wtxNew, std::vector& vDMints, const std::vector vOutpts); + std::string MintZerocoin(CAmount nValue, CWalletTx& wtxNew, std::vector& vDMints, const CCoinControl* coinControl = NULL); + bool SpendZerocoin(CAmount nValue, CWalletTx& wtxNew, CZerocoinSpendReceipt& receipt, std::vector& vMintsSelected, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* addressTo = NULL, bool isPublicSpend = true); std::string ResetMintZerocoin(); std::string ResetSpentZerocoin(); void ReconsiderZerocoins(std::list& listMintsRestored, std::list& listDMintsRestored); @@ -226,7 +226,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface bool DatabaseMint(CDeterministicMint& dMint); bool SetMintUnspent(const CBigNum& bnSerial); bool UpdateMint(const CBigNum& bnValue, const int& nHeight, const uint256& txid, const libzerocoin::CoinDenomination& denom); - string GetUniqueWalletBackupName(bool fzpivAuto) const; + std::string GetUniqueWalletBackupName(bool fzpivAuto) const; void InitAutoConvertAddresses(); diff --git a/src/wallet/wallet_ismine.cpp b/src/wallet/wallet_ismine.cpp index 4c62ff84e2a5..aaa9a61c0676 100644 --- a/src/wallet/wallet_ismine.cpp +++ b/src/wallet/wallet_ismine.cpp @@ -13,11 +13,10 @@ #include "util.h" -using namespace std; -typedef vector valtype; +typedef std::vector valtype; -unsigned int HaveKeys(const vector& pubkeys, const CKeyStore& keystore) +unsigned int HaveKeys(const std::vector& pubkeys, const CKeyStore& keystore) { unsigned int nResult = 0; for (const valtype& pubkey : pubkeys) { @@ -41,7 +40,7 @@ isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) if(keystore.HaveMultiSig(scriptPubKey)) return ISMINE_MULTISIG; - vector vSolutions; + std::vector vSolutions; txnouttype whichType; if(!Solver(scriptPubKey, whichType, vSolutions)) { if(keystore.HaveWatchOnly(scriptPubKey)) @@ -84,7 +83,7 @@ isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) // partially owned (somebody else has a key that can spend // them) enable spend-out-from-under-you attacks, especially // in shared-wallet situations. - vector keys(vSolutions.begin() + 1, vSolutions.begin() + vSolutions.size() - 1); + std::vector keys(vSolutions.begin() + 1, vSolutions.begin() + vSolutions.size() - 1); if(HaveKeys(keys, keystore) == keys.size()) return ISMINE_SPENDABLE; break; diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index 566918b9b365..9677757365e6 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -22,8 +22,6 @@ #include #include -using namespace boost; -using namespace std; static uint64_t nAccountingEntryNumber = 0; @@ -31,30 +29,30 @@ static uint64_t nAccountingEntryNumber = 0; // CWalletDB // -bool CWalletDB::WriteName(const string& strAddress, const string& strName) +bool CWalletDB::WriteName(const std::string& strAddress, const std::string& strName) { nWalletDBUpdated++; - return Write(make_pair(string("name"), strAddress), strName); + return Write(std::make_pair(std::string("name"), strAddress), strName); } -bool CWalletDB::EraseName(const string& strAddress) +bool CWalletDB::EraseName(const std::string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; - return Erase(make_pair(string("name"), strAddress)); + return Erase(std::make_pair(std::string("name"), strAddress)); } -bool CWalletDB::WritePurpose(const string& strAddress, const string& strPurpose) +bool CWalletDB::WritePurpose(const std::string& strAddress, const std::string& strPurpose) { nWalletDBUpdated++; - return Write(make_pair(string("purpose"), strAddress), strPurpose); + return Write(std::make_pair(std::string("purpose"), strAddress), strPurpose); } -bool CWalletDB::ErasePurpose(const string& strPurpose) +bool CWalletDB::ErasePurpose(const std::string& strPurpose) { nWalletDBUpdated++; - return Erase(make_pair(string("purpose"), strPurpose)); + return Erase(std::make_pair(std::string("purpose"), strPurpose)); } bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx) @@ -82,14 +80,14 @@ void CWalletDB::LoadAutoConvertKeys(std::set& setAddresses) setAddresses.clear(); Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("automint"), CKeyID()); + ssKey << make_pair(std::string("automint"), CKeyID()); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -98,7 +96,7 @@ void CWalletDB::LoadAutoConvertKeys(std::set& setAddresses) else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize @@ -314,15 +312,15 @@ bool CWalletDB::WriteMinVersion(int nVersion) return Write(std::string("minversion"), nVersion); } -bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) +bool CWalletDB::ReadAccount(const std::string& strAccount, CAccount& account) { account.SetNull(); - return Read(make_pair(string("acc"), strAccount), account); + return Read(std::make_pair(std::string("acc"), strAccount), account); } -bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) +bool CWalletDB::WriteAccount(const std::string& strAccount, const CAccount& account) { - return Write(make_pair(string("acc"), strAccount), account); + return Write(std::make_pair(std::string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) @@ -335,9 +333,9 @@ bool CWalletDB::WriteAccountingEntry_Backend(const CAccountingEntry& acentry) return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } -CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount) +CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount) { - list entries; + std::list entries; ListAccountCreditDebit(strAccount, entries); CAmount nCreditDebit = 0; @@ -347,19 +345,19 @@ CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount) return nCreditDebit; } -void CWalletDB::ListAccountCreditDebit(const string& strAccount, list& entries) +void CWalletDB::ListAccountCreditDebit(const std::string& strAccount, std::list& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); + throw std::runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? string("") : strAccount), uint64_t(0))); + ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? std::string("") : strAccount), uint64_t(0))); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -367,11 +365,11 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, listclose(); - throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); + throw std::runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "acentry") break; @@ -395,18 +393,18 @@ DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. - typedef pair TxPair; - typedef multimap TxItems; + typedef std::pair TxPair; + typedef std::multimap TxItems; TxItems txByTime; - for (map::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { + for (std::map::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); - txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); + txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } - list acentries; + std::list acentries; ListAccountCreditDebit("", acentries); for (CAccountingEntry& entry : acentries) { - txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); + txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; @@ -460,7 +458,7 @@ class CWalletScanState bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; - vector vWalletUpgrade; + std::vector vWalletUpgrade; CWalletScanState() { @@ -471,7 +469,7 @@ class CWalletScanState } }; -bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState& wss, string& strType, string& strErr) +bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState& wss, std::string& strType, std::string& strErr) { try { // Unserialize @@ -479,11 +477,11 @@ bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CW // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { - string strAddress; + std::string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].name; } else if (strType == "purpose") { - string strAddress; + std::string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].purpose; } else if (strType == "tx") { @@ -517,7 +515,7 @@ bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CW pwallet->AddToWallet(wtx, true); } else if (strType == "acentry") { - string strAccount; + std::string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; @@ -622,7 +620,7 @@ bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CW } else if (strType == "ckey") { CPubKey vchPubKey; ssKey >> vchPubKey; - vector vchPrivKey; + std::vector vchPrivKey; ssValue >> vchPrivKey; wss.nCKeys++; @@ -719,7 +717,7 @@ bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CW return true; } -static bool IsKeyType(string strType) +static bool IsKeyType(std::string strType) { return (strType == "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); @@ -735,7 +733,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; - if (Read((string) "minversion", nMinVersion)) { + if (Read((std::string) "minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); @@ -761,7 +759,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) } // Try to be tolerant of single corrupt records: - string strType, strErr; + std::string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: @@ -818,13 +816,13 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) pwallet->laccentries.clear(); ListAccountCreditDebit("*", pwallet->laccentries); for (CAccountingEntry& entry : pwallet->laccentries) { - pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry))); + pwallet->wtxOrdered.insert(std::make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry))); } return result; } -DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector& vTxHash, vector& vWtx) +DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, std::vector& vTxHash, std::vector& vWtx) { pwallet->vchDefaultKey = CPubKey(); bool fNoncriticalErrors = false; @@ -833,7 +831,7 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector& vTxHash, vec try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; - if (Read((string) "minversion", nMinVersion)) { + if (Read((std::string) "minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); @@ -858,7 +856,7 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector& vTxHash, vec return DB_CORRUPT; } - string strType; + std::string strType; ssKey >> strType; if (strType == "tx") { uint256 hash; @@ -884,10 +882,10 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector& vTxHash, vec return result; } -DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, vector& vWtx) +DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, std::vector& vWtx) { // build list of wallet TXs - vector vTxHash; + std::vector vTxHash; DBErrors err = FindWalletTx(pwallet, vTxHash, vWtx); if (err != DB_LOAD_OK) return err; @@ -901,7 +899,7 @@ DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, vector& vWtx) return DB_LOAD_OK; } -void ThreadFlushWalletDB(const string& strFile) +void ThreadFlushWalletDB(const std::string& strFile) { // Make this thread recognisable as the wallet flushing thread RenameThread("pivx-wallet"); @@ -929,7 +927,7 @@ void ThreadFlushWalletDB(const string& strFile) if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; - map::iterator mi = bitdb.mapFileUseCount.begin(); + std::map::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; @@ -937,7 +935,7 @@ void ThreadFlushWalletDB(const string& strFile) if (nRefCount == 0) { boost::this_thread::interruption_point(); - map::iterator mi = bitdb.mapFileUseCount.find(strFile); + std::map::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { LogPrint("db", "Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; @@ -956,16 +954,16 @@ void ThreadFlushWalletDB(const string& strFile) } } -void NotifyBacked(const CWallet& wallet, bool fSuccess, string strMessage) +void NotifyBacked(const CWallet& wallet, bool fSuccess, std::string strMessage) { LogPrint(nullptr, strMessage.data()); wallet.NotifyWalletBacked(fSuccess, strMessage); } -bool BackupWallet(const CWallet& wallet, const filesystem::path& strDest, bool fEnableCustom) +bool BackupWallet(const CWallet& wallet, const boost::filesystem::path& strDest, bool fEnableCustom) { - filesystem::path pathCustom; - filesystem::path pathWithFile; + boost::filesystem::path pathCustom; + boost::filesystem::path pathWithFile; if (!wallet.fFileBacked) { return false; } else if(fEnableCustom) { @@ -978,8 +976,8 @@ bool BackupWallet(const CWallet& wallet, const filesystem::path& strDest, bool f pathCustom = pathWithFile.parent_path(); } try { - filesystem::create_directories(pathCustom); - } catch(const filesystem::filesystem_error& e) { + boost::filesystem::create_directories(pathCustom); + } catch(const boost::filesystem::filesystem_error& e) { NotifyBacked(wallet, false, strprintf("%s\n", e.what())); pathCustom = ""; } @@ -996,8 +994,8 @@ bool BackupWallet(const CWallet& wallet, const filesystem::path& strDest, bool f bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat - filesystem::path pathDest(strDest); - filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; + boost::filesystem::path pathDest(strDest); + boost::filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; if (is_directory(pathDest)) { if(!exists(pathDest)) create_directory(pathDest); pathDest /= wallet.strWalletFile; @@ -1008,21 +1006,21 @@ bool BackupWallet(const CWallet& wallet, const filesystem::path& strDest, bool f int nThreshold = GetArg("-custombackupthreshold", DEFAULT_CUSTOMBACKUPTHRESHOLD); if (nThreshold > 0) { - typedef std::multimap folder_set_t; + typedef std::multimap folder_set_t; folder_set_t folderSet; - filesystem::directory_iterator end_iter; + boost::filesystem::directory_iterator end_iter; pathCustom.make_preferred(); // Build map of backup files for current(!) wallet sorted by last write time - filesystem::path currentFile; - for (filesystem::directory_iterator dir_iter(pathCustom); dir_iter != end_iter; ++dir_iter) { + boost::filesystem::path currentFile; + for (boost::filesystem::directory_iterator dir_iter(pathCustom); dir_iter != end_iter; ++dir_iter) { // Only check regular files - if (filesystem::is_regular_file(dir_iter->status())) { + if (boost::filesystem::is_regular_file(dir_iter->status())) { currentFile = dir_iter->path().filename(); // Only add the backups for the current wallet, e.g. wallet.dat.* if (dir_iter->path().stem().string() == wallet.strWalletFile) { - folderSet.insert(folder_set_t::value_type(filesystem::last_write_time(dir_iter->path()), *dir_iter)); + folderSet.insert(folder_set_t::value_type(boost::filesystem::last_write_time(dir_iter->path()), *dir_iter)); } } } @@ -1046,11 +1044,11 @@ bool BackupWallet(const CWallet& wallet, const filesystem::path& strDest, bool f try { auto entry = folderSet.find(oldestBackup); if (entry != folderSet.end()) { - filesystem::remove(entry->second); + boost::filesystem::remove(entry->second); LogPrintf("Old backup deleted: %s\n", (*entry).second); } - } catch (filesystem::filesystem_error& error) { - string strMessage = strprintf("Failed to delete backup %s\n", error.what()); + } catch (boost::filesystem::filesystem_error& error) { + std::string strMessage = strprintf("Failed to delete backup %s\n", error.what()); LogPrint(nullptr, strMessage.data()); NotifyBacked(wallet, false, strMessage); } @@ -1067,17 +1065,17 @@ bool BackupWallet(const CWallet& wallet, const filesystem::path& strDest, bool f return false; } -bool AttemptBackupWallet(const CWallet& wallet, const filesystem::path& pathSrc, const filesystem::path& pathDest) +bool AttemptBackupWallet(const CWallet& wallet, const boost::filesystem::path& pathSrc, const boost::filesystem::path& pathDest) { bool retStatus; - string strMessage; + std::string strMessage; try { if (boost::filesystem::equivalent(pathSrc, pathDest)) { LogPrintf("cannot backup to wallet source file %s\n", pathDest.string()); return false; } #if BOOST_VERSION >= 105800 /* BOOST_LIB_VERSION 1_58 */ - filesystem::copy_file(pathSrc.c_str(), pathDest, filesystem::copy_option::overwrite_if_exists); + boost::filesystem::copy_file(pathSrc.c_str(), pathDest, boost::filesystem::copy_option::overwrite_if_exists); #else std::ifstream src(pathSrc.c_str(), std::ios::binary | std::ios::in); std::ofstream dst(pathDest.c_str(), std::ios::binary | std::ios::out | std::ios::trunc); @@ -1089,7 +1087,7 @@ bool AttemptBackupWallet(const CWallet& wallet, const filesystem::path& pathSrc, strMessage = strprintf("copied wallet.dat to %s\n", pathDest.string()); LogPrint(nullptr, strMessage.data()); retStatus = true; - } catch (const filesystem::filesystem_error& e) { + } catch (const boost::filesystem::filesystem_error& e) { retStatus = false; strMessage = strprintf("%s\n", e.what()); LogPrint(nullptr, strMessage.data()); @@ -1150,7 +1148,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); - string strType, strErr; + std::string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) @@ -1191,33 +1189,33 @@ bool CWalletDB::EraseDestData(const std::string& address, const std::string& key bool CWalletDB::WriteZerocoinSpendSerialEntry(const CZerocoinSpend& zerocoinSpend) { - return Write(make_pair(string("zcserial"), zerocoinSpend.GetSerial()), zerocoinSpend, true); + return Write(std::make_pair(std::string("zcserial"), zerocoinSpend.GetSerial()), zerocoinSpend, true); } bool CWalletDB::EraseZerocoinSpendSerialEntry(const CBigNum& serialEntry) { - return Erase(make_pair(string("zcserial"), serialEntry)); + return Erase(std::make_pair(std::string("zcserial"), serialEntry)); } bool CWalletDB::ReadZerocoinSpendSerialEntry(const CBigNum& bnSerial) { CZerocoinSpend spend; - return Read(make_pair(string("zcserial"), bnSerial), spend); + return Read(std::make_pair(std::string("zcserial"), bnSerial), spend); } bool CWalletDB::WriteDeterministicMint(const CDeterministicMint& dMint) { uint256 hash = dMint.GetPubcoinHash(); - return Write(make_pair(string("dzpiv"), hash), dMint, true); + return Write(std::make_pair(std::string("dzpiv"), hash), dMint, true); } bool CWalletDB::ReadDeterministicMint(const uint256& hashPubcoin, CDeterministicMint& dMint) { - return Read(make_pair(string("dzpiv"), hashPubcoin), dMint); + return Read(std::make_pair(std::string("dzpiv"), hashPubcoin), dMint); } bool CWalletDB::EraseDeterministicMint(const uint256& hashPubcoin) { - return Erase(make_pair(string("dzpiv"), hashPubcoin)); + return Erase(std::make_pair(std::string("dzpiv"), hashPubcoin)); } bool CWalletDB::WriteZerocoinMint(const CZerocoinMint& zerocoinMint) @@ -1226,8 +1224,8 @@ bool CWalletDB::WriteZerocoinMint(const CZerocoinMint& zerocoinMint) ss << zerocoinMint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end()); - Erase(make_pair(string("zerocoin"), hash)); - return Write(make_pair(string("zerocoin"), hash), zerocoinMint, true); + Erase(std::make_pair(std::string("zerocoin"), hash)); + return Write(std::make_pair(std::string("zerocoin"), hash), zerocoinMint, true); } bool CWalletDB::ReadZerocoinMint(const CBigNum &bnPubCoinValue, CZerocoinMint& zerocoinMint) @@ -1241,7 +1239,7 @@ bool CWalletDB::ReadZerocoinMint(const CBigNum &bnPubCoinValue, CZerocoinMint& z bool CWalletDB::ReadZerocoinMint(const uint256& hashPubcoin, CZerocoinMint& mint) { - return Read(make_pair(string("zerocoin"), hashPubcoin), mint); + return Read(std::make_pair(std::string("zerocoin"), hashPubcoin), mint); } bool CWalletDB::EraseZerocoinMint(const CZerocoinMint& zerocoinMint) @@ -1250,7 +1248,7 @@ bool CWalletDB::EraseZerocoinMint(const CZerocoinMint& zerocoinMint) ss << zerocoinMint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end()); - return Erase(make_pair(string("zerocoin"), hash)); + return Erase(std::make_pair(std::string("zerocoin"), hash)); } bool CWalletDB::ArchiveMintOrphan(const CZerocoinMint& zerocoinMint) @@ -1259,12 +1257,12 @@ bool CWalletDB::ArchiveMintOrphan(const CZerocoinMint& zerocoinMint) ss << zerocoinMint.GetValue(); uint256 hash = Hash(ss.begin(), ss.end());; - if (!Write(make_pair(string("zco"), hash), zerocoinMint)) { + if (!Write(std::make_pair(std::string("zco"), hash), zerocoinMint)) { LogPrintf("%s : failed to database orphaned zerocoin mint\n", __func__); return false; } - if (!Erase(make_pair(string("zerocoin"), hash))) { + if (!Erase(std::make_pair(std::string("zerocoin"), hash))) { LogPrintf("%s : failed to erase orphaned zerocoin mint\n", __func__); return false; } @@ -1274,10 +1272,10 @@ bool CWalletDB::ArchiveMintOrphan(const CZerocoinMint& zerocoinMint) bool CWalletDB::ArchiveDeterministicOrphan(const CDeterministicMint& dMint) { - if (!Write(make_pair(string("dzco"), dMint.GetPubcoinHash()), dMint)) + if (!Write(std::make_pair(std::string("dzco"), dMint.GetPubcoinHash()), dMint)) return error("%s: write failed", __func__); - if (!Erase(make_pair(string("dzpiv"), dMint.GetPubcoinHash()))) + if (!Erase(std::make_pair(std::string("dzpiv"), dMint.GetPubcoinHash()))) return error("%s: failed to erase", __func__); return true; @@ -1285,13 +1283,13 @@ bool CWalletDB::ArchiveDeterministicOrphan(const CDeterministicMint& dMint) bool CWalletDB::UnarchiveDeterministicMint(const uint256& hashPubcoin, CDeterministicMint& dMint) { - if (!Read(make_pair(string("dzco"), hashPubcoin), dMint)) + if (!Read(std::make_pair(std::string("dzco"), hashPubcoin), dMint)) return error("%s: failed to retrieve deterministic mint from archive", __func__); if (!WriteDeterministicMint(dMint)) return error("%s: failed to write deterministic mint", __func__); - if (!Erase(make_pair(string("dzco"), dMint.GetPubcoinHash()))) + if (!Erase(std::make_pair(std::string("dzco"), dMint.GetPubcoinHash()))) return error("%s : failed to erase archived deterministic mint", __func__); return true; @@ -1299,14 +1297,14 @@ bool CWalletDB::UnarchiveDeterministicMint(const uint256& hashPubcoin, CDetermin bool CWalletDB::UnarchiveZerocoinMint(const uint256& hashPubcoin, CZerocoinMint& mint) { - if (!Read(make_pair(string("zco"), hashPubcoin), mint)) + if (!Read(std::make_pair(std::string("zco"), hashPubcoin), mint)) return error("%s: failed to retrieve zerocoinmint from archive", __func__); if (!WriteZerocoinMint(mint)) return error("%s: failed to write zerocoinmint", __func__); uint256 hash = GetPubCoinHash(mint.GetValue()); - if (!Erase(make_pair(string("zco"), hash))) + if (!Erase(std::make_pair(std::string("zco"), hash))) return error("%s : failed to erase archived zerocoin mint", __func__); return true; @@ -1314,20 +1312,20 @@ bool CWalletDB::UnarchiveZerocoinMint(const uint256& hashPubcoin, CZerocoinMint& bool CWalletDB::WriteCurrentSeedHash(const uint256& hashSeed) { - return Write(string("seedhash"), hashSeed); + return Write(std::string("seedhash"), hashSeed); } bool CWalletDB::ReadCurrentSeedHash(uint256& hashSeed) { - return Read(string("seedhash"), hashSeed); + return Read(std::string("seedhash"), hashSeed); } -bool CWalletDB::WriteZPIVSeed(const uint256& hashSeed, const vector& seed) +bool CWalletDB::WriteZPIVSeed(const uint256& hashSeed, const std::vector& seed) { if (!WriteCurrentSeedHash(hashSeed)) return error("%s: failed to write current seed hash", __func__); - return Write(make_pair(string("dzs"), hashSeed), seed); + return Write(std::make_pair(std::string("dzs"), hashSeed), seed); } bool CWalletDB::EraseZPIVSeed() @@ -1348,47 +1346,47 @@ bool CWalletDB::EraseZPIVSeed() bool CWalletDB::EraseZPIVSeed_deprecated() { - return Erase(string("dzs")); + return Erase(std::string("dzs")); } -bool CWalletDB::ReadZPIVSeed(const uint256& hashSeed, vector& seed) +bool CWalletDB::ReadZPIVSeed(const uint256& hashSeed, std::vector& seed) { - return Read(make_pair(string("dzs"), hashSeed), seed); + return Read(std::make_pair(std::string("dzs"), hashSeed), seed); } bool CWalletDB::ReadZPIVSeed_deprecated(uint256& seed) { - return Read(string("dzs"), seed); + return Read(std::string("dzs"), seed); } bool CWalletDB::WriteZPIVCount(const uint32_t& nCount) { - return Write(string("dzc"), nCount); + return Write(std::string("dzc"), nCount); } bool CWalletDB::ReadZPIVCount(uint32_t& nCount) { - return Read(string("dzc"), nCount); + return Read(std::string("dzc"), nCount); } bool CWalletDB::WriteMintPoolPair(const uint256& hashMasterSeed, const uint256& hashPubcoin, const uint32_t& nCount) { - return Write(make_pair(string("mintpool"), hashPubcoin), make_pair(hashMasterSeed, nCount)); + return Write(std::make_pair(std::string("mintpool"), hashPubcoin), std::make_pair(hashMasterSeed, nCount)); } -void CWalletDB::LoadPrecomputes(std::list >& itemList, std::map >::iterator>& itemMap) +void CWalletDB::LoadPrecomputes(std::list >& itemList, std::map >::iterator>& itemMap) { Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("precompute"), uint256(0)); + ssKey << std::make_pair(std::string("precompute"), uint256(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1397,11 +1395,11 @@ void CWalletDB::LoadPrecomputes(std::listclose(); - throw runtime_error(std::string(__func__)+" : error scanning precompute DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning precompute DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "precompute") break; @@ -1413,7 +1411,7 @@ void CWalletDB::LoadPrecomputes(std::list> cacheData; itemList.push_front(std::make_pair(hash, cacheData)); - itemMap.insert(make_pair(hash, itemList.begin())); + itemMap.insert(std::make_pair(hash, itemList.begin())); if (itemMap.size() == PRECOMPUTE_LRU_CACHE_SIZE) break; @@ -1422,18 +1420,18 @@ void CWalletDB::LoadPrecomputes(std::listclose(); } -void CWalletDB::LoadPrecomputes(set setHashes) +void CWalletDB::LoadPrecomputes(std::set setHashes) { Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("precompute"), uint256(0)); + ssKey << make_pair(std::string("precompute"), uint256(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1442,11 +1440,11 @@ void CWalletDB::LoadPrecomputes(set setHashes) else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning precompute DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning precompute DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "precompute") break; @@ -1462,7 +1460,7 @@ void CWalletDB::LoadPrecomputes(set setHashes) void CWalletDB::EraseAllPrecomputes() { - set setHashes; + std::set setHashes; LoadPrecomputes(setHashes); for (auto hash : setHashes) @@ -1471,31 +1469,31 @@ void CWalletDB::EraseAllPrecomputes() bool CWalletDB::WritePrecompute(const uint256& hash, const CoinWitnessCacheData& data) { - return Write(make_pair(string("precompute"), hash), data); + return Write(std::make_pair(std::string("precompute"), hash), data); } bool CWalletDB::ReadPrecompute(const uint256& hash, CoinWitnessCacheData& data) { - return Read(make_pair(string("precompute"), hash), data); + return Read(std::make_pair(std::string("precompute"), hash), data); } bool CWalletDB::ErasePrecompute(const uint256& hash) { - return Erase(make_pair(string("precompute"), hash)); + return Erase(std::make_pair(std::string("precompute"), hash)); } //! map with hashMasterSeed as the key, paired with vector of hashPubcoins and their count -std::map > > CWalletDB::MapMintPool() +std::map > > CWalletDB::MapMintPool() { - std::map > > mapPool; + std::map > > mapPool; Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("mintpool"), uint256(0)); + ssKey << std::make_pair(std::string("mintpool"), uint256(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1504,11 +1502,11 @@ std::map > > CWalletDB::MapMintPool else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "mintpool") break; @@ -1522,15 +1520,15 @@ std::map > > CWalletDB::MapMintPool uint32_t nCount; ssValue >> nCount; - pair pMint; + std::pair pMint; pMint.first = hashPubcoin; pMint.second = nCount; if (mapPool.count(hashMasterSeed)) { mapPool.at(hashMasterSeed).emplace_back(pMint); } else { - vector > vPairs; + std::vector > vPairs; vPairs.emplace_back(pMint); - mapPool.insert(make_pair(hashMasterSeed, vPairs)); + mapPool.insert(std::make_pair(hashMasterSeed, vPairs)); } } @@ -1544,14 +1542,14 @@ std::list CWalletDB::ListDeterministicMints() std::list listMints; Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("dzpiv"), uint256(0)); + ssKey << make_pair(std::string("dzpiv"), uint256(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1560,11 +1558,11 @@ std::list CWalletDB::ListDeterministicMints() else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "dzpiv") break; @@ -1587,16 +1585,16 @@ std::list CWalletDB::ListMintedCoins() std::list listPubCoin; Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; - vector vOverWrite; - vector vArchive; + std::vector vOverWrite; + std::vector vArchive; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("zerocoin"), uint256(0)); + ssKey << make_pair(std::string("zerocoin"), uint256(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1605,11 +1603,11 @@ std::list CWalletDB::ListMintedCoins() else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "zerocoin") break; @@ -1632,14 +1630,14 @@ std::list CWalletDB::ListSpentCoins() std::list listCoinSpend; Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("zcserial"), CBigNum(0)); + ssKey << make_pair(std::string("zcserial"), CBigNum(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1648,11 +1646,11 @@ std::list CWalletDB::ListSpentCoins() else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "zcserial") break; @@ -1687,14 +1685,14 @@ std::list CWalletDB::ListArchivedZerocoins() std::list listMints; Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("zco"), CBigNum(0)); + ssKey << make_pair(std::string("zco"), CBigNum(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1703,11 +1701,11 @@ std::list CWalletDB::ListArchivedZerocoins() else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "zco") break; @@ -1730,14 +1728,14 @@ std::list CWalletDB::ListArchivedDeterministicMints() std::list listMints; Dbc* pcursor = GetCursor(); if (!pcursor) - throw runtime_error(std::string(__func__)+" : cannot create DB cursor"); + throw std::runtime_error(std::string(__func__)+" : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; for (;;) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) - ssKey << make_pair(string("dzco"), CBigNum(0)); + ssKey << make_pair(std::string("dzco"), CBigNum(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; @@ -1746,11 +1744,11 @@ std::list CWalletDB::ListArchivedDeterministicMints() else if (ret != 0) { pcursor->close(); - throw runtime_error(std::string(__func__)+" : error scanning DB"); + throw std::runtime_error(std::string(__func__)+" : error scanning DB"); } // Unserialize - string strType; + std::string strType; ssKey >> strType; if (strType != "dzco") break; diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h index 458cbff07479..6ccc76d69f7d 100644 --- a/src/wallet/walletdb.h +++ b/src/wallet/walletdb.h @@ -179,19 +179,19 @@ class CWalletDB : public CDB bool ReadZerocoinSpendSerialEntry(const CBigNum& bnSerial); bool WriteCurrentSeedHash(const uint256& hashSeed); bool ReadCurrentSeedHash(uint256& hashSeed); - bool WriteZPIVSeed(const uint256& hashSeed, const vector& seed); - bool ReadZPIVSeed(const uint256& hashSeed, vector& seed); + bool WriteZPIVSeed(const uint256& hashSeed, const std::vector& seed); + bool ReadZPIVSeed(const uint256& hashSeed, std::vector& seed); bool ReadZPIVSeed_deprecated(uint256& seed); bool EraseZPIVSeed(); bool EraseZPIVSeed_deprecated(); bool WriteZPIVCount(const uint32_t& nCount); bool ReadZPIVCount(uint32_t& nCount); - std::map > > MapMintPool(); + std::map > > MapMintPool(); bool WriteMintPoolPair(const uint256& hashMasterSeed, const uint256& hashPubcoin, const uint32_t& nCount); - void LoadPrecomputes(std::list >& itemList, std::map >::iterator>& itemMap); - void LoadPrecomputes(set setHashes); + void LoadPrecomputes(std::list >& itemList, std::map >::iterator>& itemMap); + void LoadPrecomputes(std::set setHashes); void EraseAllPrecomputes(); bool WritePrecompute(const uint256& hash, const CoinWitnessCacheData& data); bool ReadPrecompute(const uint256& hash, CoinWitnessCacheData& data); @@ -204,7 +204,7 @@ class CWalletDB : public CDB bool WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry); }; -void NotifyBacked(const CWallet& wallet, bool fSuccess, string strMessage); +void NotifyBacked(const CWallet& wallet, bool fSuccess, std::string strMessage); bool BackupWallet(const CWallet& wallet, const boost::filesystem::path& strDest, bool fEnableCustom = true); bool AttemptBackupWallet(const CWallet& wallet, const boost::filesystem::path& pathSrc, const boost::filesystem::path& pathDest); diff --git a/src/zpiv/accumulatorcheckpoints.cpp b/src/zpiv/accumulatorcheckpoints.cpp index 3602e69e0a94..5202e9e57e57 100644 --- a/src/zpiv/accumulatorcheckpoints.cpp +++ b/src/zpiv/accumulatorcheckpoints.cpp @@ -58,7 +58,7 @@ namespace AccumulatorCheckpoints checkpoint.insert(std::make_pair(denom, bn)); } - mapCheckpoints.insert(make_pair(nHeight, checkpoint)); + mapCheckpoints.insert(std::make_pair(nHeight, checkpoint)); } return true; } diff --git a/src/zpiv/accumulatormap.cpp b/src/zpiv/accumulatormap.cpp index f07d97cd3e52..0d0137161fc9 100644 --- a/src/zpiv/accumulatormap.cpp +++ b/src/zpiv/accumulatormap.cpp @@ -8,16 +8,14 @@ #include "txdb.h" #include "libzerocoin/Denominations.h" -using namespace libzerocoin; -using namespace std; //Construct accumulators for all denominations AccumulatorMap::AccumulatorMap(libzerocoin::ZerocoinParams* params) { this->params = params; - for (auto& denom : zerocoinDenomList) { - unique_ptr uptr(new Accumulator(params, denom)); - mapAccumulators.insert(make_pair(denom, std::move(uptr))); + for (auto& denom : libzerocoin::zerocoinDenomList) { + std::unique_ptr uptr(new libzerocoin::Accumulator(params, denom)); + mapAccumulators.insert(std::make_pair(denom, std::move(uptr))); } } @@ -31,16 +29,16 @@ void AccumulatorMap::Reset(libzerocoin::ZerocoinParams* params2) { this->params = params2; mapAccumulators.clear(); - for (auto& denom : zerocoinDenomList) { - unique_ptr uptr(new Accumulator(params2, denom)); - mapAccumulators.insert(make_pair(denom, std::move(uptr))); + for (auto& denom : libzerocoin::zerocoinDenomList) { + std::unique_ptr uptr(new libzerocoin::Accumulator(params2, denom)); + mapAccumulators.insert(std::make_pair(denom, std::move(uptr))); } } //Load a checkpoint containing 8 32bit checksums of accumulator values. bool AccumulatorMap::Load(uint256 nCheckpoint) { - for (auto& denom : zerocoinDenomList) { + for (auto& denom : libzerocoin::zerocoinDenomList) { uint32_t nChecksum = ParseChecksum(nCheckpoint, denom); CBigNum bnValue; @@ -60,10 +58,10 @@ void AccumulatorMap::Load(const AccumulatorCheckpoints::Checkpoint& checkpoint) } //Add a zerocoin to the accumulator of its denomination. -bool AccumulatorMap::Accumulate(const PublicCoin& pubCoin, bool fSkipValidation) +bool AccumulatorMap::Accumulate(const libzerocoin::PublicCoin& pubCoin, bool fSkipValidation) { - CoinDenomination denom = pubCoin.getDenomination(); - if (denom == CoinDenomination::ZQ_ERROR) + libzerocoin::CoinDenomination denom = pubCoin.getDenomination(); + if (denom == libzerocoin::CoinDenomination::ZQ_ERROR) return false; if (fSkipValidation) @@ -79,9 +77,9 @@ libzerocoin::Accumulator AccumulatorMap::GetAccumulator(libzerocoin::CoinDenomin } //Get the value of a specific accumulator -CBigNum AccumulatorMap::GetValue(CoinDenomination denom) +CBigNum AccumulatorMap::GetValue(libzerocoin::CoinDenomination denom) { - if (denom == CoinDenomination::ZQ_ERROR) + if (denom == libzerocoin::CoinDenomination::ZQ_ERROR) return CBigNum(0); return mapAccumulators.at(denom)->getValue(); } @@ -92,8 +90,8 @@ uint256 AccumulatorMap::GetCheckpoint() uint256 nCheckpoint; //Prevent possible overflows from future changes to the list and forgetting to update this code - assert(zerocoinDenomList.size() == 8); - for (auto& denom : zerocoinDenomList) { + assert(libzerocoin::zerocoinDenomList.size() == 8); + for (auto& denom : libzerocoin::zerocoinDenomList) { CBigNum bnValue = mapAccumulators.at(denom)->getValue(); uint32_t nCheckSum = GetChecksum(bnValue); nCheckpoint = nCheckpoint << 32 | nCheckSum; diff --git a/src/zpiv/accumulators.cpp b/src/zpiv/accumulators.cpp index 629b58f27d1d..ca071fd63e82 100644 --- a/src/zpiv/accumulators.cpp +++ b/src/zpiv/accumulators.cpp @@ -13,17 +13,16 @@ #include "zpivchain.h" #include "tinyformat.h" -using namespace libzerocoin; std::map mapAccumulatorValues; std::list listAccCheckpointsNoDB; -uint32_t ParseChecksum(uint256 nChecksum, CoinDenomination denomination) +uint32_t ParseChecksum(uint256 nChecksum, libzerocoin::CoinDenomination denomination) { //shift to the beginning bit of this denomination and trim any remaining bits by returning 32 bits only - int pos = distance(zerocoinDenomList.begin(), find(zerocoinDenomList.begin(), zerocoinDenomList.end(), denomination)); - nChecksum = nChecksum >> (32*((zerocoinDenomList.size() - 1) - pos)); + int pos = distance(libzerocoin::zerocoinDenomList.begin(), find(libzerocoin::zerocoinDenomList.begin(), libzerocoin::zerocoinDenomList.end(), denomination)); + nChecksum = nChecksum >> (32*((libzerocoin::zerocoinDenomList.size() - 1) - pos)); return nChecksum.Get32(); } @@ -39,7 +38,7 @@ uint32_t GetChecksum(const CBigNum &bnValue) // Find the first occurance of a certain accumulator checksum. Return 0 if not found. -int GetChecksumHeight(uint32_t nChecksum, CoinDenomination denomination) +int GetChecksumHeight(uint32_t nChecksum, libzerocoin::CoinDenomination denomination) { CBlockIndex* pindex = chainActive[Params().Zerocoin_StartHeight()]; if (!pindex) @@ -83,7 +82,7 @@ bool GetAccumulatorValueFromChecksum(uint32_t nChecksum, bool fMemoryOnly, CBigN } -bool GetAccumulatorValueFromDB(uint256 nCheckpoint, CoinDenomination denom, CBigNum& bnAccValue) +bool GetAccumulatorValueFromDB(uint256 nCheckpoint, libzerocoin::CoinDenomination denom, CBigNum& bnAccValue) { uint32_t nChecksum = ParseChecksum(nCheckpoint, denom); return GetAccumulatorValueFromChecksum(nChecksum, false, bnAccValue); @@ -95,7 +94,7 @@ void AddAccumulatorChecksum(const uint32_t nChecksum, const CBigNum &bnValue) //Since accumulators are switching at v2, stop databasing v1 because its useless. Only focus on v2. if (chainActive.Height() >= Params().Zerocoin_Block_V2_Start()) { zerocoinDB->WriteAccumulatorValue(nChecksum, bnValue); - mapAccumulatorValues.insert(make_pair(nChecksum, bnValue)); + mapAccumulatorValues.insert(std::make_pair(nChecksum, bnValue)); } } @@ -103,7 +102,7 @@ void AddAccumulatorChecksum(const uint32_t nChecksum, const CBigNum &bnValue) void DatabaseChecksums(AccumulatorMap& mapAccumulators) { uint256 nCheckpoint = 0; - for (auto& denom : zerocoinDenomList) { + for (auto& denom : libzerocoin::zerocoinDenomList) { CBigNum bnValue = mapAccumulators.GetValue(denom); uint32_t nCheckSum = GetChecksum(bnValue); AddAccumulatorChecksum(nCheckSum, bnValue); @@ -121,7 +120,7 @@ bool EraseChecksum(uint32_t nChecksum) bool EraseAccumulatorValues(const uint256& nCheckpointErase, const uint256& nCheckpointPrevious) { - for (auto& denomination : zerocoinDenomList) { + for (auto& denomination : libzerocoin::zerocoinDenomList) { uint32_t nChecksumErase = ParseChecksum(nCheckpointErase, denomination); uint32_t nChecksumPrevious = ParseChecksum(nCheckpointPrevious, denomination); @@ -139,7 +138,7 @@ bool EraseAccumulatorValues(const uint256& nCheckpointErase, const uint256& nChe bool LoadAccumulatorValuesFromDB(const uint256 nCheckpoint) { - for (auto& denomination : zerocoinDenomList) { + for (auto& denomination : libzerocoin::zerocoinDenomList) { uint32_t nChecksum = ParseChecksum(nCheckpoint, denomination); //if read is not successful then we are not in a state to verify zerocoin transactions @@ -150,7 +149,7 @@ bool LoadAccumulatorValuesFromDB(const uint256 nCheckpoint) LogPrint("zero", "%s : Missing databased value for checksum %d\n", __func__, nChecksum); return false; } - mapAccumulatorValues.insert(make_pair(nChecksum, bnValue)); + mapAccumulatorValues.insert(std::make_pair(nChecksum, bnValue)); } return true; } @@ -162,22 +161,22 @@ bool EraseCheckpoints(int nStartHeight, int nEndHeight) if (chainActive.Height() < nStartHeight) return false; - nEndHeight = min(chainActive.Height(), nEndHeight); + nEndHeight = std::min(chainActive.Height(), nEndHeight); CBlockIndex* pindex = chainActive[nStartHeight]; uint256 nCheckpointPrev = pindex->pprev->nAccumulatorCheckpoint; //Keep a list of checkpoints from the previous block so that we don't delete them - list listCheckpointsPrev; - for (auto denom : zerocoinDenomList) + std::list listCheckpointsPrev; + for (auto denom : libzerocoin::zerocoinDenomList) listCheckpointsPrev.emplace_back(ParseChecksum(nCheckpointPrev, denom)); while (true) { uint256 nCheckpointDelete = pindex->nAccumulatorCheckpoint; - for (auto denom : zerocoinDenomList) { + for (auto denom : libzerocoin::zerocoinDenomList) { uint32_t nChecksumDelete = ParseChecksum(nCheckpointDelete, denom); - if (count(listCheckpointsPrev.begin(), listCheckpointsPrev.end(), nCheckpointDelete)) + if (std::count(listCheckpointsPrev.begin(), listCheckpointsPrev.end(), nCheckpointDelete)) continue; EraseChecksum(nChecksumDelete); } @@ -284,7 +283,7 @@ bool CalculateAccumulatorCheckpoint(int nHeight, uint256& nCheckpoint, Accumulat if(!ReadBlockFromDisk(block, pindex)) return error("%s: failed to read block from disk", __func__); - std::list listPubcoins; + std::list listPubcoins; if (!BlockToPubcoinList(block, listPubcoins, fFilterInvalid)) return error("%s: failed to get zerocoin mintlist from block %d", __func__, pindex->nHeight); @@ -292,7 +291,7 @@ bool CalculateAccumulatorCheckpoint(int nHeight, uint256& nCheckpoint, Accumulat LogPrint("zero", "%s found %d mints\n", __func__, listPubcoins.size()); //add the pubcoins to accumulator - for (const PublicCoin& pubcoin : listPubcoins) { + for (const libzerocoin::PublicCoin& pubcoin : listPubcoins) { if(!mapAccumulators.Accumulate(pubcoin, true)) return error("%s: failed to add pubcoin to accumulator at height %d", __func__, pindex->nHeight); } @@ -359,12 +358,12 @@ int ComputeAccumulatedCoins(int nHeightEnd, libzerocoin::CoinDenomination denom) } -list GetPubcoinFromBlock(const CBlockIndex* pindex){ +std::list GetPubcoinFromBlock(const CBlockIndex* pindex){ //grab mints from this block CBlock block; if(!ReadBlockFromDisk(block, pindex)) throw GetPubcoinException("GetPubcoinFromBlock: failed to read block from disk while adding pubcoins to witness"); - list listPubcoins; + std::list listPubcoins; if(!BlockToPubcoinList(block, listPubcoins, true)) throw GetPubcoinException("GetPubcoinFromBlock: failed to get zerocoin mintlist from block "+std::to_string(pindex->nHeight)+"\n"); return listPubcoins; @@ -372,14 +371,14 @@ list GetPubcoinFromBlock(const CBlockIndex* pindex){ -int AddBlockMintsToAccumulator(const CoinDenomination den, const CBloomFilter filter, const CBlockIndex* pindex, - libzerocoin::Accumulator* accumulator, bool isWitness, list& notAddedCoins) +int AddBlockMintsToAccumulator(const libzerocoin::CoinDenomination den, const CBloomFilter filter, const CBlockIndex* pindex, + libzerocoin::Accumulator* accumulator, bool isWitness, std::list& notAddedCoins) { // if this block contains mints of the denomination that is being spent, then add them to the witness int nMintsAdded = 0; if (pindex->MintedDenomination(den)) { //add the mints to the witness - for (const PublicCoin& pubcoin : GetPubcoinFromBlock(pindex)) { + for (const libzerocoin::PublicCoin& pubcoin : GetPubcoinFromBlock(pindex)) { if (pubcoin.getDenomination() != den) { continue; } @@ -404,7 +403,7 @@ int AddBlockMintsToAccumulator(const libzerocoin::PublicCoin& coin, const int nH int nMintsAdded = 0; if (pindex->MintedDenomination(coin.getDenomination())) { //add the mints to the witness - for (const PublicCoin& pubcoin : GetPubcoinFromBlock(pindex)) { + for (const libzerocoin::PublicCoin& pubcoin : GetPubcoinFromBlock(pindex)) { if (pubcoin.getDenomination() != coin.getDenomination()) continue; @@ -541,8 +540,8 @@ bool GenerateAccumulatorWitness(CoinWitnessData* coinWitness, AccumulatorMap& ma //If there is a Acc End height filled in, then this has already been partially accumulated. if (!coinWitness->nHeightAccEnd) { LogPrintf("RESET ACC\n"); - coinWitness->pAccumulator = std::unique_ptr(new Accumulator(Params().Zerocoin_Params(false), coinWitness->denom)); - coinWitness->pWitness = std::unique_ptr(new AccumulatorWitness(Params().Zerocoin_Params(false), *coinWitness->pAccumulator, *coinWitness->coin)); + coinWitness->pAccumulator = std::unique_ptr(new libzerocoin::Accumulator(Params().Zerocoin_Params(false), coinWitness->denom)); + coinWitness->pWitness = std::unique_ptr(new libzerocoin::AccumulatorWitness(Params().Zerocoin_Params(false), *coinWitness->pAccumulator, *coinWitness->coin)); } // Mint added height @@ -610,8 +609,8 @@ bool calculateAccumulatedBlocksFor( libzerocoin::CoinDenomination den, CBloomFilter filter, libzerocoin::Accumulator &witnessAccumulator, - list& ret, - string& strError + std::list& ret, + std::string& strError ){ bool fDoubleCounted = false; int nMintsAdded = 0; @@ -666,7 +665,7 @@ bool calculateAccumulatedBlocksFor( libzerocoin::Accumulator &accumulator, libzerocoin::Accumulator &witnessAccumulator, libzerocoin::PublicCoin coin, - string& strError + std::string& strError ){ int amountOfScannedBlocks = 0; @@ -717,16 +716,16 @@ bool calculateAccumulatedBlocksFor( bool CalculateAccumulatorWitnessFor( - const ZerocoinParams* params, + const libzerocoin::ZerocoinParams* params, int startHeight, int maxCalulationRange, - CoinDenomination den, + libzerocoin::CoinDenomination den, const CBloomFilter& filter, - Accumulator& accumulator, - AccumulatorWitness& witness, + libzerocoin::Accumulator& accumulator, + libzerocoin::AccumulatorWitness& witness, int& nMintsAdded, - string& strError, - list& ret, + std::string& strError, + std::list& ret, int &heightStop ){ // Lock @@ -734,9 +733,9 @@ bool CalculateAccumulatorWitnessFor( try { // Dummy coin init - PublicCoin temp(params, 0, den); + libzerocoin::PublicCoin temp(params, 0, den); // Dummy Acc init - Accumulator testingAcc(params, den); + libzerocoin::Accumulator testingAcc(params, den); //get the checkpoint added at the next multiple of 10 int nHeightCheckpoint = startHeight + (10 - (startHeight % 10)); @@ -798,11 +797,11 @@ bool CalculateAccumulatorWitnessFor( } bool GenerateAccumulatorWitness( - const PublicCoin &coin, - Accumulator& accumulator, - AccumulatorWitness& witness, + const libzerocoin::PublicCoin &coin, + libzerocoin::Accumulator& accumulator, + libzerocoin::AccumulatorWitness& witness, int& nMintsAdded, - string& strError, + std::string& strError, CBlockIndex* pindexCheckpoint) { try { @@ -888,11 +887,11 @@ bool GenerateAccumulatorWitness( -map GetMintMaturityHeight() +std::map GetMintMaturityHeight() { - map > mapDenomMaturity; + std::map > mapDenomMaturity; for (auto denom : libzerocoin::zerocoinDenomList) - mapDenomMaturity.insert(make_pair(denom, make_pair(0, 0))); + mapDenomMaturity.insert(std::make_pair(denom, std::make_pair(0, 0))); int nConfirmedHeight = chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations(); @@ -923,9 +922,9 @@ map GetMintMaturityHeight() } //Generate final map - map mapRet; + std::map mapRet; for (auto denom : libzerocoin::zerocoinDenomList) - mapRet.insert(make_pair(denom, mapDenomMaturity.at(denom).second)); + mapRet.insert(std::make_pair(denom, mapDenomMaturity.at(denom).second)); return mapRet; } diff --git a/src/zpiv/accumulators.h b/src/zpiv/accumulators.h index 4241a2d9ab1a..72265dfd6861 100644 --- a/src/zpiv/accumulators.h +++ b/src/zpiv/accumulators.h @@ -33,8 +33,8 @@ bool CalculateAccumulatorWitnessFor( libzerocoin::Accumulator& accumulator, libzerocoin::AccumulatorWitness& witness, int& nMintsAdded, - string& strError, - list& ret, + std::string& strError, + std::list& ret, int &heightStop ); @@ -43,12 +43,12 @@ bool GenerateAccumulatorWitness( libzerocoin::Accumulator& accumulator, libzerocoin::AccumulatorWitness& witness, int& nMintsAdded, - string& strError, + std::string& strError, CBlockIndex* pindexCheckpoint = nullptr); bool GenerateAccumulatorWitness(CoinWitnessData* coinWitness, AccumulatorMap& mapAccumulators, CBlockIndex* pindexCheckpoint); -list GetPubcoinFromBlock(const CBlockIndex* pindex); +std::list GetPubcoinFromBlock(const CBlockIndex* pindex); bool GetAccumulatorValueFromDB(uint256 nCheckpoint, libzerocoin::CoinDenomination denom, CBigNum& bnAccValue); bool GetAccumulatorValue(int& nHeight, const libzerocoin::CoinDenomination denom, CBigNum& bnAccValue); bool GetAccumulatorValueFromChecksum(uint32_t nChecksum, bool fMemoryOnly, CBigNum& bnAccValue); @@ -69,25 +69,25 @@ bool ValidateAccumulatorCheckpoint(const CBlock& block, CBlockIndex* pindex, Acc class NotEnoughMintsException : public std::exception { public: std::string message; - NotEnoughMintsException(const string &message) : message(message) {} + NotEnoughMintsException(const std::string &message) : message(message) {} }; class GetPubcoinException : public std::exception { public: std::string message; - GetPubcoinException(const string &message) : message(message) {} + GetPubcoinException(const std::string &message) : message(message) {} }; class ChecksumInDbNotFoundException : public std::exception { public: std::string message; - ChecksumInDbNotFoundException(const string &message) : message(message) {} + ChecksumInDbNotFoundException(const std::string &message) : message(message) {} }; class searchMintHeightException : public std::exception { public: std::string message; - searchMintHeightException(const string &message) : message(message) {} + searchMintHeightException(const std::string &message) : message(message) {} }; #endif //PIVX_ACCUMULATORS_H diff --git a/src/zpiv/deterministicmint.cpp b/src/zpiv/deterministicmint.cpp index 156947d79a3c..c2f0d2dfc44a 100644 --- a/src/zpiv/deterministicmint.cpp +++ b/src/zpiv/deterministicmint.cpp @@ -6,7 +6,6 @@ #include #include "deterministicmint.h" -using namespace libzerocoin; CDeterministicMint::CDeterministicMint() { @@ -26,7 +25,7 @@ CDeterministicMint::CDeterministicMint(uint8_t nVersion, const uint32_t& nCount, void CDeterministicMint::SetNull() { - nVersion = PrivateCoin::CURRENT_VERSION; + nVersion = libzerocoin::PrivateCoin::CURRENT_VERSION; nCount = 0; hashSeed = 0; hashSerial = 0; @@ -34,7 +33,7 @@ void CDeterministicMint::SetNull() hashPubcoin = 0; txid = 0; nHeight = 0; - denom = CoinDenomination::ZQ_ERROR; + denom = libzerocoin::CoinDenomination::ZQ_ERROR; isUsed = false; } diff --git a/src/zpiv/mintpool.cpp b/src/zpiv/mintpool.cpp index 0523cde17dda..565ebc343c82 100644 --- a/src/zpiv/mintpool.cpp +++ b/src/zpiv/mintpool.cpp @@ -5,7 +5,6 @@ #include "mintpool.h" #include "util.h" -using namespace std; CMintPool::CMintPool() { @@ -22,11 +21,11 @@ CMintPool::CMintPool(uint32_t nCount) void CMintPool::Add(const CBigNum& bnValue, const uint32_t& nCount) { uint256 hash = GetPubCoinHash(bnValue); - Add(make_pair(hash, nCount)); + Add(std::make_pair(hash, nCount)); LogPrintf("%s : add %s to mint pool, nCountLastGenerated=%d\n", __func__, bnValue.GetHex().substr(0, 6), nCountLastGenerated); } -void CMintPool::Add(const pair& pMint, bool fVerbose) +void CMintPool::Add(const std::pair& pMint, bool fVerbose) { insert(pMint); if (pMint.second > nCountLastGenerated) @@ -47,14 +46,14 @@ std::pair CMintPool::Get(const CBigNum& bnValue) return *it; } -bool SortSmallest(const pair& a, const pair& b) +bool SortSmallest(const std::pair& a, const std::pair& b) { return a.second < b.second; } -std::list > CMintPool::List() +std::list > CMintPool::List() { - list > listMints; + std::list > listMints; for (auto pMint : *(this)) { listMints.emplace_back(pMint); } @@ -79,7 +78,7 @@ bool CMintPool::Front(std::pair& pMint) return true; } -bool CMintPool::Next(pair& pMint) +bool CMintPool::Next(std::pair& pMint) { auto it = find(pMint.first); if (it == end() || ++it == end()) diff --git a/src/zpiv/zpivtracker.cpp b/src/zpiv/zpivtracker.cpp index 4843987e253d..84e036eb12a6 100644 --- a/src/zpiv/zpivtracker.cpp +++ b/src/zpiv/zpivtracker.cpp @@ -13,7 +13,6 @@ #include "zpiv/zpivwallet.h" #include "witness.h" -using namespace std; CzPIVTracker::CzPIVTracker(std::string strWalletFile) { @@ -136,7 +135,7 @@ bool CzPIVTracker::ClearSpendCache() std::vector CzPIVTracker::GetSerialHashes() { - vector vHashes; + std::vector vHashes; for (auto it : mapSerialHashes) { if (it.second.isArchived) continue; @@ -154,7 +153,7 @@ CAmount CzPIVTracker::GetBalance(bool fConfirmedOnly, bool fUnconfirmedOnly) con //! zerocoin specific fields std::map myZerocoinSupply; for (auto& denom : libzerocoin::zerocoinDenomList) { - myZerocoinSupply.insert(make_pair(denom, 0)); + myZerocoinSupply.insert(std::make_pair(denom, 0)); } { @@ -187,7 +186,7 @@ CAmount CzPIVTracker::GetUnconfirmedBalance() const std::vector CzPIVTracker::GetMints(bool fConfirmedOnly) const { - vector vMints; + std::vector vMints; for (auto& it : mapSerialHashes) { CMintMeta mint = it.second; if (mint.isArchived || mint.isUsed) @@ -353,7 +352,7 @@ void CzPIVTracker::SetPubcoinUsed(const uint256& hashPubcoin, const uint256& txi return; CMintMeta meta = GetMetaFromPubcoin(hashPubcoin); meta.isUsed = true; - mapPendingSpends.insert(make_pair(meta.hashSerial, txid)); + mapPendingSpends.insert(std::make_pair(meta.hashSerial, txid)); UpdateState(meta); } diff --git a/src/zpiv/zpivwallet.cpp b/src/zpiv/zpivwallet.cpp index 68ee8862e0c2..863a833bc142 100644 --- a/src/zpiv/zpivwallet.cpp +++ b/src/zpiv/zpivwallet.cpp @@ -11,7 +11,6 @@ #include "deterministicmint.h" #include "zpivchain.h" -using namespace libzerocoin; CzPIVWallet::CzPIVWallet(std::string strWalletFile) { @@ -157,7 +156,7 @@ void CzPIVWallet::GenerateMintPool(uint32_t nCountStart, uint32_t nCountEnd) // pubcoin hashes are stored to db so that a full accounting of mints belonging to the seed can be tracked without regenerating bool CzPIVWallet::LoadMintPoolFromDB() { - map > > mapMintPool = CWalletDB(strWalletFile).MapMintPool(); + std::map > > mapMintPool = CWalletDB(strWalletFile).MapMintPool(); uint256 hashSeed = Hash(seedMaster.begin(), seedMaster.end()); for (auto& pair : mapMintPool[hashSeed]) @@ -185,7 +184,7 @@ void CzPIVWallet::SyncWithChain(bool fGenerateMintPool) bool found = true; CWalletDB walletdb(strWalletFile); - set setAddedTx; + std::set setAddedTx; while (found) { found = false; if (fGenerateMintPool) @@ -193,8 +192,8 @@ void CzPIVWallet::SyncWithChain(bool fGenerateMintPool) LogPrintf("%s: Mintpool size=%d\n", __func__, mintPool.size()); std::set setChecked; - list > listMints = mintPool.List(); - for (pair pMint : listMints) { + std::list > listMints = mintPool.List(); + for (std::pair pMint : listMints) { LOCK(cs_main); if (setChecked.count(pMint.first)) return; @@ -225,14 +224,14 @@ void CzPIVWallet::SyncWithChain(bool fGenerateMintPool) } //Find the denomination - CoinDenomination denomination = CoinDenomination::ZQ_ERROR; + libzerocoin::CoinDenomination denomination = libzerocoin::CoinDenomination::ZQ_ERROR; bool fFoundMint = false; CBigNum bnValue = 0; for (const CTxOut& out : tx.vout) { if (!out.IsZerocoinMint()) continue; - PublicCoin pubcoin(Params().Zerocoin_Params(false)); + libzerocoin::PublicCoin pubcoin(Params().Zerocoin_Params(false)); CValidationState state; if (!TxOutToPublicCoin(out, pubcoin, state)) { LogPrintf("%s : failed to get mint from txout for %s!\n", __func__, pMint.first.GetHex()); @@ -249,7 +248,7 @@ void CzPIVWallet::SyncWithChain(bool fGenerateMintPool) } } - if (!fFoundMint || denomination == ZQ_ERROR) { + if (!fFoundMint || denomination == libzerocoin::ZQ_ERROR) { LogPrintf("%s : failed to get mint %s from tx %s!\n", __func__, pMint.first.GetHex(), tx.GetHash().GetHex()); found = false; break; @@ -280,11 +279,11 @@ void CzPIVWallet::SyncWithChain(bool fGenerateMintPool) } } -bool CzPIVWallet::SetMintSeen(const CBigNum& bnValue, const int& nHeight, const uint256& txid, const CoinDenomination& denom) +bool CzPIVWallet::SetMintSeen(const CBigNum& bnValue, const int& nHeight, const uint256& txid, const libzerocoin::CoinDenomination& denom) { if (!mintPool.Has(bnValue)) return error("%s: value not in pool", __func__); - pair pMint = mintPool.Get(bnValue); + std::pair pMint = mintPool.Get(bnValue); // Regenerate the mint uint512 seedZerocoin = GetZerocoinSeed(pMint.second); @@ -304,7 +303,7 @@ bool CzPIVWallet::SetMintSeen(const CBigNum& bnValue, const int& nHeight, const uint256 hashPubcoin = GetPubCoinHash(bnValue); uint256 nSerial = bnSerial.getuint256(); uint256 hashStake = Hash(nSerial.begin(), nSerial.end()); - CDeterministicMint dMint(PrivateCoin::CURRENT_VERSION, pMint.second, hashSeed, hashSerial, hashPubcoin, hashStake); + CDeterministicMint dMint(libzerocoin::PrivateCoin::CURRENT_VERSION, pMint.second, hashSeed, hashSerial, hashPubcoin, hashStake); dMint.SetDenomination(denom); dMint.SetHeight(nHeight); dMint.SetTxHash(txid); @@ -352,7 +351,7 @@ bool IsValidCoinValue(const CBigNum& bnValue) void CzPIVWallet::SeedToZPIV(const uint512& seedZerocoin, CBigNum& bnValue, CBigNum& bnSerial, CBigNum& bnRandomness, CKey& key) { - ZerocoinParams* params = Params().Zerocoin_Params(false); + libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); //convert state seed into a seed for the private key uint256 nSeedPrivKey = seedZerocoin.trim256(); @@ -414,7 +413,7 @@ void CzPIVWallet::UpdateCount() walletdb.WriteZPIVCount(nCountLastUsed); } -void CzPIVWallet::GenerateDeterministicZPIV(CoinDenomination denom, PrivateCoin& coin, CDeterministicMint& dMint, bool fGenerateOnly) +void CzPIVWallet::GenerateDeterministicZPIV(libzerocoin::CoinDenomination denom, libzerocoin::PrivateCoin& coin, CDeterministicMint& dMint, bool fGenerateOnly) { GenerateMint(nCountLastUsed + 1, denom, coin, dMint); if (fGenerateOnly) @@ -424,7 +423,7 @@ void CzPIVWallet::GenerateDeterministicZPIV(CoinDenomination denom, PrivateCoin& //LogPrintf("%s : Generated new deterministic mint. Count=%d pubcoin=%s seed=%s\n", __func__, nCount, coin.getPublicCoin().getValue().GetHex().substr(0,6), seedZerocoin.GetHex().substr(0, 4)); } -void CzPIVWallet::GenerateMint(const uint32_t& nCount, const CoinDenomination denom, PrivateCoin& coin, CDeterministicMint& dMint) +void CzPIVWallet::GenerateMint(const uint32_t& nCount, const libzerocoin::CoinDenomination denom, libzerocoin::PrivateCoin& coin, CDeterministicMint& dMint) { uint512 seedZerocoin = GetZerocoinSeed(nCount); CBigNum bnValue; @@ -432,9 +431,9 @@ void CzPIVWallet::GenerateMint(const uint32_t& nCount, const CoinDenomination de CBigNum bnRandomness; CKey key; SeedToZPIV(seedZerocoin, bnValue, bnSerial, bnRandomness, key); - coin = PrivateCoin(Params().Zerocoin_Params(false), denom, bnSerial, bnRandomness); + coin = libzerocoin::PrivateCoin(Params().Zerocoin_Params(false), denom, bnSerial, bnRandomness); coin.setPrivKey(key.GetPrivKey()); - coin.setVersion(PrivateCoin::CURRENT_VERSION); + coin.setVersion(libzerocoin::PrivateCoin::CURRENT_VERSION); uint256 hashSeed = Hash(seedMaster.begin(), seedMaster.end()); uint256 hashSerial = GetSerialHash(bnSerial); @@ -460,7 +459,7 @@ bool CzPIVWallet::RegenerateMint(const CDeterministicMint& dMint, CZerocoinMint& } //Generate the coin - PrivateCoin coin(Params().Zerocoin_Params(false), dMint.GetDenomination(), false); + libzerocoin::PrivateCoin coin(Params().Zerocoin_Params(false), dMint.GetDenomination(), false); CDeterministicMint dMintDummy; GenerateMint(dMint.GetCount(), dMint.GetDenomination(), coin, dMintDummy); diff --git a/src/zpivchain.cpp b/src/zpivchain.cpp index 465fd1871068..31111d5aeeca 100644 --- a/src/zpivchain.cpp +++ b/src/zpivchain.cpp @@ -14,7 +14,7 @@ // For Script size (BIGNUM/Uint256 size) #define BIGNUM_SIZE 4 -bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, vector& vValues) +bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, std::vector& vValues) { for (const CTransaction& tx : block.vtx) { if(!tx.HasZerocoinMintOutputs()) @@ -296,10 +296,10 @@ std::string ReindexZerocoinDB() if (!ZPIVModule::ParseZerocoinPublicSpend(in, tx, state, publicSpend)){ return _("Failed to parse public spend"); } - vSpendInfo.push_back(make_pair(publicSpend, txid)); + vSpendInfo.push_back(std::make_pair(publicSpend, txid)); } else { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(in); - vSpendInfo.push_back(make_pair(spend, txid)); + vSpendInfo.push_back(std::make_pair(spend, txid)); } } } @@ -313,7 +313,7 @@ std::string ReindexZerocoinDB() CValidationState state; libzerocoin::PublicCoin coin(Params().Zerocoin_Params(pindex->nHeight < Params().Zerocoin_Block_V2_Start())); TxOutToPublicCoin(out, coin, state); - vMintInfo.push_back(make_pair(coin, txid)); + vMintInfo.push_back(std::make_pair(coin, txid)); } } } @@ -362,7 +362,7 @@ libzerocoin::CoinSpend TxInToZerocoinSpend(const CTxIn& txin) bool TxOutToPublicCoin(const CTxOut& txout, libzerocoin::PublicCoin& pubCoin, CValidationState& state) { CBigNum publicZerocoin; - vector vchZeroMint; + std::vector vchZeroMint; vchZeroMint.insert(vchZeroMint.end(), txout.scriptPubKey.begin() + SCRIPT_OFFSET, txout.scriptPubKey.begin() + txout.scriptPubKey.size()); publicZerocoin.setvch(vchZeroMint);