Removed global namespace declarations; fixed compiler warnings

This commit is contained in:
sjn 2022-01-29 18:41:57 -08:00
parent d30f107736
commit dc9d6ec533
83 changed files with 1626 additions and 1545 deletions

View File

@ -4,7 +4,10 @@
#include "addrman.h"
using namespace std;
#include <algorithm>
#include <map>
#include <set>
#include <vector>
int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
{
@ -324,7 +327,7 @@ bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePen
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
pinfo->nTime = std::max((int64)0, addr.nTime - nTimePenalty);
// add services
pinfo->nServices |= addr.nServices;
@ -349,7 +352,7 @@ bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePen
return false;
} else {
pinfo = Create(addr, source, &nId);
pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
pinfo->nTime = std::max((int64)0, (int64)pinfo->nTime - nTimePenalty);
// printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
nNew++;
fNew = true;

View File

@ -11,9 +11,10 @@
#include "sync.h"
#include "ui_interface.h"
using namespace std;
#include <map>
#include <utility>
map<uint256, CAlert> mapAlerts;
std::map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
static const char* pszMainKey = "043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195";
@ -51,8 +52,8 @@ std::string CUnsignedAlert::ToString() const
return strprintf(
"CAlert(\n"
" nVersion = %d\n"
" nRelayUntil = %"PRI64d"\n"
" nExpiration = %"PRI64d"\n"
" nRelayUntil = %" PRI64d "\n"
" nExpiration = %" PRI64d "\n"
" nID = %d\n"
" nCancel = %d\n"
" setCancel = %s\n"
@ -161,7 +162,7 @@ CAlert CAlert::getAlertByHash(const uint256 &hash)
CAlert retval;
{
LOCK(cs_mapAlerts);
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
std::map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
if(mi != mapAlerts.end())
retval = mi->second;
}
@ -200,7 +201,7 @@ bool CAlert::ProcessAlert()
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
for (std::map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
@ -231,7 +232,7 @@ bool CAlert::ProcessAlert()
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
mapAlerts.insert(std::make_pair(GetHash(), *this));
// Notify UI if it applies to me
if(AppliesToMe())
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);

View File

@ -5,7 +5,7 @@
#ifndef curecoin_ALLOCATORS_H
#define curecoin_ALLOCATORS_H
#include <string.h>
#include <cstring>
#include <string>
#include <boost/thread/mutex.hpp>
#include <map>
@ -212,7 +212,7 @@ struct secure_allocator : public std::allocator<T>
{
if (p != NULL)
{
memset(p, 0, sizeof(T) * n);
std::memset(p, 0, sizeof(T) * n);
LockedPageManager::instance.UnlockRange(p, sizeof(T) * n);
}
std::allocator<T>::deallocate(p, n);
@ -246,7 +246,7 @@ struct zero_after_free_allocator : public std::allocator<T>
void deallocate(T* p, std::size_t n)
{
if (p != NULL)
memset(p, 0, sizeof(T) * n);
std::memset(p, 0, sizeof(T) * n);
std::allocator<T>::deallocate(p, n);
}
};

View File

@ -15,6 +15,7 @@
#ifndef curecoin_BASE58_H
#define curecoin_BASE58_H
#include <cstring>
#include <string>
#include <vector>
#include "bignum.h"
@ -150,7 +151,7 @@ inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRe
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
if (std::memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
@ -190,7 +191,7 @@ protected:
{
// zero the memory, as it may contain sensitive data
if (!vchData.empty())
memset(&vchData[0], 0, vchData.size());
std::memset(&vchData[0], 0, vchData.size());
}
void SetData(int nVersionIn, const void* pdata, size_t nSize)
@ -198,7 +199,7 @@ protected:
nVersion = nVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
std::memcpy(&vchData[0], pdata, nSize);
}
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
@ -220,8 +221,8 @@ public:
nVersion = vchTemp[0];
vchData.resize(vchTemp.size() - 1);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[1], vchData.size());
memset(&vchTemp[0], 0, vchTemp.size());
std::memcpy(&vchData[0], &vchTemp[1], vchData.size());
std::memset(&vchTemp[0], 0, vchTemp.size());
return true;
}
@ -353,13 +354,13 @@ public:
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
std::memcpy(&id, &vchData[0], 20);
return CKeyID(id);
}
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
std::memcpy(&id, &vchData[0], 20);
return CScriptID(id);
}
}
@ -373,7 +374,7 @@ public:
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
std::memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
@ -414,7 +415,7 @@ public:
{
CSecret vchSecret;
vchSecret.resize(32);
memcpy(&vchSecret[0], &vchData[0], 32);
std::memcpy(&vchSecret[0], &vchData[0], 32);
fCompressedOut = vchData.size() == 33;
return vchSecret;
}

View File

@ -5,6 +5,7 @@
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <vector>
#include <cstring>
#include <string>
#ifdef WIN32
#include <windows.h>
@ -24,8 +25,8 @@ bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::v
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
memset(&chKey, 0, sizeof chKey);
memset(&chIV, 0, sizeof chIV);
std::memset(&chKey, 0, sizeof chKey);
std::memset(&chIV, 0, sizeof chIV);
return false;
}
@ -38,8 +39,8 @@ bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigne
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
std::memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
std::memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
@ -104,7 +105,7 @@ bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, con
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
std::memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext);
@ -114,7 +115,7 @@ bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
std::memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));

View File

@ -8,6 +8,8 @@
#include "key.h"
#include "serialize.h"
#include <cstring>
const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
@ -76,8 +78,8 @@ public:
void CleanKey()
{
memset(&chKey, 0, sizeof chKey);
memset(&chIV, 0, sizeof chIV);
std::memset(&chKey, 0, sizeof chKey);
std::memset(&chIV, 0, sizeof chIV);
fKeySet = false;
}

View File

@ -24,21 +24,22 @@
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
const Object emptyobj;
void ThreadRPCServer3(void* parg);
static inline unsigned short GetDefaultRPCPort()
@ -46,55 +47,55 @@ static inline unsigned short GetDefaultRPCPort()
return GetBoolArg("-testnet", false) ? DEF_TESTNET_RPCPORT : DEF_RPCPORT;
}
Object JSONRPCError(int code, const string& message)
json_spirit::Object JSONRPCError(int code, const std::string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
json_spirit::Object error;
error.push_back(json_spirit::Pair("code", code));
error.push_back(json_spirit::Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
void RPCTypeCheck(const json_spirit::Array& params,
const std::list<json_spirit::Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
BOOST_FOREACH(json_spirit::Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
const json_spirit::Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == json_spirit::null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
std::string err = strprintf("Expected type %s, got %s",
json_spirit::Value_type_name[t], json_spirit::Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
void RPCTypeCheck(const json_spirit::Object& o,
const std::map<std::string, json_spirit::Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
BOOST_FOREACH(const PAIRTYPE(std::string, json_spirit::Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
const json_spirit::Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == json_spirit::null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
if (!((v.type() == t.second) || (fAllowNull && (v.type() == json_spirit::null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
std::string err = strprintf("Expected type %s for %s, got %s",
json_spirit::Value_type_name[t.second], t.first.c_str(), json_spirit::Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
int64 AmountFromValue(const json_spirit::Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
@ -105,7 +106,7 @@ int64 AmountFromValue(const Value& value)
return nAmount;
}
Value ValueFromAmount(int64 amount)
json_spirit::Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
@ -126,22 +127,22 @@ std::string HexBits(unsigned int nBits)
/// 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;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
std::string strRet;
std::set<rpcfn_type> setDone;
for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
std::string strMethod = mi->first;
// 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 != "" && strMethod != strCommand)
continue;
try
{
Array params;
json_spirit::Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
@ -149,9 +150,9 @@ string CRPCTable::help(string strCommand) const
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'));
strRet += strHelp + "\n";
}
@ -162,14 +163,14 @@ string CRPCTable::help(string strCommand) const
return strRet;
}
Value help(const Array& params, bool fHelp)
json_spirit::Value help(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
throw std::runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
std::string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
@ -177,10 +178,10 @@ Value help(const Array& params, bool fHelp)
}
Value stop(const Array& params, bool fHelp)
json_spirit::Value stop(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
throw std::runtime_error(
"stop <detach>\n"
"<detach> is true or false to detach the database or not for this stop only\n"
"Stop curecoin server (and possibly override the detachdb config value).");
@ -282,9 +283,9 @@ CRPCTable::CRPCTable()
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
const CRPCCommand *CRPCTable::operator[](std::string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
@ -297,9 +298,9 @@ const CRPCCommand *CRPCTable::operator[](string name) const
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
std::string HTTPPost(const std::string& strMsg, const std::map<std::string,std::string>& mapRequestHeaders)
{
ostringstream s;
std::ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: curecoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
@ -307,27 +308,27 @@ string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeader
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
std::string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
std::string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
return std::string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
static std::string HTTPReply(int nStatus, const std::string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
@ -357,7 +358,7 @@ static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Length: %" PRIszu "\r\n"
"Content-Type: application/json\r\n"
"Server: curecoin-json-rpc/%s\r\n"
"\r\n"
@ -373,9 +374,9 @@ static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
std::string str;
getline(stream, str);
vector<string> vWords;
std::vector<std::string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
@ -386,22 +387,22 @@ int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
int ReadHTTPHeader(std::basic_istream<char>& stream, std::map<std::string, std::string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
std::string::size_type nColon = str.find(":");
if (nColon != std::string::npos)
{
string strHeader = str.substr(0, nColon);
std::string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
std::string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
@ -411,7 +412,7 @@ int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHea
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
int ReadHTTP(std::basic_istream<char>& stream, std::map<std::string, std::string>& mapHeadersRet, std::string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
@ -428,12 +429,12 @@ int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRe
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
std::vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
strMessageRet = std::string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
std::string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
@ -446,13 +447,13 @@ int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRe
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
bool HTTPAuthorized(std::map<std::string, std::string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
std::string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
std::string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
std::string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
@ -466,41 +467,41 @@ bool HTTPAuthorized(map<string, string>& mapHeaders)
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
std::string JSONRPCRequest(const std::string& strMethod, const json_spirit::Array& params, const json_spirit::Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
json_spirit::Object request;
request.push_back(json_spirit::Pair("method", strMethod));
request.push_back(json_spirit::Pair("params", params));
request.push_back(json_spirit::Pair("id", id));
return write_string(json_spirit::Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
json_spirit::Object JSONRPCReplyObj(const json_spirit::Value& result, const json_spirit::Value& error, const json_spirit::Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
json_spirit::Object reply;
if (error.type() != json_spirit::null_type)
reply.push_back(json_spirit::Pair("result", json_spirit::Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
reply.push_back(json_spirit::Pair("result", result));
reply.push_back(json_spirit::Pair("error", error));
reply.push_back(json_spirit::Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
std::string JSONRPCReply(const json_spirit::Value& result, const json_spirit::Value& error, const json_spirit::Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
json_spirit::Object reply = JSONRPCReplyObj(result, error, id);
return write_string(json_spirit::Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
void ErrorReply(std::ostream& stream, const json_spirit::Object& objError, const json_spirit::Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
std::string strReply = JSONRPCReply(json_spirit::Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
@ -512,16 +513,16 @@ bool ClientAllowed(const boost::asio::ip::address& address)
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
if (address == boost::asio::ip::address_v4::loopback()
|| address == boost::asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
const std::string strAddress = address.to_string();
const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(std::string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
@ -531,15 +532,15 @@ bool ClientAllowed(const boost::asio::ip::address& address)
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
class SSLIOStreamDevice : public boost::iostreams::device<boost::iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
SSLIOStreamDevice(boost::asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
void handshake(boost::asio::ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
@ -547,23 +548,23 @@ public:
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
handshake(boost::asio::ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(boost::asio::buffer(s, n));
return stream.next_layer().read_some(boost::asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
handshake(boost::asio::ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return boost::asio::write(stream, boost::asio::buffer(s, n));
return boost::asio::write(stream.next_layer(), boost::asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(GetIOService(stream));
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
boost::asio::ip::tcp::resolver resolver(GetIOService(stream));
boost::asio::ip::tcp::resolver::query query(server.c_str(), port.c_str());
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end;
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
@ -577,7 +578,7 @@ public:
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
boost::asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
@ -595,8 +596,8 @@ class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
boost::asio::io_service& io_service,
boost::asio::ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
@ -620,11 +621,11 @@ public:
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
boost::asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
boost::iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
@ -650,8 +651,8 @@ void ThreadRPCServer(void* parg)
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
static void RPCAcceptHandler(boost::shared_ptr< boost::asio::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
boost::asio::ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
@ -660,8 +661,8 @@ static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol,
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
static void RPCListen(boost::shared_ptr< boost::asio::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
boost::asio::ssl::context& context,
const bool fUseSSL)
{
// Accept connection
@ -682,8 +683,8 @@ static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketA
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
static void RPCAcceptHandler(boost::shared_ptr< boost::asio::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
boost::asio::ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
@ -691,11 +692,11 @@ static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol,
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted
if (error != boost::asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
AcceptedConnectionImpl<boost::asio::ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<boost::asio::ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
@ -733,7 +734,7 @@ void ThreadRPCServer2(void* parg)
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use curecoind";
std::string strWhatAmI = "To use curecoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
@ -755,12 +756,12 @@ void ThreadRPCServer2(void* parg)
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
boost::asio::io_service io_service;
ssl::context context(ssl::context::sslv23);
boost::asio::ssl::context context(boost::asio::ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
context.set_options(boost::asio::ssl::context::no_sslv2);
boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile;
@ -769,19 +770,19 @@ void ThreadRPCServer2(void* parg)
boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile;
if (boost::filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
if (boost::filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), boost::asio::ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
std::string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.native_handle(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::asio::ip::address bindAddress = loopback ? boost::asio::ip::address_v6::loopback() : boost::asio::ip::address_v6::any();
boost::asio::ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
boost::shared_ptr<boost::asio::ip::tcp::acceptor> acceptor(new boost::asio::ip::tcp::acceptor(io_service));
boost::signals2::signal<void ()> StopRequests;
@ -796,12 +797,12 @@ void ThreadRPCServer2(void* parg)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
acceptor->listen(boost::asio::socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
StopRequests.connect(boost::signals2::slot<void ()>(
static_cast<void (boost::asio::ip::tcp::acceptor::*)()>(&boost::asio::ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
@ -815,19 +816,19 @@ void ThreadRPCServer2(void* parg)
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
bindAddress = loopback ? boost::asio::ip::address_v4::loopback() : boost::asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor.reset(new boost::asio::ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
acceptor->listen(boost::asio::socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
StopRequests.connect(boost::signals2::slot<void ()>(
static_cast<void (boost::asio::ip::tcp::acceptor::*)()>(&boost::asio::ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
@ -854,75 +855,75 @@ void ThreadRPCServer2(void* parg)
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
json_spirit::Value id;
std::string strMethod;
json_spirit::Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
JSONRequest() { id = json_spirit::Value::null; }
void parse(const json_spirit::Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
void JSONRequest::parse(const json_spirit::Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
if (valRequest.type() != json_spirit::obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
const json_spirit::Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
json_spirit::Value valMethod = find_value(request, "method");
if (valMethod.type() == json_spirit::null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
if (valMethod.type() != json_spirit::str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
json_spirit::Value valParams = find_value(request, "params");
if (valParams.type() == json_spirit::array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else if (valParams.type() == json_spirit::null_type)
params = json_spirit::Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
static json_spirit::Object JSONRPCExecOne(const json_spirit::Value& req)
{
Object rpc_result;
json_spirit::Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
json_spirit::Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, json_spirit::Value::null, jreq.id);
}
catch (Object& objError)
catch (json_spirit::Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
rpc_result = JSONRPCReplyObj(json_spirit::Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
rpc_result = JSONRPCReplyObj(json_spirit::Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
static std::string JSONRPCExecBatch(const json_spirit::Array& vReq)
{
Array ret;
json_spirit::Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
return write_string(json_spirit::Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
@ -950,8 +951,8 @@ void ThreadRPCServer3(void* parg)
}
return;
}
map<string, string> mapHeaders;
string strRequest;
std::map<std::string, std::string> mapHeaders;
std::string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
@ -980,30 +981,30 @@ void ThreadRPCServer3(void* parg)
try
{
// Parse request
Value valRequest;
json_spirit::Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
std::string strReply;
// singleton request
if (valRequest.type() == obj_type) {
if (valRequest.type() == json_spirit::obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
json_spirit::Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
strReply = JSONRPCReply(result, json_spirit::Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
} else if (valRequest.type() == json_spirit::array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
catch (json_spirit::Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
@ -1030,15 +1031,15 @@ json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_s
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
std::string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
json_spirit::Value result;
{
if (pcmd->unlocked)
result = pcmd->actor(params, false);
@ -1056,53 +1057,53 @@ json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_s
}
Object CallRPC(const string& strMethod, const Array& params)
json_spirit::Object CallRPC(const std::string& strMethod, const json_spirit::Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
throw std::runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
boost::asio::io_service io_service;
boost::asio::ssl::context context(boost::asio::ssl::context::sslv23);
context.set_options(boost::asio::ssl::context::no_sslv2);
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<boost::asio::ip::tcp> d(sslStream, fUseSSL);
boost::iostreams::stream< SSLIOStreamDevice<boost::asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
throw std::runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
std::string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
std::map<std::string, std::string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = std::string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
std::string strRequest = JSONRPCRequest(strMethod, params, 1);
std::string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
std::map<std::string, std::string> mapHeaders;
std::string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
throw std::runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
throw std::runtime_error("no response from server");
// Parse reply
Value valReply;
json_spirit::Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
throw std::runtime_error("couldn't parse reply from server");
const json_spirit::Object& 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;
}
@ -1111,17 +1112,17 @@ Object CallRPC(const string& strMethod, const Array& params)
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
void ConvertTo(json_spirit::Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
if (fAllowNull && value.type() == json_spirit::null_type)
return;
if (value.type() == str_type)
if (value.type() == json_spirit::str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
json_spirit::Value value2;
std::string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
throw std::runtime_error(std::string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
@ -1132,9 +1133,9 @@ void ConvertTo(Value& value, bool fAllowNull=false)
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
json_spirit::Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
json_spirit::Array params;
BOOST_FOREACH(const std::string &param, strParams)
params.push_back(param);
@ -1169,29 +1170,29 @@ Array RPCConvertValues(const std::string &strMethod, const std::vector<std::stri
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<json_spirit::Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<json_spirit::Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<json_spirit::Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "listunspent" && n > 2) ConvertTo<json_spirit::Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<json_spirit::Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<json_spirit::Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<json_spirit::Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<json_spirit::Array>(params[2], true);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
std::string strPrint;
int nRet = 0;
try
{
@ -1204,21 +1205,21 @@ 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<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
json_spirit::Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
json_spirit::Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
const json_spirit::Value& result = find_value(reply, "result");
const json_spirit::Value& error = find_value(reply, "error");
if (error.type() != null_type)
if (error.type() != json_spirit::null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
@ -1228,9 +1229,9 @@ int CommandLineRPC(int argc, char *argv[])
else
{
// Result
if (result.type() == null_type)
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == str_type)
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
@ -1238,7 +1239,7 @@ int CommandLineRPC(int argc, char *argv[])
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
strPrint = std::string("error: ") + e.what();
nRet = 87;
}
catch (...)
@ -1270,7 +1271,7 @@ int main(int argc, char *argv[])
try
{
if (argc >= 2 && string(argv[1]) == "-server")
if (argc >= 2 && std::string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);

View File

@ -13,14 +13,17 @@
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#ifndef WIN32
#include "sys/stat.h"
#endif
using namespace std;
using namespace boost;
unsigned int nWalletDBUpdated;
@ -112,10 +115,10 @@ bool CDBEnv::Open(boost::filesystem::path pathEnv_)
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw runtime_error("CDBEnv::MakeMock(): already initialized");
throw std::runtime_error("CDBEnv::MakeMock(): already initialized");
if (fShutdown)
throw runtime_error("CDBEnv::MakeMock(): during shutdown");
throw std::runtime_error("CDBEnv::MakeMock(): during shutdown");
printf("CDBEnv::MakeMock()\n");
@ -136,7 +139,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;
@ -168,7 +171,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
u_int32_t flags = DB_SALVAGE;
if (fAggressive) flags |= DB_AGGRESSIVE;
stringstream strDump;
std::stringstream strDump;
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
@ -186,7 +189,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
// ... repeated
// DATA=END
string strLine;
std::string strLine;
while (!strDump.eof() && strLine != "HEADER=END")
getline(strDump, strLine); // Skip past header
@ -197,7 +200,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
if (keyHex != "DATA_END")
{
getline(strDump, valueHex);
vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
vResult.push_back(std::make_pair(ParseHex(keyHex),ParseHex(valueHex)));
}
}
@ -230,7 +233,7 @@ CDB::CDB(const char *pszFile, const char* pszMode) :
{
LOCK(bitdb.cs_db);
if (!bitdb.Open(GetDataDir()))
throw runtime_error("env open failed");
throw std::runtime_error("env open failed");
strFile = pszFile;
++bitdb.mapFileUseCount[strFile];
@ -245,7 +248,7 @@ CDB::CDB(const char *pszFile, const char* pszMode) :
DbMpoolFile*mpf = pdb->get_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", pszFile));
throw std::runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
}
ret = pdb->open(NULL, // Txn pointer
@ -261,10 +264,10 @@ CDB::CDB(const char *pszFile, const char* pszMode) :
pdb = NULL;
--bitdb.mapFileUseCount[strFile];
strFile = "";
throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
throw std::runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
}
if (fCreate && !Exists(string("version")))
if (fCreate && !Exists(std::string("version")))
{
bool fTmp = fReadOnly;
fReadOnly = false;
@ -311,7 +314,7 @@ void CDB::Close()
}
}
void CDBEnv::CloseDb(const string& strFile)
void CDBEnv::CloseDb(const std::string& strFile)
{
{
LOCK(cs_db);
@ -326,7 +329,7 @@ void CDBEnv::CloseDb(const string& strFile)
}
}
bool CDBEnv::RemoveDb(const string& strFile)
bool CDBEnv::RemoveDb(const std::string& strFile)
{
this->CloseDb(strFile);
@ -335,7 +338,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 (!fShutdown)
{
@ -350,7 +353,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
bool fSuccess = true;
printf("Rewriting %s...\n", strFile.c_str());
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);
@ -439,10 +442,10 @@ void CDBEnv::Flush(bool fShutdown)
return;
{
LOCK(cs_db);
map<string, int>::iterator mi = mapFileUseCount.begin();
std::map<std::string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end())
{
string strFile = (*mi).first;
std::string strFile = (*mi).first;
int nRefCount = (*mi).second;
printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
if (nRefCount == 0)
@ -462,7 +465,7 @@ void CDBEnv::Flush(bool fShutdown)
else
mi++;
}
printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
printf("DBFlush(%s)%s ended %15" PRI64d "ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
if (fShutdown)
{
char** listp;
@ -488,13 +491,13 @@ bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
{
assert(!fClient);
txindex.SetNull();
return Read(make_pair(string("tx"), hash), txindex);
return Read(std::make_pair(std::string("tx"), hash), txindex);
}
bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
{
assert(!fClient);
return Write(make_pair(string("tx"), hash), txindex);
return Write(std::make_pair(std::string("tx"), hash), txindex);
}
bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
@ -504,7 +507,7 @@ bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeigh
// Add to tx index
uint256 hash = tx.GetHash();
CTxIndex txindex(pos, tx.vout.size());
return Write(make_pair(string("tx"), hash), txindex);
return Write(std::make_pair(std::string("tx"), hash), txindex);
}
bool CTxDB::EraseTxIndex(const CTransaction& tx)
@ -512,13 +515,13 @@ bool CTxDB::EraseTxIndex(const CTransaction& tx)
assert(!fClient);
uint256 hash = tx.GetHash();
return Erase(make_pair(string("tx"), hash));
return Erase(std::make_pair(std::string("tx"), hash));
}
bool CTxDB::ContainsTx(uint256 hash)
{
assert(!fClient);
return Exists(make_pair(string("tx"), hash));
return Exists(std::make_pair(std::string("tx"), hash));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
@ -549,47 +552,47 @@ bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
return Write(std::make_pair(std::string("blockindex"), blockindex.GetBlockHash()), blockindex);
}
bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
{
return Read(string("hashBestChain"), hashBestChain);
return Read(std::string("hashBestChain"), hashBestChain);
}
bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
{
return Write(string("hashBestChain"), hashBestChain);
return Write(std::string("hashBestChain"), hashBestChain);
}
bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
{
return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
return Read(std::string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
{
return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
return Write(std::string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
{
return Read(string("hashSyncCheckpoint"), hashCheckpoint);
return Read(std::string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
{
return Write(string("hashSyncCheckpoint"), hashCheckpoint);
return Write(std::string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
bool CTxDB::ReadCheckpointPubKey(std::string& strPubKey)
{
return Read(string("strCheckpointPubKey"), strPubKey);
return Read(std::string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
bool CTxDB::WriteCheckpointPubKey(const std::string& strPubKey)
{
return Write(string("strCheckpointPubKey"), strPubKey);
return Write(std::string("strCheckpointPubKey"), strPubKey);
}
CBlockIndex static * InsertBlockIndex(uint256 hash)
@ -598,15 +601,15 @@ CBlockIndex static * InsertBlockIndex(uint256 hash)
return NULL;
// Return existing
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// 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;
@ -621,12 +624,12 @@ bool CTxDB::LoadBlockIndex()
return true;
// Calculate bnChainTrust
vector<pair<int, CBlockIndex*> > vSortedByHeight;
std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& 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());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
@ -636,7 +639,7 @@ bool CTxDB::LoadBlockIndex()
// ppcoin: calculate stake modifier checksum
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRI64x, pindex->nHeight, pindex->nStakeModifier);
}
// Load hashBestChain pointer to end of best chain
@ -672,7 +675,7 @@ bool CTxDB::LoadBlockIndex()
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
std::map<std::pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
@ -689,7 +692,7 @@ bool CTxDB::LoadBlockIndex()
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
std::pair<unsigned int, unsigned int> pos = std::make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
@ -722,7 +725,7 @@ bool CTxDB::LoadBlockIndex()
{
if (!txpos.IsNull())
{
pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
std::pair<unsigned int, unsigned int> posFind = std::make_pair(txpos.nFile, txpos.nBlockPos);
if (!mapBlockPos.count(posFind))
{
printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
@ -807,7 +810,7 @@ bool CTxDB::LoadBlockIndexGuts()
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << make_pair(string("blockindex"), uint256(0));
ssKey << std::make_pair(std::string("blockindex"), uint256(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
@ -819,7 +822,7 @@ bool CTxDB::LoadBlockIndexGuts()
// Unserialize
try {
string strType;
std::string strType;
ssKey >> strType;
if (strType == "blockindex" && !fRequestShutdown)
{
@ -855,7 +858,7 @@ bool CTxDB::LoadBlockIndexGuts()
// ppcoin: build setStakeSeen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
setStakeSeen.insert(std::make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
}
else
{
@ -934,7 +937,7 @@ bool CAddrDB::Read(CAddrMan& addr)
// use file size to size memory buffer
int fileSize = GetFilesize(filein);
int dataSize = fileSize - sizeof(uint256);
vector<unsigned char> vchData;
std::vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;

View File

@ -7,6 +7,8 @@
#include "main.h"
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
@ -127,7 +129,7 @@ protected:
Dbt datValue;
datValue.set_flags(DB_DBT_MALLOC);
int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datKey.get_data(), 0, datKey.get_size());
if (datValue.get_data() == NULL)
return false;
@ -141,8 +143,8 @@ protected:
}
// Clear and free memory
memset(datValue.get_data(), 0, datValue.get_size());
free(datValue.get_data());
std::memset(datValue.get_data(), 0, datValue.get_size());
std::free(datValue.get_data());
return (ret == 0);
}
@ -170,8 +172,8 @@ protected:
int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));
// Clear memory in case it was a private key
memset(datKey.get_data(), 0, datKey.get_size());
memset(datValue.get_data(), 0, datValue.get_size());
std::memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datValue.get_data(), 0, datValue.get_size());
return (ret == 0);
}
@ -193,7 +195,7 @@ protected:
int ret = pdb->del(activeTxn, &datKey, 0);
// Clear memory
memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datKey.get_data(), 0, datKey.get_size());
return (ret == 0 || ret == DB_NOTFOUND);
}
@ -213,7 +215,7 @@ protected:
int ret = pdb->exists(activeTxn, &datKey, 0);
// Clear memory
memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datKey.get_data(), 0, datKey.get_size());
return (ret == 0);
}
@ -260,10 +262,10 @@ protected:
ssValue.write((char*)datValue.get_data(), datValue.get_size());
// Clear and free memory
memset(datKey.get_data(), 0, datKey.get_size());
memset(datValue.get_data(), 0, datValue.get_size());
free(datKey.get_data());
free(datValue.get_data());
std::memset(datKey.get_data(), 0, datKey.get_size());
std::memset(datValue.get_data(), 0, datValue.get_size());
std::free(datKey.get_data());
std::free(datValue.get_data());
return 0;
}

View File

@ -17,13 +17,13 @@
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#include <map>
#include <string>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
@ -217,7 +217,7 @@ bool static Bind(const CService &addr, bool fError = true) {
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
std::string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: curecoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: curecoind.pid)") + "\n" +
@ -510,7 +510,7 @@ bool AppInit2()
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
std::string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
@ -528,7 +528,7 @@ bool AppInit2()
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", 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."), strDataDir.c_str());
@ -633,7 +633,7 @@ bool AppInit2()
if (mapArgs.count("-externalip"))
{
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
BOOST_FOREACH(std::string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
@ -657,7 +657,7 @@ bool AppInit2()
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
BOOST_FOREACH(std::string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// TODO: replace this by DNSseed
@ -667,7 +667,7 @@ bool AppInit2()
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
std::string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
@ -695,7 +695,7 @@ bool AppInit2()
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf(" block index %15" PRI64d "ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
@ -705,9 +705,9 @@ bool AppInit2()
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
std::string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
for (std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
@ -751,7 +751,7 @@ bool AppInit2()
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."));
uiInterface.ThreadSafeMessageBox(msg, _("Curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
@ -797,7 +797,7 @@ bool AppInit2()
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf(" wallet %15" PRI64d "ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
@ -817,7 +817,7 @@ bool AppInit2()
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
printf(" rescan %15" PRI64d "ms\n", GetTimeMillis() - nStart);
}
// ********************************************************* Step 9: import blocks
@ -826,7 +826,7 @@ bool AppInit2()
{
uiInterface.InitMessage(_("<font style='color: black'>Importing blockchain data file.</font>"));
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
BOOST_FOREACH(std::string strFile, mapMultiArgs["-loadblock"])
{
FILE *file = fopen(strFile.c_str(), "rb");
if (file)
@ -858,7 +858,7 @@ bool AppInit2()
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
printf("Loaded %i addresses from peers.dat %" PRI64d "ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
@ -869,11 +869,11 @@ bool AppInit2()
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
if (!NewThread(StartNode, NULL))
InitError(_("Error: could not start node"));

View File

@ -8,8 +8,8 @@
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
#include <string>
#include <vector>
int nGotIRCAddresses = 0;
@ -26,22 +26,22 @@ struct ircaddr
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
std::string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
std::vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return std::string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
bool DecodeAddress(std::string str, CService& addr)
{
vector<unsigned char> vch;
std::vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
@ -75,7 +75,7 @@ static bool Send(SOCKET hSocket, const char* pszSend)
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
bool RecvLineIRC(SOCKET hSocket, std::string& strLine)
{
while (true)
{
@ -84,7 +84,7 @@ bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
if (fShutdown)
return false;
vector<string> vWords;
std::vector<std::string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
@ -102,18 +102,18 @@ int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const cha
{
while (true)
{
string strLine;
std::string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
if (psz1 && strLine.find(psz1) != std::string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
if (psz2 && strLine.find(psz2) != std::string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
if (psz3 && strLine.find(psz3) != std::string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
if (psz4 && strLine.find(psz4) != std::string::npos)
return 4;
}
}
@ -132,16 +132,16 @@ bool Wait(int nSeconds)
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
bool RecvCodeLine(SOCKET hSocket, const char* psz1, std::string& strRet)
{
strRet.clear();
while (true)
{
string strLine;
std::string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
std::vector<std::string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
@ -155,23 +155,23 @@ bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
bool GetIPFromIRC(SOCKET hSocket, std::string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
std::string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
std::vector<std::string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
std::string str = vWords[3];
if (str.rfind("@") == std::string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
std::string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
@ -258,13 +258,13 @@ void ThreadIRCSeed2(void* parg)
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
std::string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
strMyName = strprintf("x%" PRI64u "", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
@ -319,14 +319,14 @@ void ThreadIRCSeed2(void* parg)
}
int64 nStart = GetTime();
string strLine;
std::string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
std::vector<std::string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;

View File

@ -28,8 +28,6 @@ namespace json_spirit
template< class String_type >
String_type non_printable_to_string( unsigned int c )
{
typedef typename String_type::value_type Char_type;
String_type result( 6, '\\' );
result[1] = 'u';

View File

@ -7,7 +7,11 @@
#include "kernel.h"
#include "db.h"
using namespace std;
#include <algorithm>
#include <map>
#include <string>
#include <utility>
#include <vector>
extern int nStakeMaxAge;
extern int nStakeTargetSpacing;
@ -38,7 +42,7 @@ int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
// this change increases active coins participating the hash and helps
// to secure the network when proof-of-stake difficulty is low
return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
return std::min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
}
// Get the last stake modifier and its generation time from a given block
@ -75,8 +79,8 @@ static int64 GetStakeModifierSelectionInterval()
// already selected blocks in vSelectedBlocks, and with timestamp up to
// nSelectionIntervalStop.
static bool SelectBlockFromCandidates(
vector<pair<int64, uint256> >& vSortedByTimestamp,
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
std::vector<std::pair<int64, uint256> >& vSortedByTimestamp,
std::map<uint256, const CBlockIndex*>& mapSelectedBlocks,
int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
const CBlockIndex** pindexSelected)
{
@ -149,20 +153,20 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
return error("ComputeNextStakeModifier: unable to get last modifier");
if (fDebug)
{
printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
printf("ComputeNextStakeModifier: prev modifier=0x%016" PRI64x " time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
}
if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
return true;
// Sort candidate blocks by timestamp
vector<pair<int64, uint256> > vSortedByTimestamp;
std::vector<std::pair<int64, uint256> > vSortedByTimestamp;
vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
int64 nSelectionInterval = GetStakeModifierSelectionInterval();
int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - 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;
@ -172,8 +176,8 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
// Select 64 blocks from candidate blocks to generate stake modifier
uint64 nStakeModifierNew = 0;
int64 nSelectionIntervalStop = nSelectionIntervalStart;
map<uint256, const CBlockIndex*> mapSelectedBlocks;
for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
std::map<uint256, const CBlockIndex*> 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);
@ -183,7 +187,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
// write the entropy bit of the selected block
nStakeModifierNew |= (((uint64)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 (fDebug && GetBoolArg("-printstakemodifier"))
printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
@ -192,7 +196,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
// Print selection map for visualization of the selected blocks
if (fDebug && GetBoolArg("-printstakemodifier"))
{
string strSelectionMap = "";
std::string strSelectionMap = "";
// '-' indicates proof-of-work blocks not selected
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
pindex = pindexPrev;
@ -213,7 +217,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
}
if (fDebug)
{
printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
printf("ComputeNextStakeModifier: new modifier=0x%016" PRI64x " time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
}
nStakeModifier = nStakeModifierNew;
@ -294,7 +298,7 @@ bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned
// v0.3 protocol kernel hash weight starts from 0 at the 30-day min age
// this change increases active coins participating the hash and helps
// to secure the network when proof-of-stake difficulty is low
int64 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
int64 nTimeWeight = std::min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
// Calculate hash
@ -311,12 +315,12 @@ bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned
hashProofOfStake = Hash(ss.begin(), ss.end());
if (fPrintProofOfStake)
{
printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x " at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
nStakeModifier, nStakeModifierHeight,
DateTimeStrFormat(nStakeModifierTime).c_str(),
mapBlockIndex[blockFrom.GetHash()]->nHeight,
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016" PRI64x " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
"0.3",
nStakeModifier,
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
@ -328,12 +332,12 @@ bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned
return false;
if (fDebug && !fPrintProofOfStake)
{
printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x " at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
nStakeModifier, nStakeModifierHeight,
DateTimeStrFormat(nStakeModifierTime).c_str(),
mapBlockIndex[blockFrom.GetHash()]->nHeight,
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016" PRI64x " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
"0.3",
nStakeModifier,
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,

View File

@ -15,8 +15,14 @@
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace std;
using namespace boost;
#include <cstdio>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
const bool IsCalculatingGenesisBlockHash = false;
@ -25,15 +31,15 @@ const bool IsCalculatingGenesisBlockHash = false;
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
std::set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
std::map<uint256, CBlockIndex*> mapBlockIndex;
std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
uint256 hashGenesisBlock = hashGenesisBlockOfficial;
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
static CBigNum bnProofOfStakeLimit(~uint256(0) >> 24);
@ -59,18 +65,18 @@ int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
std::map<uint256, CBlock*> mapOrphanBlocks;
std::multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
std::set<std::pair<COutPoint, unsigned int> > setStakeSeenOrphan;
std::map<uint256, uint256> mapProofOfStake;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
std::map<uint256, CDataStream*> mapOrphanTransactions;
std::map<uint256, std::map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "curecoin Signed Message:\n";
const std::string strMessageMagic = "curecoin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
@ -215,16 +221,16 @@ bool AddOrphanTx(const CDataStream& vMsg)
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(std::make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
@ -253,7 +259,7 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
std::map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
@ -348,7 +354,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
std::vector<std::vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
@ -363,7 +369,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
std::vector<std::vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
@ -372,7 +378,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
std::vector<std::vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
@ -450,7 +456,7 @@ int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
@ -497,7 +503,7 @@ bool CTransaction::CheckTransaction() const
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
std::set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
@ -619,7 +625,7 @@ bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
std::map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
@ -644,7 +650,7 @@ bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
return error("CTxMemPool::accept() : not enough fees %s, %" PRI64d " < %" PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
@ -697,7 +703,7 @@ bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
@ -753,7 +759,7 @@ void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
for (std::map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
@ -766,7 +772,7 @@ int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
@ -790,7 +796,7 @@ int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
return std::max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
}
@ -849,7 +855,7 @@ int CTxIndex::GetDepthInMainChain() const
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
@ -1059,21 +1065,21 @@ int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTi
{
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
printf("GetProofOfStakeReward() : lower=%" PRI64d " upper=%" PRI64d " mid=%" PRI64d "\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget)
bnUpperBound = bnMidValue;
else
bnLowerBound = bnMidValue;
}
nRewardCoinYear = bnUpperBound.getuint64();
if (nBestHeight > (int)HF_BLOCK) min(nRewardCoinYear, (int64)(0.04 * MAX_MINT_PROOF_OF_WORK)); // 4% hardfork
else nRewardCoinYear = min(nRewardCoinYear, MAX_MINT_PROOF_OF_STAKE);
if (nBestHeight > (int)HF_BLOCK) std::min(nRewardCoinYear, (int64)(0.04 * MAX_MINT_PROOF_OF_WORK)); // 4% hardfork
else nRewardCoinYear = std::min(nRewardCoinYear, MAX_MINT_PROOF_OF_STAKE);
int64 nSubsidy = nRewardCoinYear * nCoinAge * 33 / (365 * 33 + 8) ;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRI64d " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
return nSubsidy;
}
@ -1169,7 +1175,7 @@ unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fP
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
if (pindexLast->nHeight > (int)HF_BLOCK) nStakeTargetSpacing = 4 * 60; // 4 minute target enforced
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : std::min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
int64 nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
@ -1243,7 +1249,7 @@ void static InvalidChainFound(CBlockIndex* pindexNew)
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
nTime = std::max(GetBlockTime(), GetAdjustedTime());
}
@ -1292,7 +1298,7 @@ bool CTransaction::DisconnectInputs(CTxDB& txdb)
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool CTransaction::FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
@ -1360,7 +1366,7 @@ bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTes
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %" PRIszu " %" PRIszu " prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
@ -1410,7 +1416,7 @@ unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
@ -1429,7 +1435,7 @@ bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %" PRIszu " %" PRIszu " prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
@ -1626,7 +1632,7 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
std::map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
int64 nValueIn = 0;
int64 nValueOut = 0;
@ -1694,13 +1700,13 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
// ppcoin: fees are not collected by miners as in curecoin
// ppcoin: fees are destroyed to compensate the entire network
if (fDebug && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
printf("ConnectBlock() : destroy=%s nFees=%" PRI64d "\n", FormatMoney(nFees).c_str(), nFees);
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
for (std::map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
@ -1753,21 +1759,21 @@ bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
std::vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
std::vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Disconnect %" PRIszu " blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %" PRIszu " blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
std::vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
@ -1783,7 +1789,7 @@ bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
}
// Connect longer branch
vector<CTransaction> vDelete;
std::vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
@ -1892,7 +1898,7 @@ bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
}
if (!vpindexSecondary.empty())
printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
@ -2007,7 +2013,7 @@ bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
printf("coin age nValueIn=%" PRI64d " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
@ -2035,7 +2041,7 @@ bool CBlock::GetCoinAge(uint64& nCoinAge) const
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
printf("block coin age total nCoinDays=%" PRI64d "\n", nCoinAge);
return true;
}
@ -2051,7 +2057,7 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
std::map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
@ -2081,12 +2087,12 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRI64x, pindexNew->nHeight, nStakeModifier);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
setStakeSeen.insert(std::make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
@ -2166,7 +2172,7 @@ bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRI64d " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// Check transactions
@ -2182,7 +2188,7 @@ bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
std::set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
@ -2221,7 +2227,7 @@ bool CBlock::AcceptBlock()
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
@ -2341,7 +2347,7 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
return false; // do not error here as we expect this during initial block download
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
mapProofOfStake.insert(std::make_pair(hash, hashProofOfStake));
}
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
@ -2380,8 +2386,8 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
else
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
}
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
mapOrphanBlocks.insert(std::make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(std::make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
@ -2400,12 +2406,12 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
std::vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
for (std::multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
@ -2431,7 +2437,7 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
// ppcoin: sign block
bool CBlock::SignBlock(const CKeyStore& keystore)
{
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
txnouttype whichType;
if(!IsProofOfStake())
@ -2492,7 +2498,7 @@ bool CBlock::CheckBlockSignature() const
if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
return vchBlockSig.empty();
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
txnouttype whichType;
if(IsProofOfStake())
@ -2548,7 +2554,7 @@ bool CheckDiskSpace(uint64 nAdditionalBytes)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low!");
std::string strMessage = _("Warning: Disk space is low!");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "curecoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
@ -2560,7 +2566,7 @@ bool CheckDiskSpace(uint64 nAdditionalBytes)
static boost::filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
std::string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
@ -2645,7 +2651,7 @@ bool LoadBlockIndex(bool fAllowNew)
txNew.nTime = nChainStartTime;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
//txNew.vout[0].scriptPubKey = CScript() << ParseHex(pszMainKey) << OP_CHECKSIG;
txNew.strTxComment = "text:curecoin genesis block";
@ -2714,7 +2720,7 @@ bool LoadBlockIndex(bool fAllowNew)
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
{
CTxDB txdb;
string strPubKey = "";
std::string strPubKey = "";
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
// write checkpoint master key to db
@ -2743,8 +2749,8 @@ bool LoadBlockIndex(bool fAllowNew)
void PrintBlockTree()
{
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
std::map<CBlockIndex*, std::vector<CBlockIndex*> > mapNext;
for (std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
@ -2753,8 +2759,8 @@ void PrintBlockTree()
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
std::vector<std::pair<int, CBlockIndex*> > vStack;
vStack.push_back(std::make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
@ -2785,7 +2791,7 @@ void PrintBlockTree()
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
@ -2798,19 +2804,19 @@ void PrintBlockTree()
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
std::vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
std::swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
vStack.push_back(std::make_pair(nCol+i, vNext[i]));
}
}
@ -2835,10 +2841,10 @@ bool LoadExternalBlockFile(FILE* fileIn)
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
void* nFind = std::memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
if (std::memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
@ -2870,7 +2876,7 @@ bool LoadExternalBlockFile(FILE* fileIn)
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
printf("Loaded %i blocks from external file in %" PRI64d "ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
@ -2887,17 +2893,17 @@ bool LoadExternalBlockFile(FILE* fileIn)
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern std::map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
static string strMintMessage = "Click 'Settings' then 'Unlock Wallet' to stake.";
static string strMintWarning;
static std::string strMintMessage = "Click 'Settings' then 'Unlock Wallet' to stake.";
static std::string strMintWarning;
string GetWarnings(string strFor)
std::string GetWarnings(std::string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
std::string strStatusBar;
std::string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
@ -3000,12 +3006,12 @@ bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
static std::map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
@ -3076,7 +3082,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
pfrom->vSend.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
@ -3151,13 +3157,13 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
pfrom->vRecv.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
std::vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
@ -3166,11 +3172,11 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %"PRIszu"", vAddr.size());
return error("message addr size() = %" PRIszu "", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
std::vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
@ -3194,19 +3200,19 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
std::multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
std::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<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
for (std::multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
@ -3224,12 +3230,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
else if (strCommand == "inv")
{
vector<CInv> vInv;
std::vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %"PRIszu"", vInv.size());
return error("message inv size() = %" PRIszu "", vInv.size());
}
// find last block in inv vector
@ -3274,16 +3280,16 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
else if (strCommand == "getdata")
{
vector<CInv> vInv;
std::vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %"PRIszu"", vInv.size());
return error("message getdata size() = %" PRIszu "", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
@ -3295,7 +3301,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
@ -3309,7 +3315,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
// peershares: send latest block
vector<CInv> vInv;
std::vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
@ -3322,7 +3328,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
std::map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
@ -3408,7 +3414,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
@ -3421,7 +3427,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
std::vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
@ -3436,8 +3442,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
std::vector<uint256> vWorkQueue;
std::vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
@ -3459,7 +3465,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
for (std::map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
@ -3526,7 +3532,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
std::vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
@ -3536,7 +3542,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
std::vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
@ -3555,7 +3561,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
pfrom->PushMessage("reply", hashReply, (int)2, std::string(""));
return true;
}
@ -3583,7 +3589,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
std::map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
@ -3699,11 +3705,11 @@ bool ProcessMessages(CNode* pfrom)
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
std::vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
@ -3711,7 +3717,7 @@ bool ProcessMessages(CNode* pfrom)
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
std::string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
@ -3730,7 +3736,7 @@ bool ProcessMessages(CNode* pfrom)
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
std::memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
@ -3835,7 +3841,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
std::vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
@ -3860,8 +3866,8 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
std::vector<CInv> vInv;
std::vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
@ -3918,7 +3924,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
//
// Message: getdata
//
vector<CInv> vGetData;
std::vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
@ -3968,7 +3974,7 @@ int static FormatHashBlocks(void* pbuffer, unsigned int len)
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
std::memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
@ -4037,7 +4043,7 @@ class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
std::set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
@ -4092,7 +4098,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
CReserveKey reservekey(pwallet);
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
std::unique_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
@ -4143,7 +4149,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
{
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
{
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
if (txCoinStake.nTime >= std::max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
{ // make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
pblock->vtx[0].vout[0].SetEmpty();
@ -4166,13 +4172,13 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
std::list<COrphan> vOrphan; // list memory doesn't move
std::map<uint256, std::vector<COrphan*> > mapDependers;
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
std::vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
for (std::map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
@ -4241,7 +4247,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
std::map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
@ -4293,7 +4299,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
std::map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
@ -4310,7 +4316,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
std::swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
@ -4348,7 +4354,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
printf("CreateNewBlock(): total size %" PRI64u "\n", nBlockSize);
if (pblock->IsProofOfWork())
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash());
@ -4358,8 +4364,8 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
if (pblock->IsProofOfStake())
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = std::max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
if (pblock->IsProofOfWork())
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
@ -4409,7 +4415,7 @@ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
std::memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
@ -4428,8 +4434,8 @@ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
std::memcpy(pdata, &tmp.block, 128);
std::memcpy(phash1, &tmp.hash1, 64);
}
@ -4514,7 +4520,7 @@ void curecoinMiner(CWallet *pwallet, bool fProofOfStake)
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
std::unique_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
@ -4539,7 +4545,7 @@ void curecoinMiner(CWallet *pwallet, bool fProofOfStake)
continue;
}
printf("Running curecoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
printf("Running curecoinMiner with %" PRIszu " transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//
@ -4636,8 +4642,8 @@ void curecoinMiner(CWallet *pwallet, bool fProofOfStake)
break;
// Update nTime every few seconds
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = std::max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);

View File

@ -649,7 +649,7 @@ public:
{
std::string str;
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d, strTxComment=%s)\n",
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu", vout.size=%" PRIszu", nLockTime=%d, strTxComment=%s)\n",
GetHash().ToString().substr(0,10).c_str(),
nTime,
nVersion,
@ -939,7 +939,7 @@ public:
printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
hashSig >>= 159; // take the first bit of the hash
if (fDebug && GetBoolArg("-printstakemodifier"))
printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
printf(" entropybit=%" PRI64d "\n", hashSig.Get64());
return hashSig.Get64();
}
@ -1075,7 +1075,7 @@ public:
void print() const
{
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ", vchBlockSig=%s)\n",
GetHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
@ -1338,7 +1338,7 @@ public:
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016" PRI64x ", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",

View File

@ -11,6 +11,15 @@
#include "addrman.h"
#include "ui_interface.h"
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#ifdef WIN32
#include <string.h>
#endif
@ -22,8 +31,6 @@
#include <miniupnpc/upnperrors.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 24;
@ -51,7 +58,7 @@ bool fDiscover = true;
bool fUseUPnP = false;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
@ -61,22 +68,22 @@ boost::array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
std::vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
std::map<CInv, CDataStream> mapRelay;
std::deque<std::pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
std::map<CInv, int64> mapAlreadyAskedFor;
static deque<string> vOneShots;
static std::deque<std::string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
std::set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
void AddOneShot(std::string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
@ -108,7 +115,7 @@ bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
@ -137,7 +144,7 @@ CAddress GetLocalAddress(const CNetAddr *paddrPeer)
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
bool RecvLine(SOCKET hSocket, std::string& strLine)
{
strLine = "";
while (true)
@ -308,7 +315,7 @@ bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const cha
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
std::string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
@ -322,14 +329,14 @@ bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const cha
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
if (strLine.find(pszKeyword) != std::string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
if (strLine.find("<") != std::string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
@ -555,7 +562,7 @@ void CNode::PushVersion()
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()), nBestHeight);
}
@ -662,7 +669,7 @@ void ThreadSocketHandler(void* parg)
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
std::list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
while (true)
@ -673,7 +680,7 @@ void ThreadSocketHandler2(void* parg)
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
std::vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
@ -690,7 +697,7 @@ void ThreadSocketHandler2(void* parg)
pnode->Cleanup();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
pnode->nReleaseTime = std::max(pnode->nReleaseTime, GetTime() + 15 * 60);
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
@ -698,7 +705,7 @@ void ThreadSocketHandler2(void* parg)
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
@ -755,7 +762,7 @@ void ThreadSocketHandler2(void* parg)
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
hSocketMax = std::max(hSocketMax, hListenSocket);
have_fds = true;
}
{
@ -766,7 +773,7 @@ void ThreadSocketHandler2(void* parg)
continue;
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
hSocketMax = std::max(hSocketMax, pnode->hSocket);
have_fds = true;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
@ -859,7 +866,7 @@ void ThreadSocketHandler2(void* parg)
//
// Service each socket
//
vector<CNode*> vNodesCopy;
std::vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
@ -886,7 +893,7 @@ void ThreadSocketHandler2(void* parg)
if (nPos > ReceiveBufferSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
printf("socket recv flood control disconnect (%" PRIszu " bytes)\n", vRecv.size());
pnode->CloseSocketDisconnect();
}
else {
@ -1065,7 +1072,7 @@ void ThreadMapPort2(void* parg)
}
}
string strDesc = "curecoin " + FormatFullVersion();
std::string strDesc = "curecoin " + FormatFullVersion();
#if MINIUPNPC_API_VERSION >= 8
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
@ -1191,8 +1198,8 @@ void ThreadDNSAddressSeed2(void* parg)
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
std::vector<CNetAddr> vaddr;
std::vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
@ -1235,7 +1242,7 @@ void DumpAddresses()
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
printf("Flushed %d addresses to peers.dat %" PRI64d "ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
@ -1290,7 +1297,7 @@ void ThreadOpenConnections(void* parg)
void static ProcessOneShot()
{
string strDest;
std::string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
@ -1337,7 +1344,7 @@ void ThreadOpenConnections2(void* parg)
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
BOOST_FOREACH(std::string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
@ -1399,7 +1406,7 @@ void ThreadOpenConnections2(void* parg)
// 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<vector<unsigned char> > setConnected;
std::set<std::vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
@ -1416,7 +1423,7 @@ void ThreadOpenConnections2(void* parg)
while (true)
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
CAddress addr = addrman.Select(10 + std::min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
@ -1479,7 +1486,7 @@ void ThreadOpenAddedConnections2(void* parg)
if (HaveNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
BOOST_FOREACH(std::string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
@ -1492,10 +1499,10 @@ void ThreadOpenAddedConnections2(void* parg)
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
std::vector<std::vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(std::string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
std::vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
@ -1508,13 +1515,13 @@ void ThreadOpenAddedConnections2(void* parg)
}
while (true)
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
std::vector<std::vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
for (std::vector<std::vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
@ -1523,7 +1530,7 @@ void ThreadOpenAddedConnections2(void* parg)
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
BOOST_FOREACH(std::vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
@ -1607,7 +1614,7 @@ void ThreadMessageHandler2(void* parg)
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
std::vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
@ -1664,7 +1671,7 @@ void ThreadMessageHandler2(void* parg)
bool BindListenPort(const CService &addrBind, string& strError)
bool BindListenPort(const CService &addrBind, std::string& strError)
{
strError = "";
int nOne = 1;
@ -1781,7 +1788,7 @@ void static Discover()
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
std::vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
@ -1834,7 +1841,7 @@ void StartNode(void* parg)
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
int nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}

View File

@ -320,7 +320,7 @@ public:
// the key is the earliest time the request can be sent
int64& nRequestTime = mapAlreadyAskedFor[inv];
if (fDebugNet)
printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
printf("askfor %s %" PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
// Make sure not to reuse time indexes to keep things in the same order
int64 nNow = (GetTime() - 1) * 1000000;

View File

@ -7,6 +7,11 @@
#include "util.h"
#include "sync.h"
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#ifndef WIN32
#include <sys/fcntl.h>
#endif
@ -14,7 +19,6 @@
#include "strlcpy.h"
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
using namespace std;
// Settings
static proxyType proxyInfo[NET_MAX];
@ -68,7 +72,7 @@ bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsign
}
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
std::memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
@ -187,8 +191,8 @@ bool static Socks4(const CService &addrDest, SOCKET& hSocket)
closesocket(hSocket);
return error("Cannot get proxy destination address");
}
memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
std::memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
std::memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
char* pszSocks4 = pszSocks4IP;
int nSize = sizeof(pszSocks4IP);
@ -215,7 +219,7 @@ bool static Socks4(const CService &addrDest, SOCKET& hSocket)
return true;
}
bool static Socks5(string strDest, int port, SOCKET& hSocket)
bool static Socks5(std::string strDest, int port, SOCKET& hSocket)
{
printf("SOCKS5 connecting %s\n", strDest.c_str());
if (strDest.size() > 255)
@ -244,7 +248,7 @@ bool static Socks5(string strDest, int port, SOCKET& hSocket)
closesocket(hSocket);
return error("Proxy failed to initialize");
}
string strSocks5("\5\1");
std::string strSocks5("\5\1");
strSocks5 += '\000'; strSocks5 += '\003';
strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
strSocks5 += strDest;
@ -513,9 +517,9 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
{
string strDest;
std::string strDest;
int port = portDefault;
SplitHostPort(string(pszDest), port, strDest);
SplitHostPort(std::string(pszDest), port, strDest);
SOCKET hSocket = INVALID_SOCKET;
@ -548,12 +552,12 @@ bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest
void CNetAddr::Init()
{
memset(ip, 0, 16);
std::memset(ip, 0, 16);
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
std::memcpy(ip, ipIn.ip, sizeof(ip));
}
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
@ -565,7 +569,7 @@ bool CNetAddr::SetSpecial(const std::string &strName)
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16-sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
std::memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
@ -574,7 +578,7 @@ bool CNetAddr::SetSpecial(const std::string &strName)
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
if (vchAddr.size() != 16-sizeof(pchGarliCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
std::memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
ip[i + sizeof(pchGarliCat)] = vchAddr[i];
return true;
@ -589,14 +593,14 @@ CNetAddr::CNetAddr()
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
memcpy(ip, pchIPv4, 12);
memcpy(ip+12, &ipv4Addr, 4);
std::memcpy(ip, pchIPv4, 12);
std::memcpy(ip+12, &ipv4Addr, 4);
}
#ifdef USE_IPV6
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
memcpy(ip, &ipv6Addr, 16);
std::memcpy(ip, &ipv6Addr, 16);
}
#endif
@ -623,7 +627,7 @@ unsigned int CNetAddr::GetByte(int n) const
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
return (std::memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
@ -657,7 +661,7 @@ bool CNetAddr::IsRFC3964() const
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
return (std::memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
@ -668,7 +672,7 @@ bool CNetAddr::IsRFC4380() const
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
return (std::memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
@ -679,7 +683,7 @@ bool CNetAddr::IsRFC4193() const
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
return (std::memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
@ -689,12 +693,12 @@ bool CNetAddr::IsRFC4843() const
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
return (std::memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsI2P() const
{
return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
return (std::memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
}
bool CNetAddr::IsLocal() const
@ -705,7 +709,7 @@ bool CNetAddr::IsLocal() const
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
if (memcmp(ip, pchLocal, 16) == 0)
if (std::memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
@ -725,12 +729,12 @@ bool CNetAddr::IsValid() const
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
if (std::memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
if (std::memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
@ -741,12 +745,12 @@ bool CNetAddr::IsValid() const
{
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip+12, &ipNone, 4) == 0)
if (std::memcmp(ip+12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip+12, &ipNone, 4) == 0)
if (std::memcmp(ip+12, &ipNone, 4) == 0)
return false;
}
@ -810,31 +814,31 @@ std::string CNetAddr::ToString() const
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
return (std::memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
return (std::memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
return (std::memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip+12, 4);
std::memcpy(pipv4Addr, ip+12, 4);
return true;
}
#ifdef USE_IPV6
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
std::memcpy(pipv6Addr, ip, 16);
return true;
}
#endif
@ -918,7 +922,7 @@ uint64 CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64 nRet;
memcpy(&nRet, &hash, sizeof(nRet));
std::memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
@ -1116,7 +1120,7 @@ bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
std::memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
@ -1129,7 +1133,7 @@ bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
std::memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
@ -1144,7 +1148,7 @@ std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
std::memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;

View File

@ -1,6 +1,6 @@
// Copyright (c) 2013 curecoin Developers
#include <string.h>
#include <cstring>
#include "pbkdf2.h"
static inline uint32_t be32dec(const void *pp)
@ -38,20 +38,20 @@ void HMAC_SHA256_Init(HMAC_SHA256_CTX * ctx, const void * _K, size_t Klen)
/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */
SHA256_Init(&ctx->ictx);
memset(pad, 0x36, 64);
std::memset(pad, 0x36, 64);
for (i = 0; i < Klen; i++)
pad[i] ^= K[i];
SHA256_Update(&ctx->ictx, pad, 64);
/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */
SHA256_Init(&ctx->octx);
memset(pad, 0x5c, 64);
std::memset(pad, 0x5c, 64);
for (i = 0; i < Klen; i++)
pad[i] ^= K[i];
SHA256_Update(&ctx->octx, pad, 64);
/* Clean the stack. */
memset(khash, 0, 32);
std::memset(khash, 0, 32);
}
/* Add bytes to the HMAC-SHA256 operation. */
@ -76,7 +76,7 @@ void HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX * ctx)
SHA256_Final(digest, &ctx->octx);
/* Clean the stack. */
memset(ihash, 0, 32);
std::memset(ihash, 0, 32);
}
/**
@ -131,5 +131,5 @@ void PBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * sal
}
/* Clean PShctx, since we never called _Final on it. */
memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
std::memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
}

View File

@ -7,6 +7,9 @@
#include "util.h"
#include "netbase.h"
#include <cstdio>
#include <cstring>
#ifndef WIN32
# include <arpa/inet.h>
#endif
@ -20,8 +23,8 @@ static const char* ppszTypeName[] =
CMessageHeader::CMessageHeader()
{
memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
memset(pchCommand, 0, sizeof(pchCommand));
std::memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
std::memset(pchCommand, 0, sizeof(pchCommand));
pchCommand[1] = 1;
nMessageSize = -1;
nChecksum = 0;
@ -29,8 +32,8 @@ CMessageHeader::CMessageHeader()
CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
{
memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
std::memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
std::strncpy(pchCommand, pszCommand, COMMAND_SIZE);
nMessageSize = nMessageSizeIn;
nChecksum = 0;
}
@ -46,7 +49,7 @@ std::string CMessageHeader::GetCommand() const
bool CMessageHeader::IsValid() const
{
// Check start string
if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
if (std::memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
return false;
// Check the command string for errors

View File

@ -74,9 +74,9 @@ public:
void updateEntry(const QString &address, const QString &label, bool isMine, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
QList<AddressTableEntry>::iterator lower = std::lower_bound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
QList<AddressTableEntry>::iterator upper = std::upper_bound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -11,6 +11,7 @@
#include "wallet.h"
#include "ui_interface.h"
#include <algorithm>
#include <QLocale>
#include <QList>
#include <QColor>
@ -95,9 +96,9 @@ public:
bool inWallet = mi != wallet->mapWallet.end();
// Find bounds of this transaction in model
QList<TransactionRecord>::iterator lower = qLowerBound(
QList<TransactionRecord>::iterator lower = std::lower_bound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
QList<TransactionRecord>::iterator upper = qUpperBound(
QList<TransactionRecord>::iterator upper = std::upper_bound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
int lowerIndex = (lower - cachedWallet.begin());
int upperIndex = (upper - cachedWallet.begin());

View File

@ -9,6 +9,8 @@
#include "walletdb.h" // for BackupWallet
#include "base58.h"
#include <functional>
#include <QSet>
#include <QTimer>
@ -335,21 +337,21 @@ static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet,
void WalletModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, boost::placeholders::_1));
wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, boost::placeholders::_1, boost::placeholders::_2,
boost::placeholders::_3, boost::placeholders::_4, boost::placeholders::_5));
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, boost::placeholders::_1, boost::placeholders::_2,
boost::placeholders::_3));
wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, std::placeholders::_1));
wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3));
}
void WalletModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, boost::placeholders::_1));
wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, boost::placeholders::_1, boost::placeholders::_2,
boost::placeholders::_3, boost::placeholders::_4, boost::placeholders::_5));
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, boost::placeholders::_1, boost::placeholders::_2,
boost::placeholders::_3));
wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, std::placeholders::_1));
wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, std::placeholders::_1, boost::placeholders::_2,
std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3));
}
// WalletModel::UnlockContext implementation

View File

@ -6,8 +6,8 @@
#include "main.h"
#include "curecoinrpc.h"
using namespace json_spirit;
using namespace std;
#include <stdexcept>
#include <vector>
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
@ -68,41 +68,41 @@ double GetPoSKernelPS()
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
json_spirit::Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
json_spirit::Object result;
result.push_back(json_spirit::Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(json_spirit::Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(json_spirit::Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(json_spirit::Pair("height", blockindex->nHeight));
result.push_back(json_spirit::Pair("version", block.nVersion));
result.push_back(json_spirit::Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(json_spirit::Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(json_spirit::Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(json_spirit::Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(json_spirit::Pair("bits", HexBits(block.nBits)));
result.push_back(json_spirit::Pair("difficulty", GetDifficulty(blockindex)));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
result.push_back(json_spirit::Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(json_spirit::Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier)));
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
Array txinfo;
result.push_back(json_spirit::Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(json_spirit::Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(json_spirit::Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(json_spirit::Pair("modifier", strprintf("%016" PRI64x, blockindex->nStakeModifier)));
result.push_back(json_spirit::Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
json_spirit::Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
json_spirit::Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(json_spirit::Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
@ -111,17 +111,17 @@ Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPri
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
result.push_back(json_spirit::Pair("tx", txinfo));
result.push_back(json_spirit::Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getblockcount(const Array& params, bool fHelp)
json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
@ -129,25 +129,25 @@ Value getblockcount(const Array& params, bool fHelp)
}
Value getdifficulty(const Array& params, bool fHelp)
json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
json_spirit::Object obj;
obj.push_back(json_spirit::Pair("proof-of-work", GetDifficulty()));
obj.push_back(json_spirit::Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(json_spirit::Pair("search-interval", (int)nLastCoinStakeSearchInterval));
return obj;
}
Value settxfee(const Array& params, bool fHelp)
json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
throw std::runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.01");
@ -157,42 +157,42 @@ Value settxfee(const Array& params, bool fHelp)
return true;
}
Value getrawmempool(const Array& params, bool fHelp)
json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
json_spirit::Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
throw std::runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
throw std::runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"getblock <hash> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-hash.");
@ -210,17 +210,17 @@ Value getblock(const Array& params, bool fHelp)
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblockbynumber(const Array& params, bool fHelp)
json_spirit::Value getblockbynumber(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"getblock <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
throw std::runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
@ -236,22 +236,22 @@ Value getblockbynumber(const Array& params, bool fHelp)
}
// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
json_spirit::Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
result.push_back(json_spirit::Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
result.push_back(json_spirit::Pair("height", pindexCheckpoint->nHeight));
result.push_back(json_spirit::Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
result.push_back(json_spirit::Pair("checkpointmaster", true));
return result;
}

View File

@ -9,10 +9,10 @@
#include <boost/lexical_cast.hpp>
#define printf OutputDebugStringF
#include <stdexcept>
#include <string>
using namespace json_spirit;
using namespace std;
#define printf OutputDebugStringF
class CTxDump
{
@ -32,15 +32,15 @@ public:
}
};
Value importprivkey(const Array& params, bool fHelp)
json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"importprivkey <curecoinPrivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
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();
CcurecoinSecret vchSecret;
@ -68,17 +68,17 @@ Value importprivkey(const Array& params, bool fHelp)
pwalletMain->ReacceptWalletTransactions();
}
return Value::null;
return json_spirit::Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
throw std::runtime_error(
"dumpprivkey <curecoinAddress>\n"
"Reveals the private key corresponding to <curecoinaddress>.");
string strAddress = params[0].get_str();
std::string strAddress = params[0].get_str();
CcurecoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid curecoin address");

View File

@ -8,15 +8,18 @@
#include "init.h"
#include "curecoinrpc.h"
using namespace json_spirit;
using namespace std;
#include <algorithm>
#include <map>
#include <stdexcept>
#include <utility>
#include <vector>
extern unsigned int nStakeTargetSpacing;
Value getgenerate(const Array& params, bool fHelp)
json_spirit::Value getgenerate(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getgenerate\n"
"Returns true or false.");
@ -24,10 +27,10 @@ Value getgenerate(const Array& params, bool fHelp)
}
Value setgenerate(const Array& params, bool fHelp)
json_spirit::Value setgenerate(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
@ -46,14 +49,14 @@ Value setgenerate(const Array& params, bool fHelp)
mapArgs["-gen"] = (fGenerate ? "1" : "0");
Generatecurecoins(fGenerate, pwalletMain);
return Value::null;
return json_spirit::Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
json_spirit::Value gethashespersec(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
@ -63,7 +66,7 @@ Value gethashespersec(const Array& params, bool fHelp)
}
// Litecoin: Return average network hashes per second based on last number of blocks.
Value GetNetworkHashPS(int lookup) {
json_spirit::Value GetNetworkHashPS(int lookup) {
if (pindexBest == NULL)
return 0;
@ -86,10 +89,10 @@ Value GetNetworkHashPS(int lookup) {
}
Value getnetworkhashps(const Array& params, bool fHelp)
json_spirit::Value getnetworkhashps(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
throw std::runtime_error(
"getnetworkhashps [blocks]\n"
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.");
@ -98,33 +101,33 @@ Value getnetworkhashps(const Array& params, bool fHelp)
}
Value getmininginfo(const Array& params, bool fHelp)
json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
// obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
json_spirit::Object obj;
obj.push_back(json_spirit::Pair("blocks", (int)nBestHeight));
obj.push_back(json_spirit::Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(json_spirit::Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(json_spirit::Pair("difficulty", (double)GetDifficulty()));
// obj.push_back(json_spirit::Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(json_spirit::Pair("errors", GetWarnings("statusbar")));
obj.push_back(json_spirit::Pair("generate", GetBoolArg("-gen")));
obj.push_back(json_spirit::Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(json_spirit::Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(json_spirit::Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(json_spirit::Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(json_spirit::Pair("testnet", fTestNet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
json_spirit::Value getstakinginfo(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
@ -135,31 +138,31 @@ Value getstakinginfo(const Array& params, bool fHelp)
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nStakeTargetSpacing * nNetworkWeight / nWeight) : -1;
Object obj;
json_spirit::Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(json_spirit::Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(json_spirit::Pair("staking", staking));
obj.push_back(json_spirit::Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(json_spirit::Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(json_spirit::Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(json_spirit::Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(json_spirit::Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(json_spirit::Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(json_spirit::Pair("weight", (uint64_t)nWeight));
obj.push_back(json_spirit::Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
obj.push_back(json_spirit::Pair("expectedtime", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
json_spirit::Value getworkex(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
@ -170,9 +173,9 @@ Value getworkex(const Array& params, bool fHelp)
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Curecoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
typedef std::map<uint256, std::pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static std::vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
@ -205,7 +208,7 @@ Value getworkex(const Array& params, bool fHelp)
}
// Update nTime
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
@ -226,21 +229,21 @@ Value getworkex(const Array& params, bool fHelp)
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
json_spirit::Object result;
result.push_back(json_spirit::Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(json_spirit::Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(json_spirit::Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
json_spirit::Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
result.push_back(json_spirit::Pair("merkle", merkle_arr));
return result;
@ -248,8 +251,8 @@ Value getworkex(const Array& params, bool fHelp)
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
std::vector<unsigned char> vchData = ParseHex(params[0].get_str());
std::vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
@ -286,10 +289,10 @@ Value getworkex(const Array& params, bool fHelp)
}
Value getwork(const Array& params, bool fHelp)
json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
throw std::runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
@ -304,9 +307,9 @@ Value getwork(const Array& params, bool fHelp)
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Curecoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
typedef std::map<uint256, std::pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static std::vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
@ -365,17 +368,17 @@ Value getwork(const Array& params, bool fHelp)
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
json_spirit::Object result;
result.push_back(json_spirit::Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(json_spirit::Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(json_spirit::Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(json_spirit::Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
std::vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
@ -402,10 +405,10 @@ Value getwork(const Array& params, bool fHelp)
}
Value getblocktemplate(const Array& params, bool fHelp)
json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
throw std::runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
@ -427,11 +430,11 @@ Value getblocktemplate(const Array& params, bool fHelp)
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
const json_spirit::Object& oparam = params[0].get_obj();
const json_spirit::Value& modeval = find_value(oparam, "mode");
if (modeval.type() == json_spirit::str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
else if (modeval.type() == json_spirit::null_type)
{
/* Do nothing */
}
@ -484,8 +487,8 @@ Value getblocktemplate(const Array& params, bool fHelp)
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
json_spirit::Array transactions;
std::map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
@ -496,43 +499,43 @@ Value getblocktemplate(const Array& params, bool fHelp)
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
json_spirit::Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(json_spirit::Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
entry.push_back(json_spirit::Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
std::map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
entry.push_back(json_spirit::Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
json_spirit::Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
entry.push_back(json_spirit::Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
entry.push_back(json_spirit::Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
json_spirit::Object aux;
aux.push_back(json_spirit::Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
static json_spirit::Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
@ -540,35 +543,35 @@ Value getblocktemplate(const Array& params, bool fHelp)
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
json_spirit::Object result;
result.push_back(json_spirit::Pair("version", pblock->nVersion));
result.push_back(json_spirit::Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(json_spirit::Pair("transactions", transactions));
result.push_back(json_spirit::Pair("coinbaseaux", aux));
result.push_back(json_spirit::Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(json_spirit::Pair("target", hashTarget.GetHex()));
result.push_back(json_spirit::Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(json_spirit::Pair("mutable", aMutable));
result.push_back(json_spirit::Pair("noncerange", "00000000ffffffff"));
result.push_back(json_spirit::Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(json_spirit::Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(json_spirit::Pair("curtime", (int64_t)pblock->nTime));
result.push_back(json_spirit::Pair("bits", HexBits(pblock->nBits)));
result.push_back(json_spirit::Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
std::vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
@ -585,6 +588,6 @@ Value submitblock(const Array& params, bool fHelp)
if (!fAccepted)
return "rejected";
return Value::null;
return json_spirit::Value::null;
}

View File

@ -9,13 +9,15 @@
#include "db.h"
#include "walletdb.h"
using namespace json_spirit;
using namespace std;
#include <map>
#include <stdexcept>
#include <vector>
Value getconnectioncount(const Array& params, bool fHelp)
json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getconnectioncount\n"
"Returns the number of connections to other nodes.");
@ -36,32 +38,32 @@ static void CopyNodeStats(std::vector<CNodeStats>& vstats)
}
}
Value getpeerinfo(const Array& params, bool fHelp)
json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
throw std::runtime_error(
"getpeerinfo\n"
"Returns data about each connected network node.");
vector<CNodeStats> vstats;
std::vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
json_spirit::Array ret;
BOOST_FOREACH(const CNodeStats& stats, vstats) {
Object obj;
json_spirit::Object obj;
obj.push_back(Pair("addr", stats.addrName));
obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices)));
obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend));
obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected));
obj.push_back(Pair("version", stats.nVersion));
obj.push_back(Pair("subver", stats.strSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("releasetime", (boost::int64_t)stats.nReleaseTime));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
obj.push_back(Pair("banscore", stats.nMisbehavior));
obj.push_back(json_spirit::Pair("addr", stats.addrName));
obj.push_back(json_spirit::Pair("services", strprintf("%08" PRI64x, stats.nServices)));
obj.push_back(json_spirit::Pair("lastsend", (boost::int64_t)stats.nLastSend));
obj.push_back(json_spirit::Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
obj.push_back(json_spirit::Pair("conntime", (boost::int64_t)stats.nTimeConnected));
obj.push_back(json_spirit::Pair("version", stats.nVersion));
obj.push_back(json_spirit::Pair("subver", stats.strSubVer));
obj.push_back(json_spirit::Pair("inbound", stats.fInbound));
obj.push_back(json_spirit::Pair("releasetime", (boost::int64_t)stats.nReleaseTime));
obj.push_back(json_spirit::Pair("startingheight", stats.nStartingHeight));
obj.push_back(json_spirit::Pair("banscore", stats.nMisbehavior));
ret.push_back(obj);
}
@ -70,16 +72,16 @@ Value getpeerinfo(const Array& params, bool fHelp)
}
extern CCriticalSection cs_mapAlerts;
extern map<uint256, CAlert> mapAlerts;
extern std::map<uint256, CAlert> mapAlerts;
// ppcoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
json_spirit::Value sendalert(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 6)
throw runtime_error(
throw std::runtime_error(
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
"<message> is the alert text message\n"
"<privatekey> is hex string of alert master private key\n"
@ -106,15 +108,15 @@ Value sendalert(const Array& params, bool fHelp)
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
std::vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
throw runtime_error(
throw std::runtime_error(
"Unable to sign alert, check private key?\n");
if(!alert.ProcessAlert())
throw runtime_error(
throw std::runtime_error(
"Failed to process alert.\n");
// Relay alert
{
@ -123,14 +125,14 @@ Value sendalert(const Array& params, bool fHelp)
alert.RelayTo(pnode);
}
Object result;
result.push_back(Pair("strStatusBar", alert.strStatusBar));
result.push_back(Pair("nVersion", alert.nVersion));
result.push_back(Pair("nMinVer", alert.nMinVer));
result.push_back(Pair("nMaxVer", alert.nMaxVer));
result.push_back(Pair("nPriority", alert.nPriority));
result.push_back(Pair("nID", alert.nID));
json_spirit::Object result;
result.push_back(json_spirit::Pair("strStatusBar", alert.strStatusBar));
result.push_back(json_spirit::Pair("nVersion", alert.nVersion));
result.push_back(json_spirit::Pair("nMinVer", alert.nMinVer));
result.push_back(json_spirit::Pair("nMaxVer", alert.nMaxVer));
result.push_back(json_spirit::Pair("nPriority", alert.nPriority));
result.push_back(json_spirit::Pair("nID", alert.nID));
if (alert.nCancel > 0)
result.push_back(Pair("nCancel", alert.nCancel));
result.push_back(json_spirit::Pair("nCancel", alert.nCancel));
return result;
}

View File

@ -13,102 +13,106 @@
#include "net.h"
#include "wallet.h"
using namespace std;
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
void ScriptPubKeyToJSON(const CScript& scriptPubKey, json_spirit::Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
std::vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
out.push_back(json_spirit::Pair("asm", scriptPubKey.ToString()));
out.push_back(json_spirit::Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
out.push_back(json_spirit::Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
out.push_back(json_spirit::Pair("reqSigs", nRequired));
out.push_back(json_spirit::Pair("type", GetTxnOutputType(type)));
Array a;
json_spirit::Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CcurecoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
out.push_back(json_spirit::Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("time", (boost::int64_t)tx.nTime));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
entry.push_back(json_spirit::Pair("txid", tx.GetHash().GetHex()));
entry.push_back(json_spirit::Pair("version", tx.nVersion));
entry.push_back(json_spirit::Pair("time", (boost::int64_t)tx.nTime));
entry.push_back(json_spirit::Pair("locktime", (boost::int64_t)tx.nLockTime));
if (tx.nVersion >= 2)
{
entry.push_back(Pair("tx-comment", tx.strTxComment));
entry.push_back(json_spirit::Pair("tx-comment", tx.strTxComment));
}
Array vin;
json_spirit::Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
json_spirit::Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(json_spirit::Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
in.push_back(json_spirit::Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(json_spirit::Pair("vout", (boost::int64_t)txin.prevout.n));
json_spirit::Object o;
o.push_back(json_spirit::Pair("asm", txin.scriptSig.ToString()));
o.push_back(json_spirit::Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(json_spirit::Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
in.push_back(json_spirit::Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
entry.push_back(json_spirit::Pair("vin", vin));
json_spirit::Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
json_spirit::Object out;
out.push_back(json_spirit::Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(json_spirit::Pair("n", (boost::int64_t)i));
json_spirit::Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
out.push_back(json_spirit::Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
entry.push_back(json_spirit::Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
entry.push_back(json_spirit::Pair("blockhash", hashBlock.GetHex()));
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
entry.push_back(json_spirit::Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(json_spirit::Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(json_spirit::Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
entry.push_back(json_spirit::Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
throw std::runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
@ -129,21 +133,21 @@ Value getrawtransaction(const Array& params, bool fHelp)
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
std::string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
json_spirit::Object result;
result.push_back(json_spirit::Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
throw std::runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
@ -151,7 +155,7 @@ Value listunspent(const Array& params, bool fHelp)
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
RPCTypeCheck(params, list_of(json_spirit::int_type)(json_spirit::int_type)(json_spirit::array_type));
int nMinDepth = 1;
if (params.size() > 0)
@ -161,23 +165,23 @@ Value listunspent(const Array& params, bool fHelp)
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CcurecoinAddress> setAddress;
std::set<CcurecoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
json_spirit::Array inputs = params[2].get_array();
BOOST_FOREACH(json_spirit::Value& input, inputs)
{
CcurecoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid curecoin address: ")+input.get_str());
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid curecoin 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);
}
}
Array results;
vector<COutput> vecOutputs;
json_spirit::Array results;
std::vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
@ -196,22 +200,22 @@ Value listunspent(const Array& params, bool fHelp)
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
json_spirit::Object entry;
entry.push_back(json_spirit::Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(json_spirit::Pair("vout", out.i));
entry.push_back(json_spirit::Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(json_spirit::Pair("amount",ValueFromAmount(nValue)));
entry.push_back(json_spirit::Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
throw std::runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
@ -220,26 +224,26 @@ Value createrawtransaction(const Array& params, bool fHelp)
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
RPCTypeCheck(params, list_of(json_spirit::array_type)(json_spirit::obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
json_spirit::Array inputs = params[0].get_array();
json_spirit::Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(Value& input, inputs)
BOOST_FOREACH(json_spirit::Value& input, inputs)
{
const Object& o = input.get_obj();
const json_spirit::Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
const json_spirit::Value& txid_v = find_value(o, "txid");
if (txid_v.type() != json_spirit::str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
std::string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
const json_spirit::Value& vout_v = find_value(o, "vout");
if (vout_v.type() != json_spirit::int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
@ -249,15 +253,15 @@ Value createrawtransaction(const Array& params, bool fHelp)
rawTx.vin.push_back(in);
}
set<CcurecoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
std::set<CcurecoinAddress> setAddress;
BOOST_FOREACH(const json_spirit::Pair& s, sendTo)
{
CcurecoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid curecoin address: ")+s.name_);
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid curecoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
@ -273,16 +277,16 @@ Value createrawtransaction(const Array& params, bool fHelp)
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
throw std::runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
RPCTypeCheck(params, list_of(str_type));
RPCTypeCheck(params, list_of(json_spirit::str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
@ -292,16 +296,16 @@ Value decoderawtransaction(const Array& params, bool fHelp)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
json_spirit::Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
throw std::runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
@ -315,11 +319,11 @@ Value signrawtransaction(const Array& params, bool fHelp)
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
RPCTypeCheck(params, list_of(json_spirit::str_type)(json_spirit::array_type)(json_spirit::array_type)(json_spirit::str_type), true);
vector<unsigned char> txData(ParseHex(params[0].get_str()));
std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
std::vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
@ -341,13 +345,13 @@ Value signrawtransaction(const Array& params, bool fHelp)
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
std::map<COutPoint, CScript> mapPrevOut;
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTransaction tempTx;
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
std::map<uint256, CTxIndex> unused;
bool fInvalid;
// FetchInputs aborts on failure, so we go one at a time.
@ -364,19 +368,19 @@ Value signrawtransaction(const Array& params, bool fHelp)
}
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
if (params.size() > 1 && params[1].type() != json_spirit::null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
json_spirit::Array prevTxs = params[1].get_array();
BOOST_FOREACH(json_spirit::Value& p, prevTxs)
{
if (p.type() != obj_type)
if (p.type() != json_spirit::obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
json_spirit::Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
RPCTypeCheck(prevOut, map_list_of("txid", json_spirit::str_type)("vout", json_spirit::int_type)("scriptPubKey", json_spirit::str_type));
string txidHex = find_value(prevOut, "txid").get_str();
std::string txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
uint256 txid;
@ -386,10 +390,10 @@ Value signrawtransaction(const Array& params, bool fHelp)
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
std::string pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
vector<unsigned char> pkData(ParseHex(pkHex));
std::vector<unsigned char> pkData(ParseHex(pkHex));
CScript scriptPubKey(pkData.begin(), pkData.end());
COutPoint outpoint(txid, nOut);
@ -398,7 +402,7 @@ Value signrawtransaction(const Array& params, bool fHelp)
// Complain if scriptPubKey doesn't match
if (mapPrevOut[outpoint] != scriptPubKey)
{
string err("Previous output scriptPubKey mismatch:\n");
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
@ -411,11 +415,11 @@ Value signrawtransaction(const Array& params, bool fHelp)
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
if (params.size() > 2 && params[2].type() != json_spirit::null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
json_spirit::Array keys = params[2].get_array();
BOOST_FOREACH(json_spirit::Value k, keys)
{
CcurecoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
@ -434,18 +438,18 @@ Value signrawtransaction(const Array& params, bool fHelp)
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
if (params.size() > 3 && params[3].type() != json_spirit::null_type)
{
static map<string, int> mapSigHashValues =
static std::map<std::string, int> 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))
(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))
;
string strHashType = params[3].get_str();
std::string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
@ -479,26 +483,26 @@ Value signrawtransaction(const Array& params, bool fHelp)
fComplete = false;
}
Object result;
json_spirit::Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
result.push_back(json_spirit::Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(json_spirit::Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
throw std::runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
RPCTypeCheck(params, list_of(str_type));
RPCTypeCheck(params, list_of(json_spirit::str_type));
// parse hex string from parameter
vector<unsigned char> txData(ParseHex(params[0].get_str()));
std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
@ -518,7 +522,7 @@ Value sendrawtransaction(const Array& params, bool fHelp)
if (GetTransaction(hashTx, existingTx, hashBlock))
{
if (hashBlock != 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex());
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("transaction already in block ")+hashBlock.GetHex());
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
using namespace std;
using namespace boost;
#include "script.h"
@ -16,7 +15,12 @@ using namespace boost;
#include "sync.h"
#include "util.h"
bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
#include <map>
#include <stdexcept>
#include <set>
#include <vector>
bool CheckSig(std::vector<unsigned char> vchSig, std::vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
static const valtype vchFalse(0);
static const valtype vchZero(0);
@ -31,7 +35,7 @@ static const size_t nMaxNumSize = 4;
CBigNum CastToBigNum(const valtype& vch)
{
if (vch.size() > nMaxNumSize)
throw runtime_error("CastToBigNum() : overflow");
throw std::runtime_error("CastToBigNum() : overflow");
// Get rid of extra leading zeros
return CBigNum(CBigNum(vch).getvch());
}
@ -85,10 +89,10 @@ void MakeSameSize(valtype& vch1, valtype& vch2)
//
#define stacktop(i) (stack.at(stack.size()+(i)))
#define altstacktop(i) (altstack.at(altstack.size()+(i)))
static inline void popstack(vector<valtype>& stack)
static inline void popstack(std::vector<valtype>& stack)
{
if (stack.empty())
throw runtime_error("popstack() : stack empty");
throw std::runtime_error("popstack() : stack empty");
stack.pop_back();
}
@ -250,7 +254,7 @@ const char* GetOpName(opcodetype opcode)
}
}
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
CAutoBN_CTX pctx;
CScript::const_iterator pc = script.begin();
@ -258,8 +262,8 @@ bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, co
CScript::const_iterator pbegincodehash = script.begin();
opcodetype opcode;
valtype vchPushValue;
vector<bool> vfExec;
vector<valtype> altstack;
std::vector<bool> vfExec;
std::vector<valtype> altstack;
if (script.size() > 10000)
return false;
int nOpCount = 0;
@ -1177,7 +1181,7 @@ public:
}
};
bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
bool CheckSig(std::vector<unsigned char> vchSig, std::vector<unsigned char> vchPubKey, CScript scriptCode,
const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static CSignatureCache signatureCache;
@ -1218,10 +1222,10 @@ bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CSc
//
// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
//
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
{
// Templates
static map<txnouttype, CScript> mTemplates;
static std::map<txnouttype, CScript> mTemplates;
if (mTemplates.empty())
{
// Standard tx, sender provides pubkey, receiver adds signature
@ -1239,7 +1243,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
if (scriptPubKey.IsPayToScriptHash())
{
typeRet = TX_SCRIPTHASH;
vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
vSolutionsRet.push_back(hashBytes);
return true;
}
@ -1252,7 +1256,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
vSolutionsRet.clear();
opcodetype opcode1, opcode2;
vector<unsigned char> vch1, vch2;
std::vector<unsigned char> vch1, vch2;
// Compare
CScript::const_iterator pc1 = script1.begin();
@ -1336,7 +1340,7 @@ bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int n
if (!keystore.GetKey(address, key))
return false;
vector<unsigned char> vchSig;
std::vector<unsigned char> vchSig;
if (!key.Sign(hash, vchSig))
return false;
vchSig.push_back((unsigned char)nHashType);
@ -1345,7 +1349,7 @@ bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int n
return true;
}
bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
bool SignN(const std::vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
{
int nSigned = 0;
int nRequired = multisigdata.front()[0];
@ -1370,7 +1374,7 @@ bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash
{
scriptSigRet.clear();
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
return false;
@ -1425,7 +1429,7 @@ int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned c
bool IsStandard(const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
@ -1445,7 +1449,7 @@ bool IsStandard(const CScript& scriptPubKey)
}
unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
{
unsigned int nResult = 0;
BOOST_FOREACH(const valtype& pubkey, pubkeys)
@ -1476,7 +1480,7 @@ bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
@ -1506,7 +1510,7 @@ bool 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<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
return HaveKeys(keys, keystore) == keys.size();
}
}
@ -1515,7 +1519,7 @@ bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
{
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
@ -1539,11 +1543,11 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
return false;
}
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
{
addressRet.clear();
typeRet = TX_NONSTANDARD;
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
if (!Solver(scriptPubKey, typeRet, vSolutions))
return false;
@ -1571,7 +1575,7 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vecto
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
bool fValidatePayToScriptHash, int nHashType)
{
vector<vector<unsigned char> > stack, stackCopy;
std::vector<std::vector<unsigned char> > stack, stackCopy;
if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
return false;
if (fValidatePayToScriptHash)
@ -1665,7 +1669,7 @@ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsig
return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
}
static CScript PushAll(const vector<valtype>& values)
static CScript PushAll(const std::vector<valtype>& values)
{
CScript result;
BOOST_FOREACH(const valtype& v, values)
@ -1674,11 +1678,11 @@ static CScript PushAll(const vector<valtype>& values)
}
static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
const vector<valtype>& vSolutions,
vector<valtype>& sigs1, vector<valtype>& sigs2)
const std::vector<valtype>& vSolutions,
std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
{
// Combine all the signatures we've got:
set<valtype> allsigs;
std::set<valtype> allsigs;
BOOST_FOREACH(const valtype& v, sigs1)
{
if (!v.empty())
@ -1694,7 +1698,7 @@ static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, u
assert(vSolutions.size() > 1);
unsigned int nSigsRequired = vSolutions.front()[0];
unsigned int nPubKeys = vSolutions.size()-2;
map<valtype, valtype> sigs;
std::map<valtype, valtype> sigs;
BOOST_FOREACH(const valtype& sig, allsigs)
{
for (unsigned int i = 0; i < nPubKeys; i++)
@ -1729,8 +1733,8 @@ static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, u
}
static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
const txnouttype txType, const vector<valtype>& vSolutions,
vector<valtype>& sigs1, vector<valtype>& sigs2)
const txnouttype txType, const std::vector<valtype>& vSolutions,
std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
{
switch (txType)
{
@ -1757,7 +1761,7 @@ static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo,
CScript pubKey2(spk.begin(), spk.end());
txnouttype txType2;
vector<vector<unsigned char> > vSolutions2;
std::vector<std::vector<unsigned char> > vSolutions2;
Solver(pubKey2, txType2, vSolutions2);
sigs1.pop_back();
sigs2.pop_back();
@ -1776,12 +1780,12 @@ CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsign
const CScript& scriptSig1, const CScript& scriptSig2)
{
txnouttype txType;
vector<vector<unsigned char> > vSolutions;
std::vector<std::vector<unsigned char> > vSolutions;
Solver(scriptPubKey, txType, vSolutions);
vector<valtype> stack1;
std::vector<valtype> stack1;
EvalScript(stack1, scriptSig1, CTransaction(), 0, 0);
vector<valtype> stack2;
std::vector<valtype> stack2;
EvalScript(stack2, scriptSig2, CTransaction(), 0, 0);
return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
@ -1820,7 +1824,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<unsigned char> data;
std::vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;

View File

@ -449,6 +449,12 @@ public:
CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
#endif
CScript& operator=(const CScript& b)
{
assign(b.begin(), b.end());
return *this;
}
CScript& operator+=(const CScript& b)
{
insert(end(), b.begin(), b.end());

View File

@ -818,7 +818,7 @@ public:
{
// special case for inserting at the front when there's room
nReadPos -= (last - first);
memcpy(&vch[nReadPos], &first[0], last - first);
std::memcpy(&vch[nReadPos], &first[0], last - first);
}
else
vch.insert(it, first, last);
@ -831,7 +831,7 @@ public:
{
// special case for inserting at the front when there's room
nReadPos -= (last - first);
memcpy(&vch[nReadPos], &first[0], last - first);
std::memcpy(&vch[nReadPos], &first[0], last - first);
}
else
vch.insert(it, first, last);
@ -845,7 +845,7 @@ public:
{
// special case for inserting at the front when there's room
nReadPos -= (last - first);
memcpy(&vch[nReadPos], &first[0], last - first);
std::memcpy(&vch[nReadPos], &first[0], last - first);
}
else
vch.insert(it, first, last);
@ -941,15 +941,15 @@ public:
if (nReadPosNext > vch.size())
{
setstate(std::ios::failbit, "CDataStream::read() : end of data");
memset(pch, 0, nSize);
std::memset(pch, 0, nSize);
nSize = vch.size() - nReadPos;
}
memcpy(pch, &vch[nReadPos], nSize);
std::memcpy(pch, &vch[nReadPos], nSize);
nReadPos = 0;
vch.clear();
return (*this);
}
memcpy(pch, &vch[nReadPos], nSize);
std::memcpy(pch, &vch[nReadPos], nSize);
nReadPos = nReadPosNext;
return (*this);
}

View File

@ -10,6 +10,13 @@
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
#include <cstring>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
@ -60,10 +67,9 @@ namespace boost {
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
std::map<std::string, std::string> mapArgs;
std::map<std::string, std::vector<std::string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
@ -73,7 +79,7 @@ bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
std::string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
@ -136,7 +142,7 @@ void RandAddSeed()
// Seed with CPU performance counter
int64 nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
std::memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
@ -153,14 +159,14 @@ void RandAddSeedPerfmon()
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
std::memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
std::memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
@ -284,7 +290,7 @@ inline int OutputDebugStringF(const char* pszFormat, ...)
return ret;
}
string vstrprintf(const char *format, va_list ap)
std::string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
@ -309,26 +315,26 @@ string vstrprintf(const char *format, va_list ap)
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
std::string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
std::string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
std::string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
std::string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
@ -344,12 +350,12 @@ bool error(const char *format, ...)
}
void ParseString(const string& str, char c, vector<string>& v)
void ParseString(const std::string& str, char c, std::vector<std::string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
std::string::size_type i1 = 0;
std::string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
@ -364,14 +370,14 @@ void ParseString(const string& str, char c, vector<string>& v)
}
string FormatMoney(int64 n, bool fPlus)
std::string FormatMoney(int64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
std::string str = strprintf("%" PRI64d ".%06" PRI64d, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
@ -388,14 +394,14 @@ string FormatMoney(int64 n, bool fPlus)
}
bool ParseMoney(const string& str, int64& nRet)
bool ParseMoney(const std::string& str, int64& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64& nRet)
{
string strWhole;
std::string strWhole;
int64 nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
@ -452,7 +458,7 @@ static const signed char phexdigit[256] =
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
bool IsHex(const std::string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
@ -462,10 +468,10 @@ bool IsHex(const string& str)
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
std::vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
std::vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
@ -483,12 +489,12 @@ vector<unsigned char> ParseHex(const char* psz)
return vch;
}
vector<unsigned char> ParseHex(const string& str)
std::vector<unsigned char> ParseHex(const std::string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
static void InterpretNegativeSetting(std::string name, std::map<std::string, std::string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
@ -530,9 +536,9 @@ void ParseParameters(int argc, const char* const argv[])
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
BOOST_FOREACH(const PAIRTYPE(std::string,std::string)& entry, mapArgs)
{
string name = entry.first;
std::string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
@ -590,11 +596,11 @@ bool SoftSetBoolArg(const std::string& strArg, bool fValue)
}
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;
@ -636,12 +642,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<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
@ -663,7 +669,7 @@ vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
std::vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
@ -724,17 +730,17 @@ vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
return vchRet;
}
string DecodeBase64(const string& str)
std::string DecodeBase64(const std::string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
std::vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return std::string((const char*)&vchRet[0], vchRet.size());
}
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;
@ -789,12 +795,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<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
@ -816,7 +822,7 @@ vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
std::vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
@ -911,10 +917,10 @@ vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
return vchRet;
}
string DecodeBase32(const string& str)
std::string DecodeBase32(const std::string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
std::vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return std::string((const char*)&vchRet[0], vchRet.size());
}
@ -942,7 +948,7 @@ bool WildcardMatch(const char* psz, const char* mask)
}
}
bool WildcardMatch(const string& str, const string& mask)
bool WildcardMatch(const std::string& str, const std::string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
@ -1077,20 +1083,20 @@ boost::filesystem::path GetConfigFile()
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet,
std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No curecoin.conf file is OK
set<string> setOptions;
std::set<std::string> 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 curecoin.conf
string strKey = string("-") + it->string_key;
std::string strKey = std::string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
@ -1211,13 +1217,13 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
int64 nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
static std::set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
printf("Added time data, samples %d, offset %+" PRI64d " (%+" PRI64d " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
@ -1243,19 +1249,19 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong curecoin will not work properly.");
std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong curecoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
uiInterface.ThreadSafeMessageBox(strMessage+" ", std::string("curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+"PRI64d" ", n);
printf("%+" PRI64d " ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
printf("nTimeOffset = %+" PRI64d " (%+" PRI64d " minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
@ -1266,7 +1272,7 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
string FormatVersion(int nVersion)
std::string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
@ -1274,7 +1280,7 @@ string FormatVersion(int nVersion)
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}

View File

@ -242,7 +242,7 @@ void runCommand(std::string strCommand);
inline std::string i64tostr(int64 n)
{
return strprintf("%"PRI64d, n);
return strprintf("%" PRI64d, n);
}
inline std::string itostr(int n)

View File

@ -10,7 +10,16 @@
#include "base58.h"
#include "kernel.h"
using namespace std;
#include <algorithm>
#include <list>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
extern int nStakeMaxAge;
@ -21,8 +30,8 @@ extern int nStakeMaxAge;
struct CompareValueOnly
{
bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
bool operator()(const std::pair<int64, std::pair<const CWalletTx*, unsigned int> >& t1,
const std::pair<int64, std::pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
@ -56,7 +65,7 @@ bool CWallet::AddKey(const CKey& key)
return true;
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
@ -317,16 +326,16 @@ CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries,
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
// would make this much faster for applications that do this a lot.
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
txOrdered.insert(std::make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
}
acentries.clear();
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
txOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
}
return txOrdered;
@ -341,7 +350,7 @@ void CWallet::WalletUpdateSpent(const CTransaction &tx)
LOCK(cs_wallet);
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& wtx = (*mi).second;
@ -374,7 +383,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn)
{
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
@ -527,7 +536,7 @@ bool CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
@ -543,7 +552,7 @@ int64 CWallet::GetDebit(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
@ -592,7 +601,7 @@ int CWalletTx::GetRequestCount() const
// Generated block
if (hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
@ -600,7 +609,7 @@ int CWalletTx::GetRequestCount() const
else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
@ -608,7 +617,7 @@ int CWalletTx::GetRequestCount() const
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
@ -620,8 +629,8 @@ int CWalletTx::GetRequestCount() const
return nRequests;
}
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const
{
nGeneratedImmature = nGeneratedMature = nFee = 0;
listReceived.clear();
@ -649,7 +658,7 @@ void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, l
BOOST_FOREACH(const CTxOut& txout, vout)
{
CTxDestination address;
vector<unsigned char> vchPubKey;
std::vector<unsigned char> vchPubKey;
if (!ExtractDestination(txout.scriptPubKey, address))
{
printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
@ -661,23 +670,23 @@ void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, l
continue;
if (nDebit > 0)
listSent.push_back(make_pair(address, txout.nValue));
listSent.push_back(std::make_pair(address, txout.nValue));
if (pwallet->IsMine(txout))
listReceived.push_back(make_pair(address, txout.nValue));
listReceived.push_back(std::make_pair(address, txout.nValue));
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
void CWalletTx::GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const
{
nGenerated = nReceived = nSent = nFee = 0;
int64 allGeneratedImmature, allGeneratedMature, allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
std::string strSentAccount;
std::list<std::pair<CTxDestination, int64> > listReceived;
std::list<std::pair<CTxDestination, int64> > listSent;
GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (strAccount == "")
@ -694,7 +703,7 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, i
{
if (pwallet->mapAddressBook.count(r.first))
{
map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
std::map<CTxDestination, std::string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
nReceived += r.second;
}
@ -713,15 +722,15 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
const int COPY_DEPTH = 3;
if (SetMerkleBranch() < COPY_DEPTH)
{
vector<uint256> vWorkQueue;
std::vector<uint256> vWorkQueue;
BOOST_FOREACH(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash);
// This critsect is OK because txdb is already open
{
LOCK(pwallet->cs_wallet);
map<uint256, const CMerkleTx*> mapWalletPrev;
set<uint256> setAlreadyDone;
std::map<uint256, const CMerkleTx*> mapWalletPrev;
std::set<uint256> setAlreadyDone;
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hash = vWorkQueue[i];
@ -730,7 +739,7 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
setAlreadyDone.insert(hash);
CMerkleTx tx;
map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
std::map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
if (mi != pwallet->mapWallet.end())
{
tx = (*mi).second;
@ -813,7 +822,7 @@ void CWallet::ReacceptWalletTransactions()
{
LOCK(cs_wallet);
fRepeat = false;
vector<CDiskTxPos> vMissingTx;
std::vector<CDiskTxPos> vMissingTx;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
@ -827,7 +836,7 @@ void CWallet::ReacceptWalletTransactions()
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
if (txindex.vSpent.size() != wtx.vout.size())
{
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
continue;
}
for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
@ -916,14 +925,14 @@ void CWallet::ResendWalletTransactions()
{
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
std::multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(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)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
@ -952,7 +961,7 @@ int64 CWallet::GetBalance() const
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsFinal() && pcoin->IsConfirmed())
@ -968,7 +977,7 @@ int64 CWallet::GetUnconfirmedBalance() const
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
@ -983,7 +992,7 @@ int64 CWallet::GetImmatureBalance() const
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx& pcoin = (*it).second;
if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
@ -994,13 +1003,13 @@ int64 CWallet::GetImmatureBalance() const
}
// populate vCoins with vector of spendable COutputs
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
void CWallet::AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed) const
{
vCoins.clear();
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
@ -1023,13 +1032,13 @@ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
}
}
void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
void CWallet::AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const
{
vCoins.clear();
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
@ -1046,10 +1055,10 @@ void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
}
}
static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
vector<char>& vfBest, int64& nBest, int iterations = 1000)
static void ApproximateBestSubset(std::vector<std::pair<int64, std::pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
std::vector<char>& vfBest, int64& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
@ -1089,7 +1098,7 @@ int64 CWallet::GetStake() const
{
int64 nTotal = 0;
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
@ -1102,7 +1111,7 @@ int64 CWallet::GetNewMint() const
{
int64 nTotal = 0;
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
@ -1111,16 +1120,16 @@ int64 CWallet::GetNewMint() const
return nTotal;
}
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
std::pair<int64, std::pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<int64>::max();
coinLowestLarger.second.first = NULL;
vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
std::vector<std::pair<int64, std::pair<const CWalletTx*,unsigned int> > > vValue;
int64 nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
@ -1139,7 +1148,7 @@ bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, in
int64 n = pcoin->vout[i].nValue;
pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
std::pair<int64,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
if (n == nTargetValue)
{
@ -1179,7 +1188,7 @@ bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, in
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
std::vector<char> vfBest;
int64 nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
@ -1216,9 +1225,9 @@ bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, in
return true;
}
bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
vector<COutput> vCoins;
std::vector<COutput> vCoins;
AvailableCoins(vCoins);
return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
@ -1227,9 +1236,9 @@ bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<
}
// Select some coins without random shuffle or best subset approximation
bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
vector<COutput> vCoins;
std::vector<COutput> vCoins;
AvailableCoinsMinConf(vCoins, nMinConf);
setCoinsRet.clear();
@ -1250,7 +1259,7 @@ bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int
int64_t n = pcoin->vout[i].nValue;
pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
std::pair<int64_t,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
if (n >= nTargetValue)
{
@ -1271,7 +1280,7 @@ bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int
}
bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
bool CWallet::CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
{
int64 nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
@ -1310,7 +1319,7 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
wtxNew.vout.push_back(CTxOut(s.second, s.first));
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
int64 nValueIn = 0;
if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
return false;
@ -1326,7 +1335,7 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
// NOTE: this depends on the exact behaviour of GetMinFee
if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
{
int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
int64 nMoveToFee = std::min(nChange, MIN_TX_FEE - nFeeRet);
nChange -= nMoveToFee;
nFeeRet += nMoveToFee;
}
@ -1358,7 +1367,7 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
scriptChange.SetDestination(vchPubKey.GetID());
// Insert change txn at random position:
vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
std::vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
}
else
@ -1384,9 +1393,9 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
if (nFeeRet < max(nPayFee, nMinFee))
if (nFeeRet < std::max(nPayFee, nMinFee))
{
nFeeRet = max(nPayFee, nMinFee);
nFeeRet = std::max(nPayFee, nMinFee);
continue;
}
@ -1403,8 +1412,8 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
{
vector< pair<CScript, int64> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
std::vector< std::pair<CScript, int64> > vecSend;
vecSend.push_back(std::make_pair(scriptPubKey, nValue));
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strTxComment);
}
@ -1419,9 +1428,9 @@ bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint
if (nBalance <= nReserveBalance)
return false;
vector<const CWalletTx*> vwtxPrev;
std::vector<const CWalletTx*> vwtxPrev;
set<pair<const CWalletTx*,unsigned int> > setCoins;
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
int64 nValueIn = 0;
if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity + 10, setCoins, nValueIn))
@ -1495,8 +1504,8 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int
return error("CreateCoinStake : invalid reserve balance amount");
if (nBalance <= nReserveBalance)
return false;
set<pair<const CWalletTx*,unsigned int> > setCoins;
vector<const CWalletTx*> vwtxPrev;
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
std::vector<const CWalletTx*> vwtxPrev;
int64 nValueIn = 0;
if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
return false;
@ -1520,7 +1529,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int
continue; // only count coins meeting min age requirement
bool fKernelFound = false;
for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
for (unsigned int n=0; n<std::min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
{
// Search backward in time from the given txNew timestamp
// Search nSearchInterval seconds back up to nMaxStakeSearchInterval
@ -1531,7 +1540,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int
// Found a kernel
if (fDebug && GetBoolArg("-printcoinstake"))
printf("CreateCoinStake : kernel found\n");
vector<valtype> vSolutions;
std::vector<valtype> vSolutions;
txnouttype whichType;
CScript scriptPubKeyOut;
scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
@ -1685,7 +1694,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
AddToWallet(wtxNew);
// Mark old coins as spent
set<CWalletTx*> setCoins;
std::set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
@ -1717,26 +1726,26 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
std::string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
{
CReserveKey reservekey(this);
int64 nFeeRequired;
if (IsLocked())
{
string strError = _("Error: Wallet locked, unable to create transaction ");
std::string strError = _("Error: Wallet locked, unable to create transaction ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (fWalletUnlockMintOnly)
{
string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
std::string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strTxComment))
{
string strError;
std::string strError;
if (nValue + nFeeRequired > GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
else
@ -1756,7 +1765,7 @@ string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew,
string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
std::string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
{
// Check amount
if (nValue <= 0)
@ -1822,7 +1831,7 @@ DBErrors CWallet::ZapWalletTx()
return DB_LOAD_OK;
}
bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
bool CWallet::SetAddressBookName(const CTxDestination& address, const std::string& strName)
{
std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
mapAddressBook[address] = strName;
@ -1849,12 +1858,12 @@ void CWallet::PrintWallet(const CBlock& block)
if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
printf(" mine: %d %d %" PRI64d "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
}
if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
printf(" stake: %d %d %" PRI64d "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
}
}
@ -1865,7 +1874,7 @@ bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
{
wtx = (*mi).second;
@ -1886,7 +1895,7 @@ bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
return true;
}
bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut)
{
if (!pwallet->fFileBacked)
return false;
@ -1910,14 +1919,14 @@ bool CWallet::NewKeyPool()
if (IsLocked())
return false;
int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
int64 nKeys = std::max(GetArg("-keypool", 100), (int64)0);
for (int i = 0; i < nKeys; i++)
{
int64 nIndex = i+1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
printf("CWallet::NewKeyPool wrote %" PRI64d " new keys\n", nKeys);
}
return true;
}
@ -1933,16 +1942,16 @@ bool CWallet::TopUpKeyPool()
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
unsigned int nTargetSize = std::max(GetArg("-keypool", 100), 0LL);
while (setKeyPool.size() < (nTargetSize + 1))
{
int64 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);
printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
printf("keypool added key %" PRI64d ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
}
}
return true;
@ -1967,12 +1976,12 @@ void CWallet::ReserveKeyFromKeyPool(int64& 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());
if (fDebug && GetBoolArg("-printkeypool"))
printf("keypool reserve %"PRI64d"\n", nIndex);
printf("keypool reserve %" PRI64d "\n", nIndex);
}
}
@ -1984,7 +1993,7 @@ int64 CWallet::AddReserveKey(const CKeyPool& keypool)
int64 nIndex = 1 + *(--setKeyPool.end());
if (!walletdb.WritePool(nIndex, keypool))
throw runtime_error("AddReserveKey() : writing added key failed");
throw std::runtime_error("AddReserveKey() : writing added key failed");
setKeyPool.insert(nIndex);
return nIndex;
}
@ -2000,7 +2009,7 @@ void CWallet::KeepKey(int64 nIndex)
walletdb.ErasePool(nIndex);
}
if(fDebug)
printf("keypool keep %"PRI64d"\n", nIndex);
printf("keypool keep %" PRI64d "\n", nIndex);
}
void CWallet::ReturnKey(int64 nIndex)
@ -2011,7 +2020,7 @@ void CWallet::ReturnKey(int64 nIndex)
setKeyPool.insert(nIndex);
}
if(fDebug)
printf("keypool return %"PRI64d"\n", nIndex);
printf("keypool return %" PRI64d "\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
@ -2051,7 +2060,7 @@ int64 CWallet::GetOldestKeyPoolTime()
std::map<CTxDestination, int64> CWallet::GetAddressBalances()
{
map<CTxDestination, int64> balances;
std::map<CTxDestination, int64> balances;
{
LOCK(cs_wallet);
@ -2089,10 +2098,10 @@ std::map<CTxDestination, int64> CWallet::GetAddressBalances()
return balances;
}
set< set<CTxDestination> > CWallet::GetAddressGroupings()
std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
{
set< set<CTxDestination> > groupings;
set<CTxDestination> grouping;
std::set< std::set<CTxDestination> > groupings;
std::set<CTxDestination> grouping;
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
@ -2136,20 +2145,20 @@ set< set<CTxDestination> > CWallet::GetAddressGroupings()
}
}
set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
BOOST_FOREACH(set<CTxDestination> grouping, groupings)
std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
BOOST_FOREACH(std::set<CTxDestination> grouping, groupings)
{
// make a set of all the groups hit by this new group
set< set<CTxDestination>* > hits;
map< CTxDestination, set<CTxDestination>* >::iterator it;
std::set< std::set<CTxDestination>* > hits;
std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
BOOST_FOREACH(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<CTxDestination>* merged = new set<CTxDestination>(grouping);
BOOST_FOREACH(set<CTxDestination>* hit, hits)
std::set<CTxDestination>* merged = new std::set<CTxDestination>(grouping);
BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
@ -2162,8 +2171,8 @@ set< set<CTxDestination> > CWallet::GetAddressGroupings()
setmap[element] = merged;
}
set< set<CTxDestination> > ret;
BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
std::set< std::set<CTxDestination> > ret;
BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
@ -2180,9 +2189,9 @@ void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool
nBalanceInQuestion = 0;
LOCK(cs_wallet);
vector<CWalletTx*> vCoins;
std::vector<CWalletTx*> vCoins;
vCoins.reserve(mapWallet.size());
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
vCoins.push_back(&(*it).second);
CTxDB txdb("r");
@ -2231,7 +2240,7 @@ void CWallet::DisableTransaction(const CTransaction &tx)
LOCK(cs_wallet);
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& prev = (*mi).second;
@ -2278,7 +2287,7 @@ void CReserveKey::ReturnKey()
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress)
{
setAddress.clear();
@ -2289,11 +2298,11 @@ void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
{
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);
}
}
@ -2303,7 +2312,7 @@ void CWallet::UpdatedTransaction(const uint256 &hashTx)
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
}

View File

@ -7,9 +7,12 @@
#include "wallet.h"
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost;
#include <list>
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
static uint64 nAccountingEntryNumber = 0;
extern bool fWalletUnlockMintOnly;
@ -18,34 +21,34 @@ extern bool fWalletUnlockMintOnly;
// 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::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 nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
return Write(boost::make_tuple(std::string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
}
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
@ -53,9 +56,9 @@ bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
int64 CWalletDB::GetAccountCreditDebit(const std::string& strAccount)
{
list<CAccountingEntry> entries;
std::list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
int64 nCreditDebit = 0;
@ -65,20 +68,20 @@ int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
void CWalletDB::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& 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 << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
ssKey << boost::make_tuple(std::string("acentry"), (fAllAccounts? std::string("") : strAccount), uint64(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
@ -87,11 +90,11 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin
else if (ret != 0)
{
pcursor->close();
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;
@ -117,20 +120,20 @@ 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<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64, TxPair > TxItems;
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
for (std::map<uint256, CWalletTx>::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<CAccountingEntry> acentries;
std::list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH(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& nOrderPosNext = pwallet->nOrderPosNext;
@ -184,8 +187,8 @@ CWalletDB::ReorderTransactions(CWallet* pwallet)
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
int& nFileVersion, vector<uint256>& vWalletUpgrade,
bool& fIsEncrypted, bool& fAnyUnordered, string& strType, string& strErr)
int& nFileVersion, std::vector<uint256>& vWalletUpgrade,
bool& fIsEncrypted, bool& fAnyUnordered, std::string& strType, std::string& strErr)
{
try {
// Unserialize
@ -194,7 +197,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
ssKey >> strType;
if (strType == "name")
{
string strAddress;
std::string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CcurecoinAddress(strAddress).Get()];
}
@ -245,7 +248,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
}
else if (strType == "acentry")
{
string strAccount;
std::string strAccount;
ssKey >> strAccount;
uint64 nNumber;
ssKey >> nNumber;
@ -262,7 +265,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
}
else if (strType == "key" || strType == "wkey")
{
vector<unsigned char> vchPubKey;
std::vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
CKey key;
if (strType == "key")
@ -330,9 +333,9 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
}
else if (strType == "ckey")
{
vector<unsigned char> vchPubKey;
std::vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
std::vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
@ -380,7 +383,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
return true;
}
static bool IsKeyType(string strType)
static bool IsKeyType(std::string strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
@ -390,7 +393,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
int nFileVersion = 0;
vector<uint256> vWalletUpgrade;
std::vector<uint256> vWalletUpgrade;
bool fIsEncrypted = false;
bool fAnyUnordered = false;
bool fNoncriticalErrors = false;
@ -399,7 +402,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;
@ -429,7 +432,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, nFileVersion,
vWalletUpgrade, fIsEncrypted, fAnyUnordered, strType, strErr))
{
@ -482,17 +485,16 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
return result;
}
DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, std::vector<uint256>& vTxHash)
{
pwallet->vchDefaultKey = CPubKey();
// CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
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;
@ -521,7 +523,7 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
return DB_CORRUPT;
}
string strType;
std::string strType;
ssKey >> strType;
if (strType == "tx") {
uint256 hash;
@ -545,7 +547,7 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet)
{
// build list of wallet TXs
vector<uint256> vTxHash;
std::vector<uint256> vTxHash;
DBErrors err = FindWalletTx(pwallet, vTxHash);
if (err != DB_LOAD_OK)
return err;
@ -564,7 +566,7 @@ void ThreadFlushWalletDB(void* parg)
// Make this thread recognisable as the wallet flushing thread
RenameThread("curecoin-wallet");
const string& strFile = ((const string*)parg)[0];
const std::string& strFile = ((const std::string*)parg)[0];
static bool fOneThread;
if (fOneThread)
return;
@ -592,7 +594,7 @@ void ThreadFlushWalletDB(void* parg)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
std::map<std::string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end())
{
nRefCount += (*mi).second;
@ -601,7 +603,7 @@ void ThreadFlushWalletDB(void* parg)
if (nRefCount == 0 && !fShutdown)
{
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
std::map<std::string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
printf("Flushing wallet.dat\n");
@ -613,7 +615,7 @@ void ThreadFlushWalletDB(void* parg)
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
printf("Flushed wallet.dat %" PRI64d "ms\n", GetTimeMillis() - nStart);
}
}
}
@ -621,7 +623,7 @@ void ThreadFlushWalletDB(void* parg)
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
bool BackupWallet(const CWallet& wallet, const std::string& strDest)
{
if (!wallet.fFileBacked)
return false;
@ -674,7 +676,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
// Set -rescan so any missing transactions will be
// found.
int64 now = GetTime();
std::string newFilename = strprintf("wallet.%"PRI64d".bak", now);
std::string newFilename = strprintf("wallet.%" PRI64d ".bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
@ -693,7 +695,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
return false;
}
printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
printf("Salvage(aggressive) found %" PRIszu " records\n", salvagedData.size());
bool fSuccess = allOK;
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
@ -710,7 +712,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
}
CWallet dummyWallet;
int nFileVersion = 0;
vector<uint256> vWalletUpgrade;
std::vector<uint256> vWalletUpgrade;
bool fIsEncrypted = false;
bool fAnyUnordered = false;
@ -721,7 +723,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool 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,
nFileVersion, vWalletUpgrade,
fIsEncrypted, fAnyUnordered,